This is an automated email from the ASF dual-hosted git repository. github-merge-queue[bot] pushed a commit to branch gh-readonly-queue/dev/pr-12005-e7f08dc52e9b7f349f4ec907c56c6420965c146e in repository https://gitbox.apache.org/repos/asf/seatunnel.git
commit 0bef81d003a9dcc3266a10140dc639534ad81bfd Author: Daniel <[email protected]> AuthorDate: Sat Nov 28 15:12:08 2026 +0000 [Improve][Connector-V2] Support safe Oracle JDBC range splitting (#12005) Co-authored-by: Daniel Leens <[email protected]> Co-authored-by: Claude Sonnet 5 <[email protected]> Co-authored-by: David Zollo <[email protected]> Co-authored-by: David Zollo <[email protected]> Co-authored-by: davidzollo <[email protected]> --- docs/en/connectors/source/Jdbc.md | 2 +- docs/zh/connectors/source/Jdbc.md | 2 +- .../jdbc/internal/dialect/JdbcDialect.java | 22 ++ .../jdbc/internal/dialect/mysql/MysqlDialect.java | 31 +- .../internal/dialect/oracle/OracleDialect.java | 282 +++++++++++++++++ .../seatunnel/jdbc/source/ChunkSplitter.java | 73 ++++- .../seatunnel/jdbc/source/FixedChunkSplitter.java | 7 +- .../dialect/JdbcDialectStringRangeSplitTest.java | 74 +++++ .../internal/dialect/mysql/MysqlDialectTest.java | 11 + .../oracle/OracleDialectStringRangeSplitTest.java | 350 +++++++++++++++++++++ .../jdbc/source/FixedChunkSplitterTest.java | 81 +++++ .../connectors/seatunnel/jdbc/JdbcOracleIT.java | 176 +++++++++++ 12 files changed, 1093 insertions(+), 18 deletions(-) diff --git a/docs/en/connectors/source/Jdbc.md b/docs/en/connectors/source/Jdbc.md index 6e370267e9..3042ca7330 100644 --- a/docs/en/connectors/source/Jdbc.md +++ b/docs/en/connectors/source/Jdbc.md @@ -210,7 +210,7 @@ Use `query` to select only the required columns. | enable_concurrent_read | Boolean | No | true | Whether to enable concurrent read with split during the snapshot phase. When set to false, the source skips split analysis and reads the table as a single split, which is useful for tables without indexes. | | common-options | | No | - | Source plugin common parameters, please refer to [Source Common Options](../common-options/source-common-options.md) for details. [...] | split.string_split_mode | Enum | No | sample | Supports different string splitting algorithms. By default, `sample` is used to determine the split by sampling the string value. You can switch to `charset_based` to enable charset-based string splitting algorithm. When set to `charset_based`, the algorithm assumes characters of partition_column are within ASCII range 32-126, which covers most character-based splitting scenarios. [...] -| split.string-strategy | Enum | No | - | Controls how String partition columns are split. Available values are `none`, `hash`, `range`, and `auto`. `range` and `auto` currently require MySQL binary collation and fixed-length printable ASCII key values. Other JDBC dialects reject `range` and `auto` until their range split support is explicitly validated. `auto` tries range splitting first and falls back to hash splitting when range splitting i [...] +| split.string-strategy | Enum | No | - | Controls how String partition columns are split. Available values are `none`, `hash`, `range`, and `auto`. `range` is enabled only after the dialect validates its ordering contract: MySQL requires binary column collation and fixed-length printable ASCII key values; Oracle requires `NLS_SORT=BINARY`, `NLS_COMP=BINARY`, a `BINARY` or `USING_NLS_COMP` column collation, database character encoding that pre [...] | split.string_split_mode_collate | String | No | - | Specifies the collation to use when string_split_mode is set to `charset_based` and the table has a special collation. If not specified, the database's default collation will be used. [...] | multi_table.failure_policy | Enum | No | FAIL_FAST | Failure handling policy for multi-table jobs. `FAIL_FAST` aborts the whole job on the first table error. `CONTINUE_OTHER_TABLES` isolates failed tables and keeps healthy tables running when the error can be attributed to a single table. [...] diff --git a/docs/zh/connectors/source/Jdbc.md b/docs/zh/connectors/source/Jdbc.md index efbced9ce5..b23479b3ab 100644 --- a/docs/zh/connectors/source/Jdbc.md +++ b/docs/zh/connectors/source/Jdbc.md @@ -208,7 +208,7 @@ JDBC Source 是有界(bounded)数据源:完成一次快照读取后即结 | split.allow-sampling | Boolean | 否 | true | 是否启用基于采样的分片策略。当设置为 false 时,无论预估分片数是否超过阈值,系统都将回退到非均匀分片方式(迭代查询方式)。默认值为 true。 | | enable_concurrent_read | Boolean | 否 | true | 是否在快照阶段启用基于分片的并发读取。当设置为 false 时,source 会跳过分片分析,并以单个 split 读取整张表,适合没有索引的表。默认值为 true。 | | split.string_split_mode | Enum | 否 | sample | 支持不同的字符串分割算法。默认使用 `sample`,通过采样字符串值来确定分割。可以切换为 `charset_based` 启用基于字符集的字符串分割算法。设置为 `charset_based` 时,算法假定 partition_column 的字符在 ASCII 32-126 范围内,覆盖了大多数基于字符的分割场景。 | -| split.string-strategy | Enum | 否 | - | 控制 String 分区列的分片方式,可选值为 `none`、`hash`、`range`、`auto`。`range` 和 `auto` 当前要求 MySQL binary collation,且键值为固定长度的可打印 ASCII 字符串。其他 JDBC 方言在显式验证 range 分片支持前会拒绝 `range` 和 `auto`。`auto` 会优先尝试 range 分片,range 不安全时回退为 hash 分片。未设置该参数时,SeaTunnel 保持现有 `split.string_split_mode` 行为。 [...] +| split.string-strategy | Enum | 否 | - | 控制 String 分区列的分片方式,可选值为 `none`、`hash`、`range`、`auto`。`range` 仅在方言验证排序语义后启用:MySQL 要求列使用 binary collation 且键值为固定长度的可打印 ASCII 字符串;Oracle 要求 `NLS_SORT=BINARY`、`NLS_COMP=BINARY`、列的 collation 为 `BINARY` 或 `USING_NLS_COMP`、数据库字符编码保持可打印 ASCII 的二进制排序,以及相同的键值限制;Oracle 的字符串 range 分片不接受自定义 `query`,因为物理表的元数据不能证明查询投影的排序和非空约束;`range` 会拒绝该配置,`auto` 会回退。Oracle 还要求 `table_path` 带 schema 限定(例如 `SCHEMA.TABLE`),以保证验证的列元数据属于实际读取 [...] | split.string_split_mode_collate | String | 否 | - | 当 string_split_mode 设置为 `charset_based` 且表具有特殊排序规则时,指定要使用的排序规则。如果未指定,将使用数据库的默认排序规则。 | | multi_table.failure_policy | Enum | 否 | FAIL_FAST | 多表作业的失败处理策略。`FAIL_FAST` 在任一表出错时中止整个作业。`CONTINUE_OTHER_TABLES` 在错误可以归因到单个表时隔离失败表,其余健康表继续运行。 | | common-options | | 否 | - | 源插件通用参数,请参考 [源通用选项](../common-options/source-common-options.md) 详见。 [...] diff --git a/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/dialect/JdbcDialect.java b/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/dialect/JdbcDialect.java index b24c8d90a1..6dd1189d99 100644 --- a/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/dialect/JdbcDialect.java +++ b/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/dialect/JdbcDialect.java @@ -371,6 +371,28 @@ public interface JdbcDialect extends Serializable { "string range split is not validated for this JDBC dialect"); } + /** + * Validates that a reader connection still uses the ordering accepted during split planning. + * + * <p>Range boundaries can be planned by one process and executed by another. Dialects that + * support String range splitting must independently validate any session-scoped comparison + * settings on each reader connection. The default preserves the existing behavior of external + * dialects that already opted into range splitting; dialects with session-scoped settings must + * override this method and fail closed when those settings are unsafe. + * + * @param connection active reader JDBC connection + * @return reader session safety decision + * @throws SQLException when the session settings cannot be read + */ + default StringRangeSplitDecision validateStringRangeSplitSession(Connection connection) + throws SQLException { + return supportStringRangeSplit() + ? StringRangeSplitDecision.safe( + "dialect has no reader-session-specific range split validation") + : StringRangeSplitDecision.unsafe( + "string range split session is not validated for this JDBC dialect"); + } + /** Returns whether this dialect has validated string range split support. */ default boolean supportStringRangeSplit() { return false; diff --git a/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/dialect/mysql/MysqlDialect.java b/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/dialect/mysql/MysqlDialect.java index 685b19efad..08bceb396b 100644 --- a/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/dialect/mysql/MysqlDialect.java +++ b/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/dialect/mysql/MysqlDialect.java @@ -243,6 +243,10 @@ public class MysqlDialect implements JdbcDialect { public StringRangeSplitDecision validateStringRangeSplit( Connection connection, JdbcSourceTable table, String columnName, int sampleSize) throws SQLException { + if (getClass() != MysqlDialect.class) { + return StringRangeSplitDecision.unsafe( + "ASCII string range splitting is only validated for the MySQL dialect"); + } if (table.getTablePath() == null || TablePath.DEFAULT.getFullName().equals(table.getTablePath().getFullName())) { return StringRangeSplitDecision.unsafe( @@ -267,9 +271,12 @@ public class MysqlDialect implements JdbcDialect { } Integer sampleLength = null; for (String sample : samples) { - if (!isPrintableAscii(sample)) { + int nonPrintableAsciiIndex = findNonPrintableAsciiIndex(sample); + if (nonPrintableAsciiIndex >= 0) { return StringRangeSplitDecision.unsafe( - String.format("sample value contains non-ASCII characters: [%s]", sample)); + String.format( + "sample value of length %s contains a non-printable ASCII character at index %s", + sample.length(), nonPrintableAsciiIndex)); } if (sampleLength == null) { sampleLength = sample.length(); @@ -284,9 +291,21 @@ public class MysqlDialect implements JdbcDialect { collation, samples.size())); } + @Override + public StringRangeSplitDecision validateStringRangeSplitSession(Connection connection) { + if (getClass() != MysqlDialect.class) { + return StringRangeSplitDecision.unsafe( + "ASCII string range splitting is only validated for the MySQL dialect"); + } + // MySQL comparison is controlled by the column collation checked during planning, not by + // a reader-session setting, so no additional database query is required here. + return StringRangeSplitDecision.safe( + "reader String comparisons use the binary column collation validated at planning"); + } + @Override public boolean supportStringRangeSplit() { - return true; + return getClass() == MysqlDialect.class; } private String queryColumnCollation( @@ -346,14 +365,14 @@ public class MysqlDialect implements JdbcDialect { return samples; } - private boolean isPrintableAscii(String value) { + private int findNonPrintableAsciiIndex(String value) { for (int i = 0; i < value.length(); i++) { char ch = value.charAt(i); if (ch < 32 || ch > 126) { - return false; + return i; } } - return true; + return -1; } @Override diff --git a/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/dialect/oracle/OracleDialect.java b/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/dialect/oracle/OracleDialect.java index 2612b2c5cb..1d428ceade 100644 --- a/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/dialect/oracle/OracleDialect.java +++ b/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/dialect/oracle/OracleDialect.java @@ -38,6 +38,7 @@ import org.apache.seatunnel.connectors.seatunnel.jdbc.internal.dialect.JdbcDiale import org.apache.seatunnel.connectors.seatunnel.jdbc.internal.dialect.SQLUtils; import org.apache.seatunnel.connectors.seatunnel.jdbc.internal.dialect.dialectenum.FieldIdeEnum; import org.apache.seatunnel.connectors.seatunnel.jdbc.source.JdbcSourceTable; +import org.apache.seatunnel.connectors.seatunnel.jdbc.source.StringRangeSplitDecision; import lombok.extern.slf4j.Slf4j; @@ -49,6 +50,7 @@ import java.sql.Statement; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; +import java.util.HashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; @@ -61,6 +63,23 @@ public class OracleDialect implements JdbcDialect { private static final int DEFAULT_ORACLE_FETCH_SIZE = 128; + private static final String NLS_SORT = "NLS_SORT"; + + private static final String NLS_COMP = "NLS_COMP"; + + private static final String BINARY_NLS_VALUE = "BINARY"; + + private static final int FIRST_PRINTABLE_ASCII = 32; + + private static final int LAST_PRINTABLE_ASCII = 126; + + private static final String BINARY_COLLATION = "BINARY"; + + private static final String USING_NLS_COMP_COLLATION = "USING_NLS_COMP"; + + /** ALL_TAB_COLUMNS.NULLABLE value reported only for columns declared NOT NULL. */ + private static final String NOT_NULL_FLAG = "N"; + /** Oracle PCTFREE legal range (inclusive). */ private static final int PCTFREE_MIN = 0; @@ -287,6 +306,269 @@ public class OracleDialect implements JdbcDialect { return SQLUtils.countForSubquery(connection, query); } + @Override + public StringRangeSplitDecision validateStringRangeSplit( + Connection connection, JdbcSourceTable table, String columnName, int sampleSize) + throws SQLException { + if (getClass() != OracleDialect.class) { + return StringRangeSplitDecision.unsafe( + "ASCII string range splitting is only validated for the Oracle dialect"); + } + // ALL_TAB_COLUMNS describes the physical table, not a query projection or join. Its + // collation and NOT NULL guarantees cannot establish safe range predicates for a query. + if (StringUtils.isNotBlank(table.getQuery())) { + return StringRangeSplitDecision.unsafe( + "Oracle string range splitting requires a physical table without a custom query"); + } + if (table.getTablePath() == null + || TablePath.DEFAULT.getFullName().equals(table.getTablePath().getFullName())) { + return StringRangeSplitDecision.unsafe( + "missing physical table path for Oracle string range split validation"); + } + // Oracle paths are parsed schema-first, so the owner of the scanned table is the schema + // component; the database component is the service name and never an object owner. An + // unqualified table is resolved by Oracle through CURRENT_SCHEMA or synonyms, which this + // validation cannot pin to one ALL_TAB_COLUMNS row, so it fails closed. + if (StringUtils.isBlank(table.getTablePath().getSchemaName())) { + return StringRangeSplitDecision.unsafe( + "Oracle string range split validation requires a schema-qualified table path"); + } + if (sampleSize <= 0) { + return StringRangeSplitDecision.unsafe("sample size must be greater than zero"); + } + StringRangeSplitDecision sessionDecision = validateStringRangeSplitSession(connection); + if (!sessionDecision.isSafe()) { + return sessionDecision; + } + StringRangeSplitDecision columnDecision = + validateStringRangeSplitColumnMetadata(connection, table, columnName); + if (!columnDecision.isSafe()) { + return columnDecision; + } + + List<String> samples = sampleStringValues(connection, table, columnName, sampleSize); + if (samples.isEmpty()) { + return StringRangeSplitDecision.unsafe("no non-null sample values found"); + } + Integer sampleLength = null; + for (String sample : samples) { + int nonPrintableAsciiIndex = findNonPrintableAsciiIndex(sample); + if (nonPrintableAsciiIndex >= 0) { + return StringRangeSplitDecision.unsafe( + String.format( + "sample value of length %s contains a non-printable ASCII character at index %s", + sample.length(), nonPrintableAsciiIndex)); + } + if (sampleLength == null) { + sampleLength = sample.length(); + } else if (sample.length() != sampleLength) { + return StringRangeSplitDecision.unsafe( + "sample values have variable lengths and cannot preserve string range order"); + } + } + return StringRangeSplitDecision.safe( + String.format( + "session %s and %s are binary and %s sampled values are fixed-length printable ASCII", + NLS_SORT, NLS_COMP, samples.size())); + } + + @Override + public StringRangeSplitDecision validateStringRangeSplitSession(Connection connection) + throws SQLException { + if (getClass() != OracleDialect.class) { + return StringRangeSplitDecision.unsafe( + "ASCII string range splitting is only validated for the Oracle dialect"); + } + Map<String, String> sessionNlsParameters = querySessionNlsParameters(connection); + String nlsSort = sessionNlsParameters.get(NLS_SORT); + if (!BINARY_NLS_VALUE.equalsIgnoreCase(nlsSort)) { + return StringRangeSplitDecision.unsafe( + String.format( + "session %s must be %s but was %s", + NLS_SORT, BINARY_NLS_VALUE, nlsSort)); + } + String nlsComp = sessionNlsParameters.get(NLS_COMP); + if (!BINARY_NLS_VALUE.equalsIgnoreCase(nlsComp)) { + return StringRangeSplitDecision.unsafe( + String.format( + "session %s must be %s but was %s", + NLS_COMP, BINARY_NLS_VALUE, nlsComp)); + } + StringRangeSplitDecision encodingDecision = validatePrintableAsciiEncoding(connection); + if (!encodingDecision.isSafe()) { + return encodingDecision; + } + return StringRangeSplitDecision.safe( + String.format( + "session %s and %s are binary and the database preserves printable ASCII binary ordering", + NLS_SORT, NLS_COMP)); + } + + @Override + public boolean supportStringRangeSplit() { + return getClass() == OracleDialect.class; + } + + private Map<String, String> querySessionNlsParameters(Connection connection) + throws SQLException { + String sql = + "SELECT PARAMETER, VALUE FROM NLS_SESSION_PARAMETERS " + + "WHERE PARAMETER IN ('NLS_SORT', 'NLS_COMP')"; + Map<String, String> parameters = new HashMap<>(); + try (Statement statement = connection.createStatement(); + ResultSet resultSet = statement.executeQuery(sql)) { + while (resultSet.next()) { + parameters.put(resultSet.getString(1), resultSet.getString(2)); + } + } + return parameters; + } + + /** + * Binary comparison follows database encoding. Verify the complete alphabet used by the Java + * boundary arithmetic so ASCII-compatible encodings work and EBCDIC encodings fail closed. + */ + private StringRangeSplitDecision validatePrintableAsciiEncoding(Connection connection) + throws SQLException { + StringBuilder sql = new StringBuilder("SELECT "); + for (int asciiCode = FIRST_PRINTABLE_ASCII; + asciiCode <= LAST_PRINTABLE_ASCII; + asciiCode++) { + if (asciiCode > FIRST_PRINTABLE_ASCII) { + sql.append(", "); + } + sql.append("ASCII(?)"); + } + sql.append(" FROM DUAL"); + + try (PreparedStatement statement = connection.prepareStatement(sql.toString())) { + for (int asciiCode = FIRST_PRINTABLE_ASCII; + asciiCode <= LAST_PRINTABLE_ASCII; + asciiCode++) { + statement.setString( + asciiCode - FIRST_PRINTABLE_ASCII + 1, String.valueOf((char) asciiCode)); + } + try (ResultSet resultSet = statement.executeQuery()) { + if (!resultSet.next()) { + return StringRangeSplitDecision.unsafe( + "database character set validation returned no result"); + } + for (int asciiCode = FIRST_PRINTABLE_ASCII; + asciiCode <= LAST_PRINTABLE_ASCII; + asciiCode++) { + if (resultSet.getInt(asciiCode - FIRST_PRINTABLE_ASCII + 1) != asciiCode) { + return StringRangeSplitDecision.unsafe( + "database character set does not preserve printable ASCII binary ordering"); + } + } + } + } + return StringRangeSplitDecision.safe("database character set preserves printable ASCII"); + } + + /** + * Oracle 12.2+ can attach a data-bound collation to a column, which overrides the session order + * used by range predicates. Accept only a binary collation or one governed by NLS_COMP. + * + * <p>The same ALL_TAB_COLUMNS row also reports nullability. Range predicates compare the split + * key against the split boundaries and a NULL key matches none of them, so rows holding a NULL + * split key would be silently skipped by every split. Only a column declared NOT NULL is + * accepted; a nullable column fails closed here so that an explicit range strategy is rejected + * and auto falls back, mirroring the collation and encoding checks. + * + * <p>The metadata row must describe the exact object that the split SQL reads. That SQL quotes + * every identifier through {@link #quoteIdentifier(String)}, which makes Oracle compare names + * case-sensitively: the owner is used verbatim and the table and column names go through the + * configured field identifier rule. The lookup binds the same names instead of upper-casing + * them, otherwise a different upper-case object could vouch for the collation and nullability + * of a quoted mixed-case target. + */ + private StringRangeSplitDecision validateStringRangeSplitColumnMetadata( + Connection connection, JdbcSourceTable table, String columnName) throws SQLException { + TablePath tablePath = table.getTablePath(); + String sql = + "SELECT COLLATION, NULLABLE FROM ALL_TAB_COLUMNS " + + "WHERE OWNER = ? AND TABLE_NAME = ? AND COLUMN_NAME = ?"; + try (PreparedStatement statement = connection.prepareStatement(sql)) { + statement.setString(1, tablePath.getSchemaName()); + statement.setString(2, getFieldIde(tablePath.getTableName(), fieldIde)); + statement.setString(3, getFieldIde(columnName, fieldIde)); + try (ResultSet resultSet = statement.executeQuery()) { + if (!resultSet.next()) { + return StringRangeSplitDecision.unsafe( + "column collation is unavailable for Oracle string range split validation"); + } + String collation = resultSet.getString(1); + if (!BINARY_COLLATION.equalsIgnoreCase(collation) + && !USING_NLS_COMP_COLLATION.equalsIgnoreCase(collation)) { + return StringRangeSplitDecision.unsafe( + String.format("column collation %s is not binary", collation)); + } + // NULLABLE is 'N' only when a NOT NULL constraint exists; treat 'Y' and any + // unexpected value as nullable so the decision stays fail-closed. + String nullable = resultSet.getString(2); + if (!NOT_NULL_FLAG.equalsIgnoreCase(nullable)) { + return StringRangeSplitDecision.unsafe( + String.format( + "column %s is nullable and rows with a NULL split key would be skipped by range predicates", + columnName)); + } + } + } + return StringRangeSplitDecision.safe( + "column collation preserves binary comparison and the column is NOT NULL"); + } + + private List<String> sampleStringValues( + Connection connection, JdbcSourceTable table, String columnName, int sampleSize) + throws SQLException { + String quotedColumn = quoteIdentifier(columnName); + String sql; + if (StringUtils.isNotBlank(table.getQuery())) { + sql = + String.format( + "SELECT %s FROM (SELECT %s FROM (%s) tmp WHERE %s IS NOT NULL ORDER BY %s ASC) WHERE ROWNUM <= %s", + quotedColumn, + quotedColumn, + table.getQuery(), + quotedColumn, + quotedColumn, + sampleSize); + } else { + sql = + String.format( + "SELECT %s FROM (SELECT %s FROM %s WHERE %s IS NOT NULL ORDER BY %s ASC) WHERE ROWNUM <= %s", + quotedColumn, + quotedColumn, + tableIdentifier(table.getTablePath()), + quotedColumn, + quotedColumn, + sampleSize); + } + + List<String> samples = new ArrayList<>(sampleSize); + try (Statement statement = connection.createStatement(); + ResultSet resultSet = statement.executeQuery(sql)) { + while (resultSet.next()) { + String value = resultSet.getString(1); + if (value != null) { + samples.add(value); + } + } + } + return samples; + } + + private int findNonPrintableAsciiIndex(String value) { + for (int i = 0; i < value.length(); i++) { + char ch = value.charAt(i); + if (ch < FIRST_PRINTABLE_ASCII || ch > LAST_PRINTABLE_ASCII) { + return i; + } + } + return -1; + } + @Override public Object queryNextChunkMax( Connection connection, diff --git a/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/source/ChunkSplitter.java b/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/source/ChunkSplitter.java index 5636ca68ee..412348a5c4 100644 --- a/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/source/ChunkSplitter.java +++ b/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/source/ChunkSplitter.java @@ -27,6 +27,7 @@ import org.apache.seatunnel.api.table.catalog.TablePath; import org.apache.seatunnel.api.table.catalog.TableSchema; import org.apache.seatunnel.api.table.type.SeaTunnelDataType; import org.apache.seatunnel.api.table.type.SeaTunnelRowType; +import org.apache.seatunnel.api.table.type.SqlType; import org.apache.seatunnel.common.exception.CommonErrorCodeDeprecated; import org.apache.seatunnel.connectors.seatunnel.jdbc.config.JdbcSourceConfig; import org.apache.seatunnel.connectors.seatunnel.jdbc.exception.JdbcConnectorException; @@ -61,6 +62,10 @@ public abstract class ChunkSplitter implements AutoCloseable, Serializable { private final int fetchSize; private final boolean autoCommit; + // This splitter can move across nodes, but a session check is valid only for the local + // physical connection that performed it. Keep the marker transient and use identity checks. + private transient Connection validatedStringRangeSessionConnection; + public ChunkSplitter(JdbcSourceConfig config) { this.config = config; this.autoCommit = config.getJdbcConnectionConfig().isAutoCommit(); @@ -148,6 +153,9 @@ public abstract class ChunkSplitter implements AutoCloseable, Serializable { public PreparedStatement generateSplitStatement(JdbcSourceSplit split, TableSchema schema) throws SQLException { + if (requiresStringRangeSplitSessionValidation(split)) { + validateStringRangeSplitReaderSession(); + } if (split.getSplitKeyName() == null) { return createSingleSplitStatement(split); } @@ -207,7 +215,6 @@ public abstract class ChunkSplitter implements AutoCloseable, Serializable { && requestedStrategy != StringSplitStrategy.AUTO)) { return requestedStrategy; } - if (!jdbcDialect.supportStringRangeSplit()) { throw new JdbcConnectorException( CommonErrorCodeDeprecated.ILLEGAL_ARGUMENT, @@ -216,9 +223,29 @@ public abstract class ChunkSplitter implements AutoCloseable, Serializable { requestedStrategy, jdbcDialect.dialectName())); } - StringRangeSplitDecision decision = - jdbcDialect.validateStringRangeSplit( - getOrEstablishConnection(), applyWhereCondition(table), splitKeyName, 256); + StringRangeSplitDecision decision; + try { + decision = + jdbcDialect.validateStringRangeSplit( + getOrEstablishConnection(), table, splitKeyName, 256); + } catch (SQLException e) { + if (requestedStrategy == StringSplitStrategy.RANGE) { + throw new JdbcConnectorException( + CommonErrorCodeDeprecated.ILLEGAL_ARGUMENT, + String.format( + "String range split validation failed for table %s, split column %s", + table.getTablePath(), splitKeyName), + e); + } + StringSplitStrategy fallback = getStringSplitFallbackStrategy(); + log.warn( + "String range split validation failed for table {}, split column {}, fallback strategy: {}", + table.getTablePath(), + splitKeyName, + fallback, + e); + return fallback; + } if (decision.isSafe()) { return StringSplitStrategy.RANGE; } @@ -230,10 +257,7 @@ public abstract class ChunkSplitter implements AutoCloseable, Serializable { table.getTablePath(), splitKeyName, decision.getReason())); } - StringSplitStrategy fallback = - jdbcDialect.supportHashSplitter() - ? StringSplitStrategy.HASH - : StringSplitStrategy.NONE; + StringSplitStrategy fallback = getStringSplitFallbackStrategy(); log.warn( "String range split is unsafe for table {}, split column {}. Requested strategy: {}, fallback strategy: {}, reason: {}", table.getTablePath(), @@ -244,6 +268,39 @@ public abstract class ChunkSplitter implements AutoCloseable, Serializable { return fallback; } + /** + * Revalidates once for each physical reader connection because planning and reading can use + * different session-scoped comparison settings. + */ + private synchronized void validateStringRangeSplitReaderSession() throws SQLException { + Connection connection = getOrEstablishConnection(); + if (connection == validatedStringRangeSessionConnection) { + return; + } + StringRangeSplitDecision decision = jdbcDialect.validateStringRangeSplitSession(connection); + if (!decision.isSafe()) { + throw new JdbcConnectorException( + CommonErrorCodeDeprecated.ILLEGAL_ARGUMENT, + "String range split reader session is unsafe: " + decision.getReason()); + } + validatedStringRangeSessionConnection = connection; + } + + private boolean requiresStringRangeSplitSessionValidation(JdbcSourceSplit split) { + return (config.getStringSplitStrategy() == StringSplitStrategy.RANGE + || config.getStringSplitStrategy() == StringSplitStrategy.AUTO) + && split.getSplitKeyType() != null + && SqlType.STRING.equals(split.getSplitKeyType().getSqlType()) + && (split.getSplitStart() instanceof String + || split.getSplitEnd() instanceof String); + } + + private StringSplitStrategy getStringSplitFallbackStrategy() { + return jdbcDialect.supportHashSplitter() + ? StringSplitStrategy.HASH + : StringSplitStrategy.NONE; + } + protected PreparedStatement createSingleSplitStatement(JdbcSourceSplit split) throws SQLException { String splitQuery = split.getSplitQuery(); diff --git a/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/source/FixedChunkSplitter.java b/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/source/FixedChunkSplitter.java index 7be8ae09ec..7cd8fe9d64 100644 --- a/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/source/FixedChunkSplitter.java +++ b/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/source/FixedChunkSplitter.java @@ -98,10 +98,13 @@ public class FixedChunkSplitter extends ChunkSplitter { return createStringRangeSplits(table, splitKeyName, splitKeyType); } catch (Exception e) { log.warn( - "Range string split failed for table {}, fallback to hash split", + "Range string split failed for table {}, fallback to {} split", table.getTablePath(), + jdbcDialect.supportHashSplitter() ? "hash" : "single", e); - return createStringColumnSplits(table, splitKeyName, splitKeyType); + return jdbcDialect.supportHashSplitter() + ? createStringColumnSplits(table, splitKeyName, splitKeyType) + : Collections.singletonList(createSingleSplit(table)); } } return createStringRangeSplits(table, splitKeyName, splitKeyType); diff --git a/seatunnel-connectors-v2/connector-jdbc/src/test/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/dialect/JdbcDialectStringRangeSplitTest.java b/seatunnel-connectors-v2/connector-jdbc/src/test/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/dialect/JdbcDialectStringRangeSplitTest.java new file mode 100644 index 0000000000..9b3a11ff07 --- /dev/null +++ b/seatunnel-connectors-v2/connector-jdbc/src/test/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/dialect/JdbcDialectStringRangeSplitTest.java @@ -0,0 +1,74 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 org.apache.seatunnel.connectors.seatunnel.jdbc.internal.dialect; + +import org.apache.seatunnel.api.table.converter.BasicTypeDefine; +import org.apache.seatunnel.api.table.converter.TypeConverter; +import org.apache.seatunnel.connectors.seatunnel.jdbc.internal.converter.JdbcRowConverter; + +import org.junit.jupiter.api.Test; + +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** Verifies adding reader-session validation does not break existing external range dialects. */ +public class JdbcDialectStringRangeSplitTest { + + @Test + public void testDefaultReaderSessionValidationPreservesExternalRangeDialectBehavior() + throws Exception { + JdbcDialect dialect = new ExternalRangeDialect(); + + assertTrue(dialect.validateStringRangeSplitSession(null).isSafe()); + } + + private static final class ExternalRangeDialect implements JdbcDialect { + + @Override + public String dialectName() { + return "external"; + } + + @Override + public JdbcRowConverter getRowConverter() { + return null; + } + + @Override + public TypeConverter<BasicTypeDefine> getTypeConverter() { + return null; + } + + @Override + public JdbcDialectTypeMapper getJdbcDialectTypeMapper() { + return null; + } + + @Override + public Optional<String> getUpsertStatement( + String database, String tableName, String[] fieldNames, String[] pkNames) { + return Optional.empty(); + } + + @Override + public boolean supportStringRangeSplit() { + return true; + } + } +} diff --git a/seatunnel-connectors-v2/connector-jdbc/src/test/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/dialect/mysql/MysqlDialectTest.java b/seatunnel-connectors-v2/connector-jdbc/src/test/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/dialect/mysql/MysqlDialectTest.java index 1c9925eb9c..4aaf3c2aec 100644 --- a/seatunnel-connectors-v2/connector-jdbc/src/test/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/dialect/mysql/MysqlDialectTest.java +++ b/seatunnel-connectors-v2/connector-jdbc/src/test/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/dialect/mysql/MysqlDialectTest.java @@ -23,6 +23,7 @@ import org.apache.seatunnel.connectors.seatunnel.jdbc.internal.converter.JdbcRow import org.apache.seatunnel.connectors.seatunnel.jdbc.internal.dialect.DatabaseIdentifier; import org.apache.seatunnel.connectors.seatunnel.jdbc.internal.dialect.JdbcDialect; import org.apache.seatunnel.connectors.seatunnel.jdbc.internal.dialect.JdbcDialectTypeMapper; +import org.apache.seatunnel.connectors.seatunnel.jdbc.internal.dialect.starrocks.StarRocksDialect; import org.apache.seatunnel.connectors.seatunnel.jdbc.source.JdbcSourceTable; import org.apache.seatunnel.connectors.seatunnel.jdbc.source.StringRangeSplitDecision; @@ -127,6 +128,16 @@ public class MysqlDialectTest { Assertions.assertTrue(decision.isSafe()); } + @Test + public void testDerivedMysqlDialectDoesNotInheritStringRangeSplitValidation() throws Exception { + StarRocksDialect dialect = new StarRocksDialect(); + StringRangeSplitDecision decision = dialect.validateStringRangeSplit(null, null, "id", 256); + + Assertions.assertFalse(decision.isSafe()); + Assertions.assertFalse(dialect.validateStringRangeSplitSession(null).isSafe()); + Assertions.assertFalse(dialect.supportStringRangeSplit()); + } + @Test public void testHashDistributionMD5vsCRC32WithSnowflakeIds() { int totalRecords = 1_100_000; diff --git a/seatunnel-connectors-v2/connector-jdbc/src/test/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/dialect/oracle/OracleDialectStringRangeSplitTest.java b/seatunnel-connectors-v2/connector-jdbc/src/test/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/dialect/oracle/OracleDialectStringRangeSplitTest.java new file mode 100644 index 0000000000..acdf1e4f78 --- /dev/null +++ b/seatunnel-connectors-v2/connector-jdbc/src/test/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/dialect/oracle/OracleDialectStringRangeSplitTest.java @@ -0,0 +1,350 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 org.apache.seatunnel.connectors.seatunnel.jdbc.internal.dialect.oracle; + +import org.apache.seatunnel.api.table.catalog.TablePath; +import org.apache.seatunnel.connectors.seatunnel.jdbc.source.JdbcSourceTable; +import org.apache.seatunnel.connectors.seatunnel.jdbc.source.StringRangeSplitDecision; + +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** Verifies Oracle range splitting requires binary session ordering and fixed ASCII keys. */ +public class OracleDialectStringRangeSplitTest { + + /** + * A physical path cannot vouch for a nullable or transformed custom-query projection. + * + * <p>A null connection also verifies that rejection happens before table metadata is queried. + */ + @Test + public void testRejectsCustomQueryEvenWithPhysicalTablePath() throws SQLException { + JdbcSourceTable table = + JdbcSourceTable.builder() + .tablePath(TablePath.of("APP", "ORDERS")) + .query("SELECT NULL AS ORDER_ID FROM APP.ORDERS") + .build(); + + StringRangeSplitDecision decision = + new OracleDialect().validateStringRangeSplit(null, table, "ORDER_ID", 1); + + assertFalse(decision.isSafe()); + assertTrue(decision.getReason().contains("without a custom query")); + } + + @Test + public void testAcceptsBinaryNlsAndFixedAsciiSamples() throws SQLException { + Connection connection = mock(Connection.class); + Statement nlsStatement = mock(Statement.class); + Statement sampleStatement = mock(Statement.class); + ResultSet nlsResultSet = binaryNlsResultSet(); + ResultSet sampleResultSet = mock(ResultSet.class); + when(connection.createStatement()).thenReturn(nlsStatement, sampleStatement); + when(nlsStatement.executeQuery(anyString())).thenReturn(nlsResultSet); + when(sampleStatement.executeQuery(anyString())).thenReturn(sampleResultSet); + when(sampleResultSet.next()).thenReturn(true, true, false); + when(sampleResultSet.getString(1)).thenReturn("A000", "A001"); + stubSafeOracleRangeMetadata(connection); + + StringRangeSplitDecision decision = + new OracleDialect() + .validateStringRangeSplit(connection, physicalTable(), "ORDER_ID", 2); + + assertTrue(decision.isSafe()); + ArgumentCaptor<String> sqlCaptor = ArgumentCaptor.forClass(String.class); + verify(sampleStatement).executeQuery(sqlCaptor.capture()); + assertTrue(sqlCaptor.getValue().contains("ROWNUM <= 2")); + assertTrue(sqlCaptor.getValue().contains("ORDER BY \"ORDER_ID\" ASC")); + } + + @Test + public void testRejectsNonBinaryComparisonSession() throws SQLException { + Connection connection = mock(Connection.class); + Statement nlsStatement = mock(Statement.class); + ResultSet nlsResultSet = mock(ResultSet.class); + when(connection.createStatement()).thenReturn(nlsStatement); + when(nlsStatement.executeQuery(anyString())).thenReturn(nlsResultSet); + when(nlsResultSet.next()).thenReturn(true, true, false); + when(nlsResultSet.getString(1)).thenReturn("NLS_SORT", "NLS_COMP"); + when(nlsResultSet.getString(2)).thenReturn("BINARY", "LINGUISTIC"); + + StringRangeSplitDecision decision = + new OracleDialect() + .validateStringRangeSplit(connection, physicalTable(), "ORDER_ID", 2); + + assertFalse(decision.isSafe()); + } + + @Test + public void testRejectsVariableLengthSamples() throws SQLException { + Connection connection = mock(Connection.class); + Statement nlsStatement = mock(Statement.class); + Statement sampleStatement = mock(Statement.class); + ResultSet sampleResultSet = mock(ResultSet.class); + ResultSet nlsResultSet = binaryNlsResultSet(); + when(connection.createStatement()).thenReturn(nlsStatement, sampleStatement); + when(nlsStatement.executeQuery(anyString())).thenReturn(nlsResultSet); + when(sampleStatement.executeQuery(anyString())).thenReturn(sampleResultSet); + when(sampleResultSet.next()).thenReturn(true, true, false); + when(sampleResultSet.getString(1)).thenReturn("A000", "A0010"); + stubSafeOracleRangeMetadata(connection); + + StringRangeSplitDecision decision = + new OracleDialect() + .validateStringRangeSplit(connection, physicalTable(), "ORDER_ID", 2); + + assertFalse(decision.isSafe()); + } + + @Test + public void testRejectsDatabaseEncodingThatDoesNotPreserveAsciiBinaryOrdering() + throws SQLException { + Connection connection = mock(Connection.class); + Statement nlsStatement = mock(Statement.class); + PreparedStatement encodingStatement = mock(PreparedStatement.class); + ResultSet encodingResultSet = mock(ResultSet.class); + when(connection.createStatement()).thenReturn(nlsStatement); + // Build the NLS result set before it is used as a stubbed return value: creating and + // stubbing a mock inside thenReturn(...) leaves the outer stubbing unfinished and + // Mockito rejects it with UnfinishedStubbingException. + ResultSet nlsResultSet = binaryNlsResultSet(); + when(nlsStatement.executeQuery(anyString())).thenReturn(nlsResultSet); + when(connection.prepareStatement(anyString())).thenReturn(encodingStatement); + when(encodingStatement.executeQuery()).thenReturn(encodingResultSet); + when(encodingResultSet.next()).thenReturn(true); + when(encodingResultSet.getInt(anyInt())).thenReturn(193); + + StringRangeSplitDecision decision = + new OracleDialect().validateStringRangeSplitSession(connection); + + assertFalse(decision.isSafe()); + assertTrue(decision.getReason().contains("does not preserve printable ASCII")); + } + + @Test + public void testRedactsNonAsciiSampleValue() throws SQLException { + Connection connection = mock(Connection.class); + Statement nlsStatement = mock(Statement.class); + Statement sampleStatement = mock(Statement.class); + ResultSet sampleResultSet = mock(ResultSet.class); + when(connection.createStatement()).thenReturn(nlsStatement, sampleStatement); + // Build the NLS result set before it is used as a stubbed return value: creating and + // stubbing a mock inside thenReturn(...) leaves the outer stubbing unfinished and + // Mockito rejects it with UnfinishedStubbingException. + ResultSet nlsResultSet = binaryNlsResultSet(); + when(nlsStatement.executeQuery(anyString())).thenReturn(nlsResultSet); + when(sampleStatement.executeQuery(anyString())).thenReturn(sampleResultSet); + when(sampleResultSet.next()).thenReturn(true, false); + when(sampleResultSet.getString(1)).thenReturn("AB\u4e2d"); + stubSafeOracleRangeMetadata(connection); + + StringRangeSplitDecision decision = + new OracleDialect() + .validateStringRangeSplit(connection, physicalTable(), "ORDER_ID", 1); + + assertFalse(decision.isSafe()); + assertFalse(decision.getReason().contains("AB\u4e2d")); + assertTrue(decision.getReason().contains("length 3")); + } + + @Test + public void testRejectsMissingPhysicalTablePath() throws SQLException { + JdbcSourceTable table = JdbcSourceTable.builder().tablePath(TablePath.DEFAULT).build(); + + StringRangeSplitDecision decision = + new OracleDialect().validateStringRangeSplit(null, table, "ORDER_ID", 1); + + assertFalse(decision.isSafe()); + } + + @Test + public void testRejectsNonBinaryDataBoundColumnCollation() throws SQLException { + Connection connection = mock(Connection.class); + Statement nlsStatement = mock(Statement.class); + PreparedStatement collationStatement = mock(PreparedStatement.class); + ResultSet collationResultSet = mock(ResultSet.class); + PreparedStatement encodingStatement = mock(PreparedStatement.class); + ResultSet encodingResultSet = mock(ResultSet.class); + when(connection.createStatement()).thenReturn(nlsStatement); + // Build the NLS result set before it is used as a stubbed return value: creating and + // stubbing a mock inside thenReturn(...) leaves the outer stubbing unfinished and + // Mockito rejects it with UnfinishedStubbingException. + ResultSet nlsResultSet = binaryNlsResultSet(); + when(nlsStatement.executeQuery(anyString())).thenReturn(nlsResultSet); + when(connection.prepareStatement(anyString())) + .thenReturn(encodingStatement, collationStatement); + stubAsciiCompatibleEncoding(encodingStatement, encodingResultSet); + when(collationStatement.executeQuery()).thenReturn(collationResultSet); + when(collationResultSet.next()).thenReturn(true); + when(collationResultSet.getString(1)).thenReturn("BINARY_CI"); + + StringRangeSplitDecision decision = + new OracleDialect() + .validateStringRangeSplit(connection, physicalTable(), "ORDER_ID", 1); + + assertFalse(decision.isSafe()); + assertTrue(decision.getReason().contains("column collation BINARY_CI is not binary")); + } + + @Test + public void testRejectsNullableSplitColumn() throws SQLException { + Connection connection = mock(Connection.class); + Statement nlsStatement = mock(Statement.class); + Statement sampleStatement = mock(Statement.class); + PreparedStatement columnStatement = mock(PreparedStatement.class); + ResultSet columnResultSet = mock(ResultSet.class); + PreparedStatement encodingStatement = mock(PreparedStatement.class); + ResultSet encodingResultSet = mock(ResultSet.class); + ResultSet sampleResultSet = mock(ResultSet.class); + when(connection.createStatement()).thenReturn(nlsStatement, sampleStatement); + // Build the NLS result set before it is used as a stubbed return value: creating and + // stubbing a mock inside thenReturn(...) leaves the outer stubbing unfinished and + // Mockito rejects it with UnfinishedStubbingException. + ResultSet nlsResultSet = binaryNlsResultSet(); + when(nlsStatement.executeQuery(anyString())).thenReturn(nlsResultSet); + when(connection.prepareStatement(anyString())) + .thenReturn(encodingStatement, columnStatement); + stubAsciiCompatibleEncoding(encodingStatement, encodingResultSet); + when(columnStatement.executeQuery()).thenReturn(columnResultSet); + when(columnResultSet.next()).thenReturn(true); + when(columnResultSet.getString(1)).thenReturn("BINARY"); + when(columnResultSet.getString(2)).thenReturn("Y"); + // Samples that would pass every other check, so only the nullability gate can reject. + when(sampleStatement.executeQuery(anyString())).thenReturn(sampleResultSet); + when(sampleResultSet.next()).thenReturn(true, true, false); + when(sampleResultSet.getString(1)).thenReturn("A000", "A001"); + + StringRangeSplitDecision decision = + new OracleDialect() + .validateStringRangeSplit(connection, physicalTable(), "ORDER_ID", 2); + + assertFalse(decision.isSafe()); + assertTrue(decision.getReason().contains("ORDER_ID is nullable")); + // Planning must stop before sampling: a nullable key is rejected without reading data. + verify(sampleStatement, never()).executeQuery(anyString()); + } + + @Test + public void testColumnMetadataLookupBindsTheExactObjectReadBySplitSql() throws SQLException { + Connection connection = mock(Connection.class); + Statement nlsStatement = mock(Statement.class); + Statement sampleStatement = mock(Statement.class); + ResultSet nlsResultSet = binaryNlsResultSet(); + ResultSet sampleResultSet = mock(ResultSet.class); + when(connection.createStatement()).thenReturn(nlsStatement, sampleStatement); + when(nlsStatement.executeQuery(anyString())).thenReturn(nlsResultSet); + when(sampleStatement.executeQuery(anyString())).thenReturn(sampleResultSet); + when(sampleResultSet.next()).thenReturn(true, false); + when(sampleResultSet.getString(1)).thenReturn("A000"); + PreparedStatement columnStatement = stubSafeOracleRangeMetadata(connection); + // The database component is the Oracle service name and differs from the owner; the + // mixed-case names are quoted by the split SQL and therefore must not be upper-cased. + JdbcSourceTable table = + JdbcSourceTable.builder() + .tablePath(new OracleDialect().parse("ORCLPDB1.App_Owner.Orders")) + .build(); + + StringRangeSplitDecision decision = + new OracleDialect().validateStringRangeSplit(connection, table, "Order_Id", 1); + + assertTrue(decision.isSafe()); + verify(columnStatement).setString(1, "App_Owner"); + verify(columnStatement).setString(2, "Orders"); + verify(columnStatement).setString(3, "Order_Id"); + ArgumentCaptor<String> sqlCaptor = ArgumentCaptor.forClass(String.class); + verify(sampleStatement).executeQuery(sqlCaptor.capture()); + assertTrue(sqlCaptor.getValue().contains("FROM \"App_Owner\".\"Orders\"")); + } + + @Test + public void testRejectsTablePathWithoutSchema() throws SQLException { + JdbcSourceTable table = + JdbcSourceTable.builder().tablePath(new OracleDialect().parse("ORDERS")).build(); + + StringRangeSplitDecision decision = + new OracleDialect().validateStringRangeSplit(null, table, "ORDER_ID", 1); + + assertFalse(decision.isSafe()); + assertTrue(decision.getReason().contains("schema-qualified table path")); + } + + @Test + public void testDerivedOracleDialectDoesNotAdvertiseRangeSplitSupport() throws SQLException { + OracleDialect dialect = new DerivedOracleDialect(); + + assertFalse(dialect.supportStringRangeSplit()); + assertFalse(dialect.validateStringRangeSplitSession(null).isSafe()); + } + + private PreparedStatement stubSafeOracleRangeMetadata(Connection connection) + throws SQLException { + PreparedStatement collationStatement = mock(PreparedStatement.class); + ResultSet collationResultSet = mock(ResultSet.class); + PreparedStatement encodingStatement = mock(PreparedStatement.class); + ResultSet encodingResultSet = mock(ResultSet.class); + when(connection.prepareStatement(anyString())) + .thenReturn(encodingStatement, collationStatement); + stubAsciiCompatibleEncoding(encodingStatement, encodingResultSet); + when(collationStatement.executeQuery()).thenReturn(collationResultSet); + when(collationResultSet.next()).thenReturn(true); + when(collationResultSet.getString(1)).thenReturn("BINARY"); + when(collationResultSet.getString(2)).thenReturn("N"); + return collationStatement; + } + + private void stubAsciiCompatibleEncoding( + PreparedStatement encodingStatement, ResultSet encodingResultSet) throws SQLException { + when(encodingStatement.executeQuery()).thenReturn(encodingResultSet); + when(encodingResultSet.next()).thenReturn(true); + when(encodingResultSet.getInt(anyInt())) + .thenAnswer(invocation -> ((Integer) invocation.getArgument(0)) + 31); + } + + private ResultSet binaryNlsResultSet() throws SQLException { + ResultSet resultSet = mock(ResultSet.class); + when(resultSet.next()).thenReturn(true, true, false); + when(resultSet.getString(1)).thenReturn("NLS_SORT", "NLS_COMP"); + when(resultSet.getString(2)).thenReturn("BINARY", "BINARY"); + return resultSet; + } + + /** + * Builds the table the same way a configured {@code table_path = "APP.ORDERS"} is parsed: + * Oracle parsing is schema-first, so APP is the schema (owner) and the database is unset. + */ + private JdbcSourceTable physicalTable() { + return JdbcSourceTable.builder().tablePath(new OracleDialect().parse("APP.ORDERS")).build(); + } + + private static final class DerivedOracleDialect extends OracleDialect {} +} diff --git a/seatunnel-connectors-v2/connector-jdbc/src/test/java/org/apache/seatunnel/connectors/seatunnel/jdbc/source/FixedChunkSplitterTest.java b/seatunnel-connectors-v2/connector-jdbc/src/test/java/org/apache/seatunnel/connectors/seatunnel/jdbc/source/FixedChunkSplitterTest.java index 852f591506..ccab13947c 100644 --- a/seatunnel-connectors-v2/connector-jdbc/src/test/java/org/apache/seatunnel/connectors/seatunnel/jdbc/source/FixedChunkSplitterTest.java +++ b/seatunnel-connectors-v2/connector-jdbc/src/test/java/org/apache/seatunnel/connectors/seatunnel/jdbc/source/FixedChunkSplitterTest.java @@ -71,6 +71,9 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; @Slf4j public class FixedChunkSplitterTest { @@ -142,6 +145,62 @@ public class FixedChunkSplitterTest { assertTrue(exception.getMessage().contains("does not support range/auto")); } + @Test + public void testReaderRejectsOracleRangeSplitWithUnsafeSession() throws SQLException { + Connection connection = mock(Connection.class); + Statement statement = mock(Statement.class); + ResultSet resultSet = mock(ResultSet.class); + when(connection.createStatement()).thenReturn(statement); + when(statement.executeQuery(anyString())).thenReturn(resultSet); + when(resultSet.next()).thenReturn(true, true, false); + when(resultSet.getString(1)).thenReturn("NLS_SORT", "NLS_COMP"); + when(resultSet.getString(2)).thenReturn("BINARY", "LINGUISTIC"); + + CapturingFixedChunkSplitter splitter = + new CapturingFixedChunkSplitter(oracleConfig(), connection); + JdbcSourceSplit split = + new JdbcSourceSplit( + TablePath.of("APP", "ORDERS"), + "split-0", + null, + "ORDER_ID", + BasicType.STRING_TYPE, + null, + "A100"); + + JdbcConnectorException exception = + assertThrows( + JdbcConnectorException.class, + () -> + splitter.generateSplitStatement( + split, TableSchema.builder().build())); + + assertTrue(exception.getMessage().contains("session NLS_COMP must be BINARY")); + } + + @Test + public void testAutoOracleStringRangeSplitFallsBackWhenSessionValidationQueryFails() + throws SQLException { + Connection connection = mock(Connection.class); + when(connection.createStatement()) + .thenThrow(new SQLException("NLS_SESSION_PARAMETERS denied")); + JdbcSourceConfig config = + JdbcSourceConfig.builder() + .jdbcConnectionConfig( + JdbcConnectionConfig.builder() + .url("jdbc:oracle:thin:@localhost:1521:xe") + .driverName("oracle.jdbc.OracleDriver") + .build()) + .stringSplitStrategy(StringSplitStrategy.AUTO) + .build(); + CapturingFixedChunkSplitter splitter = new CapturingFixedChunkSplitter(config, connection); + JdbcSourceTable table = + JdbcSourceTable.builder().tablePath(TablePath.of("APP", "ORDERS")).build(); + + assertEquals( + StringSplitStrategy.HASH, splitter.resolveStringSplitStrategy(table, "ORDER_ID")); + } + @Test public void testDateSplitsWithIsoAndLegacyBoundsBindJdbcDates() throws Exception { for (String[] bounds : @@ -377,14 +436,36 @@ public class FixedChunkSplitterTest { .build(); } + private static JdbcSourceConfig oracleConfig() { + return JdbcSourceConfig.builder() + .jdbcConnectionConfig( + JdbcConnectionConfig.builder() + .url("jdbc:oracle:thin:@localhost:1521:xe") + .driverName("oracle.jdbc.OracleDriver") + .build()) + .stringSplitStrategy(StringSplitStrategy.RANGE) + .build(); + } + private static class CapturingFixedChunkSplitter extends FixedChunkSplitter { private String sql; private final Map<Integer, String> stringParameters = new HashMap<>(); + private final Connection connection; private final Map<Integer, Date> dateParameters = new HashMap<>(); private final Map<Integer, BigDecimal> bigDecimalParameters = new HashMap<>(); private CapturingFixedChunkSplitter(JdbcSourceConfig config) { + this(config, null); + } + + private CapturingFixedChunkSplitter(JdbcSourceConfig config, Connection connection) { super(config); + this.connection = connection; + } + + @Override + protected Connection getOrEstablishConnection() { + return connection; } @Override diff --git a/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-jdbc-e2e/connector-jdbc-e2e-part-1/src/test/java/org/apache/seatunnel/connectors/seatunnel/jdbc/JdbcOracleIT.java b/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-jdbc-e2e/connector-jdbc-e2e-part-1/src/test/java/org/apache/seatunnel/connectors/seatunnel/jdbc/JdbcOracleIT.java index 062cb494be..0e8682046e 100644 --- a/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-jdbc-e2e/connector-jdbc-e2e-part-1/src/test/java/org/apache/seatunnel/connectors/seatunnel/jdbc/JdbcOracleIT.java +++ b/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-jdbc-e2e/connector-jdbc-e2e-part-1/src/test/java/org/apache/seatunnel/connectors/seatunnel/jdbc/JdbcOracleIT.java @@ -21,13 +21,23 @@ package org.apache.seatunnel.connectors.seatunnel.jdbc; import org.apache.seatunnel.shade.com.google.common.collect.Lists; import org.apache.seatunnel.shade.org.apache.commons.lang3.tuple.Pair; +import org.apache.seatunnel.api.configuration.ReadonlyConfig; +import org.apache.seatunnel.api.options.MultiTableFailurePolicy; import org.apache.seatunnel.api.table.catalog.TablePath; import org.apache.seatunnel.api.table.type.SeaTunnelRow; import org.apache.seatunnel.connectors.seatunnel.jdbc.catalog.oracle.OracleCatalog; import org.apache.seatunnel.connectors.seatunnel.jdbc.catalog.oracle.OracleURLParser; +import org.apache.seatunnel.connectors.seatunnel.jdbc.config.JdbcConnectionConfig; +import org.apache.seatunnel.connectors.seatunnel.jdbc.config.JdbcSourceConfig; +import org.apache.seatunnel.connectors.seatunnel.jdbc.config.JdbcSourceTableConfig; +import org.apache.seatunnel.connectors.seatunnel.jdbc.exception.JdbcConnectorException; import org.apache.seatunnel.connectors.seatunnel.jdbc.internal.dialect.JdbcDialect; import org.apache.seatunnel.connectors.seatunnel.jdbc.internal.dialect.oracle.OracleDialect; +import org.apache.seatunnel.connectors.seatunnel.jdbc.source.FixedChunkSplitter; +import org.apache.seatunnel.connectors.seatunnel.jdbc.source.JdbcSourceSplit; import org.apache.seatunnel.connectors.seatunnel.jdbc.source.JdbcSourceTable; +import org.apache.seatunnel.connectors.seatunnel.jdbc.source.StringRangeSplitDecision; +import org.apache.seatunnel.connectors.seatunnel.jdbc.utils.JdbcCatalogUtils; import org.apache.seatunnel.e2e.common.container.EngineType; import org.apache.seatunnel.e2e.common.container.TestContainer; @@ -46,6 +56,7 @@ import org.testcontainers.utility.MountableFile; import java.math.BigDecimal; import java.nio.charset.StandardCharsets; import java.sql.Date; +import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; import java.sql.Timestamp; @@ -54,9 +65,13 @@ import java.time.LocalDate; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; import java.util.HashMap; +import java.util.HashSet; import java.util.List; import java.util.Map; +import java.util.Set; import java.util.stream.Collectors; import java.util.stream.IntStream; @@ -85,6 +100,10 @@ public class JdbcOracleIT extends AbstractJdbcIT { "/jdbc_oracle_source_to_sink_use_select2.conf", "/jdbc_oracle_source_to_sink_use_select3.conf"); + private static final String STRING_RANGE_TABLE = "E2E_STRING_RANGE_SPLIT"; + private static final int STRING_RANGE_ROWS = 300; + private static final int STRING_RANGE_PARTITIONS = 4; + private static final String CREATE_SQL = "create table %s\n" + "(\n" @@ -177,6 +196,163 @@ public class JdbcOracleIT extends AbstractJdbcIT { dialect.sampleDataFromColumn(connection, table, "INTEGER_COL", 1, 1024); } + /** + * Runs Oracle String range splitting against a real database through the production table + * resolution path: a schema-qualified {@code table_path} is resolved by the Oracle catalog, + * validated against the real session, encoding and ALL_TAB_COLUMNS metadata, split by key + * range, and every split is read back through the reader-side session check. + * + * <p>It fails if validation looks up a different object than the split SQL reads (the + * schema-qualified path would then be rejected), if range boundaries drop or duplicate rows, or + * if a nullable split column is accepted by an explicit range strategy instead of being + * rejected, and AUTO stops falling back to a hash split that still reads every row. + */ + @Test + public void testStringRangeSplitReadsEverySchemaQualifiedRow() throws Exception { + String qualifiedTable = SCHEMA + "." + STRING_RANGE_TABLE; + try (Statement statement = connection.createStatement()) { + // ORDER_KEY is NOT NULL and therefore eligible for range splitting; NULLABLE_KEY holds + // the same values but is declared nullable, so only its metadata differs. + statement.execute( + "CREATE TABLE " + + qualifiedTable + + " (ORDER_KEY VARCHAR2(4) NOT NULL PRIMARY KEY," + + " NULLABLE_KEY VARCHAR2(4))"); + try { + Set<String> expectedKeys = new HashSet<>(); + try (PreparedStatement insert = + connection.prepareStatement( + "INSERT INTO " + + qualifiedTable + + " (ORDER_KEY, NULLABLE_KEY) VALUES (?, ?)")) { + for (int i = 0; i < STRING_RANGE_ROWS; i++) { + String key = String.format("K%03d", i); + expectedKeys.add(key); + insert.setString(1, key); + insert.setString(2, key); + insert.addBatch(); + } + insert.executeBatch(); + } + // The shared IT connection disables auto-commit; the splitter reads through its + // own connection and must see the inserted rows. + connection.commit(); + + // The real NOT NULL table must not validate a nullable query projection. + StringRangeSplitDecision queryDecision = + new OracleDialect() + .validateStringRangeSplit( + connection, + JdbcSourceTable.builder() + .tablePath(TablePath.of(SCHEMA, STRING_RANGE_TABLE)) + .query( + "SELECT NULL AS ORDER_KEY FROM " + + qualifiedTable) + .build(), + "ORDER_KEY", + 1); + Assertions.assertFalse(queryDecision.isSafe()); + Assertions.assertTrue(queryDecision.getReason().contains("without a custom query")); + + List<JdbcSourceSplit> rangeSplits = new ArrayList<>(); + Assertions.assertEquals( + expectedKeys, + readAllStringSplitKeys("range", qualifiedTable, "ORDER_KEY", rangeSplits)); + Assertions.assertTrue(rangeSplits.size() > 1, "expected several range splits"); + for (JdbcSourceSplit split : rangeSplits) { + Assertions.assertFalse(split.getSplitStart() instanceof Integer); + } + + JdbcConnectorException rejected = + Assertions.assertThrows( + JdbcConnectorException.class, + () -> + readAllStringSplitKeys( + "range", + qualifiedTable, + "NULLABLE_KEY", + new ArrayList<>())); + Assertions.assertTrue( + rejected.getMessage().contains("NULLABLE_KEY is nullable"), + rejected.getMessage()); + + List<JdbcSourceSplit> autoSplits = new ArrayList<>(); + Assertions.assertEquals( + expectedKeys, + readAllStringSplitKeys("auto", qualifiedTable, "NULLABLE_KEY", autoSplits)); + Assertions.assertEquals(STRING_RANGE_PARTITIONS, autoSplits.size()); + for (JdbcSourceSplit split : autoSplits) { + Assertions.assertTrue(split.getSplitStart() instanceof Integer); + } + } finally { + statement.execute("DROP TABLE " + qualifiedTable); + } + } + } + + /** + * Resolves {@code tablePath} through the Oracle catalog exactly as the Jdbc source does, then + * reads every generated split and returns the split column values. Each value must be read + * once; a duplicate means two splits overlap. + */ + private Set<String> readAllStringSplitKeys( + String strategy, + String tablePath, + String partitionColumn, + List<JdbcSourceSplit> generatedSplits) + throws Exception { + String jdbcUrl = jdbcCase.getJdbcUrl().replace(HOST, dbServer.getHost()); + JdbcSourceTableConfig tableConfig = + JdbcSourceTableConfig.builder() + .tablePath(tablePath) + .partitionColumn(partitionColumn) + .partitionNumber(STRING_RANGE_PARTITIONS) + .useSelectCount(false) + .skipAnalyze(true) + .useRegex(false) + .build(); + Map<TablePath, JdbcSourceTable> tables = + JdbcCatalogUtils.getTables( + JdbcConnectionConfig.builder() + .url(jdbcUrl) + .driverName(jdbcCase.getDriverClass()) + .username(jdbcCase.getUserName()) + .password(jdbcCase.getPassword()) + .build(), + Collections.singletonList(tableConfig), + MultiTableFailurePolicy.FAIL_FAST); + Assertions.assertEquals(1, tables.size()); + JdbcSourceTable sourceTable = tables.values().iterator().next(); + + Map<String, Object> configMap = new HashMap<>(); + configMap.put("url", jdbcUrl); + configMap.put("driver", jdbcCase.getDriverClass()); + configMap.put("username", jdbcCase.getUserName()); + configMap.put("password", jdbcCase.getPassword()); + configMap.put("table_path", tablePath); + configMap.put("partition_column", partitionColumn); + configMap.put("split.string-strategy", strategy); + + Set<String> keys = new HashSet<>(); + try (FixedChunkSplitter splitter = + new FixedChunkSplitter(JdbcSourceConfig.of(ReadonlyConfig.fromMap(configMap)))) { + Collection<JdbcSourceSplit> splits = splitter.generateSplits(sourceTable); + generatedSplits.addAll(splits); + for (JdbcSourceSplit split : splits) { + try (PreparedStatement splitStatement = + splitter.generateSplitStatement( + split, sourceTable.getCatalogTable().getTableSchema()); + ResultSet resultSet = splitStatement.executeQuery()) { + while (resultSet.next()) { + String key = resultSet.getString(partitionColumn); + Assertions.assertTrue(keys.add(key), "duplicated split key: " + key); + } + } + } + } + return keys; + } + /** * Disabled on Spark: TIMESTAMP WITH LOCAL TIME ZONE is now mapped to TIMESTAMP_TZ * (OffsetDateTime). Spark encodes TIMESTAMP_TZ as DecimalType(18, 5) internally, causing
