Skip to content

[SourceDbToSpanner] Use prepared statements for Spanner to MySQL - #4644

Open
darshan-sj wants to merge 3 commits into
GoogleCloudPlatform:mainfrom
darshan-sj:reverse-vuln
Open

darshan-sj wants to merge 3 commits into
GoogleCloudPlatform:mainfrom
darshan-sj:reverse-vuln

Conversation

@darshan-sj

Copy link
Copy Markdown
Contributor

No description provided.

@darshan-sj
darshan-sj requested a review from a team as a code owner November 27, 2026 07:24
@darshan-sj darshan-sj added the improvement Making existing code better label Nov 27, 2026
@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 refactors the Spanner-to-MySQL migration logic to utilize JDBC prepared statements instead of manual string concatenation for DML generation. This change mitigates SQL injection risks by separating SQL structure from record data. The update includes new model classes to manage typed parameters and updates to the DML generation utilities to ensure all column values, including custom transformations and timezone offsets, are correctly bound as parameters.

Highlights

  • Prepared Statements Implementation: Transitioned from string-concatenated DML statements to JDBC PreparedStatement for Spanner-to-MySQL migration, significantly improving security against SQL injection.
  • New Data Models: Introduced 'ColumnBinding' and 'PreparedStatementValue' classes to encapsulate SQL fragments and their corresponding typed parameters, ensuring consistent data binding.
  • Refactored DML Generation: Updated 'MySQLDMLGenerator' and 'DMLGeneratorUtils' to support parameterized queries, including handling of custom transformations and timezone conversions as bound 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 MySQL DML generation logic to use parameterized queries via PreparedStatement instead of string interpolation, significantly improving security against SQL injection. It introduces PreparedStatementValue and ColumnBinding models to manage typed parameters and updates JdbcDao and DMLGeneratorUtils to support parameter binding. The review feedback highlights two potential issues in MySQLDMLGenerator: a possible NumberFormatException when parsing special float values like NaN or Infinity as BigDecimal, and a potential StringIndexOutOfBoundsException or truncation issue when unconditionally trimming the trailing 'Z' from timestamp strings.

@codecov

codecov Bot commented Nov 27, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 40.98%. Comparing base (5145ec2) to head (582a1d1).
⚠️ Report is 6 commits behind head on main.

❗ There is a different number of reports uploaded between BASE (5145ec2) and HEAD (582a1d1). Click for more details.

HEAD has 6 uploads less than BASE
Flag BASE (5145ec2) HEAD (582a1d1)
7 1
Additional details and impacted files
@@              Coverage Diff              @@
##               main    #4644       +/-   ##
=============================================
- Coverage     59.71%   40.98%   -18.74%     
+ Complexity     8384      741     -7643     
=============================================
  Files          1123      210      -913     
  Lines         72736    15419    -57317     
  Branches       8852     1645     -7207     
=============================================
- Hits          43435     6319    -37116     
+ Misses        26402     8577    -17825     
+ Partials       2899      523     -2376     
Components Coverage Δ
spanner-templates ∅ <ø> (∅)
spanner-import-export ∅ <ø> (∅)
spanner-live-forward-migration ∅ <ø> (∅)
spanner-live-reverse-replication ∅ <ø> (∅)
spanner-bulk-migration ∅ <ø> (∅)
gcs-spanner-dv ∅ <ø> (∅)
see 938 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.
@darshan-sj

Copy link
Copy Markdown
Contributor Author

/gemini review

@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 transitions the MySQL DML generation from inline SQL literals to parameterized prepared statements, introducing PreparedStatementValue and ColumnBinding to safely bind column values and custom transformation results. The review feedback highlights critical safety improvements: handling potential NullPointerExceptions in DMLGeneratorUtils when custom transformations return null values, and safely checking for a trailing 'Z' before trimming timestamps in MySQLDMLGenerator to prevent StringIndexOutOfBoundsException or data corruption.

@darshan-sj darshan-sj changed the title [DO NOT MERGE] [SourceDbToSpanner] Use prepared statements for Spanner to MySQL Nov 29, 2026
@darshan-sj

Copy link
Copy Markdown
Contributor Author

/gemini review

@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 MySQL DML generation process to use parameterized queries instead of SQL literals, enhancing security against SQL injection. It introduces a new ColumnBinding and PreparedStatementValue structure to handle typed parameters, updates MySQLDMLGenerator to build parameterized SQL, and adds a MySQLJdbcDao to manage the binding of these parameters. Additionally, it includes comprehensive updates to existing tests to reflect the new parameterized approach and adds new unit tests for the binding logic.

@bharadwaj-aditya bharadwaj-aditya 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.

Most comments are about standardizing across jdbc flows

*
* <p>For the Orders table, it translates the OrderSource column into a custom LegacyOrderSystem
* column to validate standard data transformation operations.
* column to validate standard data transformation operations. Use {@code rawValues=true} for

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.

we should remove the rawValues flag here. The contract should be that whatever custom transform returns we pass it into the query. With the prepared queries this should not be a security issue

}
}
LOG.info("Mode set to {}", this.mode);
LOG.info("Mode set to {}, rawValues set to {}", this.mode, this.rawValues);

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.

we should not be logging all the data.

// Enclose in single quotes since DML generator injects custom responses directly as raw
// values
String legacySys = "'" + source + "_v1'";
// With rawValues the value is bound as is (e.g. Oracle). Otherwise enclose it in single

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.

this complexity need not be exposed in the IT. In the IT we should just write to spanner and check in source as is.


@Test
public void testToSourceRow_Orders_RawValues() throws Exception {
transformer.init("mode=bad,rawValues=true");

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.

why do we need this mode ?

* <p>The SQL fragment is always generated by the template (for example {@code ?} or {@code
* CONVERT_TZ(?, '+00:00', ?)}) and never contains user or record data.
*/
public final class ColumnBinding {

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.

does this need to be mysql specific ?

Why is not at the JDBC level ?

* values are handled the same way. Instead of SQL literals, it returns {@link ColumnBinding}s whose
* values are bound as {@link java.sql.PreparedStatement} parameters, in source column order.
*/
final class MySQLColumnBindings {

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.

this should be common across all jdbc sources

List<PreparedStatementValue> valueParams = new ArrayList<>();

for (Map.Entry<String, ColumnBinding> entry : allColumnBindings.entrySet()) {
String quotedColumn = quoteIdentifier(entry.getKey());

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.

this query will not change based on values. It might make sense to just create this once and cache it per table

* Value of a non-BYTES Spanner value for a column that previously received an unquoted literal
* (numeric, {@code bit}, {@code bool} and unknown types).
*/
private static PreparedStatementValue getNumericLiteralTypeValue(

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.

this logic can be common across jdbc

Comment on lines +60 to +63
Map<String, HikariDataSource> connectionPoolMap = new HashMap<>();
connectionPoolMap.put("url/user", mockHikariDataSource);
jdbcConnectionHelper = new JdbcConnectionHelper();
jdbcConnectionHelper.setConnectionPoolMap(connectionPoolMap);

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.

JdbcConnectionHelper.connectionPoolMap is a JVM-wide static volatile map, and this test populates "url/user" without clearing it in @After. When MySQLJdbcDaoTest runs before JdbcDaoTest in the same JVM, JdbcDaoTest.testNullConnection() picks up this stale mockHikariDataSource (whose mockConnection doesn't stub createStatement()) and fails with NullPointerException instead of ConnectionException—which is causing the current Spanner PR / Unit Tests CI failure.

Mock IConnectionHelper<Connection> directly instead of mutating the static JdbcConnectionHelper pool:

@Mock private IConnectionHelper<Connection> mockConnectionHelper;
// in setUp():
when(mockConnectionHelper.getConnection("url/user")).thenReturn(mockConnection);
@@ -86,4 +81,15 @@ public void write(
}

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.

Pre-existing, but more exposed now that all MySQL writes go through PreparedStatement: in the finally block (lines 74–82), statement.close() runs before connObj.close() without a nested try/finally or try-with-resources. If statement.close() throws (for example on a broken socket during server-side COM_STMT_CLOSE, or during cleanup after a concurrent TransactionalCheckException with autoCommit=false), connObj.close() is skipped—leaking a pooled HikariCP connection (potentially with an open uncommitted transaction holding MySQL row locks) and starving concurrent worker threads.

Consider using try-with-resources for connObj and statement (or closing connObj in a separate finally) so the connection is always returned to the pool.

Comment on lines +427 to +432
if (SCIENTIFIC_LITERAL.matcher(trimmed).matches()) {
double d = Double.parseDouble(trimmed);
if (Double.isFinite(d)) {
return PreparedStatementValue.ofDouble(d);
}
}

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.

Parsing scientific-notation strings via Double.parseDouble can silently lose precision or underflow when targeting MySQL DECIMAL columns (e.g., from a custom transformation or STRING column):

  • Values with >17 significant digits (e.g. "1.234567890123456789E+10") are silently rounded to 53-bit IEEE-754 double precision.
  • Very small non-zero exponents (e.g. "1E-500") silently underflow to 0.0, which still passes Double.isFinite(d).
Comment on lines +41 to +43
* column to validate standard data transformation operations. Use {@code rawValues=true} for
* sources that bind custom transformation values (e.g. Oracle) to return a plain value instead of a
* SQL literal from {@code toSourceRow}.

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.

The Javadoc/comments here (and on lines 53 and 127) are stale/inaccurate: they reference (e.g. Oracle) for rawValues=true, whereas only the MySQL ITs pass rawValues=true (SpannerToSourceDBOracleRetryAllDLQIT still passes mode=bad without rawValues=true). Consider updating these references to (e.g. MySQL).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

improvement Making existing code better size/XXL

2 participants