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

Filter by extension

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,26 +38,14 @@
* 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. 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}.
* column to validate standard data transformation operations.
*/
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 @@ -68,13 +56,11 @@ 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 {}, rawValues set to {}", this.mode, this.rawValues);
LOG.info("Mode set to {}", this.mode);
}

@Override
Expand Down Expand Up @@ -127,11 +113,8 @@ public MigrationTransformationResponse toSourceRow(MigrationTransformationReques
if (tableName.equalsIgnoreCase("Orders")) {
Object sourceObj = requestRow.get("OrderSource");
String source = (sourceObj != null) ? (String) sourceObj : "UNKNOWN_SYSTEM";
// 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'";
// Returned as a plain value: custom transformation values are written to the source as is.
String legacySys = 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,48 @@ 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 + "\'");
// Values are bound as returned, so a boolean is returned for the TINYINT(1) column.
responseRow.put("bool_column", Boolean.FALSE);
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 +202,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 +213,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,27 +134,8 @@ 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");
public void testToSourceRow_Orders_ReturnsPlainValue() throws Exception {
Map<String, Object> requestRow = new HashMap<>();
requestRow.put("OrderSource", "WEB");
MigrationTransformationRequest request =
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
/*
* 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.custom;

import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;

import com.google.cloud.teleport.v2.spanner.exceptions.InvalidTransformationException;
import com.google.cloud.teleport.v2.spanner.utils.MigrationTransformationRequest;
import com.google.cloud.teleport.v2.spanner.utils.MigrationTransformationResponse;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;

/** Tests for {@link CustomTransformationWithShardForLiveIT#toSourceRow}. */
public class CustomTransformationWithShardForLiveITTest {

private final CustomTransformationWithShardForLiveIT transformer =
new CustomTransformationWithShardForLiveIT();

private static Map<String, Object> allDatatypeRow() {
Map<String, Object> row = new HashMap<>();
row.put("varchar_column", "example2");
row.put("tinyint_column", "12");
row.put("text_column", "text");
row.put("int_column", "112");
row.put("bigint_column", "1000");
row.put("float_column", new BigDecimal("1.5"));
row.put("double_column", new BigDecimal("2.5"));
row.put("decimal_column", "10.5");
row.put("year_column", "2024");
row.put("date_column", "2024-01-31");
row.put("datetime_column", "2024-01-01T10:00:00Z");
row.put("timestamp_column", "2024-01-01T10:00:00Z");
row.put("time_column", "10:00:00");
return row;
}

private static MigrationTransformationRequest request(
String table, Map<String, Object> row, String eventType) {
return new MigrationTransformationRequest(table, row, "shard1", eventType);
}

@Test
public void testToSourceRow_AllDatatypeTransformation_InsertReturnsPlainValues()
throws Exception {
MigrationTransformationResponse response =
transformer.toSourceRow(request("AllDatatypeTransformation", allDatatypeRow(), "INSERT"));

assertFalse(response.isEventFiltered());
Map<String, Object> out = response.getResponseRow();
assertEquals("100", out.get("source_only_pk"));
assertEquals("13", out.get("tinyint_column"));
assertEquals("text append", out.get("text_column"));
assertEquals("113", out.get("int_column"));
assertEquals("1001", out.get("bigint_column"));
assertEquals("2.5", out.get("float_column"));
assertEquals("3.5", out.get("double_column"));
assertEquals("9.5", out.get("decimal_column"));
assertEquals(Boolean.FALSE, out.get("bool_column"));
assertEquals("3", out.get("enum_column"));
assertArrayEquals(
"blob_column_appended".getBytes(StandardCharsets.UTF_8), (byte[]) out.get("blob_column"));
assertArrayEquals(
"binary_column_appended".getBytes(StandardCharsets.UTF_8),
(byte[]) out.get("binary_column"));
assertArrayEquals("5".getBytes(StandardCharsets.UTF_8), (byte[]) out.get("bit_column"));
assertEquals("2025", out.get("year_column"));
assertEquals("2024-02-01", out.get("date_column"));
// Temporal values are returned in the source format, without timezone conversion.
assertEquals("2024-01-01 09:59:59", out.get("datetime_column"));
assertEquals("2024-01-01 09:59:59", out.get("timestamp_column"));
assertEquals("10:10:00", out.get("time_column"));
}

@Test
public void testToSourceRow_AllDatatypeTransformation_InvalidDate() {
Map<String, Object> row = allDatatypeRow();
row.put("date_column", "not-a-date");

assertThrows(
InvalidTransformationException.class,
() -> transformer.toSourceRow(request("AllDatatypeTransformation", row, "INSERT")));
}

@Test
public void testToSourceRow_AllDatatypeTransformation_FilteredUpdatedAndDeletedEvents()
throws Exception {
Map<String, Object> filteredRow = allDatatypeRow();
filteredRow.put("varchar_column", "example1");
assertTrue(
transformer
.toSourceRow(request("AllDatatypeTransformation", filteredRow, "INSERT"))
.isEventFiltered());

MigrationTransformationResponse update =
transformer.toSourceRow(request("AllDatatypeTransformation", allDatatypeRow(), "UPDATE"));
assertFalse(update.isEventFiltered());
assertNull(update.getResponseRow());

assertTrue(
transformer
.toSourceRow(request("AllDatatypeTransformation", allDatatypeRow(), "DELETE"))
.isEventFiltered());
}

@Test
public void testToSourceRow_OtherTables() throws Exception {
Map<String, Object> person = new HashMap<>();
person.put("first_name1", "a");
person.put("last_name1", "b");
person.put("first_name2", "c");
person.put("last_name2", "d");
person.put("first_name3", "e");
person.put("last_name3", "f");
Map<String, Object> personOut =
transformer.toSourceRow(request("Person", person, "INSERT")).getResponseRow();
assertEquals("a b", personOut.get("full_name1"));
assertEquals("e f", personOut.get("full_name3"));

Map<String, Object> user = new HashMap<>();
user.put("name", "first last");
Map<String, Object> userOut =
transformer.toSourceRow(request("Users1", user, "INSERT")).getResponseRow();
assertEquals("first", userOut.get("first_name"));
assertEquals("last", userOut.get("last_name"));

assertNull(
transformer.toSourceRow(request("Unknown", new HashMap<>(), "INSERT")).getResponseRow());
}
}
Loading
Loading