Repository navigation
Do not expand a WITH element into a subquery that does not see it when updating - #119630
alexey-milovidov merged 3 commits into
Conversation
…n updating
A standalone `UPDATE ... SET` expands common table expressions before it fills
in the default database, so that a `WITH` alias is not qualified as if it were a
table. The expansion did not consult `enable_global_with_statement`: it replaced
the name in every nested `SELECT`, including one whose own `SETTINGS` clause
disables the lookup in enclosing scopes. There the name is a table name, and the
expansion left an `ASTSubquery` carrier in its place, so the identifier the
database had to be added to was gone. `ASTSubquery::formatImplWithoutAlias`
prints the bare `cte_name`, and `MutationCommand::parse` stores the command as
text, so the mutation named an unqualified table and the background thread
resolved it in the database of the session instead of the updated table's.
With a source table of the same name in both databases the update silently read
the wrong row; with no such table in the session database it failed with
`UNKNOWN_TABLE`. `ALTER TABLE ... UPDATE` was correct already, because it runs
the expansion only on `MODIFY QUERY`.
The visitor now takes an optional context and, while descending, applies each
subquery's own `SETTINGS` clause to a copy of it, exactly as `QueryTreeBuilder`
does for the analyzer: the clause is clamped rather than rejected so a subquery
cannot widen the reader's constraints, and the copy leaves the AST untouched.
When the resulting `enable_global_with_statement` is false, the inherited
elements are dropped for that subquery, so its table names survive to be
qualified. The elements a `SELECT` declares itself are registered afterwards and
are unaffected.
Only the two call sites in `InterpreterUpdateQuery` pass a context, so the other
eight callers of the visitor keep their exact behaviour.
`Data::literals` is deliberately left alone. With
`enable_scopes_for_with_statement = 0` a `WITH` expression alias is copied into
every child scope, so the analyzer resolves it whatever
`enable_global_with_statement` says; dropping it here would leave an identifier
for `AddDefaultDatabaseVisitor` to qualify as a table or dictionary name, which
was measured to turn a working `x IN lit` into `Unknown identifier 'db.lit'` and
`dictGet(dn, ...)` into `Dictionary ('dn') not found`.
Internal second-model review: adjudication log (click to expand)Pre-publication review by an independent model (engine: codex) plus my own cold pass over the
Severity: ❌ blocker / |
|
Workflow [PR], commit [a547149] Summary: ✅
AI ReviewSummaryThis PR makes standalone PR Metadata
Findings
Final Verdict
LLVM Coverage ReportMeasured on commit a547149.
Changed lines: Changed C/C++ lines covered: 41/42 (97.62%) · Uncovered code |
|
cc @yariks5s @evillique, could you review this? The CTE prepass in |
A subquery reads its own `SETTINGS` clause per select, so a trailing clause on the last arm of a union applies to that arm alone: the arm carrying `enable_global_with_statement = 0` resolves the reference as a table in the database of the updated table, while the arm without it keeps reading the alias. The two arms are weighted differently so that every misattribution answers its own value, each measured: the clause read for the other arm gives 2007, for both arms 2002, for neither 7007. On pristine master 1b86f9d (build id e2b70dd96336dc77) the statement answers 7099, reading the table of the session database, so the arm fails without this change. The union node itself cannot carry the clause where a mutation expression sits: only `ParserQueryWithOutput` parses a trailing `SETTINGS`, so a nested `(SELECT ...) UNION ALL (SELECT ...) SETTINGS ...` is a syntax error, and at the top level the clause reaches the context before any interpreter runs.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes12 object files changed (+24.87 KiB total), 0 added.
716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units16 translation units recompiled, 109 s compile time in total, 16 of them have a recent master baseline. |
| scope_data = data; | ||
| scope_data->context = getSubqueryContext(ast, data.context); | ||
| if (!scope_data->context->getSettingsRef()[Setting::enable_global_with_statement]) | ||
| scope_data->subqueries.clear(); |
There was a problem hiding this comment.
This only clears data.subqueries, but visit(ASTFunction) below still substitutes inherited data.literals for IN and dictGet. A standalone mutation like WITH [7] AS src SELECT (SELECT 2 IN src SETTINGS enable_global_with_statement = 0) will therefore still rewrite src to the hidden alias instead of the table that subquery actually sees, leaving the same wrong-result bug in this path. Please either gate the literals carrier with the same scope logic (taking enable_scopes_for_with_statement into account) or narrow the contract/comments to the table-CTE case only.
There was a problem hiding this comment.
Narrowed, in a5471497cf1d4: Data::context now states that inherited subqueries are dropped and inherited literals are substituted either way, and the three comments around it say CTE where they said element. Comments only, no behaviour change.
You are right about the carrier. ASTWithElement is the CTE form alone, since ParserWithElement falls through to ParserExpressionWithOptionalAlias for WITH <expr> AS <alias>, so the prose was narrower than it read, while visit(ASTFunction &) does still substitute an inherited alias into IN and dictGet.
I am not taking the other option here, because it is the guard I measured and reverted a few hours ago: enable_scopes_for_with_statement is answered by the scope that declared the alias, not by the one reading it, so a guard reading it from the subquery diverges in both mixed parent/child combinations. Doing it correctly needs the per-alias bookkeeping you describe, which is a second root cause.
It is also wider than this PR. InterpreterCreateQuery runs the same visitor with no context at all, so the substitution is persisted:
CREATE VIEW v AS WITH [7] AS src
SELECT (SELECT toUInt8(2 IN src) SETTINGS enable_global_with_statement = 0) AS r;
SHOW CREATE VIEW v -- ... toUInt8(2 IN ([7] AS src)) ...
SELECT r FROM v -- 0, where the same statement as a plain query answers 1
That needs no non-default table setting, and DatabaseOnDisk / DatabaseReplicated run the visitor again over stored metadata, so a fix has to settle creation and reload together. Both carriers are being handled separately, and the description names them instead of leaving them implicit.
`Data::context` was documented as keeping "a `WITH` element" out of a subquery that does not see it, but only the inherited `subqueries` are dropped. An expression alias reaches `visit(ASTFunction &)` through `Data::literals` and is still substituted into the `IN` and `dictGet` arguments there. `ASTWithElement`, the class that prose named, is the common table expression alone, because `ParserWithElement` falls through to an ordinary aliased expression for `WITH <expr> AS <alias>`, so the text read wider than the code. Both carriers are named now, and the two call-site comments say CTE where they said element. Why `Data::literals` stays inherited is in 0772ae8; a gate on the reading subquery's settings would be wrong as well, because `enable_scopes_for_with_statement` is answered by the scope that declared the alias, not by the one that reads it. Comments only, no change in behaviour.
…-aliases-per-select Resolve the conflict in `ApplyWithSubqueryVisitor::visit(ASTSelectQuery &)` with ClickHouse#119630: keep this branch's recursive-element dispatch and pass master's per-select `scope` instead of `data` to both arms. Co-Authored-By: Claude Fable 5.1 <[email protected]>
ReproducerCREATE DATABASE db2;
-- same table name in both databases, different row
CREATE TABLE src (id UInt64) ENGINE = MergeTree ORDER BY id; -- session database
INSERT INTO src VALUES (99);
CREATE TABLE db2.src (id UInt64) ENGINE = MergeTree ORDER BY id; -- updated table's database
INSERT INTO db2.src VALUES (2);
CREATE TABLE db2.u (id UInt64, v UInt64) ENGINE = MergeTree ORDER BY id
SETTINGS enable_block_number_column = 1, enable_block_offset_column = 1;
INSERT INTO db2.u VALUES (1, 0), (2, 0);
-- control: a name no WITH element hides resolves in the updated table's database
UPDATE db2.u SET v = (SELECT max(id) FROM src) WHERE id = 1;
SELECT v FROM db2.u WHERE id = 1; -- 2
-- subject: the inner SELECT disables enclosing-scope lookup, so `src` is a table
-- name there and must resolve the same way
UPDATE db2.u SET v = (WITH src AS (SELECT 7 AS id)
SELECT (SELECT max(id) FROM src SETTINGS enable_global_with_statement = 0))
WHERE id = 2;
SELECT v FROM db2.u WHERE id = 2; -- 99 on 26.8.4.11, expected 2
-- Observed on v26.8.4.11-lts: 2 then 99 -- the hidden name read the session
-- database. Fixed on master by #119630 (2 then 2).Results:
Backport the fix to CC component owner: @scanhex12 @Michicosun Analysis metadata
|
|
Confirmed, and
I do not open release-branch PRs by hand, so this is a label ask rather than a cherry-pick from me. @PedroTadim, could you apply |
Backport #119630 to 26.8: Do not expand a WITH element into a subquery that does not see it when updating
… a subquery that does not see it when updating
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed a standalone
UPDATE ... SETreading the wrong table when a mutation expression names a table that a same-namedWITHelement hides, but which the subquery does not see because its ownSETTINGSclause disablesenable_global_with_statement. Such a name is a table name, and it is now resolved in the database of the updated table instead of the database of the session, so the statement no longer silently updates from a different table or fails withUNKNOWN_TABLE.Description
A standalone
UPDATE ... SETexpands common table expressions before filling in the default database. The expansion never consultedenable_global_with_statement, so it also replaced the name inside a nestedSELECTwhose ownSETTINGSclause disables enclosing-scope lookup. There the name is a table name, but the expansion left anASTSubquerycarrier, soAddDefaultDatabaseVisitorhad no identifier to qualify: the command, stored as text, resolved it in the session database.ALTER TABLE ... UPDATEis correct here: it runs the expansion only onMODIFY QUERY.The visitor now takes an optional context and applies each subquery's own
SETTINGSclause to a copy while descending, asQueryTreeBuilderdoes for the analyzer (clamped, not rejected). Where the resultingenable_global_with_statementis false, the inherited CTEs are dropped, so the subquery's table names survive to be qualified; a clause on one arm of aUNIONis read for that arm alone. OnlyInterpreterUpdateQuery's two call sites pass a context; the other eight callers are unchanged.Present since
bac3508(v26.8.1.2041-lts), not in 26.6 or 26.7. Asked for by the review bot on #114908 (discussion_r3995813819), pre-existing there.Not fixed here, and
Data's contract now says so: aWITHexpression alias is still substituted into a subquery that does not see it, soWITH [7] AS src SELECT (SELECT 2 IN src SETTINGS enable_global_with_statement = 0)reads the array where a plainSELECTreads the table, andCREATE VIEWpersists that substitution. Dropping them needs more than this guard: withenable_scopes_for_with_statement = 0they stay visible, decided by the scope that declared the alias, so a fix must track it per alias. Both are measured, and handled separately; #118983 is covered by #114908.visit(ASTSelectQuery &); the second to merge needs onlydata->scopethere.Workflow [PR]
Sync PR [sync-upstream/pr/119630]
Version info
26.8.21.5