Repository navigation
Conversation
DanielLeens
left a comment
There was a problem hiding this comment.
What Problem Does This PR Solve?
- User pain point: multi-table JDBC sink jobs (e.g. MySQL-CDC -> JDBC with
generate_sink_sql = true) currently have only one globalprimary_keysoption, so there is no way to give different tables different key columns (or mix${primary_key}/${unique_key}with a shared static column such asDATA_SOURCE) in a single sharding/merge job. - Fix approach: adds a new
multi-table_config.primary_keysoption toJdbcSinkFactorythat maps a table-name regex to a key-column list (with${primary_key}/${unique_key}expansion), taking precedence over the existingprimary_keys/ catalog-metadata fallback. Along the way, it also fixes a real config-reconstruction bug:ConfigFactory.parseMap(...)treats every map key as a HOCON path expression, so a regex key such as^t_nova_.*$(which contains.and$) throwsConfigException$BadPath. The PR replacesConfigFactory.parseMap(...)with a Jackson JSON round-trip in two places:ReadonlyConfig#toConfig()andConfigShadeUtils#processConfig. - One-sentence summary: a well-motivated, mostly well-tested JDBC feature, but it ships a semantics change to a widely-shared config-reconstruction API (
ReadonlyConfig#toConfig()) whose blast radius goes far beyond the JDBC connector, and it introduces some avoidable code duplication inJdbcSinkFactory.
1. Code Change Review
1.1 Core Logic Analysis
Runtime path — is the config-parsing bug real, and is the fix on the necessary path?
I traced the actual failure path instead of taking the PR description at face value:
ConfigShadeUtils.processConfig(seatunnel-core/seatunnel-core-starter/.../ConfigShadeUtils.java:161-215) runs unconditionally for every job at submission time (it is the sensitive-field encrypt/decrypt step, invoked regardless of connector type). Before the fix it ended withConfigFactory.parseMap(configMap), whereconfigMapalready came fromJsonUtils.toMap(JsonUtils.parseObject(...))— i.e. it is itself the result of a JSON parse. Reconstructing that same, already-JSON-safe map viaparseMapis exactly where a job containing amulti-table_config.primary_keysblock with regex keys would blow up withConfigException$BadPath, before the JDBC connector ever runs. So this half of the fix is real, necessary, and — becauseconfigMap's values are guaranteed JSON-serializable already — low risk:JsonUtils.toJsonString(configMap)followed byConfigFactory.parseString(json, JSON)is a lossless, purely textual re-encoding of data that was already JSON. Good, surgical fix.ReadonlyConfig#fromConfig(Config)(seatunnel-api/.../ReadonlyConfig.java:56-65) was already implemented via a JSON render + Jackson read (unchanged by this PR), so per-tableReadonlyConfigobjects built from the post-decryptConfigalready preserve the regex keys correctly.JdbcSinkFactory.resolveMultiTablePrimaryKeys()readsMULTI_TABLE_CONFIGdirectly off thisReadonlyConfigviaconfig.get(Option)(a plain map lookup, nottoConfig()), so the actual feature path does not appear to require theReadonlyConfig#toConfig()change at all.
Finding — Issue 1: The ReadonlyConfig#toConfig() change (seatunnel-api/.../ReadonlyConfig.java:78-86) swaps ConfigFactory.parseMap(confData) for a Jackson JSON round-trip. This method is @Deprecated but still very actively used — I counted ~20 call sites outside this PR's diff, including the connector prepare() fallback path in FactoryUtil.java:127 and :235 (source.prepare(options.toConfig()) / sink.prepare(config.toConfig()), used by every legacy/fallback SeaTunnelSource/SeaTunnelSink), plus MultiTableFailureHelper, ConfigBuilder, MetalakeConfigUtils, and connector code in Hive, Clickhouse, HDFS, Neo4j, AmazonSQS, AmazonDynamoDB, OpenMLDB, HTTP, IoTDB, GraphQL, and JsonPathTransformConfig.
- The semantic difference that matters:
ConfigFactory.parseMap()treats every map key (at every nesting level) as a HOCON path expression and auto-expands dotted keys into nested structure (e.g.{"a.b": 1}becomes{a: {b: 1}}). The new JSON-basedtoConfig()keeps such keys literal/flat ({"a.b": 1}stays a single flat key). Any existing caller that (a) builds aMap/ReadonlyConfigwith a deliberately dotted key relying on that auto-expansion, and (b) later reads it back through.toConfig()with a dotted-path lookup (config.getString("a.b"),config.getConfig("a")...), would silently stop finding the value after this change — no exception, just a missing/empty config, which is worse than a loud failure. - I searched the repo for this pattern (property-bag-style options with dotted keys, e.g. Kafka-style
sasl.jaas.config, feeding into.toConfig()) and did not find a currently-broken caller — the connectors that do call.toConfig()(Hive, Clickhouse, HDFS, etc.) appear to use flat, non-dotted option keys. So I cannot point at a concrete regression today, but I also could not exhaustively audit ~20 call sites across unrelated connector modules within this review, and a silent, non-throwing behavior change on a@Deprecated-but-still-load-bearing shared API is exactly the kind of change that tends to surface as a hard-to-reproduce field bug months later. - Recommendation: since the actual JDBC feature does not appear to need this method changed (per the trace above), consider narrowing the fix to only
ConfigShadeUtils.processConfig(which is provably necessary and provably safe), and leavingReadonlyConfig#toConfig()untouched — or, if there is a concrete call path that does need it (please point it out if I missed one), add an explicit regression test that proves no other caller relies on the old dot-expansion behavior, and call that out in the PR description as an intentional, audited behavior change to a shared API. - Location:
seatunnel-api/src/main/java/org/apache/seatunnel/api/configuration/ReadonlyConfig.java:78-86.
JdbcSinkFactory changes
resolveMultiTablePrimaryKeys/matchesPattern/toPrimaryKeyList/expandPrimaryKeyPlaceholder/getPrimaryKeyColumns/getUniqueKeyColumns(JdbcSinkFactory.java:222-297) are straightforward and correct for the described semantics: full-match regex (tableName.matches(pattern)), first-match-wins by declaration order (relies onMapiteration order — traced back throughfromConfig's JacksonTypeReference<Map<String,Object>>read, which defaults toLinkedHashMapand therefore preserves declaration order; consistent with the documented "first pattern in declaration order wins"), and a clearJdbcConnectorExceptionwhen${primary_key}/${unique_key}is used but the upstream table has no such key.- I verified there is no double-processing conflict with the existing generic placeholder framework:
TablePlaceholderProcessor.replaceTablePlaceholder(seatunnel-api/.../TablePlaceholderProcessor.java:161-206) only rewrites top-level config values that areStringor a single-elementStringList; a top-levelMapvalue (likemulti-table_config) falls through both branches untouched. So the framework's own${primary_key}substitution never touches values nested insidemulti-table_config.primary_keys, andexpandPrimaryKeyPlaceholderis the sole, correct place that expands those placeholders. Good — this interaction is easy to get wrong and it was handled correctly (whether by design or by a fortunate structural side effect). - Finding — Issue 2 (code duplication): the pre-existing primary-key-resolution logic (catalog PK -> first unique key -> plain INSERT) is now duplicated verbatim into the
elsebranch of the newif (multiTablePrimaryKeys.isPresent())(JdbcSinkFactory.java:159-201is essentially a copy of the pre-PR block). This is ~35 lines of copy-pasted logic instead of extracting the pre-existing block into a private helper and calling it from theelsebranch. It works, but it is an avoidable maintainability regression — a future bug fix to the fallback-resolution logic now has two places to be applied.- Location:
seatunnel-connectors-v2/connector-jdbc/.../sink/JdbcSinkFactory.java:118-201.
- Location:
1.2 Compatibility Impact
- Fully compatible for the new
multi-table_configoption itself: it is purely additive, optional, and only takes effect when a table name matches a configured pattern; unmatched tables fall back to the pre-existingprimary_keys/ catalog-metadata logic unchanged. No existing option is renamed, removed, or has its default changed. - Partially incompatible / needs verification: the
ReadonlyConfig#toConfig()semantics change described in Issue 1 above is a behavior change to a shared, widely-used API with a real (if currently unproven in-repo) potential to silently drop dotted-key config values for callers outside the JDBC connector. This should be either scoped down or explicitly verified/documented before merge. ConfigShadeUtils.processConfig's change is safe/compatible as analyzed above (input is already JSON-normalized).
1.3 Performance / Side-Effect Analysis
- All changed code runs once per job/sink-instantiation at submission time (
createSink(), config decrypt/encrypt), not in the per-record hot path. The extra Jackson serialize+parse round-trip intoConfig()/processConfigis negligible relative to job-submission overhead. - No new threads, connections, or unbounded collections are introduced.
resolveMultiTablePrimaryKeysiterates a small, user-configured map once per table.
1.4 Error Handling and Logging
| Issue | Location | Problem | Risk | Fix | Severity | Raised by another reviewer |
|---|---|---|---|---|---|---|
| 1 | seatunnel-api/.../ReadonlyConfig.java:78-86 |
toConfig() (a @Deprecated but heavily used shared API, ~20 call sites outside this diff) changes Map->Config reconstruction from ConfigFactory.parseMap (which auto-expands dotted keys into nested paths) to a literal JSON round-trip. No test proves other callers don't rely on the old dot-expansion behavior; a broken caller would fail silently (missing config value, not an exception). |
Medium — no concrete broken caller found in-repo during this review, but the audit wasn't exhaustive across ~20 unrelated call sites/connectors, and the failure mode is silent | Scope the fix to only ConfigShadeUtils.processConfig (provably necessary and safe) and leave toConfig() untouched, since the traced feature path doesn't appear to need it; or add explicit regression coverage + call this out as an intentional audited change in the PR description |
Medium | No |
| 2 | seatunnel-connectors-v2/.../JdbcSinkFactory.java:118-201 |
Pre-existing PK-fallback-resolution logic duplicated verbatim into the new else branch instead of extracted into a shared private method |
Low — maintainability only, not a correctness bug | Extract the pre-existing block (lines ~159-201) into a private method and call it from both branches | Medium | No |
Error messages themselves (INVALID_MULTI_TABLE_CONFIG, "table X matched pattern Y ... but the upstream table has no primary key") are clear, include table/pattern context, and don't leak sensitive data — good.
2. Code Quality Assessment
2.1 Coding Standards
- New public/package-visible method
resolveMultiTablePrimaryKeysand the new private helpers (matchesPattern,toPrimaryKeyList,expandPrimaryKeyPlaceholder,getPrimaryKeyColumns,getUniqueKeyColumns) have no Javadoc explaining the matching semantics (full-match regex, first-match-wins) or the placeholder-expansion contract. Given this logic implements a non-trivial, user-facing precedence rule, a short Javadoc onresolveMultiTablePrimaryKeys(at minimum) would help future maintainers avoid re-deriving the semantics from the docs. Medium severity per project convention (non-trivial new methods should have doc comments), non-blocking. - The new
MULTI_TABLE_CONFIGOption(JdbcSinkOptions.java:112-121) does have a description — good. - Naming and style otherwise follow existing conventions in the file (Google/AOSP format via Spotless, no wildcard imports).
2.2 Test Coverage and Test Stability
- New unit tests:
JdbcSinkFactoryTest(mapped hit, unmatched/fallback, missing-PK error, first-match-wins, string-value parsing, full factory-context path),ConfigShadeTest#testDecryptPreservesSpecialCharacterKeys,ReadableConfigTest#testToConfigPreservesSpecialCharacterKeys. These directly exercise the claimed bug (regex keys with./$) and the claimed fix, and cover the main success/fallback/error paths reasonably well. - Stability rating: Stable. All new tests are pure, deterministic unit tests — no sleeps, no timing assumptions, no external I/O, no shared mutable static state, no thread races. I did not find any flaky-test anti-patterns (no
Thread.sleep, no wall-clock assertions, no unordered-collection assertions without normalization). - Gap: there is no test proving
ReadonlyConfig#toConfig()'s new behavior is compatible with a dotted-key map for a caller outside the JDBC path (see Issue 1) — the two new tests fortoConfig()/processConfigonly test the "regex key is preserved" happy path, not "does anything that relied on the old path-expansion still work."
2.3 Documentation Updates
docs/en/connectors/sink/Jdbc.mdanddocs/zh/connectors/sink/Jdbc.mdare both updated with a matching newmulti-table_configsection (table row + full example), and bothdocs/en/docs/zhsink-options-placeholders.mdare updated to mention the mixed static/placeholder support insidemulti-table_config. English and Chinese docs are consistent with each other and with the code (option keymulti-table_config, sub-keyprimary_keys, placeholder syntax). Good, this satisfies the project's docs/en + docs/zh requirement.- Minor nit (non-blocking): the docs describe the option as being for "multi-table generated-SQL jobs," but the implementation applies unconditionally to any
createSink()call regardless ofgenerate_sink_sql/single-vs-multi-table — a single-table job whose table name happens to match a configured pattern would also have its primary key overridden. This is very likely intended (the underlying PK resolution logic is shared for both scenarios), but the docs could be slightly clearer that the matching applies to the sink's resolved table name in general, not only in an explicit "multi-table" topology.
3. Architectural Soundness
3.1 Elegance of the Solution
The regex-to-key-list mapping design itself (declaration-order first-match, placeholder expansion scoped to this option only) is a precise, well-scoped solution to the stated problem, and the interaction with the existing generic placeholder framework was checked and is safe (see 1.1). The underlying config-parsing bug fix, however, is applied at a broader scope than the traced necessary path requires (see Issue 1) — a more surgical fix (scoped to ConfigShadeUtils only, or to a JDBC-local helper) would be more consistent with a minimal-blast-radius change to a 3-year production system.
3.2 Maintainability
Mostly good, aside from the code duplication noted in Issue 2.
3.3 Extensibility
The multi-table_config option shape ({ primary_keys: { "<regex>": [...] } }) leaves room for adding sibling keys under multi-table_config in the future (e.g. per-table field mappings) without another breaking change, since it's read as a generic Map<String,Object>.
3.4 Historical-Version Compatibility
No existing option is renamed/removed, and the new option is opt-in with a fallback to the exact pre-existing logic when unmatched/absent. The one open question is the ReadonlyConfig#toConfig() semantics change (Issue 1), which is not a config-option compatibility break but is a shared-API behavior change that could affect historical jobs relying on the old dot-expansion quirk, if any exist.
4. Issue Summary
| Number | Issue | Location | Severity |
|---|---|---|---|
| 1 | ReadonlyConfig#toConfig() semantics changed (dotted-key auto-expansion removed) for a shared API used by ~20 call sites outside this PR's scope; feature's own path doesn't appear to need this change |
seatunnel-api/src/main/java/org/apache/seatunnel/api/configuration/ReadonlyConfig.java:78-86 |
Medium |
| 2 | Pre-existing PK-fallback logic duplicated instead of extracted into a shared helper | seatunnel-connectors-v2/connector-jdbc/.../sink/JdbcSinkFactory.java:118-201 |
Medium |
| 3 | New non-trivial methods (resolveMultiTablePrimaryKeys and helpers) lack Javadoc |
seatunnel-connectors-v2/connector-jdbc/.../sink/JdbcSinkFactory.java:222-297 |
Low |
5. Merge Recommendation
Conclusion: Ready to merge after fixes
- Blockers — must be fixed
- None that I would call a hard functional blocker today — I could not find a concrete, currently-broken caller of
ReadonlyConfig#toConfig()in this repo. However, given this is a 3-year production system and the change is a silent (non-throwing) behavior change to a widely shared, actively-used API, I'd strongly encourage narrowing Issue 1's fix to only the provably-necessaryConfigShadeUtils.processConfigpath before merge, or getting explicit maintainer sign-off that the broadertoConfig()change has been audited.
- None that I would call a hard functional blocker today — I could not find a concrete, currently-broken caller of
- Recommended fixes — non-blocking
- Extract the duplicated PK-fallback-resolution block into a shared private method (Issue 2).
- Add short Javadoc to
resolveMultiTablePrimaryKeysand its helpers describing the matching/placeholder semantics (Issue 3). - Optional doc clarification that the mapping applies to any
createSink()call whose resolved table name matches, not only strictly "multi-table" topologies.
Overall this is a solid first contribution: the core feature logic is correct and well-tested, the interaction with the existing placeholder-replacement framework was checked and doesn't conflict, and both English and Chinese docs were updated consistently. The main thing I'd want a maintainer with full-repo context to weigh in on is whether widening the ReadonlyConfig#toConfig() fix (rather than keeping it scoped to ConfigShadeUtils, which is where the actual necessary fix lives) is an accepted tradeoff — I have read-only review rights here (Comment only), so a write-capable maintainer will need to make the final call on approval/merge regardless.
CI is currently still running (Build check in progress on the fork at the time of this review) — please make sure it's green before merge.
Welcome to the Apache SeaTunnel community — thanks for digging into a real, tricky config-parsing bug in addition to the feature itself, and for the thorough PR description with worked examples and generated SQL output. Looking forward to getting this in.
|
@DanielLeens Since this merge commit has already been pushed, I'd like to ask for your preferred way to fix this: Safe way (Revert): I can run git revert -m 1 [hash] and push normally. This will add a revert commit to cancel the upstream changes and pass the CI, but it leaves a revert commit in history. Clean way (Rebase): I can drop that merge commit via interactive rebase and force push, but it will rewrite the remote history. I'm leaning towards option 1 to avoid force-push issues. Please let me know your preference. Sorry for the noise! |
|
@luozihen thanks for flagging this proactively instead of just leaving CI red — that's exactly the right instinct, and this kind of accidental merge-into-feature-branch mistake is extremely common, so no need to apologize for the noise! My preference here is actually option 2 (rebase), not option 1 (revert) — and I'd suggest an even simpler variant than a manual interactive rebase: git fetch origin dev
git rebase origin/dev
# resolve any real conflicts if your own commits touch lines dev has since changed
git push --force-with-leaseA plain (non-interactive) Why rebase over revert in this specific case:
Go ahead with the rebase + force-push, and ping me once CI is green again — I'll take another look. Thanks again for the careful contribution and for keeping the PR history clean, that's a great habit to build early! |
|
Hi @luozihen — thanks for flagging this, but good news: you don't actually need to revert or rebase to fix CI here. I traced the failure before answering, and the merge commit isn't the cause. The real failure is a genuine, 100% reproducible bug in the new unit test added by this PR itself:
Root cause is a HOCON syntax bug in the literal string passed to "sink { Jdbc { url = \"jdbc:mysql://localhost:3306/db\" "
+ "username = \"u\" password = \"p\" "
+ "multi-table_config { ... } } }"In HOCON, sibling key-value pairs on the same line need a comma (or a newline) between them. Since Fix: add commas (or put each field on its own line) between "sink { Jdbc { url = \"jdbc:mysql://localhost:3306/db\", "
+ "username = \"u\", password = \"p\", "
+ "multi-table_config { ... } } }"Separately, the other failure in this run ( On the git-history question: this repo squash-merges PRs at merge time, so the intermediate commit history (merge commit included) won't carry into the final merged commit either way — you don't need to revert or force-push-rebase purely for CI's sake. If you'd still like a tidier branch, |
|
@luozihen Thanks for flagging this, and no worries about the noise. Before answering the revert-vs-rebase question I dug into the actual CI failure, because fixing the merge commit alone will not fix CI here. The real root cause is not the upstream The failing job is The raw HOCON literal the test builds its input from is: "source { FakeSource { plugin_output = \"fake\" } }\n"
+ "sink { Jdbc { url = \"jdbc:mysql://localhost:3306/db\" "
+ "username = \"u\" password = \"p\" "
+ "multi-table_config { primary_keys { "
+ "\"^t_nova_.*$\" = [\"${primary_key}\", \"DATA_SOURCE\"] "
+ "\"^t_tyuen_txn_.*$\" = [\"id_txn_ctrl\", \"DATA_SOURCE\"] "
+ "} } } }"In HOCON, fields inside an object must be separated by a comma or a newline. Fix: add commas (or real newlines) between every field, e.g.: Config input =
ConfigFactory.parseString(
"source { FakeSource { plugin_output = \"fake\" } }\n"
+ "sink { Jdbc { url = \"jdbc:mysql://localhost:3306/db\", "
+ "username = \"u\", password = \"p\", "
+ "multi-table_config { primary_keys { "
+ "\"^t_nova_.*$\" = [\"${primary_key}\", \"DATA_SOURCE\"], "
+ "\"^t_tyuen_txn_.*$\" = [\"id_txn_ctrl\", \"DATA_SOURCE\"] "
+ "} } } }");(or switch to a Java text block / genuinely multi-line literal so real newlines do the separating for you — that tends to be less error-prone than tracking commas across a long chain of concatenated strings). On your actual question, once that test is fixed:
So: rebase onto the latest |
|
@DanielLeens |
DanielLeens
left a comment
There was a problem hiding this comment.
Hi @luozihen — thanks for the update, and glad the missing-comma HOCON bug in testDecryptPreservesSpecialCharacterKeys turned out to be a quick, local fix once you spotted it. Rebasing to drop the accidental merge commit was the right call too, that keeps the diff clean for review. I re-checked: CI on the new head is currently still queued/in-progress on your fork, so please ping again once it finishes and I'll take a final look at the green run.
Since the head has moved (2acb55a0 -> 53f84008), here is a complete re-review against the current head, not just a diff against my last review.
What Problem Does This PR Solve?
- User pain point: multi-table JDBC sink jobs (e.g. MySQL-CDC -> JDBC with
generate_sink_sql = true) only have one globalprimary_keysoption, so there's no way to give different tables different key columns (or mix${primary_key}/${unique_key}with a shared static column such asDATA_SOURCE) in a single sharding/merge job. - Fix approach: adds a
multi-table_config.primary_keysoption toJdbcSinkFactorythat maps a table-name regex to a key-column list (with${primary_key}/${unique_key}expansion), taking precedence over the existingprimary_keys/ catalog-metadata fallback. It also fixes a real config-reconstruction bug:ConfigFactory.parseMap(...)treats every map key as a HOCON path expression, so a regex key such as^t_nova_.*$(containing.and$) throwsConfigException$BadPath. The PR replacesConfigFactory.parseMap(...)with a Jackson JSON round-trip inReadonlyConfig#toConfig()andConfigShadeUtils#processConfig. - One-sentence summary: same well-motivated, mostly well-tested JDBC feature as before; the code itself is unchanged since my last review other than the CI-blocking unit-test HOCON syntax fix, so my previous findings on the shared-API change and code duplication still apply and have not yet been addressed.
1. Code Change Review
1.1 Core Logic Analysis
I diffed 2acb55a0 (my last-reviewed commit) against the current head 53f84008 directly (git diff 2acb55a0 53f84008 --stat). The only file with a real content change is seatunnel-core/seatunnel-core-starter/src/test/java/.../ConfigShadeTest.java (the comma fix in the new testDecryptPreservesSpecialCharacterKeys HOCON literal, resolving the parse failure discussed on the thread). Everything else in that raw diff is unrelated upstream dev content (BigQuery/Hive/Stripe connectors, SQL functions, etc.) that came in through the merge commit and is not part of this PR's actual diff (gh pr diff correctly excludes it via merge-base). So the functional code of this feature is byte-for-byte identical to what I reviewed at 2acb55a0.
I re-verified the core logic directly in the current checkout, all consistent with before:
JdbcSinkFactory.resolveMultiTablePrimaryKeys()/matchesPattern()/toPrimaryKeyList()/expandPrimaryKeyPlaceholder()/getPrimaryKeyColumns()/getUniqueKeyColumns()(JdbcSinkFactory.java:222-297, unchanged) — full-match regex (tableName.matches(pattern)), first-match-wins viaLinkedHashMapiteration order (traced throughfromConfig's JacksonTypeReference<Map<String,Object>>, which preserves declaration order), clearJdbcConnectorExceptionwhen a placeholder is used but the upstream key is missing. Correct.- No double-processing with
TablePlaceholderProcessor.replaceTablePlaceholder(seatunnel-api/.../TablePlaceholderProcessor.java:161-206), which only rewrites top-levelString/single-elementString Listvalues and leaves a top-levelMap(likemulti-table_config) untouched — still verified safe.
Carryover Issue 1 (from my 2acb55a0 review, still open at 53f84008): ReadonlyConfig#toConfig() (seatunnel-api/src/main/java/org/apache/seatunnel/api/configuration/ReadonlyConfig.java:78-86, confirmed unchanged in the current checkout) still swaps ConfigFactory.parseMap(confData) for a Jackson JSON round-trip. This @Deprecated-but-still-load-bearing method has ~20 call sites outside this diff (e.g. FactoryUtil.java legacy source.prepare()/sink.prepare() fallback, MultiTableFailureHelper, connectors like Hive/Clickhouse/HDFS/Neo4j/AmazonSQS/AmazonDynamoDB/OpenMLDB/HTTP/IoTDB/GraphQL). parseMap() auto-expands dotted map keys into nested HOCON paths ({"a.b":1} -> {a:{b:1}}); the new JSON-based toConfig() keeps such keys literal/flat. Any caller building a dotted-key map that's later read back via a dotted-path lookup on the resulting Config would silently get a missing value instead of an exception — a hard-to-trace regression class. I still haven't found a concrete broken caller in-repo (the trace shows the JDBC feature itself only needs the ConfigShadeUtils.processConfig half of the fix, which is provably necessary and safe since its input is already JSON-normalized), but this remains unaddressed since last review.
Carryover Issue 2 (still open): the pre-existing PK-fallback-resolution logic (catalog PK -> first unique key -> plain INSERT) is still duplicated verbatim into the else branch of if (multiTablePrimaryKeys.isPresent()) (JdbcSinkFactory.java:159-201), instead of being extracted into a shared private helper called from both branches.
Carryover Issue 3 (still open): resolveMultiTablePrimaryKeys and its private helpers still have no Javadoc describing the matching/placeholder-expansion contract (verified via grep for /** in the current file — none precede these methods).
1.2 Compatibility Impact
- Fully compatible for the new
multi-table_configoption: purely additive, optional, only takes effect when a table name matches a configured pattern; unmatched tables fall back to the pre-existing logic unchanged. - Partially incompatible / unverified, unchanged from last review: the
ReadonlyConfig#toConfig()semantics change (Issue 1) is a behavior change to a shared API with a real, if currently unproven in-repo, potential to silently drop dotted-key config values for callers outside the JDBC connector.
1.3 Performance / Side-Effect Analysis
Unchanged from last review: all changed code runs once per job/sink-instantiation at submission time, not in the per-record hot path. No new threads, connections, or unbounded collections.
1.4 Error Handling and Logging
Unchanged from last review: error messages (INVALID_MULTI_TABLE_CONFIG, missing-PK/unique-key messages) are clear, include table/pattern context, and don't leak sensitive data.
| Issue | Location | Problem | Risk | Fix | Severity | Raised by another reviewer |
|---|---|---|---|---|---|---|
| 1 | seatunnel-api/src/main/java/org/apache/seatunnel/api/configuration/ReadonlyConfig.java:78-86 |
toConfig() (shared, ~20 call sites) changes Map->Config reconstruction semantics (dotted-key auto-expansion removed); no regression test proves other callers are unaffected |
Medium — no concrete broken caller found in-repo, audit not exhaustive, failure mode is silent | Scope the fix to ConfigShadeUtils.processConfig only (provably necessary and safe) and leave toConfig() untouched; or add explicit regression coverage + call out as an audited change in the PR description |
Medium | No |
| 2 | seatunnel-connectors-v2/connector-jdbc/.../sink/JdbcSinkFactory.java:118-201 |
Pre-existing PK-fallback logic duplicated verbatim into the new else branch |
Low — maintainability only | Extract into a shared private method used by both branches | Medium | No |
| 3 | seatunnel-connectors-v2/connector-jdbc/.../sink/JdbcSinkFactory.java:222-297 |
New non-trivial methods lack Javadoc | Low | Add short Javadoc describing matching/placeholder semantics | Low | No |
2. Code Quality Assessment
2.1 Coding Standards
Unchanged from last review: naming/style follow existing conventions (Google/AOSP via Spotless, no wildcard imports). The new MULTI_TABLE_CONFIG Option has a description. Missing Javadoc on new helper methods per Issue 3 above.
2.2 Test Coverage and Test Stability
- New unit tests are unchanged in structure from last review:
JdbcSinkFactoryTest(mapped hit, unmatched/fallback, missing-PK error, first-match-wins, string-value parsing, full factory-context path),ReadableConfigTest#testToConfigPreservesSpecialCharacterKeys, andConfigShadeTest#testDecryptPreservesSpecialCharacterKeys(now fixed — the HOCON literal in this test previously had missing commas between sibling fields on the same line, which is exactly what broke CI; the current head adds the required commas, e.g.url = "...", username = "u", password = "p", multi-table_config { ... }, and I traced this to be syntactically valid HOCON that will parse successfully). - Stability rating: Stable. All new/modified tests are pure, deterministic unit tests — no sleeps, no timing assumptions, no external I/O, no unordered-collection assertions without normalization.
- Gap unchanged from last review: no test proves
ReadonlyConfig#toConfig()'s new behavior is compatible with a dotted-key map for a caller outside the JDBC path (Issue 1).
2.3 Documentation Updates
Unchanged from last review: docs/en and docs/zh for Jdbc.md and sink-options-placeholders.md are both updated consistently and match the code (option key multi-table_config, sub-key primary_keys, placeholder syntax).
3. Architectural Soundness
3.1 Elegance of the Solution
Unchanged: the regex-to-key-list mapping design is precise and well-scoped. The underlying config-parsing bug fix is still applied at a broader scope than the traced necessary path requires (Issue 1) — inconsistent with a minimal-blast-radius change to a 3-year production system.
3.2 Maintainability
Unchanged, aside from the duplication noted in Issue 2.
3.3 Extensibility
Unchanged: the multi-table_config shape ({ primary_keys: { "<regex>": [...] } }) leaves room for future sibling keys without another breaking change.
3.4 Historical-Version Compatibility
Unchanged: no existing option is renamed/removed, new option is opt-in with exact fallback to pre-existing logic. Open question remains the ReadonlyConfig#toConfig() semantics change (Issue 1).
4. Issue Summary
| Number | Issue | Location | Severity |
|---|---|---|---|
| 1 | ReadonlyConfig#toConfig() semantics changed (dotted-key auto-expansion removed) for a shared API used by ~20 call sites outside this PR's scope; feature's own path doesn't appear to need this change (carried over from 2acb55a0 review, still unaddressed) |
seatunnel-api/src/main/java/org/apache/seatunnel/api/configuration/ReadonlyConfig.java:78-86 |
Medium |
| 2 | Pre-existing PK-fallback logic duplicated instead of extracted into a shared helper (carried over, still unaddressed) | seatunnel-connectors-v2/connector-jdbc/.../sink/JdbcSinkFactory.java:118-201 |
Medium |
| 3 | New non-trivial methods lack Javadoc (carried over, still unaddressed) | seatunnel-connectors-v2/connector-jdbc/.../sink/JdbcSinkFactory.java:222-297 |
Low |
5. Merge Recommendation
Conclusion: Ready to merge after fixes
- Blockers — must be fixed
- Get CI green on the current head (the HOCON test-syntax fix looks correct from my read of the diff, but I want to see the actual run finish rather than assume it).
- No hard functional blocker in the feature logic itself, same as last time — but I'd still like Issue 1 either scoped down to
ConfigShadeUtils.processConfigonly, or explicitly justified/tested, before merge, since it's a silent behavior change to a widely-used shared API.
- Recommended fixes — non-blocking
- Extract the duplicated PK-fallback block into a shared private method (Issue 2).
- Add short Javadoc to
resolveMultiTablePrimaryKeysand its helpers (Issue 3).
Nothing new to flag on the feature logic itself since my last pass — the code is identical to what I reviewed at 2acb55a0, and the only change on this head is the CI-fixing test correction, which looks right. I have read-only review rights here (Comment only), so a write-capable maintainer will need to make the final call on approval/merge, particularly on whether the ReadonlyConfig#toConfig() scope is an accepted tradeoff.
Thanks again for staying engaged through the CI back-and-forth, and for the clean rebase — looking forward to a green run.
|
@DanielLeens I've addressed all of them in the latest push:
I also updated the tests to match: removed the now-obsolete The changes are committed and CI is running on the new head. I'll ping here again once it finishes. Regarding the previous CI run, I noticed an error that I wasn't able to interpret on my own: It looks like it timed out pulling an image from Docker Hub, so it may be a transient network |
|
@DanielLeens Quick follow-up: the latest CI run has finished, and it failed on a different set of errors — all These are ContainerLaunchException / Container startup failed from Testcontainers, which looks |
DanielLeens
left a comment
There was a problem hiding this comment.
What Problem Does This PR Solve?
- User pain point: multi-table JDBC sink jobs (e.g. MySQL-CDC -> JDBC with
generate_sink_sql = true) only have one globalprimary_keysoption, so there is no way to give different tables different key columns (or mix${primary_key}/${unique_key}with a shared static column such asDATA_SOURCE) in a single sharding/merge job. - Fix approach: adds a
multi-table_config.primary_keysoption toJdbcSinkFactorythat maps a table-name regex to a key-column list (with${primary_key}/${unique_key}expansion), taking precedence over the existingprimary_keys/ catalog-metadata fallback. It also carries a real config-reconstruction bug fix inConfigShadeUtils#processConfigso a regex key such as^t_nova_.*$(containing.and$) survives the encrypt/decrypt round trip instead of throwingConfigException$BadPath. - One-sentence summary: this is a re-review at a new head (
53f84008->1730aeef); all three issues from my previous two passes have been addressed with clean, well-scoped fixes, and my fresh trace of the current code found only one small new maintainability nit, no functional blockers.
1. Code Change Review
1.1 Core Logic Analysis
Verifying the three previously-open issues are actually resolved (not just claimed)
I diffed the current head against the commit my last review covered and re-read every touched file end to end rather than trusting the PR author's summary comment.
- Former Issue 1 (shared
ReadonlyConfig#toConfig()semantics change) — confirmed resolved.seatunnel-api/src/main/java/org/apache/seatunnel/api/configuration/ReadonlyConfig.javano longer appears anywhere ingit diff <merge-base>...HEAD— it is byte-for-byte back to the pre-PR version, so the ~20 external call sites I flagged before (FactoryUtil.javalegacyprepare()fallback, Hive/Clickhouse/HDFS/Neo4j/etc.) are no longer at risk. The actual JDBC feature's own need (surviving encrypt/decrypt with regex keys) is now met solely byConfigShadeUtils#processConfig(seatunnel-core/seatunnel-core-starter/.../ConfigShadeUtils.java:213-217), which was already the provably-necessary, provably-safe half of the original fix: it swapsConfigFactory.parseMap(configMap)forConfigFactory.parseString(JsonUtils.toJsonString(configMap), ConfigParseOptions.defaults().setSyntax(ConfigSyntax.JSON)), andconfigMapis itself already the result of a JSON parse (JsonUtils.toMap(JsonUtils.parseObject(jsonString))two lines above), so this is a lossless textual re-encoding, not a semantics change.- The one place that previously depended on the now-reverted
toConfig()behavior,MultiTableFailureHelper#mergeOptions(seatunnel-api/.../MultiTableFailureHelper.java:55-66), was reworked to merge the underlyingMap<String,Object>directly instead of round-tripping throughConfig:merged.putAll(fallback.getSourceMap()); merged.putAll(primary.getSourceMap()); return ReadonlyConfig.fromMap(merged);.getSourceMap()andfromMap()are pre-existingReadonlyConfigAPIs (unchanged by this PR — verified viagit diff), so this trades aConfig#withFallback()deep-merge for a shallow, top-level-keyputAllmerge. I checked both call sites ofmergeOptions(withMultiTableFailurePolicyandwithFailedTables, same file, lines 68-91): in both casesprimaryis a synthetic single-key map (MULTI_TABLE_FAILURE_POLICYorMULTI_TABLE_INITIAL_FAILED_TABLES) that never overlaps with any nested key inside the realoptions/envOptionsmap, so the shallow-vs-deep-merge distinction is a no-op for every current caller. The newMultiTableFailureHelperTest#testMergeOptionsPreservesSpecialCharacterKeys(seatunnel-api/src/test/.../MultiTableFailureHelperTest.java:34-65) directly exercises the regex-key-survival property this rework needed to preserve. Good, targeted fix.
- The one place that previously depended on the now-reverted
- Former Issue 2 (duplicated PK-fallback logic) — confirmed resolved. The pre-existing catalog-PK/unique-key/plain-INSERT fallback block is now extracted into
applyFallbackPrimaryKeys(JdbcSinkFactory.java:204-233), and the new multi-table-match branch calls the sharedapplyPrimaryKeyshelper (JdbcSinkFactory.java:163-191) that bothresolveMultiTablePrimaryKeysandapplyFallbackPrimaryKeys's explicit-primary_keyscase route through.createSink()itself (JdbcSinkFactory.java:122-127) is now a clean two-branch dispatch with no duplicated body. - Former Issue 3 (missing Javadoc) — confirmed resolved.
resolveMultiTablePrimaryKeys,matchesPattern,toPrimaryKeyList,expandPrimaryKeyPlaceholder,getPrimaryKeyColumns, andgetUniqueKeyColumns(JdbcSinkFactory.java:234-390) all now carry Javadoc describing the matching semantics (full-match regex, first-match-wins,${primary_key}/${unique_key}contract) or return-value contract. This matches project convention for non-trivial new methods.
New finding from this pass — Issue 1 (new, Low): while verifying the Issue-2 extraction, I noticed applyFallbackPrimaryKeys (JdbcSinkFactory.java:204-233) re-implements the exact same "catalog primary key, else first unique key" lookup that getPrimaryKeyColumns/getUniqueKeyColumns (JdbcSinkFactory.java:363-390) already provide — the two helpers were added earlier in this same diff for the ${primary_key}/${unique_key} placeholder-expansion path. Concretely, applyFallbackPrimaryKeys re-derives catalogTable.getTableSchema().getPrimaryKey() and re-filters getConstraintKeys() for a UNIQUE_KEY constraint inline, instead of calling getPrimaryKeyColumns(catalogTable) / getUniqueKeyColumns(catalogTable) and joining the result. This is a small residual duplication introduced by the very refactor that fixed the original Issue 2 — not a correctness bug (both code paths currently compute identical results, verified by reading both side by side), purely a maintainability nit: a future change to "how we pick the catalog fallback key" now has two places to update instead of one.
- Location:
seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/sink/JdbcSinkFactory.java:204-233(duplicate) vs.:363-390(existing helpers it could delegate to).
Runtime path (touches seatunnel-api: MultiTableFailureHelper, and the core-starter config-decrypt step)
- Job submission:
ConfigShadeUtils.processConfig(seatunnel-core-starter/.../ConfigShadeUtils.java:151-224) runs once per job, decrypting sensitive fields in the raw JSON-rendered config map (including anymulti-table_config.primary_keysblock) and reconstructing aConfigvia the JSON-syntax parse path fixed here. - Per-table dispatch: for each table in a multi-table sink,
FactoryUtil/engine code builds aTableSinkFactoryContextand callsJdbcSinkFactory.createSink(context)(JdbcSinkFactory.java:88-161). - Inside
createSink,resolveMultiTablePrimaryKeys(config, catalogTable)(JdbcSinkFactory.java:242-263) readsMULTI_TABLE_CONFIGoff the per-tableReadonlyConfig(a plain map lookup, notoConfig()involved) and either matches a regex pattern (first-match-wins viaLinkedHashMap-preserving iteration order fromReadonlyConfig.fromMap/fromConfig's Jackson read) or falls through toapplyFallbackPrimaryKeys. - Either branch calls
applyPrimaryKeys(or its inline equivalent) to writePRIMARY_KEYSback into the sink config map and rebuild theCatalogTablewith aPrimaryKey.of(...)reflecting the resolved columns;config = ReadonlyConfig.fromMap(new HashMap<>(map))then feedsJdbcSinkConfig.of(config)and the eventualJdbcSinkconstruction, which is what generated UPSERT/UPDATE/DELETE statements key off. - Separately,
MultiTableFailureHelper.withMultiTableFailurePolicy/withFailedTables(unrelated call sites, engine/translation layer) merge environment-level failure-policy options into per-connector options via the reworkedmergeOptions— this path does not intersect with the JDBCmulti-table_configvalues above (different config keys), so there is no interaction risk between the two changes in this PR. - I re-verified there is still no double-processing with the generic placeholder framework:
TablePlaceholderProcessor.replaceTablePlaceholder(seatunnel-api/.../TablePlaceholderProcessor.java:161-206, unchanged) only rewrites top-levelString/single-element-String-Listvalues, so it never touches the nestedMapundermulti-table_config, leavingexpandPrimaryKeyPlaceholderas the sole place that expands${primary_key}/${unique_key}inside this option.
1.2 Compatibility Impact
Fully compatible. The new multi-table_config option is purely additive and opt-in; unmatched or absent configuration falls back to the exact pre-existing primary_keys/catalog-metadata resolution logic (now in applyFallbackPrimaryKeys, byte-equivalent to the pre-PR inline code). The ReadonlyConfig#toConfig() behavior-change risk I flagged in both previous reviews is fully eliminated now that the method is untouched. ConfigShadeUtils#processConfig's JSON-syntax parse is a lossless re-encoding of already-JSON-normalized data, and MultiTableFailureHelper#mergeOptions's shallow-merge rework is behaviorally identical to the old deep merge for every current caller (verified above). No existing option is renamed, removed, or has its default changed; no protocol/serialization/checkpoint format is touched.
1.3 Performance / Side-Effect Analysis
- All changed code executes once per job submission / per-table sink instantiation (
createSink(), config decrypt), not in the per-record hot path — negligible overhead relative to job-submission cost. mergeOptions's shallowHashMapcopy is strictly cheaper than the oldConfig#withFallback()deep merge it replaces.- No new threads, connections, unbounded collections, or retry loops introduced.
1.4 Error Handling and Logging
| Issue | Location | Problem | Risk | Fix | Severity | Raised by another reviewer |
|---|---|---|---|---|---|---|
| 1 | seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/sink/JdbcSinkFactory.java:204-233 |
applyFallbackPrimaryKeys re-implements the catalog-PK/unique-key lookup that getPrimaryKeyColumns/getUniqueKeyColumns (lines 363-390) already provide, instead of delegating to them |
Low — maintainability only; both paths currently compute identical results | Have applyFallbackPrimaryKeys call getPrimaryKeyColumns(catalogTable) and, if empty, getUniqueKeyColumns(catalogTable), joining the result, instead of re-deriving the lookup inline |
Low | No |
Error messages (INVALID_MULTI_TABLE_CONFIG, "table X matched pattern Y ... but the upstream table has no primary/unique key") remain clear, include table/pattern context, and do not leak sensitive data.
2. Code Quality Assessment
2.1 Coding Standards
All new non-trivial methods now have Javadoc (former Issue 3, confirmed fixed above). The new MULTI_TABLE_CONFIG Option (JdbcSinkOptions.java:112-121) has a description. Naming/style follow existing conventions (Google/AOSP via Spotless, no wildcard imports). No missing-comment items found in this pass.
2.2 Test Coverage and Test Stability
JdbcSinkFactoryTestgained direct unit tests forresolveMultiTablePrimaryKeys(mapped hit, unmatched/fallback, missing-key error, first-match-wins, string-value parsing) plus an end-to-endtestFactoryContextWithMultiTableConfigValidthrough the realcreateSinkViaFactoryContextentry path.MultiTableFailureHelperTest#testMergeOptionsPreservesSpecialCharacterKeysdirectly covers the reworked shallow-merge behavior for regex keys.ConfigShadeTest#testDecryptPreservesSpecialCharacterKeyscovers theConfigShadeUtilsfix; the previously CI-breaking missing-comma HOCON syntax bug in this test's literal is fixed in the current head (verified: every sibling field in the object literal is now comma-separated).- Stability rating: Stable. All new/modified tests are pure, deterministic unit tests operating on in-memory maps — no
Thread.sleep, no wall-clock assertions, no external I/O, no unordered-collection comparisons without normalization, no shared mutable static state.
2.3 Documentation Updates
docs/en/connectors/sink/Jdbc.md and docs/zh/connectors/sink/Jdbc.md both add a matching multi-table_config option-table row and a full ### multi-table_config [object] section with two worked examples (pure mapping, and mixed with top-level primary_keys). docs/en/introduction/configuration/sink-options-placeholders.md and its docs/zh counterpart both add a clarifying paragraph distinguishing the generic placeholder framework's single-element-list restriction from the JDBC-specific multi-table_config.primary_keys mixing support — this is accurate per my trace of TablePlaceholderProcessor vs. expandPrimaryKeyPlaceholder above. English and Chinese docs are consistent with each other and with the code (option key multi-table_config, sub-key primary_keys, placeholder syntax).
3. Architectural Soundness
3.1 Elegance of the Solution
Precise fix. With the ReadonlyConfig#toConfig() scope-down, both halves of this PR are now minimal-blast-radius: the config-decrypt fix is confined to ConfigShadeUtils, and the JDBC feature logic is confined to JdbcSinkFactory/JdbcSinkOptions. The regex-to-key-list design (declaration-order first-match, placeholder expansion scoped to this option only) is well-suited to the stated problem and was verified not to conflict with the existing generic placeholder framework.
3.2 Maintainability
Good, aside from the small residual duplication noted in Issue 1 above.
3.3 Extensibility
Unchanged from my prior assessment: the multi-table_config shape ({ primary_keys: { "<regex>": [...] } }) leaves room for future sibling keys under multi-table_config without another breaking change, since it is read as a generic Map<String,Object>.
3.4 Historical-Version Compatibility
No existing option is renamed/removed; the new option is opt-in with an exact fallback to the pre-existing logic when unmatched/absent. The shared-API risk that was the main open question in my last two reviews (ReadonlyConfig#toConfig()) is fully closed now that the method is untouched.
4. Issue Summary
| Number | Issue | Location | Severity |
|---|---|---|---|
| 1 | applyFallbackPrimaryKeys duplicates the catalog-PK/unique-key lookup already provided by getPrimaryKeyColumns/getUniqueKeyColumns instead of delegating to them |
seatunnel-connectors-v2/connector-jdbc/.../sink/JdbcSinkFactory.java:204-233 (vs. :363-390) |
Low |
5. Merge Recommendation
Conclusion: Ready to merge
- Blockers — must be fixed
- None. All three issues from my previous two review passes (shared
ReadonlyConfig#toConfig()behavior change, duplicated PK-fallback logic, missing Javadoc) are verified resolved in the current head, and this fresh independent pass found no new functional, compatibility, or data-safety issues.
- None. All three issues from my previous two review passes (shared
- Recommended fixes — non-blocking
- Have
applyFallbackPrimaryKeysdelegate to the existinggetPrimaryKeyColumns/getUniqueKeyColumnshelpers instead of re-deriving the same lookup inline (Issue 1 above).
- Have
On CI: the apache-side Build check is currently red, but I dereferenced it to the actual fork run (luozihen/seatunnel run 33743266792) and both failing jobs are doris-connector-it (JDK 8 and 11), not any module touched by this PR's diff (JDBC connector, seatunnel-api config, seatunnel-core-starter). I pulled the actual job logs and the failures are Testcontainers/Docker networking symptoms around the Doris FE/BE containers — Connection reset, Temporary failure in name resolution on the doris_e2e hostname, and Can't find tablet id ... maybe already dropped — not assertion failures on JDBC/PK-mapping behavior. This matches the author's own report on the PR thread and is consistent with a transient container-networking flake rather than a regression caused by this diff; I'd recommend a rerun of just the doris-connector-it job rather than any code change. mergeStateStatus shows BLOCKED/mergeable: MERGEABLE — that reflects branch protection requiring an approving review (reviewDecision: REVIEW_REQUIRED), not a merge conflict; no sync-with-dev action is needed on that front.
Overall this turned into a genuinely productive back-and-forth: the author correctly diagnosed and fixed a real HOCON test-syntax bug I flagged, and then addressed all three substantive review findings with clean, well-scoped fixes rather than papering over them — the shared-API change was properly scoped down instead of left broad, the duplication was properly extracted, and the documentation (English and Chinese) is thorough and matches the implementation. I do not see a materially better alternative implementation for the core feature; the regex-map design is a reasonable, minimal-footprint choice for this kind of per-table override. I have read-only review rights here (Comment only), so a write-capable maintainer will need to make the final call on approval/merge once the unrelated Doris IT flake clears on rerun.
Thanks for the thorough engagement through several rounds of CI back-and-forth, and for taking the shared-API scoping concern seriously rather than just chasing green CI — that is exactly the kind of care a 3-year production system needs from new contributors. Welcome again to the Apache SeaTunnel community.
|
@DanielLeens |
|
@luozihen Good question — and yes, this is still the same unrelated Doris-connector flake I called out in my last review, not a new failure. I re-checked the fork run just now ( Since this PR's CI runs inside your own fork, you have direct rerun access without needing me or another maintainer:
That reruns only the failed/skipped legs, not the whole matrix, so it should be quick. To be clear: CI hasn't actually re-executed since your last push (the HOCON fix + rebase) — GitHub is just still displaying that same red run from 2026-09-03. A rerun is exactly the right next step here, no further code change needed on your side. If it comes back green (or fails again with the same Doris/Testcontainers signature), ping this thread and I'll do a fresh confirmation pass. |
|
@DanielLeens Thank you for your guidance. The CI checks have now turned green. Could you please advise on the next steps? This is my first time submitting a PR, so I’m not entirely familiar with the full process. Apologies for any inconvenience, and thank you for your time. |
|
@luozihen Great news, thanks for rerunning — glad the Doris flake cleared and the run is green now. No need to apologise, you're doing everything right for a first PR. Next steps from here:
You don't need to take any further action on CI. Just the checklist above and I'll take it from there. |
|
@luozihen Congratulations on getting CI all the way to green, and welcome to the Apache SeaTunnel community — this has been a genuinely solid first contribution, and the way you dug into the HOCON/CI issues yourself along the way was great to see. Where things stand right now, for your reference: I approved this PR on my side after the last round of fixes, and the latest run on On next steps, here is roughly how it works in an Apache project like this one:
Thanks again for your patience through the CI back-and-forth, and for the clear, cooperative communication throughout review — that makes this a lot smoother for everyone. Nicely done for a first PR. |
|
@SEZ9 Here's the status against F1–F8 on the latest head: Addressed:
Addressed, but please confirm if you'd like it stricter:
Still open — happy to address as follow-ups:
Happy to take the open ones on, or wait for your targeted comments and fix them accordingly. |
|
@luozihen Thanks for the detailed status — here's my response point by point. F1 / F4 — direction looks right; closure pending verification. Reverting F2 / F5 — yes, please make it stricter. Relying on Jackson happening to produce a
F3 — please handle in this PR. Since the resolved key columns are comma-joined into F6 — please also do this in this PR. Lazy failure at match time means a bad regex only surfaces once data flows for a matching table. Please compile every pattern during config validation and raise F7 — two pieces:
F8 — please rename. The existing JDBC sink options are snake_case, so the mixed hyphen/underscore in Summary for this PR: F2/F5 explicit ordering + test, F3 identifier validation + test, F6 eager regex validation + test, F7 |
|
Thanks @luozihen, both fixes sound right.
Remaining asks before I can approve:
|
|
@luozihen, there is real overlap at Your JSON rebuild keeps every map key literal. #12443 quotes only invalid path expressions and preserves the existing handling of valid ones. For example, #12443 also covers ReadonlyConfig.toConfig(), the config-adapter conversion and both variable-map conversions, which remain outside the three rebuild sites changed here. Its REST submit-path tests are separate from the JDBC mapping coverage. I propose keeping one shared config fix in #12443 and rebasing the JDBC feature onto it, while keeping the primary-key validation changes in this PR. That avoids merging competing conversions. The intended key contract and merge order need to be agreed before either version lands; the two patches cannot simply be treated as identical fixes. |
|
@nzw921rx @DanielLeens @SEZ9
Issue 1 should be caused by merging code, and issue 2 should be intermittent. For issue 2, I can recompile. For issue 1, how can I handle it? |
DanielLeens
left a comment
There was a problem hiding this comment.
Thanks @luozihen for the fast fixes, and thanks @nzw921rx, @SEZ9 and @hutiefang76 for the follow-up. The head moved from 82fc5e61a (the head I approved) to d9bb1574f with three new commits: 6cacc034a (reject empty or non-string key columns), 0c43f10dd (ConfigBuilder.of(Map) keeps keys literal) and a dev merge. I diffed the 18 PR-owned files between the two heads (the rest of the 680-file raw diff is the dev merge) and re-read the changed code and the REST call chain. This is a static review; I did not build or run tests. The two extra optionRule() entries and the two extra tests in JdbcSinkFactory/JdbcSinkFactoryTest come from dev, not from this PR.
I am withdrawing my earlier Approve. Sorry for approving a head whose REST entry point I had only treated as "a documented limitation": the new commit 0c43f10dd turns that limitation into a behavior change for existing REST users, and I only found the consequence now (Issue 1). Everything else is in good shape.
What Problem Does This PR Solve?
- User pain point: a multi-table JDBC sink cannot declare a different primary key per upstream table; users need regex-keyed
multi_table_config.primary_keys. - Fix approach:
JdbcSinkFactoryresolves the key columns per table (first matching regex wins,${primary_key}/${unique_key}expanded), validates the shape inoptionRule(), and the core config rebuilds keep option keys literal so regex keys surviveConfigFactory.parseMap. - One-sentence summary: per-table primary keys for the JDBC sink, plus the config-loading changes needed to carry regex keys.
1. Code Change Review
1.1 Core Logic Analysis
Status of the open points
| Point | Status | Evidence at d9bb1574f |
|---|---|---|
@nzw921rx / my last comment: empty resolved key list, null / non-string elements |
Fixed | JdbcSinkFactory.toPrimaryKeyList(value, pattern) (JdbcSinkFactory.java:392-433) rejects non-string elements, non-list/non-string values and any value that yields no column with JDBC-12 naming the pattern; toCompiledPatternMap (:345) calls it for every entry at sink creation, so the failure happens before JdbcSink.createWriter(). validatePrimaryKeyColumns (:283) stays as the final guard for [""]. Tests: testMultiTableConfigWithEmptyKeyListFails, ...BlankStringValueFails, ...BlankKeyFails, ...NullKeyFails, ...NonStringKeyFails, ...NonListNonStringValueFails, ...NullValueFails, ...CommaSeparatedStringValue, testFactoryContextWithEmptyKeyListFailsBeforeWriterIsCreated. |
| @nzw921rx: REST JSON body rejects regex keys | Implemented, but with a compatibility side effect | Issue 1 below. |
@SEZ9 earlier asks (declaration order, placeholder order, toConfig() regression test, E2E, key naming) |
Unchanged and still covered | None of those files changed since the head I verified on 10-21. |
Runtime path of the new REST change:
POST submit-job (JSON body) -> RestUtil.buildConfig (RestUtil.java:75-76) -> ConfigBuilder.of(Map) (ConfigBuilder.java:112-115)
before: ConfigFactory.parseMap(map) keys are path expressions: "a.b" becomes {a:{b}}
now: rebuildWithLiteralKeys(map) (:283) JSON render + JSON parse: "a.b" stays one literal key
-> JobInfoService.submitJob (JobInfoService.java:472-476) -> ConfigShadeUtils.decryptConfig(config)
-> config.getConfig("env") + TypesafeConfigUtils.getConfig(env, "shade.identifier" | "shade.properties", ...) (ConfigShadeUtils.java:109-125)
-> submitJobInternal
Issue 1 (new in 0c43f10dd, High): ConfigBuilder.of(Map) no longer expands dotted keys, so REST JSON submissions and /encrypt-config that use dotted env keys lose their shade settings
- Location:
seatunnel-core/seatunnel-core-starter/.../ConfigBuilder.java:112-115and:283; consumersConfigShadeUtils.java:109-125/:127-143(identifier and properties),getSensitiveOptions(shade.options),TypesafeConfigUtils.getConfig(it callsconfig.hasPath(configKey)),JobInfoService.java:472-476,EncryptConfigService.java:36-37; testConfigBuilderTest.java:118-155. - Problem:
ConfigFactory.parseMaptreats every map key as a path expression, so a REST JSON body{"env": {"shade.identifier": "my-shade", "shade.options": ["password"]}}used to becomeenv { shade { identifier = ..., options = [...] } }. The repository itself pins this behavior:ReadableConfigTest#testToConfigPreservesDottedKeyExpansion(ReadableConfigTest.java:383-390) puts a literal"a.b"into a map and expectsconfig.getInt("a.b")to work afterparseMap. After this commit the same body becomesenv { "shade.identifier" = ... }with one literal key, andhasPath("shade.identifier")looks forshadethenidentifier, so it is false.ConfigShadeUtils.decryptConfigthen falls back toDEFAULT_SHADE(ConfigShadeUtils.java:68) and an emptyshade.options/shade.properties. The dotted form is exactly what the documented encrypted output looks like (docs/en/introduction/configuration/config-encryption-decryption.mdprints"shade.identifier" : "base64"insideenv), so users re-submitting such a JSON body through the REST API are the affected group. The new test confirms the shape change rather than refuting it: it asserts thatenvunwraps to the literal{"job.mode": "BATCH"}(ConfigBuilderTest.java:153) and describes this as the shape "they had before this change", which is not whatparseMapproduced before. - Potential risk: for a REST JSON job with a custom shade, the encrypted option values are no longer decrypted (or are decoded with the wrong shade) and the job fails with credential errors or, worse, runs with a wrong value;
/encrypt-configsilently encrypts with the default shade or skipsshade.options. Anything else that reads dotted keys through theConfigAPI on the REST JSON path changes the same way, while code that goes throughReadonlyConfig(it accepts both shapes,ReadonlyConfig.javagetValue) keeps working, which makes the breakage selective and hard to spot. I traced this by reading the source; I did not run it, so please confirm with a test as described below. - Best improvement: keep the previous behavior for every key that is a valid path expression and only protect the keys that
parseMapcannot take. Two safe options:- Minimal: drop
0c43f10ddfrom this PR and leave the REST JSON body as the documented limitation tracked in #12434 (the docs text on82fc5e61aalready says so). The JDBC feature and the file and HOCON paths stay complete. - Root cause: in
of(Map)(and the shared helper), quote or escape only the keys that are not valid path expressions (for example the regex keys) and letparseMapexpand the rest, then add a test that runs a REST-shaped map withenv."shade.identifier",env."job.mode"and a regex key throughRestUtil.buildConfigandConfigShadeUtils.decryptConfigand asserts both the shade lookup and the regex key survive. This is the same direction @hutiefang76 describes for #12443, so it should be agreed with that PR first.
- Minimal: drop
- Severity: High
- Raised by another reviewer: Partly. @hutiefang76 pointed out that the literal rebuild and #12443 have different key semantics and asked for one agreed contract; the shade consequence is new here.
Issue 2 (Low): the new test comment contradicts the pre-change behavior
- Location:
ConfigBuilderTest.java:118-155(the comment "Dotted option keys keep the literal shape they had before this change"). - Problem: see Issue 1; whichever option you pick, the comment and the
job.modeassertion should describe the real before/after shape. - Severity: Low
- Raised by another reviewer: No
1.2 Compatibility Impact
Partially incompatible, because of Issue 1 only: the REST JSON submit and encrypt endpoints change how dotted keys are represented in the Config. The JDBC part is additive: multi_table_config is a new optional key, nothing existing is renamed, and a sink without it takes the unchanged fallback path (applyFallbackPrimaryKeys). The file and HOCON paths are unaffected because their maps are already expanded before the literal rebuild.
1.3 Performance / Side-Effect Analysis
No concern. Patterns are compiled and validated once per sink creation (COMPILED_PATTERN_CACHE), the cost is proportional to the number of configured patterns, and no hot-path code changed.
1.4 Error Handling and Logging
Good. Every malformed shape is rejected with JDBC-12 and a message that names the pattern; no exception is swallowed.
2. Code Quality Assessment
2.1 Coding Standards
Javadoc on the changed helpers explains the failure mode being prevented. No concern.
2.2 Test Coverage and Test Stability
The new JDBC validation tests would go red on the previous toPrimaryKeyList (it stringified null and accepted an empty list), by reading the diff, and cover [], "", [""], [null], [123], non-list values, null and the positive comma-separated case. Gap: nothing tests the REST path with a dotted env shade key (Issue 1). Stability rating: Stable for the JDBC tests (deterministic, no containers); the E2E JdbcMysqlMultipleTablesIT is unchanged since my last check. No existing test was weakened.
CI for head d9bb1574f (the apache-side Build check is still in progress; the real run is https://github.com/luozihen/seatunnel/actions/runs/39710874854, completed with failure). To answer @luozihen's question:
- Unit tests: all four
unit-testlanes (JDK 11/17, ubuntu/windows) fail with the same single error,LLMBooleanOutputTest.readsLegacyFactoryWrapperWithValidationDisabled:248 InvalidClassinseatunnel-transforms-v2. TheOpen udf failedtext is a logged message, not the failing assertion. This PR does not touch that module, and the fix is ondev:cc54bb43([Fix][Transform-V2] Restore archived LLM wrapper deserialization, #12938), which this head does not contain (the branch is 3 commits behinddev). Syncingdevand re-running is the right step; this is not an intermittent flake. - Dead links:
https://raw.githubusercontent.com/intersystems-community/iris-driver-distribution/main/JDBC/JDK18/intersystems-jdbc-3.8.4.jaris an existing link in the Jdbc docs ondev(the en sink and source pages and the zh source page), not in this PR's diff, and the job is not a merge gate, so nothing to do here. transform-v2-it-part-2 (17)failed inTestPythonTransformIT(a parameter resolution error before the test body); it is a transform E2E unrelated to this diff and should pass on re-run.
2.3 Documentation Updates
docs/en/connectors/sink/Jdbc.md and the zh page now claim that regex keys work for the JSON REST body. If Issue 1 is resolved by dropping the REST commit, that sentence must go back to the limitation wording from 82fc5e61a.
3. Architectural Soundness
The connector part is well contained: all JDBC behavior sits in JdbcSinkFactory, validation is early and uniform, and the legacy primary_keys branch is untouched. The REST change is a shared-entry-point change in seatunnel-core that overlaps with #12443 (same method, different key contract), which is why it deserves its own agreement and its own tests rather than riding along with a connector feature.
4. Issue Summary
| Number | Issue | Location | Severity |
|---|---|---|---|
| 1 | ConfigBuilder.of(Map) keeps all keys literal, so dotted env keys such as shade.identifier are no longer found on REST JSON submit and /encrypt-config |
ConfigBuilder.java:112-115, :283; ConfigShadeUtils.java:109-143 |
High |
| 2 | Test comment describes the wrong "before" shape | ConfigBuilderTest.java:118-155 |
Low |
5. Merge Recommendation
Conclusion: Ready to merge after fixes
1. Blockers - must be fixed
- Issue 1: either remove
0c43f10dd(and restore the limitation wording in the two Jdbc docs) and keep the REST body in #12434 / #12443, or makeof(Map)expand valid path keys as before and only protect the invalid ones, with the REST-shaped test described above. Please also agree the key contract with @hutiefang76 so that #12443 and this PR do not land competing conversions. - CI: sync with the latest
dev(it carries #12938) and re-run; the unit-test failures are unrelated to this diff, andBuildmust be green before merge.
2. Recommended fixes - non-blocking
- Issue 2. The two optional Low items from my previous review (an unreachable defensive branch and a test nit) are still optional.
Overall assessment: the per-table primary key feature and the empty/non-string validation are done well and well tested. The only thing standing between this PR and merge is the REST key semantics, which is a small change either way. Thank you again for the patience through these rounds!
|
Hi @hutiefang76 — thanks for the careful comparison. You are right that these are two different key contracts rather than two copies of the same fix, so it is worth agreeing on the contract and the ownership before either lands. I ran the semantics against the shaded HOCON in this repo, because the thread mixes upstream typesafe-config behaviour with this fork's:
The first row matters for the thread: this repo patches the shaded parser (#8975), so plain dotted keys are not expanded by parseMap here, and env.hasPath("shade.identifier") is true both before and after this change. I could not reproduce the REST shade consequence, but I agree it is exactly the kind of thing that should be pinned rather than argued, so I will add the REST-shaped test Daniel asked for (map -> RestUtil.buildConfig -> ConfigShadeUtils.decryptConfig, with a regex key, job.mode, shade.identifier and a->b). The remaining deltas are the ones you named, and they are the contract question. Items I would like us to agree on:
Concretely, two ways to proceed:
Which of the two would you prefer? Once we agree on the contract and the owner, I will make the change the same day. |
|
@luozihen thanks for digging through the CI logs. Issue 1 (dead link): I cannot tell from the thread whether that URL comes from the base branch or from the JDBC sink doc this PR touches. Could you check whether the link appears in your diff? If it is only in the base branch, a rebase onto the latest main should tell us, and a docs-only fix in a separate PR would be the right place for it; I would not block this PR on it. If it is in your diff, please update or remove the link here. Issue 2 ( On the
The JDBC-specific items from the earlier review (declaration-order guarantee for the map-typed option and its docs, identifier validation on the resolved key columns, the |
|
Thanks @luozihen for the thorough follow-up, and thanks @SEZ9 and @hutiefang76 for helping converge on the key contract. The head is still 1. The first row of the semantics table does not match the shaded parser source on this head. The table says
I could not find a patch to this path in This is a factual question we can settle by test rather than by argument, and you already offered the right one. Please add the REST-shaped test exactly as you described (map -> 2. Which option to take. Both are fine from my side. I agree with @SEZ9 and your own lean: keep existing keys behaving exactly as today and only rescue keys that cannot be parsed as a path today (quote-only-invalid). Only one PR should change 3. CI, to correct one point in the thread. The unit-test failure is not the Next step: sync |
|
Thanks for the follow-up. The head is still On the semantics table (F1). The first row says This is easiest to settle with a test rather than discussion, and you already proposed the right one:
Once the test and the table update are pushed, I'll re-check F1 and F7 against the new head. |
|
+1 to @SEZ9's request to settle the dotted-key contract with the REST-shaped test already proposed here. Preserving valid existing path semantics matters as much as accepting the regex key: a literal rebuild must not silently change how env's Please push the map -> |
|
Hi @hutiefang76 — following up on the contract question from 23 Oct. I have not heard back for a few days, so rather than leave this open I will proceed in the direction @SEZ9 and @DanielLeens converged on, and I wanted to tell you explicitly first.
Thanks — I would like to settle this and move the PR forward; if you disagree with either the contract or the ownership, a short reply is enough and I will adapt. |
|
Hi @luozihen, @hutiefang76, @SEZ9, thanks for pushing this to a concrete answer, and @luozihen, I owe you a correction. I re-checked the shaded parser on What does still differ, per your table, is narrower: Two practical notes: please settle ownership of |
|
Noting that #12443 has been approved (thanks @hutiefang76 and @DanielLeens). To avoid two competing config conversions, I will hold further config-loading changes here until #12443 lands:
The head stays at |
|
Hi @luozihen, thanks for the clear plan, and for telling everyone before holding the branch. This sounds right to me, and it matches the direction we converged on:
The head is still |
|
@luozihen Thank you for your contribution. Moving forward with this work after 3.1.0🔥 |
|
@luozihen — apologies for the slow reply on the contract question; answering it directly now.
@nzw921rx noted — fine to take this after 3.1.0; nothing here needs to rush the release. Nothing further is needed from you until #12443 merges. Ping me when the rebased head is up. |
|
Thanks @SEZ9, @nzw921rx and @luozihen. The sequencing is unchanged: #12443 remains open at 509fdda, so please land that config-key contract first, then sync this branch and remove its competing conversion while retaining the combined REST/toConfig regression. The unchanged head here does not resolve that dependency. I also respect the maintainer's after-3.1.0 scheduling note; there is no need for an empty trigger commit or unrelated patch while waiting for the prerequisite. Gate snapshot (2026-10-28T15:57:29+00:00), head The blocking jobs are Run / Dead links Observed log evidence: Please inspect or rerun only the named failed job where a rerun is appropriate. The logs establish the failing stage, but do not alone establish whether the current PR caused it. No matching upstream cure has been proved by this follow-up; a base sync alone is not a verified resolution, so no unrelated module/dependency patch is requested. My previous source conclusion remains unchanged, including its independent source/documentation requests. CI is not being passed by inference, and this follow-up is not an effective approval. Comparison recorded in this scan: base |
DanielLeens
left a comment
There was a problem hiding this comment.
Thanks for the careful follow-up, and sorry for my earlier incorrect assumption about dotted keys. I re-read the complete current Apache SeaTunnel diff, the vendored path parser and the shared configuration reconstruction chain. The repository uses -> as its path separator; my earlier dotted-key/shade failure argument was not valid. The current rebased implementation and tests close the source blockers for me.
What problem does this PR solve?
User pain: one multi-table JDBC sink cannot select different key columns for different upstream tables. Fix: resolve an ordered regex-keyed primary_keys map before target-name remapping, with an unchanged legacy fallback. Example: orders use order_id while order_lines use the composite order_id,line_id.
1. Code changes
1.1 Core logic
Complete runtime path:
File / REST JSON -> ConfigBuilder -> shared quoteInvalidPathKeys contract from dev
-> ConfigShadeUtils decrypt/rebuild -> factory optionRule structural check
-> JdbcSinkFactory.createSink(upstream CatalogTable)
-> validate/compile every mapping -> first matching upstream identifier
-> expand whole primary_key / unique_key tokens -> validate column list
-> otherwise configured legacy keys, upstream PK, then unique-key fallback
-> target remapping -> JdbcSink.createWriter -> dialect-generated keyed writes
Key findings and correctness:
The normal per-table factory path reaches the feature before names are remapped. The cache is bounded to 256 compiled pattern maps; declaration order is preserved. Empty/null/non-string resolved keys fail before writer creation. The current diff no longer replaces the core map loader: it uses the merged shared quote-only-invalid contract. Crucially, this repository uses PATH_TOKEN_SEPARATOR="->", not a dot. job.mode and shade.identifier are literal valid keys; a->b expands. My previous claim that dotted keys necessarily expanded was incorrect, and I withdraw that consequence rather than carrying it forward. The current narrow helper preserves all already-valid path keys and protects regex keys at each reconstruction boundary.
Before:
import org.apache.seatunnel.connectors.seatunnel.jdbc.internal.dialect.dialectenum.FieldIdeEnum;
import java.util.List;
public class JdbcSinkOptions extends JdbcCommonOptions {
After:
import org.apache.seatunnel.connectors.seatunnel.jdbc.internal.dialect.dialectenum.FieldIdeEnum;
import java.util.List;
import java.util.Map;
public class JdbcSinkOptions extends JdbcCommonOptions {
1.2 Compatibility
Fully compatible for existing JDBC options and key fallback. The new optional mapping takes precedence only when configured and matched. Core parsing now follows the already-merged shared contract: dot is literal and -> is the path separator. No checkpoint/wire/default rename is introduced.
1.3 Performance and side effects
Regex compilation is submission-time and bounded by a synchronized 256-entry access cache. Concurrent misses may compile twice without changing results. Matching cost scales with mapping count per table, not per record; row-writing, transaction and resource ownership remain unchanged.
1.4 Errors, logging, and findings
No new source-level blocker found. Exceptions must still reach the existing job failure path; this review does not substitute for current-head CI.
I agree with @nzw921rx's earlier requested structural validation and empty-key safeguards; both are implemented. @SEZ9's parser correction is right: PATH_TOKEN_SEPARATOR is ->. The agreed #12443 sequencing is now reflected in the current source, and the REST/key-shape regressions cover that shared contract rather than a competing loader. His declaration-order/placeholder and integration requests are addressed. The earlier approval and later change requests must be assessed against this rebased head; I do not retain their now-closed source blockers.
2. Code quality
2.1 Conventions
Reviewed all changed files for license, imports, naming, core-method and state-field comments. No additional convention blocker found.
2.2 Test coverage and stability
Stability rating: Stable. Deterministic factory/config tests exercise first-match order, invalid mappings, placeholder precedence, real HOCON ordering and map/toConfig/REST-shaped rebuilds. Existing JdbcMysqlMultipleTablesIT now checks real target primary-key column order and row counts for the mapped tables, with cleanup. Exact-head upstream CI ran ConfigBuilderTest: 21 tests, zero failures/errors in unit-test JDK17 job 135377264734 (run 44469734647); all four collected unit lanes succeeded. These are downloaded CI results, not local execution. No timing-dependent assertion was identified in the added unit cases.
2.3 Documentation
Both JDBC guides explain upstream-name matching, first match, precedence, placeholders and invalid resolved keys. One minor wording nuance: an entirely empty outer multi_table_config is intentionally accepted by the validator/tests and uses fallback, whereas a nonempty malformed mapping fails. The current text should describe that distinction precisely.
3. Architecture
3.1 Change location
The affected component owns this behavior. Keep the smallest complete correction there; a wider engine or connector redesign is not justified by this diff.
3.2 Maintainability
Keep the behavior, lifecycle ownership, and failure contract together. The affected component owns this behavior. Keep the smallest complete correction there; a wider engine or connector redesign is not justified by this diff.
3.3 Extensibility
Prefer the existing component boundary and tests over unrelated shared abstractions.
3.4 Upgrade impact
Fully compatible for existing JDBC options and key fallback. The new optional mapping takes precedence only when configured and matched. Core parsing now follows the already-merged shared contract: dot is literal and -> is the path separator. No checkpoint/wire/default rename is introduced.
4. Findings summary
| # | Finding | Location | Severity |
|---|---|---|---|
| - | No new source blocker found | - | - |
5. Merge recommendation
Can merge once the recorded CI and repository gates are satisfied
Blocking items: No source blocker. Current-head CI and write-capable maintainer review remain independent requirements.
Non-blocking suggestions: None beyond the validation limits above.
Overall: the reviewed source path is coherent; no runtime acceptance is claimed beyond the actual CI result. Daniel has READ permission, so this COMMENT cannot dismiss historical requested changes or satisfy a write-capable maintainer approval gate.
CI and repository state: no check reported in the Apache rollup; Build: in_progress. GitHub reports BLOCKED / CHANGES_REQUESTED.
Verification: Reviewed all changed files and the referenced call sites at 2c899fc6cb16eb376988e180f1447ce5372030a1 against merge base f1ab36f0423c8aa17766959dfd6c6b3f5bc1426a. git diff --check passed. I did not build, run tests, or execute SeaTunnel locally.
Review time: 2026-11-19T07:22:46.039521-05:00
Local evidence: git fetch obtained head 2c899fc6cb16eb376988e180f1447ce5372030a1; git merge-base returned f1ab36f0423c8aa17766959dfd6c6b3f5bc1426a; git diff --stat reports 14 files changed, 1455 insertions(+), 42 deletions(-). git show and source searches were used for the entry points above. No local build, unit test, E2E, Docker run or service startup was executed.
|
@nzw921rx @SEZ9 @DanielLeens — following the after-3.1.0 plan, this branch is now synced with the 3.1.0 dev branch and #12443's config-key contract, and the Build is green. Head: 2c899fc (merge of upstream/dev f1ab36f, which contains #12443) What changed:
Local verification: ConfigBuilderTest 21, ConfigShadeTest 20, ReadableConfigTest 18, JdbcSinkFactoryTest 47, JdbcTableOptionsConditionExtensionTest 15 — all pass; spotless check passes. One CI bookkeeping note: the PR currently shows no attached Build check because the |
DanielLeens
left a comment
There was a problem hiding this comment.
Thanks, @luozihen, for the exact head and Build link. I checked the named common config classes: there is no diff against latest dev in ConfigBuilder, ConfigShadeUtils or MultiTableFailureHelper, consistent with using the merged #12443 key contract rather than carrying a competing conversion. My complete review already covers this unchanged feature head; the reported local tests are yours, not executions performed by me.
The previous CI-only blocker has changed: the exact-head fork Build is successful, including the previously incomplete connector lanes. I found no remaining source blocker in the prior full review, so I am changing my review to approve. Apache's PR-signal/workflow approval and adoption of the fork result remain distinct bookkeeping gates; the fork success should not be described as an already attached Apache Build.
Merge recommendation: Can merge from Daniel's technical perspective once repository gates are satisfied.
Blocking source items: None.
Non-blocking suggestions: Existing review suggestions are unchanged. A write-capable maintainer still owns effective approval/dismissal and workflow approval.
Checked unchanged head 2c899fc6cb16eb376988e180f1447ce5372030a1 against dev: compare diverged, ahead 34 / behind 6. This drift is recorded independently; it does not by itself request synchronization. This is a discussion/CI follow-up, not another full source review. No local build, test or runtime execution was performed. Daniel has READ repository permission; effective maintainer approval/dismissal remains a separate repository gate. Checked 2026-11-20T12:05:54.019197+00:00.
|
@luozihen thanks for the sync and the clear summary. The latest review on this thread is an approval that lists no blocking source items and says the existing review suggestions are unchanged. So everything below is a non-blocking follow-up from the earlier review, not a new requirement. CI: you report fork run 44469734647 as successful for head 2c899fc. Because the Not confirmed from the comments alone
Earlier suggestions your comment doesn't cover
A short "done / not done / intentionally kept" per item is enough, with a pointer to the relevant test or doc section where one exists. |
|
Thanks, @SEZ9. Here are the six boundary answers on the unchanged head.
The CI fact in my earlier approval has also changed: an exact-head fork Build now exists and is successful, and Apache Build is successful too. The old missing-Build/action-required guidance no longer applies. My existing technical approval stands; optional wording cleanup and effective maintainer review remain separate. Checked unchanged head |
|
@DanielLeens @nzw921rx @davidzollo |
|
Thanks for following up, @luozihen. From my side, you do not need another consolidation rewrite: my existing source assessment and technical approval stand on this unchanged head. The shared config-key repair from #12443 is already in your branch, and the spelling is The concrete next step has changed: GitHub now reports merge conflicts with Discussion-only follow-up on unchanged head |
Resolved the only conflicts in docs/en|zh/connectors/sink/Jdbc.md by keeping both upstream's multi_table_sink_replica row/paragraph and this PR's multi_table_config section. The JDBC code and tests merged automatically.
DanielLeens
left a comment
There was a problem hiding this comment.
Thanks for resolving the conflicts and strengthening the real-HOCON and generated-DDL regressions, @luozihen. I re-read the complete 14-file diff at the new head. My previous source approval still holds technically; the new head needs its own completed CI result, and the earlier conflict-resolution request is superseded by this source recheck.
What problem does this PR solve?
User pain: A multi-table JDBC job can need a different composite target key for each source table; one top-level primary_keys cannot express that.
Approach: Add optional multi_table_config.primary_keys regex mappings, upstream primary/unique-key expansion, fail-fast validation, and apply the resolved keys to both sink options and catalog schema before SQL/table creation.
In one sentence: Let each source table choose its intended target key while retaining the old fallback. For example, orders can use [id, DATA_SOURCE] while another table uses a different key.
1. Code changes
1.1 Core logic
Complete runtime path:
File/REST job loading -> existing merged ConfigMapPathUtils invalid-path rescue -> shade/decrypt rebuild
-> engine TablePlaceholderProcessor.replaceTablePlaceholder (158-181): top-level replacements only
-> option validation -> JdbcMultiTableConfigConditionExtension.evaluate (54-67)
-> per-table JdbcSinkFactory.createSink (105): retain upstreamTable before target remap
-> resolveMultiTablePrimaryKeys (316): eagerly compile patterns, match original upstream name
-> expandPrimaryKeyPlaceholder -> reject absent upstream keys / bad values
-> applyPrimaryKeys (193): validate names, update PRIMARY_KEYS and rebuilt catalog primary key
or applyFallbackPrimaryKeys (239): existing explicit/catalog-PK/first-unique-key behavior
-> JdbcSinkConfig -> JdbcSink -> save-mode handler creates target DDL using rebuilt schema
-> createWriter -> JdbcOutputFormatBuilder (77,212): resolved keys drive generated SQL
-> normal flush/checkpoint/commit and multi-table routing remain existing implementations
Key findings and correctness:
- Normal generated-SQL multi-table creation reaches the new mapping before target-name remapping can alter the source matching identity. Missing/unmatched mappings preserve the original top-level/catalog fallback.
- The old REST/config concern is closed through the merged #12443 contract; this diff does not modify ReadonlyConfig, ConfigBuilder, ConfigShadeUtils or MultiTableFailureHelper production code. In this repository the path separator is ->, so the name of the dotted-key test does not itself prove nesting. My earlier dotted-key-expansion objection remains withdrawn.
- The prior pattern-order uncertainty can now be narrowed with actual source evidence: this head's ConfigParser.java:256,392 creates LinkedHashMap, SimpleConfigObject.java:428-430 renders key iteration without sorting, and its unwrapped map is LinkedHashMap (258-265). The new real-HOCON test deliberately declares a broad overlapping pattern last, and the E2E checks generated target keys. This is stronger than testing a manually constructed ordered map. Arbitrary external unordered Java maps still have their own iteration semantics; avoid promising a declaration order for those.
- Empty lists, blank keys, null/non-string list elements and invalid regex are rejected before writer creation. Per-table options update both the effective JDBC key list and target catalog PK, preventing DDL/upsert disagreement. The bounded 256-entry pattern cache permits harmless duplicate compilation across concurrent misses.
Before:
PrimaryKey primaryKey = catalogTable.getTableSchema().getPrimaryKey();
if (CollectionUtils.isEmpty(config.get(JdbcSinkOptions.PRIMARY_KEYS))) {
// catalog PK, otherwise first UNIQUE key
} else {
// rebuild schema with top-level configured keys
}After (JdbcSinkFactory.java:144-149):
Optional<List<String>> multiTablePrimaryKeys =
resolveMultiTablePrimaryKeys(config, upstreamTable);
if (multiTablePrimaryKeys.isPresent()) {
catalogTable = applyPrimaryKeys(map, catalogTable, multiTablePrimaryKeys.get());
} else {
catalogTable = applyFallbackPrimaryKeys(config, map, catalogTable);
}Concrete CI next step: The current Build is not green. All-connectors partition 4 JDK 17 fails downloading Maven wrapper with HTTP 429, then MavenWrapperMain is missing, before tests. Partition 6 JDK 11 fails DatabendCDCSinkIT.testDatabendSinkCDC on the Flink invocation with NoResourceAvailableException / pending slot allocation, not on a JDBC key assertion. The changed files do not alter Databend or wrapper bootstrap. I checked latest dev ee0fb0d and the intervening history of those paths; no matching landed cure is established. Please rerun those failed lanes after bootstrap/resource availability recovers and keep the resulting exact-head links; syncing alone is not a verified fix. Do not add unrelated Databend/dependency patches here.
1.2 Compatibility
Fully compatible for jobs that do not use the new option: the old explicit primary_keys branch is intentionally not rewritten/revalidated, and PK/unique-key fallback is preserved. New option spelling is multi_table_config with no default. Existing public connector API, default, protocol, row/checkpoint serialization and shared config conversion are unchanged; no new dependency. The opt-in mapping intentionally overrides keys only on matched tables. Blank/comma key validation avoids ambiguity in the existing comma-delimited config representation; it is not a general SQL identifier whitelist.
1.3 Performance and side effects
Pattern compilation is cached in a synchronized access-order LRU capped at 256; per-table resolution copies mappings and iterates patterns once during sink creation, not per row. No new data buffer, per-record network operation, checkpoint state, retry policy or writer lock. Regex complexity remains user-controlled initialization work. Target DDL/SQL reflects the resolved PK while existing writer release/flush semantics remain unchanged.
1.4 Errors, logging, and findings
No new source-level blocker found. Exceptions must still reach the existing job failure path; this review does not substitute for current-head CI.
The earlier @nzw921rx change request concerned REST regex loading and empty/null key acceptance. Both are closed in the inspected current path: merged shared invalid-path rescue, eager value validation and factory-level negative tests. His earlier approval and subsequent request are historical separate records; a write-capable maintainer must reconcile them. @SEZ9 explicitly classified the later six questions as non-blocking: production config conversion is unchanged; regex compilation and column delimiter validation exist; placeholder order has an explicit new regression and bilingual docs; the engine E2E now verifies generated DDL; underscore spelling is retained. The new HOCON/DDL tests and current shaded parser address the earlier pattern-order question. I agree with the earlier technical approval from the reviewed source paths; no additional source blocker found.
2. Code quality
2.1 Conventions
Reviewed all changed files for license, imports, naming, core-method and state-field comments. No additional convention blocker found.
2.2 Test coverage and stability
Stability rating: Stable. JdbcSinkFactoryTest.java:651 exercises real HOCON overlapping-pattern precedence; line 806 exercises engine-top-level versus nested JDBC placeholder passes. Negative cases cover missing/empty/wrong-shaped primary_keys, invalid regex, empty lists, null/non-string values, blank columns, upstream-name versus target remapping and missing upstream PK. JdbcMysqlMultipleTablesIT.java:236-267 drops dedicated target tables, runs the actual config, asserts ordered information_schema PRIMARY columns and exact row counts, then drops fixtures in finally. Test keys are NOT NULL, shared fixtures remain untouched, query ordering is explicit, statements/result sets use scoped cleanup and no new hard sleep/performance threshold is added. Thus stability is Stable on inspection. REST-shaped config/shade tests and direct toConfig assertions reuse the upstream implementation; the single a.b lookup does not alone prove shape. No local tests were run.
2.3 Documentation
EN/ZH JDBC docs and placeholder guides describe regex full-match semantics, precedence, mixed static/primary/unique-key expansion and both replacement passes. File and REST regex support relies on the merged shared helper. Existing optional follow-up: docs should distinguish an entirely empty multi_table_config object (explicitly accepted as no customization at JdbcMultiTableConfigConditionExtension.java:56-57) from a nonempty object with absent/empty primary_keys (rejected). This is wording clarification, not a new source blocker.
3. Architecture
3.1 Change location
The affected component owns this behavior. Keep the smallest complete correction there; a wider engine or connector redesign is not justified by this diff.
3.2 Maintainability
Keep the behavior, lifecycle ownership, and failure contract together. The affected component owns this behavior. Keep the smallest complete correction there; a wider engine or connector redesign is not justified by this diff.
3.3 Extensibility
Prefer the existing component boundary and tests over unrelated shared abstractions.
3.4 Upgrade impact
Fully compatible for jobs that do not use the new option: the old explicit primary_keys branch is intentionally not rewritten/revalidated, and PK/unique-key fallback is preserved. New option spelling is multi_table_config with no default. Existing public connector API, default, protocol, row/checkpoint serialization and shared config conversion are unchanged; no new dependency. The opt-in mapping intentionally overrides keys only on matched tables. Blank/comma key validation avoids ambiguity in the existing comma-delimited config representation; it is not a general SQL identifier whitelist.
4. Findings summary
Completeness check: All changed files and affected entry/failure paths were reviewed; configuration/serialization compatibility, test failure capability and stability, documentation/examples, change ownership, and current CI/conflict/review gates are covered above. No unreviewed source scope is claimed complete.
| # | Finding | Location | Severity |
|---|---|---|---|
| - | No new source blocker found | - | - |
5. Merge recommendation
Can merge once the recorded CI and repository gates are satisfied
Blocking items: No source blocker. Current-head CI and write-capable maintainer review remain independent requirements.
Non-blocking suggestions: None beyond the validation limits above.
Overall: the reviewed source path is coherent; no runtime acceptance is claimed beyond the actual CI result. Daniel has READ permission, so this COMMENT cannot dismiss historical requested changes or satisfy a write-capable maintainer approval gate.
CI and repository state: Signal pull request update: SUCCESS; Build: IN_PROGRESS; Build: in_progress. GitHub reports BLOCKED / CHANGES_REQUESTED.
Verification: Reviewed all changed files and the referenced call sites at 4903f9c2bd224708cb19a7fffafb5c46ee77bc9b against merge base 39c74ce48b0fb5e0318326b8d57a42c7380c40c8. git diff --check passed. I did not build, run tests, or execute SeaTunnel locally.
Review time: 2026-11-27T05:07:21.867573-05:00
Local evidence: git fetch obtained head 4903f9c2bd224708cb19a7fffafb5c46ee77bc9b; git merge-base returned 39c74ce48b0fb5e0318326b8d57a42c7380c40c8; git diff --stat reports 14 files changed, 1454 insertions(+), 42 deletions(-). git show and source searches were used for the entry points above. No local build, unit test, E2E, Docker run or service startup was executed.
DanielLeens
left a comment
There was a problem hiding this comment.
The exact-head Build cited as in progress is now completed/failure. The concrete causes remain those identified in the full review: all-connectors partition 4 JDK 17 fails wrapper bootstrap with HTTP 429/MavenWrapperMain missing, and partition 6 JDK 11 fails the Databend Flink invocation with zero registered TaskManagers and NoResourceAvailableException. Neither is a JDBC mapping assertion. No matching landed dev fix was established, so sync alone is not a verified cure. This attempt has finished: rerun those failed lanes after artifact/resource availability recovers and retain the new exact-head results. My source clearance stands.
5. Merge recommendation
Conclusion: Merge after fixes / remaining repository gates.
Blocking items: No remaining source blocker from Daniel. The current CI/repository gate described above still needs attention.
Non-blocking suggestions: Those from the existing complete review are unchanged; this follow-up adds no source finding. No alternative implementation or unrelated module/dependency patch is requested.
Unchanged head 4903f9c2bd224708cb19a7fffafb5c46ee77bc9b; base dev compare diverged, ahead 35 / behind 2. This drift is recorded separately and alone does not request synchronization. This is a CI/gate correction, not another full source review; no local build/test/runtime execution was performed. Daniel has READ permission, so historical requested-changes controls and an effective write-level approval/dismissal remain maintainer actions. Checked 2026-11-27T10:23:37.836897+00:00.
DanielLeens
left a comment
There was a problem hiding this comment.
The CI fact in my previous follow-up has changed again: exact-head Build attempt 2 is now in progress on this unchanged head. The failures previously identified belong to attempt 1; they are not the result of this active rerun. Please let the existing attempt complete rather than start a duplicate. My source-level blocker remains cleared. The earlier wrapper-429 and Databend/Flink capacity diagnostics remain context for comparison if those same lanes fail again; they do not justify unrelated parser/dependency patches while this rerun is active. This is not yet successful runtime acceptance.
5. Merge recommendation
Conclusion: Merge after the remaining CI and repository gates are satisfied.
Blocking items: No source blocker from Daniel; current-head CI must complete successfully and a write-capable maintainer must provide any effective approval/dismissal required by repository policy.
Non-blocking suggestions: The existing full review is unchanged. No new source finding or alternative implementation is introduced.
Unchanged head 4903f9c2bd224708cb19a7fffafb5c46ee77bc9b; base dev, compare diverged, ahead 35 / behind 2. Branch drift alone does not request synchronization. This corrects the CI/gate fact only; no local build, test or runtime execution was performed. Daniel has READ permission, so this does not dismiss historical requested changes or replace effective maintainer review. Checked 2026-11-27T10:41:26.967182+00:00.
Purpose of this pull request
Close #11878.
Add a new JDBC sink option
multi_table_config.primary_keysto support per-tableprimary key mapping in multi-table generated-SQL scenarios.
When the upstream table name matches one of the configured patterns, the mapped key
columns are used; otherwise it falls back to the existing
primary_keys/ catalogmetadata logic. Inside this new option,
${primary_key}/${unique_key}can bemixed with static columns. The legacy top-level
primary_keyscontract is keptunchanged.
This PR also fixes the config-parsing issue that blocked the feature. SeaTunnel rebuilds
configs with
ConfigFactory.parseMap(...), which treats map keys as Typesafe Config pathexpressions; regex keys such as
^t_nova_.*$contain.and$, so they failed withConfigException$BadPath. The rebuild inConfigShadeUtils.processConfigtherefore now uses aJSON round-trip (
ConfigFactory.parseString(..., ConfigSyntax.JSON)), which keeps plugin optionkeys literal.
The fix is deliberately scoped to avoid a cross-cutting API change:
ReadonlyConfig#toConfig()is left byte-for-byte identical to
dev, so dotted-key semantics are unchanged for all existingcallers. The only shared code touched is
MultiTableFailureHelper#mergeOptions(), which nowmerges the two option maps directly instead of round-tripping through HOCON
withFallback, witha Javadoc note stating that the merge is shallow/top-level.
Review status (F1-F8)
F1 (ReadonlyConfig#toConfig dotted-key round-trip):
Done.
ReadonlyConfig#toConfig()is unchanged and identical todev, so dotted-key pathsemantics for existing callers are untouched. The parsing fix is scoped to
ConfigShadeUtils.processConfig()(JSON round-trip, so regex option keys such as^t_nova_.*$are not read as HOCON paths) and to
MultiTableFailureHelper#mergeOptions()(direct shallow mapmerge instead of
Config#withFallback, with the merge contract documented on the method).Regression test:
ReadableConfigTest#testToConfigPreservesDottedKeyExpansion;MultiTableFailureHelperTest#testMergeOptionsPreservesSpecialCharacterKeyscovers the merge.Neither parsing change is specific to the new option, and both are documented as such:
ConfigShadeUtils.processConfigruns for every job (it is the shade rebuild); the change only makesthe rebuild keep keys literal instead of interpreting them as HOCON paths.
ConfigFactory.parseMapstores dotted keys literally as well (an
envmap with"job.mode"keeps a literal key in bothcases), so the shape of every other option is unchanged and only inputs that previously failed with
ConfigException.BadPathbehave differently.MultiTableFailureHelper#mergeOptionsis shared too:its merge changed from a HOCON deep merge to a shallow top-level merge, where the primary side's
value replaces the fallback side's on a key collision. All of its callers -
MultipleTableJobConfigParser,AbstractSinkExecuteProcessorand its Flink 1.13 variant, the Spark 2 / Spark commonSinkExecuteProcessors (five production call sites), plus the two helpers in the same class - mergesink plugin options against job-env options (disjoint namespaces) or a single-key internal map, so no
caller can hit a nested-object collision; the new contract is documented on the method.
One entry point is still open and is out of scope here: when a job is submitted through the REST
submit-job API with the (default) JSON body, the body is turned into a map and parsed by
ConfigBuilder.of(Map)before the shade rebuild, soConfigFactory.parseMap(...)still rejectsregex keys such as
^t_nova_.*$withConfigException.BadPath. This is documented as a knownlimitation in
docs/en|zh/connectors/sink/Jdbc.md(config files and the HOCON REST body work) andwill be fixed separately; see the Follow-up section.
F2 / F5 (declaration-order semantics):
Done.
JdbcSinkFactory#toCompiledPatternMapcopies the configured patterns into an explicitLinkedHashMap<Pattern, List<String>>, so "the first pattern in declaration order wins" isguaranteed by the code instead of relying on the map implementation that Jackson happens to
produce.
JdbcSinkFactoryTest#testResolveMultiTablePrimaryKeysFromHoconFirstMatchWinsdeclaresoverlapping patterns in a real HOCON string in non-alphabetical order (
^table2$,^table1$,then a catch-all
^table.*$) and asserts that the first declared match wins. That test does not usea hand-built map: it parses the HOCON string with
ConfigFactory.parseString, wraps thesinkblockwith
ReadonlyConfig.fromConfig(...)and callsJdbcSinkFactory#resolveMultiTablePrimaryKeys, whichreads the option and builds the ordered map in
toCompiledPatternMap- the sameHOCON string -> ReadonlyConfig -> option -> toCompiledPatternMapchain the runtime uses (the E2E below covers theremaining engine-level steps: shade rebuild, placeholder pass,
createSink). The English and Chineseconnectors/sink/Jdbc.mddocs state the same rule.F3 (identifier validation for the resolved key columns):
Done.
JdbcSinkFactory#validatePrimaryKeyColumnsrejects blank names and names containing acomma before they are joined into
PRIMARY_KEYS, raisingJDBC-12(
INVALID_MULTI_TABLE_CONFIG). Those are the only unsafe inputs, because the resolved names areinterpolated through the dialect's
quoteIdentifierwhen SQL is generated(
JdbcDialect#getDeleteStatement,MysqlDialect#quoteIdentifier,MysqlCreateTableSqlBuilder#buildPrimaryKeySql); a comma would collide with the delimiter of thecomma-joined
primary_keysvalue and a blank name would produce an empty list element. Test:JdbcSinkFactoryTest#testFactoryContextWithMultiTableConfigInvalidColumnFails.Embedded quote characters are deliberately not rejected: the dialect quoting only wraps the name
(
MysqlDialect#quoteIdentifierreturns a backtick-wrapped name without escaping, andCatalogUtils#quoteIdentifierbehaves the same), so a name containing the dialect quote characterwould already be unusable in the generated SQL. Such a name cannot come from the
${primary_key}/${unique_key}expansion (those are upstream catalog column names) and would have to be typed by theuser, so it surfaces as a database error rather than as a silently wrong key. A dialect-specific
quote-character rule is left as a deliberate follow-up instead of half-implementing it here.
F4 (connector-level
${primary_key}/${unique_key}vs engine-level TablePlaceholder):The engine pass runs first (
TableSinkFactoryContext#replacePlaceholderAndCreate->TablePlaceholderProcessor#replaceTablePlaceholder), but it only rewrites top-levelStringvalues and single-element
Stringlists and never descends into nested objects, so themulti_table_configmap reaches the connector untouched. The connector then expands${primary_key}/${unique_key}per matched table inJdbcSinkFactory#expandPrimaryKeyPlaceholder. When a matched table uses such a placeholder butthe upstream catalog table has no primary key (or no unique key), the job fails fast with
JDBC-12; it does not silently fall back and does not leave the literal placeholder inPRIMARY_KEYS. Documented indocs/{en,zh}/introduction/configuration/sink-options-placeholders.mdand pinned by
JdbcSinkFactoryTest#testPlaceholderOrderBetweenEngineAndConnectorPasses, whichasserts that the engine pass expands a top-level
primary_keys = ["${primary_key}"], leaves thenested
multi_table_config.primary_keysmap untouched, and that the connector expands itafterwards. The fail-fast path is covered by
JdbcSinkFactoryTest#testResolveMultiTablePrimaryKeysMissingPrimaryKeyFails.F5: see F2.
F6 (regex validation -> JDBC-12):
Done. Every configured pattern is compiled up front in
toCompiledPatternMap->compilePattern, which mapsPatternSyntaxExceptiontoJdbcConnectorExceptioncarryingJDBC-12. Tests:JdbcSinkFactoryTest#testResolveMultiTablePrimaryKeysInvalidRegexFailsandJdbcSinkFactoryTest#testCompilePatternInvalidFails. Compiled patterns are memoized in abounded, access-ordered LRU cache (
MAX_CACHED_PATTERNS = 256, wrapped inCollections.synchronizedMap), so each distinct pattern is compiled once per JVM. 256 sitscomfortably above the number of distinct patterns a busy deployment configures (a handful to a
few dozen), and exceeding it only evicts an older entry that is recompiled on next use.
F7 (tests):
Done, no longer deferred. Both halves are in this PR.
The
toConfig()regression test already exists and is part of this PR's diff:ReadableConfigTest#testToConfigPreservesDottedKeyExpansion(seatunnel-api, line 383) assertsthat a dotted map key such as
a.bstill expands through the dotted path.The engine-level E2E for the new option is
JdbcMysqlMultipleTablesIT#testMysqlJdbcMultipleTableE2e. It uses two dedicated source tables(
source.mtc_table1/source.mtc_table2) whose key columns areNOT NULL, pointsjdbc_mysql_source_and_sink_with_multi_table_config.confat them, and lets the sink create thetarget tables (
schema_save_mode = "CREATE_SCHEMA_WHEN_NOT_EXIST"). It then asserts the resolvedprimary keys read from
information_schema.STATISTICS(sink.mtc_table1->c_int, c_integer;sink.mtc_table2->c_mediumint) plus the table row counts. It runs on the Zeta, Flink andSpark containers in CI.
The dedicated fixture (rather than the shared
source.table1/source.table2, which the othertest methods depend on) is required because of the pre-existing MySQL DDL gap described in the
Follow-up section: a column that is explicitly declared
NULLcannot be part of aPRIMARY KEY.F8 (option key naming):
Done. The key is fully snake_case -
multi_table_config- inJdbcSinkOptions, the English andChinese docs, the E2E config and all tests; no mixed
multi-table_configspelling remains in thePR.
Additional fix from the previous review round (not part of F1-F8):
The patterns were previously matched against the resolved sink table name, so combining
multi_table_config.primary_keyswithtable/tablePrefix/tableSuffixsilently defeatedthe mapping and the sink fell back to catalog metadata.
JdbcSinkFactory#createSinknow keeps theupstream
CatalogTableand matches on that, which is what the docs already described. Regressiontest:
JdbcSinkFactoryTest#testFactoryContextWithMultiTableConfigMatchesUpstreamTableName.Does this PR introduce any user-facing change?
Yes. Adds a new optional JDBC sink option
multi_table_config.Semantics:
full-match semantics (
tableName.matches(pattern)).${primary_key}and${unique_key}aresupported only inside this option and can be mixed with static columns.
(top-level
primary_keys-> catalog primary key -> first unique key -> plain INSERT).${primary_key}/${unique_key}but the upstream table hasno primary/unique key, the job fails with a clear error.
No existing option is renamed, removed, or changed in default behavior.
Example configurations
Example 1
Example 2
Table DDL
The source tables are created manually on the upstream side; the target tables are created by
generate_sink_sql = true.multi_table_config.primary_keysdecides which key columns are usedwhen writing to the target tables, which shows up as the key columns of the generated
upsert / delete statements.
To keep the transform-derived
DATA_SOURCEcolumn (a length-less STRING) from being created asLONGTEXTby the MySQL dialect - which cannot be part of a primary key - the exampleconfigurations use
DefineSinkTypeto declare it asVARCHAR(32). The source table DDL is listedbelow, followed by the target table DDL as created by the sink.
Demo 1 source tables
Demo 1 target tables (created by the sink)
Demo 2 source tables
Demo 2 target tables (created by the sink)
Generated SQL
Below are the upsert / delete statements that the MySQL JDBC sink actually generated after
running the two demos above. Each target table uses the different key columns assigned to it by
multi_table_config.primary_keys.How was this patch tested?
Added unit tests:
JdbcSinkFactoryTest: mapping hit, fallback to legacyprimary_keys, missing upstreamprimary key error, first-match-wins, string value handling, invalid regex, blank/comma column
rejection, compiled-pattern caching, matching against the upstream table name when the sink
table name is remapped, and the full factory-context path.
JdbcSinkFactoryTest#testResolveMultiTablePrimaryKeysFromHoconFirstMatchWins: parses a realHOCON config string whose patterns overlap in non-alphabetical declaration order (
^table2$,^table1$, then a catch-all^table.*$) and asserts that the first declared match wins.JdbcSinkFactoryTest#testFactoryContextWithMultiTableConfigMatchesUpstreamTableName: runs thewhole
createSinkpath with a statictableremap and asserts the pattern still resolvesagainst the upstream table name.
JdbcSinkFactoryTest#testPlaceholderOrderBetweenEngineAndConnectorPasses: pins the orderbetween the engine-level TablePlaceholder pass and the connector-level expansion (the nested
multi_table_config.primary_keysmap reaches the sink untouched and is expanded there).ConfigShadeTest#testDecryptPreservesSpecialCharacterKeys: special-character config keys arepreserved after
decryptConfig.ReadableConfigTest#testToConfigPreservesDottedKeyExpansion: dotted-key expansion is preservedfor existing
ReadonlyConfig#toConfigcallers.MultiTableFailureHelperTest#testMergeOptionsPreservesSpecialCharacterKeys: overlapping scalaroption keys keep the primary-side value under the direct map merge.
ConfigShadeTest#testDecryptPreservesOrdinaryConfigShapes: an unquoted dotted key, a quoteddotted key inside a nested map and numeric values come back unchanged from
decryptConfig.JdbcSinkFactoryTest#testLegacyPrimaryKeysStillRebuildCatalogPrimaryKey: the legacy top-levelprimary_keysbranch still rebuilds the catalog primary key after the refactor.Engine-level E2E coverage (exercised by CI on the Zeta, Flink and Spark containers):
JdbcMysqlMultipleTablesIT#testMysqlJdbcMultipleTableE2edrops the dedicated target tables andruns
seatunnel-e2e/seatunnel-connector-v2-e2e/connector-jdbc-e2e/connector-jdbc-e2e-part-1/src/test/resources/jdbc_mysql_source_and_sink_with_multi_table_config.conf.The job reads two dedicated source tables (
source.mtc_table1/source.mtc_table2) whose keycolumns are
NOT NULL, so the sink can create the target tables itself(
schema_save_mode = "CREATE_SCHEMA_WHEN_NOT_EXIST") and the resolved key columns end up in thegenerated create-table DDL. The
NOT NULLkey columns are required because of the pre-existingMySQL DDL gap described in the Follow-up section, and the shared
source.table1/source.table2fixture used by the other test methods is left untouched.information_schema.STATISTICS(
sink.mtc_table1->c_int, c_integer,sink.mtc_table2->c_mediumint) plus the table rowcounts, which fails if the per-table mapping or the declaration order is lost.
primary_keys = ["id"]must not be used, anda catch-all pattern declared last must not win.
Manually verified with MySQL-CDC -> JDBC using the two demo configurations above
(
generate_sink_sql = true), and confirmed the auto-created target tables (withDefineSinkTypesettingDATA_SOURCEtoVARCHAR(32)) together with the generatedupsert / delete statements match the expected per-table primary key mapping.
Also run
./mvnw spotless:applyand./mvnw -pl :connector-jdbc-e2e-part-1 -am -DskipTests -Dskip.ui=true packageto compile theE2E module locally.
Follow-up
MysqlCreateTableSqlBuilder(and theOceanBase MySQL-mode twin) emit an explicit
NULLfor nullable columns even when those columnsare part of a
PRIMARY KEY, which MySQL rejects withER_PRIMARY_CANT_HAVE_NULL(1171,All parts of a PRIMARY KEY must be NOT NULL). It affects the existing top-levelprimary_keysoption as well, so it is not specific to
multi_table_config. Tracked in[Bug][Connector-V2][JDBC] MySQL sink auto-create fails when a configured primary key column is nullable #12415 and deliberately left out of this PR to keep the diff scoped; a follow-up
PR will emit
NOT NULLfor key columns plus a unit test inMysqlCreateTableSqlBuilderTest.JDBC-12when a static primary key column does not exist inthe upstream schema. Not done here because the check has to account for
field_idecaseconversion, so it deserves its own change.
ConfigBuilder.of(Map)(used byRestUtil.buildConfig/RestUtil.buildConfigList) still parses the JSON body withConfigFactory.parseMap(...), whichrejects regex keys such as
^t_nova_.*$withConfigException.BadPath. Documented as a knownlimitation in the JDBC sink docs; the fix (rebuild the map with literal keys when a key is not a
valid path) will be tracked in a separate issue so this PR stays scoped.
Check list
incompatible-changes.mdto describe the incompatibility caused by this PR.