Repository navigation
Conversation
The reference files stay empty until the fix is in place. Related: #113711 Co-Authored-By: Claude Fable 5.1 <[email protected]>
Co-Authored-By: Claude Fable 5.1 <[email protected]>
`visitKeepingMaterializedCTEs` expands plain CTE references as before but leaves references to `MATERIALIZED` elements as identifiers, visible in the whole WITH list (forward references) and scoped like the expanded ones, and returns the identifier nodes of the resulting tree so that the default database is not added to them. Related: #113711 Co-Authored-By: Claude Fable 5.1 <[email protected]>
…the full ATTACH syntax `enable_analyzer = 0` is rejected since 26.9, and a full-definition `ATTACH MATERIALIZED VIEW` needs its column list to be treated as a definition rather than as a short attach. Co-Authored-By: Claude Fable 5.1 <[email protected]>
The second pass of `visitKeepingMaterializedCTEs` descends into the clones the first pass created and must only record identifiers there, never expand them again: otherwise a plain forward reference or a recursive self-reference inside a clone is expanded once more and a materialized reference created by that expansion escapes the recorded set. Co-Authored-By: Claude Fable 5.1 <[email protected]>
`ApplyWithSubqueryVisitor` expanded every CTE reference of a view `SELECT` into a copy of the body tagged only with `cte_name`, so `ASTWithElement::is_materialized` was lost and the analyzer ran the CTE once per reference. `CREATE`, metadata load, Replicated DDL replay and `MODIFY QUERY` now keep references to `MATERIALIZED` elements as identifiers, and `AddDefaultDatabaseVisitor` skips exactly those nodes instead of qualifying them as tables. A fresh materialized view definition that fixes `enable_global_with_statement` is rejected before the query is forwarded to a cluster or a Replicated database; a loaded or replayed one keeps the legacy full expansion, because the query of a materialized view is otherwise always run with that setting enabled. Related: #113711 Co-Authored-By: Claude Sonnet 5 <[email protected]>
`getSelectQueryFromASTForMatView` takes the source table from the first table expression and rejects PREWHERE, SAMPLE and FINAL by descending into subqueries. With `MATERIALIZED` CTE references kept in the stored definition both must follow a CTE reference into its body, through chains, forward references and same-named shadowing declarations, using a stack of the WITH declarations visible at each step. The stored query is still qualified with the current database, skipping the references. Related: #113711 Co-Authored-By: Claude Sonnet 5 <[email protected]>
…_statement enabled With `MATERIALIZED` CTE references kept in the stored definition, a nested reference to a CTE of an enclosing SELECT binds differently depending on `enable_global_with_statement`, while the source table the view depends on is decided once, at CREATE. Pin the setting for the column inference at CREATE and MODIFY QUERY, for the per-insert push, for POPULATE and for refreshes, so no session setting can make the query read a table other than the registered source. Related: #113711 Co-Authored-By: Claude Sonnet 5 <[email protected]>
`replaceStorageInQueryTree` substitutes the inserted block for the source table of a materialized view using `extractAllTableReferences`, which stopped at a `TableNode`. A materialized CTE holds its body as a child of its `TableNode`, so the source table inside the body was left pointing at the real table and the view would have read all of it on every insert. Related: #113711 Co-Authored-By: Claude Fable 5.1 <[email protected]>
Co-Authored-By: Claude Fable 5.1 <[email protected]>
…ation The recording pass of `visitKeepingMaterializedCTEs` entered the copies made by expanding a plain CTE with the scope of the reference site, so a materialized reference inside the copy was not recorded when the reference site declared a plain CTE of the same name, and the default database was added to it. Each plain CTE now remembers the scope its body was visited with, and a copy (an `ASTSubquery` tagged with `cte_name`) is classified with that scope. Related: #113711 Co-Authored-By: Claude Fable 5.1 <[email protected]>
`checkAllowedQueries` rejects a non-`SELECT` arm (`INTERSECT`, `EXCEPT`) with a user-facing error; running it after the first arm was already cast to `ASTSelectQuery` turned that into a logical error (test `03247_materialized_view_select_intersect`). Co-Authored-By: Claude Fable 5.1 <[email protected]>
…definition A refresh runs with the server defaults, where `enable_materialized_cte` is off, so the CTE was inlined; the definition now carries the setting, and the documentation says where it must be enabled. Co-Authored-By: Claude Fable 5.1 <[email protected]>
Stateless: views, parameterized views, materialized views (MODIFY QUERY, inserted-block substitution, chained, forward-referenced and shadowed CTEs, the pinned enable_global_with_statement on insert, POPULATE and refresh, rejection of that setting in a fresh CREATE, MODIFY QUERY and full-definition ATTACH, PREWHERE/SAMPLE/FINAL rejection including a later UNION arm), DETACH/ATTACH, a CTE named like its source table, CTE chains including a plain CTE carrying a materialized reference through FROM and IN, forward references, UNION views with shared and same-named per-branch CTEs, sibling scopes, enable_global_with_statement = 0 for ordinary views. Integration: legacy metadata that fixes the setting keeps the full expansion when loaded by short ATTACH and at server start, and a Replicated database replays such a CREATE or MODIFY QUERY of an older initiator instead of failing. Closes: #113711 Co-Authored-By: Claude Fable 5.1 <[email protected]> Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`assert_eq_with_retry` is never used in `test_materialized_cte_view_legacy_metadata`, and `ruff` rule `F401` is enforced by the CI style check. Co-Authored-By: Claude Fable 5.1 <[email protected]>
`cte_declaration_scopes` is now erased and cleared wherever `subqueries` is, so the invariants of the keep mode are local instead of derived. The `IN` literal fallback gets the read-only one-liner the other three gates carry. Co-Authored-By: Claude Fable 5.1 <[email protected]>
A plain `CREATE TABLE ... AS SELECT` now keeps using the query context instead of a copy, `isFreshTableDefinition` is evaluated once in the view block, and the unused `ASTSubquery.h` include is dropped. Co-Authored-By: Claude Fable 5.1 <[email protected]>
The paragraph now also says that the rejection covers any `SETTINGS` clause inside a new materialized view definition, including one on a nested subquery, and that a loaded or replayed definition which sets `enable_global_with_statement` keeps the earlier full expansion. Co-Authored-By: Claude Fable 5.1 <[email protected]>
…n views Cover a materialized view whose materialized CTE is named like its source table, the declaration-scope classification of an expansion copy of a plain CTE, and a view definition whose own `SETTINGS enable_global_with_statement = 0` clause makes a nested reference fail at definition time. The dead `SET enable_analyzer = 1` is removed. Co-Authored-By: Claude Fable 5.1 <[email protected]>
|
Workflow [PR], commit [76fdb76] Summary: ❌
AI ReviewSummaryThis PR keeps Findings❌ Blockers
Final VerdictChanges requested. LLVM Coverage ReportMeasured on commit 76fdb76.
Changed lines: Changed C/C++ lines covered: 264/272 (97.06%) · Uncovered code |
|
|
||
| /// Before the visitors and before the query is enqueued or forwarded, so an accepted definition is valid on | ||
| /// every replica; a replayed entry of an older initiator is not fresh and keeps the legacy expansion below. | ||
| if (create.is_materialized_view && is_fresh_definition) |
There was a problem hiding this comment.
checkSettingsAllowedInMatView is still too late for CREATE ... ON CLUSTER. InterpreterCreateQuery::execute returns through executeQueryOnCluster before createTable runs, so the initiator never executes this branch; only the worker legs do. That means a fresh CREATE MATERIALIZED VIEW ... SETTINGS enable_global_with_statement = 0 ON CLUSTER is enqueued instead of being rejected locally, and on a mixed-version cluster older workers can accept it while newer ones reject it. This validation needs to happen on the initiator side before the early executeQueryOnCluster(create) return.
There was a problem hiding this comment.
Addressed in 41c1868: InterpreterCreateQuery::execute now runs checkSettingsAllowedInMatView inside the legacy-entry-format ON CLUSTER branch, before executeQueryOnCluster, so the initiator rejects the definition with every distributed_ddl_entry_format_version. Covered by the ON CLUSTER section of 05233_materialized_view_global_with_effective_value.
| { | ||
| if (const auto * set_query = select.as<ASTSetQuery>()) | ||
| { | ||
| for (const auto & change : set_query->changes) |
There was a problem hiding this comment.
This guard can still be bypassed through SETTINGS compatibility = '21.1'. compatibility flips enable_global_with_statement back to 0 via the 21.2 settings-history entry, and InterpreterSetQuery::applySettingsFromQuery replays the definition's SETTINGS on every insert or refresh. So a fresh materialized-view definition can still execute with global WITH disabled even though fixesGlobalWithSetting accepted it, which reintroduces the source-table divergence this PR is trying to prevent. I think the check has to compare the effective value after applying each SETTINGS clause to a scratch context, not only scan for the literal setting name.
There was a problem hiding this comment.
Addressed in 41c1868 and e5a104c: the check now also applies the compatibility and profile entries of every SETTINGS clause in the definition to a scratch context (reset to the declared default, clamped, applied) and rejects when the effective value turns off. Only those two entries are applied, so unrelated nested settings behave as before. Covered by 05233_materialized_view_global_with_effective_value.
|
|
||
| std::unordered_set<const IAST *> ApplyWithSubqueryVisitor::visitKeepingMaterializedCTEs(ASTSelectWithUnionQuery & select) | ||
| { | ||
| Data data; |
There was a problem hiding this comment.
visit(ASTSelectQuery &) only clears inherited CTE names for SETTINGS enable_global_with_statement = 0 when data.context is populated, but visitKeepingMaterializedCTEs never sets it. The second pass therefore still marks an out-of-scope reference as a kept CTE reference, and AddDefaultDatabaseVisitor skips qualifying it. For ordinary or parameterized views that changes the persisted semantics from "bind to the table that resolved at CREATE time" to "resolve a bare name at read time": with a real table db1.r present, USE db1; CREATE VIEW db2.v AS WITH r AS MATERIALIZED (SELECT 1 AS x) SELECT * FROM (SELECT * FROM r SETTINGS enable_global_with_statement = 0); stores bare r, so later reads depend on the reader's current database instead of the create-time table.
There was a problem hiding this comment.
Addressed in 3eef4f6 and 41c1868: the visitor has a single behaviour now (visitKeepingMaterializedCTEs is gone), and a fresh CREATE/MODIFY QUERY passes a copy of the global context with enable_global_with_statement forced on, so a reference that the definition itself hides behind a nested SETTINGS enable_global_with_statement = 0 is qualified with the current database of the creating session at CREATE time instead of being resolved in the reader's database later. Covered by 05234_materialized_cte_view_nested_setting_qualified.
There was a problem hiding this comment.
Follow-up: the pointer protocol between the two visitors is gone (commits cca5286..d518a3d). ApplyWithSubqueryVisitor is a single pass that simply does not register MATERIALIZED CTEs; AddDefaultDatabaseVisitor keeps a per-SELECT set of the visible MATERIALIZED names with an inherited global-WITH flag that a select's own SETTINGS enable_global_with_statement clause overrides for itself and its nested selects (seeded on at definition sites, so the stored text depends only on the definition and the server defaults), and DDLDependencyVisitor skips the WITH names it meets while walking the view's query. An expansion copy of a plain CTE is classified like its declaration body (nested copies included), because the stored text keeps only the declaration bodies. Covered by 05234 (nested, outer and repeated clauses) and the v_copy_113711/v_nested_copy_113711 sections of 05227, which reload the views.
The new stateless tests cover the defects the change has to fix and guard the paths it must not break: a view never records a referential dependency on a table named like its CTE, a distributed `INSERT SELECT` writes the rows of the CTE exactly once whatever table carries its name, a lightweight `UPDATE` materializes a CTE declared in an assignment and does not bind an `IN` reference to a same-named table, `EXPLAIN SYNTAX` and `EXPLAIN AST optimize = 1` keep inlining, a fresh materialized view definition cannot turn `enable_global_with_statement` off through `compatibility` or `profile`, and a definition that turns it off inside itself stores the nested reference qualified. The integration test now expects a legacy definition to load with its references kept and a warning in the log, and gains a case for a plain CTE named like a table after a restart. The `.reference` files are empty on purpose: they are filled once the behaviour is in place. Co-Authored-By: Claude Fable 5.1 <[email protected]>
The inserts of the integration test that fire a materialized view now carry `enable_materialized_cte = 1`: the feature is experimental and off by default, so every `same = 1` assertion was unreachable. The setting cannot live in the definition's own `SETTINGS` clause, because the first test appends a second clause there with `sed`. `05233` gains the `ON CLUSTER` case: with a `distributed_ddl_entry_format_version` below `NORMALIZE_CREATE_ON_INITIATOR_VERSION` the initiator returns through `executeQueryOnCluster` before `createTable`, so the definition is not checked there today; the default format is kept alongside as the control. The redundant `curl` flags are dropped and `grep -oFm1` replaces `grep -oF | head -n 1`. `05234` now shows both halves in one definition: a top-level reference stays bare while the reference the definition hides with its own `SETTINGS` clause is qualified. The header of `05230` says what a single-shard cluster actually proves. Co-Authored-By: Claude Fable 5.1 <[email protected]>
A name declared by a `WITH` list is not a table, so `DDLDependencyVisitor` now walks a copy of the view query with the CTE references expanded instead of the stored one. Master records a plain CTE name as a dependency after a restart too, because the loader reads the bare names of the metadata query. Co-Authored-By: Claude Fable 5.1 <[email protected]>
The pointer sets of `DDLDependencyVisitorData` key on nodes of the expanded query, so it is held by a member instead of a local of `visitCreateQuery`. Also name the set of the kept references as the rest of the branch does. Co-Authored-By: Claude Fable 5.1 <[email protected]>
… every call The visitor has one behaviour now: it expands plain CTEs and always leaves a reference to a `MATERIALIZED` CTE as an identifier for the analyzer, which materializes the CTE once. Every `visit` returns the identifiers it kept, so each caller hands them to its `AddDefaultDatabaseVisitor` and they are not qualified as table names. A fresh `CREATE` or `MODIFY QUERY` classifies the definition with `enable_global_with_statement` on, so only the `SETTINGS` clauses written inside the definition decide which names it sees; a loaded or replayed definition is already qualified and is visited without a context. Co-Authored-By: Claude Fable 5.1 <[email protected]>
…p the distributed insert fast paths
`InterpreterSelectQuery` and the old `MutationsInterpreter` have no CTE name resolution of their own, so
a kept `MATERIALIZED` reference reaches `JoinedTables::getLeftTableStorage` as an unknown table; both now
clear the `MATERIALIZED` flag before `ApplyWithSubqueryVisitor` runs, which inlines the CTE as before.
The distributed `INSERT SELECT` fast paths probe the source table by expanding the `SELECT` in place and
cannot take a kept reference either, so they are skipped for a query that declares one. The two shared
helpers live in the new `Interpreters/MaterializedCTEUtils.{h,cpp}`.
Co-Authored-By: Claude Fable 5.1 <[email protected]>
…view definitions `checkSettingsAllowedInMatView` now applies every `SETTINGS` clause of a fresh definition to a scratch context copy and rejects it when the effective value of `enable_global_with_statement` is off, so `compatibility` and `profile` clauses that turn it off without naming it are rejected too. The initiator of an `ON CLUSTER` query with `distributed_ddl_entry_format_version` below `NORMALIZE_CREATE_ON_INITIATOR_VERSION` returns through `executeQueryOnCluster` before `createTable` and now runs the check in that branch, so such an entry is never enqueued. A materialized view whose stored definition turns the setting off and declares a `MATERIALIZED` CTE logs a warning at load, replay and short `ATTACH TABLE`: its nested references are resolved as table names from now on. The warning uses the literal predicate only, because applying a stored definition's clauses at server start could throw. Co-Authored-By: Claude Fable 5.1 <[email protected]>
…ition check `turnsGlobalWithOff` applied every entry of a `SETTINGS` clause to the scratch context and checked it against the creating user's constraints, so a materialized view definition whose nested clause carried an unrelated constrained or unknown setting was rejected although master accepts it: a nested clause is clamped, not checked, at run time (`Analyzer/QueryTreeBuilder.cpp` and `ApplyWithSubqueryVisitor::getSubqueryContext`). Only the `compatibility` and `profile` entries are applied now - nothing else in a clause can change the setting without naming it, and the literal predicate covers the name - and they are clamped instead of checked. The warning site in `DatabaseOnDisk.cpp` logs under the component name instead of the function name. Co-Authored-By: Claude Fable 5.1 <[email protected]>
…ences The `WITH` page is generated from this doc string. A stored view definition no longer expands its `MATERIALIZED` CTE references in any case, so the paragraph drops the legacy expansion of a materialized view loaded from disk and says what happens instead: such a definition loads with a warning and its nested references resolve as table names, as in a plain query. Two more rules that the change introduced: the rejection of the setting in a fresh materialized view definition looks at the effective value, so `compatibility` and `profile` clauses are rejected too, and a definition of any view kind that turns the setting off inside itself stores the reference as a table name of the definition's database. Co-Authored-By: Claude Fable 5.1 <[email protected]>
The sentence about a definition that turns global `WITH` off in a `SETTINGS` clause of its own said "a definition of any view kind", which cannot happen for a materialized view: a fresh definition with such a clause is rejected, and load and replay do not evaluate clauses. It speaks of a `VIEW` or a parameterized view now. The paragraph is also laid out one sentence per line as the rest of this doc string is, the three longest sentences are split, and the load sentence names replay and `ATTACH` as well. Co-Authored-By: Claude Fable 5.1 <[email protected]>
Three comment-only items deferred from the reviews of the tests. `05232` now says that its `EXPLAIN SYNTAX` line documents the inlined form rather than proving it: an inlined body prints under its alias, which is the CTE's name, exactly where a kept reference would print that name, and the text is byte-identical to the same statement with a plain CTE. The `EXPLAIN AST` block below it is the proof. `05229` points at `test_materialized_cte_view_legacy_metadata::test_plain_cte_dependency_after_restart` for the plain-CTE case, which a stateless test cannot reach because a fresh `CREATE` expands a plain CTE before the dependency visitor sees the definition. `05233` drops `mv_eff_cluster_113711b` in its initial `DROP TABLE IF EXISTS` batch as well. `05234` gains the plain-CTE shape of the nested-setting rule, as the review of the `ApplyWithSubqueryVisitor` change asked: a definition that turns `enable_global_with_statement` off inside itself qualifies the hidden reference of a plain CTE too, so the view returns the table's row, which is what the same query returns outside a view. `05232` becomes a shell test. Its `EXPLAIN AST` prints the dummy alias of the `WITH` element's own subquery, and that alias is numbered from a process-global counter (`subquery_index` in `QueryAliasesVisitor.cpp`), so consecutive runs against one server printed `_subquery2`, `_subquery4`, `_subquery6` and so on and no reference could hold it. The shell form masks the number with `sed` and leaves the statements untouched; reading the `EXPLAIN` from a subquery instead would analyze the inlined body copies one step further and no longer show the tree the old interpreter built. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The six tests were committed with empty `.reference` files so that every run printed its whole output as a diff while the behaviour was still changing. The files hold the measured output now, checked line by line against the expectations the tasks recorded. `05229`: the three views read the CTE, the `DROP` of the same-named table succeeds and the `DROP` of the table a CTE body reads is refused. `05230`: three identical `3 3` pairs, so no fast path binds a same-named table or fails on a missing one. `05231`: `1` for one materialization of an assignment's CTE, and the `IN` form updates the CTE's rows rather than the same-named table's. `05232`: the `EXPLAIN AST` tree carries `Subquery (alias c_old_113711b)` in the table expression, the inlined body. `05233`: `NOT_IMPLEMENTED` for `compatibility`, `profile` and both `MODIFY QUERY` forms, for `ON CLUSTER` with the default and the legacy DDL entry format, and none of the rejected views exists. `05234`: the nested references are stored as `db.r_nested_113711b` and `db.r_plain_113711b` and read the tables, the top-level reference stays bare and reads the CTE. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`AddDefaultDatabaseVisitor` is built with the current database of the session that runs the `CREATE`, not with the database of the view, so that is the database the stored reference names. Co-Authored-By: Claude Fable 5.1 <[email protected]>
…or` and drop the test profile on entry The `chassert` plus a raw `as<ASTTableIdentifier>` left a null dereference in release builds; `assert_cast` throws there instead. `05233` now drops its settings profile next to the initial `DROP TABLE IF EXISTS`, so an aborted run does not leave a server-global profile behind. Co-Authored-By: Claude Fable 5.1 <[email protected]>
An expansion copy of a plain CTE is resolved at its reference site, like the analyzer resolves it at run time, so `v_copy_113711` reads the `MATERIALIZED` CTE declared there instead of the table. Co-Authored-By: Claude Fable 5.1 <[email protected]>
… scope The visitor now tracks the names of the `MATERIALIZED` CTEs visible in the select it visits (inherited by nested selects unless their own `SETTINGS` clause turns `enable_global_with_statement` off, and excluding a CTE's own name inside its body) and leaves bare identifiers with such names unqualified. This replaces the pointer set handed over by `ApplyWithSubqueryVisitor` through `setKeptCTEReferences`, which is removed together with its plumbing at the four callers. Co-Authored-By: Claude Fable 5.1 <[email protected]>
…aseVisitor` A select's own `SETTINGS enable_global_with_statement` now applies to everything nested in it, as in `ApplyWithSubqueryVisitor` and the analyzer, so an outer clause that hides a `MATERIALIZED` CTE qualifies the nested references instead of leaving them to the reader's current database. The initial value comes from the context, except at definition sites (`CREATE VIEW`, `MODIFY QUERY`, the stored materialized view query), which are seeded with `true`. The constructor moves to a new `AddDefaultDatabaseVisitor.cpp` so the header does not include `Core/Settings.h`. Co-Authored-By: Claude Fable 5.1 <[email protected]>
`DDLDependencyVisitor` walks the query of a view with the names declared by its `WITH` lists and skips bare table references with such names, instead of expanding a copy of the query. The loader reads bare plain-CTE names from the metadata text, so a view with a CTE named like a real table no longer pins that table after a restart. The names are scoped to the view's `SELECT`, so a bare name in the inner-table `TTL` of a materialized view still records the real table. Co-Authored-By: Claude Fable 5.1 <[email protected]>
…endencies `DDLDependencyVisitor` now walks the query of a view with a recursion that sees only the `WITH` names of the enclosing selects, so a `WITH RECURSIVE` name, which `AddDefaultDatabaseVisitor` leaves unscoped, no longer hides a same-named table in a sibling `UNION` branch. The dictionary `QUERY` text is walked as before, without CTE names. Co-Authored-By: Claude Fable 5.1 <[email protected]>
…`MATERIALIZED` CTEs A `MATERIALIZED` name declared in a `WITH` list now only hides the enclosing meaning of that name in its select, so references to it stay identifiers for the analyzer. The recording pass, the kept-reference pointer set and the declaration scopes are gone; `visit` returns nothing, since `AddDefaultDatabaseVisitor` and `DDLDependencyVisitor` scope CTE names themselves. `globalWithSettingOf` now takes the first `enable_global_with_statement` in a `SETTINGS` clause, as the analyzer does. Co-Authored-By: Claude Fable 5.1 <[email protected]>
…s off When `enable_global_with_statement` is repeated in one `SETTINGS` clause, the analyzer hides enclosing CTEs if any occurrence is false, whatever the order. `globalWithSettingOf` now follows that rule, so a view with `= 1, = 0` stores the nested reference qualified, like `= 0, = 1` already did. Also refresh a comment in `ApplyWithSubqueryVisitor` that still described registering every CTE. Co-Authored-By: Claude Fable 5.1 <[email protected]>
…default database The stored text of a view prints an expansion copy of a plain CTE as the bare CTE name and keeps only the declaration body, so after `DETACH`/`ATTACH` or a restart the copy is re-expanded from that body. Classifying the copy at its reference site made the view read different rows after a reload, with the column type inferred from the in-session reading (values were truncated). `AddDefaultDatabaseVisitor` now records, per plain `WITH` element, the `MATERIALIZED` name set, the global `WITH` flag and a snapshot of the visible plain CTE records its body is visited with. An `ASTSubquery` with a `cte_name` installs all three for its subtree, so nested copies are classified like their own declaration bodies too. The records are saved and restored per select, like the name set. `05227`: `v_copy_113711` returns the table's rows with the table's type again, and a new `v_nested_copy_113711` section covers a copy nested in a copy under a same-named inner CTE; both are read before and after a reload. Co-Authored-By: Claude Fable 5.1 <[email protected]>
…ore the WITH bodies `globalWithSettingOf` converted the clause value with `SettingFieldBool`, which throws on a literal such as `'abc'`. Master stores and loads such a definition (an explicit column list skips analysis), and the helper runs at server start for a materialized view, so the start failed. The value is now read without throwing; an unrecognised value is ignored. The helper moved to `AddDefaultDatabaseVisitor.cpp`. The `WITH` bodies are visited after the `FROM` tables again, as on master: the unscoped `with_aliases` set absorbs a `WITH RECURSIVE` name declared inside a body, which left a same-named real table bare in the outer `FROM`. Co-Authored-By: Claude Fable 5.1 <[email protected]>
|
@novikd is this still planned? We depend on it and I'd like to help it along if possible. I merged current master (6751421, 2026-11-16) into fix-materialized-cte-in-view locally to see what updating the branch would take. 13 of the PR's 21 source files conflict. Roughly a third are mechanical (includes, a neighbouring line changed). The rest are two real overlaps with work that landed on master since your last commits:
AddDefaultDatabaseVisitor.h: master now tracks WITH declarations per scope itself ( Smaller ones: If you'd like, a PR into your branch with master merged and the mechanical conflicts plus the |
Closes: #113711
Related: #118853
Related: #114908
Related: #22657
CREATE VIEW,CREATE MATERIALIZED VIEWandALTER TABLE ... MODIFY QUERYrunApplyWithSubqueryVisitorover the definition, which replaces every CTE reference with a copy of the CTE body. TheMATERIALIZEDflag lives on theWITHelement, not on the reference, so the copy loses it and a CTE referenced twice in a view is evaluated twice.The change keeps such references unexpanded in the stored definition, so the analyzer materializes the CTE once.
MATERIALIZEDCTE names by scope while it walks the AST:ApplyWithSubqueryVisitoris a single pass that expands plain CTEs and simply does not registerMATERIALIZEDones (forward references included),AddDefaultDatabaseVisitorkeeps a per-SELECTset of visible names,DDLDependencyVisitorskips theWITHnames it met.AddDefaultDatabaseVisitorleaves a bare name from that set unqualified instead of turning it intodefault.cte_name; nested selects inherit the set unless their own or an enclosingSETTINGSclause turnsenable_global_with_statementoff. The predicate and assignments of a lightweightUPDATEare selects too, so aMATERIALIZEDCTE declared there is materialized instead of binding the name to a table.SelectQueryDescriptionresolves the source table and runs the query checks (JOIN,UNIONshape,GROUP BY) by following CTE references through chains, forward references and shadowing, instead of relying on the expansion.enable_global_with_statementon - every path that runs it pins the setting - so the registered source table cannot diverge from the table the query reads. A new definition setting it is rejected withNOT_IMPLEMENTED: the check uses the effective value, socompatibilityandprofilecount, and theON CLUSTERinitiator runs it with every DDL entry format. An older definition keeps loading, replaying and attaching, with a warning in the log.DDLDependencyVisitorwalks a view's query itself, with no expanded copy, skipping bare references to theWITHnames of the enclosing selects, so a CTE name is not recorded as a dependency on a table; this also fixes master's plain-CTE case, where the loader reads the bare names of the metadata query after a restart.extractAllTableReferencesdescends into the body of aMATERIALIZEDCTE.InterpreterSelectQueryand the oldMutationsInterpreterhave no CTE resolution of their own, so they clear the flag and inline as before. They are reached byEXPLAIN SYNTAXof a non-SELECTstatement,EXPLAIN AST ... optimize = 1, a pre-23.3 initiator, a materialized view overDistributed, anduse_analyzer_for_mutations = 0.INSERT SELECTfast paths probe the source table by expanding theSELECTin place, which an unexpanded reference breaks, so a query declaring aMATERIALIZEDCTE skips them and takes the regular pipeline.Behaviour changes, described in the documentation of the
WITHelement:MATERIALIZEDCTE in a view is materialized once per read, insert,POPULATEor refresh, whereverenable_materialized_cteis enabled.SELECTnow followsenable_global_with_statement, as in an ordinary query.VIEWdefinition that turns that setting off in a clause of its own stores the reference as a table name in the current database of theCREATE, as the same query resolves it directly; a plain CTE used to be expanded into a copy and aMATERIALIZEDone left bare.INSERT ... SELECTwith aMATERIALIZEDCTE into aDistributedorReplicatedtarget no longer takes the distributed fast paths.Tests:
05227-05234(views and parameterized views, materialized view paths, dependencies, distributedINSERT SELECT, lightweightUPDATE, old-interpreter inlining, the effective-value rejection, the nested-SETTINGScase) andtest_materialized_cte_view_legacy_metadata.Notes for reviewers and for whoever merges second:
Buffertable directly and through a materialized CTE now counts two uses, as it already does for a plain CTE; the same-table-twice guard is unaffected, because a materialized CTE body is planned separately.MATERIALIZEDCTE shadows an outer one of the same name and reads it hits a pre-existing analyzer bug (TOO_DEEP_SUBQUERIES), which the expansion used to hide.enable_global_with_statementis pinned on every materialized view query path,enable_materialized_cteis not: whether a stored definition materializes still depends on the session or on its ownSETTINGSclause. Revisit when the feature stops being experimental.= 1; narrowing that is a possible follow-up. The load warning is literal-only, because the load path must not evaluate a clause (an unknown profile would throw at start): an older definition usingcompatibilityorprofilechanges meaning silently.AddDefaultDatabaseVisitoralso reads only a literalenable_global_with_statement, so aVIEWturning it off throughcompatibilityorprofileleaves nestedMATERIALIZEDreferences bare for the analyzer to resolve at read time.EXPLAIN SYNTAXnow prints aMATERIALIZEDWITHelement without the keyword, because the old interpreter clears the flag before inlining andEXPLAIN SYNTAXprints its rewritten AST.enable_materialized_ctenow gets the analyzer's "materialized CTE ... inlined" warning on every read of such a view; the expansion used to hide it.force_materialized_cteto throw when aMATERIALIZEDCTE cannot be materialized #118853 adds the same insert fast-path gate and rejectsMATERIALIZEDCTEs on the old pipelines, where this PR inlines them instead: whoever merges second drops the duplicated gate, and its rejection ofMATERIALIZEDin a view definition must go.AddDefaultDatabaseVisitor.handApplyWithSubqueryVisitor.{h,cpp}, and one expectation differs: here an expansion copy is classified like its declaration body, nested copies included, because the stored text keeps only the declaration bodies, while its05235_with_alias_scope_copied_body_nearer_same_nameexpects the reference-site classification, which does not survive a reload (v_copy_113711andv_nested_copy_113711in05227reload the views). Whoever merges second reconciles that test.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixes
MATERIALIZEDcommon table expressions being evaluated once per reference instead of once in the definition of aVIEW, parameterized view orMATERIALIZED VIEW. A view's referential dependencies no longer include CTE names, which previously madeDROPfail withcheck_referential_table_dependenciesenabled (off by default) and could upset the unconditionalRENAMEcycle check. Nested references to a CTE of an enclosingSELECTinside a view now followenable_global_with_statement, as in ordinary queries, and a materialized view definition can no longer set that setting.🤖 Generated with Claude Code