Skip to content
Draft
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 @@ -16,6 +16,7 @@
package com.google.cloud.teleport.v2.reader.io.jdbc.uniformsplitter;

import com.google.cloud.teleport.v2.reader.io.jdbc.uniformsplitter.range.BoundaryExtractorFactory;
import com.google.cloud.teleport.v2.reader.io.jdbc.uniformsplitter.range.PartitionColumn;
import com.google.cloud.teleport.v2.reader.io.jdbc.uniformsplitter.stringmapper.CollationOrderRow;
import com.google.common.collect.ImmutableList;
import java.io.Serializable;
Expand All @@ -25,6 +26,7 @@
import java.time.LocalTime;
import java.time.OffsetTime;
import java.util.List;
import javax.annotation.Nullable;

/** Helper Interface to help uniform splitter adapt to the source database. */
public interface UniformSplitterDBAdapter extends Serializable {
Expand Down Expand Up @@ -111,4 +113,39 @@ default LocalTime extractBoundaryLocalTime(ResultSet rs, int index) throws SQLEx
default OffsetTime extractBoundaryOffsetTime(ResultSet rs, int index) throws SQLException {
return BoundaryExtractorFactory.parseTimeStringToOffsetTime(rs.getString(index));
}

/**
* Reads a binary boundary (the MIN or MAX of a {@code byte[]} partition column) from a boundary
* query result. The returned bytes must sort, as unsigned big-endian bytes, the same way the
* database sorts the column, since split points are computed on them in Java.
*
* <p>Override for types whose driver representation or sort order differs from raw bytes (for
* example Postgres {@code uuid} or SQL Server {@code uniqueidentifier}).
*
* @param rs result set positioned on the boundary row.
* @param index column index of the boundary.
* @param partitionColumn the partition column.
* @return boundary bytes, or null.
*/
default byte[] extractBinaryBoundary(ResultSet rs, int index, PartitionColumn partitionColumn)
throws SQLException {
return rs.getBytes(index);
}

/**
* Converts a boundary value to the object bound to a prepared statement parameter. The default
* binds the value unchanged.
*
* <p>Override for values the JDBC driver doesn't accept as is (for example bytes of a Postgres
* {@code uuid}, which must be bound as a {@link java.util.UUID}). Must be the inverse of {@link
* #extractBinaryBoundary} for binary columns.
*
* @param value boundary value (start or end of a range), or null.
* @param partitionColumn the partition column.
* @return the object to bind.
*/
@Nullable
default Object toQueryParameter(@Nullable Object value, PartitionColumn partitionColumn) {
return value;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,7 @@
*/
package com.google.cloud.teleport.v2.reader.io.jdbc.uniformsplitter.columnboundary;

import com.google.cloud.teleport.v2.reader.io.jdbc.JdbcCommonConstants;
import com.google.cloud.teleport.v2.reader.io.jdbc.uniformsplitter.range.BoundaryExtractorFactory;
import com.google.cloud.teleport.v2.reader.io.jdbc.uniformsplitter.UniformSplitterDBAdapter;
import com.google.cloud.teleport.v2.reader.io.jdbc.uniformsplitter.range.PartitionColumn;
import com.google.cloud.teleport.v2.reader.io.jdbc.uniformsplitter.range.Range;
import com.google.cloud.teleport.v2.reader.io.jdbc.uniformsplitter.range.TableIdentifier;
Expand All @@ -39,44 +38,25 @@ public class ColumnForBoundaryQueryPreparedStatementSetter
implements PreparedStatementSetter<ColumnForBoundaryQuery> {

private final ImmutableMap<TableIdentifier, TableSplitSpecification> tableSplitSpecificationMap;
private final UniformSplitterDBAdapter dbAdapter;

/**
* Construct {@link ColumnForBoundaryQueryPreparedStatementSetter}.
*
* @param tableSplitSpecifications list of table split specifications.
* @param dbAdapter dialect adapter that converts boundary values before they are bound.
*/
public ColumnForBoundaryQueryPreparedStatementSetter(
ImmutableList<TableSplitSpecification> tableSplitSpecifications) {
ImmutableList<TableSplitSpecification> tableSplitSpecifications,
UniformSplitterDBAdapter dbAdapter) {
this.dbAdapter = dbAdapter;
this.tableSplitSpecificationMap =
tableSplitSpecifications.stream()
.collect(
ImmutableMap.toImmutableMap(
TableSplitSpecification::tableIdentifier, Function.identity()));
}

/**
* Convert raw byte[] boundaries of UUID-like columns into the representation expected by the JDBC
* driver: {@link java.util.UUID} for PostgreSQL {@code uuid} (avoids a BYTEA vs UUID type
* mismatch), and a canonical UUID string for SQL Server {@code uniqueidentifier} (whose bytes are
* held in SQL Server comparison order, see {@link
* BoundaryExtractorFactory#sqlServerSortableBytesToUuidString}).
*
* <p>TODO(#4489): The uniqueidentifier branches are dialect-specific; route them through a
* SQLServer connector.
*/
private static Object convertIfUuid(Object val, PartitionColumn pc) {
if (val instanceof byte[] bytes
&& JdbcCommonConstants.UUID_TYPE.equalsIgnoreCase(pc.columnTypeName())) {
java.nio.ByteBuffer bb = java.nio.ByteBuffer.wrap(bytes);
return new java.util.UUID(bb.getLong(), bb.getLong());
}
if (val instanceof byte[] bytes
&& JdbcCommonConstants.UNIQUEIDENTIFIER_TYPE.equalsIgnoreCase(pc.columnTypeName())) {
return BoundaryExtractorFactory.sqlServerSortableBytesToUuidString(bytes);
}
return val;
}

/**
* Set statement parameters.
*
Expand Down Expand Up @@ -111,10 +91,9 @@ public void setParameters(
preparedStatement.setObject(parameterIdx++, null);
} else if (parentRanges.containsKey(partitionColumn.columnName())) {
Range rangeForColumn = parentRanges.get(partitionColumn.columnName());
// Convert raw byte[] to java.util.UUID to prevent PostgreSQL JDBC type mismatch (BYTEA vs
// UUID).
Object start = convertIfUuid(rangeForColumn.start(), partitionColumn);
Object end = convertIfUuid(rangeForColumn.end(), partitionColumn);
// The dialect adapter converts values the JDBC driver doesn't accept as is.
Object start = dbAdapter.toQueryParameter(rangeForColumn.start(), partitionColumn);
Object end = dbAdapter.toQueryParameter(rangeForColumn.end(), partitionColumn);
preparedStatement.setObject(parameterIdx++, true); // Enabled
preparedStatement.setObject(parameterIdx++, start);
preparedStatement.setObject(parameterIdx++, end);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,12 @@
package com.google.cloud.teleport.v2.reader.io.jdbc.uniformsplitter.range;

import static com.google.cloud.teleport.v2.reader.io.jdbc.JdbcCommonConstants.BIT_TYPE;
import static com.google.cloud.teleport.v2.reader.io.jdbc.JdbcCommonConstants.UNIQUEIDENTIFIER_TYPE;
import static com.google.cloud.teleport.v2.reader.io.jdbc.JdbcCommonConstants.UUID_TYPE;

import com.google.cloud.teleport.v2.reader.io.jdbc.uniformsplitter.UniformSplitterDBAdapter;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableMap;
import java.io.Serializable;
import java.math.BigDecimal;
import java.nio.ByteBuffer;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.SQLException;
Expand All @@ -34,7 +31,6 @@
import java.time.OffsetTime;
import java.util.Calendar;
import java.util.TimeZone;
import java.util.UUID;
import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Preconditions;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.slf4j.Logger;
Expand All @@ -60,6 +56,11 @@ public interface BoundaryOffsetTimeExtractor extends Serializable {
OffsetTime extract(ResultSet rs, int index) throws SQLException;
}

@FunctionalInterface
public interface BoundaryBinaryExtractor extends Serializable {
byte[] extract(ResultSet rs, int index, PartitionColumn partitionColumn) throws SQLException;
}

public static final Class BYTE_ARRAY_CLASS = (new byte[] {}).getClass();
private static final ImmutableMap<Class, BoundaryExtractor<?>> extractorMap =
ImmutableMap.<Class, BoundaryExtractor<?>>builder()
Expand All @@ -69,7 +70,17 @@ public interface BoundaryOffsetTimeExtractor extends Serializable {
.put(
BigDecimal.class,
(BoundaryExtractor<BigDecimal>) BoundaryExtractorFactory::fromBigDecimals)
.put(BYTE_ARRAY_CLASS, (BoundaryExtractor<byte[]>) BoundaryExtractorFactory::fromBinary)
.put(
BYTE_ARRAY_CLASS,
(BoundaryExtractor<byte[]>)
(partitionColumn, resultSet, boundaryTypeMapper, tableIdentifier) ->
// Fallback when adapter is not provided: read the raw bytes.
fromBinary(
partitionColumn,
resultSet,
boundaryTypeMapper,
tableIdentifier,
(rs, index, column) -> rs.getBytes(index)))
.put(
Timestamp.class,
(BoundaryExtractor<Timestamp>) BoundaryExtractorFactory::fromTimestamps)
Expand Down Expand Up @@ -140,6 +151,17 @@ public static <T extends Serializable> BoundaryExtractor<T> create(Class<T> c) {
public static <T extends Serializable> BoundaryExtractor<T> create(
Class<T> c, UniformSplitterDBAdapter dbAdapter) {

if (c.equals(BYTE_ARRAY_CLASS) && dbAdapter != null) {
BoundaryExtractor<byte[]> extractor =
(partitionColumn, resultSet, boundaryTypeMapper, tableIdentifier) ->
fromBinary(
partitionColumn,
resultSet,
boundaryTypeMapper,
tableIdentifier,
dbAdapter::extractBinaryBoundary);
return (BoundaryExtractor<T>) extractor;
}
if (c.equals(Duration.class) && dbAdapter != null) {
BoundaryExtractor<Duration> extractor =
(partitionColumn, resultSet, boundaryTypeMapper, tableIdentifier) ->
Expand Down Expand Up @@ -236,25 +258,13 @@ private static Boundary<byte[]> fromBinary(
PartitionColumn partitionColumn,
ResultSet resultSet,
@Nullable BoundaryTypeMapper boundaryTypeMapper,
TableIdentifier tableIdentifier)
TableIdentifier tableIdentifier,
BoundaryBinaryExtractor binaryExtractor)
throws SQLException {
Preconditions.checkArgument(partitionColumn.columnClass().equals(BYTE_ARRAY_CLASS));
resultSet.next();
boolean isUuid = UUID_TYPE.equalsIgnoreCase(partitionColumn.columnTypeName());
boolean isSqlServerUniqueIdentifier =
UNIQUEIDENTIFIER_TYPE.equalsIgnoreCase(partitionColumn.columnTypeName());
byte[] start =
isUuid
? extractUuidBytes(resultSet, 1)
: (isSqlServerUniqueIdentifier
? extractSqlServerUniqueIdentifierBytes(resultSet, 1)
: resultSet.getBytes(1));
byte[] end =
isUuid
? extractUuidBytes(resultSet, 2)
: (isSqlServerUniqueIdentifier
? extractSqlServerUniqueIdentifierBytes(resultSet, 2)
: resultSet.getBytes(2));
byte[] start = binaryExtractor.extract(resultSet, 1, partitionColumn);
byte[] end = binaryExtractor.extract(resultSet, 2, partitionColumn);
return Boundary.<byte[]>builder()
.setTableIdentifier(tableIdentifier)
.setPartitionColumn(partitionColumn)
Expand All @@ -265,81 +275,6 @@ private static Boundary<byte[]> fromBinary(
.build();
}

/**
* Permutation mapping Java big-endian UUID bytes {@code raw[0..15]} to SQL Server's {@code
* UNIQUEIDENTIFIER} comparison order.
*
* <p>SQL Server stores a {@code UNIQUEIDENTIFIER} {@code g0-g1-g2-g3-g4} in mixed-endian form
* ({@code g0}, {@code g1} and {@code g2} little-endian, {@code g3} and {@code g4} big-endian) and
* compares the stored bytes in group order {@code g4, g3, g2, g1, g0}. Relative to the canonical
* big-endian byte layout this yields: {@code g4} (10..15), {@code g3} (8, 9), and the bytes of
* {@code g2} (7, 6), {@code g1} (5, 4) and {@code g0} (3, 2, 1, 0) from least to most
* significant. For example, in SQL Server {@code '01000000-0000-0000-0000-000000000000'} sorts
* before {@code '00000001-0000-0000-0000-000000000000'}.
*
* <p>TODO(#4489): The SQL Server UNIQUEIDENTIFIER handling below is dialect-specific and should
* move into SQLServer connector.
*/
public static final int[] SQL_SERVER_UUID_BYTE_ORDER = {
10, 11, 12, 13, 14, 15, 8, 9, 7, 6, 5, 4, 3, 2, 1, 0
};

/**
* Extracts a SQL Server {@code UNIQUEIDENTIFIER} column into a 16-byte array ordered by SQL
* Server's {@code UNIQUEIDENTIFIER} comparison precedence, so that unsigned big-endian comparison
* of the returned bytes matches SQL Server's {@code <}, {@code >} and {@code ORDER BY} semantics.
*
* @see #SQL_SERVER_UUID_BYTE_ORDER
*/
private static byte[] extractSqlServerUniqueIdentifierBytes(ResultSet rs, int colIndex)
throws SQLException {
String uuidStr = rs.getString(colIndex);
if (uuidStr == null) {
return null;
}
UUID uuid = UUID.fromString(uuidStr);
ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
bb.putLong(uuid.getMostSignificantBits()).putLong(uuid.getLeastSignificantBits());
byte[] raw = bb.array();
byte[] sorted = new byte[16];
for (int i = 0; i < 16; i++) {
sorted[i] = raw[SQL_SERVER_UUID_BYTE_ORDER[i]];
}
return sorted;
}

/**
* Converts a 16-byte array in SQL Server's {@code UNIQUEIDENTIFIER} comparison order back to a
* canonical UUID string. Inverse of {@link #extractSqlServerUniqueIdentifierBytes}.
*
* @see #SQL_SERVER_UUID_BYTE_ORDER
*/
public static String sqlServerSortableBytesToUuidString(byte[] sorted) {
Preconditions.checkArgument(sorted != null && sorted.length == 16);
byte[] raw = new byte[16];
for (int i = 0; i < 16; i++) {
raw[SQL_SERVER_UUID_BYTE_ORDER[i]] = sorted[i];
}
ByteBuffer bb = ByteBuffer.wrap(raw);
return new UUID(bb.getLong(), bb.getLong()).toString();
}

/**
* Extracts exactly 16 raw binary bytes from a PostgreSQL UUID column.
*
* <p>{@code rs.getBytes()} returns 36 ASCII string bytes instead of 16 raw binary bytes, which
* corrupts range calculations.
*/
private static byte[] extractUuidBytes(ResultSet rs, int colIndex) throws SQLException {
UUID uuid = rs.getObject(colIndex, UUID.class);
if (uuid == null) {
return null;
}
ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
bb.putLong(uuid.getMostSignificantBits()).putLong(uuid.getLeastSignificantBits());
return bb.array();
}

private static Boundary<String> fromStrings(
PartitionColumn partitionColumn,
ResultSet resultSet,
Expand Down
Loading
Loading