Repository navigation
[SourceDbToSpanner] Use prepared statements for Spanner to MySQL - #4644
darshan-sj wants to merge 3 commits into
Conversation
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 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
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 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.
19c9715 to
f6603f8
Compare
Codecov Report✅ All modified and coverable lines are covered by tests.
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
🚀 New features to boost your workflow:
|
|
/gemini review |
There was a problem hiding this comment.
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.
|
/gemini review |
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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); |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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"); |
There was a problem hiding this comment.
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 { |
There was a problem hiding this comment.
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 { |
There was a problem hiding this comment.
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()); |
There was a problem hiding this comment.
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( |
There was a problem hiding this comment.
this logic can be common across jdbc
| Map<String, HikariDataSource> connectionPoolMap = new HashMap<>(); | ||
| connectionPoolMap.put("url/user", mockHikariDataSource); | ||
| jdbcConnectionHelper = new JdbcConnectionHelper(); | ||
| jdbcConnectionHelper.setConnectionPoolMap(connectionPoolMap); |
There was a problem hiding this comment.
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( | |||
| } | |||
There was a problem hiding this comment.
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.
| if (SCIENTIFIC_LITERAL.matcher(trimmed).matches()) { | ||
| double d = Double.parseDouble(trimmed); | ||
| if (Double.isFinite(d)) { | ||
| return PreparedStatementValue.ofDouble(d); | ||
| } | ||
| } |
There was a problem hiding this comment.
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-754doubleprecision. - Very small non-zero exponents (e.g.
"1E-500") silently underflow to0.0, which still passesDouble.isFinite(d).
| * 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}. |
There was a problem hiding this comment.
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).
No description provided.