Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add literal parser #546

Draft
wants to merge 3 commits into
base: postgresql-dialect
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@
import com.google.cloud.spanner.ResultSet;
import com.google.cloud.spanner.Statement;
import com.google.cloud.spanner.pgadapter.error.PGExceptionFactory;
import java.math.BigDecimal;
import java.math.RoundingMode;
import org.postgresql.util.ByteConverter;

/** Translate from wire protocol to int. */
Expand All @@ -36,7 +38,8 @@ class IntegerParser extends Parser<Integer> {
case TEXT:
String stringValue = new String(item);
try {
this.item = Integer.valueOf(stringValue);
this.item =
new BigDecimal(stringValue).setScale(0, RoundingMode.HALF_UP).intValueExact();
} catch (Exception exception) {
throw PGExceptionFactory.newPGException("Invalid int4 value: " + stringValue);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@
import com.google.cloud.spanner.Statement;
import com.google.cloud.spanner.pgadapter.ProxyServer.DataFormat;
import com.google.cloud.spanner.pgadapter.error.PGExceptionFactory;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.nio.charset.StandardCharsets;
import javax.annotation.Nonnull;
import org.postgresql.util.ByteConverter;
Expand All @@ -43,7 +45,8 @@ public class LongParser extends Parser<Long> {
case TEXT:
String stringValue = new String(item);
try {
this.item = Long.valueOf(stringValue);
this.item =
new BigDecimal(stringValue).setScale(0, RoundingMode.HALF_UP).longValueExact();
} catch (Exception exception) {
throw PGExceptionFactory.newPGException("Invalid int8 value: " + stringValue);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@

import com.google.cloud.spanner.Statement;
import com.google.cloud.spanner.pgadapter.error.PGExceptionFactory;
import java.math.BigDecimal;
import java.math.RoundingMode;
import org.postgresql.util.ByteConverter;

/** Translate from wire protocol to short. */
Expand All @@ -31,9 +33,10 @@ class ShortParser extends Parser<Short> {
case TEXT:
String stringValue = new String(item);
try {
this.item = Short.valueOf(stringValue);
this.item =
new BigDecimal(stringValue).setScale(0, RoundingMode.HALF_UP).shortValueExact();
} catch (Exception exception) {
throw PGExceptionFactory.newPGException("Invalid int4 value: " + stringValue);
throw PGExceptionFactory.newPGException("Invalid int2 value: " + stringValue);
}
break;
case BINARY:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,11 @@
import com.google.common.base.Preconditions;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.temporal.ChronoField;
Expand Down Expand Up @@ -71,7 +74,7 @@ public class TimestampParser extends Parser<Timestamp> {
.appendOffset(OptionsMetadata.isJava8() ? "+HH:mm" : "+HH:mm:ss", "+00")
.toFormatter();

private static final DateTimeFormatter TIMESTAMP_INPUT_FORMATTER =
private static final DateTimeFormatter TIMESTAMPTZ_INPUT_FORMATTER =
new DateTimeFormatterBuilder()
.parseLenient()
.parseCaseInsensitive()
Expand All @@ -80,6 +83,13 @@ public class TimestampParser extends Parser<Timestamp> {
// Java 8 does not support seconds in timezone offset.
.appendOffset(OptionsMetadata.isJava8() ? "+HH:mm" : "+HH:mm:ss", "+00:00:00")
.toFormatter();
private static final DateTimeFormatter TIMESTAMP_INPUT_FORMATTER =
new DateTimeFormatterBuilder()
.parseLenient()
.parseCaseInsensitive()
.appendPattern("yyyy-MM-dd[[ ]['T']HH:mm[:ss][XXX]]")
.appendFraction(ChronoField.NANO_OF_SECOND, 0, 9, true)
.toFormatter();

private final SessionState sessionState;

Expand All @@ -98,7 +108,7 @@ public class TimestampParser extends Parser<Timestamp> {
if (item != null) {
switch (formatCode) {
case TEXT:
this.item = toTimestamp(new String(item, StandardCharsets.UTF_8));
this.item = toTimestamp(new String(item, StandardCharsets.UTF_8), sessionState);
break;
case BINARY:
this.item = toTimestamp(item);
Expand All @@ -123,15 +133,37 @@ public static Timestamp toTimestamp(@Nonnull byte[] data) {
}

/** Converts the given string value to a {@link Timestamp}. */
public static Timestamp toTimestamp(String value) {
public static Timestamp toTimestamp(String value, SessionState sessionState) {
try {
String stringValue = toPGString(value);
TemporalAccessor temporalAccessor = TIMESTAMP_INPUT_FORMATTER.parse(stringValue);
TemporalAccessor temporalAccessor = TIMESTAMPTZ_INPUT_FORMATTER.parse(stringValue);
return Timestamp.ofTimeSecondsAndNanos(
temporalAccessor.getLong(ChronoField.INSTANT_SECONDS),
temporalAccessor.get(ChronoField.NANO_OF_SECOND));
} catch (Exception exception) {
throw PGExceptionFactory.newPGException("Invalid timestamp value: " + value);
} catch (Exception ignore) {
try {
TemporalAccessor temporalAccessor =
TIMESTAMP_INPUT_FORMATTER.parseBest(
value, ZonedDateTime::from, LocalDateTime::from, LocalDate::from);
ZonedDateTime zonedDateTime = null;
if (temporalAccessor instanceof ZonedDateTime) {
zonedDateTime = (ZonedDateTime) temporalAccessor;
} else if (temporalAccessor instanceof LocalDateTime) {
LocalDateTime localDateTime = (LocalDateTime) temporalAccessor;
zonedDateTime = localDateTime.atZone(sessionState.getTimezone());
} else if (temporalAccessor instanceof LocalDate) {
LocalDate localDate = (LocalDate) temporalAccessor;
zonedDateTime = localDate.atStartOfDay().atZone(sessionState.getTimezone());
}
if (zonedDateTime != null) {
return Timestamp.ofTimeSecondsAndNanos(
zonedDateTime.getLong(ChronoField.INSTANT_SECONDS),
zonedDateTime.get(ChronoField.NANO_OF_SECOND));
}
throw PGExceptionFactory.newPGException("Invalid timestamp value: " + value);
} catch (Exception exception) {
throw PGExceptionFactory.newPGException("Invalid timestamp value: " + value);
}
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,11 @@ public CopySettings(SessionState sessionState) {
this.sessionState = sessionState;
}

/** Returns the underlying session state for these copy settings. */
public SessionState getSessionState() {
return sessionState;
}

/** Returns the maximum number of parallel transactions for a single COPY operation. */
public int getMaxParallelism() {
return sessionState.getIntegerSetting("spanner", "copy_max_parallelism", 128);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@
import com.google.cloud.spanner.pgadapter.ConnectionHandler;
import com.google.cloud.spanner.pgadapter.error.PGExceptionFactory;
import com.google.cloud.spanner.pgadapter.metadata.OptionsMetadata;
import com.google.cloud.spanner.pgadapter.session.SessionState;
import com.google.cloud.spanner.pgadapter.statements.LiteralParser.Literal;
import com.google.cloud.spanner.pgadapter.statements.SimpleParser.TableOrIndexName;
import com.google.cloud.spanner.pgadapter.wireprotocol.BindMessage;
import com.google.cloud.spanner.pgadapter.wireprotocol.ControlMessage.ManuallyCreatedToken;
Expand Down Expand Up @@ -71,7 +73,13 @@ public ExecuteStatement(
NO_PARAMS,
ImmutableList.of(),
ImmutableList.of());
this.executeStatement = parse(originalStatement.getSql());
this.executeStatement =
parse(
originalStatement.getSql(),
connectionHandler
.getExtendedQueryProtocolHandler()
.getBackendConnection()
.getSessionState());
}

@Override
Expand Down Expand Up @@ -126,7 +134,7 @@ public IntermediatePortalStatement createPortal(
return this;
}

static ParsedExecuteStatement parse(String sql) {
static ParsedExecuteStatement parse(String sql, SessionState sessionState) {
Preconditions.checkNotNull(sql);

SimpleParser parser = new SimpleParser(sql);
Expand All @@ -139,7 +147,7 @@ static ParsedExecuteStatement parse(String sql) {
}
String statementName = unquoteOrFoldIdentifier(name.name);

List<String> parameters;
List<Literal> parameters;
if (parser.eatToken("(")) {
List<String> parametersList = parser.parseExpressionList();
if (parametersList == null || parametersList.isEmpty()) {
Expand All @@ -149,7 +157,9 @@ static ParsedExecuteStatement parse(String sql) {
throw PGExceptionFactory.newPGException("missing closing parentheses in parameters list");
}
parameters =
parametersList.stream().map(ExecuteStatement::unquoteString).collect(Collectors.toList());
parametersList.stream()
.map(LiteralParser::parseSingleConstantLiteralExpression)
.collect(Collectors.toList());
} else {
parameters = Collections.emptyList();
}
Expand All @@ -161,7 +171,11 @@ static ParsedExecuteStatement parse(String sql) {
return new ParsedExecuteStatement(
statementName,
parameters.stream()
.map(p -> p == null ? null : p.getBytes(StandardCharsets.UTF_8))
.map(
p ->
p == null
? null
: p.getConvertedValue(sessionState).getBytes(StandardCharsets.UTF_8))
.toArray(byte[][]::new));
}

Expand Down
Loading