Skip to content
Original file line number Diff line number Diff line change
Expand Up @@ -38,14 +38,26 @@
* 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
* sources that bind custom transformation values (e.g. Oracle) to return a plain value instead of a
* SQL literal from {@code toSourceRow}.
*/
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.
*
* <p>TODO: Remove rawValues (and always return plain values) once all sources bind custom
* transformation values with prepared statements.
*/
private boolean rawValues = false;

@Override
public void init(String parameters) {
LOG.info("init called with {}", parameters);
Expand All @@ -56,11 +68,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);
}

@Override
Expand Down Expand Up @@ -113,9 +127,11 @@ 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
// quotes since the DML generator injects custom responses directly as raw values.
// TODO: Remove rawValues once all sources bind custom transformation values with prepared
// statements.
String legacySys = rawValues ? source + "_v1" : "'" + source + "_v1'";

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.

i'm not sure why this variation in flow is required. Do we need the rawValues flag here ?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

CustomTransformation is shared across different source's IT (Mysql/PG/Oracle). In Oracle we are using prepared statement which will bind the value as it is from CustomTransformation, while other source's are using inline values, so they need sql literals for it.

Hence we have added this flag for passing rawValues for oracle and sql literals for other. Once other sources are also starts using prepared statement, we can remove this rawValues flag.

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 @@ -21,6 +21,7 @@
import com.google.cloud.teleport.v2.spanner.utils.MigrationTransformationResponse;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
Expand Down Expand Up @@ -48,18 +49,12 @@ public MigrationTransformationResponse toSpannerRow(MigrationTransformationReque
return new CustomTransformationWithShardForLiveIT().toSpannerRow(request);
}

private String bytesToHex(byte[] bytes) {
StringBuilder hexString = new StringBuilder();
for (byte b : bytes) {
String hex = Integer.toHexString(0xFF & b);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString().toUpperCase();
}

/**
* Oracle binds custom transformation values exactly as returned (no conversion), so {@code
* toSourceRow} returns objects that Oracle accepts for the column (e.g. {@code Long}, {@code
* BigDecimal}, {@code byte[]}, {@code java.sql.Date}, {@code java.sql.Timestamp}) instead of SQL
* literals or expressions.
*/
@Override
public MigrationTransformationResponse toSourceRow(MigrationTransformationRequest request)
throws InvalidTransformationException {
Expand All @@ -86,35 +81,24 @@ public MigrationTransformationResponse toSourceRow(MigrationTransformationReques
Long yearColumn = Long.parseLong((String) requestRow.get("year_column")) + 1;
BigDecimal floatColumn = (BigDecimal) requestRow.get("float_column");
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("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());
responseRow.put("source_only_pk", sourceOnlyPk);
responseRow.put("tinyint_column", tinyIntColumn);
responseRow.put("text_column", requestRow.get("text_column") + " append");
responseRow.put("int_column", intColumn);
responseRow.put("bigint_column", bigIntColumn);
responseRow.put("float_column", floatColumn.add(BigDecimal.ONE));
responseRow.put("double_column", doubleColumn.add(BigDecimal.ONE));
Double value = Double.parseDouble((String) requestRow.get("decimal_column"));
responseRow.put("decimal_column", String.valueOf(value - 1));
responseRow.put("bool_column", "0"); // Oracle uses 1/0 usually, mapped from false
responseRow.put("enum_column", "\'3\'");

// Oracle HEXTORAW formatting
responseRow.put(
"blob_column",
"HEXTORAW('"
+ bytesToHex("blob_column_appended".getBytes(StandardCharsets.UTF_8))
+ "')");

responseRow.put(
"binary_column",
"HEXTORAW('"
+ bytesToHex("binary_column_appended".getBytes(StandardCharsets.UTF_8))
+ "')");
responseRow.put("decimal_column", BigDecimal.valueOf(value - 1));
responseRow.put("bool_column", 0); // Oracle uses 1/0 usually, mapped from false
responseRow.put("enum_column", "3");

responseRow.put(
"bit_column", "HEXTORAW('" + bytesToHex("5".getBytes(StandardCharsets.UTF_8)) + "')");
// 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 + "\'");
responseRow.put("year_column", yearColumn);
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat dateTimeFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");
Expand All @@ -123,36 +107,24 @@ public MigrationTransformationResponse toSourceRow(MigrationTransformationReques
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DAY_OF_MONTH, 1);
responseRow.put(
"date_column",
"TO_DATE('" + dateFormat.format(calendar.getTime()) + "', 'YYYY-MM-DD')");
responseRow.put("date_column", new java.sql.Date(calendar.getTimeInMillis()));

// Date / time values are returned as java.sql types, which are written as is.
Date dateTime = dateTimeFormat.parse((String) requestRow.get("datetime_column"));
calendar.setTime(dateTime);
calendar.add(Calendar.SECOND, -1);
String dateTimeColumn = dateTimeFormat.format(calendar.getTime());
// Oracle TO_TIMESTAMP
responseRow.put(
"datetime_column",
"CAST(FROM_TZ(CAST(TO_TIMESTAMP('"
+ dateTimeColumn.substring(0, dateTimeColumn.length() - 1)
+ "', 'YYYY-MM-DD\"T\"HH24:MI:SS') AS TIMESTAMP), 'UTC') AT TIME ZONE '+00:00' AS TIMESTAMP)");
responseRow.put("datetime_column", new Timestamp(calendar.getTimeInMillis()));

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",
"CAST(FROM_TZ(CAST(TO_TIMESTAMP('"
+ timestampColumn.substring(0, timestampColumn.length() - 1)
+ "', 'YYYY-MM-DD\"T\"HH24:MI:SS') AS TIMESTAMP), 'UTC') AT TIME ZONE '+00:00' AS TIMESTAMP)");
responseRow.put("timestamp_column", new Timestamp(calendar.getTimeInMillis()));

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 @@ -170,9 +142,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 @@ -181,8 +153,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,36 @@ public void testToSourceRow_AllDataTypes_SemiFixedMode_NonCrashingId() throws Ex
assertNotNull(response);
}

// TODO: Remove the rawValues tests once all sources bind custom transformation values with
// prepared statements.
@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"));

transformer.init("mode=bad,rawValues=false");
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");
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(
}
}
}

/** Binds a prepared statement parameter. Sources can override this for type specific binding. */
protected void bindParameter(java.sql.PreparedStatement pstmt, int paramIdx, Object param)

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.

is there any value in the refactor on this method ?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

As discussed in [https://github.com//pull/4628#discussion_r4717510296], we might need specific bind handling to few types, respactive JDBCDAO per source will need this method for doing it.

Like for oracle this method will be overriden for bounding different types in this loop: setFixedCHAR for CHAR/NCHAR, setNString/setNClob for national types, streamed setClob for large CLOBs, and typed setNull.

This might require for other source as well if when we do prepared statement, hence I abstracted out this method.

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