From bad7025b026d7919d3a43e51c8a1b1126344ed1d Mon Sep 17 00:00:00 2001 From: aasthabharill Date: Wed, 2 Dec 2026 19:08:56 +0000 Subject: [PATCH 1/6] [SpannerToSourceDb] Migrate PostgreSQLDMLGenerator to PreparedStatement binding --- v2/spanner-to-sourcedb/README.md | 11 +- .../dbutils/dml/PreparedStatementValue.java | 22 +- .../postgres/PostgreSQLDMLGenerator.java | 881 +++++-- .../dml/PreparedStatementValueTest.java | 46 + .../postgres/PostgreSQLDMLGeneratorTest.java | 2157 ++++++++++++++--- 5 files changed, 2594 insertions(+), 523 deletions(-) diff --git a/v2/spanner-to-sourcedb/README.md b/v2/spanner-to-sourcedb/README.md index d96b0dbaef..ed4b65090a 100644 --- a/v2/spanner-to-sourcedb/README.md +++ b/v2/spanner-to-sourcedb/README.md @@ -386,11 +386,18 @@ Reverse transformation can not be supported for following scenarios out of the b 8. CLOB will not be read from GCS and put in source 9. DELETES on Spanner that have Primary key columns different from the Source database column - such records will be dropped 10. Primary key of the source table cannot be determined - such records will be dropped -11. **PostgreSQL:** Replicating array columns to native PostgreSQL array types (e.g., `varchar[]`) is not fully supported and is converted to comma-separated strings instead. +11. **PostgreSQL:** Replicating Spanner `ARRAY` columns is not supported out of the box (rejected by the shard-assignment stage). 12. **PostgreSQL:** Writing to non-default schemas (namespaces) is not supported; records will be written to the default schema of the connected user. In the above cases, custom code will need to be written to perform reverse transformation.Refer the [customization](#customize) section for the source code to extend and write these custom transforms. +#### PostgreSQL value handling notes + +- `sourceDbTimezoneOffset` is not applied for PostgreSQL; Spanner UTC timestamps are cast via `?::timestamptz` so PostgreSQL converts them using the database session timezone for `timestamp without time zone` columns. +- Non-finite floating-point values (`NaN`, `Infinity`, `-Infinity`) are bound directly for `real`, `double precision`, and `numeric` (`Infinity` on `numeric` requires PostgreSQL 14+). +- NUL (`U+0000`) characters are stripped from string values (including custom transformation outputs) because PostgreSQL text types cannot store NUL bytes. +- Spanner `BYTES` mapped to PostgreSQL character columns are formatted using PostgreSQL's default `bytea_output = hex` representation (`\x...`). + ## When to perform cut-back In the event that cut-back is needed to start serving from the original database instead for Spanner, following should be taken care: @@ -483,6 +490,8 @@ Steps to perform customization: 4. If any events are filtered/skipped during the reverse transformation they can be written to a GCS directory by passing the GCS path via the *filterEventsDirectoryName* input to the runner. 5. If any custom parameters are needed in the custom transformation logic, they can be passed via the *transformationCustomParameters* input to the runner. These parameters will be passed to the *init* method of the custom class. The *init* method is invoked once per worker setup. +> **Breaking change (PostgreSQL):** PostgreSQL reverse replication binds `toSourceRow()` output values strictly as `PreparedStatement` parameters (raw data), never as SQL fragments. Do **not** wrap string values in single quotes (`'abc'`) or return SQL expressions (such as `now()` or `decode(...)`), as quotes and function calls are now stored literally or rejected by PostgreSQL. Supported Java output types are `String`, `byte[]`, `Boolean`, `Long`, `Integer`, `Short`, `Byte`, `BigDecimal`, `BigInteger`, `Double`, `Float`, and `null`; any other object is converted via `toString()`. + ## Cost 1. Cloud Spanner change stream incur additional storage requirement, refer [here](https://cloud.google.com/spanner/docs/change-streams#data-retention). diff --git a/v2/spanner-to-sourcedb/src/main/java/com/google/cloud/teleport/v2/templates/dbutils/dml/PreparedStatementValue.java b/v2/spanner-to-sourcedb/src/main/java/com/google/cloud/teleport/v2/templates/dbutils/dml/PreparedStatementValue.java index 5ffb4121e6..411478be40 100644 --- a/v2/spanner-to-sourcedb/src/main/java/com/google/cloud/teleport/v2/templates/dbutils/dml/PreparedStatementValue.java +++ b/v2/spanner-to-sourcedb/src/main/java/com/google/cloud/teleport/v2/templates/dbutils/dml/PreparedStatementValue.java @@ -32,7 +32,8 @@ * *

The value is always one of {@code String}, {@code byte[]}, {@code Boolean}, {@code * BigDecimal}, {@code Long}, {@code Double} or {@code null}. The {@link #getSqlType() SQL type} is - * used to bind {@code null} values via {@link PreparedStatement#setNull(int, int)}. + * used to bind {@code null} values via {@link PreparedStatement#setNull(int, int)} and to + * distinguish untyped strings ({@link Types#OTHER}) from typed {@code VARCHAR} strings. */ public final class PreparedStatementValue { @@ -50,6 +51,19 @@ public static PreparedStatementValue ofString(@Nullable String value) { : new PreparedStatementValue(value, Types.VARCHAR); } + /** + * Returns an untyped string binding ({@link Types#OTHER}). + * + *

Used by PostgreSQL ({@code pgjdbc}), which transmits {@link Types#OTHER} strings with OID + * {@code UNSPECIFIED} ({@code 0}) so the server parses the bound parameter using the target + * column's input function (for example {@code jsonb}, {@code uuid}, {@code date}, {@code time}, + * {@code real}, arrays, or enums) instead of rejecting {@code VARCHAR}. Other JDBC drivers may + * interpret {@link Types#OTHER} differently. + */ + public static PreparedStatementValue ofUntypedString(@Nullable String value) { + return value == null ? nullValue(Types.OTHER) : new PreparedStatementValue(value, Types.OTHER); + } + public static PreparedStatementValue ofBytes(@Nullable byte[] value) { return value == null ? nullValue(Types.VARBINARY) @@ -136,11 +150,15 @@ public boolean isNull() { /** * Binds this value to parameter {@code paramIdx} of {@code statement} with the setter of its Java - * type, or {@link PreparedStatement#setNull(int, int)} with its SQL type for {@code null}. + * type, {@link PreparedStatement#setObject(int, Object, int)} for {@link Types#OTHER} untyped + * strings, or {@link PreparedStatement#setNull(int, int)} with its SQL type for {@code null}. */ public void bind(PreparedStatement statement, int paramIdx) throws SQLException { if (value == null) { statement.setNull(paramIdx, sqlType); + } else if (sqlType == Types.OTHER) { + // pgjdbc sends OID UNSPECIFIED (0) so PostgreSQL infers the target column type. + statement.setObject(paramIdx, value, Types.OTHER); } else if (value instanceof byte[]) { statement.setBytes(paramIdx, (byte[]) value); } else if (value instanceof String) { diff --git a/v2/spanner-to-sourcedb/src/main/java/com/google/cloud/teleport/v2/templates/source/postgres/PostgreSQLDMLGenerator.java b/v2/spanner-to-sourcedb/src/main/java/com/google/cloud/teleport/v2/templates/source/postgres/PostgreSQLDMLGenerator.java index dbc95192d5..58aaeca807 100644 --- a/v2/spanner-to-sourcedb/src/main/java/com/google/cloud/teleport/v2/templates/source/postgres/PostgreSQLDMLGenerator.java +++ b/v2/spanner-to-sourcedb/src/main/java/com/google/cloud/teleport/v2/templates/source/postgres/PostgreSQLDMLGenerator.java @@ -23,23 +23,203 @@ import com.google.cloud.teleport.v2.spanner.sourceddl.SourceSchema; 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.dbutils.dml.ColumnBinding; import com.google.cloud.teleport.v2.templates.dbutils.dml.DMLGeneratorUtils; import com.google.cloud.teleport.v2.templates.dbutils.dml.IDMLGenerator; +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.common.annotations.VisibleForTesting; +import com.google.common.base.Preconditions; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableSet; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.sql.Types; import java.util.ArrayList; +import java.util.Base64; +import java.util.HashSet; +import java.util.HexFormat; import java.util.List; +import java.util.Locale; import java.util.Map; import java.util.NoSuchElementException; +import java.util.Set; +import java.util.regex.Pattern; import java.util.stream.Collectors; +import javax.annotation.Nullable; import org.apache.commons.lang3.StringUtils; +import org.json.JSONException; import org.json.JSONObject; -/** Creates DML statements for PostgreSQL. */ +/** + * Generates parameterized DML statements for PostgreSQL. + * + *

Every column value (including {@code NULL}s, custom transformation outputs, and unknown column + * types) is bound as a {@link java.sql.PreparedStatement} parameter. Only template-generated SQL + * and double-quote-escaped identifiers appear in the SQL text. + * + *

PostgreSQL does not implicitly cast {@code VARCHAR} parameters (sent by {@code pgjdbc} for + * {@code setString}) into strictly typed columns such as {@code jsonb}, {@code uuid}, {@code date}, + * {@code time}, arrays, or enums. Bindings are therefore dispatched once by the PostgreSQL column + * category: + * + *

+ */ public class PostgreSQLDMLGenerator implements IDMLGenerator { + /** SQL fragment casting a bound UTC timestamp string to {@code timestamptz}. */ + private static final String TIMESTAMPTZ_PLACEHOLDER = "?::timestamptz"; + + /** PostgreSQL NUMERIC precision limits (up to 131072 integer digits, scale up to 16383). */ + private static final int PG_NUMERIC_MAX_INTEGER_DIGITS = 131072; + + private static final int PG_NUMERIC_MAX_SCALE = 16383; + + /** + * Character length cap for Java {@link BigDecimal#BigDecimal(String)} parsing to prevent CPU DoS + * on huge digit strings. Longer values fall back to {@link + * PreparedStatementValue#ofUntypedString} so PostgreSQL's native parser handles them. + */ + private static final int MAX_BIG_DECIMAL_TEXT_LENGTH = 2048; + + /** Matches parenthesized type modifiers such as {@code (255)} or {@code (10, 2)}. */ + private static final Pattern PAREN_MODIFIER = Pattern.compile("\\([^)]*\\)"); + + /** Matches runs of whitespace when normalizing PostgreSQL type names. */ + private static final Pattern WHITESPACE = Pattern.compile("\\s+"); + + /** Matches signed base-10 integer literals (for example {@code -42}, {@code +7}). */ + private static final Pattern INTEGER_LITERAL = Pattern.compile("[+-]?\\d+"); + + /** Matches fixed-point decimal literals (for example {@code 1.5}, {@code .5}, {@code 5.}). */ + private static final Pattern DECIMAL_LITERAL = Pattern.compile("[+-]?(\\d+\\.\\d*|\\.\\d+)"); + + /** Matches scientific-notation numeric literals (for example {@code 1.25E-10}). */ + private static final Pattern SCIENTIFIC_LITERAL = + Pattern.compile("[+-]?(\\d+(\\.\\d*)?|\\.\\d+)[eE][+-]?\\d+"); + + /** Lower-cased text of non-finite float / numeric literals. */ + private static final ImmutableSet NON_FINITE_VALUES = + ImmutableSet.of("nan", "infinity", "+infinity", "-infinity"); + + /** + * Column binding mapper delegating non-null and null Spanner values to {@link + * #getMappedColumnBinding} and {@link #getNullColumnBinding} (preserving {@code ?::timestamptz} + * for null timestamp columns). + */ + private static final DMLGeneratorUtils.ColumnBindingMapper COLUMN_BINDING_MAPPER = + new DMLGeneratorUtils.ColumnBindingMapper() { + @Override + public ColumnBinding getColumnBinding( + Column spannerColDef, + SourceColumn sourceColDef, + JSONObject valuesJson, + String sourceDbTimezoneOffset) { + return getMappedColumnBinding( + spannerColDef, sourceColDef, valuesJson, sourceDbTimezoneOffset); + } + + @Override + public ColumnBinding getNullColumnBinding(Column spannerColDef, SourceColumn sourceColDef) { + return PostgreSQLDMLGenerator.getNullColumnBinding(sourceColDef); + } + }; + + /** + * 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, + FLOAT4, + FLOAT8, + DECIMAL, + OTHER; + + static PgColumnType fromSourceType(@Nullable String rawPgType) { + String normalized = normalizeSourceType(rawPgType); + if (isTimestampName(normalized)) { + return TIMESTAMP; + } + switch (normalized) { + case "varchar": + case "character varying": + case "char": + case "character": + case "bpchar": + case "text": + case "name": + return CHARACTER; + case "boolean": + case "bool": + return BOOLEAN; + case "smallint": + case "int2": + case "integer": + case "int": + case "int4": + case "bigint": + case "int8": + case "smallserial": + case "serial": + case "bigserial": + return INTEGER; + case "real": + case "float4": + return FLOAT4; + case "double precision": + case "float8": + return FLOAT8; + case "numeric": + case "decimal": + return DECIMAL; + default: + // Includes bytea, json/jsonb, uuid, date/time, arrays, USER-DEFINED (enums/citext/ + // domains), and unknown types. All bind untyped via Types.OTHER so PostgreSQL resolves + // the column's exact type and operators. + return OTHER; + } + } + + private static boolean isTimestampName(String normalized) { + return "timestamp".equals(normalized) + || "timestamp without time zone".equals(normalized) + || "timestamp with time zone".equals(normalized) + || "timestamptz".equals(normalized); + } + } + @Override public DMLGeneratorResponse getDMLStatement(DMLGeneratorRequest dmlGeneratorRequest) { if (dmlGeneratorRequest == null) { @@ -68,7 +248,7 @@ public DMLGeneratorResponse getDMLStatement(DMLGeneratorRequest dmlGeneratorRequ "The spanner table %s was not found in ddl found on spanner", spannerTableName)); } - String sourceTableName = ""; + String sourceTableName; try { sourceTableName = schemaMapper.getSourceTableName("", spannerTableName); } catch (NoSuchElementException e) { @@ -83,15 +263,17 @@ public DMLGeneratorResponse getDMLStatement(DMLGeneratorRequest dmlGeneratorRequ sourceTableName, spannerTableName)); } - if (sourceTable.primaryKeyColumns() == null || sourceTable.primaryKeyColumns().size() == 0) { + if (sourceTable.primaryKeyColumns() == null || sourceTable.primaryKeyColumns().isEmpty()) { throw new InvalidDMLGenerationException( String.format( - "Cannot reverse replicate for source table %s without primary key, skipping the record.", + "Cannot reverse replicate for source table %s without primary key, skipping the" + + " record.", sourceTableName)); } - Map pkcolumnNameValues = - DMLGeneratorUtils.getPkColumnValues( + // Resolve primary key bindings first; missing PK values make both upserts and deletes invalid. + Map pkColumnBindings = + DMLGeneratorUtils.getPkColumnBindings( schemaMapper, spannerTable, sourceTable, @@ -99,9 +281,9 @@ public DMLGeneratorResponse getDMLStatement(DMLGeneratorRequest dmlGeneratorRequ dmlGeneratorRequest.getKeyValuesJson(), dmlGeneratorRequest.getSourceDbTimezoneOffset(), dmlGeneratorRequest.getCustomTransformationResponse(), - PostgreSQLDMLGenerator::getMappedColumnValue, - new ArrayList<>()); - if (pkcolumnNameValues == null || pkcolumnNameValues.isEmpty()) { + COLUMN_BINDING_MAPPER, + PostgreSQLDMLGenerator::getCustomValueBinding); + if (pkColumnBindings == null || pkColumnBindings.isEmpty()) { throw new InvalidDMLGenerationException( String.format( "Cannot reverse replicate for table %s without primary key, skipping the record", @@ -111,10 +293,9 @@ public DMLGeneratorResponse getDMLStatement(DMLGeneratorRequest dmlGeneratorRequ if ("INSERT".equals(dmlGeneratorRequest.getModType()) || "UPDATE".equals(dmlGeneratorRequest.getModType())) { return generateUpsertStatement( - spannerTable, sourceTable, dmlGeneratorRequest, pkcolumnNameValues); - + spannerTable, sourceTable, dmlGeneratorRequest, pkColumnBindings); } else if ("DELETE".equals(dmlGeneratorRequest.getModType())) { - return getDeleteStatement(sourceTable.name(), pkcolumnNameValues); + return getDeleteStatement(sourceTable.name(), pkColumnBindings); } else { throw new InvalidDMLGenerationException( String.format( @@ -123,82 +304,109 @@ public DMLGeneratorResponse getDMLStatement(DMLGeneratorRequest dmlGeneratorRequ } } + /** + * Builds {@code INSERT INTO "t" ("c1",...) VALUES (?,...) ON CONFLICT ("pk",...) DO UPDATE SET + * "c1" = EXCLUDED."c1",...} (or {@code DO NOTHING} when all columns are primary keys). + */ private static DMLGeneratorResponse getUpsertStatement( - String tableName, Map allColumnNameValues, List primaryKeys) { - - StringBuilder allColumns = new StringBuilder(); - StringBuilder allValues = new StringBuilder(); - - int index = 0; - - for (Map.Entry entry : allColumnNameValues.entrySet()) { - String colName = entry.getKey(); - String colValue = entry.getValue(); - String sqlValue = (colValue == null) ? "NULL" : colValue; - allColumns.append("\"").append(colName).append("\""); - allValues.append(sqlValue); + String tableName, Map allColumnBindings, List primaryKeys) { + List columns = new ArrayList<>(allColumnBindings.size()); + List values = new ArrayList<>(allColumnBindings.size()); + List params = new ArrayList<>(allColumnBindings.size()); - // Add comma if not the last item in this loop - if (index + 1 < allColumnNameValues.size()) { - allColumns.append(","); - allValues.append(","); - } - index++; + // PostgreSQL references the proposed row via EXCLUDED."col", so each parameter is bound once. + for (Map.Entry entry : allColumnBindings.entrySet()) { + columns.add(quoteIdentifier(entry.getKey())); + ColumnBinding binding = entry.getValue(); + values.add(binding.getPlaceholderSql()); + params.addAll(binding.getParams()); } String conflictCols = - primaryKeys.stream().map(k -> "\"" + k + "\"").collect(Collectors.joining(",")); + primaryKeys.stream() + .map(PostgreSQLDMLGenerator::quoteIdentifier) + .collect(Collectors.joining(",")); + Set pkSet = new HashSet<>(primaryKeys); String updateValues = - allColumnNameValues.keySet().stream() - .filter(k -> !primaryKeys.contains(k)) - .map(k -> "\"" + k + "\" = EXCLUDED.\"" + k + "\"") + allColumnBindings.keySet().stream() + .filter(k -> !pkSet.contains(k)) + .map( + k -> { + String quoted = quoteIdentifier(k); + return quoted + " = EXCLUDED." + quoted; + }) .collect(Collectors.joining(",")); - String returnVal = - "INSERT INTO \"" - + tableName - + "\" (" - + allColumns.toString() - + ") VALUES (" - + allValues.toString() - + ")"; - + StringBuilder sql = + new StringBuilder("INSERT INTO ") + .append(quoteIdentifier(tableName)) + .append(" (") + .append(String.join(",", columns)) + .append(") VALUES (") + .append(String.join(",", values)) + .append(") ON CONFLICT (") + .append(conflictCols) + .append(") "); if (updateValues.isEmpty()) { - returnVal += " ON CONFLICT (" + conflictCols + ") DO NOTHING"; + sql.append("DO NOTHING"); } else { - returnVal += " ON CONFLICT (" + conflictCols + ") DO UPDATE SET " + updateValues; + sql.append("DO UPDATE SET ").append(updateValues); } - return new DMLGeneratorResponse(returnVal); + return newResponse(sql.toString(), params); } + /** + * Builds {@code DELETE FROM "t" WHERE "pk1" = ? AND ...}. Columns whose value is {@code NULL} in + * this record (for example non-PK columns included when the table has a generated primary key) + * emit {@code IS NULL} instead of {@code = ?} because {@code = NULL} never matches in SQL. + */ private static DMLGeneratorResponse getDeleteStatement( - String tableName, Map pkcolumnNameValues) { - String deleteValues = ""; - - int index = 0; - for (Map.Entry entry : pkcolumnNameValues.entrySet()) { - String colName = entry.getKey(); - String colValue = entry.getValue(); - - deleteValues += " \"" + colName + "\" = " + colValue; - if (index + 1 < pkcolumnNameValues.size()) { - deleteValues += " AND "; + String tableName, Map pkColumnBindings) { + List conditions = new ArrayList<>(pkColumnBindings.size()); + List params = new ArrayList<>(pkColumnBindings.size()); + for (Map.Entry entry : pkColumnBindings.entrySet()) { + ColumnBinding binding = entry.getValue(); + if (isNullBinding(binding)) { + conditions.add(quoteIdentifier(entry.getKey()) + " IS NULL"); + } else { + conditions.add(quoteIdentifier(entry.getKey()) + " = " + binding.getPlaceholderSql()); + params.addAll(binding.getParams()); } - index++; } - String returnVal = "DELETE FROM \"" + tableName + "\" WHERE " + deleteValues; + String sql = + "DELETE FROM " + quoteIdentifier(tableName) + " WHERE " + String.join(" AND ", conditions); + return newResponse(sql, params); + } + + /** + * Returns {@code true} if {@code binding} represents a single SQL {@code NULL} value regardless + * of whether its placeholder carries a type cast (such as {@code ?::timestamptz}). + */ + @VisibleForTesting + static boolean isNullBinding(ColumnBinding binding) { + return binding.getParams().size() == 1 && binding.getParams().get(0).isNull(); + } - return new DMLGeneratorResponse(returnVal); + private static DMLGeneratorResponse newResponse(String sql, List params) { + DMLGeneratorResponse response = new DMLGeneratorResponse(sql); + response.setPreparedStatementParameters(params); + return response; } private static DMLGeneratorResponse generateUpsertStatement( Table spannerTable, SourceTable sourceTable, DMLGeneratorRequest dmlGeneratorRequest, - Map pkcolumnNameValues) { - Map columnNameValues = - DMLGeneratorUtils.getColumnValues( + Map pkColumnBindings) { + // When any PK column is generated, getPkColumnBindings already includes all non-PK columns; + // reuse that map directly instead of resolving non-PK columns twice. + if (hasGeneratedPrimaryKey(sourceTable)) { + return getUpsertStatement( + sourceTable.name(), pkColumnBindings, sourceTable.primaryKeyColumns()); + } + Map columnBindings = + DMLGeneratorUtils.getColumnBindings( dmlGeneratorRequest.getSchemaMapper(), spannerTable, sourceTable, @@ -206,123 +414,476 @@ private static DMLGeneratorResponse generateUpsertStatement( dmlGeneratorRequest.getKeyValuesJson(), dmlGeneratorRequest.getSourceDbTimezoneOffset(), dmlGeneratorRequest.getCustomTransformationResponse(), - PostgreSQLDMLGenerator::getMappedColumnValue, - new ArrayList<>()); - columnNameValues.putAll(pkcolumnNameValues); - return getUpsertStatement( - sourceTable.name(), columnNameValues, sourceTable.primaryKeyColumns()); + COLUMN_BINDING_MAPPER, + PostgreSQLDMLGenerator::getCustomValueBinding); + columnBindings.putAll(pkColumnBindings); + return getUpsertStatement(sourceTable.name(), columnBindings, sourceTable.primaryKeyColumns()); + } + + private static boolean hasGeneratedPrimaryKey(SourceTable sourceTable) { + for (String pkColName : sourceTable.primaryKeyColumns()) { + SourceColumn col = sourceTable.column(pkColName); + if (col != null && col.isGenerated()) { + return true; + } + } + return false; + } + + /** + * 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, "\"", "\"\"") + "\""; } + /** + * Returns a SQL {@code NULL} binding whose placeholder matches the non-null placeholder of the + * PostgreSQL column so the generated SQL text stays stable for {@code pgjdbc} statement caching. + */ @VisibleForTesting - static String getMappedColumnValue( + static ColumnBinding getNullColumnBinding(SourceColumn sourceColDef) { + PgColumnType pgType = PgColumnType.fromSourceType(sourceColDef.type()); + if (pgType == PgColumnType.TIMESTAMP) { + return ColumnBinding.of( + TIMESTAMPTZ_PLACEHOLDER, ImmutableList.of(PreparedStatementValue.nullValue(Types.NULL))); + } + return ColumnBinding.of(PreparedStatementValue.nullValue(Types.NULL)); + } + + /** + * 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 ColumnBinding getMappedColumnBinding( Column spannerColDef, SourceColumn sourceColDef, JSONObject valuesJson, - String sourceDbTimezoneOffset, - List preparedStatementParameters) { - - String colInputValue = ""; + String sourceDbTimezoneOffset) { 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; + + switch (pgType) { + case CHARACTER: + String charValue = getSpannerTextValue(colType, valuesJson, colName); + return ColumnBinding.of(PreparedStatementValue.ofString(removeNullBytes(charValue))); + case TIMESTAMP: + // Spanner timestamps are UTC. Casting via ?::timestamptz converts to the database session + // timezone for timestamp-without-tz columns (sourceDbTimezoneOffset is not applied). + String tsValue = getSpannerTextValue(colType, valuesJson, colName); + return ColumnBinding.of( + TIMESTAMPTZ_PLACEHOLDER, + ImmutableList.of(PreparedStatementValue.ofUntypedString(removeNullBytes(tsValue)))); + case BOOLEAN: + return ColumnBinding.of(getBooleanBindingValue(colType, valuesJson, colName)); + case INTEGER: + case FLOAT4: + case FLOAT8: + case DECIMAL: + return ColumnBinding.of(getNumberBindingValue(colType, pgType, valuesJson, colName)); + case OTHER: + default: + // Structured, temporal, binary-from-string, arrays (e.g. from Spanner STRING), + // USER-DEFINED (enums/domains), and unknown columns use Types.OTHER so pgjdbc sends OID + // UNSPECIFIED and PostgreSQL infers the type. + // TODO: Add PostgreSQL array literal formatting and ?::timestamptz[] casting when + // AssignShardIdFn supports Spanner ARRAY columns end-to-end. + String otherValue = getSpannerTextValue(colType, valuesJson, colName); + return ColumnBinding.of( + PreparedStatementValue.ofUntypedString(removeNullBytes(otherValue))); + } + } catch (JSONException | NumberFormatException e) { + // Omit the cause because org.json's JSONException and NumberFormatException embed raw column + // values in their messages, which SourceWriterFn appends to DLQ error records. + throw new InvalidDMLGenerationException( + String.format( + "Failed to convert column %s (Spanner type %s, PostgreSQL type %s): %s", + sourceColDef.name(), colType, sourceColDef.type(), e.getClass().getSimpleName())); + } catch (IllegalArgumentException e) { + // Preserve cause/stack trace for non-value-bearing errors such as invalid Base64 decoding. + throw new InvalidDMLGenerationException( + String.format( + "Failed to convert column %s (Spanner type %s, PostgreSQL type %s): %s", + sourceColDef.name(), colType, sourceColDef.type(), e.getClass().getSimpleName()), + 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) { + static ColumnBinding getCustomValueBinding( + SourceColumn sourceColDef, @Nullable Object customValue) { + if (customValue == null || JSONObject.NULL.equals(customValue)) { + return ColumnBinding.of(PreparedStatementValue.nullValue(Types.NULL)); + } + PgColumnType pgType = PgColumnType.fromSourceType(sourceColDef.type()); + + // Character columns must always receive VARCHAR (never bytea/number/bool OIDs) so DELETE works. + if (pgType == PgColumnType.CHARACTER) { + if (customValue instanceof byte[]) { + return ColumnBinding.of( + PreparedStatementValue.ofString(toPostgresHexByteaText((byte[]) customValue))); + } + return ColumnBinding.of( + PreparedStatementValue.ofString(removeNullBytes(customValue.toString()))); + } + + // Raw byte[] targeting non-character columns binds directly via setBytes. + if (customValue instanceof byte[]) { + return ColumnBinding.of(PreparedStatementValue.ofBytes((byte[]) customValue)); + } + + switch (pgType) { + case BOOLEAN: + if (customValue instanceof Boolean) { + return ColumnBinding.of(PreparedStatementValue.ofBoolean((Boolean) customValue)); + } + return ColumnBinding.of(booleanTextToParam(customValue.toString())); + case INTEGER: + case FLOAT4: + case FLOAT8: + case DECIMAL: + return ColumnBinding.of(customNumberToParam(customValue, pgType)); + case TIMESTAMP: + case OTHER: + default: + // Custom timestamp values use plain '?' without ::timestamptz so user-formatted values are + // not double-converted; structured/array/unknown types bind untyped via Types.OTHER. + return ColumnBinding.of( + PreparedStatementValue.ofUntypedString(removeNullBytes(customValue.toString()))); + } + } + + private static PreparedStatementValue getBooleanBindingValue( + Type colType, JSONObject valuesJson, String colName) { + Type.Code code = colType.getCode(); + if (code == Type.Code.BOOL || code == Type.Code.PG_BOOL) { + return PreparedStatementValue.ofBoolean(valuesJson.getBoolean(colName)); + } + return booleanTextToParam(getSpannerTextValue(colType, valuesJson, colName)); + } + + private static PreparedStatementValue booleanTextToParam(String value) { + String cleaned = 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 PreparedStatementValue getNumberBindingValue( + Type colType, PgColumnType pgType, JSONObject valuesJson, String colName) { + // Bind real (float4) untyped so PostgreSQL always resolves float4in/float4eq even when pgjdbc + // binaryTransfer is disabled (where setFloat falls back to OID float8). + if (pgType == PgColumnType.FLOAT4) { + String text = getSpannerTextValue(colType, valuesJson, colName); + return PreparedStatementValue.ofUntypedString(removeNullBytes(text)); + } + + Type.Code code = colType.getCode(); + if (DMLGeneratorUtils.isFloatOrPgNumeric(code) || code == Type.Code.NUMERIC) { + String nonFiniteText = DMLGeneratorUtils.getNonFiniteText(valuesJson, colName); + if (nonFiniteText != null) { + return nonFiniteToNumberParam(nonFiniteText, pgType); + } + Object raw = valuesJson.get(colName); + // Dispatch Double/Float directly so -0.0 keeps its sign bit (org.json parses -0.0 as Double + // and getBigDecimal would drop the sign) and numeric targets avoid new BigDecimal(double) + // binary expansion. + if (raw instanceof Double || raw instanceof Float) { + return floatingNumberToParam((Number) raw, pgType); + } + // Guard against O(N^2) BigDecimal parsing on oversized numeric strings before getBigDecimal. + if (raw instanceof String && ((String) raw).trim().length() > MAX_BIG_DECIMAL_TEXT_LENGTH) { + return PreparedStatementValue.ofUntypedString(removeNullBytes((String) raw)); + } + BigDecimal decimalValue = valuesJson.getBigDecimal(colName); + String originalText = (raw instanceof String) ? removeNullBytes((String) raw) : null; + return decimalToNumberParam(decimalValue, pgType, originalText); + } + + 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); + } + return numberTextToParam((raw instanceof String) ? (String) raw : raw.toString(), pgType); + } + + String stringValue = getSpannerTextValue(colType, valuesJson, colName); + return numberTextToParam(stringValue, pgType); + } + + private static PreparedStatementValue customNumberToParam( + Object customValue, PgColumnType pgType) { + // Bind real (float4) untyped so PostgreSQL always resolves float4 regardless of transfer mode. + if (pgType == PgColumnType.FLOAT4) { + return PreparedStatementValue.ofUntypedString(removeNullBytes(customValue.toString())); + } + if (customValue instanceof String) { + return numberTextToParam((String) customValue, pgType); + } + 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(removeNullBytes(customValue.toString())); + } + + private static PreparedStatementValue longToNumberParam(long value, PgColumnType pgType) { + if (pgType == PgColumnType.FLOAT8) { + return PreparedStatementValue.ofDouble((double) value); + } + if (pgType == PgColumnType.DECIMAL) { + return PreparedStatementValue.ofBigDecimal(BigDecimal.valueOf(value)); + } + // OID INT8 (20) uses int2/int4/int8 B-tree indexes on DELETE. + return PreparedStatementValue.ofLong(value); + } + + private static PreparedStatementValue decimalToNumberParam( + BigDecimal decimalValue, PgColumnType pgType, @Nullable String originalText) { + if (pgType == PgColumnType.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)) { + return PreparedStatementValue.ofDouble(d); + } + return PreparedStatementValue.ofUntypedString( + originalText != null ? originalText : decimalValue.toString()); + } + if (pgType == PgColumnType.INTEGER) { + try { + return 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. + } + } + 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 nonFiniteText, PgColumnType pgType) { + if (pgType == PgColumnType.FLOAT8) { + return PreparedStatementValue.ofDouble(parseNonFiniteDouble(nonFiniteText)); + } + // 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(nonFiniteText); + } + + /** + * Converts a string targeting a PostgreSQL number 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}; {@code real} and any non-numeric, + * oversized, or out-of-bounds text bind via {@link Types#OTHER} as data. + */ + private static PreparedStatementValue numberTextToParam(String value, PgColumnType pgType) { + String cleaned = removeNullBytes(value); + PreparedStatementValue typed = tryParseNumber(cleaned.trim(), cleaned, pgType); + return typed != null ? typed : PreparedStatementValue.ofUntypedString(cleaned); + } + + @Nullable + private static PreparedStatementValue tryParseNumber( + String trimmed, String cleaned, PgColumnType pgType) { + if (trimmed.isEmpty()) { return null; } - return rawHex.isEmpty() ? "''" : "'\\x" + rawHex + "'"; + if (isNonFiniteLiteral(trimmed)) { + return nonFiniteToNumberParam(trimmed, pgType); + } + if (trimmed.length() > MAX_BIG_DECIMAL_TEXT_LENGTH) { + return null; + } + 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 null; + } + } + return null; } - 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; + private static boolean isWithinPostgresNumericBounds(BigDecimal bd) { + long scale = bd.scale(); + long integerDigits = (long) bd.precision() - scale; + return scale <= PG_NUMERIC_MAX_SCALE && integerDigits <= PG_NUMERIC_MAX_INTEGER_DIGITS; + } + + private static double parseNonFiniteDouble(String text) { + String lower = text.trim().toLowerCase(Locale.ROOT); + if ("nan".equals(lower)) { + return Double.NaN; } - return response; + if ("-infinity".equals(lower)) { + return Double.NEGATIVE_INFINITY; + } + return Double.POSITIVE_INFINITY; + } + + /** + * 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(); + } + return new BigDecimal(raw.toString()).stripTrailingZeros().toPlainString(); + } + BigDecimal bd = valuesJson.getBigDecimal(colName); + return isWithinPostgresNumericBounds(bd) ? bd.toPlainString() : bd.toString(); + } + if (DMLGeneratorUtils.isFloatOrPgNumeric(code)) { + // PG_NUMERIC is handled above; remaining codes are FLOAT32/FLOAT64/PG_FLOAT4/PG_FLOAT8. + Object raw = valuesJson.get(colName); + if (raw instanceof String) { + String trimmed = ((String) raw).trim(); + return isNonFiniteLiteral(trimmed) ? trimmed : (String) raw; + } + if (raw instanceof Double || raw instanceof Float) { + return raw.toString(); + } + return DMLGeneratorUtils.getSpannerValueAsString(colType, valuesJson, colName); + } + 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(); + } + + private static boolean isNonFiniteLiteral(@Nullable String text) { + return text != null && NON_FINITE_VALUES.contains(text.trim().toLowerCase(Locale.ROOT)); } - 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; + /** Strips NUL ({@code U+0000}) characters, which PostgreSQL rejects in UTF-8 text. */ + private static String removeNullBytes(String input) { + return StringUtils.replace(input, "\u0000", ""); } - static String getQuotedEscapedString(String input, String spannerColType) { - if ("BYTES".equals(spannerColType) || "PG_BYTEA".equals(spannerColType)) { - return input; + /** + * 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); + } + + /** + * Normalizes a PostgreSQL column type string by stripping parenthesized modifiers, collapsing + * whitespace, preserving the {@code []} array suffix, and lowercasing. + */ + @VisibleForTesting + static String normalizeSourceType(@Nullable String pgType) { + if (pgType == null) { + return ""; } - String cleanedString = escapeString(input); - String response = "'" + cleanedString + "'"; - return response; + String withoutModifiers = PAREN_MODIFIER.matcher(pgType).replaceAll(" "); + String collapsed = WHITESPACE.matcher(withoutModifiers).replaceAll(" ").trim(); + return StringUtils.replace(collapsed, " []", "[]").toLowerCase(Locale.ROOT); } } 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..269875461c 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 @@ -108,6 +108,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()); + assertEquals(null, 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 +167,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 +198,13 @@ public void testEqualsHashCodeAndToString() { assertEquals( "PreparedStatementValue{value=a, sqlType=12}", PreparedStatementValue.ofString("a").toString()); + + PreparedStatementValue untyped = PreparedStatementValue.ofUntypedString("x"); + PreparedStatementValue typed = PreparedStatementValue.ofString("x"); + assertFalse(untyped.equals(typed)); + assertFalse(typed.equals(untyped)); + assertEquals(untyped, PreparedStatementValue.ofUntypedString("x")); + assertEquals(untyped.hashCode(), PreparedStatementValue.ofUntypedString("x").hashCode()); + assertEquals("PreparedStatementValue{value=x, sqlType=1111}", 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..9fa62d35ec 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,20 @@ 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"; + JSONObject newValuesJson = new JSONObject().put("FirstName", "kk").put("LastName", "ll"); + JSONObject keyValuesJson = new JSONObject().put("SomeRandomName", "999"); - 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())); + new PostgreSQLDMLGenerator() + .getDMLStatement( + new DMLGeneratorRequest.Builder( + "INSERT", "Singers", newValuesJson, keyValuesJson, "+00:00") + .setSchemaMapper(schemaMapper) + .setDdl(ddl) + .setSourceSchema(sourceSchema) + .build())); } @Test @@ -146,119 +163,45 @@ 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"; + JSONObject newValuesJson = new JSONObject().put("FirstName", "kk").put("LastName", "ll"); + JSONObject keyValuesJson = new JSONObject().put("SingerId", "999"); - 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())); + new PostgreSQLDMLGenerator() + .getDMLStatement( + new DMLGeneratorRequest.Builder( + "INSERT", "Singers", newValuesJson, keyValuesJson, "+00:00") + .setSchemaMapper(schemaMapper) + .setDdl(ddl) + .setSourceSchema(sourceSchema) + .build())); } @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)); - // Request with null mapper Ddl ddl = Ddl.builder().build(); SourceSchema sourceSchema = SourceSchema.builder(SourceDatabaseType.POSTGRESQL).databaseName("test").build(); @@ -349,7 +323,6 @@ public void testNullValiationsRequest() { ISchemaMapper schemaMapper = new SessionBasedMapper("src/test/resources/allMatchSession.json", ddl); - // Request with null ddl assertThrows( InvalidDMLGenerationException.class, () -> @@ -361,7 +334,6 @@ public void testNullValiationsRequest() { .setSourceSchema(sourceSchema) .build())); - // Request with null source schema assertThrows( InvalidDMLGenerationException.class, () -> @@ -381,122 +353,1457 @@ public void testUnsupportedModType() { SourceSchema sourceSchema = SchemaUtils.buildSourceSchemaFromSessionFile(sessionFile); ISchemaMapper schemaMapper = new SessionBasedMapper(sessionFile, ddl); - PostgreSQLDMLGenerator generator = new PostgreSQLDMLGenerator(); - 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())); + new PostgreSQLDMLGenerator() + .getDMLStatement( + new DMLGeneratorRequest.Builder( + "REPLACE", + "Singers", + new JSONObject().put("FirstName", "a"), + new JSONObject().put("SingerId", "1"), + "+00:00") + .setSchemaMapper(schemaMapper) + .setDdl(ddl) + .setSourceSchema(sourceSchema) + .build())); } @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 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")); + } - // Invalid base64 - assertThrows( - IllegalArgumentException.class, - () -> PostgreSQLDMLGenerator.convertBase64ToHex("invalid-base64!")); + @Test + 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.getCause()).isInstanceOf(IllegalArgumentException.class); + assertThat(bytesEx.getMessage()).contains("test_col"); + assertThat(bytesEx.getMessage()).contains("bytea"); + assertThat(bytesEx.getMessage()).contains("IllegalArgumentException"); + assertThat(bytesEx.getMessage()).doesNotContain(badSecretBase64); + assertThat(bytesEx.getCause().getMessage()).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.getCause()).isNull(); + assertThat(jsonEx.getMessage()).contains("test_col"); + assertThat(jsonEx.getMessage()).contains("JSONException"); + assertThat(jsonEx.getMessage()).doesNotContain("secret-not-a-json-bool"); } @Test - public void testNonByteaDecodeBranch() { - // Mocking Spanner Column + 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 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(6) WITH TIME ZONE" + }) { + ColumnBinding nonNull = bind(spannerTsType, tsType, "2023-05-18T12:01:13.088397258Z"); + assertThat(nonNull.getPlaceholderSql()).isEqualTo("?::timestamptz"); + assertThat(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 = + PostgreSQLDMLGenerator.getNullColumnBinding(srcCol("ts", tsType)); + assertThat(nullBinding.getPlaceholderSql()).isEqualTo("?::timestamptz"); + assertThat(PostgreSQLDMLGenerator.isNullBinding(nullBinding)).isTrue(); + assertThat(nullBinding.getParams()) + .containsExactly(PreparedStatementValue.nullValue(Types.NULL)); + } + } + } + + @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")); + } + + @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", "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"))); + } + + @Test + public void testNumericIntegerAndDecimalBindings() { + // Integer targets: 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("")); + + // 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(10, 2)", "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)); + // 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. + assertThat(bindValue(Type.string(), "numeric", "1E+999999999999")) + .isEqualTo(PreparedStatementValue.ofUntypedString("1E+999999999999")); + for (String targetType : new String[] {"numeric", "double precision", "integer"}) { + assertThat(bindValue(Type.string(), targetType, "1e9999999999")) + .isEqualTo(PreparedStatementValue.ofUntypedString("1e9999999999")); + assertThat(bindValue(Type.string(), targetType, "1e-2147483648")) + .isEqualTo(PreparedStatementValue.ofUntypedString("1e-2147483648")); + } + assertThat(bindValue(Type.string(), "numeric", "-1E-9999999999")) + .isEqualTo(PreparedStatementValue.ofUntypedString("-1E-9999999999")); + assertThat(bindValue(Type.string(), "double precision", "-1E-9999999999")) + .isEqualTo(PreparedStatementValue.ofUntypedString("-1E-9999999999")); + InvalidDMLGenerationException pgNumericExtremeEx = + assertThrows( + InvalidDMLGenerationException.class, + () -> bind(Type.pgNumeric(), "numeric", "1e9999999999")); + assertThat(pgNumericExtremeEx.getMessage()).doesNotContain("1e9999999999"); + assertThat(bindValue(Type.pgNumeric(), "numeric", overCapDigits)) + .isEqualTo(PreparedStatementValue.ofUntypedString(overCapDigits)); + assertThat(bindValue(Type.float32(), "real", overCapDigits)) + .isEqualTo(PreparedStatementValue.ofUntypedString(overCapDigits)); + + // 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"))); + } + + @Test + public void testNumericFloatOverflowUnderflowAndNonFinite() { + // 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("c"); - 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}"), + "+00:00"); + 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}"), + "+00:00"); + assertThat(negZeroReal.getPlaceholderSql()).isEqualTo("?"); + assertThat(negZeroReal.getParams()) + .containsExactly(PreparedStatementValue.ofUntypedString("-0.0")); + } + + // 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")); + + // 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")); + + // Non-finite floats/numerics across double precision, numeric, integer, and text. + 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")); + } - // Mocking SourceColumn - SourceColumn sourceCol = mock(SourceColumn.class); - when(sourceCol.name()).thenReturn("c"); - when(sourceCol.type()).thenReturn("text"); + @Test + 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")); + } - JSONObject json = new JSONObject("{\"c\":\"YWJj\"}"); + @Test + public void testCustomTransformationBindingsDispatchedByTargetType() { + // Character targets always bind as VARCHAR regardless of Java object type. + assertThat(customValue("text", "kk ll")).isEqualTo(PreparedStatementValue.ofString("kk ll")); + assertThat(customValue("varchar(50)", "'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")); + + // Number targets dispatch by PostgreSQL column type. + 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("numeric", Double.POSITIVE_INFINITY)) + .isEqualTo(PreparedStatementValue.ofUntypedString("Infinity")); + assertThat(customValue("integer", Boolean.TRUE)) + .isEqualTo(PreparedStatementValue.ofUntypedString("true")); + + // Boolean targets bind Boolean as ofBoolean and other inputs untyped. + assertThat(customValue("boolean", Boolean.TRUE)) + .isEqualTo(PreparedStatementValue.ofBoolean(true)); + assertThat(customValue("boolean", "true")).isEqualTo(PreparedStatementValue.ofBoolean(true)); + assertThat(customValue("boolean", 1)).isEqualTo(PreparedStatementValue.ofUntypedString("1")); + + // Structured, array, temporal, and binary targets. + 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")); + + // Null & JSONObject.NULL both bind as Types.NULL with plain '?' placeholder. + assertThat(customValue("integer", null)) + .isEqualTo(PreparedStatementValue.nullValue(Types.NULL)); + assertThat(customValue("integer", JSONObject.NULL)) + .isEqualTo(PreparedStatementValue.nullValue(Types.NULL)); + assertThat(customValue("text", JSONObject.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)); + } - String res = - PostgreSQLDMLGenerator.getMappedColumnValue(spannerCol, sourceCol, json, "+00:00", null); - assertTrue(res.contains("decode('YWJj', 'base64')")); + @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); - // Test string escape - Column spannerStrCol = mock(Column.class); - when(spannerStrCol.name()).thenReturn("s"); - when(spannerStrCol.type()).thenReturn(Type.string()); + Map customTransformation = new HashMap<>(); + customTransformation.put("FullName", "kk ll"); + customTransformation.put("SingerId", "1"); - SourceColumn sourceStrCol = mock(SourceColumn.class); - when(sourceStrCol.type()).thenReturn("text"); + 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.NULL), + 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.NULL), + PreparedStatementValue.ofLong(999L)); + } - JSONObject jsonStr = new JSONObject("{\"s\":\"it\\'s a string\"}"); + @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() + .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") + .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(10)"))) + .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")) + .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"); + + 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 "); + Map custom = new HashMap<>(); + // Custom transform returns boxed Integer for text_pk: must bind as VARCHAR on INSERT & DELETE. + custom.put("text_pk", 123); - String resStr = - PostgreSQLDMLGenerator.getMappedColumnValue( - spannerStrCol, sourceStrCol, jsonStr, "+00:00", null); - assertEquals("'it''s a string'", resStr); + 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 ")); + + 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\") " + + "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\")" + + " 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\" = ?"); + // INSERT and DELETE bind the exact same ordered PreparedStatementValues. + assertParams(insertResp.getPreparedStatementParameters(), expectedParams); + assertParams(deleteResp.getPreparedStatementParameters(), expectedParams); } @Test - public void testByteaTypeDML() throws Exception { - Column spannerCol = mock(Column.class); - when(spannerCol.name()).thenReturn("bytea_column"); - when(spannerCol.type()).thenReturn(Type.bytes()); + 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.NULL)); + + // 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(); + } - SourceColumn sourceCol = mock(SourceColumn.class); - when(sourceCol.name()).thenReturn("bytea_column"); - when(sourceCol.type()).thenReturn("bytea"); + @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")); + } - JSONObject json = new JSONObject("{\"bytea_column\":\"SGVsbG8=\"}"); // "Hello" in base64 + @Test + public void testInformationSchemaScannerDataTypesMatrix() { + // Verifies the exact information_schema.columns.data_type strings emitted by + // PostgreSQLInformationSchemaScanner.scanColumns. + Map expectedCategories = new HashMap<>(); + expectedCategories.put("character varying", PgColumnType.CHARACTER); + expectedCategories.put("character", PgColumnType.CHARACTER); + expectedCategories.put("text", PgColumnType.CHARACTER); + expectedCategories.put("name", PgColumnType.CHARACTER); + expectedCategories.put("smallint", PgColumnType.INTEGER); + expectedCategories.put("integer", PgColumnType.INTEGER); + expectedCategories.put("bigint", PgColumnType.INTEGER); + expectedCategories.put("real", PgColumnType.FLOAT4); + expectedCategories.put("double precision", PgColumnType.FLOAT8); + expectedCategories.put("numeric", PgColumnType.DECIMAL); + expectedCategories.put("boolean", PgColumnType.BOOLEAN); + expectedCategories.put("timestamp without time zone", PgColumnType.TIMESTAMP); + expectedCategories.put("timestamp with time zone", PgColumnType.TIMESTAMP); + expectedCategories.put("timestamp without time zone[]", PgColumnType.OTHER); + expectedCategories.put("timestamp with time zone[]", PgColumnType.OTHER); + expectedCategories.put("character varying[]", PgColumnType.OTHER); + expectedCategories.put("integer[]", PgColumnType.OTHER); + expectedCategories.put("bytea[]", PgColumnType.OTHER); + expectedCategories.put("USER-DEFINED[]", PgColumnType.OTHER); + expectedCategories.put("ARRAY", PgColumnType.OTHER); + expectedCategories.put("citext", PgColumnType.OTHER); + expectedCategories.put("bytea", PgColumnType.OTHER); + expectedCategories.put("date", PgColumnType.OTHER); + expectedCategories.put("time without time zone", PgColumnType.OTHER); + expectedCategories.put("time with time zone", PgColumnType.OTHER); + expectedCategories.put("interval", PgColumnType.OTHER); + expectedCategories.put("json", PgColumnType.OTHER); + expectedCategories.put("jsonb", PgColumnType.OTHER); + expectedCategories.put("uuid", PgColumnType.OTHER); + expectedCategories.put("money", PgColumnType.OTHER); + expectedCategories.put("bit", PgColumnType.OTHER); + expectedCategories.put("bit varying", PgColumnType.OTHER); + expectedCategories.put("inet", PgColumnType.OTHER); + expectedCategories.put("xml", PgColumnType.OTHER); + expectedCategories.put("USER-DEFINED", PgColumnType.OTHER); + + for (Map.Entry entry : expectedCategories.entrySet()) { + assertThat(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("")); + } - String res = - PostgreSQLDMLGenerator.getMappedColumnValue(spannerCol, sourceCol, json, "+00:00", null); - assertEquals("'\\x48656c6c6f'", res); // "Hello" in hex is 48656c6c6f + // --------------------------------------------------------------------------------------------- + // SQL Injection Regression Tests + // --------------------------------------------------------------------------------------------- + + @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 testUuidTypeDML() throws Exception { - Column spannerCol = mock(Column.class); - when(spannerCol.name()).thenReturn("uuid_column"); - when(spannerCol.type()).thenReturn(Type.string()); + 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); - SourceColumn sourceCol = mock(SourceColumn.class); - when(sourceCol.name()).thenReturn("uuid_column"); - when(sourceCol.type()).thenReturn("uuid"); + 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); - JSONObject json = new JSONObject("{\"uuid_column\":\"123e4567-e89b-12d3-a456-426614174000\"}"); + // 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)); + } - String res = - PostgreSQLDMLGenerator.getMappedColumnValue(spannerCol, sourceCol, json, "+00:00", null); - assertEquals("'123e4567-e89b-12d3-a456-426614174000'", res); + @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 testJsonbTypeDML() throws Exception { - Column spannerCol = mock(Column.class); - when(spannerCol.name()).thenReturn("jsonb_column"); - when(spannerCol.type()).thenReturn(Type.string()); + 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); - SourceColumn sourceCol = mock(SourceColumn.class); - when(sourceCol.name()).thenReturn("jsonb_column"); - when(sourceCol.type()).thenReturn("jsonb"); + // Spanner table missing from DDL. + assertThrows( + InvalidDMLGenerationException.class, + () -> + generator.getDMLStatement( + new DMLGeneratorRequest.Builder( + "INSERT", "MissingTable", new JSONObject(), new JSONObject(), "+00:00") + .setSchemaMapper(mapper) + .setDdl(emptyDdl) + .setSourceSchema(sourceSchema) + .build())); - JSONObject json = new JSONObject("{\"jsonb_column\":\"{\\\"a\\\": 1}\"}"); + // 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")); + assertThrows( + InvalidDMLGenerationException.class, + () -> + generator.getDMLStatement( + new DMLGeneratorRequest.Builder( + "INSERT", "Singers", new JSONObject(), new JSONObject(), "+00:00") + .setSchemaMapper(mapper) + .setDdl(singersDdl) + .setSourceSchema(sourceSchema) + .build())); - String res = - PostgreSQLDMLGenerator.getMappedColumnValue(spannerCol, sourceCol, json, "+00:00", null); - assertEquals("'{\"a\": 1}'", res); + // 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")); + assertThrows( + InvalidDMLGenerationException.class, + () -> + generator.getDMLStatement( + new DMLGeneratorRequest.Builder( + "DELETE", + "Singers", + new JSONObject(), + new JSONObject().put("SingerId", "1"), + "+00:00") + .setSchemaMapper(unmappedPkMapper) + .setDdl(singersDdl) + .setSourceSchema(sourceSchema) + .build())); } @Test @@ -505,12 +1812,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 +1833,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 +1855,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 +1888,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 +1928,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 +1942,146 @@ 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.NULL), + PreparedStatementValue.ofLong(999L)); + } + + @Test + public void testNormalizeSourceType() { + assertThat(PostgreSQLDMLGenerator.normalizeSourceType(null)).isEmpty(); + assertThat(PostgreSQLDMLGenerator.normalizeSourceType("VARCHAR(255)")).isEqualTo("varchar"); + assertThat(PostgreSQLDMLGenerator.normalizeSourceType("NUMERIC(10, 2)")).isEqualTo("numeric"); + assertThat(PostgreSQLDMLGenerator.normalizeSourceType("TIMESTAMP(6) WITH TIME ZONE")) + .isEqualTo("timestamp with time zone"); + assertThat(PostgreSQLDMLGenerator.normalizeSourceType("TIMESTAMP(6)WITH TIME ZONE")) + .isEqualTo("timestamp with time zone"); + assertThat(PostgreSQLDMLGenerator.normalizeSourceType("character varying(10)[]")) + .isEqualTo("character varying[]"); + } + + 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), "+00:00"); + } + + 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) { + switch (sqlType) { + case Types.VARCHAR: + return "VARCHAR"; + case Types.OTHER: + return "OTHER"; + case Types.VARBINARY: + return "VARBINARY"; + case Types.BOOLEAN: + return "BOOLEAN"; + case Types.DECIMAL: + return "DECIMAL"; + case Types.BIGINT: + return "BIGINT"; + case Types.DOUBLE: + return "DOUBLE"; + case Types.NULL: + return "NULL"; + default: + return "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); } } From 27850aa7a086efdb32e3114ee73086099a1b3bde Mon Sep 17 00:00:00 2001 From: aasthabharill Date: Fri, 4 Dec 2026 07:10:28 +0000 Subject: [PATCH 2/6] Simplify PgColumnType lookup, share normalizeSourceType, and clean up README --- v2/spanner-to-sourcedb/README.md | 11 +- .../dbutils/dml/DMLGeneratorUtils.java | 5 + .../source/mysql/MySQLDMLGenerator.java | 9 +- .../postgres/PostgreSQLDMLGenerator.java | 108 ++++++------------ .../dbutils/dml/DMLGeneratorUtilsTest.java | 10 ++ .../postgres/PostgreSQLDMLGeneratorTest.java | 21 +--- 6 files changed, 61 insertions(+), 103 deletions(-) diff --git a/v2/spanner-to-sourcedb/README.md b/v2/spanner-to-sourcedb/README.md index ed4b65090a..be0261d33c 100644 --- a/v2/spanner-to-sourcedb/README.md +++ b/v2/spanner-to-sourcedb/README.md @@ -386,18 +386,11 @@ Reverse transformation can not be supported for following scenarios out of the b 8. CLOB will not be read from GCS and put in source 9. DELETES on Spanner that have Primary key columns different from the Source database column - such records will be dropped 10. Primary key of the source table cannot be determined - such records will be dropped -11. **PostgreSQL:** Replicating Spanner `ARRAY` columns is not supported out of the box (rejected by the shard-assignment stage). +11. **PostgreSQL:** Replicating array columns to native PostgreSQL array types (e.g., `varchar[]`) is not fully supported and is converted to comma-separated strings instead. 12. **PostgreSQL:** Writing to non-default schemas (namespaces) is not supported; records will be written to the default schema of the connected user. In the above cases, custom code will need to be written to perform reverse transformation.Refer the [customization](#customize) section for the source code to extend and write these custom transforms. -#### PostgreSQL value handling notes - -- `sourceDbTimezoneOffset` is not applied for PostgreSQL; Spanner UTC timestamps are cast via `?::timestamptz` so PostgreSQL converts them using the database session timezone for `timestamp without time zone` columns. -- Non-finite floating-point values (`NaN`, `Infinity`, `-Infinity`) are bound directly for `real`, `double precision`, and `numeric` (`Infinity` on `numeric` requires PostgreSQL 14+). -- NUL (`U+0000`) characters are stripped from string values (including custom transformation outputs) because PostgreSQL text types cannot store NUL bytes. -- Spanner `BYTES` mapped to PostgreSQL character columns are formatted using PostgreSQL's default `bytea_output = hex` representation (`\x...`). - ## When to perform cut-back In the event that cut-back is needed to start serving from the original database instead for Spanner, following should be taken care: @@ -490,7 +483,7 @@ Steps to perform customization: 4. If any events are filtered/skipped during the reverse transformation they can be written to a GCS directory by passing the GCS path via the *filterEventsDirectoryName* input to the runner. 5. If any custom parameters are needed in the custom transformation logic, they can be passed via the *transformationCustomParameters* input to the runner. These parameters will be passed to the *init* method of the custom class. The *init* method is invoked once per worker setup. -> **Breaking change (PostgreSQL):** PostgreSQL reverse replication binds `toSourceRow()` output values strictly as `PreparedStatement` parameters (raw data), never as SQL fragments. Do **not** wrap string values in single quotes (`'abc'`) or return SQL expressions (such as `now()` or `decode(...)`), as quotes and function calls are now stored literally or rejected by PostgreSQL. Supported Java output types are `String`, `byte[]`, `Boolean`, `Long`, `Integer`, `Short`, `Byte`, `BigDecimal`, `BigInteger`, `Double`, `Float`, and `null`; any other object is converted via `toString()`. +> **Note:** Reverse replication binds `toSourceRow()` output values strictly as query parameters (raw data), never as SQL fragments. Do **not** wrap string values in single quotes (`'abc'`) or return SQL expressions (such as `now()` or `decode(...)`), as quotes and function calls will be stored literally or rejected by the database. ## Cost diff --git a/v2/spanner-to-sourcedb/src/main/java/com/google/cloud/teleport/v2/templates/dbutils/dml/DMLGeneratorUtils.java b/v2/spanner-to-sourcedb/src/main/java/com/google/cloud/teleport/v2/templates/dbutils/dml/DMLGeneratorUtils.java index 0359cc4af9..90b96a6706 100644 --- a/v2/spanner-to-sourcedb/src/main/java/com/google/cloud/teleport/v2/templates/dbutils/dml/DMLGeneratorUtils.java +++ b/v2/spanner-to-sourcedb/src/main/java/com/google/cloud/teleport/v2/templates/dbutils/dml/DMLGeneratorUtils.java @@ -268,6 +268,11 @@ public static boolean isStringArray(Type colType) { || colType.getArrayElementType().getCode().equals(Type.Code.PG_TEXT))); } + /** Normalizes a source database column type name by trimming and lowercasing it. */ + public static String normalizeSourceType(@Nullable String sourceType) { + return sourceType == null ? "" : sourceType.trim().toLowerCase(Locale.ROOT); + } + /** * Removes the trailing {@code Z} (UTC designator) of a Spanner timestamp. Values without it (e.g. * from a Spanner STRING column) are returned as is. diff --git a/v2/spanner-to-sourcedb/src/main/java/com/google/cloud/teleport/v2/templates/source/mysql/MySQLDMLGenerator.java b/v2/spanner-to-sourcedb/src/main/java/com/google/cloud/teleport/v2/templates/source/mysql/MySQLDMLGenerator.java index af6f03fbf4..993aed08c4 100644 --- a/v2/spanner-to-sourcedb/src/main/java/com/google/cloud/teleport/v2/templates/source/mysql/MySQLDMLGenerator.java +++ b/v2/spanner-to-sourcedb/src/main/java/com/google/cloud/teleport/v2/templates/source/mysql/MySQLDMLGenerator.java @@ -37,7 +37,6 @@ import java.util.ArrayList; import java.util.Base64; import java.util.List; -import java.util.Locale; import java.util.Map; import java.util.NoSuchElementException; import java.util.regex.Pattern; @@ -312,16 +311,12 @@ static String quoteIdentifier(String identifier) { */ @VisibleForTesting static boolean isNumericLiteralType(String sourceType) { - String type = normalizeSourceType(sourceType); + String type = DMLGeneratorUtils.normalizeSourceType(sourceType); return !TEXT_TYPES.contains(type) && !TIMESTAMP_TYPES.contains(type) && !BINARY_TYPES.contains(type); } - private static String normalizeSourceType(String sourceType) { - return sourceType == null ? "" : sourceType.toLowerCase(Locale.ROOT); - } - /** * Maps a non-null Spanner column value to a {@link ColumnBinding} based on the Spanner column * type and the MySQL source column type. @@ -343,7 +338,7 @@ static ColumnBinding getMappedColumnBinding( return ColumnBinding.of(PreparedStatementValue.ofBytes(bytes)); } - String sourceType = normalizeSourceType(sourceColDef.type()); + String sourceType = DMLGeneratorUtils.normalizeSourceType(sourceColDef.type()); if (isNumericLiteralType(sourceType)) { return ColumnBinding.of(getNumericLiteralTypeValue(colType, valuesJson, colName)); } diff --git a/v2/spanner-to-sourcedb/src/main/java/com/google/cloud/teleport/v2/templates/source/postgres/PostgreSQLDMLGenerator.java b/v2/spanner-to-sourcedb/src/main/java/com/google/cloud/teleport/v2/templates/source/postgres/PostgreSQLDMLGenerator.java index 58aaeca807..6641f124a5 100644 --- a/v2/spanner-to-sourcedb/src/main/java/com/google/cloud/teleport/v2/templates/source/postgres/PostgreSQLDMLGenerator.java +++ b/v2/spanner-to-sourcedb/src/main/java/com/google/cloud/teleport/v2/templates/source/postgres/PostgreSQLDMLGenerator.java @@ -33,6 +33,7 @@ import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import java.math.BigDecimal; import java.math.BigInteger; @@ -106,12 +107,6 @@ public class PostgreSQLDMLGenerator implements IDMLGenerator { */ private static final int MAX_BIG_DECIMAL_TEXT_LENGTH = 2048; - /** Matches parenthesized type modifiers such as {@code (255)} or {@code (10, 2)}. */ - private static final Pattern PAREN_MODIFIER = Pattern.compile("\\([^)]*\\)"); - - /** Matches runs of whitespace when normalizing PostgreSQL type names. */ - private static final Pattern WHITESPACE = Pattern.compile("\\s+"); - /** Matches signed base-10 integer literals (for example {@code -42}, {@code +7}). */ private static final Pattern INTEGER_LITERAL = Pattern.compile("[+-]?\\d+"); @@ -167,56 +162,43 @@ enum PgColumnType { DECIMAL, OTHER; - static PgColumnType fromSourceType(@Nullable String rawPgType) { - String normalized = normalizeSourceType(rawPgType); - if (isTimestampName(normalized)) { - return TIMESTAMP; - } - switch (normalized) { - case "varchar": - case "character varying": - case "char": - case "character": - case "bpchar": - case "text": - case "name": - return CHARACTER; - case "boolean": - case "bool": - return BOOLEAN; - case "smallint": - case "int2": - case "integer": - case "int": - case "int4": - case "bigint": - case "int8": - case "smallserial": - case "serial": - case "bigserial": - return INTEGER; - case "real": - case "float4": - return FLOAT4; - case "double precision": - case "float8": - return FLOAT8; - case "numeric": - case "decimal": - return DECIMAL; - default: - // Includes bytea, json/jsonb, uuid, date/time, arrays, USER-DEFINED (enums/citext/ - // domains), and unknown types. All bind untyped via Types.OTHER so PostgreSQL resolves - // the column's exact type and operators. - return 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("real", FLOAT4) + .put("float4", FLOAT4) + .put("double precision", FLOAT8) + .put("float8", FLOAT8) + .put("numeric", DECIMAL) + .put("decimal", DECIMAL) + .build(); - private static boolean isTimestampName(String normalized) { - return "timestamp".equals(normalized) - || "timestamp without time zone".equals(normalized) - || "timestamp with time zone".equals(normalized) - || "timestamptz".equals(normalized); + static PgColumnType fromSourceType(@Nullable String rawPgType) { + // Unmapped types (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. + return TYPE_MAP.getOrDefault(DMLGeneratorUtils.normalizeSourceType(rawPgType), OTHER); } } @@ -248,7 +230,7 @@ public DMLGeneratorResponse getDMLStatement(DMLGeneratorRequest dmlGeneratorRequ "The spanner table %s was not found in ddl found on spanner", spannerTableName)); } - String sourceTableName; + String sourceTableName = ""; try { sourceTableName = schemaMapper.getSourceTableName("", spannerTableName); } catch (NoSuchElementException e) { @@ -872,18 +854,4 @@ private static String removeNullBytes(String input) { private static String toPostgresHexByteaText(byte[] bytes) { return "\\x" + HexFormat.of().formatHex(bytes); } - - /** - * Normalizes a PostgreSQL column type string by stripping parenthesized modifiers, collapsing - * whitespace, preserving the {@code []} array suffix, and lowercasing. - */ - @VisibleForTesting - static String normalizeSourceType(@Nullable String pgType) { - if (pgType == null) { - return ""; - } - String withoutModifiers = PAREN_MODIFIER.matcher(pgType).replaceAll(" "); - String collapsed = WHITESPACE.matcher(withoutModifiers).replaceAll(" ").trim(); - return StringUtils.replace(collapsed, " []", "[]").toLowerCase(Locale.ROOT); - } } 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..2d0d15afd2 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,16 @@ public void testGetNonFiniteTextForDoubleAndFloatValues() { assertNull(DMLGeneratorUtils.getNonFiniteText(values, "finite")); } + @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 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/source/postgres/PostgreSQLDMLGeneratorTest.java b/v2/spanner-to-sourcedb/src/test/java/com/google/cloud/teleport/v2/templates/source/postgres/PostgreSQLDMLGeneratorTest.java index 9fa62d35ec..50140fac6a 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 @@ -468,7 +468,7 @@ public void testTimestampScalarAndNullBindingsStabilizePlaceholder() { "timestamp without time zone", "timestamp with time zone", "timestamptz", - "TIMESTAMP(6) WITH TIME ZONE" + "TIMESTAMP WITH TIME ZONE" }) { ColumnBinding nonNull = bind(spannerTsType, tsType, "2023-05-18T12:01:13.088397258Z"); assertThat(nonNull.getPlaceholderSql()).isEqualTo("?::timestamptz"); @@ -568,7 +568,7 @@ public void testNumericIntegerAndDecimalBindings() { // 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(10, 2)", "1E-500")) + 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")) @@ -784,7 +784,7 @@ public void testStringEncodedNegativeZeroForDoublePrecision() { public void testCustomTransformationBindingsDispatchedByTargetType() { // Character targets always bind as VARCHAR regardless of Java object type. assertThat(customValue("text", "kk ll")).isEqualTo(PreparedStatementValue.ofString("kk ll")); - assertThat(customValue("varchar(50)", "'quoted'")) + assertThat(customValue("varchar", "'quoted'")) .isEqualTo(PreparedStatementValue.ofString("'quoted'")); assertThat(customValue("text", 42)).isEqualTo(PreparedStatementValue.ofString("42")); assertThat(customValue("text", Boolean.TRUE)) @@ -1049,7 +1049,7 @@ public void testSymmetricalInsertAndDeleteAcrossPgPkTypes() { srcCol("bool_pk", "boolean"), srcCol("int_pk", "integer"), srcCol("text_pk", "text"), - srcCol("char_pk", "character(10)"))) + srcCol("char_pk", "character"))) .primaryKeyColumns( ImmutableList.of( "real_pk", @@ -1969,19 +1969,6 @@ public void testGetDMLStatement_NullValueInUpsert() { PreparedStatementValue.ofLong(999L)); } - @Test - public void testNormalizeSourceType() { - assertThat(PostgreSQLDMLGenerator.normalizeSourceType(null)).isEmpty(); - assertThat(PostgreSQLDMLGenerator.normalizeSourceType("VARCHAR(255)")).isEqualTo("varchar"); - assertThat(PostgreSQLDMLGenerator.normalizeSourceType("NUMERIC(10, 2)")).isEqualTo("numeric"); - assertThat(PostgreSQLDMLGenerator.normalizeSourceType("TIMESTAMP(6) WITH TIME ZONE")) - .isEqualTo("timestamp with time zone"); - assertThat(PostgreSQLDMLGenerator.normalizeSourceType("TIMESTAMP(6)WITH TIME ZONE")) - .isEqualTo("timestamp with time zone"); - assertThat(PostgreSQLDMLGenerator.normalizeSourceType("character varying(10)[]")) - .isEqualTo("character varying[]"); - } - private static SourceColumn srcCol(String name, String type) { return SourceColumn.builder(SourceDatabaseType.POSTGRESQL).name(name).type(type).build(); } From 1ccd1fc54112d694869d0061c4e3700aa689bf1e Mon Sep 17 00:00:00 2001 From: aasthabharill Date: Fri, 4 Dec 2026 08:51:29 +0000 Subject: [PATCH 3/6] Address review feedback: simplify PgColumnType, optimize hot paths, and expand tests --- v2/spanner-to-sourcedb/README.md | 2 +- .../dbutils/dml/DMLGeneratorUtils.java | 31 +- .../source/mysql/MySQLDMLGenerator.java | 12 +- .../postgres/PostgreSQLDMLGenerator.java | 712 ++++++++++-------- .../dbutils/dml/DMLGeneratorUtilsTest.java | 20 + .../dml/PreparedStatementValueTest.java | 11 +- .../postgres/PostgreSQLDMLGeneratorTest.java | 576 ++++++++------ 7 files changed, 793 insertions(+), 571 deletions(-) diff --git a/v2/spanner-to-sourcedb/README.md b/v2/spanner-to-sourcedb/README.md index be0261d33c..be4a1f51d7 100644 --- a/v2/spanner-to-sourcedb/README.md +++ b/v2/spanner-to-sourcedb/README.md @@ -483,7 +483,7 @@ Steps to perform customization: 4. If any events are filtered/skipped during the reverse transformation they can be written to a GCS directory by passing the GCS path via the *filterEventsDirectoryName* input to the runner. 5. If any custom parameters are needed in the custom transformation logic, they can be passed via the *transformationCustomParameters* input to the runner. These parameters will be passed to the *init* method of the custom class. The *init* method is invoked once per worker setup. -> **Note:** Reverse replication binds `toSourceRow()` output values strictly as query parameters (raw data), never as SQL fragments. Do **not** wrap string values in single quotes (`'abc'`) or return SQL expressions (such as `now()` or `decode(...)`), as quotes and function calls will be stored literally or rejected by the database. +> **Note:** For MySQL and PostgreSQL reverse replication, `toSourceRow()` output values are bound strictly as query parameters (raw data), never as SQL fragments. Do **not** wrap string values in single quotes (`'abc'`) or return SQL expressions (such as `now()` or `decode(...)`), as quotes and function calls will be stored literally or rejected by the database. ## Cost diff --git a/v2/spanner-to-sourcedb/src/main/java/com/google/cloud/teleport/v2/templates/dbutils/dml/DMLGeneratorUtils.java b/v2/spanner-to-sourcedb/src/main/java/com/google/cloud/teleport/v2/templates/dbutils/dml/DMLGeneratorUtils.java index 90b96a6706..6e971817e8 100644 --- a/v2/spanner-to-sourcedb/src/main/java/com/google/cloud/teleport/v2/templates/dbutils/dml/DMLGeneratorUtils.java +++ b/v2/spanner-to-sourcedb/src/main/java/com/google/cloud/teleport/v2/templates/dbutils/dml/DMLGeneratorUtils.java @@ -21,7 +21,6 @@ import com.google.cloud.teleport.v2.spanner.sourceddl.SourceColumn; import com.google.cloud.teleport.v2.spanner.sourceddl.SourceTable; import com.google.cloud.teleport.v2.spanner.type.Type; -import com.google.common.collect.ImmutableSet; import java.sql.Types; import java.util.Base64; import java.util.LinkedHashMap; @@ -41,10 +40,6 @@ public class DMLGeneratorUtils { private static final Logger LOG = LoggerFactory.getLogger(DMLGeneratorUtils.class); - /** Lower-cased text of non-finite float / numeric values in the change stream. */ - private static final ImmutableSet NON_FINITE_VALUES = - ImmutableSet.of("nan", "infinity", "+infinity", "-infinity"); - @FunctionalInterface public interface ColumnValueMapper { String getMappedColumnValue( @@ -226,6 +221,25 @@ public static String getSpannerValueAsString( return valuesJson.getString(colName); } + /** + * Returns {@code true} if {@code trimmed} is a case-insensitive non-finite float / numeric + * literal ({@code NaN}, {@code Infinity}, {@code +Infinity}, or {@code -Infinity}). + */ + public static boolean isNonFiniteTrimmed(String trimmed) { + int len = trimmed.length(); + if (len == 3) { + return "nan".equalsIgnoreCase(trimmed); + } + if (len == 8) { + return "infinity".equalsIgnoreCase(trimmed); + } + if (len == 9) { + char first = trimmed.charAt(0); + return (first == '+' || first == '-') && trimmed.regionMatches(true, 1, "infinity", 0, 8); + } + return false; + } + /** * Returns the text of a non-finite float / numeric value ({@code NaN}, {@code Infinity}, {@code * -Infinity}), which the change stream writes as a JSON string, or {@code null} otherwise. @@ -235,7 +249,7 @@ public static String getNonFiniteText(JSONObject valuesJson, String colName) { Object value = valuesJson.get(colName); if (value instanceof String) { String text = ((String) value).trim(); - if (NON_FINITE_VALUES.contains(text.toLowerCase(Locale.ROOT))) { + if (isNonFiniteTrimmed(text)) { return text; } } else if (value instanceof Double || value instanceof Float) { @@ -273,6 +287,11 @@ public static String normalizeSourceType(@Nullable String sourceType) { return sourceType == null ? "" : sourceType.trim().toLowerCase(Locale.ROOT); } + /** Strips NUL ({@code U+0000}) characters from {@code input}. */ + public static String removeNullBytes(String input) { + return StringUtils.replace(input, "\u0000", ""); + } + /** * Removes the trailing {@code Z} (UTC designator) of a Spanner timestamp. Values without it (e.g. * from a Spanner STRING column) are returned as is. diff --git a/v2/spanner-to-sourcedb/src/main/java/com/google/cloud/teleport/v2/templates/source/mysql/MySQLDMLGenerator.java b/v2/spanner-to-sourcedb/src/main/java/com/google/cloud/teleport/v2/templates/source/mysql/MySQLDMLGenerator.java index 993aed08c4..3606f611d6 100644 --- a/v2/spanner-to-sourcedb/src/main/java/com/google/cloud/teleport/v2/templates/source/mysql/MySQLDMLGenerator.java +++ b/v2/spanner-to-sourcedb/src/main/java/com/google/cloud/teleport/v2/templates/source/mysql/MySQLDMLGenerator.java @@ -349,15 +349,17 @@ static ColumnBinding getMappedColumnBinding( return ColumnBinding.of( CONVERT_TZ_PLACEHOLDER, ImmutableList.of( - PreparedStatementValue.ofString(removeNullBytes(utcTimestamp)), + PreparedStatementValue.ofString(DMLGeneratorUtils.removeNullBytes(utcTimestamp)), PreparedStatementValue.ofString(sourceDbTimezoneOffset))); } if (BINARY_TYPES.contains(sourceType)) { return ColumnBinding.of( BINARY_PLACEHOLDER, - ImmutableList.of(PreparedStatementValue.ofString(removeNullBytes(stringValue)))); + ImmutableList.of( + PreparedStatementValue.ofString(DMLGeneratorUtils.removeNullBytes(stringValue)))); } - return ColumnBinding.of(PreparedStatementValue.ofString(removeNullBytes(stringValue))); + return ColumnBinding.of( + PreparedStatementValue.ofString(DMLGeneratorUtils.removeNullBytes(stringValue))); } /** @@ -473,8 +475,4 @@ private static void checkFinite(JSONObject valuesJson, String colName) { nonFiniteText, colName)); } } - - private static String removeNullBytes(String input) { - return StringUtils.replace(input, "\u0000", ""); - } } diff --git a/v2/spanner-to-sourcedb/src/main/java/com/google/cloud/teleport/v2/templates/source/postgres/PostgreSQLDMLGenerator.java b/v2/spanner-to-sourcedb/src/main/java/com/google/cloud/teleport/v2/templates/source/postgres/PostgreSQLDMLGenerator.java index 6641f124a5..dc7999c60c 100644 --- a/v2/spanner-to-sourcedb/src/main/java/com/google/cloud/teleport/v2/templates/source/postgres/PostgreSQLDMLGenerator.java +++ b/v2/spanner-to-sourcedb/src/main/java/com/google/cloud/teleport/v2/templates/source/postgres/PostgreSQLDMLGenerator.java @@ -34,7 +34,6 @@ import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableSet; import java.math.BigDecimal; import java.math.BigInteger; import java.sql.Types; @@ -43,12 +42,10 @@ import java.util.HashSet; import java.util.HexFormat; import java.util.List; -import java.util.Locale; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import java.util.regex.Pattern; -import java.util.stream.Collectors; import javax.annotation.Nullable; import org.apache.commons.lang3.StringUtils; import org.json.JSONException; @@ -79,15 +76,15 @@ * for exact integers within {@code long} range (preserving B-tree index usage), {@code * ofBigDecimal} for in-bounds fractional decimals or out-of-{@code long}-range integers, else * {@code ofUntypedString}. - *
  • {@code real} ({@code float4}): {@code ofUntypedString} so PostgreSQL always resolves - * the parameter to {@code float4} regardless of {@code pgjdbc} binary-transfer mode. *
  • {@code double precision} ({@code float8}): {@code ofDouble} when finite and in range * (or non-finite literal), else {@code ofUntypedString}. *
  • {@code numeric}/{@code decimal}: {@code ofBigDecimal} when within PostgreSQL * precision/scale bounds and length cap, else {@code ofUntypedString}. - *
  • All other types ({@code bytea}, {@code json}, {@code jsonb}, {@code uuid}, {@code - * date}, {@code time}, arrays, {@code USER-DEFINED}, unknown): {@code ofBytes} for Spanner - * {@code BYTES} or custom {@code byte[]}; otherwise {@code ofUntypedString}. + *
  • All other types ({@code real}/{@code float4}, {@code bytea}, {@code json}, {@code + * jsonb}, {@code uuid}, {@code date}, {@code time}, arrays, {@code USER-DEFINED}, unknown): + * {@code ofBytes} for Spanner {@code BYTES} or custom {@code byte[]}; otherwise {@code + * ofUntypedString} (for {@code real}, this guarantees {@code float4} resolution regardless of + * {@code pgjdbc} binary-transfer mode). * */ public class PostgreSQLDMLGenerator implements IDMLGenerator { @@ -95,6 +92,15 @@ public class PostgreSQLDMLGenerator implements IDMLGenerator { /** SQL fragment casting a bound UTC timestamp string to {@code timestamptz}. */ private static final String TIMESTAMPTZ_PLACEHOLDER = "?::timestamptz"; + /** Cached SQL {@code NULL} binding for non-timestamp columns. */ + private static final ColumnBinding NULL_BINDING = + ColumnBinding.of(PreparedStatementValue.nullValue(Types.NULL)); + + /** Cached SQL {@code NULL} binding preserving {@code ?::timestamptz} for statement caching. */ + private static final ColumnBinding NULL_TIMESTAMPTZ_BINDING = + ColumnBinding.of( + TIMESTAMPTZ_PLACEHOLDER, ImmutableList.of(PreparedStatementValue.nullValue(Types.NULL))); + /** PostgreSQL NUMERIC precision limits (up to 131072 integer digits, scale up to 16383). */ private static final int PG_NUMERIC_MAX_INTEGER_DIGITS = 131072; @@ -107,9 +113,6 @@ public class PostgreSQLDMLGenerator implements IDMLGenerator { */ private static final int MAX_BIG_DECIMAL_TEXT_LENGTH = 2048; - /** Matches signed base-10 integer literals (for example {@code -42}, {@code +7}). */ - private static final Pattern INTEGER_LITERAL = Pattern.compile("[+-]?\\d+"); - /** Matches fixed-point decimal literals (for example {@code 1.5}, {@code .5}, {@code 5.}). */ private static final Pattern DECIMAL_LITERAL = Pattern.compile("[+-]?(\\d+\\.\\d*|\\.\\d+)"); @@ -117,10 +120,6 @@ public class PostgreSQLDMLGenerator implements IDMLGenerator { private static final Pattern SCIENTIFIC_LITERAL = Pattern.compile("[+-]?(\\d+(\\.\\d*)?|\\.\\d+)[eE][+-]?\\d+"); - /** Lower-cased text of non-finite float / numeric literals. */ - private static final ImmutableSet NON_FINITE_VALUES = - ImmutableSet.of("nan", "infinity", "+infinity", "-infinity"); - /** * Column binding mapper delegating non-null and null Spanner values to {@link * #getMappedColumnBinding} and {@link #getNullColumnBinding} (preserving {@code ?::timestamptz} @@ -134,8 +133,7 @@ public ColumnBinding getColumnBinding( SourceColumn sourceColDef, JSONObject valuesJson, String sourceDbTimezoneOffset) { - return getMappedColumnBinding( - spannerColDef, sourceColDef, valuesJson, sourceDbTimezoneOffset); + return getMappedColumnBinding(spannerColDef, sourceColDef, valuesJson); } @Override @@ -144,64 +142,6 @@ public ColumnBinding getNullColumnBinding(Column spannerColDef, SourceColumn sou } }; - /** - * 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, - FLOAT4, - 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("real", FLOAT4) - .put("float4", FLOAT4) - .put("double precision", FLOAT8) - .put("float8", FLOAT8) - .put("numeric", DECIMAL) - .put("decimal", DECIMAL) - .build(); - - static PgColumnType fromSourceType(@Nullable String rawPgType) { - // Unmapped types (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. - return TYPE_MAP.getOrDefault(DMLGeneratorUtils.normalizeSourceType(rawPgType), OTHER); - } - } - @Override public DMLGeneratorResponse getDMLStatement(DMLGeneratorRequest dmlGeneratorRequest) { if (dmlGeneratorRequest == null) { @@ -230,7 +170,7 @@ public DMLGeneratorResponse getDMLStatement(DMLGeneratorRequest dmlGeneratorRequ "The spanner table %s was not found in ddl found on spanner", spannerTableName)); } - String sourceTableName = ""; + String sourceTableName; try { sourceTableName = schemaMapper.getSourceTableName("", spannerTableName); } catch (NoSuchElementException e) { @@ -286,53 +226,99 @@ public DMLGeneratorResponse getDMLStatement(DMLGeneratorRequest dmlGeneratorRequ } } + private static DMLGeneratorResponse generateUpsertStatement( + Table spannerTable, + SourceTable sourceTable, + DMLGeneratorRequest dmlGeneratorRequest, + Map pkColumnBindings) { + // When any PK column is generated, getPkColumnBindings already includes all non-PK columns; + // reuse that map directly instead of resolving non-PK columns twice. + if (hasGeneratedPrimaryKey(sourceTable)) { + return getUpsertStatement( + sourceTable.name(), pkColumnBindings, sourceTable.primaryKeyColumns()); + } + Map columnBindings = + DMLGeneratorUtils.getColumnBindings( + dmlGeneratorRequest.getSchemaMapper(), + spannerTable, + sourceTable, + dmlGeneratorRequest.getNewValuesJson(), + dmlGeneratorRequest.getKeyValuesJson(), + dmlGeneratorRequest.getSourceDbTimezoneOffset(), + dmlGeneratorRequest.getCustomTransformationResponse(), + COLUMN_BINDING_MAPPER, + PostgreSQLDMLGenerator::getCustomValueBinding); + columnBindings.putAll(pkColumnBindings); + return getUpsertStatement(sourceTable.name(), columnBindings, sourceTable.primaryKeyColumns()); + } + + private static boolean hasGeneratedPrimaryKey(SourceTable sourceTable) { + for (String pkColName : sourceTable.primaryKeyColumns()) { + SourceColumn col = sourceTable.column(pkColName); + if (col != null && col.isGenerated()) { + return true; + } + } + return false; + } + /** * Builds {@code INSERT INTO "t" ("c1",...) VALUES (?,...) ON CONFLICT ("pk",...) DO UPDATE SET * "c1" = EXCLUDED."c1",...} (or {@code DO NOTHING} when all columns are primary keys). */ private static DMLGeneratorResponse getUpsertStatement( String tableName, Map allColumnBindings, List primaryKeys) { - List columns = new ArrayList<>(allColumnBindings.size()); - List values = new ArrayList<>(allColumnBindings.size()); + String singlePk = primaryKeys.size() == 1 ? primaryKeys.get(0) : null; + Set pkSet = primaryKeys.size() > 3 ? new HashSet<>(primaryKeys) : null; + StringBuilder columnsSql = new StringBuilder(); + StringBuilder valuesSql = new StringBuilder(); + StringBuilder updatesSql = new StringBuilder(); List params = new ArrayList<>(allColumnBindings.size()); // PostgreSQL references the proposed row via EXCLUDED."col", so each parameter is bound once. for (Map.Entry entry : allColumnBindings.entrySet()) { - columns.add(quoteIdentifier(entry.getKey())); + String colName = entry.getKey(); + String quotedCol = quoteIdentifier(colName); ColumnBinding binding = entry.getValue(); - values.add(binding.getPlaceholderSql()); + if (columnsSql.length() > 0) { + columnsSql.append(','); + valuesSql.append(','); + } + columnsSql.append(quotedCol); + valuesSql.append(binding.getPlaceholderSql()); params.addAll(binding.getParams()); - } - String conflictCols = - primaryKeys.stream() - .map(PostgreSQLDMLGenerator::quoteIdentifier) - .collect(Collectors.joining(",")); - Set pkSet = new HashSet<>(primaryKeys); - String updateValues = - allColumnBindings.keySet().stream() - .filter(k -> !pkSet.contains(k)) - .map( - k -> { - String quoted = quoteIdentifier(k); - return quoted + " = EXCLUDED." + quoted; - }) - .collect(Collectors.joining(",")); + boolean isPk = + singlePk != null + ? singlePk.equals(colName) + : (pkSet != null ? pkSet.contains(colName) : primaryKeys.contains(colName)); + if (!isPk) { + if (updatesSql.length() > 0) { + updatesSql.append(','); + } + updatesSql.append(quotedCol).append(" = EXCLUDED.").append(quotedCol); + } + } StringBuilder sql = new StringBuilder("INSERT INTO ") .append(quoteIdentifier(tableName)) .append(" (") - .append(String.join(",", columns)) + .append(columnsSql) .append(") VALUES (") - .append(String.join(",", values)) - .append(") ON CONFLICT (") - .append(conflictCols) - .append(") "); - if (updateValues.isEmpty()) { + .append(valuesSql) + .append(") ON CONFLICT ("); + for (int i = 0; i < primaryKeys.size(); i++) { + if (i > 0) { + sql.append(','); + } + sql.append(quoteIdentifier(primaryKeys.get(i))); + } + sql.append(") "); + if (updatesSql.length() == 0) { sql.append("DO NOTHING"); } else { - sql.append("DO UPDATE SET ").append(updateValues); + sql.append("DO UPDATE SET ").append(updatesSql); } return newResponse(sql.toString(), params); @@ -345,20 +331,25 @@ private static DMLGeneratorResponse getUpsertStatement( */ private static DMLGeneratorResponse getDeleteStatement( String tableName, Map pkColumnBindings) { - List conditions = new ArrayList<>(pkColumnBindings.size()); + StringBuilder sql = + new StringBuilder("DELETE FROM ").append(quoteIdentifier(tableName)).append(" WHERE "); List params = new ArrayList<>(pkColumnBindings.size()); + boolean first = true; for (Map.Entry entry : pkColumnBindings.entrySet()) { + if (!first) { + sql.append(" AND "); + } + first = false; ColumnBinding binding = entry.getValue(); + sql.append(quoteIdentifier(entry.getKey())); if (isNullBinding(binding)) { - conditions.add(quoteIdentifier(entry.getKey()) + " IS NULL"); + sql.append(" IS NULL"); } else { - conditions.add(quoteIdentifier(entry.getKey()) + " = " + binding.getPlaceholderSql()); + sql.append(" = ").append(binding.getPlaceholderSql()); params.addAll(binding.getParams()); } } - String sql = - "DELETE FROM " + quoteIdentifier(tableName) + " WHERE " + String.join(" AND ", conditions); - return newResponse(sql, params); + return newResponse(sql.toString(), params); } /** @@ -376,42 +367,6 @@ private static DMLGeneratorResponse newResponse(String sql, List params) return response; } - private static DMLGeneratorResponse generateUpsertStatement( - Table spannerTable, - SourceTable sourceTable, - DMLGeneratorRequest dmlGeneratorRequest, - Map pkColumnBindings) { - // When any PK column is generated, getPkColumnBindings already includes all non-PK columns; - // reuse that map directly instead of resolving non-PK columns twice. - if (hasGeneratedPrimaryKey(sourceTable)) { - return getUpsertStatement( - sourceTable.name(), pkColumnBindings, sourceTable.primaryKeyColumns()); - } - Map columnBindings = - DMLGeneratorUtils.getColumnBindings( - dmlGeneratorRequest.getSchemaMapper(), - spannerTable, - sourceTable, - dmlGeneratorRequest.getNewValuesJson(), - dmlGeneratorRequest.getKeyValuesJson(), - dmlGeneratorRequest.getSourceDbTimezoneOffset(), - dmlGeneratorRequest.getCustomTransformationResponse(), - COLUMN_BINDING_MAPPER, - PostgreSQLDMLGenerator::getCustomValueBinding); - columnBindings.putAll(pkColumnBindings); - return getUpsertStatement(sourceTable.name(), columnBindings, sourceTable.primaryKeyColumns()); - } - - private static boolean hasGeneratedPrimaryKey(SourceTable sourceTable) { - for (String pkColName : sourceTable.primaryKeyColumns()) { - SourceColumn col = sourceTable.column(pkColName); - if (col != null && col.isGenerated()) { - return true; - } - } - return false; - } - /** * Quotes a PostgreSQL identifier with double quotes, escaping embedded double quotes by doubling * them. @@ -424,18 +379,79 @@ static String quoteIdentifier(String identifier) { 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). + if (rawPgType == null) { + return OTHER; + } + PgColumnType direct = TYPE_MAP.get(rawPgType); + if (direct != null) { + return direct; + } + return TYPE_MAP.getOrDefault(DMLGeneratorUtils.normalizeSourceType(rawPgType), OTHER); + } + } + /** * Returns a SQL {@code NULL} binding whose placeholder matches the non-null placeholder of the * PostgreSQL column so the generated SQL text stays stable for {@code pgjdbc} statement caching. */ @VisibleForTesting static ColumnBinding getNullColumnBinding(SourceColumn sourceColDef) { - PgColumnType pgType = PgColumnType.fromSourceType(sourceColDef.type()); - if (pgType == PgColumnType.TIMESTAMP) { - return ColumnBinding.of( - TIMESTAMPTZ_PLACEHOLDER, ImmutableList.of(PreparedStatementValue.nullValue(Types.NULL))); - } - return ColumnBinding.of(PreparedStatementValue.nullValue(Types.NULL)); + return PgColumnType.fromSourceType(sourceColDef.type()) == PgColumnType.TIMESTAMP + ? NULL_TIMESTAMPTZ_BINDING + : NULL_BINDING; } /** @@ -447,10 +463,7 @@ static ColumnBinding getNullColumnBinding(SourceColumn sourceColDef) { */ @VisibleForTesting static ColumnBinding getMappedColumnBinding( - Column spannerColDef, - SourceColumn sourceColDef, - JSONObject valuesJson, - String sourceDbTimezoneOffset) { + Column spannerColDef, SourceColumn sourceColDef, JSONObject valuesJson) { Type colType = spannerColDef.type(); String colName = spannerColDef.name(); Type.Code code = colType.getCode(); @@ -468,52 +481,54 @@ static ColumnBinding getMappedColumnBinding( return ColumnBinding.of(PreparedStatementValue.ofBytes(bytes)); } - switch (pgType) { - case CHARACTER: - String charValue = getSpannerTextValue(colType, valuesJson, colName); - return ColumnBinding.of(PreparedStatementValue.ofString(removeNullBytes(charValue))); - case TIMESTAMP: - // Spanner timestamps are UTC. Casting via ?::timestamptz converts to the database session - // timezone for timestamp-without-tz columns (sourceDbTimezoneOffset is not applied). - String tsValue = getSpannerTextValue(colType, valuesJson, colName); - return ColumnBinding.of( - TIMESTAMPTZ_PLACEHOLDER, - ImmutableList.of(PreparedStatementValue.ofUntypedString(removeNullBytes(tsValue)))); - case BOOLEAN: - return ColumnBinding.of(getBooleanBindingValue(colType, valuesJson, colName)); - case INTEGER: - case FLOAT4: - case FLOAT8: - case DECIMAL: - return ColumnBinding.of(getNumberBindingValue(colType, pgType, valuesJson, colName)); - case OTHER: - default: - // Structured, temporal, binary-from-string, arrays (e.g. from Spanner STRING), - // USER-DEFINED (enums/domains), and unknown columns use Types.OTHER so pgjdbc sends OID - // UNSPECIFIED and PostgreSQL infers the type. - // TODO: Add PostgreSQL array literal formatting and ?::timestamptz[] casting when - // AssignShardIdFn supports Spanner ARRAY columns end-to-end. - String otherValue = getSpannerTextValue(colType, valuesJson, colName); - return ColumnBinding.of( - PreparedStatementValue.ofUntypedString(removeNullBytes(otherValue))); - } + 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(getBooleanBindingValue(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 | NumberFormatException e) { // Omit the cause because org.json's JSONException and NumberFormatException embed raw column // values in their messages, which SourceWriterFn appends to DLQ error records. throw new InvalidDMLGenerationException( - String.format( - "Failed to convert column %s (Spanner type %s, PostgreSQL type %s): %s", - sourceColDef.name(), colType, sourceColDef.type(), e.getClass().getSimpleName())); + formatConversionError(sourceColDef, colType, e.getClass().getSimpleName())); } catch (IllegalArgumentException e) { // Preserve cause/stack trace for non-value-bearing errors such as invalid Base64 decoding. throw new InvalidDMLGenerationException( - String.format( - "Failed to convert column %s (Spanner type %s, PostgreSQL type %s): %s", - sourceColDef.name(), colType, sourceColDef.type(), e.getClass().getSimpleName()), - e); + formatConversionError(sourceColDef, colType, e.getClass().getSimpleName()), e); } } + private static String formatConversionError( + SourceColumn sourceColDef, Type colType, String exceptionName) { + return String.format( + "Failed to convert column %s (Spanner type %s, PostgreSQL type %s): %s", + sourceColDef.name(), colType, sourceColDef.type(), exceptionName); + } + /** * 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 @@ -523,44 +538,40 @@ static ColumnBinding getMappedColumnBinding( static ColumnBinding getCustomValueBinding( SourceColumn sourceColDef, @Nullable Object customValue) { if (customValue == null || JSONObject.NULL.equals(customValue)) { - return ColumnBinding.of(PreparedStatementValue.nullValue(Types.NULL)); + return NULL_BINDING; } PgColumnType pgType = PgColumnType.fromSourceType(sourceColDef.type()); - // Character columns must always receive VARCHAR (never bytea/number/bool OIDs) so DELETE works. - if (pgType == PgColumnType.CHARACTER) { - if (customValue instanceof byte[]) { - return ColumnBinding.of( - PreparedStatementValue.ofString(toPostgresHexByteaText((byte[]) customValue))); - } - return ColumnBinding.of( - PreparedStatementValue.ofString(removeNullBytes(customValue.toString()))); - } - - // Raw byte[] targeting non-character columns binds directly via setBytes. + // 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[]) { - return ColumnBinding.of(PreparedStatementValue.ofBytes((byte[]) customValue)); - } + byte[] bytes = (byte[]) customValue; + return pgType == PgColumnType.CHARACTER + ? ColumnBinding.of(PreparedStatementValue.ofString(toPostgresHexByteaText(bytes))) + : ColumnBinding.of(PreparedStatementValue.ofBytes(bytes)); + } + + 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))); + }; + } - switch (pgType) { - case BOOLEAN: - if (customValue instanceof Boolean) { - return ColumnBinding.of(PreparedStatementValue.ofBoolean((Boolean) customValue)); - } - return ColumnBinding.of(booleanTextToParam(customValue.toString())); - case INTEGER: - case FLOAT4: - case FLOAT8: - case DECIMAL: - return ColumnBinding.of(customNumberToParam(customValue, pgType)); - case TIMESTAMP: - case OTHER: - default: - // Custom timestamp values use plain '?' without ::timestamptz so user-formatted values are - // not double-converted; structured/array/unknown types bind untyped via Types.OTHER. - return ColumnBinding.of( - PreparedStatementValue.ofUntypedString(removeNullBytes(customValue.toString()))); - } + @Nullable + private static String safeStringWithoutNullBytes(Object value) { + String text = value.toString(); + return text == null ? null : DMLGeneratorUtils.removeNullBytes(text); } private static PreparedStatementValue getBooleanBindingValue( @@ -572,8 +583,11 @@ private static PreparedStatementValue getBooleanBindingValue( return booleanTextToParam(getSpannerTextValue(colType, valuesJson, colName)); } - private static PreparedStatementValue booleanTextToParam(String value) { - String cleaned = removeNullBytes(value); + private static PreparedStatementValue booleanTextToParam(@Nullable String value) { + if (value == null) { + return PreparedStatementValue.ofUntypedString(null); + } + String cleaned = DMLGeneratorUtils.removeNullBytes(value); String trimmed = cleaned.trim(); if ("true".equalsIgnoreCase(trimmed)) { return PreparedStatementValue.ofBoolean(true); @@ -588,33 +602,30 @@ private static PreparedStatementValue booleanTextToParam(String value) { private static PreparedStatementValue getNumberBindingValue( Type colType, PgColumnType pgType, JSONObject valuesJson, String colName) { - // Bind real (float4) untyped so PostgreSQL always resolves float4in/float4eq even when pgjdbc - // binaryTransfer is disabled (where setFloat falls back to OID float8). - if (pgType == PgColumnType.FLOAT4) { - String text = getSpannerTextValue(colType, valuesJson, colName); - return PreparedStatementValue.ofUntypedString(removeNullBytes(text)); - } - Type.Code code = colType.getCode(); if (DMLGeneratorUtils.isFloatOrPgNumeric(code) || code == Type.Code.NUMERIC) { - String nonFiniteText = DMLGeneratorUtils.getNonFiniteText(valuesJson, colName); - if (nonFiniteText != null) { - return nonFiniteToNumberParam(nonFiniteText, pgType); - } 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) and numeric targets avoid new BigDecimal(double) - // binary expansion. + // 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); } - // Guard against O(N^2) BigDecimal parsing on oversized numeric strings before getBigDecimal. - if (raw instanceof String && ((String) raw).trim().length() > MAX_BIG_DECIMAL_TEXT_LENGTH) { - return PreparedStatementValue.ofUntypedString(removeNullBytes((String) raw)); - } - BigDecimal decimalValue = valuesJson.getBigDecimal(colName); - String originalText = (raw instanceof String) ? removeNullBytes((String) raw) : null; - return decimalToNumberParam(decimalValue, pgType, originalText); + return decimalToNumberParam(valuesJson.getBigDecimal(colName), pgType, null); } if (code == Type.Code.INT64 || code == Type.Code.PG_INT8) { @@ -624,7 +635,21 @@ private static PreparedStatementValue getNumberBindingValue( if (raw instanceof Long || raw instanceof Integer || raw instanceof Short) { return longToNumberParam(((Number) raw).longValue(), pgType); } - return numberTextToParam((raw instanceof String) ? (String) raw : raw.toString(), 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); @@ -633,10 +658,6 @@ private static PreparedStatementValue getNumberBindingValue( private static PreparedStatementValue customNumberToParam( Object customValue, PgColumnType pgType) { - // Bind real (float4) untyped so PostgreSQL always resolves float4 regardless of transfer mode. - if (pgType == PgColumnType.FLOAT4) { - return PreparedStatementValue.ofUntypedString(removeNullBytes(customValue.toString())); - } if (customValue instanceof String) { return numberTextToParam((String) customValue, pgType); } @@ -657,49 +678,59 @@ private static PreparedStatementValue customNumberToParam( } // 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(removeNullBytes(customValue.toString())); + return PreparedStatementValue.ofUntypedString(safeStringWithoutNullBytes(customValue)); } private static PreparedStatementValue longToNumberParam(long value, PgColumnType pgType) { - if (pgType == PgColumnType.FLOAT8) { - return PreparedStatementValue.ofDouble((double) value); - } - if (pgType == PgColumnType.DECIMAL) { - return PreparedStatementValue.ofBigDecimal(BigDecimal.valueOf(value)); - } - // OID INT8 (20) uses int2/int4/int8 B-tree indexes on DELETE. - return PreparedStatementValue.ofLong(value); + 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) { - if (pgType == PgColumnType.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)) { - return PreparedStatementValue.ofDouble(d); + 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()); } - return PreparedStatementValue.ofUntypedString( - originalText != null ? originalText : decimalValue.toString()); - } - if (pgType == PgColumnType.INTEGER) { - try { - return 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. + 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); } @@ -721,41 +752,47 @@ private static PreparedStatementValue floatingNumberToParam(Number value, PgColu } private static PreparedStatementValue nonFiniteToNumberParam( - String nonFiniteText, PgColumnType pgType) { + String trimmedNonFiniteText, PgColumnType pgType) { if (pgType == PgColumnType.FLOAT8) { - return PreparedStatementValue.ofDouble(parseNonFiniteDouble(nonFiniteText)); + 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(nonFiniteText); + return PreparedStatementValue.ofUntypedString(trimmedNonFiniteText); } /** - * Converts a string targeting a PostgreSQL number 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}; {@code real} and any non-numeric, - * oversized, or out-of-bounds text bind via {@link Types#OTHER} as data. + * 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(String value, PgColumnType pgType) { - String cleaned = removeNullBytes(value); - PreparedStatementValue typed = tryParseNumber(cleaned.trim(), cleaned, pgType); - return typed != null ? typed : PreparedStatementValue.ofUntypedString(cleaned); - } - - @Nullable - private static PreparedStatementValue tryParseNumber( - String trimmed, String cleaned, PgColumnType pgType) { + 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 null; + return PreparedStatementValue.ofUntypedString(cleaned); } - if (isNonFiniteLiteral(trimmed)) { + if (DMLGeneratorUtils.isNonFiniteTrimmed(trimmed)) { return nonFiniteToNumberParam(trimmed, pgType); } if (trimmed.length() > MAX_BIG_DECIMAL_TEXT_LENGTH) { - return null; + return PreparedStatementValue.ofUntypedString(cleaned); } - if (INTEGER_LITERAL.matcher(trimmed).matches()) { + if (isAsciiIntegerLiteral(trimmed)) { if (pgType == PgColumnType.INTEGER) { try { return PreparedStatementValue.ofLong(Long.parseLong(trimmed)); @@ -771,27 +808,35 @@ private static PreparedStatementValue tryParseNumber( return decimalToNumberParam(new BigDecimal(trimmed), pgType, cleaned); } catch (NumberFormatException e) { // Exponent overflow in BigDecimal(String) falls back to untyped binding. - return null; + return PreparedStatementValue.ofUntypedString(cleaned); } } - return null; - } - - private static boolean isWithinPostgresNumericBounds(BigDecimal bd) { - long scale = bd.scale(); - long integerDigits = (long) bd.precision() - scale; - return scale <= PG_NUMERIC_MAX_SCALE && integerDigits <= PG_NUMERIC_MAX_INTEGER_DIGITS; + return PreparedStatementValue.ofUntypedString(cleaned); } - private static double parseNonFiniteDouble(String text) { - String lower = text.trim().toLowerCase(Locale.ROOT); - if ("nan".equals(lower)) { - return Double.NaN; + private static boolean isAsciiIntegerLiteral(String trimmed) { + int len = trimmed.length(); + int start = 0; + char first = trimmed.charAt(0); + if (first == '+' || first == '-') { + if (len == 1) { + return false; + } + start = 1; } - if ("-infinity".equals(lower)) { - return Double.NEGATIVE_INFINITY; + for (int i = start; i < len; i++) { + char c = trimmed.charAt(i); + if (c < '0' || c > '9') { + return false; + } } - return Double.POSITIVE_INFINITY; + return true; + } + + 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; } /** @@ -812,22 +857,25 @@ private static String getSpannerTextValue(Type colType, JSONObject valuesJson, S 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 bd = valuesJson.getBigDecimal(colName); - return isWithinPostgresNumericBounds(bd) ? bd.toPlainString() : bd.toString(); + BigDecimal decimalValue = valuesJson.getBigDecimal(colName); + // Guard toPlainString() with PostgreSQL numeric bounds to avoid OOM on extreme exponents. + return isWithinPostgresNumericBounds(decimalValue) + ? decimalValue.toPlainString() + : decimalValue.toString(); } - if (DMLGeneratorUtils.isFloatOrPgNumeric(code)) { - // PG_NUMERIC is handled above; remaining codes are FLOAT32/FLOAT64/PG_FLOAT4/PG_FLOAT8. + if (isSpannerFloat(code)) { Object raw = valuesJson.get(colName); if (raw instanceof String) { String trimmed = ((String) raw).trim(); - return isNonFiniteLiteral(trimmed) ? trimmed : (String) raw; + return DMLGeneratorUtils.isNonFiniteTrimmed(trimmed) ? trimmed : (String) raw; } if (raw instanceof Double || raw instanceof Float) { return raw.toString(); } - return DMLGeneratorUtils.getSpannerValueAsString(colType, valuesJson, colName); + return valuesJson.getBigDecimal(colName).toString(); } if (code == Type.Code.BOOL || code == Type.Code.PG_BOOL @@ -838,13 +886,11 @@ private static String getSpannerTextValue(Type colType, JSONObject valuesJson, S return (raw instanceof String) ? (String) raw : raw.toString(); } - private static boolean isNonFiniteLiteral(@Nullable String text) { - return text != null && NON_FINITE_VALUES.contains(text.trim().toLowerCase(Locale.ROOT)); - } - - /** Strips NUL ({@code U+0000}) characters, which PostgreSQL rejects in UTF-8 text. */ - private static String removeNullBytes(String input) { - return StringUtils.replace(input, "\u0000", ""); + private static boolean isSpannerFloat(Type.Code code) { + return code == Type.Code.FLOAT32 + || code == Type.Code.FLOAT64 + || code == Type.Code.PG_FLOAT4 + || code == Type.Code.PG_FLOAT8; } /** 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 2d0d15afd2..566f44264d 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,19 @@ 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")); + } + @Test public void testNormalizeSourceType() { assertEquals("", DMLGeneratorUtils.normalizeSourceType(null)); @@ -562,6 +575,13 @@ public void testNormalizeSourceType() { 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 269875461c..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; @@ -121,7 +123,7 @@ public void testOfUntypedStringDirectBindAndAccessors() throws Exception { PreparedStatementValue nullVal = PreparedStatementValue.ofUntypedString(null); assertTrue(nullVal.isNull()); assertEquals(Types.OTHER, nullVal.getSqlType()); - assertEquals(null, nullVal.getValue()); + assertNull(nullVal.getValue()); assertEquals(PreparedStatementValue.nullValue(Types.OTHER), nullVal); nullVal.bind(mockPreparedStatement, 2); verify(mockPreparedStatement).setNull(2, Types.OTHER); @@ -201,10 +203,11 @@ public void testEqualsHashCodeAndToString() { PreparedStatementValue untyped = PreparedStatementValue.ofUntypedString("x"); PreparedStatementValue typed = PreparedStatementValue.ofString("x"); - assertFalse(untyped.equals(typed)); - assertFalse(typed.equals(untyped)); + assertNotEquals(untyped, typed); + assertNotEquals(typed, untyped); assertEquals(untyped, PreparedStatementValue.ofUntypedString("x")); assertEquals(untyped.hashCode(), PreparedStatementValue.ofUntypedString("x").hashCode()); - assertEquals("PreparedStatementValue{value=x, sqlType=1111}", untyped.toString()); + 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 50140fac6a..5766f47a09 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 @@ -143,17 +143,16 @@ public void primaryKeyNotFoundInJson() { JSONObject newValuesJson = new JSONObject().put("FirstName", "kk").put("LastName", "ll"); JSONObject keyValuesJson = new JSONObject().put("SomeRandomName", "999"); - assertThrows( - InvalidDMLGenerationException.class, - () -> - new PostgreSQLDMLGenerator() - .getDMLStatement( - new DMLGeneratorRequest.Builder( - "INSERT", "Singers", newValuesJson, keyValuesJson, "+00:00") - .setSchemaMapper(schemaMapper) - .setDdl(ddl) - .setSourceSchema(sourceSchema) - .build())); + 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 @@ -166,17 +165,16 @@ public void primaryKeyNotPresentInSourceSchema() { JSONObject newValuesJson = new JSONObject().put("FirstName", "kk").put("LastName", "ll"); JSONObject keyValuesJson = new JSONObject().put("SingerId", "999"); - assertThrows( - InvalidDMLGenerationException.class, - () -> - new PostgreSQLDMLGenerator() - .getDMLStatement( - new DMLGeneratorRequest.Builder( - "INSERT", "Singers", newValuesJson, keyValuesJson, "+00:00") - .setSchemaMapper(schemaMapper) - .setDdl(ddl) - .setSourceSchema(sourceSchema) - .build())); + 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 @@ -304,46 +302,48 @@ record = IOUtils.toString(stream, StandardCharsets.UTF_8); @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"); 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); - assertThrows( - InvalidDMLGenerationException.class, - () -> - generator.getDMLStatement( - new DMLGeneratorRequest.Builder( - "INSERT", "T", new JSONObject(), new JSONObject(), "+00:00") - .setSchemaMapper(schemaMapper) - .setDdl(null) - .setSourceSchema(sourceSchema) - .build())); - - 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 @@ -353,21 +353,21 @@ public void testUnsupportedModType() { SourceSchema sourceSchema = SchemaUtils.buildSourceSchemaFromSessionFile(sessionFile); ISchemaMapper schemaMapper = new SessionBasedMapper(sessionFile, ddl); - assertThrows( - InvalidDMLGenerationException.class, - () -> - new PostgreSQLDMLGenerator() - .getDMLStatement( - new DMLGeneratorRequest.Builder( - "REPLACE", - "Singers", - new JSONObject().put("FirstName", "a"), - new JSONObject().put("SingerId", "1"), - "+00:00") - .setSchemaMapper(schemaMapper) - .setDdl(ddl) - .setSourceSchema(sourceSchema) - .build())); + 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"); } @Test @@ -414,12 +414,12 @@ public void testConversionFailure_wrapsWithColumnNameAndTypesWithoutRawValue() { InvalidDMLGenerationException.class, () -> bindValue(Type.bytes(), "bytea", badSecretBase64)); // Non-value-bearing IllegalArgumentException preserves cause/stack trace without leaking value. - assertThat(bytesEx.getCause()).isInstanceOf(IllegalArgumentException.class); - assertThat(bytesEx.getMessage()).contains("test_col"); - assertThat(bytesEx.getMessage()).contains("bytea"); - assertThat(bytesEx.getMessage()).contains("IllegalArgumentException"); - assertThat(bytesEx.getMessage()).doesNotContain(badSecretBase64); - assertThat(bytesEx.getCause().getMessage()).doesNotContain(badSecretBase64); + 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). @@ -427,10 +427,10 @@ public void testConversionFailure_wrapsWithColumnNameAndTypesWithoutRawValue() { assertThrows( InvalidDMLGenerationException.class, () -> bindValue(Type.bool(), "boolean", "secret-not-a-json-bool")); - assertThat(jsonEx.getCause()).isNull(); - assertThat(jsonEx.getMessage()).contains("test_col"); - assertThat(jsonEx.getMessage()).contains("JSONException"); - assertThat(jsonEx.getMessage()).doesNotContain("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"); } @Test @@ -471,17 +471,25 @@ public void testTimestampScalarAndNullBindingsStabilizePlaceholder() { "TIMESTAMP WITH TIME ZONE" }) { ColumnBinding nonNull = bind(spannerTsType, tsType, "2023-05-18T12:01:13.088397258Z"); - assertThat(nonNull.getPlaceholderSql()).isEqualTo("?::timestamptz"); - assertThat(nonNull.getParams()) + 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 = PostgreSQLDMLGenerator.getNullColumnBinding(srcCol("ts", tsType)); - assertThat(nullBinding.getPlaceholderSql()).isEqualTo("?::timestamptz"); - assertThat(PostgreSQLDMLGenerator.isNullBinding(nullBinding)).isTrue(); - assertThat(nullBinding.getParams()) + 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)); } } @@ -541,8 +549,8 @@ public void testBooleanAndCrossTypeSafety() { } @Test - public void testNumericIntegerAndDecimalBindings() { - // Integer targets: exact integers (including padded, decimal, scientific) bind as Long. + 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 ")) @@ -564,7 +572,12 @@ public void testNumericIntegerAndDecimalBindings() { .isEqualTo(PreparedStatementValue.ofBigDecimal(new BigDecimal("9223372036854775808"))); assertThat(bindValue(Type.string(), "integer", "")) .isEqualTo(PreparedStatementValue.ofUntypedString("")); + assertThat(bindValue(Type.string(), "integer", "+")) + .isEqualTo(PreparedStatementValue.ofUntypedString("+")); + } + @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"))); @@ -585,6 +598,14 @@ public void testNumericIntegerAndDecimalBindings() { 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)); + } + + @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")); @@ -596,28 +617,21 @@ public void testNumericIntegerAndDecimalBindings() { .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. - assertThat(bindValue(Type.string(), "numeric", "1E+999999999999")) - .isEqualTo(PreparedStatementValue.ofUntypedString("1E+999999999999")); for (String targetType : new String[] {"numeric", "double precision", "integer"}) { - assertThat(bindValue(Type.string(), targetType, "1e9999999999")) + assertWithMessage("positive exponent overflow for %s", targetType) + .that(bindValue(Type.string(), targetType, "1e9999999999")) .isEqualTo(PreparedStatementValue.ofUntypedString("1e9999999999")); - assertThat(bindValue(Type.string(), targetType, "1e-2147483648")) + assertWithMessage("negative exponent overflow for %s", targetType) + .that(bindValue(Type.string(), targetType, "1e-2147483648")) .isEqualTo(PreparedStatementValue.ofUntypedString("1e-2147483648")); } - assertThat(bindValue(Type.string(), "numeric", "-1E-9999999999")) - .isEqualTo(PreparedStatementValue.ofUntypedString("-1E-9999999999")); - assertThat(bindValue(Type.string(), "double precision", "-1E-9999999999")) - .isEqualTo(PreparedStatementValue.ofUntypedString("-1E-9999999999")); InvalidDMLGenerationException pgNumericExtremeEx = assertThrows( InvalidDMLGenerationException.class, () -> bind(Type.pgNumeric(), "numeric", "1e9999999999")); - assertThat(pgNumericExtremeEx.getMessage()).doesNotContain("1e9999999999"); - assertThat(bindValue(Type.pgNumeric(), "numeric", overCapDigits)) - .isEqualTo(PreparedStatementValue.ofUntypedString(overCapDigits)); - assertThat(bindValue(Type.float32(), "real", overCapDigits)) - .isEqualTo(PreparedStatementValue.ofUntypedString(overCapDigits)); + assertThat(pgNumericExtremeEx).hasMessageThat().doesNotContain("1e9999999999"); // Programmatic Double/Float targeting numeric avoids new BigDecimal(double) binary expansion. assertThat(bindValue(Type.float64(), "numeric", 52.67d)) @@ -627,7 +641,23 @@ public void testNumericIntegerAndDecimalBindings() { } @Test - public void testNumericFloatOverflowUnderflowAndNonFinite() { + 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 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("test_col"); @@ -636,8 +666,7 @@ public void testNumericFloatOverflowUnderflowAndNonFinite() { PostgreSQLDMLGenerator.getMappedColumnBinding( spannerCol, srcCol("test_col", "double precision"), - new JSONObject("{\"test_col\": -0.0}"), - "+00:00"); + new JSONObject("{\"test_col\": -0.0}")); PreparedStatementValue negZeroParam = negZeroBinding.getParams().get(0); assertThat(negZeroParam.getSqlType()).isEqualTo(Types.DOUBLE); assertThat(Double.doubleToRawLongBits((Double) negZeroParam.getValue())) @@ -650,15 +679,18 @@ public void testNumericFloatOverflowUnderflowAndNonFinite() { when(float4Col.type()).thenReturn(float4SpannerType); ColumnBinding negZeroReal = PostgreSQLDMLGenerator.getMappedColumnBinding( - float4Col, - srcCol("test_col", "real"), - new JSONObject("{\"test_col\": -0.0}"), - "+00:00"); - assertThat(negZeroReal.getPlaceholderSql()).isEqualTo("?"); - assertThat(negZeroReal.getParams()) + 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")); } + } + @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)) @@ -673,7 +705,10 @@ public void testNumericFloatOverflowUnderflowAndNonFinite() { .isEqualTo(PreparedStatementValue.ofUntypedString("Infinity")); assertThat(bindValue(Type.float32(), "real", "-Infinity")) .isEqualTo(PreparedStatementValue.ofUntypedString("-Infinity")); + } + @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")) @@ -688,8 +723,10 @@ public void testNumericFloatOverflowUnderflowAndNonFinite() { .isEqualTo(PreparedStatementValue.ofUntypedString("1E+500")); assertThat(bindValue(Type.pgNumeric(), "double precision", "1E-500")) .isEqualTo(PreparedStatementValue.ofUntypedString("1E-500")); + } - // Non-finite floats/numerics across double precision, numeric, integer, and text. + @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")) @@ -781,8 +818,7 @@ public void testStringEncodedNegativeZeroForDoublePrecision() { } @Test - public void testCustomTransformationBindingsDispatchedByTargetType() { - // Character targets always bind as VARCHAR regardless of Java object type. + public void customBinding_characterTarget_alwaysBindsVarchar() { assertThat(customValue("text", "kk ll")).isEqualTo(PreparedStatementValue.ofString("kk ll")); assertThat(customValue("varchar", "'quoted'")) .isEqualTo(PreparedStatementValue.ofString("'quoted'")); @@ -793,8 +829,10 @@ public void testCustomTransformationBindingsDispatchedByTargetType() { assertThat(customValue("text", Double.NaN)).isEqualTo(PreparedStatementValue.ofString("NaN")); assertThat(customValue("text", "abc".getBytes(StandardCharsets.UTF_8))) .isEqualTo(PreparedStatementValue.ofString("\\x616263")); + } - // Number targets dispatch by PostgreSQL column type. + @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)); @@ -827,18 +865,21 @@ public void testCustomTransformationBindingsDispatchedByTargetType() { .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")); + } - // Boolean targets bind Boolean as ofBoolean and other inputs untyped. + @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", 1)).isEqualTo(PreparedStatementValue.ofUntypedString("1")); - // Structured, array, temporal, and binary targets. assertThat(customValue("jsonb", "{\"k\":1}")) .isEqualTo(PreparedStatementValue.ofUntypedString("{\"k\":1}")); assertThat(customValue("jsonb", 42)).isEqualTo(PreparedStatementValue.ofUntypedString("42")); @@ -855,8 +896,10 @@ public void testCustomTransformationBindingsDispatchedByTargetType() { 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")); + } - // Null & JSONObject.NULL both bind as Types.NULL with plain '?' placeholder. + @Test + public void customBinding_nullAndTimestampTargets_usePlainPlaceholder() { assertThat(customValue("integer", null)) .isEqualTo(PreparedStatementValue.nullValue(Types.NULL)); assertThat(customValue("integer", JSONObject.NULL)) @@ -1019,6 +1062,21 @@ public void testSymmetricalInsertAndDeleteAcrossPgPkTypes() { .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") @@ -1031,6 +1089,10 @@ public void testSymmetricalInsertAndDeleteAcrossPgPkTypes() { .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(); @@ -1049,7 +1111,11 @@ public void testSymmetricalInsertAndDeleteAcrossPgPkTypes() { srcCol("bool_pk", "boolean"), srcCol("int_pk", "integer"), srcCol("text_pk", "text"), - srcCol("char_pk", "character"))) + 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", @@ -1062,7 +1128,11 @@ public void testSymmetricalInsertAndDeleteAcrossPgPkTypes() { "bool_pk", "int_pk", "text_pk", - "char_pk")) + "char_pk", + "bytes_text_pk", + "enum_pk", + "jsonb_pk", + "time_pk")) .build(); SourceSchema sourceSchema = SourceSchema.builder(SourceDatabaseType.POSTGRESQL) @@ -1082,7 +1152,11 @@ public void testSymmetricalInsertAndDeleteAcrossPgPkTypes() { "bool_pk", "int_pk", "text_pk", - "char_pk"); + "char_pk", + "bytes_text_pk", + "enum_pk", + "jsonb_pk", + "time_pk"); JSONObject keys = new JSONObject() @@ -1096,7 +1170,11 @@ public void testSymmetricalInsertAndDeleteAcrossPgPkTypes() { .put("bool_pk", true) .put("int_pk", "42") .put("text_pk", "ignored") - .put("char_pk", "abc "); + .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); @@ -1131,24 +1209,32 @@ public void testSymmetricalInsertAndDeleteAcrossPgPkTypes() { PreparedStatementValue.ofBoolean(true), PreparedStatementValue.ofLong(42L), PreparedStatementValue.ofString("123"), - PreparedStatementValue.ofString("abc ")); + 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\") " - + "VALUES (?,?,?,?,?,?::timestamptz,?,?,?,?,?) " + + "\"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\")" + + "\"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 \"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); @@ -1417,45 +1503,49 @@ public void testCompositeRegularAndGeneratedPrimaryKeyUpsertAndDelete() { public void testInformationSchemaScannerDataTypesMatrix() { // Verifies the exact information_schema.columns.data_type strings emitted by // PostgreSQLInformationSchemaScanner.scanColumns. - Map expectedCategories = new HashMap<>(); - expectedCategories.put("character varying", PgColumnType.CHARACTER); - expectedCategories.put("character", PgColumnType.CHARACTER); - expectedCategories.put("text", PgColumnType.CHARACTER); - expectedCategories.put("name", PgColumnType.CHARACTER); - expectedCategories.put("smallint", PgColumnType.INTEGER); - expectedCategories.put("integer", PgColumnType.INTEGER); - expectedCategories.put("bigint", PgColumnType.INTEGER); - expectedCategories.put("real", PgColumnType.FLOAT4); - expectedCategories.put("double precision", PgColumnType.FLOAT8); - expectedCategories.put("numeric", PgColumnType.DECIMAL); - expectedCategories.put("boolean", PgColumnType.BOOLEAN); - expectedCategories.put("timestamp without time zone", PgColumnType.TIMESTAMP); - expectedCategories.put("timestamp with time zone", PgColumnType.TIMESTAMP); - expectedCategories.put("timestamp without time zone[]", PgColumnType.OTHER); - expectedCategories.put("timestamp with time zone[]", PgColumnType.OTHER); - expectedCategories.put("character varying[]", PgColumnType.OTHER); - expectedCategories.put("integer[]", PgColumnType.OTHER); - expectedCategories.put("bytea[]", PgColumnType.OTHER); - expectedCategories.put("USER-DEFINED[]", PgColumnType.OTHER); - expectedCategories.put("ARRAY", PgColumnType.OTHER); - expectedCategories.put("citext", PgColumnType.OTHER); - expectedCategories.put("bytea", PgColumnType.OTHER); - expectedCategories.put("date", PgColumnType.OTHER); - expectedCategories.put("time without time zone", PgColumnType.OTHER); - expectedCategories.put("time with time zone", PgColumnType.OTHER); - expectedCategories.put("interval", PgColumnType.OTHER); - expectedCategories.put("json", PgColumnType.OTHER); - expectedCategories.put("jsonb", PgColumnType.OTHER); - expectedCategories.put("uuid", PgColumnType.OTHER); - expectedCategories.put("money", PgColumnType.OTHER); - expectedCategories.put("bit", PgColumnType.OTHER); - expectedCategories.put("bit varying", PgColumnType.OTHER); - expectedCategories.put("inet", PgColumnType.OTHER); - expectedCategories.put("xml", PgColumnType.OTHER); - expectedCategories.put("USER-DEFINED", PgColumnType.OTHER); + 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()) { - assertThat(PgColumnType.fromSourceType(entry.getKey())).isEqualTo(entry.getValue()); + 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. @@ -1481,10 +1571,6 @@ public void testInformationSchemaScannerDataTypesMatrix() { .isEqualTo(PreparedStatementValue.ofUntypedString("")); } - // --------------------------------------------------------------------------------------------- - // SQL Injection Regression Tests - // --------------------------------------------------------------------------------------------- - @Test public void sqlInjection_spannerStringMappedToNonStringAndDefaultPostgresTypes() { String payload = "0); DROP TABLE pwned; --"; @@ -1749,16 +1835,17 @@ public void testGetDMLStatement_SchemaAndPkValidationFailures() { ISchemaMapper mapper = mock(ISchemaMapper.class); // Spanner table missing from DDL. - assertThrows( - InvalidDMLGenerationException.class, - () -> - generator.getDMLStatement( - new DMLGeneratorRequest.Builder( - "INSERT", "MissingTable", new JSONObject(), new JSONObject(), "+00:00") - .setSchemaMapper(mapper) - .setDdl(emptyDdl) - .setSourceSchema(sourceSchema) - .build())); + 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 = @@ -1774,36 +1861,38 @@ public void testGetDMLStatement_SchemaAndPkValidationFailures() { .build(); when(mapper.getSourceTableName("", "Singers")) .thenThrow(new NoSuchElementException("unmapped")); - assertThrows( - InvalidDMLGenerationException.class, - () -> - generator.getDMLStatement( - new DMLGeneratorRequest.Builder( - "INSERT", "Singers", new JSONObject(), new JSONObject(), "+00:00") - .setSchemaMapper(mapper) - .setDdl(singersDdl) - .setSourceSchema(sourceSchema) - .build())); + 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")); - assertThrows( - InvalidDMLGenerationException.class, - () -> - generator.getDMLStatement( - new DMLGeneratorRequest.Builder( - "DELETE", - "Singers", - new JSONObject(), - new JSONObject().put("SingerId", "1"), - "+00:00") - .setSchemaMapper(unmappedPkMapper) - .setDdl(singersDdl) - .setSourceSchema(sourceSchema) - .build())); + 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 @@ -1969,6 +2058,62 @@ public void testGetDMLStatement_NullValueInUpsert() { 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(); } @@ -1979,7 +2124,7 @@ private static ColumnBinding bind(Type spannerType, String pgType, Object value) when(spannerCol.type()).thenReturn(spannerType); SourceColumn sourceCol = srcCol("test_col", pgType); return PostgreSQLDMLGenerator.getMappedColumnBinding( - spannerCol, sourceCol, new JSONObject().put("test_col", value), "+00:00"); + spannerCol, sourceCol, new JSONObject().put("test_col", value)); } private static PreparedStatementValue bindValue(Type spannerType, String pgType, Object value) { @@ -2046,26 +2191,17 @@ private static String describeParams(@Nullable List params) { } private static String sqlTypeName(int sqlType) { - switch (sqlType) { - case Types.VARCHAR: - return "VARCHAR"; - case Types.OTHER: - return "OTHER"; - case Types.VARBINARY: - return "VARBINARY"; - case Types.BOOLEAN: - return "BOOLEAN"; - case Types.DECIMAL: - return "DECIMAL"; - case Types.BIGINT: - return "BIGINT"; - case Types.DOUBLE: - return "DOUBLE"; - case Types.NULL: - return "NULL"; - default: - return "sqlType=" + 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; + }; } private static byte[] decodeBase64(String encoded) { From a75594d14e1db30a1149550f9ffe821b16cccb34 Mon Sep 17 00:00:00 2001 From: aasthabharill Date: Fri, 4 Dec 2026 09:59:55 +0000 Subject: [PATCH 4/6] Simplify PostgreSQL DML generation helpers and cover text-path edge cases - Restore the list + String.join form of getUpsertStatement and the INTEGER_LITERAL regex, replacing the hand-written fast paths. - PgColumnType.fromSourceType does a single normalized lookup. - Inline getBooleanBindingValue and formatConversionError; make isSpannerFloat a local variable. - isNonFiniteTrimmed uses a Locale.ROOT lower-cased set lookup again, so only ASCII spellings of NaN / Infinity match (equalsIgnoreCase also matched the Turkish dotless and dotted i). - Reword comments on NULL timestamp placeholders and dropped exception causes to say what the code guarantees. - Tests: string "false" into boolean columns, non-finite text via Spanner STRING and custom values, INT64 string edge cases (0, -0, out of long range, non-numeric, BigInteger), and decimals in the shape org.json parses from text. --- .../dbutils/dml/DMLGeneratorUtils.java | 18 +- .../postgres/PostgreSQLDMLGenerator.java | 156 +++++++----------- .../dbutils/dml/DMLGeneratorUtilsTest.java | 3 + .../postgres/PostgreSQLDMLGeneratorTest.java | 39 +++++ 4 files changed, 105 insertions(+), 111 deletions(-) diff --git a/v2/spanner-to-sourcedb/src/main/java/com/google/cloud/teleport/v2/templates/dbutils/dml/DMLGeneratorUtils.java b/v2/spanner-to-sourcedb/src/main/java/com/google/cloud/teleport/v2/templates/dbutils/dml/DMLGeneratorUtils.java index 6e971817e8..f3c7644eb1 100644 --- a/v2/spanner-to-sourcedb/src/main/java/com/google/cloud/teleport/v2/templates/dbutils/dml/DMLGeneratorUtils.java +++ b/v2/spanner-to-sourcedb/src/main/java/com/google/cloud/teleport/v2/templates/dbutils/dml/DMLGeneratorUtils.java @@ -21,6 +21,7 @@ import com.google.cloud.teleport.v2.spanner.sourceddl.SourceColumn; import com.google.cloud.teleport.v2.spanner.sourceddl.SourceTable; import com.google.cloud.teleport.v2.spanner.type.Type; +import com.google.common.collect.ImmutableSet; import java.sql.Types; import java.util.Base64; import java.util.LinkedHashMap; @@ -40,6 +41,10 @@ public class DMLGeneratorUtils { private static final Logger LOG = LoggerFactory.getLogger(DMLGeneratorUtils.class); + /** Lower-cased text of non-finite float / numeric values in the change stream. */ + private static final ImmutableSet NON_FINITE_VALUES = + ImmutableSet.of("nan", "infinity", "+infinity", "-infinity"); + @FunctionalInterface public interface ColumnValueMapper { String getMappedColumnValue( @@ -226,18 +231,7 @@ public static String getSpannerValueAsString( * literal ({@code NaN}, {@code Infinity}, {@code +Infinity}, or {@code -Infinity}). */ public static boolean isNonFiniteTrimmed(String trimmed) { - int len = trimmed.length(); - if (len == 3) { - return "nan".equalsIgnoreCase(trimmed); - } - if (len == 8) { - return "infinity".equalsIgnoreCase(trimmed); - } - if (len == 9) { - char first = trimmed.charAt(0); - return (first == '+' || first == '-') && trimmed.regionMatches(true, 1, "infinity", 0, 8); - } - return false; + return NON_FINITE_VALUES.contains(trimmed.toLowerCase(Locale.ROOT)); } /** diff --git a/v2/spanner-to-sourcedb/src/main/java/com/google/cloud/teleport/v2/templates/source/postgres/PostgreSQLDMLGenerator.java b/v2/spanner-to-sourcedb/src/main/java/com/google/cloud/teleport/v2/templates/source/postgres/PostgreSQLDMLGenerator.java index dc7999c60c..e926d66a2f 100644 --- a/v2/spanner-to-sourcedb/src/main/java/com/google/cloud/teleport/v2/templates/source/postgres/PostgreSQLDMLGenerator.java +++ b/v2/spanner-to-sourcedb/src/main/java/com/google/cloud/teleport/v2/templates/source/postgres/PostgreSQLDMLGenerator.java @@ -46,6 +46,7 @@ import java.util.NoSuchElementException; import java.util.Set; import java.util.regex.Pattern; +import java.util.stream.Collectors; import javax.annotation.Nullable; import org.apache.commons.lang3.StringUtils; import org.json.JSONException; @@ -96,7 +97,7 @@ public class PostgreSQLDMLGenerator implements IDMLGenerator { private static final ColumnBinding NULL_BINDING = ColumnBinding.of(PreparedStatementValue.nullValue(Types.NULL)); - /** Cached SQL {@code NULL} binding preserving {@code ?::timestamptz} for statement caching. */ + /** Cached SQL {@code NULL} binding that keeps the {@code ?::timestamptz} placeholder. */ private static final ColumnBinding NULL_TIMESTAMPTZ_BINDING = ColumnBinding.of( TIMESTAMPTZ_PLACEHOLDER, ImmutableList.of(PreparedStatementValue.nullValue(Types.NULL))); @@ -113,6 +114,9 @@ public class PostgreSQLDMLGenerator implements IDMLGenerator { */ private static final int MAX_BIG_DECIMAL_TEXT_LENGTH = 2048; + /** Matches signed base-10 integer literals (for example {@code -42}, {@code +7}). */ + private static final Pattern INTEGER_LITERAL = Pattern.compile("[+-]?\\d+"); + /** Matches fixed-point decimal literals (for example {@code 1.5}, {@code .5}, {@code 5.}). */ private static final Pattern DECIMAL_LITERAL = Pattern.compile("[+-]?(\\d+\\.\\d*|\\.\\d+)"); @@ -268,57 +272,47 @@ private static boolean hasGeneratedPrimaryKey(SourceTable sourceTable) { */ private static DMLGeneratorResponse getUpsertStatement( String tableName, Map allColumnBindings, List primaryKeys) { - String singlePk = primaryKeys.size() == 1 ? primaryKeys.get(0) : null; - Set pkSet = primaryKeys.size() > 3 ? new HashSet<>(primaryKeys) : null; - StringBuilder columnsSql = new StringBuilder(); - StringBuilder valuesSql = new StringBuilder(); - StringBuilder updatesSql = new StringBuilder(); + List columns = new ArrayList<>(allColumnBindings.size()); + List values = new ArrayList<>(allColumnBindings.size()); List params = new ArrayList<>(allColumnBindings.size()); // PostgreSQL references the proposed row via EXCLUDED."col", so each parameter is bound once. for (Map.Entry entry : allColumnBindings.entrySet()) { - String colName = entry.getKey(); - String quotedCol = quoteIdentifier(colName); + columns.add(quoteIdentifier(entry.getKey())); ColumnBinding binding = entry.getValue(); - if (columnsSql.length() > 0) { - columnsSql.append(','); - valuesSql.append(','); - } - columnsSql.append(quotedCol); - valuesSql.append(binding.getPlaceholderSql()); + values.add(binding.getPlaceholderSql()); params.addAll(binding.getParams()); - - boolean isPk = - singlePk != null - ? singlePk.equals(colName) - : (pkSet != null ? pkSet.contains(colName) : primaryKeys.contains(colName)); - if (!isPk) { - if (updatesSql.length() > 0) { - updatesSql.append(','); - } - updatesSql.append(quotedCol).append(" = EXCLUDED.").append(quotedCol); - } } + String conflictCols = + primaryKeys.stream() + .map(PostgreSQLDMLGenerator::quoteIdentifier) + .collect(Collectors.joining(",")); + Set pkSet = new HashSet<>(primaryKeys); + String updateValues = + allColumnBindings.keySet().stream() + .filter(k -> !pkSet.contains(k)) + .map( + k -> { + String quoted = quoteIdentifier(k); + return quoted + " = EXCLUDED." + quoted; + }) + .collect(Collectors.joining(",")); + StringBuilder sql = new StringBuilder("INSERT INTO ") .append(quoteIdentifier(tableName)) .append(" (") - .append(columnsSql) + .append(String.join(",", columns)) .append(") VALUES (") - .append(valuesSql) - .append(") ON CONFLICT ("); - for (int i = 0; i < primaryKeys.size(); i++) { - if (i > 0) { - sql.append(','); - } - sql.append(quoteIdentifier(primaryKeys.get(i))); - } - sql.append(") "); - if (updatesSql.length() == 0) { + .append(String.join(",", values)) + .append(") ON CONFLICT (") + .append(conflictCols) + .append(") "); + if (updateValues.isEmpty()) { sql.append("DO NOTHING"); } else { - sql.append("DO UPDATE SET ").append(updatesSql); + sql.append("DO UPDATE SET ").append(updateValues); } return newResponse(sql.toString(), params); @@ -432,20 +426,15 @@ static PgColumnType fromSourceType(@Nullable String rawPgType) { // 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). - if (rawPgType == null) { - return OTHER; - } - PgColumnType direct = TYPE_MAP.get(rawPgType); - if (direct != null) { - return direct; - } return TYPE_MAP.getOrDefault(DMLGeneratorUtils.normalizeSourceType(rawPgType), OTHER); } } /** * Returns a SQL {@code NULL} binding whose placeholder matches the non-null placeholder of the - * PostgreSQL column so the generated SQL text stays stable for {@code pgjdbc} statement caching. + * PostgreSQL column, so the generated SQL text is the same for null and non-null values. The SQL + * text is the key of {@code pgjdbc}'s statement cache; reusing a server-prepared statement also + * requires the parameter types to match. */ @VisibleForTesting static ColumnBinding getNullColumnBinding(SourceColumn sourceColDef) { @@ -496,7 +485,10 @@ static ColumnBinding getMappedColumnBinding( PreparedStatementValue.ofUntypedString( DMLGeneratorUtils.removeNullBytes( getSpannerTextValue(colType, valuesJson, colName))))); - case BOOLEAN -> ColumnBinding.of(getBooleanBindingValue(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 -> @@ -510,25 +502,21 @@ static ColumnBinding getMappedColumnBinding( DMLGeneratorUtils.removeNullBytes( getSpannerTextValue(colType, valuesJson, colName)))); }; - } catch (JSONException | NumberFormatException e) { - // Omit the cause because org.json's JSONException and NumberFormatException embed raw column - // values in their messages, which SourceWriterFn appends to DLQ error records. - throw new InvalidDMLGenerationException( - formatConversionError(sourceColDef, colType, e.getClass().getSimpleName())); - } catch (IllegalArgumentException e) { - // Preserve cause/stack trace for non-value-bearing errors such as invalid Base64 decoding. - throw new InvalidDMLGenerationException( - formatConversionError(sourceColDef, colType, e.getClass().getSimpleName()), e); + } 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); } } - private static String formatConversionError( - SourceColumn sourceColDef, Type colType, String exceptionName) { - return String.format( - "Failed to convert column %s (Spanner type %s, PostgreSQL type %s): %s", - sourceColDef.name(), colType, sourceColDef.type(), exceptionName); - } - /** * 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 @@ -574,15 +562,6 @@ private static String safeStringWithoutNullBytes(Object value) { return text == null ? null : DMLGeneratorUtils.removeNullBytes(text); } - private static PreparedStatementValue getBooleanBindingValue( - Type colType, JSONObject valuesJson, String colName) { - Type.Code code = colType.getCode(); - if (code == Type.Code.BOOL || code == Type.Code.PG_BOOL) { - return PreparedStatementValue.ofBoolean(valuesJson.getBoolean(colName)); - } - return booleanTextToParam(getSpannerTextValue(colType, valuesJson, colName)); - } - private static PreparedStatementValue booleanTextToParam(@Nullable String value) { if (value == null) { return PreparedStatementValue.ofUntypedString(null); @@ -792,7 +771,7 @@ private static PreparedStatementValue numberTextToParam( if (trimmed.length() > MAX_BIG_DECIMAL_TEXT_LENGTH) { return PreparedStatementValue.ofUntypedString(cleaned); } - if (isAsciiIntegerLiteral(trimmed)) { + if (INTEGER_LITERAL.matcher(trimmed).matches()) { if (pgType == PgColumnType.INTEGER) { try { return PreparedStatementValue.ofLong(Long.parseLong(trimmed)); @@ -814,25 +793,6 @@ private static PreparedStatementValue numberTextToParam( return PreparedStatementValue.ofUntypedString(cleaned); } - private static boolean isAsciiIntegerLiteral(String trimmed) { - int len = trimmed.length(); - int start = 0; - char first = trimmed.charAt(0); - if (first == '+' || first == '-') { - if (len == 1) { - return false; - } - start = 1; - } - for (int i = start; i < len; i++) { - char c = trimmed.charAt(i); - if (c < '0' || c > '9') { - return false; - } - } - return true; - } - private static boolean isWithinPostgresNumericBounds(BigDecimal decimalValue) { long scale = decimalValue.scale(); long integerDigits = (long) decimalValue.precision() - scale; @@ -866,7 +826,12 @@ private static String getSpannerTextValue(Type colType, JSONObject valuesJson, S ? decimalValue.toPlainString() : decimalValue.toString(); } - if (isSpannerFloat(code)) { + 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(); @@ -886,13 +851,6 @@ private static String getSpannerTextValue(Type colType, JSONObject valuesJson, S return (raw instanceof String) ? (String) raw : raw.toString(); } - private static boolean isSpannerFloat(Type.Code code) { - return code == Type.Code.FLOAT32 - || code == Type.Code.FLOAT64 - || code == Type.Code.PG_FLOAT4 - || code == Type.Code.PG_FLOAT8; - } - /** * Formats bytes using PostgreSQL's default {@code bytea_output = hex} representation ({@code * \x...}). 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 566f44264d..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 @@ -563,6 +563,9 @@ public void testIsNonFiniteTrimmed() { 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 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 5766f47a09..054a0ea10f 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 @@ -521,6 +521,8 @@ public void testBooleanAndCrossTypeSafety() { .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")) @@ -546,6 +548,20 @@ public void testBooleanAndCrossTypeSafety() { .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 @@ -723,6 +739,15 @@ public void floatBinding_doublePrecision_handlesRangeAndOverflowUnderflow() { .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"))); } @Test @@ -753,6 +778,19 @@ public void floatBinding_nonFiniteValues_dispatchedByTargetType() { .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 @@ -878,6 +916,7 @@ 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}")) From bf9d344f91a1118598d30971c2a340e64e74ed72 Mon Sep 17 00:00:00 2001 From: aasthabharill <77983396+aasthabharill@users.noreply.github.com> Date: Fri, 4 Dec 2026 15:38:05 +0530 Subject: [PATCH 5/6] Update README.md --- v2/spanner-to-sourcedb/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/v2/spanner-to-sourcedb/README.md b/v2/spanner-to-sourcedb/README.md index be4a1f51d7..1fa5237480 100644 --- a/v2/spanner-to-sourcedb/README.md +++ b/v2/spanner-to-sourcedb/README.md @@ -483,7 +483,7 @@ Steps to perform customization: 4. If any events are filtered/skipped during the reverse transformation they can be written to a GCS directory by passing the GCS path via the *filterEventsDirectoryName* input to the runner. 5. If any custom parameters are needed in the custom transformation logic, they can be passed via the *transformationCustomParameters* input to the runner. These parameters will be passed to the *init* method of the custom class. The *init* method is invoked once per worker setup. -> **Note:** For MySQL and PostgreSQL reverse replication, `toSourceRow()` output values are bound strictly as query parameters (raw data), never as SQL fragments. Do **not** wrap string values in single quotes (`'abc'`) or return SQL expressions (such as `now()` or `decode(...)`), as quotes and function calls will be stored literally or rejected by the database. +> **Note:** `toSourceRow()` output values are bound strictly as query parameters (raw data), never as SQL fragments. Do **not** wrap string values in single quotes (`'abc'`) or return SQL expressions (such as `now()` or `decode(...)`), as quotes and function calls will be stored literally or rejected by the database. ## Cost From 8e438ae37d97efa6b97322f556d163165acab415 Mon Sep 17 00:00:00 2001 From: aasthabharill Date: Fri, 4 Dec 2026 17:15:09 +0000 Subject: [PATCH 6/6] Bind typed NULLs for PostgreSQL and share removeNullBytes across JDBC sources - getNullColumnBinding returns a NULL with the JDBC type of the column's non-null values (VARCHAR, BIGINT, BOOLEAN, DOUBLE, DECIMAL, VARBINARY). pgjdbc reuses a server-prepared statement only while parameter types stay the same, so an untyped NULL forced a Close and re-Parse whenever a column switched between NULL and a value. Timestamp and untyped (Types.OTHER) columns keep an untyped NULL, which already matches their values. - Null custom transformation values use the same mapping. - Oracle and SQL Server call DMLGeneratorUtils.removeNullBytes instead of their own inline copy of the same replace. - Tests: one test pinning that a NULL binds with the placeholder and parameter type of the column's values, and updated NULL expectations. --- .../source/oracle/OracleDMLGenerator.java | 2 +- .../postgres/PostgreSQLDMLGenerator.java | 59 +++++++++++---- .../sqlserver/SQLServerDMLGenerator.java | 3 +- .../postgres/PostgreSQLDMLGeneratorTest.java | 74 ++++++++++++++++--- 4 files changed, 113 insertions(+), 25 deletions(-) diff --git a/v2/spanner-to-sourcedb/src/main/java/com/google/cloud/teleport/v2/templates/source/oracle/OracleDMLGenerator.java b/v2/spanner-to-sourcedb/src/main/java/com/google/cloud/teleport/v2/templates/source/oracle/OracleDMLGenerator.java index 3a4cfaf323..500fac61bc 100644 --- a/v2/spanner-to-sourcedb/src/main/java/com/google/cloud/teleport/v2/templates/source/oracle/OracleDMLGenerator.java +++ b/v2/spanner-to-sourcedb/src/main/java/com/google/cloud/teleport/v2/templates/source/oracle/OracleDMLGenerator.java @@ -499,7 +499,7 @@ private static Object toBindValue( // Non-BYTES Spanner value (e.g. STRING) written to a binary column: Base64 encoded bytes. return toTypedBindValue(bindSqlType, decodeBase64(colInputValue)); } - return toBindValueByType(sourceType, StringUtils.replace(colInputValue, "\u0000", "")); + return toBindValueByType(sourceType, DMLGeneratorUtils.removeNullBytes(colInputValue)); } /** Converts a non-BYTES Spanner value to its string form. */ diff --git a/v2/spanner-to-sourcedb/src/main/java/com/google/cloud/teleport/v2/templates/source/postgres/PostgreSQLDMLGenerator.java b/v2/spanner-to-sourcedb/src/main/java/com/google/cloud/teleport/v2/templates/source/postgres/PostgreSQLDMLGenerator.java index e926d66a2f..d4dc34ec55 100644 --- a/v2/spanner-to-sourcedb/src/main/java/com/google/cloud/teleport/v2/templates/source/postgres/PostgreSQLDMLGenerator.java +++ b/v2/spanner-to-sourcedb/src/main/java/com/google/cloud/teleport/v2/templates/source/postgres/PostgreSQLDMLGenerator.java @@ -93,15 +93,31 @@ public class PostgreSQLDMLGenerator implements IDMLGenerator { /** SQL fragment casting a bound UTC timestamp string to {@code timestamptz}. */ private static final String TIMESTAMPTZ_PLACEHOLDER = "?::timestamptz"; - /** Cached SQL {@code NULL} binding for non-timestamp columns. */ + /** SQL {@code NULL} binding without a parameter type, for columns whose values bind untyped. */ private static final ColumnBinding NULL_BINDING = ColumnBinding.of(PreparedStatementValue.nullValue(Types.NULL)); - /** Cached SQL {@code NULL} binding that keeps the {@code ?::timestamptz} placeholder. */ + /** Untyped SQL {@code NULL} binding that keeps the {@code ?::timestamptz} placeholder. */ private static final ColumnBinding NULL_TIMESTAMPTZ_BINDING = ColumnBinding.of( TIMESTAMPTZ_PLACEHOLDER, ImmutableList.of(PreparedStatementValue.nullValue(Types.NULL))); + // SQL NULL bindings with the JDBC type of the non-null values of each column category. pgjdbc + // reuses a server-prepared statement only while the parameter types stay the same, so a NULL + // must not change the type of its position. + private static final ColumnBinding NULL_VARCHAR_BINDING = + ColumnBinding.of(PreparedStatementValue.nullValue(Types.VARCHAR)); + private static final ColumnBinding NULL_BOOLEAN_BINDING = + ColumnBinding.of(PreparedStatementValue.nullValue(Types.BOOLEAN)); + private static final ColumnBinding NULL_BIGINT_BINDING = + ColumnBinding.of(PreparedStatementValue.nullValue(Types.BIGINT)); + private static final ColumnBinding NULL_DOUBLE_BINDING = + ColumnBinding.of(PreparedStatementValue.nullValue(Types.DOUBLE)); + private static final ColumnBinding NULL_DECIMAL_BINDING = + ColumnBinding.of(PreparedStatementValue.nullValue(Types.DECIMAL)); + private static final ColumnBinding NULL_VARBINARY_BINDING = + ColumnBinding.of(PreparedStatementValue.nullValue(Types.VARBINARY)); + /** PostgreSQL NUMERIC precision limits (up to 131072 integer digits, scale up to 16383). */ private static final int PG_NUMERIC_MAX_INTEGER_DIGITS = 131072; @@ -142,7 +158,7 @@ public ColumnBinding getColumnBinding( @Override public ColumnBinding getNullColumnBinding(Column spannerColDef, SourceColumn sourceColDef) { - return PostgreSQLDMLGenerator.getNullColumnBinding(sourceColDef); + return PostgreSQLDMLGenerator.getNullColumnBinding(spannerColDef, sourceColDef); } }; @@ -431,16 +447,33 @@ static PgColumnType fromSourceType(@Nullable String rawPgType) { } /** - * Returns a SQL {@code NULL} binding whose placeholder matches the non-null placeholder of the - * PostgreSQL column, so the generated SQL text is the same for null and non-null values. The SQL - * text is the key of {@code pgjdbc}'s statement cache; reusing a server-prepared statement also - * requires the parameter types to match. + * 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(SourceColumn sourceColDef) { - return PgColumnType.fromSourceType(sourceColDef.type()) == PgColumnType.TIMESTAMP - ? NULL_TIMESTAMPTZ_BINDING - : NULL_BINDING; + 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); + } + + /** 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; + }; } /** @@ -525,10 +558,10 @@ static ColumnBinding getMappedColumnBinding( @VisibleForTesting static ColumnBinding getCustomValueBinding( SourceColumn sourceColDef, @Nullable Object customValue) { + PgColumnType pgType = PgColumnType.fromSourceType(sourceColDef.type()); if (customValue == null || JSONObject.NULL.equals(customValue)) { - return NULL_BINDING; + return typedNullBinding(pgType); } - PgColumnType pgType = PgColumnType.fromSourceType(sourceColDef.type()); // 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. 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/source/postgres/PostgreSQLDMLGeneratorTest.java b/v2/spanner-to-sourcedb/src/test/java/com/google/cloud/teleport/v2/templates/source/postgres/PostgreSQLDMLGeneratorTest.java index 054a0ea10f..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 @@ -480,8 +480,7 @@ public void testTimestampScalarAndNullBindingsStabilizePlaceholder() { PreparedStatementValue.ofUntypedString("2023-05-18T12:01:13.088397258Z")); // Null timestamps reuse ?::timestamptz so pgjdbc sees one stable SQL statement per table. - ColumnBinding nullBinding = - PostgreSQLDMLGenerator.getNullColumnBinding(srcCol("ts", tsType)); + ColumnBinding nullBinding = nullBindingFor(spannerTsType, tsType); assertWithMessage("null placeholder for %s", tsType) .that(nullBinding.getPlaceholderSql()) .isEqualTo("?::timestamptz"); @@ -495,6 +494,49 @@ public void testTimestampScalarAndNullBindingsStabilizePlaceholder() { } } + @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); + } + } + @Test public void testReachableArrayTargetAndScalarArrayBindings() { // Spanner STRING mapped to a PostgreSQL array column (reachable through AssignShardIdFn) @@ -939,12 +981,20 @@ public void customBinding_booleanAndStructuredTargets_dispatchByPostgresType() { @Test 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.NULL)); + .isEqualTo(PreparedStatementValue.nullValue(Types.BIGINT)); assertThat(customValue("integer", JSONObject.NULL)) - .isEqualTo(PreparedStatementValue.nullValue(Types.NULL)); + .isEqualTo(PreparedStatementValue.nullValue(Types.BIGINT)); assertThat(customValue("text", JSONObject.NULL)) - .isEqualTo(PreparedStatementValue.nullValue(Types.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 = @@ -1029,7 +1079,7 @@ public void testCustomTransformationEndToEndIncludingNull() { + " ON CONFLICT (\"SingerId\") DO UPDATE SET \"FullName\" = EXCLUDED.\"FullName\""); assertParams( nullResponse.getPreparedStatementParameters(), - PreparedStatementValue.nullValue(Types.NULL), + PreparedStatementValue.nullValue(Types.VARCHAR), PreparedStatementValue.ofLong(999L)); // JSONObject.NULL custom transformation output also binds as SQL NULL end-to-end. @@ -1055,7 +1105,7 @@ public void testCustomTransformationEndToEndIncludingNull() { + " ON CONFLICT (\"SingerId\") DO UPDATE SET \"FullName\" = EXCLUDED.\"FullName\""); assertParams( jsonNullResponse.getPreparedStatementParameters(), - PreparedStatementValue.nullValue(Types.NULL), + PreparedStatementValue.nullValue(Types.VARCHAR), PreparedStatementValue.ofLong(999L)); } @@ -1422,7 +1472,7 @@ public void testGeneratedColumnsAndGeneratedPkUpsertAndDeleteWithNull() { assertParams( upsertResp.getPreparedStatementParameters(), PreparedStatementValue.ofString("Ada"), - PreparedStatementValue.nullValue(Types.NULL)); + PreparedStatementValue.nullValue(Types.VARCHAR)); // Delete on generated-PK table emits IS NULL for null non-PK columns instead of "= ?". DMLGeneratorResponse deleteResp = @@ -2093,7 +2143,7 @@ public void testGetDMLStatement_NullValueInUpsert() { assertParams( response.getPreparedStatementParameters(), PreparedStatementValue.ofString("kk"), - PreparedStatementValue.nullValue(Types.NULL), + PreparedStatementValue.nullValue(Types.VARCHAR), PreparedStatementValue.ofLong(999L)); } @@ -2166,6 +2216,12 @@ private static ColumnBinding bind(Type spannerType, String pgType, Object value) 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("?");