Repository navigation
feat: multi-table INSERT ALL / INSERT FIRST ... INTO ... SELECT (#27470) - #27560
Conversation
…ixorigin#27470) Snowflake-style multi-table insert: INSERT ALL INTO t1 [(cols)] [VALUES (...)] INTO t2 ... SELECT ... INSERT {ALL | FIRST} WHEN cond THEN INTO t1 ... [INTO ...] [WHEN ... THEN INTO ...] [ELSE INTO ...] SELECT ... Parser: new tree.MultiInsert AST (INTO clauses with optional column list and VALUES expressions evaluated over the source query's output columns); grammar with no new conflicts (a parenthesized source directly after a bare INTO is rejected, since it is indistinguishable from a column list). Planner: the source query is bound once and materialized in a SINK (step 0). Every target table gets its own write step reading it through a SINK_SCAN -> [FILTER on the WHEN condition] -> PROJECT (VALUES) and then the regular modern insert pipeline (casts/defaults/auto-increment, lock, dedup joins, MULTI_UPDATE), so primary/unique keys and B-tree indexes are maintained exactly as for a single INSERT, and IVF/fulltext indexes get their usual maintenance steps. INSERT FIRST and ELSE are expressed as "earlier condition IS NOT TRUE" filters, so a NULL condition never matches. When the same table appears in several INTO clauses, the clauses are widened to the union of their column lists and merged with UNION ALL in front of one write pipeline, so duplicate keys produced by different clauses are rejected like in-batch duplicates of one INSERT ... SELECT. Affected rows are summed over targets; a failure in any target rolls back the whole statement. Tables with foreign keys and external tables are rejected, per the issue's scope. Frontend: MultiInsert is classified as DML (transactions, INSERT privilege on every target, last_insert_id, db remapping, PREPARE).
- multi_insert_conditional.sql (107): INSERT ALL vs INSERT FIRST over overlapping WHEN conditions, ELSE, NULL conditions, subquery/LIKE/BETWEEN/ IS NULL conditions, computed source aliases, several INTOs per WHEN, the same table under several WHENs, aggregate/join/union/limit/distinct/empty sources, atomicity and explicit transactions. Every assertion is checked against the equivalent filtered SELECT or a join between targets. - multi_insert_schema.sql (74): destination tables with different shapes, types and constraints (unique/secondary/composite/fake pk, auto-increment, NOT NULL, CHECK, generated, cluster by), json/enum/binary/date conversions, other-database and temporary targets, a target that is also the source, case-insensitive and qualified column lists, widened same-table clauses. - multi_insert_big.sql (73): 300k rows x ~520 bytes so every target's Multi Update flushes S3 objects (asserted through metadata_scan), FIRST/ALL over the big source, a merged 600k-row same-table write, a late duplicate that rolls back already-flushed objects of another target, mo_ctl flush and re-read, big insert in a rolled-back transaction. All four multi_insert*.sql files pass in mo-tester compare mode.
…ches (matrixorigin#27470) multi_insert_skew.sql (82): on the 300k-row source, one WHEN takes (almost) everything while siblings take 3 rows, 1 row or nothing; an ELSE that never fires; WHENs that never match; ELSE taking everything; nothing matching with no ELSE (statement succeeds, writes nothing); empty source; skew in the other direction (1 wide row vs 299,999 narrow rows); the same table fed by a dominant clause and an empty one; an empty target still enforcing its constraints later; small-scale replicas of every shape. Object assertions (metadata_scan) are restricted to the deterministic cases: the write mode is chosen at compile time from the planner estimate (Outcnt x SingleLineSizeEstimate > DistributedThreshold), so only dominant targets (objects for every row) and empty targets (no objects in either mode) are checked. multi_insert_big.sql comments corrected accordingly (its narrow 300k-row target is on the S3 path too) and the doc's test plan describes the rule and the new file.
…ds for multi-table INSERT tests
…INSERT and why the sink design was kept
Qodo reviews are paused for this user.Troubleshooting steps vary by plan Learn more → On a Teams plan? Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center? |
…ooks - remap_db: the target's schema was remapped twice (remapDbInTableExpr on the table expr, then remapInsertTarget on the same SchemaName field); remapInsertTarget now only rewrites the qualified column names, as the table expr remap already handles the schema. Test covers targets, VALUES, WHEN conditions and the source query. - compile2: rewriteAutoModeToPre / forceModePre now reach a MultiInsert's source query like Insert.Rows / Replace.Rows, so a vector search in auto mode inside INSERT ALL ... SELECT gets the pre-mode rebuild.
fengttt
left a comment
There was a problem hiding this comment.
Self-review of the multi-insert change (multi-angle sweep: correctness, control path, resource lifecycle, compatibility, failure modes, contract, performance; functional closure of parser → planner → compile → frontend → tests). Two fixes and several decision-log items; each inline thread says which.
…atrixorigin#27560 review) @iamlinjunhong's P2. The level-i selector projection rebuilt "did any earlier selector match" from all i earlier selectors, so the routing bookkeeping was O(W^2) in plan size and per-row work -- at the 127-clause cap, thousands of prior-selector visits for every source row, contradicting the linear clause-cost bound the cap was justified with. INSERT FIRST now uses two projections per WHEN: level i-A: sel_i = if(matched, false, cond_i) level i-B: matched = matched OR istrue(sel_i) The split is required because a projection cannot reference its own outputs: matched_i needs sel_i, produced in the same projection, so it is accumulated in the next one from materialized columns. Each level is now O(1) and the column layout is stable (source, carriers, matched, selectors). ELSE under FIRST also becomes one column test instead of one term per WHEN, since the flag already answers "did anything claim this row". INSERT ALL is unchanged: with no first-match rule there is no cumulative flag, and its ELSE genuinely has to test every selector. Semantics re-verified on a server build: volatile FIRST still partitions exactly (1000 rows, 0 overlap), an unreachable erroring predicate is still skipped, and three-way FIRST + ELSE routing is 300/300/400. TestMultiInsertFirstSelectorChainIsLinear pins the property: doubling the WHEN count must not more than triple the boolean bookkeeping, so a return to the prefix rebuild fails the test rather than only showing up in a benchmark.
aunjgr
left a comment
There was a problem hiding this comment.
Reviewed exact head b33a62e01ee35cb3239cf6daab75deace1384177 against merge base ae12701a888fac102e9641cc7cbb8706527366d8.
I audited the complete parser → AST/remap/rewrite → planner → sink/branch/write-step → privilege/status/transaction closure, including the latest fixes. Each INSERT FIRST condition is now lazily masked per row and evaluated once, with a cumulative matched column that keeps routing linear; INSERT ALL selectors remain one evaluation shared by every target. Unmaskable later-WHEN and conditional-VALUES subqueries are rejected before flattening. Same-table clauses share one dedup/write pipeline, the auto-increment guard is conservative across prepare-time sql_mode changes, and multi-target LAST_INSERT_ID no longer assigns meaning to unrelated counters. Source/target privileges, irregular index maintenance, positional sink pruning, affected-row aggregation, cancellation/drain ownership, prepared rebuild, and atomic failure paths are closed. I found no blocking issue.
XuPeng-SH
left a comment
There was a problem hiding this comment.
Requesting changes on exact head 9a98ef9315bdb0e3d62a0637d24a8be84e218caa.
[P1 correctness] Restore the session-visible process value when suppressing an ambiguous multi-target insert id.
SetStatementLastInsertIDIfEarlier updates both StatementLastInsertID and LastInsertID (pkg/vm/process/types.go), but the new MultiInsert response path only declines to copy the statement value into the OK packet/session. It never restores proc.LastInsertID. doComQuery reuses that process for every statement in one COM_QUERY and resets only StatementLastInsertID before the next statement (mysql_cmd_executor.go:5567). Therefore the suppressed cross-table minimum leaks into the next statement in the same request.
I reproduced this deterministically with a focused frontend test: establish session/process LAST_INSERT_ID=51, simulate two target PRE_INSERT publications 101 and 1, run respStatus with two auto-increment PRE_INSERT nodes. The OK packet reports 0 and ses.GetLastInsertID() remains 51, but proc.GetLastInsertID() is 1. Thus INSERT ALL ...; SELECT LAST_INSERT_ID(); submitted as one multi-statement COM_QUERY returns the arbitrary suppressed value instead of 51. Separate-statement BVT calls hide the bug because a new process is initialized from the session on the next request.
Please keep the statement coordinator separate from session-visible state, or restore proc.LastInsertID from the session baseline on the ambiguous path before another statement can run. Add a frontend unit regression that checks all three states (OK packet, Session, Process) and a same-COM_QUERY control.
[P2 performance] The FIRST selector fix still builds and executes O(W^2) projection bookkeeping; the new test only counts boolean function nodes and misses it.
Both projection levels carry every prior selector (for j := 0; j < i at bind_multi_insert.go:443 and for j := 0; j <= i at line 462). Across W WHENs that is W^2 column expressions/executors. Projection.Prepare creates an executor per expression and Projection.Call / EvalProjection iterates every executor for every input batch, so these are not free plan-only references. My independent plan probe measured:
WHEN=8 PROJECT_exprs=129
WHEN=32 PROJECT_exprs=1281
WHEN=64 PROJECT_exprs=4609
WHEN=126 PROJECT_exprs=16885
The committed TestMultiInsertFirstSelectorChainIsLinear counts only or, istrue, and isnottrue, so it stays green while total projection work is quadratic. Please either make the full selector materialization linear or make the supported bound/performance contract honest and test total plan/executor work rather than a selected subset of function names.
[P2 documentation] The latest restrictions are not reflected consistently in the design document. The binding section still says subqueries in WHEN and VALUES are flattened, without documenting that later FIRST WHEN subqueries and every conditional VALUES subquery are now rejected. The same-table coverage row also still says the expression form is accepted under NO_AUTO_VALUE_ON_ZERO, while 06ce2900c3 deliberately rejects non-constant expressions in every mode. Please update the public limitations and coverage claims with the code change.
Validation: full pkg/sql/plan, pkg/sql/parsers/..., pkg/frontend, and pkg/sql/compile tests passed; focused multi-insert/parser/frontend/compile race tests passed 10x. The P1 probe fails only on the expected process-state assertion (expected 51, actual 1).
…origin#27560 review) XuPeng-SH, three findings on 9a98ef9. [P1] Suppressing the ambiguous multi-target insert id was not enough. SetStatementLastInsertIDIfEarlier writes the session-visible LastInsertID as well as the statement one, and doComQuery reuses the process for the next statement of the same COM_QUERY while resetting only the statement value. The suppressed cross-table minimum therefore answered the next statement's LAST_INSERT_ID(). The ambiguous path now puts the session's value back on the process. Reproduced exactly as reported -- session/process 51, publications 101 and 1, OK packet 0 and session 51 but process 1 -- and the new frontend test asserts all three states plus the same-COM_QUERY control (it fails without the fix with expected 51, actual 1). [P2 perf] The FIRST selector chain was quadratic and the test hid it. Carrying one boolean selector per WHEN made each level re-project all the earlier ones -- W^2 expressions, and W^2 executors built by Projection.Prepare and run by Projection.Call for every batch. INSERT FIRST now carries a single int32 route column holding the index of the WHEN that claimed the row (-1 for none): route_i = if(route_{i-1} >= 0, route_{i-1}, if(cond_i, i, -1)) one projection per WHEN instead of two, and a branch filters on `route = i` rather than a boolean, so ELSE is `route = -1`. Laziness is unchanged and now rests on nesting: EvalIff evaluates a false branch only on the rows whose condition was false and passes that selection to the child executor, which a nested if propagates -- so cond_i still runs only on rows an earlier WHEN did not claim. Measured total plan work is now 215 expressions for 8 WHENs and 815 for 32, 25 per added WHEN, against 129 and 1281 before. INSERT ALL is unchanged: a row may match several WHENs, so it keeps one selector per WHEN in a single projection. TestMultiInsertFirstSelectorChainIsLinear counted only or/istrue/isnottrue and stayed green while the real work was quadratic. It is replaced by TestMultiInsertFirstRoutingWorkIsLinear, which counts every expression node in every ProjectList and FilterList and asserts both the growth ratio and a bounded per-WHEN cost. [P2 docs] The design doc now documents the route column, that a subquery is rejected in a later FIRST WHEN and in the VALUES of any conditional clause (flattening would run it for rows the branch never receives), and that a non-constant expression in a merged clause's auto_increment column is rejected in every sql_mode, not accepted under NO_AUTO_VALUE_ON_ZERO. Multi-insert BVT: 518/518 statements green across all five files. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_016qdL5akNrbUfXfqjC659n6
|
All three fixed in [P1] Process state restored. You were right that declining to copy the value was not enough: } else {
execCtx.proc.SetLastInsertID(ses.GetLastInsertID())
}
[P2 perf] The chain is now genuinely linear, and the test measures total work. You are right that the pass-through was the quadratic term and that my test measured a subset of function names, so it could not see it. One projection per WHEN instead of two, one decision column instead of Laziness is preserved and now rests on the nesting: Measured total plan work, counting every expression node in every
25 expressions per added WHEN, flat, versus 48 and rising.
[P2 docs] Updated. The Routing section now describes the two shapes separately (route column for FIRST, per-WHEN selectors for ALL) with the laziness and linearity arguments. The binding section documents that a subquery is rejected in a later FIRST Validation. |
XuPeng-SH
left a comment
There was a problem hiding this comment.
Requesting changes on a3a519c.
The previous blockers are fixed in this head: ambiguous multi-target insert IDs no longer leak process state, INSERT FIRST routing is linear and preserves lazy WHEN evaluation, and the focused/full normal plus race suites pass.
[P1] Branch subqueries lose statement-level binding metadata. The source bind stores stmt.Source.RewriteOption in srcCtx.remapOption, but appendMultiInsertSelectors creates condCtx with NewBindContext(builder, nil), and bindMultiInsertBranchSource creates bCtx the same way; both copy only the snapshot. Consequently, supported subqueries in WHEN predicates and VALUES expressions are extra read sides that bypass statement rewrite policy, and they also cannot resolve statement-level CTEs.
I reproduced both paths with temporary checked planner tests:
- Configure an inline rewrite from tpch.nation to SELECT r_regionkey FROM tpch.region. A WHEN EXISTS subquery and an unconditional VALUES scalar subquery that still reference n_nationkey both plan successfully. If rewrite reached those reads, planning must fail because the rewritten relation has no n_nationkey.
- A WITH vip AS (...) INSERT ALL statement whose WHEN subquery reads vip fails with table vip does not exist.
Please propagate the statement declaration context needed by selector and VALUES subqueries, including CTE/rewrite/remap/snapshot metadata as appropriate, without accidentally inheriting the SELECT source row bindings. Add checked regressions for both WHEN and unconditional VALUES subqueries under rewrite policy, plus statement-level CTE references from those two locations.
Validation on this exact head:
- existing MultiInsert tests: PASS
- focused race/stress, count=20: PASS
- full related plan/frontend/compile/parser packages: PASS
- full related packages with -race: PASS
- the two temporary rewrite and CTE counterexamples: FAIL as described
Lifecycle Q1-Q3 review found no additional confirmed blocker: sink edges remain bounded, same-table UNION stays on the eager path, and failure cancellation/drain uses the existing ownership paths. The requested change is for functional and read-policy closure.
…origin#27560 review) XuPeng-SH, P1 on a3a519c: a subquery in a WHEN condition or in a clause's VALUES is another read performed by this statement, but both were bound in a fresh root context (NewBindContext(builder, nil) plus a snapshot copy). Two things followed, both reproduced as described: - Read-policy bypass. The source bind puts the statement's RewriteOption on srcCtx.remapOption; a fresh root has none, so a branch subquery read the base table directly even when the statement's rewrite policy had remapped it. - Statement CTEs were unreachable: `WITH vip AS (...) INSERT ALL ... WHEN EXISTS (SELECT ... FROM vip)` failed with `table vip does not exist`. Both now bind under newCTEDeclarationContext(builder, srcCtx), which already exists for exactly this shape: it carries the declaration scope -- CTEs, rewrite/remap option, snapshot, view state -- and then detaches from srcCtx, so the source block's own row bindings are NOT inherited and the source columns remain reachable only through the alias the binder adds. The write pipeline's context is deliberately left alone: a target is written, not read, so it must not inherit a read rewrite. Regressions cover both locations for both failures: TestMultiInsertBranchSubqueriesObeyRewritePolicy drives the real `/*+ {"rewrites": ...} */` hint path through AddRewriteHints, with a no-rewrite control, and asserts planning now fails because the rewritten relation lacks the column the subquery resolves; TestMultiInsertBranchSubqueriesSeeStatementCTEs asserts a statement CTE resolves from both places. All four subtests fail without the fix -- the rewrite ones with "An error is expected but got nil", the CTE ones with `table "vip" does not exist`. Multi-insert BVT: 518/518 green. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_016qdL5akNrbUfXfqjC659n6
|
Fixed in Cause. Fix. Both now bind under The write pipeline's context ( Regressions, both locations for both failures:
All four subtests fail without the fix, with your symptoms: the rewrite pair as Validation on this head. The design doc now records the binding scope and why the write pipeline is excluded. |
XuPeng-SH
left a comment
There was a problem hiding this comment.
Requesting changes on f5c29c6.
[P1] Preserve the statement and source CTE scopes separately when the source SELECT has its own WITH.
The parser accepts a statement-level WITH before INSERT and a separate WITH on the trailing source SELECT. These are distinct lexical scopes: WHEN predicates and INTO VALUES subqueries may see the statement CTEs, while source-local CTEs must remain private to the source query.
The current implementation collapses those scopes:
- bindMultiInsert moves stmt.With to stmt.Source.With only when Source.With is nil (pkg/sql/plan/bind_multi_insert.go:177-178). If the source already has a WITH, the statement CTE is never installed in srcCtx.
- appendMultiInsertSelectors and bindMultiInsertBranchSource then derive their branch declaration contexts from srcCtx. This both loses the outer CTE and exposes the source-local CTE to syntactically preceding WHEN/VALUES expressions.
I reproduced all four directions with temporary planner tests:
- WHEN EXISTS referencing a statement-level outer_vip, with a separate source WITH, fails with table outer_vip does not exist.
- An unconditional VALUES scalar subquery referencing outer_vip fails the same way.
- WHEN EXISTS referencing source_only, declared only in the trailing source WITH, incorrectly plans successfully.
- An unconditional VALUES scalar subquery referencing source_only also incorrectly plans successfully.
This rejects valid SQL and accepts invalid SQL whose branch routing/value can be computed from the wrong namespace, so it is a data-correctness blocker.
Please model the declaration scopes independently: source binding should see the outer statement CTEs plus its own local CTEs; WHEN/VALUES branch contexts should see the statement CTEs and statement rewrite/remap/snapshot metadata, but neither source-local CTEs nor source row bindings. Add checked regressions for both WHEN and unconditional VALUES in both directions.
The previous blocker is fixed for the simple no-source-WITH case: the added rewrite-policy and statement-CTE tests pass, as do the routing, same-table merge, auto-increment, sink-pruning, and irregular-index regressions.
Validation on this exact head:
- all affected Go packages: PASS
- go vet on all affected Go packages: PASS
- focused MultiInsert race suite, count=10: PASS
- four temporary dual-scope counterexamples: FAIL as described
Lifecycle Q1-Q3 review found no additional confirmed blocker: sink fan-out remains bounded, synthesized same-table UNION stays on the eager path, and failure cancellation/drain follows the existing ownership paths.
…review) XuPeng-SH, P1 on f5c29c6. A statement-level WITH and a WITH on the trailing source SELECT are different lexical scopes and can both appear; the code collapsed them two ways at once: - bindMultiInsert moved stmt.With into stmt.Source.With only when the source had no WITH of its own, so with both present the statement CTE was never installed anywhere. `WITH outer AS (...) INSERT ALL WHEN EXISTS (... outer ...) ... WITH local AS (...) SELECT ...` failed with `table "outer_vip" does not exist` -- valid SQL rejected. - the branch contexts were derived from the source context, so a CTE the source declared privately, after the WHEN/VALUES that reference it, was visible to them -- invalid SQL accepted, with routing and values computed from the wrong namespace. The scopes are now modelled independently. The statement's CTEs are installed on the statement bind context via preprocessCte, so the source (its child) sees them and a source-local WITH stays on the source context alone. The statement's rewrite option -- which AddRewriteHints attaches to the source query but which governs every read the statement performs -- is lifted to the statement context too, and WHEN/VALUES bind under a declaration context built from that: statement CTEs plus statement rewrite/remap/snapshot, and neither source-local CTEs nor source row bindings. TestMultiInsertBranchSubqueriesSeeStatementScopeOnly covers both directions for both locations. All four subtests fail without the fix, with the reported symptoms: `table "outer_vip" does not exist` for the two that must plan, `An error is expected but got nil` for the two that must be rejected. Multi-insert BVT: 518/518 green. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_016qdL5akNrbUfXfqjC659n6
|
Fixed in The two scopes are now modelled independently.
The write pipeline's context is still a plain root — a target is written, not read.
Worth noting for anyone reproducing: the first two only fail if the source's Validation on this head. |
XuPeng-SH
left a comment
There was a problem hiding this comment.
Requesting changes on exact head 7cf290fbee1e05a9b7c6d1cff59994e94f787320.
The previous statement-vs-source CTE visibility blocker is fixed: outer CTEs remain visible to WHEN/VALUES and the source, while source-local CTEs no longer leak into branch scopes. One P1 read-policy closure gap remains.
[P1 correctness/policy] Install the statement rewrite policy before snapshotting statement CTE declaration contexts.
In bindMultiInsert, preprocessCte(..., bindCtx) runs at lines 191-194, and only afterwards is stmt.Source.RewriteOption assigned to bindCtx.remapOption at lines 199-200. preprocessCte immediately creates each CTERef.declarationCtx through newCTEDeclarationContext; that context copies remapOption and then detaches from bindCtx. The later assignment therefore reaches the source and branch contexts, but never the already-created statement CTE contexts.
I reproduced the bypass with a temporary checked planner test:
/*+ {"rewrites": {"tpch.dept": "select 1 as x"}} */
WITH d AS (SELECT deptno FROM dept)
INSERT ALL INTO t2 (a, b) VALUES (deptno, 2)
SELECT deptno FROM d;The no-hint control plans. Under the rewrite, every read of tpch.dept should resolve to a relation that has only x, so the CTE body must fail on deptno. This head instead plans successfully: the statement CTE reads the unrewritten base table. The new direct WHEN/VALUES rewrite tests stay green because those declaration contexts are created after the assignment, so they do not cover this path.
Please lift the rewrite/remap option onto bindCtx before preprocessCte snapshots any declaration context (or explicitly propagate the complete policy into every CTE declaration context). Add a regression for a statement CTE body, ideally covering both a table rewrite and database remap, including the case where the trailing source has its own WITH.
Validation on this exact head:
- full
pkg/sql/plan,pkg/sql/parsers/...,pkg/frontend, andpkg/sql/compile: PASS - focused multi-insert/parser/frontend/compile
-race -count=5: PASS - temporary statement-CTE rewrite counterexample: FAIL as described; removed after verification
The broader correctness/performance/unhappy-path recheck found no additional confirmed blocker: FIRST routing remains linear and lazy, same-table grouping and privilege extraction remain closed, and sink cancellation/backpressure follows the existing bounded ownership paths.
…rixorigin#27560 review) XuPeng-SH, P1 on 7cf290f. preprocessCte creates a declaration context per statement CTE through newCTEDeclarationContext, and that context copies remapOption and then detaches from bindCtx. Assigning the statement's rewrite policy after preprocessCte therefore reached the source and the branch contexts but never the CTE bodies, so /*+ {"rewrites": {"tpch.dept": "select 1 as x"}} */ WITH d AS (SELECT deptno FROM dept) INSERT ALL INTO t2 (a, b) VALUES (deptno, 2) SELECT deptno FROM d planned successfully: the CTE read the unrewritten base table. The existing WHEN/VALUES rewrite tests could not see it, since those contexts are built after the assignment. The assignment now precedes preprocessCte. TestMultiInsertStatementCTEObeysRewritePolicy covers a statement CTE body under a table rewrite, with and without the trailing source declaring its own WITH, each with a no-policy control; both fail without the fix with "An error is expected but got nil". The requested remapdb direction is not asserted: the planner mock's Resolve ignores the database name and stamps back whatever was requested, so a database remap has no observable effect under it -- both policies travel on the same remapOption, which is what the ordering governs. Multi-insert BVT: 518/518 green. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_016qdL5akNrbUfXfqjC659n6
|
Fixed in Fix. Regression.
Both fail without the fix with One direction I did not assert, and why. I could not make Validation on this head. |
XuPeng-SH
left a comment
There was a problem hiding this comment.
Requesting changes on exact head a9d7f1bb8ffbcda5c0839559df1c27abf191795c.
The previous correctness/read-policy blockers are fixed in this head. The source-once + per-physical-table write-pipeline design is sound, same-table clauses converge before one dedup/MULTI_UPDATE, and the focused routing/frontend/parser plus sink lifecycle race suites pass. One performance/design blocker remains.
[P2 performance] INSERT FIRST routing is still quadratic for a wide source; the committed linearity test only exercises one source column.
carriedPrefix at bind_multi_insert.go:426-438 re-emits every source column and every distinct condition carrier at each of the W projection levels. Therefore total projection work is O(W * (M + C)), where M is the source width and C is the number of distinct columns read by WHEN conditions. A normal shape with W conditions reading W different source outputs has M/C proportional to W, so the optimized plan and runtime executor work are still O(W²). This is not plan-only bookkeeping: Projection.Prepare creates one executor per ProjectList entry and Projection.Call evaluates every executor for every input batch.
I reproduced it with a temporary checked planner probe using the same total-expression walk as TestMultiInsertFirstRoutingWorkIsLinear, but generating WHEN c0 = 0 ... WHEN cN = 0 over SELECT 0 AS c0, ... N AS cN:
WHENs total exprs PROJECT nodes max PROJECT width
8 199 19 9
16 459 35 17
32 1171 67 33
64 3363 131 65
126 10524 255 127
The current regression at bind_multi_insert_test.go:583-640 always binds every condition and every target value to the single deptno column. It proves only the fixed-width special case and therefore stays green while the documented per-WHEN bounded-work contract is false.
Please build the lazy first-match route in a bounded number of projections—for example, normalize the final child/carriers once and emit one nested if(cond_0, 0, if(cond_1, 1, ... -1)) route expression, relying on the same recursive EvalIff selection propagation—or an equivalent O(M + C + W) shape. Add a regression where added WHENs also introduce distinct source columns and count the complete optimized plan work.
Unhappy-path/lifecycle recheck found no additional blocker: sink edges are bounded, the synthesized same-table UNION remains eager on this plan shape, and failure cancellation/release follows the existing paths. Focused affected-package and sink/merge race tests passed repeatedly.
…ixorigin#27560 review) XuPeng-SH, P2 on a9d7f1b. The route column removed one quadratic term but not the other: carriedPrefix re-emitted every source column and every condition carrier at each of the W levels, so the cost was O(W * (M + C)). For the ordinary shape where W conditions read W different source columns, M and C grow with W and the plan is quadratic again. My linearity test bound every condition to the single deptno column, so M and C were constant and it could not see this. The chain is gone. The whole decision is one nested expression in one projection above the conditions' own node: route = if(cond_0, 0, if(cond_1, 1, ... if(cond_{W-1}, W-1, -1))) Laziness is unchanged and still rests on EvalIff: it evaluates a false branch only on the rows whose condition was false and passes that selection to the child executor, which the next nested if propagates. Each cond_i therefore runs once and only on rows no earlier WHEN claimed. Verified end to end on a live server -- a later WHEN of cast('bad' as signed) does not error when an earlier WHEN claims every row, and does error when a row reaches it, which is aptend's original counterexample. Nothing needs carrying between levels any more, so the carrier machinery (collectMultiInsertCarriers, rewriteMultiInsertColRefs) is deleted. Measured with a generator where each added WHEN also adds a source column it reads, counting every expression node in every ProjectList and FilterList: WHENs chained one projection 8 272 146 32 2204 530 126 - 2034 16 expressions per added WHEN, flat. TestMultiInsertFirstRoutingWorkIsLinear now uses that widening generator and asserts total expressions, projection count and widest projection; it fails on the chained implementation with "2204 is not less than 1632". TestMultiInsertFirstMasksLaterConditions now asserts the nested chain's shape and first-match order directly. Multi-insert BVT: 518/518 green. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_016qdL5akNrbUfXfqjC659n6
|
Fixed in The chain is gone. The whole decision is now one nested expression in one projection above the conditions' own node — the shape you suggested: Nothing has to be carried between levels, so Laziness is unchanged and still rests on
Measured with your generator shape (each added WHEN also adds a source column it reads; total expression nodes across every
16 expressions per added WHEN, flat. (My absolute numbers differ slightly from your probe's because the generated SQL isn't identical; the growth is the point, and mine reproduce the same quadratic on the old code.) The test now measures what the contract claims. Validation on this head. |
What type of PR is this?
Which issue(s) this PR fixes:
issue #27470
What this PR does / why we need it:
Snowflake-style multi-table INSERT: insert the rows of one source query into several tables — possibly with different schemas — in one statement. Design doc:
docs/design/multi_insert.md.Syntax
WHENconditions andVALUESexpressions are evaluated against the source query's output columns;INTO twithoutVALUESinserts positionally.INSERT ALLroutes a row to everyWHENwhose condition is true,INSERT FIRSTto the first one only; rows matching noWHENgo toELSE; a NULL condition never matches. The same table may appear in severalINTOclauses.WITHand prepared statements work.Per the issue's scope, targets with foreign keys and external tables are rejected with a clear error; ON DUPLICATE KEY UPDATE / IGNORE / RETURNING / OVERWRITE are not part of the syntax. One grammar limitation: a parenthesized source subquery directly after a bare
INTO tis a parse error (indistinguishable from a column list) — writeSELECT ...without parentheses or give a column list.Design
The source query is bound once and materialized in a
SINK(step 0). Every target table becomes its own step reading it through aSINK_SCAN, followed by the unchanged modern single-table insert pipeline:This is the same fan-out the engine already uses for IVF/fulltext maintenance; no operator or compiler changes — the planner only assembles existing nodes, so constraints, indexes (B-tree/unique/fulltext/ivfflat), defaults, auto-increment, atomicity, affected rows and privileges are inherited from single-table INSERT.
INSERT FIRST/ELSEare expressed asearlier cond IS NOT TRUEfilters. When the same table appears in several clauses, the clauses are widened to the union of their column lists and merged withUNION ALLin front of one write pipeline, so cross-clause duplicate keys are rejected exactly like in-batch duplicates of oneINSERT ... SELECT. The sink is a streaming, in-memory channel fan-out (one batch per consumer edge, shared ref-counted batches, backpressure), not a materialization to disk.The doc also records the chained/selector-based single-pipeline alternative that was considered, its costs and benefits, and why the sink design was kept.
Changes
tree.MultiInsertAST; grammar forINSERT ALL / FIRST ... INTO ... [WHEN/ELSE] ... SELECT(regenerated with zero conflicts).pkg/sql/plan/bind_multi_insert.go; the tail ofinitInsertReplaceStmtis extracted intoappendInsertReplaceSourceCasts/castInsertSourceColumnso single-table INSERT/REPLACE and every multi-insert target share it (single-table behaviour unchanged).MultiInsertclassified as DML (transactions, INSERT privilege on every target,last_insert_id, db remapping, PREPARE).docs_fttable.Tests
MULTI_UPDATEwithUNION ALL, fulltext maintenance retained, rejected targets).test/distributed/cases/dml/insert/:multi_insert(smoke coverage incl. EXPLAIN),multi_insert_conditional(ALL vs FIRST over overlapping WHENs, ELSE, NULL conditions, condition/source shapes, atomicity, transactions),multi_insert_schema(different target schemas, types, constraints, conversions, other-db/temporary targets),multi_insert_big(300k-row source so every target writes S3 objects, asserted viametadata_scan; late failure rolls back already-flushed objects),multi_insert_skew(extreme imbalance, empty targets, ELSE that never fires / takes everything).pkg/sql/plansuite, the wholedml/insertBVT directory (2000/2000), lint/vet. Verified by hand: affected-row sums, PREPARE/EXECUTE with parameters, privilege denial when one target lacks INSERT.🤖 Generated with Claude Code
https://claude.ai/code/session_016qdL5akNrbUfXfqjC659n6