Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -38,14 +38,23 @@
* again and gets routed back into the DLQ.
*
* <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

* sources that bind custom transformation values (e.g. Oracle) to return a plain value instead of a
* SQL literal from {@code toSourceRow}.
Comment on lines +41 to +43

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

*/
public class CustomTransformationForDLQIT implements ISpannerMigrationTransformer {

private static final Logger LOG = LoggerFactory.getLogger(CustomTransformationForDLQIT.class);

private String mode = "bad";

/**
* When {@code true} (parameter {@code rawValues=true}), {@link #toSourceRow} returns plain values
* for sources that bind custom transformation values (e.g. Oracle). Otherwise it returns SQL
* literals, since the other sources write custom transformation values to the SQL as is.
*/
private boolean rawValues = false;

@Override
public void init(String parameters) {
LOG.info("init called with {}", parameters);
Expand All @@ -56,11 +65,13 @@ public void init(String parameters) {
if (kv.length == 2) {
if (kv[0].trim().equals("mode")) {
this.mode = kv[1].trim();
} else if (kv[0].trim().equals("rawValues")) {
this.rawValues = Boolean.parseBoolean(kv[1].trim());
}
}
}
}
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.

}

@Override
Expand Down Expand Up @@ -113,9 +124,9 @@ public MigrationTransformationResponse toSourceRow(MigrationTransformationReques
if (tableName.equalsIgnoreCase("Orders")) {
Object sourceObj = requestRow.get("OrderSource");
String source = (sourceObj != null) ? (String) sourceObj : "UNKNOWN_SYSTEM";
// 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.

// quotes since the DML generator injects custom responses directly as raw values.
String legacySys = rawValues ? source + "_v1" : "'" + source + "_v1'";
responseRow.put("LegacyOrderSystem", legacySys);
return new MigrationTransformationResponse(responseRow, false);
} else if (tableName.equalsIgnoreCase("AllDataTypes")) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@
import java.text.SimpleDateFormat;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Base64;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
Expand Down Expand Up @@ -111,6 +110,11 @@ public MigrationTransformationResponse toSpannerRow(MigrationTransformationReque
return new MigrationTransformationResponse(null, false);
}

/**
* Reverse replication binds custom transformation values as data, so plain values are returned
* (no SQL quotes or functions): strings as is, binary values as {@code byte[]}, and temporal
* values in the source (MySQL) format without any timezone conversion.
*/
@Override
public MigrationTransformationResponse toSourceRow(MigrationTransformationRequest request)
throws InvalidTransformationException {
Expand Down Expand Up @@ -139,65 +143,47 @@ public MigrationTransformationResponse toSourceRow(MigrationTransformationReques
BigDecimal doubleColumn = (BigDecimal) requestRow.get("double_column");
responseRow.put("source_only_pk", sourceOnlyPk.toString());
responseRow.put("tinyint_column", tinyIntColumn.toString());
responseRow.put("text_column", "\'" + requestRow.get("text_column") + " append\'");
responseRow.put("text_column", requestRow.get("text_column") + " append");
responseRow.put("int_column", intColumn.toString());
responseRow.put("bigint_column", bigIntColumn.toString());
responseRow.put("float_column", floatColumn.add(BigDecimal.ONE).toString());
responseRow.put("double_column", doubleColumn.add(BigDecimal.ONE).toString());
Double value = Double.parseDouble((String) requestRow.get("decimal_column"));
responseRow.put("decimal_column", String.valueOf(value - 1));
responseRow.put("bool_column", "false");
responseRow.put("enum_column", "\'3\'");
responseRow.put(
"blob_column",
"from_base64(\'"
+ Base64.getEncoder()
.encodeToString("blob_column_appended".getBytes(StandardCharsets.UTF_8))
+ "\')");
responseRow.put(
"binary_column",
"binary(from_base64(\'"
+ Base64.getEncoder()
.encodeToString("binary_column_appended".getBytes(StandardCharsets.UTF_8))
+ "\'))");
responseRow.put(
"bit_column",
"binary(from_base64(\'"
+ Base64.getEncoder().encodeToString("5".getBytes(StandardCharsets.UTF_8))
+ "\'))");
responseRow.put("year_column", "\'" + yearColumn + "\'");
responseRow.put("enum_column", "3");
// Binary values are returned as byte arrays.
responseRow.put("blob_column", "blob_column_appended".getBytes(StandardCharsets.UTF_8));
responseRow.put("binary_column", "binary_column_appended".getBytes(StandardCharsets.UTF_8));
responseRow.put("bit_column", "5".getBytes(StandardCharsets.UTF_8));
responseRow.put("year_column", yearColumn.toString());
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat dateTimeFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");
dateTimeFormat.setTimeZone(TimeZone.getTimeZone("UTC")); // Ensure it handles UTC correctly
// The source database timezone of the test is UTC.
SimpleDateFormat sourceDateTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sourceDateTimeFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = dateFormat.parse((String) requestRow.get("date_column"));
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DAY_OF_MONTH, 1);
responseRow.put("date_column", "\'" + dateFormat.format(calendar.getTime()) + "\'");
responseRow.put("date_column", dateFormat.format(calendar.getTime()));
Date dateTime = dateTimeFormat.parse((String) requestRow.get("datetime_column"));
calendar.setTime(dateTime);
calendar.add(Calendar.SECOND, -1);
String dateTimeColumn = dateTimeFormat.format(calendar.getTime());
responseRow.put(
"datetime_column",
"CONVERT_TZ(\'"
+ dateTimeColumn.substring(0, dateTimeColumn.length() - 1)
+ "\','+00:00','+00:00')");
// Temporal values are bound as returned (no timezone conversion), so they are returned in
// the source format.
responseRow.put("datetime_column", sourceDateTimeFormat.format(calendar.getTime()));
dateTime = dateTimeFormat.parse((String) requestRow.get("timestamp_column"));
calendar.setTime(dateTime);
calendar.add(Calendar.SECOND, -1);
String timestampColumn = dateTimeFormat.format(calendar.getTime());
responseRow.put(
"timestamp_column",
"CONVERT_TZ(\'"
+ timestampColumn.substring(0, timestampColumn.length() - 1)
+ "\','+00:00','+00:00')");
responseRow.put("timestamp_column", sourceDateTimeFormat.format(calendar.getTime()));
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");
LocalTime time = LocalTime.parse((String) requestRow.get("time_column"), formatter);

LocalTime newTime = time.plusMinutes(10);
responseRow.put("time_column", "\'" + newTime.format(formatter) + "\'");
responseRow.put("time_column", newTime.format(formatter));

} catch (Exception e) {
throw new InvalidTransformationException(e);
Expand All @@ -215,9 +201,9 @@ public MigrationTransformationResponse toSourceRow(MigrationTransformationReques
String lastName2 = requestRow.get("last_name2").toString();
String firstName3 = requestRow.get("first_name3").toString();
String lastName3 = requestRow.get("last_name3").toString();
responseRow.put("full_name1", "\'" + firstName1 + " " + lastName1 + "\'");
responseRow.put("full_name2", "\'" + firstName2 + " " + lastName2 + "\'");
responseRow.put("full_name3", "\'" + firstName3 + " " + lastName3 + "\'");
responseRow.put("full_name1", firstName1 + " " + lastName1);
responseRow.put("full_name2", firstName2 + " " + lastName2);
responseRow.put("full_name3", firstName3 + " " + lastName3);
MigrationTransformationResponse response =
new MigrationTransformationResponse(responseRow, false);
return response;
Expand All @@ -226,8 +212,8 @@ public MigrationTransformationResponse toSourceRow(MigrationTransformationReques
Map<String, Object> requestRow = request.getRequestRow();
String name = requestRow.get("name").toString();
String[] nameArray = name.split(" ");
responseRow.put("first_name", "\'" + nameArray[0] + "\'");
responseRow.put("last_name", "\'" + nameArray[1] + "\'");
responseRow.put("first_name", nameArray[0]);
responseRow.put("last_name", nameArray[1]);
MigrationTransformationResponse response =
new MigrationTransformationResponse(responseRow, false);
return response;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,30 @@ public void testToSourceRow_AllDataTypes_SemiFixedMode_NonCrashingId() throws Ex
assertNotNull(response);
}

@Test
public void testToSourceRow_Orders_ReturnsSqlLiteralByDefault() throws Exception {
transformer.init("mode=bad");
Map<String, Object> requestRow = new HashMap<>();
requestRow.put("OrderSource", "WEB");
MigrationTransformationRequest request =
new MigrationTransformationRequest("Orders", requestRow, "shard1", "INSERT");

MigrationTransformationResponse response = transformer.toSourceRow(request);
assertEquals("'WEB_v1'", response.getResponseRow().get("LegacyOrderSystem"));
}

@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 ?

Map<String, Object> requestRow = new HashMap<>();
requestRow.put("OrderSource", "WEB");
MigrationTransformationRequest request =
new MigrationTransformationRequest("Orders", requestRow, "shard1", "INSERT");

MigrationTransformationResponse response = transformer.toSourceRow(request);
assertEquals("WEB_v1", response.getResponseRow().get("LegacyOrderSystem"));
}

@Test
public void testTransformFailedSpannerMutation() throws Exception {
MigrationTransformationResponse response = transformer.transformFailedSpannerMutation(null);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,12 +58,7 @@ public void write(
statement = pstmt;
int paramIdx = 1;
for (Object param : params) {
if (param instanceof byte[]) {
byte[] bytes = (byte[]) param;
pstmt.setBlob(paramIdx++, new java.io.ByteArrayInputStream(bytes), bytes.length);
} else {
pstmt.setObject(paramIdx++, param);
}
bindParameter(pstmt, paramIdx++, param);
}
pstmt.executeUpdate();
} else {
Expand All @@ -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.

}
}

/** Binds a prepared statement parameter. Sources can override this for type specific binding. */
protected void bindParameter(java.sql.PreparedStatement pstmt, int paramIdx, Object param)
throws java.sql.SQLException {
if (param instanceof byte[]) {
byte[] bytes = (byte[]) param;
pstmt.setBlob(paramIdx, new java.io.ByteArrayInputStream(bytes), bytes.length);
} else {
pstmt.setObject(paramIdx, param);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
/*
* Copyright (C) 2026 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.cloud.teleport.v2.templates.source.mysql;

import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import java.util.List;
import java.util.Objects;

/**
* The SQL fragment used for a single column value in a parameterized DML statement, together with
* the values to be bound to the {@code ?} placeholders in that fragment (in order).
*
* <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 ?


public static final String PLACEHOLDER = "?";

private final String placeholderSql;
private final ImmutableList<PreparedStatementValue> params;

private ColumnBinding(String placeholderSql, List<PreparedStatementValue> params) {
Preconditions.checkNotNull(placeholderSql, "placeholderSql must not be null");
Preconditions.checkNotNull(params, "params must not be null");
long placeholderCount = placeholderSql.chars().filter(c -> c == '?').count();
Preconditions.checkArgument(
placeholderCount == params.size(),
"Placeholder count %s does not match parameter count %s for SQL fragment: %s",
placeholderCount,
params.size(),
placeholderSql);
this.placeholderSql = placeholderSql;
this.params = ImmutableList.copyOf(params);
}

/** A binding with a single {@code ?} placeholder. */
public static ColumnBinding of(PreparedStatementValue value) {
return new ColumnBinding(PLACEHOLDER, ImmutableList.of(value));
}

/** A binding with a template-generated SQL fragment containing one {@code ?} per parameter. */
public static ColumnBinding of(String placeholderSql, List<PreparedStatementValue> params) {
return new ColumnBinding(placeholderSql, params);
}

public String getPlaceholderSql() {
return placeholderSql;
}

public ImmutableList<PreparedStatementValue> getParams() {
return params;
}

@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof ColumnBinding)) {
return false;
}
ColumnBinding that = (ColumnBinding) o;
return placeholderSql.equals(that.placeholderSql) && params.equals(that.params);
}

@Override
public int hashCode() {
return Objects.hash(placeholderSql, params);
}

@Override
public String toString() {
return "ColumnBinding{placeholderSql=" + placeholderSql + ", params=" + params + "}";
}
}
Loading
Loading