Skip to content

[SpannerToSourceDb] Migrate PostgreSQLDMLGenerator to PreparedStatement binding - #4664

Open
aasthabharill wants to merge 6 commits into
GoogleCloudPlatform:mainfrom
aasthabharill:pg-ps-3-postgres-dml
Open

aasthabharill wants to merge 6 commits into
GoogleCloudPlatform:mainfrom
aasthabharill:pg-ps-3-postgres-dml

Conversation

@aasthabharill

@aasthabharill aasthabharill commented Dec 1, 2026 •

Copy link
Copy Markdown
Member

Why This Change Is Required

PostgreSQLDMLGenerator previously built INSERT and DELETE statements by concatenating record values, custom transformation outputs, and identifiers into raw SQL strings. That left a SQL injection surface on unquoted/default column types, custom transformation responses, and double-quoted identifiers. It also caused runtime failures on non-finite floats (NaN/Infinity), USER-DEFINED enums, and time without time zone, and it generated DELETE statements that ran without error but could miss the row for real primary keys, and never matched for NULL values in generated-PK deletes ("col" = null).

Scope: this PR changes how the PostgreSQL generator builds and binds SQL. MySQL was migrated in #4644. The Oracle and SQL Server generators change only in calling the shared removeNullBytes helper.

Changes Made & What They Do

  • PreparedStatementValue & PreparedStatementValueTest:
    • Adds PreparedStatementValue.ofUntypedString(@Nullable String) (Types.OTHER) and binds it via setObject(idx, value, Types.OTHER).
    • pgjdbc sends Oid.VARCHAR for setString(), which PostgreSQL rejects for non-character columns (jsonb, uuid, date, time, timestamptz, real, enums, arrays). Types.OTHER sends Oid.UNSPECIFIED (0) so PostgreSQL parses the bound value using the target column type.
  • DMLGeneratorUtils, DMLGeneratorUtilsTest, MySQLDMLGenerator, OracleDMLGenerator, & SQLServerDMLGenerator:
    • Shares normalizeSourceType, removeNullBytes, and isNonFiniteTrimmed across the MySQL and PostgreSQL DML generators. The only MySQL difference is that source type names are trimmed before lookup. Oracle and SQL Server call removeNullBytes in place of their own inline copy of the same replace.
  • PostgreSQLDMLGenerator:
    • Replaces string-concatenated SQL generation with PreparedStatement parameter binding using the shared DMLGeneratorUtils / ColumnBinding / JdbcDao layer from [SourceDbToSpanner] Use prepared statements for Spanner to MySQL #4644.
    • Escapes double quotes (" -> "") in all table and column identifiers.
    • Dispatches bindings via PgColumnType (CHARACTER, TIMESTAMP, BOOLEAN, INTEGER, FLOAT8, DECIMAL, OTHER): ofString for character types, ?::timestamptz for timestamps (NULL timestamps keep the same placeholder, so the SQL text does not depend on whether the value is NULL), ofBoolean for booleans, ofLong / ofDouble / bounded ofBigDecimal for integers, double precision, and numeric, and ofUntypedString for real (ensuring DELETE matches regardless of pgjdbc binary-transfer mode) and all structured/temporal/enum/unknown types.
    • Binds NULL with the JDBC type of the column category's non-null values (VARCHAR, BIGINT, BOOLEAN, DOUBLE, DECIMAL, VARBINARY; untyped for timestamp and Types.OTHER columns, whose values are also untyped). A NULL then does not change the statement's parameter types, which pgjdbc requires to keep reusing a server-prepared statement. Null custom transformation values use the same mapping.
    • Emits "col" IS NULL on DELETE when a key binding is NULL (needed for generated-PK tables with nullable non-PK columns).
    • Binds custom transformation outputs strictly as parameter values (raw data) instead of splicing SQL text, matching [SourceDbToSpanner] Use prepared statements for Spanner to MySQL #4644.
    • Wraps value-conversion errors into InvalidDMLGenerationException with column name and types only. For JSONException and NumberFormatException the cause is left out so the raw value is not repeated in the error message; the error record still carries the change record itself.
  • PostgreSQLDMLGeneratorTest:
    • Replaces substring checks with exact SQL and ordered PreparedStatementValue assertions across information_schema types, 15-type PK INSERT/DELETE symmetry, IS NULL deletes, null-timestamp upserts, numeric precision/overflow/underflow/non-finite edge cases, text-path edge cases (string booleans, non-finite text, INT64 string boundaries), custom transformations, and SQL injection payloads.
  • v2/spanner-to-sourcedb/README.md:
    • Documents the MySQL and PostgreSQL custom transformation contract (raw values, no SQL quotes or expressions).

Breaking / Behavioral Changes

  • PostgreSQL custom transformations: toSourceRow() values are now bound as raw parameters, never SQL fragments. Custom jars must not wrap strings in single quotes ('abc') or return SQL expressions (now(), decode(...)). The string NULL is no longer SQL NULL; return Java null instead. Values for timestamp columns are bound with a plain ? (no ::timestamptz cast) and written as given.
  • DELETE with NULL key values: Null predicates now emit "col" IS NULL instead of "col" = null.
  • Boolean columns: String values other than true/false (for example t, 1, yes) are bound as untyped text for PostgreSQL's boolean input to parse, instead of being written unquoted into the SQL.
  • String values: NUL (U+0000) characters are stripped for all column types.
  • BYTES into character columns: Bound as PostgreSQL hex text (\x...) for both INSERT and DELETE.
  • FLOAT64 -0.0: Keeps its sign for double precision columns.
  • Execution: Statements run through PreparedStatement, so pgjdbc can switch to server-side prepared statements after prepareThreshold executions (default 5).

Verification

  • Local Maven (JAVA_HOME=/usr/lib/jvm/java-21-openjdk-amd64, -Dbeam.version=2.77.0):
    • mvn -pl v2/spanner-common,v2/spanner-custom-shard,v2/spanner-to-sourcedb spotless:check checkstyle:check test: 1,256 unit tests passed (0 failures, 0 Checkstyle violations, Spotless clean).
  • Unit tests use a mocked JDBC driver. Server-side behaviour of the new bindings is exercised by SpannerToPostgreSQLDataTypesIT (INSERT paths) and by follow-up [SpannerToSourceDb] Expand SpannerToPostgreSQLDataTypesIT CRUD and PK coverage #4665 (DELETE, non-bigint keys, enums, NULL deletes), which is stacked on this branch.

Related / Follow-up PRs

@codecov

codecov Bot commented Dec 1, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 94.45983% with 20 lines in your changes missing coverage. Please review.
✅ Project coverage is 67.93%. Comparing base (e4ea790) to head (8e438ae).
⚠️ Report is 10 commits behind head on main.

Files with missing lines Patch % Lines
...plates/source/postgres/PostgreSQLDMLGenerator.java 94.20% 5 Missing and 15 partials ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##               main    #4664      +/-   ##
============================================
+ Coverage     60.34%   67.93%   +7.59%     
+ Complexity     8965     3649    -5316     
============================================
  Files          1125      555     -570     
  Lines         72994    33079   -39915     
  Branches       8888     3842    -5046     
============================================
- Hits          44049    22473   -21576     
+ Misses        26016     9496   -16520     
+ Partials       2929     1110    -1819     
Components Coverage Δ
spanner-templates 86.24% <94.45%> (+0.13%) ⬆️
spanner-import-export ∅ <ø> (∅)
spanner-live-forward-migration 87.63% <ø> (-0.03%) ⬇️
spanner-live-reverse-replication 84.50% <94.45%> (+0.30%) ⬆️
spanner-bulk-migration 88.29% <ø> (+<0.01%) ⬆️
gcs-spanner-dv 86.54% <ø> (-0.04%) ⬇️
Files with missing lines Coverage Δ
...rt/v2/templates/dbutils/dml/DMLGeneratorUtils.java 99.31% <100.00%> (+0.01%) ⬆️
.../templates/dbutils/dml/PreparedStatementValue.java 100.00% <100.00%> (ø)
...t/v2/templates/source/mysql/MySQLDMLGenerator.java 98.84% <100.00%> (ø)
...v2/templates/source/oracle/OracleDMLGenerator.java 79.41% <100.00%> (ø)
...plates/source/sqlserver/SQLServerDMLGenerator.java 93.65% <100.00%> (-0.04%) ⬇️
...plates/source/postgres/PostgreSQLDMLGenerator.java 94.89% <94.20%> (+3.56%) ⬆️

... and 601 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@aasthabharill
aasthabharill marked this pull request as ready for review December 2, 2026 20:26
@aasthabharill
aasthabharill requested a review from a team as a code owner December 2, 2026 20:26
@gemini-code-assist

Copy link
Copy Markdown
Contributor

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request completes the migration of the PostgreSQL DML generation logic to use parameterized PreparedStatements. By moving away from manual SQL string construction, the implementation now benefits from improved security, better type safety, and more reliable handling of PostgreSQL-specific data types. The changes ensure that null values and complex types are correctly interpreted by the database driver, while also introducing necessary safeguards for numeric precision and floating-point edge cases.

Highlights

  • Migration to PreparedStatement: Migrated PostgreSQLDMLGenerator from string concatenation to parameterized PreparedStatement binding to eliminate SQL injection risks and improve type handling.
  • PostgreSQL Type Compatibility: Introduced PreparedStatementValue.ofUntypedString (Types.OTHER) to ensure pgjdbc correctly resolves PostgreSQL-specific types like jsonb, uuid, and arrays.
  • Behavioral Improvements: Updated DELETE logic to emit 'IS NULL' for null bindings and added robust handling for extreme numeric values, non-finite floats, and negative zero preservation.
  • Breaking Change: Custom transformations must now return raw data instead of SQL fragments, as values are strictly bound as parameters.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize the Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counterproductive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution. ↩

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request refactors the PostgreSQL DML generation in the Spanner-to-SourceDB template to use parameterized PreparedStatement bindings instead of raw SQL fragments. It introduces PreparedStatementValue.ofUntypedString (binding as Types.OTHER) to allow PostgreSQL to correctly infer target column types (such as JSONB, UUID, dates, and arrays) from string parameters. Additionally, it updates the documentation to reflect these changes and includes corresponding unit tests. I have no further feedback to provide as the implementation is robust and well-tested.

@aasthabharill
aasthabharill marked this pull request as draft December 3, 2026 05:46
aasthabharill and others added 4 commits December 4, 2026 07:10
…ases

- 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.
@aasthabharill
aasthabharill marked this pull request as ready for review December 4, 2026 10:15

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request refactors and enhances the DML generation logic for PostgreSQL in the Spanner-to-SourceDB template. It introduces parameterized query bindings for all column values to prevent SQL injection and ensure type safety, particularly addressing PostgreSQL's strict casting rules by utilizing untyped string bindings (Types.OTHER) for complex types like JSONB, UUID, and arrays. Additionally, common utility methods for string normalization and null-byte removal have been consolidated into DMLGeneratorUtils, and corresponding unit tests have been added. I have no feedback to provide as there are no review comments.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request refactors the PostgreSQL DML generation to use parameterized queries with prepared statement bindings instead of inline string formatting. It introduces untyped string bindings (Types.OTHER) to allow PostgreSQL to correctly infer target column types (such as JSONB, UUID, or arrays) and centralizes common utility methods (like string normalization and null-byte removal) in DMLGeneratorUtils. Additionally, the README is updated to clarify that custom transformation outputs are bound strictly as query parameters. There are no review comments, and I have no feedback to provide.

Comment on lines +439 to +444
@VisibleForTesting
static ColumnBinding getNullColumnBinding(SourceColumn sourceColDef) {
return PgColumnType.fromSourceType(sourceColDef.type()) == PgColumnType.TIMESTAMP
? NULL_TIMESTAMPTZ_BINDING
: NULL_BINDING;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As noted in the Javadoc above, reusing a server-prepared statement in pgjdbc requires parameter OIDs to match as well as the SQL text, but getNullColumnBinding currently returns NULL_BINDING (Types.NULL → Oid.UNSPECIFIED) for every non-timestamp column while non-null values bind typed OIDs (Oid.VARCHAR, Oid.BOOL, Oid.INT8, Oid.FLOAT8, Oid.NUMERIC, Oid.BYTEA).

In pgjdbc's SimpleQuery.isPreparedFor:

  1. Once a statement crosses prepareThreshold (default 5) on a pooled connection with non-null rows, unspecifiedParams is not set for those typed positions. When a NULL row arrives (Oid.UNSPECIFIED), isPreparedFor returns false, causing pgjdbc to unprepare (Close) and re-parse the statement.
  2. When re-parsed with Oid.UNSPECIFIED, PostgreSQL describes the parameter with the column's exact OID — which differs from the Java setter OID for text (TEXT vs VARCHAR), character/bpchar (BPCHAR vs VARCHAR), name (NAME vs VARCHAR), smallint (INT2 vs INT8), and integer (INT4 vs INT8). The next non-null row then fails isPreparedFor again, thrashing Close + Parse + Describe on every NULL ↔ non-NULL transition.

Returning cached typed-null bindings matching each column's non-null JDBC type keeps parameter OIDs consistent (and isNullBinding still returns true for DELETE ... IS NULL):

  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));

  @VisibleForTesting
  static ColumnBinding getNullColumnBinding(Column spannerColDef, SourceColumn sourceColDef) {
    PgColumnType pgType = PgColumnType.fromSourceType(sourceColDef.type());
    Type.Code code = spannerColDef.type().getCode();
    if ((code == Type.Code.BYTES || code == Type.Code.PG_BYTEA)
        && pgType != PgColumnType.CHARACTER) {
      return NULL_VARBINARY_BINDING;
    }
    return switch (pgType) {
      case CHARACTER -> NULL_VARCHAR_BINDING;
      case TIMESTAMP -> NULL_TIMESTAMPTZ_BINDING;
      case BOOLEAN -> NULL_BOOLEAN_BINDING;
      case INTEGER -> NULL_BIGINT_BINDING;
      case FLOAT8 -> NULL_DOUBLE_BINDING;
      case DECIMAL -> NULL_DECIMAL_BINDING;
      case OTHER -> NULL_BINDING;
    };
  }

The same CHARACTER/BOOLEAN/INTEGER/FLOAT8/DECIMAL typed-null mapping can also be reused for null custom values in getCustomValueBinding (lines 528–530, keeping NULL_BINDING for TIMESTAMP and OTHER).

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done. NULLs now bind with the column category's type, and null custom values use the same mapping.

@bharadwaj-aditya

Copy link
Copy Markdown
Contributor

Aside from the comments, overall looks fine.

… 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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants