Repository navigation
Reject DEFAULT/MATERIALIZED expressions over virtual columns - #111776
PedroTadim merged 3 commits into
Conversation
With the analyzer, column defaults are validated by resolving SELECT <defaults> FROM dummy over a StorageDummy built from the declared columns. Like every storage, StorageDummy exposes the common virtual columns _table and _database, so a DEFAULT or MATERIALIZED expression referencing one of them resolved during validation. But such an expression is evaluated over an insert block, which never contains virtual columns, so the table could never be inserted into (NOT_FOUND_COLUMN_IN_BLOCK); with MATERIALIZED it was permanently un-insertable. The non-analyzer path only sees the declared columns and correctly rejected these expressions. After resolving the defaults, reject an insert-time column (DEFAULT or MATERIALIZED) whose expression reads a virtual column, directly or transitively through an alias. ALIAS and EPHEMERAL columns are read-time only and may still reference virtual columns, so they keep working. A real column that happens to be named like a virtual is a declared column and is left untouched. Covers CREATE TABLE and ALTER TABLE ADD/MODIFY COLUMN. Closes: ClickHouse#111658 Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-author-slot-0:20260724-083100 |
Internal second-model review — adjudication log (click to expand)Pre-publication review by an independent model (engine: codex; several rounds as the fix evolved; each round bounded: 1 pass + 1 fix round + 1 delta recheck).
Severity: ❌ blocker / Session id: cron:clickhouse-author-slot-0:20260724-083100 |
|
cc @PedroTadim — could you review this? Per your note on #111658, it rejects a column DEFAULT/MATERIALIZED that references a virtual column ( |
|
Workflow [PR], commit [110c0f9] Summary: ❌
AI ReviewSummaryThis PR closes the direct analyzer path that let Findings
💡 Nits
Final VerdictStatus: |
|
Follow-up (pushed): also exempt external-target ( |
… views The previous commit rejected a DEFAULT/MATERIALIZED column expression that references a virtual column (e.g. _table/_database) at CREATE and ALTER time. That rejection was exempt for ordinary views but not for external-target (TO) materialized views. An external-target materialized view forwards inserts to its target table using the target metadata (StorageMaterializedView::write) and never evaluates its own column defaults over an insert block, so such a default is inert there, exactly like an ordinary view. Rejecting it turned a harmless (if pointless) view definition into a new analyzer-only DDL error, e.g. CREATE MATERIALIZED VIEW mv TO t (x String DEFAULT _table) AS ... Exempt external-target materialized views from the check in both paths: - CREATE: widen the exemption flag to is_materialized_view_with_external_target(). - ALTER: skip collecting insert-time default columns when the storage is an external-target materialized view (its column-modifying ALTERs are rejected by checkAlterIsPossible anyway, so this restores the prior NOT_IMPLEMENTED error instead of a misleading UNKNOWN_IDENTIFIER). Inner-table materialized views keep the rejection: their inner table applies the view column defaults on insert, so a virtual-column default is genuinely harmful.
d6aed27 to
347fbbc
Compare
| } | ||
| } | ||
|
|
||
| std::optional<Block> validateDefaultsWithAnalyzer(ASTPtr default_expr_list, const NamesAndTypesList & all_columns, ContextPtr context, bool get_sample_block, const NameSet & insert_time_default_columns) |
There was a problem hiding this comment.
validateDefaultsWithAnalyzer still only receives a NamesAndTypesList, so any pre-existing ALIAS/EPHEMERAL body in the table metadata has already been erased before you build the dummy storage here.
That leaves an ALTER hole in the exact invariant this PR is trying to enforce: for example, an existing a String ALIAS _table still lets ALTER TABLE t ADD COLUMN c String DEFAULT a through, because the virtual-column walk only sees a as an ordinary source column and never reaches the underlying _table. The resulting table is still uninsertable on INSERT.
To close the ALTER side you need to validate against the full resulting ColumnsDescription (or otherwise carry the existing alias/ephemeral expressions into the dummy metadata), not just names and types.
There was a problem hiding this comment.
Confirmed real on the current head (build cacbaa30). Both this and the L1386 finding reproduce:
- ALTER over a pre-existing ALIAS:
CREATE TABLE t1 (a String ALIAS _table, c1 UInt16) ENGINE = MergeTree ORDER BY tuple(); ALTER TABLE t1 ADD COLUMN c String DEFAULT a;is accepted, thenINSERT INTO t1 (c1) VALUES (1)fails withCode: 10 NOT_FOUND_COLUMN_IN_BLOCK. prefer_column_name_to_alias = 1and thedummy.<alias>qualifier: a same-statementDEFAULT a(withabeingALIAS _table) is accepted at CREATE.
These are the pre-existing same-class corners already listed as intentionally deferred in the PR description, not the reported #111658 case (a direct DEFAULT/MATERIALIZED over a virtual), which is rejected in all of them. As you note, closing them needs validation against the full resulting ColumnsDescription (declared ALIAS/EPHEMERAL bodies and declared types) threaded through the CREATE/ALTER/load call sites, plus a recursive alias-resolution fallback for the non-inlined path. That is a larger, separate change than the reported fix.
I scoped this PR to the reported harm to keep it reviewable. I can fold the alias/ephemeral-body threading in here or send a dedicated follow-up, whichever the reviewer prefers.
| assertNoAggregateFunctionNodes(expression_list, "in column DEFAULT expression"); | ||
|
|
||
| const auto dummy_metadata = storage->getInMemoryMetadataPtr(execution_context, false); | ||
| assertInsertTimeDefaultsDoNotReferenceVirtuals( |
There was a problem hiding this comment.
This check relies on the analyzer having already inlined every alias-mediated path to the virtual column into the resolved projection tree, but that is not true in all supported cases.
With prefer_column_name_to_alias=1 or an explicit dummy.<alias> qualifier, a same-statement DEFAULT/MATERIALIZED that reaches _table through an alias can still get here without ever producing a virtual ColumnNode, so CREATE/ALTER still accepts a permanently uninsertable definition under a supported setting/spelling.
If the goal is to reject every alias-mediated virtual reference, this needs a fallback that resolves alias columns recursively instead of depending only on prior alias inlining.
There was a problem hiding this comment.
Confirmed, reproduced via prefer_column_name_to_alias = 1 and via the dummy.<alias> qualifier. This is one of the same-class corners already deferred in the PR description; closing it needs the same ColumnsDescription-threading plus recursive alias-resolution change. Full disposition on the L1327 thread.
CI finish ledger — 347fbbcEvery failure below has an owner. None are caused by this PR's diff (analyzer default-validation over virtual columns in
Session id: cron:our-pr-ci-monitor:20260724-203000 |
…-default-over-virtual-column
| /// over a virtual column is inert there and is left out of this set. | ||
| NameSet insert_time_default_columns; | ||
| bool defaults_evaluated_at_insert_time = true; | ||
| if (const auto * mv = dynamic_cast<const StorageMaterializedView *>(table.get())) |
There was a problem hiding this comment.
StorageView needs the same alter-time exemption here as external-target materialized views.
InterpreterCreateQuery now explicitly allows CREATE VIEW v (x String DEFAULT _table) AS ..., but InterpreterAlterQuery still calls AlterCommands::validate before StorageView::checkAlterIsPossible. Because this branch only disables insert_time_default_columns for StorageMaterializedView, ALTER TABLE v MODIFY COLUMN x String DEFAULT _table now dies in the new virtual-column check with UNKNOWN_IDENTIFIER instead of reaching the storage's existing NOT_IMPLEMENTED.
So the "objects that never evaluate their own column defaults over an insert block are exempt" rule is still inconsistent between CREATE and ALTER for ordinary views. StorageView needs the same defaults_evaluated_at_insert_time = false handling here.
There was a problem hiding this comment.
Confirmed on head 110c0f9 (build 65d86958): CREATE VIEW v (x String DEFAULT _table) AS ... succeeds, then ALTER TABLE v MODIFY COLUMN x String DEFAULT _table throws Code: 47 UNKNOWN_IDENTIFIER from the new check in AlterCommands::validate, which runs before StorageView::checkAlterIsPossible (NOT_IMPLEMENTED). CREATE exempts is_ordinary_view; ALTER only exempts external-target MVs, so the exemption is inconsistent for ordinary views, as you note.
The impact is the error code only: an ordinary view rejects every column ALTER with NOT_IMPLEMENTED regardless, so this operation fails either way (47 vs 48), not a newly-broken workflow.
The consistent one-line fix at AlterCommands.cpp:1691:
if (const auto * mv = dynamic_cast<const StorageMaterializedView *>(table.get()))
defaults_evaluated_at_insert_time = mv->hasInnerTable();
else if (table->as<StorageView>())
defaults_evaluated_at_insert_time = false;I have the fix + an ALTER-view NOT_IMPLEMENTED test ready. I did not push it now to avoid restarting the CI currently running on this head for a code-only change on an already-unsupported operation. I can fold it into the next review wave, or leave it as a follow-up, whichever you prefer.
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 103/105 (98.10%) · Uncovered code |
CI finish ledger — 110c0f9Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task whose fixing-PR link will be posted here when it opens. Only
This PR's diff is DEFAULT/MATERIALIZED-over-virtual-column validation ( Session id: cron:our-pr-ci-monitor:20260725-033000 |
d312f95
Closes: #111658
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix
CREATE TABLE/ALTER TABLEwith the analyzer accepting a columnDEFAULT/MATERIALIZEDexpression that references a virtual column such as_tableor_database. Inserting into such a table failed withNOT_FOUND_COLUMN_IN_BLOCK, and aMATERIALIZEDcolumn (which cannot be supplied explicitly) made the table permanently un-insertable. These expressions are now rejected at definition time, matching the behavior without the analyzer.ALIAScolumns (read-time) andEPHEMERALcolumns (non-stored insert inputs) over virtual columns keep working.Description
With the analyzer, column defaults are validated by resolving
SELECT <defaults> FROM dummyover aStorageDummybuilt from the declared columns. Like every storage,StorageDummyexposes the common virtual columns_table/_database, so aDEFAULT/MATERIALIZEDexpression referencing one of them resolved during validation. But that expression is evaluated over an insert block, which never contains virtual columns, so an insert failed withNOT_FOUND_COLUMN_IN_BLOCK(and withMATERIALIZEDthe column cannot be supplied, so the table is permanently un-insertable). The non-analyzer path only sees the declared columns and already rejected these.After the analyzer resolves the defaults, a
DEFAULT/MATERIALIZEDcolumn whose expression reads a virtual column, directly or transitively through an alias within the same statement, is rejected withUNKNOWN_IDENTIFIER.ALIAS/EPHEMERALmay still reference virtual columns, so they keep working; a real column that happens to be named like a virtual is a declared column and is left untouched; a subcolumn (e.g.a.x) is not a virtual column. CoversCREATE TABLEandALTER TABLE ADD/MODIFY COLUMN. Objects that never evaluate their own column defaults over an insert block are exempt: ordinary views, and external-target (TO) materialized views (which forward inserts to the target). An inner-table materialized view does apply its column defaults on insert, so it stays checked.Reproducer (before this PR, with the analyzer):
Existing tables created by an affected version still load: default validation runs only at
CREATE(or for typeless defaults), not onATTACH, so such a table attaches unchanged (it stays un-insertable, as before), and an unrelatedALTERon it does not start failing.This targets the reported case: a
DEFAULT/MATERIALIZEDthat references a virtual column directly (and transitively when the analyzer inlines the alias). A few pre-existing corners in the same class are intentionally left for a dedicated follow-up, as they need the full resulting column set (with declared types) during validation rather than the local one: aDEFAULTreaching a virtual only through a pre-existingALIAS/EPHEMERALonALTER;CREATE TABLE ... AS <legacy_table>copying an already-invalid default; and the transitive case underprefer_column_name_to_alias=1or via an explicitdummy.<alias>qualifier (the analyzer does not inline the alias there). The direct reported case is handled in all of these.