You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@seatunnel.apache.org by "zhangshenghang (via GitHub)" <gi...@apache.org> on 2026/02/13 02:37:03 UTC
[PR] [Fix][Connector-v2][JDBC] Enhance WHERE condition handling in SQL queries [seatunnel]
zhangshenghang opened a new pull request, #10488:
URL: https://github.com/apache/seatunnel/pull/10488
<!--
Thank you for contributing to SeaTunnel! Please make sure that your code changes
are covered with tests. And in case of new features or big changes
remember to adjust the documentation.
Feel free to ping committers for the review!
## Contribution Checklist
- Make sure that the pull request corresponds to a [GITHUB issue](https://github.com/apache/seatunnel/issues).
- Name the pull request in the form "[Feature] [component] Title of the pull request", where *Feature* can be replaced by `Hotfix`, `Bug`, etc.
- Minor fixes should be named following this pattern: `[hotfix] [docs] Fix typo in README.md doc`.
-->
### Purpose of this pull request
<!-- Describe the purpose of this pull request. For example: This pull request adds checkstyle plugin.-->
### Does this PR introduce _any_ user-facing change?
<!--
Note that it means *any* user-facing change including all aspects such as the documentation fix.
If yes, please clarify the previous behavior and the change this PR proposes - provide the console output, description and/or an example to show the behavior difference if possible.
If possible, please also clarify if this is a user-facing change compared to the released SeaTunnel versions or within the unreleased branches such as dev.
If no, write 'No'.
If you are adding/modifying connector documents, please follow our new specifications: https://github.com/apache/seatunnel/issues/4544.
-->
### How was this patch tested?
<!--
If tests were added, say they were added here. Please make sure to add some test cases that check the changes thoroughly including negative and positive cases if possible.
If it was tested in a way different from regular unit tests, please clarify how you tested step by step, ideally copy and paste-able, so that other reviewers can test and check, and descendants can verify in the future.
If tests were not added, please describe why they were not added and/or why it was difficult to add.
If you are adding E2E test cases, maybe refer to https://github.com/apache/seatunnel/blob/dev/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-cdc-mysql-e2e/src/test/resources/mysqlcdc_to_mysql.conf, here is a good example.
-->
### Check list
* [ ] If any new Jar binary package adding in your PR, please add License Notice according
[New License Guide](https://github.com/apache/seatunnel/blob/dev/docs/en/contribution/new-license.md)
* [ ] If necessary, please update the documentation to describe the new feature. https://github.com/apache/seatunnel/tree/dev/docs
* [ ] If necessary, please update `incompatible-changes.md` to describe the incompatibility caused by this PR.
* [ ] If you are contributing the connector code, please check that the following files are updated:
1. Update [plugin-mapping.properties](https://github.com/apache/seatunnel/blob/dev/plugin-mapping.properties) and add new connector information in it
2. Update the pom file of [seatunnel-dist](https://github.com/apache/seatunnel/blob/dev/seatunnel-dist/pom.xml)
3. Add ci label in [label-scope-conf](https://github.com/apache/seatunnel/blob/dev/.github/workflows/labeler/label-scope-conf.yml)
4. Add e2e testcase in [seatunnel-e2e](https://github.com/apache/seatunnel/tree/dev/seatunnel-e2e/seatunnel-connector-v2-e2e/)
5. Update connector [plugin_config](https://github.com/apache/seatunnel/blob/dev/config/plugin_config)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@seatunnel.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [Fix][Connector-v2][JDBC] Enhance WHERE condition handling in SQL queries [seatunnel]
Posted by "corgy-w (via GitHub)" <gi...@apache.org>.
corgy-w merged PR #10488:
URL: https://github.com/apache/seatunnel/pull/10488
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@seatunnel.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [Fix][Connector-v2][JDBC] Enhance WHERE condition handling in SQL queries [seatunnel]
Posted by "DanielCarter-stack (via GitHub)" <gi...@apache.org>.
DanielCarter-stack commented on PR #10488:
URL: https://github.com/apache/seatunnel/pull/10488#issuecomment-3895112022
<!-- code-pr-reviewer -->
<!-- cpr:pr_reply_v2_parts {"group": "apache/seatunnel#10488", "part": 1, "total": 1} -->
### Issue 1: Code Duplication - DynamicChunkSplitter and FixedChunkSplitter
**Location**:
- `DynamicChunkSplitter.java:676-682`
- `FixedChunkSplitter.java:228-240`
**Issue**:
Both subclasses use identical logic when `table.getQuery()` is empty and `whereConditionClause` is not empty:
```java
if (StringUtils.isNotBlank(config.getWhereConditionClause())) {
String userQuery = String.format(
"SELECT * FROM %s", jdbcDialect.tableIdentifier(split.getTablePath()));
splitQuery = String.format("SELECT * FROM (%s) tmp", applyUserWhereCondition(userQuery));
} else {
splitQuery = String.format(
"SELECT * FROM %s", jdbcDialect.tableIdentifier(split.getTablePath()));
}
```
**Potential Risks**:
- High maintenance cost: future changes require synchronization in two places
- Easy to miss: may lead to inconsistent behavior
**Impact Scope**:
- Direct impact: `DynamicChunkSplitter`, `FixedChunkSplitter`
- Indirect impact: all users using JDBC Connector with `where_condition` configured but `query` not configured
- Affected area: single Connector (JDBC)
**Severity**: **MINOR**
**Improvement Suggestions**:
Add a common method in the `ChunkSplitter` base class:
```java
// ChunkSplitter.java
protected String buildSimpleQueryWithWhere(TablePath tablePath) {
String baseQuery = String.format(
"SELECT * FROM %s", jdbcDialect.tableIdentifier(tablePath));
return applyUserWhereCondition(baseQuery);
}
```
Simplify subclasses to:
```java
// DynamicChunkSplitter.java & FixedChunkSplitter.java
} else {
splitQuery = buildSimpleQueryWithWhere(split.getTablePath());
splitQuery = String.format("SELECT * FROM (%s) tmp", splitQuery);
}
```
---
### Issue 2: Insufficient Exception Handling - Users Unaware When Field Extraction Fails
**Location**: `SqlWhereConditionHelper.java:115-135`
**Issue**:
When WHERE conditions cannot be parsed (e.g., containing unsupported syntax), the method silently returns an empty collection, and users cannot perceive the problem.
**Potential Risks**:
- Risk 1: Users configure incorrect WHERE conditions, system fails silently, leading to query results that don't meet expectations
- Risk 2: Difficult to troubleshoot in production environments due to lack of error logs
**Impact Scope**:
- Direct impact: all configurations using the `where_condition` parameter
- Indirect impact: may cause data loss or return incorrect data
- Affected area: single Connector (JDBC)
**Severity**: **MAJOR**
**Improvement Suggestions**:
See the code example in the "Error Handling" section above, add:
1. try-catch to wrap parsing logic
2. Output WARN log when parsing fails
3. Return safe value (empty collection or original SQL)
---
### Issue 3: hasTopLevelSelectWildcard Method Too Long and Complex
**Location**: `SqlWhereConditionHelper.java:235-301`
**Issue**:
The method is 68 lines long and contains multi-level nested logic:
- String cleaning
- SELECT finding
- FROM finding
- DISTINCT/ALL handling
- Column splitting
- Wildcard checking
**Potential Risks**:
- Risk 1: Difficult to understand and maintain
- Risk 2: Increases bug risk (e.g., boundary condition handling)
**Impact Scope**:
- Direct impact: code readability and maintainability
- Indirect impact: new bugs may be introduced during future modifications
- Affected area: single Connector (JDBC)
**Severity**: **MINOR**
**Improvement Suggestions**:
Split into 3 private methods:
```java
private static boolean hasTopLevelSelectWildcard(String sql) {
String cleaned = sql.replaceAll("'[^']*'|\"[^\"]*\"", "");
String columnList = extractSelectColumnList(cleaned);
return containsWildcardInColumns(columnList);
}
private static String extractSelectColumnList(String sql) { /* ... */ }
private static List<String> splitColumnList(String columnList) { /* ... */ }
private static boolean containsWildcardInColumns(List<String> columns) { /* ... */ }
```
---
### Issue 4: Lack of Support Validation for Chinese/Multi-byte Field Names
**Location**: `SqlWhereConditionHelper.java:39-43`
**Issue**:
`FIELD_PATTERN` regular expression:
```java
Pattern.compile(
"([a-zA-Z_][a-zA-Z0-9_]*|`[^`]+`|\"[^\"]+\"|\\[[^\\]]+\\])\\s*"
+ "(?:=|!=|<>|<|>|<=|>=|\\s+IN\\s|\\s+BETWEEN\\s|\\s+LIKE\\s|\\s+IS\\s)",
Pattern.CASE_INSENSITIVE)
```
Only matches ASCII field names. For databases that allow Chinese, Japanese field names (e.g., MySQL's utf8mb4 character set), extraction may not be possible.
**Potential Risks**:
- Risk 1: Chinese WHERE condition fields cannot be automatically added
- Risk 2: Leads to SQL execution failure (field does not exist)
**Impact Scope**:
- Direct impact: databases using non-English field names (Chinese, Japanese, Korean, etc.)
- Indirect impact: SQL execution failure, job failure
- Affected area: single Connector (JDBC)
**Severity**: **MAJOR**
**Improvement Suggestions**:
Extend regular expression to support Unicode letters:
```java
private static final Pattern FIELD_PATTERN =
Pattern.compile(
"([\\p{L}_][\\p{L}\\p{N}_]*|`[^`]+`|\"[^\"]+\"|\\[[^\\]]+\\])\\s*"
+ "(?:=|!=|<>|<|>|<=|>=|\\s+IN\\s|\\s+BETWEEN\\s|\\s+LIKE\\s|\\s+IS\\s)",
Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CHARACTER_CLASS);
```
- `\p{L}` matches letters in any language
- `\p{N}` matches numbers in any language
---
### Issue 5: Missing Test Coverage - Edge Cases and Performance Testing
**Location**: `SqlWhereConditionHelperTest.java`
**Issue**:
Test cases mainly cover normal scenarios, lacking:
1. Edge cases:
- Extra-long WHERE conditions (> 10KB)
- Deeply nested subqueries (> 5 levels)
- Large number of fields (100+ columns)
2. Performance testing:
- Parsing performance benchmarks
- Memory usage tests
3. Database dialects:
- Oracle-specific syntax (e.g., `:param` bind variables)
- MySQL-specific syntax (e.g., `@variable`)
- PostgreSQL-specific syntax (e.g., `::type` cast)
**Potential Risks**:
- Risk 1: Unpredictable behavior in production environments under extreme conditions
- Risk 2: Performance degradation cannot be detected in time
**Impact Scope**:
- Direct impact: test coverage
- Indirect impact: production environment stability
- Affected area: single Connector (JDBC)
**Severity**: **MINOR**
**Improvement Suggestions**:
Add test cases:
```java
@Test
public void testExtractFieldNamesFromWhere_VeryLongCondition() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 1000; i++) {
sb.append("field").append(i).append(" = ").append(i).append(" AND ");
}
sb.append("last_field = 1");
long start = System.currentTimeMillis();
Set<String> fields = SqlWhereConditionHelper.extractFieldNamesFromWhere(sb.toString());
long duration = System.currentTimeMillis() - start;
Assertions.assertEquals(1001, fields.size());
Assertions.assertTrue(duration < 100, "Parsing should complete in < 100ms, took: " + duration);
}
@Test
public void testExtractFieldNamesFromWhere_ChineseFieldName() {
String whereCondition = "WHERE 姓名 = '张三' AND 年龄 > 18";
Set<String> fields = SqlWhereConditionHelper.extractFieldNamesFromWhere(whereCondition);
Assertions.assertTrue(fields.contains("姓名"));
Assertions.assertTrue(fields.contains("年龄"));
}
```
---
### Issue 6: Missing Documentation - User Documentation and Migration Guide Not Updated
**Location**: project root directory `docs/en/connectors/source/Jdbc.md`
**Issue**:
The PR modifies user-visible behavior (automatically adding fields to SELECT), but has not updated:
1. User documentation: explaining how `where_condition` works
2. Migration guide: considerations when upgrading from older versions
3. Known limitations: restrictions on UNION/INTERSECT/EXCEPT queries
**Potential Risks**:
- Risk 1: Users confused by behavior changes
- Risk 2: Unexpected errors during upgrades
**Impact Scope**:
- Direct impact: documentation completeness
- Indirect impact: user experience
- Affected area: single Connector (JDBC)
**Severity**: **MINOR**
**Improvement Suggestions**:
Add in `docs/en/connectors/source/Jdbc.md`:
```markdown
### where_condition
The user-defined WHERE condition. The connector will automatically add fields referenced
in the WHERE condition to the SELECT clause if they are not present.
**Example**:
```yaml
source:
Jdbc:
query: "SELECT id, name FROM users"
where_condition: "WHERE partition_date = '2023-01-01'"
```
The generated SQL will be:
```sql
SELECT * FROM (SELECT id, name, partition_date FROM users) tmp WHERE partition_date = '2023-01-01'
```
**Limitations**:
- For UNION/INTERSECT/EXCEPT queries, fields will NOT be auto-added to avoid column mismatch.
- Please manually include all required fields in each SELECT branch.
```
---
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@seatunnel.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [Fix][Connector-v2][JDBC] Enhance WHERE condition handling in SQL queries [seatunnel]
Posted by "zhangshenghang (via GitHub)" <gi...@apache.org>.
zhangshenghang commented on PR #10488:
URL: https://github.com/apache/seatunnel/pull/10488#issuecomment-3894509898
<!-- code-pr-reviewer -->
<!-- cpr:pr_reply_v2_parts {"group": "apache/seatunnel#10488", "part": 1, "total": 1} -->
## 1) PR 基本信息(事实)
- **PR 标题**:`[Fix][Connector-v2][JDBC] Enhance WHERE condition handling in SQL queries`(置信度:高)
- **模块**:`Connector-V2 / JDBC Source`(置信度:高)
- **类型**:Bug Fix(围绕 `where_condition` SQL 组装逻辑)(置信度:高)
- **变更文件**:5 个(`ChunkSplitter`、`DynamicChunkSplitter`、`FixedChunkSplitter`、新增 `SqlWhereConditionHelper`、新增其测试)(置信度:高)
- **Issue 链接**:PR 描述中未提供(置信度:高)
- **测试执行情况**:未执行构建/测试(按你的只读约束)(置信度:高)
---
## 2) 问题定义(通俗解释)
### 原始问题(推断+代码佐证)
- 旧实现在 `ChunkSplitter.createPreparedStatement` 里统一外包一层 `SELECT * FROM (...) tmp where_condition`。
- 当用户自定义 `query` 只选了部分列,而 `where_condition` 使用了未投影列时,外层 `WHERE` 会引用不到列,导致 SQL 失败。
(置信度:高,旧代码在 `dev` 分支可见)
### 场景示例
- 用户配置:
- `query = "SELECT id, name FROM orders"`
- `where_condition = "where partition_date = '2026-02-01'"`
- 旧逻辑会生成外层过滤,`partition_date` 不在内层输出列里,数据库会报列不存在。
(置信度:高)
### 影响范围
- 主要影响 JDBC Source 中使用 `where_condition + 自定义 query` 的用户。
(置信度:高)
---
## 3) 调用链(含修改点)
```mermaid
graph TD
A[SeaTunnel Job] --> B[JdbcSourceSplitEnumerator.run]
B --> C[ChunkSplitter.generateSplits]
C --> D[DynamicChunkSplitter / FixedChunkSplitter]
A --> E[JdbcSourceReader -> JdbcInputFormat.open]
E --> F[ChunkSplitter.generateSplitStatement]
F --> G[ChunkSplitter.applyUserWhereCondition]
G --> H[SqlWhereConditionHelper.applyWhereConditionWithWrap]
H --> I[ChunkSplitter.createPreparedStatement]
I --> J[JDBC executeQuery]
style H fill:#f9f,stroke:#333,stroke-width:3px
```
---
## 4) 核心审查结论
### 已确认的正向点(事实)
1. `where_condition` 的拼接不再在 `createPreparedStatement` 全局硬拼,而是前移到 split SQL 生成阶段,调用链更可控(置信度:高)。
2. 新增 `SqlWhereConditionHelperTest`,覆盖了很多字符串场景(置信度:高)。
3. 无新增第三方依赖;配置项和 SPI 接口未改(置信度:高)。
---
## 问题 1:缺列检测扫描了**整条 SQL**,会漏判“SELECT 未投影但在 WHERE/ON/字符串里出现”的列(阻塞)
**位置**:`SqlWhereConditionHelper.java:154`、`106-123`
```java
List<String> missingFields = findMissingFields(sql, requiredFields);
...
Matcher matcher = pattern.matcher(sql);
```
相关上下文:
- 调用入口:`ChunkSplitter.java:150-154`
- 调用方1:`DynamicChunkSplitter.java:674,682`
- 调用方2:`FixedChunkSplitter.java:222,236,309,321`
**问题描述(事实+推断)**:
- 方法目标是“确保字段在 SELECT 子句里”,但实际用整条 SQL 做存在性判断。
- 如果列仅出现在内层 `WHERE/JOIN/ORDER BY`,会被误判为“已存在”,从而不补到 SELECT 列表。
- 外层再套 `WHERE` 时仍可能找不到该列,原 bug 在这类场景仍可复现。
(置信度:高)
**潜在风险**:
- 风险1:`where_condition` 仍可能触发运行时 SQL 列不存在异常。
- 风险2:字符串字面量命中字段名时也会误判“已存在”。
(置信度:高)
**影响范围**:
- 直接影响:`SqlWhereConditionHelper.applyWhereConditionWithWrap`
- 间接影响:Dynamic/Fixed/Single split 的 SQL 生成链路
- 影响面:JDBC Connector(单 Connector)
(置信度:高)
**严重程度**:高
**改进建议**:
```java
// ensureFieldsInSelect 内
String selectClause = (fromIndex != -1) ? sql.substring(0, fromIndex) : sql;
List<String> missingFields = findMissingFields(selectClause, requiredFields);
```
并在 `findMissingFields` 前去除字符串字面量/注释后再匹配。
理由:目标是判断“是否在投影列中”,不是“是否在 SQL 任意位置出现”。
(置信度:高)
---
## 问题 2:去引号后直接回填列名,遇到保留字/特殊字符列会生成非法 SQL(阻塞)
**位置**:`SqlWhereConditionHelper.java:87-90, 163-166`
```java
field = field.replaceAll("^[`\"\\[]|[`\"\\]]$", "");
...
insertion.append(", ").append(field);
```
相关上下文:
- 调用入口:`ChunkSplitter.applyUserWhereCondition`
- 下游执行:`ChunkSplitter.createPreparedStatement`
**问题描述(事实+推断)**:
- 代码先去掉反引号/双引号/方括号,再把字段原样拼回 SQL。
- 若字段本来需要引用(如保留字 `order`、特殊字符 `order-id`),回填后 SQL 可能非法或语义错误。
(置信度:高)
**潜在风险**:
- 风险1:SQL 语法错误(生产直接失败)。
- 风险2:跨方言兼容性下降(不同数据库标识符规则不同)。
(置信度:高)
**影响范围**:
- 直接影响:`extractFieldNamesFromWhere` + `ensureFieldsInSelect`
- 间接影响:所有启用 `where_condition` 的 JDBC Source 读链路
- 影响面:JDBC Connector
(置信度:高)
**严重程度**:高
**改进建议**:
- 保留“原始带引号 token”用于回填;
- 或在 helper 接收 dialect/quote 策略,统一 `quoteIdentifier` 后插入;
- 同时新增包含保留字、`-`、空格列名的单元测试。
理由:当前实现破坏了用户显式给出的标识符引用语义。
(置信度:高)
---
## 问题 3:测试主要是字符串 contains,缺少关键集成场景断言(非阻塞但建议补)
**位置**:`SqlWhereConditionHelperTest.java`(整体)
**问题描述(事实)**:
- 现有测试大量使用 `contains("SELECT * FROM (")` 这类弱断言。
- 未覆盖“字段出现在原 SQL 的 WHERE/ON,但不在 SELECT 投影”这一关键失败场景。
- 也未覆盖“保留字/特殊字符列名回填后 SQL 合法性”场景。
(置信度:高)
**严重程度**:中
**建议补充**:
1. `SELECT id FROM t WHERE partition_date > ...` + `where_condition` 引用 `partition_date`
2. `where_condition` 使用 `` `order-id` `` / `"order"` / `[order]`
3. Dynamic/Fixed splitter 端到端 SQL 断言(不仅 helper)
(置信度:高)
---
## 5) 兼容性与架构评估(简要)
- **API/SPI**:未破坏公开接口;`Option` 未变更(置信度:高)
- **调用方完整性**:`createPreparedStatement` 的 4 个现有调用点已迁移到前置拼接(置信度:高)
- **性能**:新增正则解析与 SQL 字符串处理,单次开销小;但 `log.warn` 可能在多 split 下刷屏(置信度:中)
- **Checkpoint/Exactly-once/Schema 机制**:未见直接改动(置信度:中高)
---
## 最终结论
**当前不建议直接 merge。**
原因:存在 2 个高严重度逻辑缺陷(问题 1、2),会导致部分真实场景下 SQL 仍失败或新失败。建议先修复并补充针对性测试后再合并。
(结论置信度:高)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@seatunnel.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org