Repository navigation
[SpannerToSourceDb] Migrate PostgreSQLDMLGenerator to PreparedStatement binding - #4664
aasthabharill wants to merge 6 commits into
Conversation
Codecov Report❌ Patch coverage is
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
🚀 New features to boost your workflow:
|
0c8317d to
cb2b8df
Compare
cb2b8df to
a513f77
Compare
a513f77 to
bad7025
Compare
Summary of ChangesHello, 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
Using Gemini Code AssistThe 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
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 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
|
There was a problem hiding this comment.
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.
…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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
| @VisibleForTesting | ||
| static ColumnBinding getNullColumnBinding(SourceColumn sourceColDef) { | ||
| return PgColumnType.fromSourceType(sourceColDef.type()) == PgColumnType.TIMESTAMP | ||
| ? NULL_TIMESTAMPTZ_BINDING | ||
| : NULL_BINDING; | ||
| } |
There was a problem hiding this comment.
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:
- Once a statement crosses
prepareThreshold(default 5) on a pooled connection with non-null rows,unspecifiedParamsis not set for those typed positions. When aNULLrow arrives (Oid.UNSPECIFIED),isPreparedForreturnsfalse, causingpgjdbcto unprepare (Close) and re-parse the statement. - When re-parsed with
Oid.UNSPECIFIED, PostgreSQL describes the parameter with the column's exact OID — which differs from the Java setter OID fortext(TEXTvsVARCHAR),character/bpchar(BPCHARvsVARCHAR),name(NAMEvsVARCHAR),smallint(INT2vsINT8), andinteger(INT4vsINT8). The next non-null row then failsisPreparedForagain, thrashingClose+Parse+Describeon everyNULL↔ non-NULLtransition.
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).
There was a problem hiding this comment.
Done. NULLs now bind with the column category's type, and null custom values use the same mapping.
|
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.
Why This Change Is Required
PostgreSQLDMLGeneratorpreviously builtINSERTandDELETEstatements 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-DEFINEDenums, andtime without time zone, and it generatedDELETEstatements that ran without error but could miss the row forrealprimary keys, and never matched forNULLvalues 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
removeNullByteshelper.Changes Made & What They Do
PreparedStatementValue&PreparedStatementValueTest:PreparedStatementValue.ofUntypedString(@Nullable String)(Types.OTHER) and binds it viasetObject(idx, value, Types.OTHER).pgjdbcsendsOid.VARCHARforsetString(), which PostgreSQL rejects for non-character columns (jsonb,uuid,date,time,timestamptz,real, enums, arrays).Types.OTHERsendsOid.UNSPECIFIED(0) so PostgreSQL parses the bound value using the target column type.DMLGeneratorUtils,DMLGeneratorUtilsTest,MySQLDMLGenerator,OracleDMLGenerator, &SQLServerDMLGenerator:normalizeSourceType,removeNullBytes, andisNonFiniteTrimmedacross the MySQL and PostgreSQL DML generators. The only MySQL difference is that source type names are trimmed before lookup. Oracle and SQL Server callremoveNullBytesin place of their own inline copy of the same replace.PostgreSQLDMLGenerator:PreparedStatementparameter binding using the sharedDMLGeneratorUtils/ColumnBinding/JdbcDaolayer from [SourceDbToSpanner] Use prepared statements for Spanner to MySQL #4644."->"") in all table and column identifiers.PgColumnType(CHARACTER,TIMESTAMP,BOOLEAN,INTEGER,FLOAT8,DECIMAL,OTHER):ofStringfor character types,?::timestamptzfor timestamps (NULLtimestamps keep the same placeholder, so the SQL text does not depend on whether the value isNULL),ofBooleanfor booleans,ofLong/ofDouble/ boundedofBigDecimalfor integers,double precision, andnumeric, andofUntypedStringforreal(ensuringDELETEmatches regardless ofpgjdbcbinary-transfer mode) and all structured/temporal/enum/unknown types.NULLwith the JDBC type of the column category's non-null values (VARCHAR,BIGINT,BOOLEAN,DOUBLE,DECIMAL,VARBINARY; untyped for timestamp andTypes.OTHERcolumns, whose values are also untyped). ANULLthen does not change the statement's parameter types, whichpgjdbcrequires to keep reusing a server-prepared statement. Null custom transformation values use the same mapping."col" IS NULLonDELETEwhen a key binding isNULL(needed for generated-PK tables with nullable non-PK columns).InvalidDMLGenerationExceptionwith column name and types only. ForJSONExceptionandNumberFormatExceptionthe 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:PreparedStatementValueassertions acrossinformation_schematypes, 15-type PKINSERT/DELETEsymmetry,IS NULLdeletes, null-timestamp upserts, numeric precision/overflow/underflow/non-finite edge cases, text-path edge cases (string booleans, non-finite text,INT64string boundaries), custom transformations, and SQL injection payloads.v2/spanner-to-sourcedb/README.md:Breaking / Behavioral Changes
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 stringNULLis no longer SQLNULL; return Javanullinstead. Values for timestamp columns are bound with a plain?(no::timestamptzcast) and written as given.DELETEwithNULLkey values: Null predicates now emit"col" IS NULLinstead of"col" = null.true/false(for examplet,1,yes) are bound as untyped text for PostgreSQL's boolean input to parse, instead of being written unquoted into the SQL.U+0000) characters are stripped for all column types.BYTESinto character columns: Bound as PostgreSQL hex text (\x...) for bothINSERTandDELETE.FLOAT64-0.0: Keeps its sign fordouble precisioncolumns.PreparedStatement, sopgjdbccan switch to server-side prepared statements afterprepareThresholdexecutions (default 5).Verification
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).SpannerToPostgreSQLDataTypesIT(INSERTpaths) and by follow-up [SpannerToSourceDb] Expand SpannerToPostgreSQLDataTypesIT CRUD and PK coverage #4665 (DELETE, non-bigint keys, enums,NULLdeletes), which is stacked on this branch.Related / Follow-up PRs
PreparedStatementabstractions).SpannerToPostgreSQLDataTypesITto test the new CRUD, PK, enum, andNULL-delete paths against real Cloud Spanner and PostgreSQL.