params) {
+ DMLGeneratorResponse response = new DMLGeneratorResponse(sql);
+ response.setPreparedStatementParameters(params);
+ return response;
+ }
- deleteValues += " \"" + colName + "\" = " + colValue;
- if (index + 1 < pkcolumnNameValues.size()) {
- deleteValues += " AND ";
- }
- index++;
+ /**
+ * Quotes a PostgreSQL identifier with double quotes, escaping embedded double quotes by doubling
+ * them.
+ *
+ * @throws NullPointerException if {@code identifier} is null
+ */
+ @VisibleForTesting
+ static String quoteIdentifier(String identifier) {
+ Preconditions.checkNotNull(identifier, "Identifier must not be null");
+ return "\"" + StringUtils.replace(identifier, "\"", "\"\"") + "\"";
+ }
+
+ /**
+ * Binding category for a PostgreSQL column type.
+ *
+ * Recognizes both {@code information_schema.columns.data_type} names emitted by {@code
+ * PostgreSQLInformationSchemaScanner} and standard PostgreSQL aliases (such as {@code varchar},
+ * {@code int4}, {@code timestamptz}, {@code bool}) that may appear in tests.
+ */
+ @VisibleForTesting
+ enum PgColumnType {
+ CHARACTER,
+ TIMESTAMP,
+ BOOLEAN,
+ INTEGER,
+ FLOAT8,
+ DECIMAL,
+ OTHER;
+
+ private static final ImmutableMap TYPE_MAP =
+ ImmutableMap.builder()
+ .put("varchar", CHARACTER)
+ .put("character varying", CHARACTER)
+ .put("char", CHARACTER)
+ .put("character", CHARACTER)
+ .put("bpchar", CHARACTER)
+ .put("text", CHARACTER)
+ .put("name", CHARACTER)
+ .put("timestamp", TIMESTAMP)
+ .put("timestamp without time zone", TIMESTAMP)
+ .put("timestamp with time zone", TIMESTAMP)
+ .put("timestamptz", TIMESTAMP)
+ .put("boolean", BOOLEAN)
+ .put("bool", BOOLEAN)
+ .put("smallint", INTEGER)
+ .put("int2", INTEGER)
+ .put("integer", INTEGER)
+ .put("int", INTEGER)
+ .put("int4", INTEGER)
+ .put("bigint", INTEGER)
+ .put("int8", INTEGER)
+ .put("smallserial", INTEGER)
+ .put("serial", INTEGER)
+ .put("bigserial", INTEGER)
+ .put("double precision", FLOAT8)
+ .put("float8", FLOAT8)
+ .put("numeric", DECIMAL)
+ .put("decimal", DECIMAL)
+ .build();
+
+ static PgColumnType fromSourceType(@Nullable String rawPgType) {
+ // Unmapped types (real/float4, bytea, json/jsonb, uuid, date/time, arrays, USER-DEFINED,
+ // unknown) bind untyped via Types.OTHER so PostgreSQL resolves the column's exact type and
+ // operators. Keeping real/float4 in OTHER ensures float4in/float4eq even when pgjdbc
+ // binaryTransfer is disabled (where setFloat falls back to OID float8).
+ return TYPE_MAP.getOrDefault(DMLGeneratorUtils.normalizeSourceType(rawPgType), OTHER);
}
- String returnVal = "DELETE FROM \"" + tableName + "\" WHERE " + deleteValues;
+ }
- return new DMLGeneratorResponse(returnVal);
+ /**
+ * Returns the SQL {@code NULL} binding of a column, with the placeholder and parameter type of
+ * the column's non-null values. A {@code NULL} then changes neither the SQL text nor the
+ * parameter types of the statement, and {@code pgjdbc} reuses a server-prepared statement only
+ * while both stay the same.
+ */
+ @VisibleForTesting
+ static ColumnBinding getNullColumnBinding(Column spannerColDef, SourceColumn sourceColDef) {
+ PgColumnType pgType = PgColumnType.fromSourceType(sourceColDef.type());
+ Type.Code code = spannerColDef.type().getCode();
+ // Spanner BYTES bind as bytea, except into character columns (hex text bound as VARCHAR).
+ if ((code == Type.Code.BYTES || code == Type.Code.PG_BYTEA)
+ && pgType != PgColumnType.CHARACTER) {
+ return NULL_VARBINARY_BINDING;
+ }
+ return pgType == PgColumnType.TIMESTAMP ? NULL_TIMESTAMPTZ_BINDING : typedNullBinding(pgType);
}
- private static DMLGeneratorResponse generateUpsertStatement(
- Table spannerTable,
- SourceTable sourceTable,
- DMLGeneratorRequest dmlGeneratorRequest,
- Map pkcolumnNameValues) {
- Map columnNameValues =
- DMLGeneratorUtils.getColumnValues(
- dmlGeneratorRequest.getSchemaMapper(),
- spannerTable,
- sourceTable,
- dmlGeneratorRequest.getNewValuesJson(),
- dmlGeneratorRequest.getKeyValuesJson(),
- dmlGeneratorRequest.getSourceDbTimezoneOffset(),
- dmlGeneratorRequest.getCustomTransformationResponse(),
- PostgreSQLDMLGenerator::getMappedColumnValue,
- new ArrayList<>());
- columnNameValues.putAll(pkcolumnNameValues);
- return getUpsertStatement(
- sourceTable.name(), columnNameValues, sourceTable.primaryKeyColumns());
+ /** Returns a plain {@code ?} SQL {@code NULL} binding typed like the values of {@code pgType}. */
+ private static ColumnBinding typedNullBinding(PgColumnType pgType) {
+ return switch (pgType) {
+ case CHARACTER -> NULL_VARCHAR_BINDING;
+ case BOOLEAN -> NULL_BOOLEAN_BINDING;
+ case INTEGER -> NULL_BIGINT_BINDING;
+ case FLOAT8 -> NULL_DOUBLE_BINDING;
+ case DECIMAL -> NULL_DECIMAL_BINDING;
+ case TIMESTAMP, OTHER -> NULL_BINDING;
+ };
}
+ /**
+ * Maps a non-null Spanner column value to a {@link ColumnBinding} based on the Spanner column
+ * type and the PostgreSQL column type.
+ *
+ * @throws InvalidDMLGenerationException if the JSON value cannot be decoded or converted for the
+ * column (error message contains column name and types only, never the row value)
+ */
@VisibleForTesting
- static String getMappedColumnValue(
- Column spannerColDef,
- SourceColumn sourceColDef,
- JSONObject valuesJson,
- String sourceDbTimezoneOffset,
- List preparedStatementParameters) {
-
- String colInputValue = "";
+ static ColumnBinding getMappedColumnBinding(
+ Column spannerColDef, SourceColumn sourceColDef, JSONObject valuesJson) {
Type colType = spannerColDef.type();
String colName = spannerColDef.name();
- if (colType.getCode().equals(Type.Code.FLOAT64)
- || colType.getCode().equals(Type.Code.FLOAT32)
- || colType.getCode().equals(Type.Code.PG_FLOAT4)
- || colType.getCode().equals(Type.Code.PG_FLOAT8)
- || colType.getCode().equals(Type.Code.PG_NUMERIC)) {
- colInputValue = valuesJson.getBigDecimal(colName).toString();
- } else if (colType.getCode().equals(Type.Code.BOOL)
- || colType.getCode().equals(Type.Code.PG_BOOL)) {
- colInputValue = String.valueOf(valuesJson.getBoolean(colName));
- } else if ((colType.getCode().equals(Type.Code.ARRAY)
- && colType.getArrayElementType().getCode().equals(Type.Code.STRING))
- || (colType.getCode().equals(Type.Code.PG_ARRAY)
- && (colType.getArrayElementType().getCode().equals(Type.Code.PG_VARCHAR)
- || colType.getArrayElementType().getCode().equals(Type.Code.PG_TEXT)))) {
-
- colInputValue =
- valuesJson.getJSONArray(colName).toList().stream()
- .map(String::valueOf)
- .collect(Collectors.joining(","));
- } else if (colType.getCode().equals(Type.Code.BYTES)
- || colType.getCode().equals(Type.Code.PG_BYTEA)) {
- if (sourceColDef.type().toLowerCase().equals("bytea")) {
- colInputValue = convertBase64ToHex(valuesJson.getString(colName));
- } else {
- // Postgres decode: decode('base64string', 'base64')
- colInputValue = "decode('" + valuesJson.getString(colName) + "', 'base64')";
+ Type.Code code = colType.getCode();
+ PgColumnType pgType = PgColumnType.fromSourceType(sourceColDef.type());
+
+ try {
+ // Spanner BYTES values are Base64 encoded in the change stream. Bind raw bytes for bytea and
+ // non-character columns; for character columns, format as PostgreSQL hex bytea text (\x...)
+ // so INSERT and DELETE work symmetrically without text=bytea operator errors.
+ if (code == Type.Code.BYTES || code == Type.Code.PG_BYTEA) {
+ byte[] bytes = Base64.getDecoder().decode(valuesJson.getString(colName));
+ if (pgType == PgColumnType.CHARACTER) {
+ return ColumnBinding.of(PreparedStatementValue.ofString(toPostgresHexByteaText(bytes)));
+ }
+ return ColumnBinding.of(PreparedStatementValue.ofBytes(bytes));
}
- } else {
- colInputValue = valuesJson.getString(colName);
- }
- String response =
- getColumnValueByType(
- sourceColDef.type().toLowerCase(),
- colInputValue,
- sourceDbTimezoneOffset,
- colType.toString());
- return response;
+
+ return switch (pgType) {
+ case CHARACTER -> ColumnBinding.of(
+ PreparedStatementValue.ofString(
+ DMLGeneratorUtils.removeNullBytes(
+ getSpannerTextValue(colType, valuesJson, colName))));
+ case TIMESTAMP ->
+ // Spanner timestamps are UTC. Casting via ?::timestamptz converts to the database
+ // session timezone for timestamp-without-tz columns (sourceDbTimezoneOffset is not
+ // applied).
+ ColumnBinding.of(
+ TIMESTAMPTZ_PLACEHOLDER,
+ ImmutableList.of(
+ PreparedStatementValue.ofUntypedString(
+ DMLGeneratorUtils.removeNullBytes(
+ getSpannerTextValue(colType, valuesJson, colName)))));
+ case BOOLEAN -> ColumnBinding.of(
+ code == Type.Code.BOOL || code == Type.Code.PG_BOOL
+ ? PreparedStatementValue.ofBoolean(valuesJson.getBoolean(colName))
+ : booleanTextToParam(getSpannerTextValue(colType, valuesJson, colName)));
+ case INTEGER, FLOAT8, DECIMAL -> ColumnBinding.of(
+ getNumberBindingValue(colType, pgType, valuesJson, colName));
+ case OTHER ->
+ // Structured, temporal, real/float4, binary-from-string, arrays (e.g. from Spanner
+ // STRING), USER-DEFINED (enums, composite/range/extension types), and unknown columns
+ // use Types.OTHER so pgjdbc sends OID UNSPECIFIED and PostgreSQL infers the type.
+ // TODO(b/586644347): Add PostgreSQL array literal formatting and ?::timestamptz[]
+ // casting when AssignShardIdFn supports Spanner ARRAY columns end-to-end.
+ ColumnBinding.of(
+ PreparedStatementValue.ofUntypedString(
+ DMLGeneratorUtils.removeNullBytes(
+ getSpannerTextValue(colType, valuesJson, colName))));
+ };
+ } catch (JSONException | IllegalArgumentException e) {
+ String message =
+ String.format(
+ "Failed to convert column %s (Spanner type %s, PostgreSQL type %s): %s",
+ sourceColDef.name(), colType, sourceColDef.type(), e.getClass().getSimpleName());
+ // JSONException and NumberFormatException messages contain the raw column value, and
+ // SourceWriterFn appends the cause's message to the error message, so the cause is kept
+ // only for other errors (for example invalid Base64).
+ if (e instanceof JSONException || e instanceof NumberFormatException) {
+ throw new InvalidDMLGenerationException(message);
+ }
+ throw new InvalidDMLGenerationException(message, e);
+ }
}
+ /**
+ * Maps a custom transformation output for a PostgreSQL column to a {@link ColumnBinding}.
+ * Dispatching follows the PostgreSQL column category so {@code INSERT} and {@code DELETE} bind
+ * compatible OIDs. Values are always bound as data (never SQL) without forced timezone casting.
+ */
@VisibleForTesting
- protected static String convertBase64ToHex(String base64EncodedString) {
- String rawHex = DMLGeneratorUtils.convertBase64ToRawHex(base64EncodedString);
- if (rawHex == null) {
- return null;
+ static ColumnBinding getCustomValueBinding(
+ SourceColumn sourceColDef, @Nullable Object customValue) {
+ PgColumnType pgType = PgColumnType.fromSourceType(sourceColDef.type());
+ if (customValue == null || JSONObject.NULL.equals(customValue)) {
+ return typedNullBinding(pgType);
+ }
+
+ // Raw byte[] targeting non-character columns binds directly via setBytes; character columns
+ // receive PostgreSQL hex text as VARCHAR so DELETE works without text=bytea operator errors.
+ if (customValue instanceof byte[]) {
+ byte[] bytes = (byte[]) customValue;
+ return pgType == PgColumnType.CHARACTER
+ ? ColumnBinding.of(PreparedStatementValue.ofString(toPostgresHexByteaText(bytes)))
+ : ColumnBinding.of(PreparedStatementValue.ofBytes(bytes));
}
- return rawHex.isEmpty() ? "''" : "'\\x" + rawHex + "'";
+
+ return switch (pgType) {
+ case CHARACTER -> ColumnBinding.of(
+ PreparedStatementValue.ofString(safeStringWithoutNullBytes(customValue)));
+ case BOOLEAN -> ColumnBinding.of(
+ customValue instanceof Boolean
+ ? PreparedStatementValue.ofBoolean((Boolean) customValue)
+ : booleanTextToParam(customValue.toString()));
+ case INTEGER, FLOAT8, DECIMAL -> ColumnBinding.of(customNumberToParam(customValue, pgType));
+ case TIMESTAMP, OTHER ->
+ // Custom timestamp values use plain '?' without ::timestamptz so user-formatted values
+ // are not double-converted; real/float4 and structured/array/unknown types bind untyped
+ // via Types.OTHER.
+ ColumnBinding.of(
+ PreparedStatementValue.ofUntypedString(safeStringWithoutNullBytes(customValue)));
+ };
}
- private static String getColumnValueByType(
- String columnType, String colValue, String sourceDbTimezoneOffset, String spannerColType) {
- String response = "";
- // TODO: Add support for array types (e.g., varchar[], integer[]) to generate valid PostgreSQL
- // array literals.
- switch (columnType) {
- case "varchar":
- case "char":
- case "text":
- case "character varying":
- case "character":
- case "json":
- case "jsonb":
- case "date":
- case "time":
- case "uuid":
- response = getQuotedEscapedString(colValue, spannerColType);
- break;
- case "timestamp":
- case "timestamp without time zone":
- case "timestamp with time zone":
- case "timestamptz":
- response = getQuotedEscapedString(colValue, spannerColType) + "::timestamptz";
- break;
- case "bytea":
- case "binary":
- case "varbinary":
- response = colValue; // Handled in getMappedColumnValue via decode() or convertBase64ToHex()
- break;
- default:
- response = colValue;
+ @Nullable
+ private static String safeStringWithoutNullBytes(Object value) {
+ String text = value.toString();
+ return text == null ? null : DMLGeneratorUtils.removeNullBytes(text);
+ }
+
+ private static PreparedStatementValue booleanTextToParam(@Nullable String value) {
+ if (value == null) {
+ return PreparedStatementValue.ofUntypedString(null);
}
- return response;
+ String cleaned = DMLGeneratorUtils.removeNullBytes(value);
+ String trimmed = cleaned.trim();
+ if ("true".equalsIgnoreCase(trimmed)) {
+ return PreparedStatementValue.ofBoolean(true);
+ }
+ if ("false".equalsIgnoreCase(trimmed)) {
+ return PreparedStatementValue.ofBoolean(false);
+ }
+ // Delegate other PostgreSQL boolean literals ("0", "1", "t", "f", "yes", "no") and invalid
+ // inputs to PostgreSQL's boolin via Types.OTHER rather than binding as integer/numeric.
+ return PreparedStatementValue.ofUntypedString(cleaned);
}
- private static String escapeString(String input) {
- String cleanedNullBytes = StringUtils.replace(input, "\u0000", "");
- cleanedNullBytes = StringUtils.replace(cleanedNullBytes, "'", "''");
- // PostgreSQL defaults to standard conforming strings, so backslash is just a
- // backslash.
- // For standard string literals '', we just need to escape the single quote as
- // ''
- return cleanedNullBytes;
+ private static PreparedStatementValue getNumberBindingValue(
+ Type colType, PgColumnType pgType, JSONObject valuesJson, String colName) {
+ Type.Code code = colType.getCode();
+ if (DMLGeneratorUtils.isFloatOrPgNumeric(code) || code == Type.Code.NUMERIC) {
+ Object raw = valuesJson.get(colName);
+ if (raw instanceof String) {
+ String text = (String) raw;
+ String trimmed = text.trim();
+ if (DMLGeneratorUtils.isNonFiniteTrimmed(trimmed)) {
+ return nonFiniteToNumberParam(trimmed, pgType);
+ }
+ // Guard against O(N^2) BigDecimal parsing on oversized numeric strings before
+ // getBigDecimal.
+ if (trimmed.length() > MAX_BIG_DECIMAL_TEXT_LENGTH) {
+ return PreparedStatementValue.ofUntypedString(DMLGeneratorUtils.removeNullBytes(text));
+ }
+ BigDecimal decimalValue = valuesJson.getBigDecimal(colName);
+ return decimalToNumberParam(decimalValue, pgType, text);
+ }
+ // Dispatch Double/Float directly so -0.0 keeps its sign bit (org.json parses -0.0 as Double
+ // and getBigDecimal would drop the sign), non-finite doubles bind properly, and numeric
+ // targets avoid new BigDecimal(double) binary expansion.
+ if (raw instanceof Double || raw instanceof Float) {
+ return floatingNumberToParam((Number) raw, pgType);
+ }
+ return decimalToNumberParam(valuesJson.getBigDecimal(colName), pgType, null);
+ }
+
+ if (code == Type.Code.INT64 || code == Type.Code.PG_INT8) {
+ // Spanner change streams serialize INT64 as JSON strings, while callers/tests may pass JSON
+ // numbers.
+ Object raw = valuesJson.get(colName);
+ if (raw instanceof Long || raw instanceof Integer || raw instanceof Short) {
+ return longToNumberParam(((Number) raw).longValue(), pgType);
+ }
+ if (raw instanceof String) {
+ String text = (String) raw;
+ String trimmed = text.trim();
+ try {
+ long parsed = Long.parseLong(trimmed);
+ // Preserve "-0" sign bit when targeting FLOAT8 by falling through to numberTextToParam.
+ if (parsed != 0L || pgType != PgColumnType.FLOAT8 || !trimmed.startsWith("-")) {
+ return longToNumberParam(parsed, pgType);
+ }
+ } catch (NumberFormatException e) {
+ // Fall through for out-of-long-range or non-integer text.
+ }
+ return numberTextToParam(text, pgType);
+ }
+ return numberTextToParam(raw.toString(), pgType);
+ }
+
+ String stringValue = getSpannerTextValue(colType, valuesJson, colName);
+ return numberTextToParam(stringValue, pgType);
}
- static String getQuotedEscapedString(String input, String spannerColType) {
- if ("BYTES".equals(spannerColType) || "PG_BYTEA".equals(spannerColType)) {
- return input;
+ private static PreparedStatementValue customNumberToParam(
+ Object customValue, PgColumnType pgType) {
+ if (customValue instanceof String) {
+ return numberTextToParam((String) customValue, pgType);
}
- String cleanedString = escapeString(input);
- String response = "'" + cleanedString + "'";
- return response;
+ if (customValue instanceof Long
+ || customValue instanceof Integer
+ || customValue instanceof Short
+ || customValue instanceof Byte) {
+ return longToNumberParam(((Number) customValue).longValue(), pgType);
+ }
+ if (customValue instanceof BigDecimal) {
+ return decimalToNumberParam((BigDecimal) customValue, pgType, null);
+ }
+ if (customValue instanceof BigInteger) {
+ return decimalToNumberParam(new BigDecimal((BigInteger) customValue), pgType, null);
+ }
+ if (customValue instanceof Double || customValue instanceof Float) {
+ return floatingNumberToParam((Number) customValue, pgType);
+ }
+ // Booleans or other arbitrary objects targeting number columns must never bind as OID BOOL
+ // (which has no implicit cast to numeric/int in PostgreSQL); bind untyped via Types.OTHER.
+ return PreparedStatementValue.ofUntypedString(safeStringWithoutNullBytes(customValue));
+ }
+
+ private static PreparedStatementValue longToNumberParam(long value, PgColumnType pgType) {
+ return switch (pgType) {
+ case FLOAT8 -> PreparedStatementValue.ofDouble((double) value);
+ case DECIMAL -> PreparedStatementValue.ofBigDecimal(BigDecimal.valueOf(value));
+ // OID INT8 (20) uses int2/int4/int8 B-tree indexes on DELETE.
+ case INTEGER -> PreparedStatementValue.ofLong(value);
+ case CHARACTER, TIMESTAMP, BOOLEAN, OTHER -> throw new AssertionError(
+ "Unexpected numeric PgColumnType: " + pgType);
+ };
+ }
+
+ private static PreparedStatementValue decimalToNumberParam(
+ BigDecimal decimalValue, PgColumnType pgType, @Nullable String originalText) {
+ return switch (pgType) {
+ case FLOAT8 -> {
+ double d = decimalValue.doubleValue();
+ // BigDecimal drops the sign of -0.0; restore IEEE 754 -0.0d when the original text was a
+ // signed negative zero literal (decimalValue.signum() == 0 distinguishes zero from negative
+ // subnormal underflow like "-1e-400" where signum() == -1).
+ if (d == 0.0d
+ && decimalValue.signum() == 0
+ && originalText != null
+ && originalText.trim().startsWith("-")) {
+ d = -0.0d;
+ }
+ // Fall back to untyped binding on overflow to Infinity or underflow to 0.0 so PostgreSQL
+ // validates the range instead of silently corrupting the value.
+ if (Double.isFinite(d) && (d != 0.0d || decimalValue.signum() == 0)) {
+ yield PreparedStatementValue.ofDouble(d);
+ }
+ yield PreparedStatementValue.ofUntypedString(
+ originalText != null ? originalText : decimalValue.toString());
+ }
+ case INTEGER -> {
+ try {
+ yield PreparedStatementValue.ofLong(decimalValue.longValueExact());
+ } catch (ArithmeticException e) {
+ // Fractional or out-of-long-range values fall through to bounded BigDecimal so PostgreSQL
+ // performs assignment casting (for example 1.5 -> 2) or range validation.
+ }
+ yield bindBoundedNumeric(decimalValue, originalText);
+ }
+ case DECIMAL -> bindBoundedNumeric(decimalValue, originalText);
+ case CHARACTER, TIMESTAMP, BOOLEAN, OTHER -> throw new AssertionError(
+ "Unexpected numeric PgColumnType: " + pgType);
+ };
+ }
+
+ private static PreparedStatementValue bindBoundedNumeric(
+ BigDecimal decimalValue, @Nullable String originalText) {
+ if (isWithinPostgresNumericBounds(decimalValue)) {
+ return PreparedStatementValue.ofBigDecimal(decimalValue);
+ }
+ return PreparedStatementValue.ofUntypedString(
+ originalText != null ? originalText : decimalValue.toString());
+ }
+
+ private static PreparedStatementValue floatingNumberToParam(Number value, PgColumnType pgType) {
+ // Widen Float via its decimal text so e.g. 1.1f becomes 1.1d instead of 1.100000023841858d.
+ double d = (value instanceof Float) ? Double.parseDouble(value.toString()) : (Double) value;
+ if (!Double.isFinite(d)) {
+ return nonFiniteToNumberParam(value.toString(), pgType);
+ }
+ if (pgType == PgColumnType.FLOAT8) {
+ return PreparedStatementValue.ofDouble(d);
+ }
+ // Preserve exact decimal text for numeric/decimal/integer columns.
+ return decimalToNumberParam(new BigDecimal(value.toString()), pgType, value.toString());
+ }
+
+ private static PreparedStatementValue nonFiniteToNumberParam(
+ String trimmedNonFiniteText, PgColumnType pgType) {
+ if (pgType == PgColumnType.FLOAT8) {
+ double value;
+ if ("nan".equalsIgnoreCase(trimmedNonFiniteText)) {
+ value = Double.NaN;
+ } else if ("-infinity".equalsIgnoreCase(trimmedNonFiniteText)) {
+ value = Double.NEGATIVE_INFINITY;
+ } else {
+ value = Double.POSITIVE_INFINITY;
+ }
+ return PreparedStatementValue.ofDouble(value);
+ }
+ // Delegate non-finite literals for numeric (Infinity supported on PG 14+, NaN on all versions)
+ // and integer columns to PostgreSQL via Types.OTHER so the server accepts or rejects them.
+ return PreparedStatementValue.ofUntypedString(trimmedNonFiniteText);
+ }
+
+ /**
+ * Converts a string targeting a PostgreSQL {@code INTEGER}, {@code FLOAT8}, or {@code DECIMAL}
+ * column into a {@link PreparedStatementValue}. Integer literals for integer columns bind as
+ * {@link Long}; decimals and scientific notation bind with exact {@link BigDecimal} precision for
+ * {@code numeric}/{@code decimal} and range-checked {@link Double} for {@code double precision};
+ * any non-numeric, oversized, or out-of-bounds text binds via {@link Types#OTHER} as data.
+ */
+ private static PreparedStatementValue numberTextToParam(
+ @Nullable String value, PgColumnType pgType) {
+ if (value == null) {
+ return PreparedStatementValue.ofUntypedString(null);
+ }
+ String cleaned = DMLGeneratorUtils.removeNullBytes(value);
+ String trimmed = cleaned.trim();
+ if (trimmed.isEmpty()) {
+ return PreparedStatementValue.ofUntypedString(cleaned);
+ }
+ if (DMLGeneratorUtils.isNonFiniteTrimmed(trimmed)) {
+ return nonFiniteToNumberParam(trimmed, pgType);
+ }
+ if (trimmed.length() > MAX_BIG_DECIMAL_TEXT_LENGTH) {
+ return PreparedStatementValue.ofUntypedString(cleaned);
+ }
+ if (INTEGER_LITERAL.matcher(trimmed).matches()) {
+ if (pgType == PgColumnType.INTEGER) {
+ try {
+ return PreparedStatementValue.ofLong(Long.parseLong(trimmed));
+ } catch (NumberFormatException e) {
+ // Out-of-long-range integer falls through to BigDecimal bounds check below.
+ }
+ }
+ return decimalToNumberParam(new BigDecimal(trimmed), pgType, cleaned);
+ }
+ if (DECIMAL_LITERAL.matcher(trimmed).matches()
+ || SCIENTIFIC_LITERAL.matcher(trimmed).matches()) {
+ try {
+ return decimalToNumberParam(new BigDecimal(trimmed), pgType, cleaned);
+ } catch (NumberFormatException e) {
+ // Exponent overflow in BigDecimal(String) falls back to untyped binding.
+ return PreparedStatementValue.ofUntypedString(cleaned);
+ }
+ }
+ return PreparedStatementValue.ofUntypedString(cleaned);
+ }
+
+ private static boolean isWithinPostgresNumericBounds(BigDecimal decimalValue) {
+ long scale = decimalValue.scale();
+ long integerDigits = (long) decimalValue.precision() - scale;
+ return scale <= PG_NUMERIC_MAX_SCALE && integerDigits <= PG_NUMERIC_MAX_INTEGER_DIGITS;
+ }
+
+ /**
+ * Returns the text of a non-null, non-BYTES Spanner value in {@code valuesJson}. Preserves exact
+ * string-encoded {@code NUMERIC}/{@code PG_NUMERIC} text (avoiding scientific-notation
+ * reformatting such as {@code 0.0000001} -> {@code 1E-7}), preserves {@code -0.0} sign bits for
+ * floating-point values, handles numeric JSON primitives for non-float Spanner columns, and
+ * delegates booleans and string arrays to {@link DMLGeneratorUtils#getSpannerValueAsString}.
+ */
+ private static String getSpannerTextValue(Type colType, JSONObject valuesJson, String colName) {
+ Type.Code code = colType.getCode();
+ if (code == Type.Code.NUMERIC || code == Type.Code.PG_NUMERIC) {
+ Object raw = valuesJson.get(colName);
+ if (raw instanceof String) {
+ return (String) raw;
+ }
+ if (raw instanceof Double || raw instanceof Float) {
+ if (!Double.isFinite(((Number) raw).doubleValue())) {
+ return raw.toString();
+ }
+ // Render floating JSON primitives without trailing ".0" or scientific notation.
+ return new BigDecimal(raw.toString()).stripTrailingZeros().toPlainString();
+ }
+ BigDecimal decimalValue = valuesJson.getBigDecimal(colName);
+ // Guard toPlainString() with PostgreSQL numeric bounds to avoid OOM on extreme exponents.
+ return isWithinPostgresNumericBounds(decimalValue)
+ ? decimalValue.toPlainString()
+ : decimalValue.toString();
+ }
+ boolean isSpannerFloat =
+ code == Type.Code.FLOAT32
+ || code == Type.Code.FLOAT64
+ || code == Type.Code.PG_FLOAT4
+ || code == Type.Code.PG_FLOAT8;
+ if (isSpannerFloat) {
+ Object raw = valuesJson.get(colName);
+ if (raw instanceof String) {
+ String trimmed = ((String) raw).trim();
+ return DMLGeneratorUtils.isNonFiniteTrimmed(trimmed) ? trimmed : (String) raw;
+ }
+ if (raw instanceof Double || raw instanceof Float) {
+ return raw.toString();
+ }
+ return valuesJson.getBigDecimal(colName).toString();
+ }
+ if (code == Type.Code.BOOL
+ || code == Type.Code.PG_BOOL
+ || DMLGeneratorUtils.isStringArray(colType)) {
+ return DMLGeneratorUtils.getSpannerValueAsString(colType, valuesJson, colName);
+ }
+ Object raw = valuesJson.get(colName);
+ return (raw instanceof String) ? (String) raw : raw.toString();
+ }
+
+ /**
+ * Formats bytes using PostgreSQL's default {@code bytea_output = hex} representation ({@code
+ * \x...}).
+ */
+ private static String toPostgresHexByteaText(byte[] bytes) {
+ return "\\x" + HexFormat.of().formatHex(bytes);
}
}
diff --git a/v2/spanner-to-sourcedb/src/main/java/com/google/cloud/teleport/v2/templates/source/sqlserver/SQLServerDMLGenerator.java b/v2/spanner-to-sourcedb/src/main/java/com/google/cloud/teleport/v2/templates/source/sqlserver/SQLServerDMLGenerator.java
index c682b1ae68..5f3020322d 100644
--- a/v2/spanner-to-sourcedb/src/main/java/com/google/cloud/teleport/v2/templates/source/sqlserver/SQLServerDMLGenerator.java
+++ b/v2/spanner-to-sourcedb/src/main/java/com/google/cloud/teleport/v2/templates/source/sqlserver/SQLServerDMLGenerator.java
@@ -416,8 +416,7 @@ static String getColumnValueByType(
}
private static String escapeString(String input) {
- String cleanedNullBytes = StringUtils.replace(input, "\u0000", "");
- return StringUtils.replace(cleanedNullBytes, "'", "''");
+ return StringUtils.replace(DMLGeneratorUtils.removeNullBytes(input), "'", "''");
}
private static String getQuotedEscapedString(String input, String spannerColType) {
diff --git a/v2/spanner-to-sourcedb/src/test/java/com/google/cloud/teleport/v2/templates/dbutils/dml/DMLGeneratorUtilsTest.java b/v2/spanner-to-sourcedb/src/test/java/com/google/cloud/teleport/v2/templates/dbutils/dml/DMLGeneratorUtilsTest.java
index 5454b61ff2..f54bbbf7ad 100644
--- a/v2/spanner-to-sourcedb/src/test/java/com/google/cloud/teleport/v2/templates/dbutils/dml/DMLGeneratorUtilsTest.java
+++ b/v2/spanner-to-sourcedb/src/test/java/com/google/cloud/teleport/v2/templates/dbutils/dml/DMLGeneratorUtilsTest.java
@@ -552,6 +552,39 @@ public void testGetNonFiniteTextForDoubleAndFloatValues() {
assertNull(DMLGeneratorUtils.getNonFiniteText(values, "finite"));
}
+ @Test
+ public void testIsNonFiniteTrimmed() {
+ assertTrue(DMLGeneratorUtils.isNonFiniteTrimmed("NaN"));
+ assertTrue(DMLGeneratorUtils.isNonFiniteTrimmed("nan"));
+ assertTrue(DMLGeneratorUtils.isNonFiniteTrimmed("Infinity"));
+ assertTrue(DMLGeneratorUtils.isNonFiniteTrimmed("+Infinity"));
+ assertTrue(DMLGeneratorUtils.isNonFiniteTrimmed("-INFINITY"));
+ assertFalse(DMLGeneratorUtils.isNonFiniteTrimmed(""));
+ assertFalse(DMLGeneratorUtils.isNonFiniteTrimmed("123"));
+ assertFalse(DMLGeneratorUtils.isNonFiniteTrimmed("inf"));
+ assertFalse(DMLGeneratorUtils.isNonFiniteTrimmed("*Infinity"));
+ // Only ASCII spellings match; the Turkish dotless (U+0131) and dotted (U+0130) i do not.
+ assertFalse(DMLGeneratorUtils.isNonFiniteTrimmed("\u0131nf\u0131n\u0131ty"));
+ assertFalse(DMLGeneratorUtils.isNonFiniteTrimmed("\u0130nfinity"));
+ }
+
+ @Test
+ public void testNormalizeSourceType() {
+ assertEquals("", DMLGeneratorUtils.normalizeSourceType(null));
+ assertEquals("", DMLGeneratorUtils.normalizeSourceType(" "));
+ assertEquals("varchar", DMLGeneratorUtils.normalizeSourceType(" VARCHAR "));
+ assertEquals(
+ "timestamp with time zone",
+ DMLGeneratorUtils.normalizeSourceType("TIMESTAMP WITH TIME ZONE"));
+ }
+
+ @Test
+ public void testRemoveNullBytes() {
+ assertEquals("abc", DMLGeneratorUtils.removeNullBytes("a\u0000b\u0000c"));
+ assertEquals("plain", DMLGeneratorUtils.removeNullBytes("plain"));
+ assertEquals("", DMLGeneratorUtils.removeNullBytes("\u0000"));
+ }
+
@Test
public void testTrimUtcSuffix() {
assertEquals("2024-01-01T12:34:56", DMLGeneratorUtils.trimUtcSuffix("2024-01-01T12:34:56Z"));
diff --git a/v2/spanner-to-sourcedb/src/test/java/com/google/cloud/teleport/v2/templates/dbutils/dml/PreparedStatementValueTest.java b/v2/spanner-to-sourcedb/src/test/java/com/google/cloud/teleport/v2/templates/dbutils/dml/PreparedStatementValueTest.java
index 9d834c9fe4..dea618895a 100644
--- a/v2/spanner-to-sourcedb/src/test/java/com/google/cloud/teleport/v2/templates/dbutils/dml/PreparedStatementValueTest.java
+++ b/v2/spanner-to-sourcedb/src/test/java/com/google/cloud/teleport/v2/templates/dbutils/dml/PreparedStatementValueTest.java
@@ -17,6 +17,8 @@
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotEquals;
+import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
@@ -108,6 +110,43 @@ public void testBindNullUsesSqlType() throws Exception {
verify(mockPreparedStatement).setNull(2, Types.VARBINARY);
}
+ @Test
+ public void testOfUntypedStringDirectBindAndAccessors() throws Exception {
+ PreparedStatementValue val = PreparedStatementValue.ofUntypedString("{\"a\":1}");
+ assertEquals(Types.OTHER, val.getSqlType());
+ assertEquals("{\"a\":1}", val.getValue());
+ assertFalse(val.isNull());
+ val.bind(mockPreparedStatement, 1);
+ verify(mockPreparedStatement).setObject(1, "{\"a\":1}", Types.OTHER);
+ verify(mockPreparedStatement, never()).setString(eq(1), any());
+
+ PreparedStatementValue nullVal = PreparedStatementValue.ofUntypedString(null);
+ assertTrue(nullVal.isNull());
+ assertEquals(Types.OTHER, nullVal.getSqlType());
+ assertNull(nullVal.getValue());
+ assertEquals(PreparedStatementValue.nullValue(Types.OTHER), nullVal);
+ nullVal.bind(mockPreparedStatement, 2);
+ verify(mockPreparedStatement).setNull(2, Types.OTHER);
+ verify(mockPreparedStatement, never()).setObject(eq(2), any(), eq(Types.OTHER));
+ }
+
+ @Test
+ public void testJdbcDaoBindsUntypedStringWithTypesOther() throws Exception {
+ DMLGeneratorResponse response = new DMLGeneratorResponse("sql ? ?");
+ response.setPreparedStatementParameters(
+ Arrays.asList(
+ PreparedStatementValue.ofUntypedString("{\"a\":1}"),
+ PreparedStatementValue.ofUntypedString(null)));
+
+ new JdbcDao("url", "user", mockConnectionHelper).write(response, null);
+
+ verify(mockPreparedStatement).setObject(1, "{\"a\":1}", Types.OTHER);
+ verify(mockPreparedStatement, never()).setString(eq(1), any());
+ verify(mockPreparedStatement).setNull(2, Types.OTHER);
+ verify(mockPreparedStatement).executeUpdate();
+ verify(mockConnection).commit();
+ }
+
@Test
public void testFromObjectKeepsJavaType() {
assertEquals(PreparedStatementValue.ofLong(5L), PreparedStatementValue.fromObject(5));
@@ -130,6 +169,7 @@ public void testFromObjectKeepsJavaType() {
@Test
public void testTypedNullFactories() {
assertEquals(Types.VARCHAR, PreparedStatementValue.ofString(null).getSqlType());
+ assertEquals(Types.OTHER, PreparedStatementValue.ofUntypedString(null).getSqlType());
assertEquals(Types.VARBINARY, PreparedStatementValue.ofBytes(null).getSqlType());
assertEquals(Types.BOOLEAN, PreparedStatementValue.ofBoolean(null).getSqlType());
assertEquals(Types.DECIMAL, PreparedStatementValue.ofBigDecimal(null).getSqlType());
@@ -160,5 +200,14 @@ public void testEqualsHashCodeAndToString() {
assertEquals(
"PreparedStatementValue{value=a, sqlType=12}",
PreparedStatementValue.ofString("a").toString());
+
+ PreparedStatementValue untyped = PreparedStatementValue.ofUntypedString("x");
+ PreparedStatementValue typed = PreparedStatementValue.ofString("x");
+ assertNotEquals(untyped, typed);
+ assertNotEquals(typed, untyped);
+ assertEquals(untyped, PreparedStatementValue.ofUntypedString("x"));
+ assertEquals(untyped.hashCode(), PreparedStatementValue.ofUntypedString("x").hashCode());
+ assertEquals(
+ "PreparedStatementValue{value=x, sqlType=" + Types.OTHER + "}", untyped.toString());
}
}
diff --git a/v2/spanner-to-sourcedb/src/test/java/com/google/cloud/teleport/v2/templates/source/postgres/PostgreSQLDMLGeneratorTest.java b/v2/spanner-to-sourcedb/src/test/java/com/google/cloud/teleport/v2/templates/source/postgres/PostgreSQLDMLGeneratorTest.java
index 10f09b8e7b..282e622da3 100644
--- a/v2/spanner-to-sourcedb/src/test/java/com/google/cloud/teleport/v2/templates/source/postgres/PostgreSQLDMLGeneratorTest.java
+++ b/v2/spanner-to-sourcedb/src/test/java/com/google/cloud/teleport/v2/templates/source/postgres/PostgreSQLDMLGeneratorTest.java
@@ -15,15 +15,12 @@
*/
package com.google.cloud.teleport.v2.templates.source.postgres;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
+import static com.google.common.truth.Truth.assertThat;
+import static com.google.common.truth.Truth.assertWithMessage;
import static org.junit.Assert.assertThrows;
-import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.fasterxml.jackson.databind.ObjectWriter;
import com.google.cloud.teleport.v2.spanner.ddl.Column;
import com.google.cloud.teleport.v2.spanner.ddl.Ddl;
import com.google.cloud.teleport.v2.spanner.ddl.Table;
@@ -35,23 +32,43 @@
import com.google.cloud.teleport.v2.spanner.sourceddl.SourceTable;
import com.google.cloud.teleport.v2.spanner.type.Type;
import com.google.cloud.teleport.v2.templates.changestream.TrimmedShardedDataChangeRecord;
+import com.google.cloud.teleport.v2.templates.dbutils.dml.ColumnBinding;
+import com.google.cloud.teleport.v2.templates.dbutils.dml.PreparedStatementValue;
import com.google.cloud.teleport.v2.templates.exceptions.InvalidDMLGenerationException;
import com.google.cloud.teleport.v2.templates.models.DMLGeneratorRequest;
import com.google.cloud.teleport.v2.templates.models.DMLGeneratorResponse;
+import com.google.cloud.teleport.v2.templates.source.postgres.PostgreSQLDMLGenerator.PgColumnType;
import com.google.cloud.teleport.v2.templates.utils.SchemaUtils;
import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.GsonBuilder;
import java.io.InputStream;
+import java.math.BigDecimal;
+import java.math.BigInteger;
import java.nio.channels.Channels;
import java.nio.charset.StandardCharsets;
+import java.sql.Timestamp;
+import java.sql.Types;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Base64;
+import java.util.HashMap;
+import java.util.HexFormat;
+import java.util.List;
+import java.util.Map;
+import java.util.NoSuchElementException;
+import java.util.UUID;
+import javax.annotation.Nullable;
import org.apache.beam.sdk.io.FileSystems;
import org.apache.commons.io.IOUtils;
+import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
+/** Unit tests for {@link PostgreSQLDMLGenerator}. */
@RunWith(JUnit4.class)
public final class PostgreSQLDMLGeneratorTest {
@@ -62,26 +79,30 @@ public void tableAndAllColumnNameTypesMatch() {
SourceSchema sourceSchema = SchemaUtils.buildSourceSchemaFromSessionFile(sessionFile);
ISchemaMapper schemaMapper = new SessionBasedMapper(sessionFile, ddl);
- String tableName = "Singers";
- String newValuesString = "{\"FirstName\":\"kk\",\"LastName\":\"ll\"}";
- JSONObject newValuesJson = new JSONObject(newValuesString);
- JSONObject keyValuesJson = new JSONObject("{\"SingerId\":\"999\"}");
- String modType = "INSERT";
-
- PostgreSQLDMLGenerator postgreSQLDMLGenerator = new PostgreSQLDMLGenerator();
- DMLGeneratorResponse dmlGeneratorResponse =
- postgreSQLDMLGenerator.getDMLStatement(
- new DMLGeneratorRequest.Builder(
- modType, tableName, newValuesJson, keyValuesJson, "+00:00")
- .setSchemaMapper(schemaMapper)
- .setDdl(ddl)
- .setSourceSchema(sourceSchema)
- .build());
- String sql = dmlGeneratorResponse.getDmlStatement();
+ JSONObject newValuesJson = new JSONObject().put("FirstName", "kk").put("LastName", "ll");
+ JSONObject keyValuesJson = new JSONObject().put("SingerId", "999");
- assertTrue(sql.contains("\"FirstName\" = EXCLUDED.\"FirstName\""));
- assertTrue(sql.contains("\"LastName\" = EXCLUDED.\"LastName\""));
- assertTrue(sql.contains("ON CONFLICT (\"SingerId\") DO UPDATE SET"));
+ DMLGeneratorResponse response =
+ new PostgreSQLDMLGenerator()
+ .getDMLStatement(
+ new DMLGeneratorRequest.Builder(
+ "INSERT", "Singers", newValuesJson, keyValuesJson, "+00:00")
+ .setSchemaMapper(schemaMapper)
+ .setDdl(ddl)
+ .setSourceSchema(sourceSchema)
+ .build());
+
+ assertThat(response.getDmlStatement())
+ .isEqualTo(
+ "INSERT INTO \"Singers\" (\"FirstName\",\"LastName\",\"SingerId\") VALUES (?,?,?)"
+ + " ON CONFLICT (\"SingerId\") DO UPDATE SET"
+ + " \"FirstName\" = EXCLUDED.\"FirstName\","
+ + "\"LastName\" = EXCLUDED.\"LastName\"");
+ assertParams(
+ response.getPreparedStatementParameters(),
+ PreparedStatementValue.ofString("kk"),
+ PreparedStatementValue.ofString("ll"),
+ PreparedStatementValue.ofLong(999L));
}
@Test
@@ -91,26 +112,25 @@ public void deleteMultiplePKColumns() {
SourceSchema sourceSchema = SchemaUtils.buildSourceSchemaFromSessionFile(sessionFile);
ISchemaMapper schemaMapper = new SessionBasedMapper(sessionFile, ddl);
- String tableName = "Singers";
- String newValuesString = "{\"LastName\":null}";
- JSONObject newValuesJson = new JSONObject(newValuesString);
- JSONObject keyValuesJson = new JSONObject("{\"SingerId\":\"999\",\"FirstName\":\"kk\"}");
- String modType = "DELETE";
-
- PostgreSQLDMLGenerator postgreSQLDMLGenerator = new PostgreSQLDMLGenerator();
- DMLGeneratorResponse dmlGeneratorResponse =
- postgreSQLDMLGenerator.getDMLStatement(
- new DMLGeneratorRequest.Builder(
- modType, tableName, newValuesJson, keyValuesJson, "+00:00")
- .setSchemaMapper(schemaMapper)
- .setDdl(ddl)
- .setSourceSchema(sourceSchema)
- .build());
- String sql = dmlGeneratorResponse.getDmlStatement();
+ JSONObject newValuesJson = new JSONObject().put("LastName", JSONObject.NULL);
+ JSONObject keyValuesJson = new JSONObject().put("SingerId", "999").put("FirstName", "kk");
- assertTrue(sql.contains("\"FirstName\" = 'kk'"));
- assertTrue(sql.contains("\"SingerId\" = 999"));
- assertTrue(sql.contains("DELETE FROM \"Singers\" WHERE"));
+ DMLGeneratorResponse response =
+ new PostgreSQLDMLGenerator()
+ .getDMLStatement(
+ new DMLGeneratorRequest.Builder(
+ "DELETE", "Singers", newValuesJson, keyValuesJson, "+00:00")
+ .setSchemaMapper(schemaMapper)
+ .setDdl(ddl)
+ .setSourceSchema(sourceSchema)
+ .build());
+
+ assertThat(response.getDmlStatement())
+ .isEqualTo("DELETE FROM \"Singers\" WHERE \"SingerId\" = ? AND \"FirstName\" = ?");
+ assertParams(
+ response.getPreparedStatementParameters(),
+ PreparedStatementValue.ofLong(999L),
+ PreparedStatementValue.ofString("kk"));
}
@Test
@@ -120,23 +140,19 @@ public void primaryKeyNotFoundInJson() {
SourceSchema sourceSchema = SchemaUtils.buildSourceSchemaFromSessionFile(sessionFile);
ISchemaMapper schemaMapper = new SessionBasedMapper(sessionFile, ddl);
- String tableName = "Singers";
- String newValuesString = "{\"FirstName\":\"kk\",\"LastName\":\"ll\"}";
- JSONObject newValuesJson = new JSONObject(newValuesString);
- JSONObject keyValuesJson = new JSONObject("{\"SomeRandomName\":\"999\"}");
- String modType = "INSERT";
-
- PostgreSQLDMLGenerator postgreSQLDMLGenerator = new PostgreSQLDMLGenerator();
- assertThrows(
- InvalidDMLGenerationException.class,
- () ->
- postgreSQLDMLGenerator.getDMLStatement(
- new DMLGeneratorRequest.Builder(
- modType, tableName, newValuesJson, keyValuesJson, "+00:00")
- .setSchemaMapper(schemaMapper)
- .setDdl(ddl)
- .setSourceSchema(sourceSchema)
- .build()));
+ JSONObject newValuesJson = new JSONObject().put("FirstName", "kk").put("LastName", "ll");
+ JSONObject keyValuesJson = new JSONObject().put("SomeRandomName", "999");
+
+ DMLGeneratorRequest request =
+ new DMLGeneratorRequest.Builder("INSERT", "Singers", newValuesJson, keyValuesJson, "+00:00")
+ .setSchemaMapper(schemaMapper)
+ .setDdl(ddl)
+ .setSourceSchema(sourceSchema)
+ .build();
+ PostgreSQLDMLGenerator generator = new PostgreSQLDMLGenerator();
+ InvalidDMLGenerationException thrown =
+ assertThrows(InvalidDMLGenerationException.class, () -> generator.getDMLStatement(request));
+ assertThat(thrown).hasMessageThat().contains("without primary key");
}
@Test
@@ -146,119 +162,44 @@ public void primaryKeyNotPresentInSourceSchema() {
SourceSchema sourceSchema = SchemaUtils.buildSourceSchemaFromSessionFile(sessionFile);
ISchemaMapper schemaMapper = new SessionBasedMapper(sessionFile, ddl);
- String tableName = "Singers";
- String newValuesString = "{\"FirstName\":\"kk\",\"LastName\":\"ll\"}";
- JSONObject newValuesJson = new JSONObject(newValuesString);
- JSONObject keyValuesJson = new JSONObject("{\"SingerId\":\"999\"}");
- String modType = "INSERT";
-
- PostgreSQLDMLGenerator postgreSQLDMLGenerator = new PostgreSQLDMLGenerator();
- assertThrows(
- InvalidDMLGenerationException.class,
- () ->
- postgreSQLDMLGenerator.getDMLStatement(
- new DMLGeneratorRequest.Builder(
- modType, tableName, newValuesJson, keyValuesJson, "+00:00")
- .setSchemaMapper(schemaMapper)
- .setDdl(ddl)
- .setSourceSchema(sourceSchema)
- .build()));
+ JSONObject newValuesJson = new JSONObject().put("FirstName", "kk").put("LastName", "ll");
+ JSONObject keyValuesJson = new JSONObject().put("SingerId", "999");
+
+ DMLGeneratorRequest request =
+ new DMLGeneratorRequest.Builder("INSERT", "Singers", newValuesJson, keyValuesJson, "+00:00")
+ .setSchemaMapper(schemaMapper)
+ .setDdl(ddl)
+ .setSourceSchema(sourceSchema)
+ .build();
+ PostgreSQLDMLGenerator generator = new PostgreSQLDMLGenerator();
+ InvalidDMLGenerationException thrown =
+ assertThrows(InvalidDMLGenerationException.class, () -> generator.getDMLStatement(request));
+ assertThat(thrown).hasMessageThat().contains("without primary key");
}
@Test
public void allDatatypesDML() throws Exception {
- String sessionFile = "src/test/resources/pgAllDatatypesSession.json";
- Ddl ddl = SchemaUtils.buildSpannerDdlFromSessionFile(sessionFile);
- SourceSchema sourceSchema = SchemaUtils.buildSourceSchemaFromSessionFile(sessionFile);
- ISchemaMapper schemaMapper = new SessionBasedMapper(sessionFile, ddl);
-
- InputStream stream =
- Channels.newInputStream(
- FileSystems.open(
- FileSystems.matchNewResource(
- "src/test/resources/bufferInputAllDatatypes.json", false)));
- String record = IOUtils.toString(stream, StandardCharsets.UTF_8);
-
- ObjectWriter ow = new ObjectMapper().writer();
- TrimmedShardedDataChangeRecord chrec =
- new GsonBuilder()
- .setFieldNamingPolicy(FieldNamingPolicy.IDENTITY)
- .create()
- .fromJson(record, TrimmedShardedDataChangeRecord.class);
-
- String tableName = chrec.getTableName();
- String modType = chrec.getModType().name();
- String keysJsonStr = chrec.getMod().getKeysJson();
- String newValueJsonStr = chrec.getMod().getNewValuesJson();
- JSONObject newValuesJson = new JSONObject(newValueJsonStr);
- JSONObject keyValuesJson = new JSONObject(keysJsonStr);
-
- PostgreSQLDMLGenerator postgreSQLDMLGenerator = new PostgreSQLDMLGenerator();
- DMLGeneratorResponse dmlGeneratorResponse =
- postgreSQLDMLGenerator.getDMLStatement(
- new DMLGeneratorRequest.Builder(
- modType, tableName, newValuesJson, keyValuesJson, "+00:00")
- .setSchemaMapper(schemaMapper)
- .setDdl(ddl)
- .setSourceSchema(sourceSchema)
- .build());
- String sql = dmlGeneratorResponse.getDmlStatement();
-
- assertTrue(sql.contains("333"));
- assertTrue(sql.contains("'\\x616263'"));
- assertTrue(sql.contains("'2023-05-18T12:01:13.088397258Z'::timestamptz"));
- assertTrue(sql.contains("'1'"));
- assertTrue(sql.contains("''"));
- assertTrue(sql.contains("'\\x6162636c61726765'"));
- assertTrue(sql.contains("'aaaaaddd'"));
- assertTrue(sql.contains("1"));
- assertTrue(sql.contains("4.2"));
- assertTrue(sql.contains("4444"));
- assertTrue(sql.contains("'10:10:10'"));
- assertTrue(sql.contains("''"));
- assertTrue(sql.contains("'1,2'"));
- assertTrue(sql.contains("'\\x61626c6f6e67626c6f6263'"));
- assertTrue(sql.contains("''"));
- assertTrue(sql.contains("2023"));
- assertTrue(sql.contains("'\\x616262696763'"));
- assertTrue(sql.contains("444.222"));
- assertTrue(sql.contains("false"));
- assertTrue(sql.contains("''"));
- assertTrue(sql.contains("'\\x6162636c61726765'"));
- assertTrue(sql.contains("'aaaaaddd'"));
- assertTrue(sql.contains("1"));
- assertTrue(sql.contains("4.2"));
- assertTrue(sql.contains("4444"));
- assertTrue(sql.contains("'10:10:10'"));
- assertTrue(sql.contains("''"));
- assertTrue(sql.contains("'1,2'"));
- assertTrue(sql.contains("'\\x61626c6f6e67626c6f6263'"));
- assertTrue(sql.contains("''"));
- assertTrue(sql.contains("2023"));
- assertTrue(sql.contains("'\\x616262696763'"));
- assertTrue(sql.contains("444.222"));
- assertTrue(sql.contains("false"));
- assertTrue(sql.contains("'"),
+ PreparedStatementValue.ofBytes(decodeBase64("YWJjbGFyZ2U=")),
+ PreparedStatementValue.ofLong(333L),
+ PreparedStatementValue.ofString(""),
+ PreparedStatementValue.ofString("1,2"),
+ PreparedStatementValue.ofLong(22L),
+ PreparedStatementValue.ofString("aaaaaddd"),
+ PreparedStatementValue.ofUntypedString("10:10:10"),
+ PreparedStatementValue.ofUntypedString("2023-05-18T12:01:13.088397258Z"),
+ PreparedStatementValue.ofBytes(decodeBase64("YWJj")),
+ PreparedStatementValue.ofLong(1L),
+ PreparedStatementValue.ofString(""),
+ PreparedStatementValue.ofBytes(decodeBase64("YWJjbGFyZ2U=")),
+ PreparedStatementValue.ofString("abc"),
+ PreparedStatementValue.ofLong(2023L),
+ PreparedStatementValue.ofLong(12L));
+ }
+
+ @Test
+ public void testNullValidationsRequest() {
PostgreSQLDMLGenerator generator = new PostgreSQLDMLGenerator();
- assertThrows(InvalidDMLGenerationException.class, () -> generator.getDMLStatement(null));
+ InvalidDMLGenerationException nullReqEx =
+ assertThrows(InvalidDMLGenerationException.class, () -> generator.getDMLStatement(null));
+ assertThat(nullReqEx).hasMessageThat().contains("DMLGeneratorRequest is null");
- // Request with null mapper
Ddl ddl = Ddl.builder().build();
SourceSchema sourceSchema =
SourceSchema.builder(SourceDatabaseType.POSTGRESQL).databaseName("test").build();
- assertThrows(
- InvalidDMLGenerationException.class,
- () ->
- generator.getDMLStatement(
- new DMLGeneratorRequest.Builder(
- "INSERT", "T", new JSONObject(), new JSONObject(), "+00:00")
- .setSchemaMapper(null)
- .setDdl(ddl)
- .setSourceSchema(sourceSchema)
- .build()));
+ DMLGeneratorRequest nullMapperReq =
+ new DMLGeneratorRequest.Builder("INSERT", "T", new JSONObject(), new JSONObject(), "+00:00")
+ .setSchemaMapper(null)
+ .setDdl(ddl)
+ .setSourceSchema(sourceSchema)
+ .build();
+ InvalidDMLGenerationException nullMapperEx =
+ assertThrows(
+ InvalidDMLGenerationException.class, () -> generator.getDMLStatement(nullMapperReq));
+ assertThat(nullMapperEx).hasMessageThat().contains("Schema Mapper");
ISchemaMapper schemaMapper =
new SessionBasedMapper("src/test/resources/allMatchSession.json", ddl);
- // Request with null ddl
- assertThrows(
- InvalidDMLGenerationException.class,
- () ->
- generator.getDMLStatement(
- new DMLGeneratorRequest.Builder(
- "INSERT", "T", new JSONObject(), new JSONObject(), "+00:00")
- .setSchemaMapper(schemaMapper)
- .setDdl(null)
- .setSourceSchema(sourceSchema)
- .build()));
-
- // Request with null source schema
- assertThrows(
- InvalidDMLGenerationException.class,
- () ->
- generator.getDMLStatement(
- new DMLGeneratorRequest.Builder(
- "INSERT", "T", new JSONObject(), new JSONObject(), "+00:00")
- .setSchemaMapper(schemaMapper)
- .setDdl(ddl)
- .setSourceSchema(null)
- .build()));
+ DMLGeneratorRequest nullDdlReq =
+ new DMLGeneratorRequest.Builder("INSERT", "T", new JSONObject(), new JSONObject(), "+00:00")
+ .setSchemaMapper(schemaMapper)
+ .setDdl(null)
+ .setSourceSchema(sourceSchema)
+ .build();
+ InvalidDMLGenerationException nullDdlEx =
+ assertThrows(
+ InvalidDMLGenerationException.class, () -> generator.getDMLStatement(nullDdlReq));
+ assertThat(nullDdlEx).hasMessageThat().contains("Spanner Ddl");
+
+ DMLGeneratorRequest nullSourceReq =
+ new DMLGeneratorRequest.Builder("INSERT", "T", new JSONObject(), new JSONObject(), "+00:00")
+ .setSchemaMapper(schemaMapper)
+ .setDdl(ddl)
+ .setSourceSchema(null)
+ .build();
+ InvalidDMLGenerationException nullSourceEx =
+ assertThrows(
+ InvalidDMLGenerationException.class, () -> generator.getDMLStatement(nullSourceReq));
+ assertThat(nullSourceEx).hasMessageThat().contains("SourceSchema");
}
@Test
@@ -381,122 +353,1635 @@ public void testUnsupportedModType() {
SourceSchema sourceSchema = SchemaUtils.buildSourceSchemaFromSessionFile(sessionFile);
ISchemaMapper schemaMapper = new SessionBasedMapper(sessionFile, ddl);
+ DMLGeneratorRequest request =
+ new DMLGeneratorRequest.Builder(
+ "REPLACE",
+ "Singers",
+ new JSONObject().put("FirstName", "a"),
+ new JSONObject().put("SingerId", "1"),
+ "+00:00")
+ .setSchemaMapper(schemaMapper)
+ .setDdl(ddl)
+ .setSourceSchema(sourceSchema)
+ .build();
PostgreSQLDMLGenerator generator = new PostgreSQLDMLGenerator();
+ InvalidDMLGenerationException thrown =
+ assertThrows(InvalidDMLGenerationException.class, () -> generator.getDMLStatement(request));
+ assertThat(thrown).hasMessageThat().contains("Unsupported modType: REPLACE");
+ }
- assertThrows(
- InvalidDMLGenerationException.class,
- () ->
- generator.getDMLStatement(
- new DMLGeneratorRequest.Builder(
- "REPLACE",
- "Singers",
- new JSONObject("{\"FirstName\":\"a\"}"),
- new JSONObject("{\"SingerId\":\"1\"}"),
- "+00:00")
- .setSchemaMapper(schemaMapper)
- .setDdl(ddl)
- .setSourceSchema(sourceSchema)
- .build()));
+ @Test
+ public void testBytesAndCharacterBindings() {
+ // Spanner BYTES -> bytea binds decoded bytes directly.
+ assertThat(bindValue(Type.bytes(), "bytea", "SGVsbG8="))
+ .isEqualTo(PreparedStatementValue.ofBytes("Hello".getBytes(StandardCharsets.UTF_8)));
+ assertThat(bindValue(Type.pgBytea(), "bytea", ""))
+ .isEqualTo(PreparedStatementValue.ofBytes(new byte[0]));
+ // NUL bytes inside bytea are preserved.
+ assertThat(bindValue(Type.bytes(), "bytea", "AA=="))
+ .isEqualTo(PreparedStatementValue.ofBytes(new byte[] {0}));
+
+ // Spanner BYTES -> character column formats PostgreSQL hex bytea text (\x...) as VARCHAR.
+ assertThat(bindValue(Type.bytes(), "text", "YWJj"))
+ .isEqualTo(PreparedStatementValue.ofString("\\x616263"));
+ assertThat(bindValue(Type.pgBytea(), "character varying", ""))
+ .isEqualTo(PreparedStatementValue.ofString("\\x"));
+ String highBytesBase64 =
+ Base64.getEncoder().encodeToString(new byte[] {(byte) 0xFF, (byte) 0x80, 0x00});
+ assertThat(bindValue(Type.bytes(), "text", highBytesBase64))
+ .isEqualTo(PreparedStatementValue.ofString("\\xff8000"));
+
+ // Spanner STRING -> text binds raw value (single quotes unescaped, NUL stripped).
+ assertThat(bindValue(Type.string(), "text", "it's a\u0000 string"))
+ .isEqualTo(PreparedStatementValue.ofString("it's a string"));
+
+ // Spanner NUMERIC -> text preserves exact decimal string form (never reformatted to 1E-7).
+ assertThat(bindValue(Type.numeric(), "text", "0.0000001"))
+ .isEqualTo(PreparedStatementValue.ofString("0.0000001"));
+ assertThat(bindValue(Type.pgNumeric(), "character varying", "0.0000001"))
+ .isEqualTo(PreparedStatementValue.ofString("0.0000001"));
+
+ // Spanner STRING -> bytea binds untyped via Types.OTHER so PostgreSQL parses bytea text.
+ assertThat(bindValue(Type.string(), "bytea", "\\x48656c6c6f"))
+ .isEqualTo(PreparedStatementValue.ofUntypedString("\\x48656c6c6f"));
}
@Test
- public void testConvertBase64ToHexEdgeCases() {
- // Empty string
- assertEquals("''", PostgreSQLDMLGenerator.convertBase64ToHex(""));
- // null string
- assertNull(PostgreSQLDMLGenerator.convertBase64ToHex(null));
- // Valid Base64 "hello" -> 68656c6c6f
- assertEquals("'\\x68656c6c6f'", PostgreSQLDMLGenerator.convertBase64ToHex("aGVsbG8="));
+ public void testConversionFailure_wrapsWithColumnNameAndTypesWithoutRawValue() {
+ String badSecretBase64 = "invalid-secret-base64!";
+ InvalidDMLGenerationException bytesEx =
+ assertThrows(
+ InvalidDMLGenerationException.class,
+ () -> bindValue(Type.bytes(), "bytea", badSecretBase64));
+ // Non-value-bearing IllegalArgumentException preserves cause/stack trace without leaking value.
+ assertThat(bytesEx).hasCauseThat().isInstanceOf(IllegalArgumentException.class);
+ assertThat(bytesEx).hasMessageThat().contains("test_col");
+ assertThat(bytesEx).hasMessageThat().contains("bytea");
+ assertThat(bytesEx).hasMessageThat().contains("IllegalArgumentException");
+ assertThat(bytesEx).hasMessageThat().doesNotContain(badSecretBase64);
+ assertThat(bytesEx).hasCauseThat().hasMessageThat().doesNotContain(badSecretBase64);
+
+ // Wrong JSON type (JSONException) wraps into permanent InvalidDMLGenerationException without
+ // attaching org.json's cause (which embeds the raw row value in its message).
+ InvalidDMLGenerationException jsonEx =
+ assertThrows(
+ InvalidDMLGenerationException.class,
+ () -> bindValue(Type.bool(), "boolean", "secret-not-a-json-bool"));
+ assertThat(jsonEx).hasCauseThat().isNull();
+ assertThat(jsonEx).hasMessageThat().contains("test_col");
+ assertThat(jsonEx).hasMessageThat().contains("JSONException");
+ assertThat(jsonEx).hasMessageThat().doesNotContain("secret-not-a-json-bool");
+ }
- // Invalid base64
- assertThrows(
- IllegalArgumentException.class,
- () -> PostgreSQLDMLGenerator.convertBase64ToHex("invalid-base64!"));
+ @Test
+ public void testStructuredAndTemporalBindings() {
+ String uuid = "123e4567-e89b-12d3-a456-426614174000";
+ assertThat(bindValue(Type.string(), "uuid", uuid))
+ .isEqualTo(PreparedStatementValue.ofUntypedString(uuid));
+ assertThat(bindValue(Type.uuid(), "uuid", uuid))
+ .isEqualTo(PreparedStatementValue.ofUntypedString(uuid));
+ assertThat(bindValue(Type.pgUuid(), "uuid", uuid))
+ .isEqualTo(PreparedStatementValue.ofUntypedString(uuid));
+ assertThat(bindValue(Type.string(), "jsonb", "{\"a\": 1}"))
+ .isEqualTo(PreparedStatementValue.ofUntypedString("{\"a\": 1}"));
+ assertThat(bindValue(Type.json(), "json", "{\"k\": \"v\"}"))
+ .isEqualTo(PreparedStatementValue.ofUntypedString("{\"k\": \"v\"}"));
+ assertThat(bindValue(Type.pgJsonb(), "jsonb", "{\"k\": \"v\"}"))
+ .isEqualTo(PreparedStatementValue.ofUntypedString("{\"k\": \"v\"}"));
+ assertThat(bindValue(Type.date(), "date", "2012-09-17"))
+ .isEqualTo(PreparedStatementValue.ofUntypedString("2012-09-17"));
+ assertThat(bindValue(Type.pgDate(), "date", "2012-09-17"))
+ .isEqualTo(PreparedStatementValue.ofUntypedString("2012-09-17"));
+ assertThat(bindValue(Type.string(), "time without time zone", "10:10:10"))
+ .isEqualTo(PreparedStatementValue.ofUntypedString("10:10:10"));
+ assertThat(bindValue(Type.string(), "time with time zone", "10:10:10+00"))
+ .isEqualTo(PreparedStatementValue.ofUntypedString("10:10:10+00"));
}
@Test
- public void testNonByteaDecodeBranch() {
- // Mocking Spanner Column
- Column spannerCol = mock(Column.class);
- when(spannerCol.name()).thenReturn("c");
- when(spannerCol.type()).thenReturn(Type.bytes());
+ public void testTimestampScalarAndNullBindingsStabilizePlaceholder() {
+ for (Type spannerTsType :
+ new Type[] {Type.timestamp(), Type.pgTimestamptz(), Type.pgCommitTimestamp()}) {
+ for (String tsType :
+ new String[] {
+ "timestamp",
+ "timestamp without time zone",
+ "timestamp with time zone",
+ "timestamptz",
+ "TIMESTAMP WITH TIME ZONE"
+ }) {
+ ColumnBinding nonNull = bind(spannerTsType, tsType, "2023-05-18T12:01:13.088397258Z");
+ assertWithMessage("non-null placeholder for %s -> %s", spannerTsType, tsType)
+ .that(nonNull.getPlaceholderSql())
+ .isEqualTo("?::timestamptz");
+ assertWithMessage("non-null params for %s -> %s", spannerTsType, tsType)
+ .that(nonNull.getParams())
+ .containsExactly(
+ PreparedStatementValue.ofUntypedString("2023-05-18T12:01:13.088397258Z"));
+
+ // Null timestamps reuse ?::timestamptz so pgjdbc sees one stable SQL statement per table.
+ ColumnBinding nullBinding = nullBindingFor(spannerTsType, tsType);
+ assertWithMessage("null placeholder for %s", tsType)
+ .that(nullBinding.getPlaceholderSql())
+ .isEqualTo("?::timestamptz");
+ assertWithMessage("isNullBinding for %s", tsType)
+ .that(PostgreSQLDMLGenerator.isNullBinding(nullBinding))
+ .isTrue();
+ assertWithMessage("null params for %s", tsType)
+ .that(nullBinding.getParams())
+ .containsExactly(PreparedStatementValue.nullValue(Types.NULL));
+ }
+ }
+ }
- // Mocking SourceColumn
- SourceColumn sourceCol = mock(SourceColumn.class);
- when(sourceCol.name()).thenReturn("c");
- when(sourceCol.type()).thenReturn("text");
+ @Test
+ public void nullBinding_matchesPlaceholderAndParameterTypeOfNonNullValues() {
+ // pgjdbc reuses a server-prepared statement only while the SQL text and the parameter types
+ // stay the same, so a NULL binds like the non-null values of the same column.
+ Object[][] columns = {
+ {Type.string(), "text", "a"},
+ {Type.string(), "character varying", "a"},
+ {Type.string(), "character", "a"},
+ {Type.string(), "name", "a"},
+ {Type.int64(), "smallint", "7"},
+ {Type.int64(), "integer", "7"},
+ {Type.int64(), "bigint", "7"},
+ {Type.bool(), "boolean", true},
+ {Type.float64(), "double precision", 1.5d},
+ {Type.numeric(), "numeric", "1.5"},
+ {Type.bytes(), "bytea", "AQI="},
+ {Type.pgBytea(), "integer", "AQI="},
+ {Type.bytes(), "text", "AQI="},
+ {Type.string(), "jsonb", "{}"},
+ {Type.float32(), "real", 1.5d},
+ {Type.timestamp(), "timestamp with time zone", "2024-01-01T00:00:00Z"},
+ };
+ for (Object[] column : columns) {
+ Type spannerType = (Type) column[0];
+ String pgType = (String) column[1];
+ ColumnBinding nonNullBinding = bind(spannerType, pgType, column[2]);
+ ColumnBinding nullBinding = nullBindingFor(spannerType, pgType);
+
+ assertWithMessage("isNullBinding for %s -> %s", spannerType, pgType)
+ .that(PostgreSQLDMLGenerator.isNullBinding(nullBinding))
+ .isTrue();
+ assertWithMessage("placeholder for %s -> %s", spannerType, pgType)
+ .that(nullBinding.getPlaceholderSql())
+ .isEqualTo(nonNullBinding.getPlaceholderSql());
+ // Untyped values (Types.OTHER) pair with an untyped NULL (Types.NULL): pgjdbc sends both
+ // without a parameter type.
+ int valueSqlType = nonNullBinding.getParams().get(0).getSqlType();
+ assertWithMessage("NULL parameter type for %s -> %s", spannerType, pgType)
+ .that(nullBinding.getParams().get(0).getSqlType())
+ .isEqualTo(valueSqlType == Types.OTHER ? Types.NULL : valueSqlType);
+ }
+ }
- JSONObject json = new JSONObject("{\"c\":\"YWJj\"}");
+ @Test
+ public void testReachableArrayTargetAndScalarArrayBindings() {
+ // Spanner STRING mapped to a PostgreSQL array column (reachable through AssignShardIdFn)
+ // forwards untyped text via Types.OTHER so PostgreSQL parses the array literal.
+ assertThat(bindValue(Type.string(), "text[]", "{\"a\",\"b\"}"))
+ .isEqualTo(PreparedStatementValue.ofUntypedString("{\"a\",\"b\"}"));
+ assertThat(bindValue(Type.string(), "timestamp without time zone[]", "{\"2023-05-18\"}"))
+ .isEqualTo(PreparedStatementValue.ofUntypedString("{\"2023-05-18\"}"));
+ assertThat(bindValue(Type.string(), "ARRAY", "{1,2}"))
+ .isEqualTo(PreparedStatementValue.ofUntypedString("{1,2}"));
+ assertThat(bindValue(Type.string(), "text[]", "{\"x\u0000y\"}"))
+ .isEqualTo(PreparedStatementValue.ofUntypedString("{\"xy\"}"));
+
+ // Scalar text target retains comma-joined string formatting for ARRAY.
+ assertThat(bindValue(Type.array(Type.string()), "text", new JSONArray(List.of("1", "2"))))
+ .isEqualTo(PreparedStatementValue.ofString("1,2"));
+ }
- String res =
- PostgreSQLDMLGenerator.getMappedColumnValue(spannerCol, sourceCol, json, "+00:00", null);
- assertTrue(res.contains("decode('YWJj', 'base64')"));
+ @Test
+ public void testBooleanAndCrossTypeSafety() {
+ assertThat(bindValue(Type.bool(), "boolean", true))
+ .isEqualTo(PreparedStatementValue.ofBoolean(true));
+ assertThat(bindValue(Type.pgBool(), "bool", false))
+ .isEqualTo(PreparedStatementValue.ofBoolean(false));
+ assertThat(bindValue(Type.string(), "boolean", "TRUE"))
+ .isEqualTo(PreparedStatementValue.ofBoolean(true));
+ assertThat(bindValue(Type.string(), "boolean", " false "))
+ .isEqualTo(PreparedStatementValue.ofBoolean(false));
+ assertThat(bindValue(Type.string(), "boolean", "1"))
+ .isEqualTo(PreparedStatementValue.ofUntypedString("1"));
+ assertThat(bindValue(Type.int64(), "boolean", "0"))
+ .isEqualTo(PreparedStatementValue.ofUntypedString("0"));
+
+ // Numeric target: BOOL or "true" must NEVER bind as OID BOOL.
+ assertThat(bindValue(Type.bool(), "integer", true))
+ .isEqualTo(PreparedStatementValue.ofUntypedString("true"));
+ assertThat(bindValue(Type.string(), "numeric", "false"))
+ .isEqualTo(PreparedStatementValue.ofUntypedString("false"));
+
+ // INT64 / PG_INT8 as both JSON numbers and JSON strings (how change streams emit INT64).
+ assertThat(bindValue(Type.int64(), "bigint", 42)).isEqualTo(PreparedStatementValue.ofLong(42L));
+ assertThat(bindValue(Type.pgInt8(), "integer", 99))
+ .isEqualTo(PreparedStatementValue.ofLong(99L));
+ assertThat(bindValue(Type.int64(), "real", 42))
+ .isEqualTo(PreparedStatementValue.ofUntypedString("42"));
+ assertThat(bindValue(Type.int64(), "double precision", 42))
+ .isEqualTo(PreparedStatementValue.ofDouble(42.0));
+ assertThat(bindValue(Type.int64(), "double precision", "42"))
+ .isEqualTo(PreparedStatementValue.ofDouble(42.0));
+ assertThat(bindValue(Type.int64(), "numeric", 42))
+ .isEqualTo(PreparedStatementValue.ofBigDecimal(BigDecimal.valueOf(42L)));
+ assertThat(bindValue(Type.int64(), "numeric", "42"))
+ .isEqualTo(PreparedStatementValue.ofBigDecimal(new BigDecimal("42")));
+
+ // INT64 strings at the edges: zero, negative zero into float8, beyond long range, non-numeric,
+ // and a JSON number too large for long (held by org.json as BigInteger).
+ assertThat(bindValue(Type.int64(), "bigint", "0")).isEqualTo(PreparedStatementValue.ofLong(0L));
+ assertThat(bindValue(Type.int64(), "double precision", "0"))
+ .isEqualTo(PreparedStatementValue.ofDouble(0.0d));
+ assertThat(bindValue(Type.int64(), "double precision", "-0"))
+ .isEqualTo(PreparedStatementValue.ofDouble(-0.0d));
+ assertThat(bindValue(Type.int64(), "bigint", "9223372036854775808"))
+ .isEqualTo(PreparedStatementValue.ofBigDecimal(new BigDecimal("9223372036854775808")));
+ assertThat(bindValue(Type.int64(), "bigint", "abc"))
+ .isEqualTo(PreparedStatementValue.ofUntypedString("abc"));
+ assertThat(bindValue(Type.int64(), "numeric", new BigInteger("9223372036854775808")))
+ .isEqualTo(PreparedStatementValue.ofBigDecimal(new BigDecimal("9223372036854775808")));
+ }
- // Test string escape
- Column spannerStrCol = mock(Column.class);
- when(spannerStrCol.name()).thenReturn("s");
- when(spannerStrCol.type()).thenReturn(Type.string());
+ @Test
+ public void numericBinding_integerTargets_bindLongOrBoundedDecimal() {
+ // Exact integers (including padded, decimal, scientific) bind as Long.
+ assertThat(bindValue(Type.string(), "integer", "42"))
+ .isEqualTo(PreparedStatementValue.ofLong(42L));
+ assertThat(bindValue(Type.string(), "integer", " 42 "))
+ .isEqualTo(PreparedStatementValue.ofLong(42L));
+ assertThat(bindValue(Type.string(), "integer", "1.00"))
+ .isEqualTo(PreparedStatementValue.ofLong(1L));
+ assertThat(bindValue(Type.string(), "integer", "1e2"))
+ .isEqualTo(PreparedStatementValue.ofLong(100L));
+ assertThat(bindValue(Type.string(), "integer", "1.5"))
+ .isEqualTo(PreparedStatementValue.ofBigDecimal(new BigDecimal("1.5")));
+ assertThat(bindValue(Type.string(), "integer", ".5"))
+ .isEqualTo(PreparedStatementValue.ofBigDecimal(new BigDecimal("0.5")));
+ assertThat(bindValue(Type.string(), "integer", "5."))
+ .isEqualTo(PreparedStatementValue.ofLong(5L));
+ assertThat(bindValue(Type.string(), "bigint", "9223372036854775807"))
+ .isEqualTo(PreparedStatementValue.ofLong(Long.MAX_VALUE));
+ // Beyond Long.MAX_VALUE binds as BigDecimal (within PG NUMERIC bounds) for PG range validation.
+ assertThat(bindValue(Type.string(), "bigint", "9223372036854775808"))
+ .isEqualTo(PreparedStatementValue.ofBigDecimal(new BigDecimal("9223372036854775808")));
+ assertThat(bindValue(Type.string(), "integer", ""))
+ .isEqualTo(PreparedStatementValue.ofUntypedString(""));
+ assertThat(bindValue(Type.string(), "integer", "+"))
+ .isEqualTo(PreparedStatementValue.ofUntypedString("+"));
+ }
- SourceColumn sourceStrCol = mock(SourceColumn.class);
- when(sourceStrCol.type()).thenReturn("text");
+ @Test
+ public void numericBinding_decimalTargets_respectPostgresBoundsAndLengthCap() {
+ // Scientific notation for numeric/decimal preserves exact BigDecimal precision.
+ assertThat(bindValue(Type.string(), "numeric", "1.234567890123456789E+10"))
+ .isEqualTo(PreparedStatementValue.ofBigDecimal(new BigDecimal("1.234567890123456789E+10")));
+ assertThat(bindValue(Type.string(), "numeric", "1E-500"))
+ .isEqualTo(PreparedStatementValue.ofBigDecimal(new BigDecimal("1E-500")));
+ // Exact PostgreSQL NUMERIC bounds (131072 integer digits, 16383 scale) and length cap (2048).
+ assertThat(bindValue(Type.string(), "numeric", "1E+131071"))
+ .isEqualTo(PreparedStatementValue.ofBigDecimal(new BigDecimal("1E+131071")));
+ assertThat(bindValue(Type.string(), "numeric", "1E+131072"))
+ .isEqualTo(PreparedStatementValue.ofUntypedString("1E+131072"));
+ assertThat(bindValue(Type.string(), "numeric", "1E-16383"))
+ .isEqualTo(PreparedStatementValue.ofBigDecimal(new BigDecimal("1E-16383")));
+ assertThat(bindValue(Type.string(), "numeric", "1E-16384"))
+ .isEqualTo(PreparedStatementValue.ofUntypedString("1E-16384"));
+ String maxCapDigits = "9".repeat(2048);
+ assertThat(bindValue(Type.string(), "numeric", maxCapDigits))
+ .isEqualTo(PreparedStatementValue.ofBigDecimal(new BigDecimal(maxCapDigits)));
+ String overCapDigits = "9".repeat(2049);
+ assertThat(bindValue(Type.string(), "numeric", overCapDigits))
+ .isEqualTo(PreparedStatementValue.ofUntypedString(overCapDigits));
+ assertThat(bindValue(Type.pgNumeric(), "numeric", overCapDigits))
+ .isEqualTo(PreparedStatementValue.ofUntypedString(overCapDigits));
+ assertThat(bindValue(Type.float32(), "real", overCapDigits))
+ .isEqualTo(PreparedStatementValue.ofUntypedString(overCapDigits));
+ }
- JSONObject jsonStr = new JSONObject("{\"s\":\"it\\'s a string\"}");
+ @Test
+ public void numericBinding_extremeExponentsAndFloatInputs_handledSafely() {
+ // 32-bit int overflow guard in BigDecimal bounds check (precision - scale computed in long).
+ assertThat(bindValue(Type.string(), "numeric", "1e2147483647"))
+ .isEqualTo(PreparedStatementValue.ofUntypedString("1e2147483647"));
+ assertThat(bindValue(Type.string(), "integer", "1e2147483647"))
+ .isEqualTo(PreparedStatementValue.ofUntypedString("1e2147483647"));
+ assertThat(bindValue(Type.string(), "double precision", "1e2147483647"))
+ .isEqualTo(PreparedStatementValue.ofUntypedString("1e2147483647"));
+ assertThat(bindValue(Type.pgNumeric(), "numeric", "1e2147483647"))
+ .isEqualTo(PreparedStatementValue.ofUntypedString("1e2147483647"));
+ assertThat(bindValue(Type.string(), "numeric", "1e-2147483647"))
+ .isEqualTo(PreparedStatementValue.ofUntypedString("1e-2147483647"));
+
+ // Exponents exceeding 32-bit int overflow BigDecimal(String) and fall back untyped.
+ for (String targetType : new String[] {"numeric", "double precision", "integer"}) {
+ assertWithMessage("positive exponent overflow for %s", targetType)
+ .that(bindValue(Type.string(), targetType, "1e9999999999"))
+ .isEqualTo(PreparedStatementValue.ofUntypedString("1e9999999999"));
+ assertWithMessage("negative exponent overflow for %s", targetType)
+ .that(bindValue(Type.string(), targetType, "1e-2147483648"))
+ .isEqualTo(PreparedStatementValue.ofUntypedString("1e-2147483648"));
+ }
+ InvalidDMLGenerationException pgNumericExtremeEx =
+ assertThrows(
+ InvalidDMLGenerationException.class,
+ () -> bind(Type.pgNumeric(), "numeric", "1e9999999999"));
+ assertThat(pgNumericExtremeEx).hasMessageThat().doesNotContain("1e9999999999");
+
+ // Programmatic Double/Float targeting numeric avoids new BigDecimal(double) binary expansion.
+ assertThat(bindValue(Type.float64(), "numeric", 52.67d))
+ .isEqualTo(PreparedStatementValue.ofBigDecimal(new BigDecimal("52.67")));
+ assertThat(bindValue(Type.float32(), "numeric", 1.1f))
+ .isEqualTo(PreparedStatementValue.ofBigDecimal(new BigDecimal("1.1")));
+ }
- String resStr =
- PostgreSQLDMLGenerator.getMappedColumnValue(
- spannerStrCol, sourceStrCol, jsonStr, "+00:00", null);
- assertEquals("'it''s a string'", resStr);
+ @Test
+ public void numericTextBinding_jsonNumericPrimitives_preservePlainOrBoundedString() {
+ // Non-String JSON numeric primitives targeting text/untyped columns.
+ assertThat(bindValue(Type.pgNumeric(), "text", 1.50d))
+ .isEqualTo(PreparedStatementValue.ofString("1.5"));
+ assertThat(bindValue(Type.pgNumeric(), "text", 2.0f))
+ .isEqualTo(PreparedStatementValue.ofString("2"));
+ assertThat(bindValue(Type.pgNumeric(), "text", new BigDecimal("0.0000001")))
+ .isEqualTo(PreparedStatementValue.ofString("0.0000001"));
+ // Out-of-bounds BigDecimal uses toString() instead of toPlainString() to avoid OOM.
+ assertThat(bindValue(Type.pgNumeric(), "text", new BigDecimal("1E+200000")))
+ .isEqualTo(PreparedStatementValue.ofString("1E+200000"));
+ assertThat(bindValue(Type.float64(), "text", new BigDecimal("12.34")))
+ .isEqualTo(PreparedStatementValue.ofString("12.34"));
}
@Test
- public void testByteaTypeDML() throws Exception {
+ public void floatBinding_liveJsonNegativeZero_preservesSignBit() {
+ // Live JSON -0.0 (parsed by org.json as Double -0.0d) preserves its sign bit for float8.
Column spannerCol = mock(Column.class);
- when(spannerCol.name()).thenReturn("bytea_column");
- when(spannerCol.type()).thenReturn(Type.bytes());
+ when(spannerCol.name()).thenReturn("test_col");
+ when(spannerCol.type()).thenReturn(Type.float64());
+ ColumnBinding negZeroBinding =
+ PostgreSQLDMLGenerator.getMappedColumnBinding(
+ spannerCol,
+ srcCol("test_col", "double precision"),
+ new JSONObject("{\"test_col\": -0.0}"));
+ PreparedStatementValue negZeroParam = negZeroBinding.getParams().get(0);
+ assertThat(negZeroParam.getSqlType()).isEqualTo(Types.DOUBLE);
+ assertThat(Double.doubleToRawLongBits((Double) negZeroParam.getValue()))
+ .isEqualTo(Double.doubleToRawLongBits(-0.0d));
+
+ // Live JSON -0.0 also preserves its sign bit for real (float4) via untyped string binding.
+ for (Type float4SpannerType : new Type[] {Type.float32(), Type.pgFloat4()}) {
+ Column float4Col = mock(Column.class);
+ when(float4Col.name()).thenReturn("test_col");
+ when(float4Col.type()).thenReturn(float4SpannerType);
+ ColumnBinding negZeroReal =
+ PostgreSQLDMLGenerator.getMappedColumnBinding(
+ float4Col, srcCol("test_col", "real"), new JSONObject("{\"test_col\": -0.0}"));
+ assertWithMessage("placeholder for %s", float4SpannerType)
+ .that(negZeroReal.getPlaceholderSql())
+ .isEqualTo("?");
+ assertWithMessage("params for %s", float4SpannerType)
+ .that(negZeroReal.getParams())
+ .containsExactly(PreparedStatementValue.ofUntypedString("-0.0"));
+ }
+ }
- SourceColumn sourceCol = mock(SourceColumn.class);
- when(sourceCol.name()).thenReturn("bytea_column");
- when(sourceCol.type()).thenReturn("bytea");
+ @Test
+ public void floatBinding_realColumn_alwaysBindsUntyped() {
+ // real (float4) always binds untyped (Types.OTHER) so PostgreSQL resolves float4 regardless of
+ // pgjdbc binaryTransfer mode (avoiding float4 vs float8 mismatch on DELETE).
+ assertThat(bindValue(Type.float32(), "real", 1.1))
+ .isEqualTo(PreparedStatementValue.ofUntypedString("1.1"));
+ assertThat(bindValue(Type.string(), "real", "1e39"))
+ .isEqualTo(PreparedStatementValue.ofUntypedString("1e39"));
+ assertThat(bindValue(Type.string(), "real", "1e-50"))
+ .isEqualTo(PreparedStatementValue.ofUntypedString("1e-50"));
+ assertThat(bindValue(Type.float32(), "real", "NaN"))
+ .isEqualTo(PreparedStatementValue.ofUntypedString("NaN"));
+ assertThat(bindValue(Type.pgFloat4(), "real", "Infinity"))
+ .isEqualTo(PreparedStatementValue.ofUntypedString("Infinity"));
+ assertThat(bindValue(Type.float32(), "real", "-Infinity"))
+ .isEqualTo(PreparedStatementValue.ofUntypedString("-Infinity"));
+ }
- JSONObject json = new JSONObject("{\"bytea_column\":\"SGVsbG8=\"}"); // "Hello" in base64
+ @Test
+ public void floatBinding_doublePrecision_handlesRangeAndOverflowUnderflow() {
+ // double precision (float8) binds finite in-range values as Double; overflow/underflow fall
+ // back to untyped binding so PostgreSQL validates the range instead of silent corruption.
+ assertThat(bindValue(Type.string(), "double precision", "1.7976931348623157E308"))
+ .isEqualTo(PreparedStatementValue.ofDouble(Double.MAX_VALUE));
+ assertThat(bindValue(Type.string(), "double precision", "0.0e-400"))
+ .isEqualTo(PreparedStatementValue.ofDouble(0.0d));
+ assertThat(bindValue(Type.string(), "double precision", "1E+500"))
+ .isEqualTo(PreparedStatementValue.ofUntypedString("1E+500"));
+ assertThat(bindValue(Type.string(), "double precision", "1e-400"))
+ .isEqualTo(PreparedStatementValue.ofUntypedString("1e-400"));
+ assertThat(bindValue(Type.pgNumeric(), "double precision", "1E+500"))
+ .isEqualTo(PreparedStatementValue.ofUntypedString("1E+500"));
+ assertThat(bindValue(Type.pgNumeric(), "double precision", "1E-500"))
+ .isEqualTo(PreparedStatementValue.ofUntypedString("1E-500"));
+
+ // The pipeline parses change-stream JSON from text, where org.json holds a finite decimal as
+ // BigDecimal, not as the Double that put(col, 1.1d) stores.
+ Object parsedDecimal = new JSONObject("{\"v\": 1.1}").get("v");
+ assertThat(parsedDecimal).isInstanceOf(BigDecimal.class);
+ assertThat(bindValue(Type.float64(), "double precision", parsedDecimal))
+ .isEqualTo(PreparedStatementValue.ofDouble(1.1d));
+ assertThat(bindValue(Type.float64(), "numeric", parsedDecimal))
+ .isEqualTo(PreparedStatementValue.ofBigDecimal(new BigDecimal("1.1")));
+ }
- String res =
- PostgreSQLDMLGenerator.getMappedColumnValue(spannerCol, sourceCol, json, "+00:00", null);
- assertEquals("'\\x48656c6c6f'", res); // "Hello" in hex is 48656c6c6f
+ @Test
+ public void floatBinding_nonFiniteValues_dispatchedByTargetType() {
+ assertThat(bindValue(Type.float64(), "double precision", "NaN"))
+ .isEqualTo(PreparedStatementValue.ofDouble(Double.NaN));
+ assertThat(bindValue(Type.float64(), "double precision", "Infinity"))
+ .isEqualTo(PreparedStatementValue.ofDouble(Double.POSITIVE_INFINITY));
+ assertThat(bindValue(Type.float64(), "double precision", "+Infinity"))
+ .isEqualTo(PreparedStatementValue.ofDouble(Double.POSITIVE_INFINITY));
+ assertThat(bindValue(Type.float64(), "double precision", "-Infinity"))
+ .isEqualTo(PreparedStatementValue.ofDouble(Double.NEGATIVE_INFINITY));
+ assertThat(bindValue(Type.pgNumeric(), "numeric", "NaN"))
+ .isEqualTo(PreparedStatementValue.ofUntypedString("NaN"));
+ assertThat(bindValue(Type.pgNumeric(), "numeric", "Infinity"))
+ .isEqualTo(PreparedStatementValue.ofUntypedString("Infinity"));
+ assertThat(bindValue(Type.float64(), "numeric", "-Infinity"))
+ .isEqualTo(PreparedStatementValue.ofUntypedString("-Infinity"));
+ assertThat(bindValue(Type.float64(), "integer", "NaN"))
+ .isEqualTo(PreparedStatementValue.ofUntypedString("NaN"));
+ assertThat(bindValue(Type.float64(), "integer", "+Infinity"))
+ .isEqualTo(PreparedStatementValue.ofUntypedString("+Infinity"));
+ assertThat(bindValue(Type.float64(), "integer", "-Infinity"))
+ .isEqualTo(PreparedStatementValue.ofUntypedString("-Infinity"));
+ assertThat(bindValue(Type.float64(), "text", "NaN"))
+ .isEqualTo(PreparedStatementValue.ofString("NaN"));
+ assertThat(bindValue(Type.float64(), "text", "Infinity"))
+ .isEqualTo(PreparedStatementValue.ofString("Infinity"));
+ assertThat(bindValue(Type.float64(), "text", "-Infinity"))
+ .isEqualTo(PreparedStatementValue.ofString("-Infinity"));
+
+ // Spanner STRING columns and custom transformation strings take the text path.
+ assertThat(bindValue(Type.string(), "double precision", "NaN"))
+ .isEqualTo(PreparedStatementValue.ofDouble(Double.NaN));
+ assertThat(bindValue(Type.string(), "numeric", " -Infinity "))
+ .isEqualTo(PreparedStatementValue.ofUntypedString("-Infinity"));
+ assertThat(customValue("double precision", "infinity"))
+ .isEqualTo(PreparedStatementValue.ofDouble(Double.POSITIVE_INFINITY));
+ assertThat(customValue("integer", "NaN"))
+ .isEqualTo(PreparedStatementValue.ofUntypedString("NaN"));
+ // Only ASCII spellings are non-finite literals; a dotless i (U+0131) is ordinary text.
+ assertThat(bindValue(Type.string(), "double precision", "\u0131nf\u0131n\u0131ty"))
+ .isEqualTo(PreparedStatementValue.ofUntypedString("\u0131nf\u0131n\u0131ty"));
}
@Test
- public void testUuidTypeDML() throws Exception {
- Column spannerCol = mock(Column.class);
- when(spannerCol.name()).thenReturn("uuid_column");
- when(spannerCol.type()).thenReturn(Type.string());
+ public void testStringEncodedNegativeZeroForDoublePrecision() {
+ long negZeroBits = Double.doubleToRawLongBits(-0.0d);
+ long posZeroBits = Double.doubleToRawLongBits(0.0d);
+
+ // Spanner STRING negative zero literals preserve the IEEE 754 -0.0d sign bit on float8.
+ for (String negZeroText : new String[] {"-0.0", "-0", "-0.00", "-0e5", " -0.0 ", "-0.0e-400"}) {
+ PreparedStatementValue param = bindValue(Type.string(), "double precision", negZeroText);
+ assertWithMessage("Spanner STRING '%s'", negZeroText)
+ .that(param)
+ .isEqualTo(PreparedStatementValue.ofDouble(-0.0d));
+ assertWithMessage("Spanner STRING '%s' rawBits", negZeroText)
+ .that(Double.doubleToRawLongBits((Double) param.getValue()))
+ .isEqualTo(negZeroBits);
+ }
+
+ // JSON-string-encoded "-0.0" across FLOAT64, PG_FLOAT8, and PG_NUMERIC also preserves -0.0d.
+ for (Type spannerType : new Type[] {Type.float64(), Type.pgFloat8(), Type.pgNumeric()}) {
+ PreparedStatementValue param = bindValue(spannerType, "double precision", "-0.0");
+ assertWithMessage("Spanner %s '-0.0'", spannerType)
+ .that(param)
+ .isEqualTo(PreparedStatementValue.ofDouble(-0.0d));
+ assertWithMessage("Spanner %s '-0.0' rawBits", spannerType)
+ .that(Double.doubleToRawLongBits((Double) param.getValue()))
+ .isEqualTo(negZeroBits);
+ }
+
+ // Custom transformation returning string "-0.0" preserves -0.0d on double precision.
+ for (String negZeroText : new String[] {"-0.0", " -0.0 "}) {
+ PreparedStatementValue customParam = customValue("double precision", negZeroText);
+ assertWithMessage("Custom string '%s'", negZeroText)
+ .that(customParam)
+ .isEqualTo(PreparedStatementValue.ofDouble(-0.0d));
+ assertWithMessage("Custom string '%s' rawBits", negZeroText)
+ .that(Double.doubleToRawLongBits((Double) customParam.getValue()))
+ .isEqualTo(negZeroBits);
+ }
+
+ // Positive zero strings keep +0.0d (rawBits == 0L).
+ for (String posZeroText : new String[] {"0.0", "+0.0"}) {
+ PreparedStatementValue param = bindValue(Type.string(), "double precision", posZeroText);
+ assertWithMessage("Spanner STRING '%s'", posZeroText)
+ .that(param)
+ .isEqualTo(PreparedStatementValue.ofDouble(0.0d));
+ assertWithMessage("Spanner STRING '%s' rawBits", posZeroText)
+ .that(Double.doubleToRawLongBits((Double) param.getValue()))
+ .isEqualTo(posZeroBits);
+ }
+ PreparedStatementValue float64PosZero = bindValue(Type.float64(), "double precision", "0.0");
+ assertThat(float64PosZero).isEqualTo(PreparedStatementValue.ofDouble(0.0d));
+ assertThat(Double.doubleToRawLongBits((Double) float64PosZero.getValue()))
+ .isEqualTo(posZeroBits);
+
+ // Non-zero negative subnormal underflow ("-1e-400") still falls back to untyped binding.
+ assertThat(bindValue(Type.string(), "double precision", "-1e-400"))
+ .isEqualTo(PreparedStatementValue.ofUntypedString("-1e-400"));
+ assertThat(bindValue(Type.pgNumeric(), "double precision", "-1e-400"))
+ .isEqualTo(PreparedStatementValue.ofUntypedString("-1e-400"));
+ assertThat(customValue("double precision", "-1e-400"))
+ .isEqualTo(PreparedStatementValue.ofUntypedString("-1e-400"));
+ }
- SourceColumn sourceCol = mock(SourceColumn.class);
- when(sourceCol.name()).thenReturn("uuid_column");
- when(sourceCol.type()).thenReturn("uuid");
+ @Test
+ public void customBinding_characterTarget_alwaysBindsVarchar() {
+ assertThat(customValue("text", "kk ll")).isEqualTo(PreparedStatementValue.ofString("kk ll"));
+ assertThat(customValue("varchar", "'quoted'"))
+ .isEqualTo(PreparedStatementValue.ofString("'quoted'"));
+ assertThat(customValue("text", 42)).isEqualTo(PreparedStatementValue.ofString("42"));
+ assertThat(customValue("text", Boolean.TRUE))
+ .isEqualTo(PreparedStatementValue.ofString("true"));
+ assertThat(customValue("text", 3.14)).isEqualTo(PreparedStatementValue.ofString("3.14"));
+ assertThat(customValue("text", Double.NaN)).isEqualTo(PreparedStatementValue.ofString("NaN"));
+ assertThat(customValue("text", "abc".getBytes(StandardCharsets.UTF_8)))
+ .isEqualTo(PreparedStatementValue.ofString("\\x616263"));
+ }
- JSONObject json = new JSONObject("{\"uuid_column\":\"123e4567-e89b-12d3-a456-426614174000\"}");
+ @Test
+ public void customBinding_numericTargets_dispatchByPostgresType() {
+ assertThat(customValue("integer", "42")).isEqualTo(PreparedStatementValue.ofLong(42L));
+ assertThat(customValue("bigint", 7L)).isEqualTo(PreparedStatementValue.ofLong(7L));
+ assertThat(customValue("smallint", (short) 5)).isEqualTo(PreparedStatementValue.ofLong(5L));
+ assertThat(customValue("smallint", (byte) 3)).isEqualTo(PreparedStatementValue.ofLong(3L));
+ assertThat(customValue("numeric", 7L))
+ .isEqualTo(PreparedStatementValue.ofBigDecimal(BigDecimal.valueOf(7L)));
+ assertThat(customValue("numeric", "1.234567890123456789E+10"))
+ .isEqualTo(PreparedStatementValue.ofBigDecimal(new BigDecimal("1.234567890123456789E+10")));
+ assertThat(customValue("numeric", 1.1f))
+ .isEqualTo(PreparedStatementValue.ofBigDecimal(new BigDecimal("1.1")));
+ assertThat(customValue("integer", 5.0d)).isEqualTo(PreparedStatementValue.ofLong(5L));
+ assertThat(customValue("numeric", new BigInteger("12345678901234567890")))
+ .isEqualTo(PreparedStatementValue.ofBigDecimal(new BigDecimal("12345678901234567890")));
+ assertThat(customValue("numeric", new BigDecimal("1E+200000")))
+ .isEqualTo(PreparedStatementValue.ofUntypedString("1E+200000"));
+ assertThat(customValue("double precision", new BigDecimal("1E+500")))
+ .isEqualTo(PreparedStatementValue.ofUntypedString("1E+500"));
+ assertThat(customValue("double precision", new BigDecimal("1E-500")))
+ .isEqualTo(PreparedStatementValue.ofUntypedString("1E-500"));
+ assertThat(customValue("integer", new BigDecimal("1.5")))
+ .isEqualTo(PreparedStatementValue.ofBigDecimal(new BigDecimal("1.5")));
+ assertThat(customValue("real", 1.1f)).isEqualTo(PreparedStatementValue.ofUntypedString("1.1"));
+ assertThat(customValue("real", Double.NaN))
+ .isEqualTo(PreparedStatementValue.ofUntypedString("NaN"));
+ assertThat(customValue("double precision", 1.1f))
+ .isEqualTo(PreparedStatementValue.ofDouble(1.1));
+ assertThat(customValue("double precision", Double.NaN))
+ .isEqualTo(PreparedStatementValue.ofDouble(Double.NaN));
+ assertThat(customValue("double precision", Float.NaN))
+ .isEqualTo(PreparedStatementValue.ofDouble(Double.NaN));
+ assertThat(customValue("double precision", Float.POSITIVE_INFINITY))
+ .isEqualTo(PreparedStatementValue.ofDouble(Double.POSITIVE_INFINITY));
+ assertThat(customValue("double precision", Double.NEGATIVE_INFINITY))
+ .isEqualTo(PreparedStatementValue.ofDouble(Double.NEGATIVE_INFINITY));
+ assertThat(customValue("numeric", Double.POSITIVE_INFINITY))
+ .isEqualTo(PreparedStatementValue.ofUntypedString("Infinity"));
+ assertThat(customValue("integer", Boolean.TRUE))
+ .isEqualTo(PreparedStatementValue.ofUntypedString("true"));
+ }
- String res =
- PostgreSQLDMLGenerator.getMappedColumnValue(spannerCol, sourceCol, json, "+00:00", null);
- assertEquals("'123e4567-e89b-12d3-a456-426614174000'", res);
+ @Test
+ public void customBinding_booleanAndStructuredTargets_dispatchByPostgresType() {
+ assertThat(customValue("boolean", Boolean.TRUE))
+ .isEqualTo(PreparedStatementValue.ofBoolean(true));
+ assertThat(customValue("boolean", "true")).isEqualTo(PreparedStatementValue.ofBoolean(true));
+ assertThat(customValue("boolean", "FALSE")).isEqualTo(PreparedStatementValue.ofBoolean(false));
+ assertThat(customValue("boolean", 1)).isEqualTo(PreparedStatementValue.ofUntypedString("1"));
+
+ assertThat(customValue("jsonb", "{\"k\":1}"))
+ .isEqualTo(PreparedStatementValue.ofUntypedString("{\"k\":1}"));
+ assertThat(customValue("jsonb", 42)).isEqualTo(PreparedStatementValue.ofUntypedString("42"));
+ UUID uuid = UUID.fromString("123e4567-e89b-12d3-a456-426614174000");
+ assertThat(customValue("uuid", uuid))
+ .isEqualTo(PreparedStatementValue.ofUntypedString("123e4567-e89b-12d3-a456-426614174000"));
+ byte[] bytes = "raw".getBytes(StandardCharsets.UTF_8);
+ assertThat(customValue("bytea", bytes)).isEqualTo(PreparedStatementValue.ofBytes(bytes));
+ assertThat(customValue("integer", bytes)).isEqualTo(PreparedStatementValue.ofBytes(bytes));
+ assertThat(customValue("boolean", bytes)).isEqualTo(PreparedStatementValue.ofBytes(bytes));
+ // Non-string objects (such as List or java.sql.Timestamp) fall back to untyped toString().
+ assertThat(customValue("text[]", List.of("a", "b")))
+ .isEqualTo(PreparedStatementValue.ofUntypedString("[a, b]"));
+ Timestamp sqlTs = Timestamp.valueOf("2024-01-01 10:00:00");
+ assertThat(customValue("timestamp with time zone", sqlTs))
+ .isEqualTo(PreparedStatementValue.ofUntypedString("2024-01-01 10:00:00.0"));
}
@Test
- public void testJsonbTypeDML() throws Exception {
- Column spannerCol = mock(Column.class);
- when(spannerCol.name()).thenReturn("jsonb_column");
- when(spannerCol.type()).thenReturn(Type.string());
+ public void customBinding_nullAndTimestampTargets_usePlainPlaceholder() {
+ // Custom nulls are typed like the non-null values of the column category.
+ assertThat(customValue("integer", null))
+ .isEqualTo(PreparedStatementValue.nullValue(Types.BIGINT));
+ assertThat(customValue("integer", JSONObject.NULL))
+ .isEqualTo(PreparedStatementValue.nullValue(Types.BIGINT));
+ assertThat(customValue("text", JSONObject.NULL))
+ .isEqualTo(PreparedStatementValue.nullValue(Types.VARCHAR));
+ assertThat(customValue("boolean", null))
+ .isEqualTo(PreparedStatementValue.nullValue(Types.BOOLEAN));
+ assertThat(customValue("double precision", null))
+ .isEqualTo(PreparedStatementValue.nullValue(Types.DOUBLE));
+ assertThat(customValue("numeric", null))
+ .isEqualTo(PreparedStatementValue.nullValue(Types.DECIMAL));
+ assertThat(customValue("jsonb", null)).isEqualTo(PreparedStatementValue.nullValue(Types.NULL));
+
+ // Custom timestamp string uses plain '?' (no forced ::timestamptz cast).
+ ColumnBinding tsBinding =
+ PostgreSQLDMLGenerator.getCustomValueBinding(
+ srcCol("ts", "timestamp with time zone"), "2024-01-01 10:00:00");
+ assertThat(tsBinding.getPlaceholderSql()).isEqualTo("?");
+ assertThat(tsBinding.getParams())
+ .containsExactly(PreparedStatementValue.ofUntypedString("2024-01-01 10:00:00"));
+
+ // Custom null and JSONObject.NULL on timestamp also use plain '?' placeholder.
+ ColumnBinding nullTsBinding =
+ PostgreSQLDMLGenerator.getCustomValueBinding(
+ srcCol("ts", "timestamp with time zone"), null);
+ assertThat(nullTsBinding.getPlaceholderSql()).isEqualTo("?");
+ assertThat(PostgreSQLDMLGenerator.isNullBinding(nullTsBinding)).isTrue();
+ assertThat(nullTsBinding.getParams())
+ .containsExactly(PreparedStatementValue.nullValue(Types.NULL));
+
+ ColumnBinding jsonNullTsBinding =
+ PostgreSQLDMLGenerator.getCustomValueBinding(
+ srcCol("ts", "timestamp with time zone"), JSONObject.NULL);
+ assertThat(jsonNullTsBinding.getPlaceholderSql()).isEqualTo("?");
+ assertThat(PostgreSQLDMLGenerator.isNullBinding(jsonNullTsBinding)).isTrue();
+ assertThat(jsonNullTsBinding.getParams())
+ .containsExactly(PreparedStatementValue.nullValue(Types.NULL));
+ }
- SourceColumn sourceCol = mock(SourceColumn.class);
- when(sourceCol.name()).thenReturn("jsonb_column");
- when(sourceCol.type()).thenReturn("jsonb");
+ @Test
+ public void testCustomTransformationEndToEndIncludingNull() {
+ String sessionFile = "src/test/resources/customTransformation.json";
+ Ddl ddl = SchemaUtils.buildSpannerDdlFromSessionFile(sessionFile);
+ SourceSchema sourceSchema = SchemaUtils.buildSourceSchemaFromSessionFile(sessionFile);
+ ISchemaMapper schemaMapper = new SessionBasedMapper(sessionFile, ddl);
- JSONObject json = new JSONObject("{\"jsonb_column\":\"{\\\"a\\\": 1}\"}");
+ Map customTransformation = new HashMap<>();
+ customTransformation.put("FullName", "kk ll");
+ customTransformation.put("SingerId", "1");
- String res =
- PostgreSQLDMLGenerator.getMappedColumnValue(spannerCol, sourceCol, json, "+00:00", null);
- assertEquals("'{\"a\": 1}'", res);
+ DMLGeneratorResponse response =
+ new PostgreSQLDMLGenerator()
+ .getDMLStatement(
+ new DMLGeneratorRequest.Builder(
+ "INSERT",
+ "Singers",
+ new JSONObject().put("FirstName", "kk").put("LastName", "ll"),
+ new JSONObject().put("SingerId", "999"),
+ "+00:00")
+ .setSchemaMapper(schemaMapper)
+ .setDdl(ddl)
+ .setSourceSchema(sourceSchema)
+ .setCustomTransformationResponse(customTransformation)
+ .build());
+ assertThat(response.getDmlStatement())
+ .isEqualTo(
+ "INSERT INTO \"Singers\" (\"FullName\",\"SingerId\") VALUES (?,?)"
+ + " ON CONFLICT (\"SingerId\") DO UPDATE SET \"FullName\" = EXCLUDED.\"FullName\"");
+ assertParams(
+ response.getPreparedStatementParameters(),
+ PreparedStatementValue.ofString("kk ll"),
+ PreparedStatementValue.ofLong(1L));
+
+ // Null custom transformation output binds as NULL without throwing NPE.
+ Map nullCustom = new HashMap<>();
+ nullCustom.put("FullName", null);
+ DMLGeneratorResponse nullResponse =
+ new PostgreSQLDMLGenerator()
+ .getDMLStatement(
+ new DMLGeneratorRequest.Builder(
+ "INSERT",
+ "Singers",
+ new JSONObject().put("FirstName", "kk").put("LastName", "ll"),
+ new JSONObject().put("SingerId", "999"),
+ "+00:00")
+ .setSchemaMapper(schemaMapper)
+ .setDdl(ddl)
+ .setSourceSchema(sourceSchema)
+ .setCustomTransformationResponse(nullCustom)
+ .build());
+ assertThat(nullResponse.getDmlStatement())
+ .isEqualTo(
+ "INSERT INTO \"Singers\" (\"FullName\",\"SingerId\") VALUES (?,?)"
+ + " ON CONFLICT (\"SingerId\") DO UPDATE SET \"FullName\" = EXCLUDED.\"FullName\"");
+ assertParams(
+ nullResponse.getPreparedStatementParameters(),
+ PreparedStatementValue.nullValue(Types.VARCHAR),
+ PreparedStatementValue.ofLong(999L));
+
+ // JSONObject.NULL custom transformation output also binds as SQL NULL end-to-end.
+ Map jsonNullCustom = new HashMap<>();
+ jsonNullCustom.put("FullName", JSONObject.NULL);
+ DMLGeneratorResponse jsonNullResponse =
+ new PostgreSQLDMLGenerator()
+ .getDMLStatement(
+ new DMLGeneratorRequest.Builder(
+ "INSERT",
+ "Singers",
+ new JSONObject().put("FirstName", "kk").put("LastName", "ll"),
+ new JSONObject().put("SingerId", "999"),
+ "+00:00")
+ .setSchemaMapper(schemaMapper)
+ .setDdl(ddl)
+ .setSourceSchema(sourceSchema)
+ .setCustomTransformationResponse(jsonNullCustom)
+ .build());
+ assertThat(jsonNullResponse.getDmlStatement())
+ .isEqualTo(
+ "INSERT INTO \"Singers\" (\"FullName\",\"SingerId\") VALUES (?,?)"
+ + " ON CONFLICT (\"SingerId\") DO UPDATE SET \"FullName\" = EXCLUDED.\"FullName\"");
+ assertParams(
+ jsonNullResponse.getPreparedStatementParameters(),
+ PreparedStatementValue.nullValue(Types.VARCHAR),
+ PreparedStatementValue.ofLong(999L));
+ }
+
+ @Test
+ public void testSymmetricalInsertAndDeleteAcrossPgPkTypes() {
+ Ddl ddl =
+ Ddl.builder()
+ .createTable("TypedPk")
+ .column("real_pk")
+ .float32()
+ .endColumn()
+ .column("dbl_pk")
+ .float64()
+ .endColumn()
+ .column("num_pk")
+ .numeric()
+ .endColumn()
+ .column("uuid_pk")
+ .uuid()
+ .endColumn()
+ .column("date_pk")
+ .date()
+ .endColumn()
+ .column("ts_pk")
+ .timestamp()
+ .endColumn()
+ .column("bytea_pk")
+ .bytes()
+ .max()
+ .endColumn()
+ .column("bool_pk")
+ .bool()
+ .endColumn()
+ .column("int_pk")
+ .string()
+ .max()
+ .endColumn()
+ .column("text_pk")
+ .string()
+ .max()
+ .endColumn()
+ .column("char_pk")
+ .string()
+ .size(10)
+ .endColumn()
+ .column("bytes_text_pk")
+ .bytes()
+ .max()
+ .endColumn()
+ .column("enum_pk")
+ .string()
+ .max()
+ .endColumn()
+ .column("jsonb_pk")
+ .json()
+ .endColumn()
+ .column("time_pk")
+ .string()
+ .max()
+ .endColumn()
+ .primaryKey()
+ .asc("real_pk")
+ .asc("dbl_pk")
+ .asc("num_pk")
+ .asc("uuid_pk")
+ .asc("date_pk")
+ .asc("ts_pk")
+ .asc("bytea_pk")
+ .asc("bool_pk")
+ .asc("int_pk")
+ .asc("text_pk")
+ .asc("char_pk")
+ .asc("bytes_text_pk")
+ .asc("enum_pk")
+ .asc("jsonb_pk")
+ .asc("time_pk")
+ .end()
+ .endTable()
+ .build();
+ SourceTable sourceTable =
+ SourceTable.builder(SourceDatabaseType.POSTGRESQL)
+ .name("TypedPk")
+ .columns(
+ ImmutableList.of(
+ srcCol("real_pk", "real"),
+ srcCol("dbl_pk", "double precision"),
+ srcCol("num_pk", "numeric"),
+ srcCol("uuid_pk", "uuid"),
+ srcCol("date_pk", "date"),
+ srcCol("ts_pk", "timestamp with time zone"),
+ srcCol("bytea_pk", "bytea"),
+ srcCol("bool_pk", "boolean"),
+ srcCol("int_pk", "integer"),
+ srcCol("text_pk", "text"),
+ srcCol("char_pk", "character"),
+ srcCol("bytes_text_pk", "text"),
+ srcCol("enum_pk", "USER-DEFINED"),
+ srcCol("jsonb_pk", "jsonb"),
+ srcCol("time_pk", "time without time zone")))
+ .primaryKeyColumns(
+ ImmutableList.of(
+ "real_pk",
+ "dbl_pk",
+ "num_pk",
+ "uuid_pk",
+ "date_pk",
+ "ts_pk",
+ "bytea_pk",
+ "bool_pk",
+ "int_pk",
+ "text_pk",
+ "char_pk",
+ "bytes_text_pk",
+ "enum_pk",
+ "jsonb_pk",
+ "time_pk"))
+ .build();
+ SourceSchema sourceSchema =
+ SourceSchema.builder(SourceDatabaseType.POSTGRESQL)
+ .databaseName("testdb")
+ .tables(ImmutableMap.of("TypedPk", sourceTable))
+ .build();
+ ISchemaMapper mapper =
+ identityMapper(
+ "TypedPk",
+ "real_pk",
+ "dbl_pk",
+ "num_pk",
+ "uuid_pk",
+ "date_pk",
+ "ts_pk",
+ "bytea_pk",
+ "bool_pk",
+ "int_pk",
+ "text_pk",
+ "char_pk",
+ "bytes_text_pk",
+ "enum_pk",
+ "jsonb_pk",
+ "time_pk");
+
+ JSONObject keys =
+ new JSONObject()
+ .put("real_pk", 1.1)
+ .put("dbl_pk", 2.2)
+ .put("num_pk", "3.3")
+ .put("uuid_pk", "123e4567-e89b-12d3-a456-426614174000")
+ .put("date_pk", "2024-01-02")
+ .put("ts_pk", "2024-01-02T03:04:05Z")
+ .put("bytea_pk", "YWJj")
+ .put("bool_pk", true)
+ .put("int_pk", "42")
+ .put("text_pk", "ignored")
+ .put("char_pk", "abc ")
+ .put("bytes_text_pk", "YWJj")
+ .put("enum_pk", "active")
+ .put("jsonb_pk", "{\"k\":1}")
+ .put("time_pk", "10:10:10");
+ Map custom = new HashMap<>();
+ // Custom transform returns boxed Integer for text_pk: must bind as VARCHAR on INSERT & DELETE.
+ custom.put("text_pk", 123);
+
+ PostgreSQLDMLGenerator generator = new PostgreSQLDMLGenerator();
+ DMLGeneratorResponse insertResp =
+ generator.getDMLStatement(
+ new DMLGeneratorRequest.Builder("INSERT", "TypedPk", new JSONObject(), keys, "+00")
+ .setSchemaMapper(mapper)
+ .setDdl(ddl)
+ .setSourceSchema(sourceSchema)
+ .setCustomTransformationResponse(custom)
+ .build());
+ DMLGeneratorResponse deleteResp =
+ generator.getDMLStatement(
+ new DMLGeneratorRequest.Builder("DELETE", "TypedPk", new JSONObject(), keys, "+00")
+ .setSchemaMapper(mapper)
+ .setDdl(ddl)
+ .setSourceSchema(sourceSchema)
+ .setCustomTransformationResponse(custom)
+ .build());
+
+ List expectedParams =
+ List.of(
+ PreparedStatementValue.ofUntypedString("1.1"),
+ PreparedStatementValue.ofDouble(2.2),
+ PreparedStatementValue.ofBigDecimal(new BigDecimal("3.3")),
+ PreparedStatementValue.ofUntypedString("123e4567-e89b-12d3-a456-426614174000"),
+ PreparedStatementValue.ofUntypedString("2024-01-02"),
+ PreparedStatementValue.ofUntypedString("2024-01-02T03:04:05Z"),
+ PreparedStatementValue.ofBytes("abc".getBytes(StandardCharsets.UTF_8)),
+ PreparedStatementValue.ofBoolean(true),
+ PreparedStatementValue.ofLong(42L),
+ PreparedStatementValue.ofString("123"),
+ PreparedStatementValue.ofString("abc "),
+ PreparedStatementValue.ofString("\\x616263"),
+ PreparedStatementValue.ofUntypedString("active"),
+ PreparedStatementValue.ofUntypedString("{\"k\":1}"),
+ PreparedStatementValue.ofUntypedString("10:10:10"));
+
+ assertThat(insertResp.getDmlStatement())
+ .isEqualTo(
+ "INSERT INTO \"TypedPk\" ("
+ + "\"real_pk\",\"dbl_pk\",\"num_pk\",\"uuid_pk\",\"date_pk\","
+ + "\"ts_pk\",\"bytea_pk\",\"bool_pk\",\"int_pk\",\"text_pk\",\"char_pk\","
+ + "\"bytes_text_pk\",\"enum_pk\",\"jsonb_pk\",\"time_pk\") "
+ + "VALUES (?,?,?,?,?,?::timestamptz,?,?,?,?,?,?,?,?,?) "
+ + "ON CONFLICT ("
+ + "\"real_pk\",\"dbl_pk\",\"num_pk\",\"uuid_pk\",\"date_pk\","
+ + "\"ts_pk\",\"bytea_pk\",\"bool_pk\",\"int_pk\",\"text_pk\",\"char_pk\","
+ + "\"bytes_text_pk\",\"enum_pk\",\"jsonb_pk\",\"time_pk\")"
+ + " DO NOTHING");
+ assertThat(deleteResp.getDmlStatement())
+ .isEqualTo(
+ "DELETE FROM \"TypedPk\" WHERE "
+ + "\"real_pk\" = ? AND \"dbl_pk\" = ? AND \"num_pk\" = ? AND \"uuid_pk\" = ? "
+ + "AND \"date_pk\" = ? AND \"ts_pk\" = ?::timestamptz AND \"bytea_pk\" = ? "
+ + "AND \"bool_pk\" = ? AND \"int_pk\" = ? AND \"text_pk\" = ? AND \"char_pk\" = ? "
+ + "AND \"bytes_text_pk\" = ? AND \"enum_pk\" = ? AND \"jsonb_pk\" = ? "
+ + "AND \"time_pk\" = ?");
+ // INSERT and DELETE bind the exact same ordered PreparedStatementValues.
+ assertParams(insertResp.getPreparedStatementParameters(), expectedParams);
+ assertParams(deleteResp.getPreparedStatementParameters(), expectedParams);
+ }
+
+ @Test
+ public void testDeleteWithNullRegularPrimaryKeyFromJsonAndCustomTransform() {
+ Ddl ddl =
+ Ddl.builder()
+ .createTable("T")
+ .column("pk1")
+ .timestamp()
+ .endColumn()
+ .column("pk2")
+ .string()
+ .max()
+ .endColumn()
+ .primaryKey()
+ .asc("pk1")
+ .asc("pk2")
+ .end()
+ .endTable()
+ .build();
+ SourceTable sourceTable =
+ SourceTable.builder(SourceDatabaseType.POSTGRESQL)
+ .name("T")
+ .columns(
+ ImmutableList.of(srcCol("pk1", "timestamp with time zone"), srcCol("pk2", "text")))
+ .primaryKeyColumns(ImmutableList.of("pk1", "pk2"))
+ .build();
+ SourceSchema sourceSchema =
+ SourceSchema.builder(SourceDatabaseType.POSTGRESQL)
+ .databaseName("testdb")
+ .tables(ImmutableMap.of("T", sourceTable))
+ .build();
+ ISchemaMapper mapper = identityMapper("T", "pk1", "pk2");
+
+ // JSON null on timestamp PK (whose placeholder is ?::timestamptz) and custom null on pk2 both
+ // emit IS NULL in DELETE.
+ JSONObject keys = new JSONObject().put("pk1", JSONObject.NULL).put("pk2", "ignored");
+ Map custom = new HashMap<>();
+ custom.put("pk2", null);
+
+ DMLGeneratorResponse deleteResp =
+ new PostgreSQLDMLGenerator()
+ .getDMLStatement(
+ new DMLGeneratorRequest.Builder("DELETE", "T", new JSONObject(), keys, "+00:00")
+ .setSchemaMapper(mapper)
+ .setDdl(ddl)
+ .setSourceSchema(sourceSchema)
+ .setCustomTransformationResponse(custom)
+ .build());
+
+ assertThat(deleteResp.getDmlStatement())
+ .isEqualTo("DELETE FROM \"T\" WHERE \"pk1\" IS NULL AND \"pk2\" IS NULL");
+ assertThat(deleteResp.getPreparedStatementParameters()).isEmpty();
+
+ // JSONObject.NULL in custom transformation also emits IS NULL on DELETE.
+ Map jsonNullCustom = new HashMap<>();
+ jsonNullCustom.put("pk2", JSONObject.NULL);
+ DMLGeneratorResponse jsonNullDeleteResp =
+ new PostgreSQLDMLGenerator()
+ .getDMLStatement(
+ new DMLGeneratorRequest.Builder("DELETE", "T", new JSONObject(), keys, "+00:00")
+ .setSchemaMapper(mapper)
+ .setDdl(ddl)
+ .setSourceSchema(sourceSchema)
+ .setCustomTransformationResponse(jsonNullCustom)
+ .build());
+ assertThat(jsonNullDeleteResp.getDmlStatement())
+ .isEqualTo("DELETE FROM \"T\" WHERE \"pk1\" IS NULL AND \"pk2\" IS NULL");
+ assertThat(jsonNullDeleteResp.getPreparedStatementParameters()).isEmpty();
+ }
+
+ @Test
+ public void testGeneratedColumnsAndGeneratedPkUpsertAndDeleteWithNull() {
+ Ddl ddl =
+ Ddl.builder()
+ .createTable("Singers")
+ .column("GenPk")
+ .string()
+ .max()
+ .endColumn()
+ .column("FirstName")
+ .string()
+ .max()
+ .endColumn()
+ .column("LastName")
+ .string()
+ .max()
+ .endColumn()
+ .column("GenNonPk")
+ .string()
+ .max()
+ .endColumn()
+ .primaryKey()
+ .asc("GenPk")
+ .end()
+ .endTable()
+ .build();
+ SourceTable sourceTable =
+ SourceTable.builder(SourceDatabaseType.POSTGRESQL)
+ .name("Singers")
+ .columns(
+ ImmutableList.of(
+ SourceColumn.builder(SourceDatabaseType.POSTGRESQL)
+ .name("GenPk")
+ .type("text")
+ .isGenerated(true)
+ .build(),
+ srcCol("FirstName", "text"),
+ srcCol("LastName", "text"),
+ SourceColumn.builder(SourceDatabaseType.POSTGRESQL)
+ .name("GenNonPk")
+ .type("text")
+ .isGenerated(true)
+ .build()))
+ .primaryKeyColumns(ImmutableList.of("GenPk"))
+ .build();
+ SourceSchema sourceSchema =
+ SourceSchema.builder(SourceDatabaseType.POSTGRESQL)
+ .databaseName("testdb")
+ .tables(ImmutableMap.of("Singers", sourceTable))
+ .build();
+ ISchemaMapper mapper = identityMapper("Singers", "GenPk", "FirstName", "LastName", "GenNonPk");
+
+ JSONObject newValues =
+ new JSONObject().put("FirstName", "Ada").put("LastName", JSONObject.NULL);
+ JSONObject keyValues = new JSONObject().put("GenPk", "Ada");
+
+ // Upsert skips both generated PK and generated non-PK, binding non-PK columns once.
+ DMLGeneratorResponse upsertResp =
+ new PostgreSQLDMLGenerator()
+ .getDMLStatement(
+ new DMLGeneratorRequest.Builder("INSERT", "Singers", newValues, keyValues, "+00:00")
+ .setSchemaMapper(mapper)
+ .setDdl(ddl)
+ .setSourceSchema(sourceSchema)
+ .build());
+ assertThat(upsertResp.getDmlStatement())
+ .isEqualTo(
+ "INSERT INTO \"Singers\" (\"FirstName\",\"LastName\") VALUES (?,?)"
+ + " ON CONFLICT (\"GenPk\") DO UPDATE SET"
+ + " \"FirstName\" = EXCLUDED.\"FirstName\","
+ + "\"LastName\" = EXCLUDED.\"LastName\"");
+ assertParams(
+ upsertResp.getPreparedStatementParameters(),
+ PreparedStatementValue.ofString("Ada"),
+ PreparedStatementValue.nullValue(Types.VARCHAR));
+
+ // Delete on generated-PK table emits IS NULL for null non-PK columns instead of "= ?".
+ DMLGeneratorResponse deleteResp =
+ new PostgreSQLDMLGenerator()
+ .getDMLStatement(
+ new DMLGeneratorRequest.Builder("DELETE", "Singers", newValues, keyValues, "+00:00")
+ .setSchemaMapper(mapper)
+ .setDdl(ddl)
+ .setSourceSchema(sourceSchema)
+ .build());
+ assertThat(deleteResp.getDmlStatement())
+ .isEqualTo("DELETE FROM \"Singers\" WHERE \"FirstName\" = ? AND \"LastName\" IS NULL");
+ assertParams(
+ deleteResp.getPreparedStatementParameters(), PreparedStatementValue.ofString("Ada"));
+
+ // All-NULL delete on generated-PK table emits pure IS NULL predicates with empty param list.
+ DMLGeneratorResponse allNullDelete =
+ new PostgreSQLDMLGenerator()
+ .getDMLStatement(
+ new DMLGeneratorRequest.Builder(
+ "DELETE",
+ "Singers",
+ new JSONObject()
+ .put("FirstName", JSONObject.NULL)
+ .put("LastName", JSONObject.NULL),
+ keyValues,
+ "+00:00")
+ .setSchemaMapper(mapper)
+ .setDdl(ddl)
+ .setSourceSchema(sourceSchema)
+ .build());
+ assertThat(allNullDelete.getDmlStatement())
+ .isEqualTo("DELETE FROM \"Singers\" WHERE \"FirstName\" IS NULL AND \"LastName\" IS NULL");
+ assertThat(allNullDelete.getPreparedStatementParameters()).isEmpty();
+ }
+
+ @Test
+ public void testCompositeRegularAndGeneratedPrimaryKeyUpsertAndDelete() {
+ Ddl ddl =
+ Ddl.builder()
+ .createTable("Items")
+ .column("TenantId")
+ .int64()
+ .endColumn()
+ .column("GenCode")
+ .string()
+ .max()
+ .endColumn()
+ .column("Name")
+ .string()
+ .max()
+ .endColumn()
+ .primaryKey()
+ .asc("TenantId")
+ .asc("GenCode")
+ .end()
+ .endTable()
+ .build();
+ SourceTable sourceTable =
+ SourceTable.builder(SourceDatabaseType.POSTGRESQL)
+ .name("Items")
+ .columns(
+ ImmutableList.of(
+ srcCol("TenantId", "bigint"),
+ SourceColumn.builder(SourceDatabaseType.POSTGRESQL)
+ .name("GenCode")
+ .type("text")
+ .isGenerated(true)
+ .build(),
+ srcCol("Name", "text")))
+ .primaryKeyColumns(ImmutableList.of("TenantId", "GenCode"))
+ .build();
+ SourceSchema sourceSchema =
+ SourceSchema.builder(SourceDatabaseType.POSTGRESQL)
+ .databaseName("testdb")
+ .tables(ImmutableMap.of("Items", sourceTable))
+ .build();
+ ISchemaMapper mapper = identityMapper("Items", "TenantId", "GenCode", "Name");
+
+ JSONObject keys = new JSONObject().put("TenantId", "7").put("GenCode", "C1");
+ JSONObject values = new JSONObject().put("Name", "Widget");
+
+ DMLGeneratorResponse upsert =
+ new PostgreSQLDMLGenerator()
+ .getDMLStatement(
+ new DMLGeneratorRequest.Builder("INSERT", "Items", values, keys, "+00:00")
+ .setSchemaMapper(mapper)
+ .setDdl(ddl)
+ .setSourceSchema(sourceSchema)
+ .build());
+ assertThat(upsert.getDmlStatement())
+ .isEqualTo(
+ "INSERT INTO \"Items\" (\"TenantId\",\"Name\") VALUES (?,?) ON CONFLICT"
+ + " (\"TenantId\",\"GenCode\") DO UPDATE SET \"Name\" = EXCLUDED.\"Name\"");
+ assertParams(
+ upsert.getPreparedStatementParameters(),
+ PreparedStatementValue.ofLong(7L),
+ PreparedStatementValue.ofString("Widget"));
+
+ DMLGeneratorResponse delete =
+ new PostgreSQLDMLGenerator()
+ .getDMLStatement(
+ new DMLGeneratorRequest.Builder("DELETE", "Items", values, keys, "+00:00")
+ .setSchemaMapper(mapper)
+ .setDdl(ddl)
+ .setSourceSchema(sourceSchema)
+ .build());
+ assertThat(delete.getDmlStatement())
+ .isEqualTo("DELETE FROM \"Items\" WHERE \"TenantId\" = ? AND \"Name\" = ?");
+ assertParams(
+ delete.getPreparedStatementParameters(),
+ PreparedStatementValue.ofLong(7L),
+ PreparedStatementValue.ofString("Widget"));
+ }
+
+ @Test
+ public void testInformationSchemaScannerDataTypesMatrix() {
+ // Verifies the exact information_schema.columns.data_type strings emitted by
+ // PostgreSQLInformationSchemaScanner.scanColumns.
+ ImmutableMap expectedCategories =
+ ImmutableMap.builder()
+ .put("character varying", PgColumnType.CHARACTER)
+ .put("character", PgColumnType.CHARACTER)
+ .put("text", PgColumnType.CHARACTER)
+ .put("name", PgColumnType.CHARACTER)
+ .put("smallint", PgColumnType.INTEGER)
+ .put("integer", PgColumnType.INTEGER)
+ .put("bigint", PgColumnType.INTEGER)
+ .put("real", PgColumnType.OTHER)
+ .put("double precision", PgColumnType.FLOAT8)
+ .put("numeric", PgColumnType.DECIMAL)
+ .put("boolean", PgColumnType.BOOLEAN)
+ .put("timestamp without time zone", PgColumnType.TIMESTAMP)
+ .put("timestamp with time zone", PgColumnType.TIMESTAMP)
+ .put("timestamp without time zone[]", PgColumnType.OTHER)
+ .put("timestamp with time zone[]", PgColumnType.OTHER)
+ .put("character varying[]", PgColumnType.OTHER)
+ .put("integer[]", PgColumnType.OTHER)
+ .put("bytea[]", PgColumnType.OTHER)
+ .put("USER-DEFINED[]", PgColumnType.OTHER)
+ .put("ARRAY", PgColumnType.OTHER)
+ .put("citext", PgColumnType.OTHER)
+ .put("bytea", PgColumnType.OTHER)
+ .put("date", PgColumnType.OTHER)
+ .put("time without time zone", PgColumnType.OTHER)
+ .put("time with time zone", PgColumnType.OTHER)
+ .put("interval", PgColumnType.OTHER)
+ .put("json", PgColumnType.OTHER)
+ .put("jsonb", PgColumnType.OTHER)
+ .put("uuid", PgColumnType.OTHER)
+ .put("money", PgColumnType.OTHER)
+ .put("bit", PgColumnType.OTHER)
+ .put("bit varying", PgColumnType.OTHER)
+ .put("inet", PgColumnType.OTHER)
+ .put("xml", PgColumnType.OTHER)
+ .put("USER-DEFINED", PgColumnType.OTHER)
+ .build();
+
+ for (Map.Entry entry : expectedCategories.entrySet()) {
+ assertWithMessage("PgColumnType for '%s'", entry.getKey())
+ .that(PgColumnType.fromSourceType(entry.getKey()))
+ .isEqualTo(entry.getValue());
+ }
+
+ // Spot-check end-to-end binding of scanner-emitted types previously untested.
+ assertThat(bindValue(Type.string(), "USER-DEFINED", "active"))
+ .isEqualTo(PreparedStatementValue.ofUntypedString("active"));
+ assertThat(bindValue(Type.string(), "USER-DEFINED[]", "{\"a\"}"))
+ .isEqualTo(PreparedStatementValue.ofUntypedString("{\"a\"}"));
+ assertThat(bindValue(Type.string(), "citext", "CaseTest"))
+ .isEqualTo(PreparedStatementValue.ofUntypedString("CaseTest"));
+ assertThat(bindValue(Type.string(), "name", "pg_catalog"))
+ .isEqualTo(PreparedStatementValue.ofString("pg_catalog"));
+ assertThat(bindValue(Type.string(), "interval", "1 day"))
+ .isEqualTo(PreparedStatementValue.ofUntypedString("1 day"));
+ assertThat(bindValue(Type.string(), "money", "$12.34"))
+ .isEqualTo(PreparedStatementValue.ofUntypedString("$12.34"));
+ assertThat(bindValue(Type.string(), "bit", "1"))
+ .isEqualTo(PreparedStatementValue.ofUntypedString("1"));
+ assertThat(bindValue(Type.string(), "bit varying", "101"))
+ .isEqualTo(PreparedStatementValue.ofUntypedString("101"));
+ assertThat(bindValue(Type.string(), "inet", "192.168.1.1"))
+ .isEqualTo(PreparedStatementValue.ofUntypedString("192.168.1.1"));
+ assertThat(bindValue(Type.string(), "xml", " "))
+ .isEqualTo(PreparedStatementValue.ofUntypedString(" "));
+ }
+
+ @Test
+ public void sqlInjection_spannerStringMappedToNonStringAndDefaultPostgresTypes() {
+ String payload = "0); DROP TABLE pwned; --";
+ String maliciousTz = "'+00:00'; DROP TABLE evil_tz; --";
+ Ddl ddl =
+ Ddl.builder()
+ .createTable("Singers")
+ .column("SingerId")
+ .int64()
+ .endColumn()
+ .column("IntCol")
+ .string()
+ .max()
+ .endColumn()
+ .column("NumCol")
+ .string()
+ .max()
+ .endColumn()
+ .column("BoolCol")
+ .string()
+ .max()
+ .endColumn()
+ .column("TsCol")
+ .timestamp()
+ .endColumn()
+ .column("DefaultCol")
+ .string()
+ .max()
+ .endColumn()
+ .primaryKey()
+ .asc("SingerId")
+ .end()
+ .endTable()
+ .build();
+ SourceTable sourceTable =
+ SourceTable.builder(SourceDatabaseType.POSTGRESQL)
+ .name("Singers")
+ .columns(
+ ImmutableList.of(
+ srcCol("SingerId", "bigint"),
+ srcCol("IntCol", "integer"),
+ srcCol("NumCol", "numeric"),
+ srcCol("BoolCol", "boolean"),
+ srcCol("TsCol", "timestamp with time zone"),
+ srcCol("DefaultCol", "USER-DEFINED")))
+ .primaryKeyColumns(ImmutableList.of("SingerId"))
+ .build();
+ SourceSchema sourceSchema =
+ SourceSchema.builder(SourceDatabaseType.POSTGRESQL)
+ .databaseName("testdb")
+ .tables(ImmutableMap.of("Singers", sourceTable))
+ .build();
+ ISchemaMapper mapper =
+ identityMapper("Singers", "SingerId", "IntCol", "NumCol", "BoolCol", "TsCol", "DefaultCol");
+
+ JSONObject newValues =
+ new JSONObject()
+ .put("IntCol", payload)
+ .put("NumCol", payload)
+ .put("BoolCol", payload)
+ .put("TsCol", payload)
+ .put("DefaultCol", payload);
+
+ DMLGeneratorResponse response =
+ new PostgreSQLDMLGenerator()
+ .getDMLStatement(
+ new DMLGeneratorRequest.Builder(
+ "INSERT",
+ "Singers",
+ newValues,
+ new JSONObject().put("SingerId", "1"),
+ maliciousTz)
+ .setSchemaMapper(mapper)
+ .setDdl(ddl)
+ .setSourceSchema(sourceSchema)
+ .build());
+
+ assertThat(response.getDmlStatement())
+ .isEqualTo(
+ "INSERT INTO \"Singers\""
+ + " (\"IntCol\",\"NumCol\",\"BoolCol\",\"TsCol\",\"DefaultCol\",\"SingerId\")"
+ + " VALUES (?,?,?,?::timestamptz,?,?) ON CONFLICT (\"SingerId\") DO UPDATE SET"
+ + " \"IntCol\" = EXCLUDED.\"IntCol\","
+ + "\"NumCol\" = EXCLUDED.\"NumCol\","
+ + "\"BoolCol\" = EXCLUDED.\"BoolCol\","
+ + "\"TsCol\" = EXCLUDED.\"TsCol\","
+ + "\"DefaultCol\" = EXCLUDED.\"DefaultCol\"");
+ assertThat(response.getDmlStatement()).doesNotContain("evil_tz");
+ assertParams(
+ response.getPreparedStatementParameters(),
+ PreparedStatementValue.ofUntypedString(payload),
+ PreparedStatementValue.ofUntypedString(payload),
+ PreparedStatementValue.ofUntypedString(payload),
+ PreparedStatementValue.ofUntypedString(payload),
+ PreparedStatementValue.ofUntypedString(payload),
+ PreparedStatementValue.ofLong(1L));
+ }
+
+ @Test
+ public void sqlInjection_maliciousCustomTransformationPayloadBoundAsParameter() {
+ String sessionFile = "src/test/resources/customTransformation.json";
+ Ddl ddl = SchemaUtils.buildSpannerDdlFromSessionFile(sessionFile);
+ SourceSchema sourceSchema = SchemaUtils.buildSourceSchemaFromSessionFile(sessionFile);
+ ISchemaMapper schemaMapper = new SessionBasedMapper(sessionFile, ddl);
+
+ String nonPkPayload = "0,(SELECT current_user),version()) --";
+ String pkPayload = "1 OR 1=1; DROP TABLE Singers; --";
+ Map customTransformation = new HashMap<>();
+ customTransformation.put("FullName", nonPkPayload);
+ customTransformation.put("SingerId", pkPayload);
+
+ // Upsert path: both payloads bind as typed parameters (VARCHAR for FullName, OTHER for int PK).
+ DMLGeneratorResponse upsertResp =
+ new PostgreSQLDMLGenerator()
+ .getDMLStatement(
+ new DMLGeneratorRequest.Builder(
+ "INSERT",
+ "Singers",
+ new JSONObject().put("FirstName", "kk").put("LastName", "ll"),
+ new JSONObject().put("SingerId", "999"),
+ "+00:00")
+ .setSchemaMapper(schemaMapper)
+ .setDdl(ddl)
+ .setSourceSchema(sourceSchema)
+ .setCustomTransformationResponse(customTransformation)
+ .build());
+ assertThat(upsertResp.getDmlStatement())
+ .isEqualTo(
+ "INSERT INTO \"Singers\" (\"FullName\",\"SingerId\") VALUES (?,?)"
+ + " ON CONFLICT (\"SingerId\") DO UPDATE SET \"FullName\" = EXCLUDED.\"FullName\"");
+ assertParams(
+ upsertResp.getPreparedStatementParameters(),
+ PreparedStatementValue.ofString(nonPkPayload),
+ PreparedStatementValue.ofUntypedString(pkPayload));
+
+ // Delete path.
+ DMLGeneratorResponse deleteResp =
+ new PostgreSQLDMLGenerator()
+ .getDMLStatement(
+ new DMLGeneratorRequest.Builder(
+ "DELETE",
+ "Singers",
+ new JSONObject(),
+ new JSONObject().put("SingerId", "999"),
+ "+00:00")
+ .setSchemaMapper(schemaMapper)
+ .setDdl(ddl)
+ .setSourceSchema(sourceSchema)
+ .setCustomTransformationResponse(customTransformation)
+ .build());
+ assertThat(deleteResp.getDmlStatement())
+ .isEqualTo("DELETE FROM \"Singers\" WHERE \"SingerId\" = ?");
+ assertParams(
+ deleteResp.getPreparedStatementParameters(),
+ PreparedStatementValue.ofUntypedString(pkPayload));
+ }
+
+ @Test
+ public void sqlInjection_identifiersWithDoubleQuotesAreEscaped() {
+ String evilTable = "Singers\"; DROP TABLE pwned; --";
+ String evilPk = "id\"col";
+ String evilCol = "first\"name\"; --";
+
+ assertThat(PostgreSQLDMLGenerator.quoteIdentifier("Singers")).isEqualTo("\"Singers\"");
+ assertThat(PostgreSQLDMLGenerator.quoteIdentifier("a\"b")).isEqualTo("\"a\"\"b\"");
+ assertThat(PostgreSQLDMLGenerator.quoteIdentifier(evilTable))
+ .isEqualTo("\"Singers\"\"; DROP TABLE pwned; --\"");
+ assertThrows(NullPointerException.class, () -> PostgreSQLDMLGenerator.quoteIdentifier(null));
+
+ Ddl ddl =
+ Ddl.builder()
+ .createTable("Singers")
+ .column("id")
+ .int64()
+ .endColumn()
+ .column("name")
+ .string()
+ .max()
+ .endColumn()
+ .primaryKey()
+ .asc("id")
+ .end()
+ .endTable()
+ .build();
+ SourceTable sourceTable =
+ SourceTable.builder(SourceDatabaseType.POSTGRESQL)
+ .name(evilTable)
+ .columns(ImmutableList.of(srcCol(evilPk, "bigint"), srcCol(evilCol, "text")))
+ .primaryKeyColumns(ImmutableList.of(evilPk))
+ .build();
+ SourceSchema sourceSchema =
+ SourceSchema.builder(SourceDatabaseType.POSTGRESQL)
+ .databaseName("testdb")
+ .tables(ImmutableMap.of(evilTable, sourceTable))
+ .build();
+ ISchemaMapper mapper = mock(ISchemaMapper.class);
+ when(mapper.getSourceTableName("", "Singers")).thenReturn(evilTable);
+ when(mapper.getSpannerColumnName("", evilTable, evilPk)).thenReturn("id");
+ when(mapper.getSpannerColumnName("", evilTable, evilCol)).thenReturn("name");
+
+ String escapedTable = "\"Singers\"\"; DROP TABLE pwned; --\"";
+ String escapedPk = "\"id\"\"col\"";
+ String escapedCol = "\"first\"\"name\"\"; --\"";
+
+ DMLGeneratorResponse upsertResp =
+ new PostgreSQLDMLGenerator()
+ .getDMLStatement(
+ new DMLGeneratorRequest.Builder(
+ "INSERT",
+ "Singers",
+ new JSONObject().put("name", "Ada"),
+ new JSONObject().put("id", "7"),
+ "+00:00")
+ .setSchemaMapper(mapper)
+ .setDdl(ddl)
+ .setSourceSchema(sourceSchema)
+ .build());
+ assertThat(upsertResp.getDmlStatement())
+ .isEqualTo(
+ String.format(
+ "INSERT INTO %s (%s,%s) VALUES (?,?) ON CONFLICT (%s) DO UPDATE SET %s ="
+ + " EXCLUDED.%s",
+ escapedTable, escapedCol, escapedPk, escapedPk, escapedCol, escapedCol));
+ assertParams(
+ upsertResp.getPreparedStatementParameters(),
+ PreparedStatementValue.ofString("Ada"),
+ PreparedStatementValue.ofLong(7L));
+
+ DMLGeneratorResponse deleteResp =
+ new PostgreSQLDMLGenerator()
+ .getDMLStatement(
+ new DMLGeneratorRequest.Builder(
+ "DELETE",
+ "Singers",
+ new JSONObject(),
+ new JSONObject().put("id", "7"),
+ "+00:00")
+ .setSchemaMapper(mapper)
+ .setDdl(ddl)
+ .setSourceSchema(sourceSchema)
+ .build());
+ assertThat(deleteResp.getDmlStatement())
+ .isEqualTo(String.format("DELETE FROM %s WHERE %s = ?", escapedTable, escapedPk));
+ assertParams(deleteResp.getPreparedStatementParameters(), PreparedStatementValue.ofLong(7L));
+ }
+
+ @Test
+ public void testGetDMLStatement_SchemaAndPkValidationFailures() {
+ PostgreSQLDMLGenerator generator = new PostgreSQLDMLGenerator();
+ Ddl emptyDdl = Ddl.builder().build();
+ SourceTable singlePkTable =
+ SourceTable.builder(SourceDatabaseType.POSTGRESQL)
+ .name("Singers")
+ .columns(ImmutableList.of(srcCol("SingerId", "bigint")))
+ .primaryKeyColumns(ImmutableList.of("SingerId"))
+ .build();
+ SourceSchema sourceSchema =
+ SourceSchema.builder(SourceDatabaseType.POSTGRESQL)
+ .databaseName("testdb")
+ .tables(ImmutableMap.of("Singers", singlePkTable))
+ .build();
+ ISchemaMapper mapper = mock(ISchemaMapper.class);
+
+ // Spanner table missing from DDL.
+ DMLGeneratorRequest missingTableReq =
+ new DMLGeneratorRequest.Builder(
+ "INSERT", "MissingTable", new JSONObject(), new JSONObject(), "+00:00")
+ .setSchemaMapper(mapper)
+ .setDdl(emptyDdl)
+ .setSourceSchema(sourceSchema)
+ .build();
+ InvalidDMLGenerationException missingTableEx =
+ assertThrows(
+ InvalidDMLGenerationException.class, () -> generator.getDMLStatement(missingTableReq));
+ assertThat(missingTableEx).hasMessageThat().contains("MissingTable");
+
+ // Schema mapper fails to map Spanner table to source table.
+ Ddl singersDdl =
+ Ddl.builder()
+ .createTable("Singers")
+ .column("SingerId")
+ .int64()
+ .endColumn()
+ .primaryKey()
+ .asc("SingerId")
+ .end()
+ .endTable()
+ .build();
+ when(mapper.getSourceTableName("", "Singers"))
+ .thenThrow(new NoSuchElementException("unmapped"));
+ DMLGeneratorRequest unmappedTableReq =
+ new DMLGeneratorRequest.Builder(
+ "INSERT", "Singers", new JSONObject(), new JSONObject(), "+00:00")
+ .setSchemaMapper(mapper)
+ .setDdl(singersDdl)
+ .setSourceSchema(sourceSchema)
+ .build();
+ InvalidDMLGenerationException unmappedTableEx =
+ assertThrows(
+ InvalidDMLGenerationException.class, () -> generator.getDMLStatement(unmappedTableReq));
+ assertThat(unmappedTableEx).hasMessageThat().contains("Could not find source table name");
+
+ // Sole PK column has no Spanner mapping -> pkColumnBindings is empty -> throws.
+ ISchemaMapper unmappedPkMapper = mock(ISchemaMapper.class);
+ when(unmappedPkMapper.getSourceTableName("", "Singers")).thenReturn("Singers");
+ when(unmappedPkMapper.getSpannerColumnName("", "Singers", "SingerId"))
+ .thenThrow(new NoSuchElementException("unmapped pk"));
+ DMLGeneratorRequest unmappedPkReq =
+ new DMLGeneratorRequest.Builder(
+ "DELETE",
+ "Singers",
+ new JSONObject(),
+ new JSONObject().put("SingerId", "1"),
+ "+00:00")
+ .setSchemaMapper(unmappedPkMapper)
+ .setDdl(singersDdl)
+ .setSourceSchema(sourceSchema)
+ .build();
+ InvalidDMLGenerationException unmappedPkEx =
+ assertThrows(
+ InvalidDMLGenerationException.class, () -> generator.getDMLStatement(unmappedPkReq));
+ assertThat(unmappedPkEx).hasMessageThat().contains("without primary key");
}
@Test
@@ -505,12 +1990,16 @@ public void testGetDMLStatement_SourceTableNotFound() {
DMLGeneratorRequest request = mock(DMLGeneratorRequest.class);
ISchemaMapper schemaMapper = mock(ISchemaMapper.class);
SourceSchema sourceSchema = mock(SourceSchema.class);
+ Ddl ddl = mock(Ddl.class);
+ Table spannerTable = mock(Table.class);
when(request.getSpannerTableName()).thenReturn("Singers");
when(request.getSchemaMapper()).thenReturn(schemaMapper);
when(request.getSourceSchema()).thenReturn(sourceSchema);
+ when(request.getSpannerDdl()).thenReturn(ddl);
+ when(ddl.table("Singers")).thenReturn(spannerTable);
when(schemaMapper.getSourceTableName("", "Singers")).thenReturn("Singers");
- when(sourceSchema.table("Singers")).thenReturn(null); // Not found!
+ when(sourceSchema.table("Singers")).thenReturn(null);
assertThrows(InvalidDMLGenerationException.class, () -> generator.getDMLStatement(request));
}
@@ -522,10 +2011,14 @@ public void testGetDMLStatement_NoPrimaryKeys() {
ISchemaMapper schemaMapper = mock(ISchemaMapper.class);
SourceSchema sourceSchema = mock(SourceSchema.class);
SourceTable sourceTable = mock(SourceTable.class);
+ Ddl ddl = mock(Ddl.class);
+ Table spannerTable = mock(Table.class);
when(request.getSpannerTableName()).thenReturn("Singers");
when(request.getSchemaMapper()).thenReturn(schemaMapper);
when(request.getSourceSchema()).thenReturn(sourceSchema);
+ when(request.getSpannerDdl()).thenReturn(ddl);
+ when(ddl.table("Singers")).thenReturn(spannerTable);
when(schemaMapper.getSourceTableName("", "Singers")).thenReturn("Singers");
when(sourceSchema.table("Singers")).thenReturn(sourceTable);
when(sourceTable.primaryKeyColumns()).thenReturn(ImmutableList.of());
@@ -540,26 +2033,30 @@ public void testGetDMLStatement_UpdateMode() {
SourceSchema sourceSchema = SchemaUtils.buildSourceSchemaFromSessionFile(sessionFile);
ISchemaMapper schemaMapper = new SessionBasedMapper(sessionFile, ddl);
- String tableName = "Singers";
- String newValuesString = "{\"FirstName\":\"kk\",\"LastName\":\"ll\"}";
- JSONObject newValuesJson = new JSONObject(newValuesString);
- JSONObject keyValuesJson = new JSONObject("{\"SingerId\":\"999\"}");
- String modType = "UPDATE";
-
- PostgreSQLDMLGenerator postgreSQLDMLGenerator = new PostgreSQLDMLGenerator();
- DMLGeneratorResponse dmlGeneratorResponse =
- postgreSQLDMLGenerator.getDMLStatement(
- new DMLGeneratorRequest.Builder(
- modType, tableName, newValuesJson, keyValuesJson, "+00:00")
- .setSchemaMapper(schemaMapper)
- .setDdl(ddl)
- .setSourceSchema(sourceSchema)
- .build());
- String sql = dmlGeneratorResponse.getDmlStatement();
+ JSONObject newValuesJson = new JSONObject().put("FirstName", "kk").put("LastName", "ll");
+ JSONObject keyValuesJson = new JSONObject().put("SingerId", "999");
- assertTrue(sql.contains("\"FirstName\" = EXCLUDED.\"FirstName\""));
- assertTrue(sql.contains("\"LastName\" = EXCLUDED.\"LastName\""));
- assertTrue(sql.contains("ON CONFLICT (\"SingerId\") DO UPDATE SET"));
+ DMLGeneratorResponse response =
+ new PostgreSQLDMLGenerator()
+ .getDMLStatement(
+ new DMLGeneratorRequest.Builder(
+ "UPDATE", "Singers", newValuesJson, keyValuesJson, "+00:00")
+ .setSchemaMapper(schemaMapper)
+ .setDdl(ddl)
+ .setSourceSchema(sourceSchema)
+ .build());
+
+ assertThat(response.getDmlStatement())
+ .isEqualTo(
+ "INSERT INTO \"Singers\" (\"FirstName\",\"LastName\",\"SingerId\") VALUES (?,?,?)"
+ + " ON CONFLICT (\"SingerId\") DO UPDATE SET"
+ + " \"FirstName\" = EXCLUDED.\"FirstName\","
+ + "\"LastName\" = EXCLUDED.\"LastName\"");
+ assertParams(
+ response.getPreparedStatementParameters(),
+ PreparedStatementValue.ofString("kk"),
+ PreparedStatementValue.ofString("ll"),
+ PreparedStatementValue.ofLong(999L));
}
@Test
@@ -569,24 +2066,29 @@ public void testGetUpsertStatement_AllColumnsArePKs() {
SourceSchema sourceSchema = SchemaUtils.buildSourceSchemaFromSessionFile(sessionFile);
ISchemaMapper schemaMapper = new SessionBasedMapper(sessionFile, ddl);
- String tableName = "resource_access";
- String newValuesString = "{\"user_id\":\"101\",\"group_id\":\"5\",\"resource_id\":\"99\"}";
- JSONObject newValuesJson = new JSONObject(newValuesString);
- JSONObject keyValuesJson = new JSONObject(newValuesString);
- String modType = "INSERT";
-
- PostgreSQLDMLGenerator postgreSQLDMLGenerator = new PostgreSQLDMLGenerator();
- DMLGeneratorResponse dmlGeneratorResponse =
- postgreSQLDMLGenerator.getDMLStatement(
- new DMLGeneratorRequest.Builder(
- modType, tableName, newValuesJson, keyValuesJson, "+00:00")
- .setSchemaMapper(schemaMapper)
- .setDdl(ddl)
- .setSourceSchema(sourceSchema)
- .build());
- String sql = dmlGeneratorResponse.getDmlStatement();
+ JSONObject values =
+ new JSONObject().put("user_id", "101").put("group_id", "5").put("resource_id", "99");
- assertTrue(sql.contains("DO NOTHING"));
+ DMLGeneratorResponse response =
+ new PostgreSQLDMLGenerator()
+ .getDMLStatement(
+ new DMLGeneratorRequest.Builder(
+ "INSERT", "resource_access", values, values, "+00:00")
+ .setSchemaMapper(schemaMapper)
+ .setDdl(ddl)
+ .setSourceSchema(sourceSchema)
+ .build());
+
+ assertThat(response.getDmlStatement())
+ .isEqualTo(
+ "INSERT INTO \"resource_access\" (\"user_id\",\"group_id\",\"resource_id\")"
+ + " VALUES (?,?,?) ON CONFLICT (\"user_id\",\"group_id\",\"resource_id\")"
+ + " DO NOTHING");
+ assertParams(
+ response.getPreparedStatementParameters(),
+ PreparedStatementValue.ofLong(101L),
+ PreparedStatementValue.ofLong(5L),
+ PreparedStatementValue.ofLong(99L));
}
@Test
@@ -604,20 +2106,13 @@ public void testGetDMLStatement_NullPrimaryKeys() {
when(request.getSourceSchema()).thenReturn(sourceSchema);
when(request.getSpannerDdl()).thenReturn(ddl);
when(ddl.table("Singers")).thenReturn(spannerTable);
-
when(schemaMapper.getSourceTableName("", "Singers")).thenReturn("Singers");
when(sourceSchema.table("Singers")).thenReturn(sourceTable);
- when(sourceTable.primaryKeyColumns()).thenReturn(null); // NULL!
+ when(sourceTable.primaryKeyColumns()).thenReturn(null);
assertThrows(InvalidDMLGenerationException.class, () -> generator.getDMLStatement(request));
}
- @Test
- public void testGetQuotedEscapedString_PgBytea() {
- String result = PostgreSQLDMLGenerator.getQuotedEscapedString("Hello", "PG_BYTEA");
- assertEquals("Hello", result); // No quotes!
- }
-
@Test
public void testGetDMLStatement_NullValueInUpsert() {
String sessionFile = "src/test/resources/allMatchSession.json";
@@ -625,26 +2120,186 @@ public void testGetDMLStatement_NullValueInUpsert() {
SourceSchema sourceSchema = SchemaUtils.buildSourceSchemaFromSessionFile(sessionFile);
ISchemaMapper schemaMapper = new SessionBasedMapper(sessionFile, ddl);
- String tableName = "Singers";
- String newValuesString = "{\"FirstName\":\"kk\",\"LastName\":null}"; // NULL value!
- JSONObject newValuesJson = new JSONObject(newValuesString);
- JSONObject keyValuesJson = new JSONObject("{\"SingerId\":\"999\"}");
- String modType = "INSERT";
-
- PostgreSQLDMLGenerator postgreSQLDMLGenerator = new PostgreSQLDMLGenerator();
- DMLGeneratorResponse dmlGeneratorResponse =
- postgreSQLDMLGenerator.getDMLStatement(
- new DMLGeneratorRequest.Builder(
- modType, tableName, newValuesJson, keyValuesJson, "+00:00")
- .setSchemaMapper(schemaMapper)
- .setDdl(ddl)
- .setSourceSchema(sourceSchema)
- .build());
- String sql = dmlGeneratorResponse.getDmlStatement();
+ JSONObject newValuesJson =
+ new JSONObject().put("FirstName", "kk").put("LastName", JSONObject.NULL);
+ JSONObject keyValuesJson = new JSONObject().put("SingerId", "999");
+
+ DMLGeneratorResponse response =
+ new PostgreSQLDMLGenerator()
+ .getDMLStatement(
+ new DMLGeneratorRequest.Builder(
+ "INSERT", "Singers", newValuesJson, keyValuesJson, "+00:00")
+ .setSchemaMapper(schemaMapper)
+ .setDdl(ddl)
+ .setSourceSchema(sourceSchema)
+ .build());
+
+ assertThat(response.getDmlStatement())
+ .isEqualTo(
+ "INSERT INTO \"Singers\" (\"FirstName\",\"LastName\",\"SingerId\") VALUES (?,?,?)"
+ + " ON CONFLICT (\"SingerId\") DO UPDATE SET"
+ + " \"FirstName\" = EXCLUDED.\"FirstName\","
+ + "\"LastName\" = EXCLUDED.\"LastName\"");
+ assertParams(
+ response.getPreparedStatementParameters(),
+ PreparedStatementValue.ofString("kk"),
+ PreparedStatementValue.nullValue(Types.VARCHAR),
+ PreparedStatementValue.ofLong(999L));
+ }
+
+ @Test
+ public void getDMLStatement_nullTimestampInUpsert_preservesTimestamptzPlaceholder() {
+ Ddl ddl =
+ Ddl.builder()
+ .createTable("Events")
+ .column("id")
+ .int64()
+ .endColumn()
+ .column("created_at")
+ .timestamp()
+ .endColumn()
+ .primaryKey()
+ .asc("id")
+ .end()
+ .endTable()
+ .build();
+ SourceTable sourceTable =
+ SourceTable.builder(SourceDatabaseType.POSTGRESQL)
+ .name("Events")
+ .columns(
+ ImmutableList.of(
+ srcCol("id", "bigint"), srcCol("created_at", "timestamp without time zone")))
+ .primaryKeyColumns(ImmutableList.of("id"))
+ .build();
+ SourceSchema sourceSchema =
+ SourceSchema.builder(SourceDatabaseType.POSTGRESQL)
+ .databaseName("testdb")
+ .tables(ImmutableMap.of("Events", sourceTable))
+ .build();
+ ISchemaMapper mapper = identityMapper("Events", "id", "created_at");
+
+ DMLGeneratorResponse response =
+ new PostgreSQLDMLGenerator()
+ .getDMLStatement(
+ new DMLGeneratorRequest.Builder(
+ "INSERT",
+ "Events",
+ new JSONObject().put("created_at", JSONObject.NULL),
+ new JSONObject().put("id", "42"),
+ "+00:00")
+ .setSchemaMapper(mapper)
+ .setDdl(ddl)
+ .setSourceSchema(sourceSchema)
+ .build());
+
+ assertThat(response.getDmlStatement())
+ .isEqualTo(
+ "INSERT INTO \"Events\" (\"created_at\",\"id\") VALUES (?::timestamptz,?)"
+ + " ON CONFLICT (\"id\") DO UPDATE SET"
+ + " \"created_at\" = EXCLUDED.\"created_at\"");
+ assertParams(
+ response.getPreparedStatementParameters(),
+ PreparedStatementValue.nullValue(Types.NULL),
+ PreparedStatementValue.ofLong(42L));
+ }
+
+ private static SourceColumn srcCol(String name, String type) {
+ return SourceColumn.builder(SourceDatabaseType.POSTGRESQL).name(name).type(type).build();
+ }
+
+ private static ColumnBinding bind(Type spannerType, String pgType, Object value) {
+ Column spannerCol = mock(Column.class);
+ when(spannerCol.name()).thenReturn("test_col");
+ when(spannerCol.type()).thenReturn(spannerType);
+ SourceColumn sourceCol = srcCol("test_col", pgType);
+ return PostgreSQLDMLGenerator.getMappedColumnBinding(
+ spannerCol, sourceCol, new JSONObject().put("test_col", value));
+ }
+
+ private static ColumnBinding nullBindingFor(Type spannerType, String pgType) {
+ Column spannerCol = mock(Column.class);
+ when(spannerCol.type()).thenReturn(spannerType);
+ return PostgreSQLDMLGenerator.getNullColumnBinding(spannerCol, srcCol("test_col", pgType));
+ }
+
+ private static PreparedStatementValue bindValue(Type spannerType, String pgType, Object value) {
+ ColumnBinding binding = bind(spannerType, pgType, value);
+ assertThat(binding.getPlaceholderSql()).isEqualTo("?");
+ assertThat(binding.getParams()).hasSize(1);
+ return binding.getParams().get(0);
+ }
+
+ private static PreparedStatementValue customValue(String pgType, Object value) {
+ ColumnBinding binding =
+ PostgreSQLDMLGenerator.getCustomValueBinding(srcCol("test_col", pgType), value);
+ assertThat(binding.getPlaceholderSql()).isEqualTo("?");
+ assertThat(binding.getParams()).hasSize(1);
+ return binding.getParams().get(0);
+ }
+
+ private static ISchemaMapper identityMapper(String tableName, String... columns) {
+ ISchemaMapper mapper = mock(ISchemaMapper.class);
+ when(mapper.getSourceTableName("", tableName)).thenReturn(tableName);
+ for (String col : columns) {
+ when(mapper.getSpannerColumnName("", tableName, col)).thenReturn(col);
+ }
+ return mapper;
+ }
+
+ // Format PreparedStatementValue parameters with readable SQL type names and hex bytes on failure.
+ private static void assertParams(@Nullable List> actual, PreparedStatementValue... expected) {
+ assertParams(actual, Arrays.asList(expected));
+ }
+
+ private static void assertParams(@Nullable List> actual, List> expected) {
+ assertWithMessage(
+ "PreparedStatement parameters mismatch\n actual: %s\n expected: %s",
+ describeParams(actual), describeParams(expected))
+ .that(actual)
+ .containsExactlyElementsIn(expected)
+ .inOrder();
+ }
+
+ private static String describeParams(@Nullable List> params) {
+ if (params == null) {
+ return "null";
+ }
+ List parts = new ArrayList<>(params.size());
+ for (Object item : params) {
+ if (item instanceof PreparedStatementValue) {
+ PreparedStatementValue psv = (PreparedStatementValue) item;
+ Object val = psv.getValue();
+ String formattedVal;
+ if (val instanceof byte[]) {
+ formattedVal = "bytes(0x" + HexFormat.of().formatHex((byte[]) val) + ")";
+ } else if (val instanceof String) {
+ formattedVal = "\"" + val + "\"";
+ } else {
+ formattedVal = String.valueOf(val);
+ }
+ parts.add("(" + sqlTypeName(psv.getSqlType()) + ", " + formattedVal + ")");
+ } else {
+ parts.add(String.valueOf(item));
+ }
+ }
+ return parts.toString();
+ }
+
+ private static String sqlTypeName(int sqlType) {
+ return switch (sqlType) {
+ case Types.VARCHAR -> "VARCHAR";
+ case Types.OTHER -> "OTHER";
+ case Types.VARBINARY -> "VARBINARY";
+ case Types.BOOLEAN -> "BOOLEAN";
+ case Types.DECIMAL -> "DECIMAL";
+ case Types.BIGINT -> "BIGINT";
+ case Types.DOUBLE -> "DOUBLE";
+ case Types.NULL -> "NULL";
+ default -> "sqlType=" + sqlType;
+ };
+ }
- // Verify that LastName=NULL results in unquoted NULL in VALUES list
- String[] parts = sql.split("VALUES");
- assertTrue(parts.length > 1);
- assertTrue(parts[1].contains("NULL"));
+ private static byte[] decodeBase64(String encoded) {
+ return Base64.getDecoder().decode(encoded);
}
}