Skip to content

Resolve a database-qualified parameterized view call in INSERT SELECT and EXPLAIN SYNTAX the same way as in SELECT - #128992

Merged
PedroTadim merged 5 commits into
ClickHouse:masterfrom
groeneai:fix-parameterized-view-qualified-name-legacy-lookup
Nov 4, 2026
Merged

PedroTadim merged 5 commits into
ClickHouse:masterfrom
groeneai:fix-parameterized-view-qualified-name-legacy-lookup

Conversation

@groeneai

@groeneai groeneai commented Nov 3, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #128872
Related: #119027
Related: #118193

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Fixed UNKNOWN_FUNCTION in the refresh of a refreshable materialized view that reads a parameterized view as db.view(...) into a ReplicatedMergeTree table (always in a Replicated database, after a restart in an Atomic one), and in INSERT ... SELECT from `db.view`(...) into a ReplicatedMergeTree or Distributed table. A formatted query now keeps db.view(...) in two parts. Closes #128872.

Description

On 26.10.3.7 and 25.8, SYSTEM REFRESH VIEW of a refreshable materialized view that reads db.view(...) into a ReplicatedMergeTree table fails with UNKNOWN_FUNCTION: always in a Replicated database, after a restart in an Atomic one.

The formatter wrote db.view(...) as `db.view`(...), which parses back as a one-part name. The analyzer splits such a name on the dot, so SELECT works. Context::executeTableFunction and the EXPLAIN SYNTAX view inlining split it only for a name the parser marked as compound. INSERT ... SELECT reaches executeTableFunction whenever parallel_distributed_insert_select is non-zero (the default is 2).

Both places now use extractDatabaseAndTableNameForParameterizedView, so views already stored as `db.view`(...) work unchanged; if the split of such a one-part name is not a parameterized view, they try the whole name in the current database, so a view named `v.x` still resolves with the old analyzer of 26.3 and 26.8. ASTFunction writes a compound name part by part, quoting a keyword part, and the analyzer marks a two-part parameterized view name compound in its AST, so stored definitions, Replicated DDL and queries sent to shards keep db.view(...).

The test covers INSERT ... SELECT into ReplicatedMergeTree and Distributed, a refreshable view stored as `db.view`(...) reloaded by DETACH/ATTACH that appends into the source of an ordinary materialized view, the same in a Replicated database, EXPLAIN SYNTAX, the formatter (also with keyword parts) and the analyzer's AST; each fails on master and passes with the fix (randomized runs), plus three guards for a view named `v.x`.

#119027 makes the same formatter change but no longer applies to master. #118193 rewrites the same lookup for hierarchical names; either merge order keeps this call.


Workflow [PR]
Sync PR [sync-upstream/pr/128992]

Version info

  • Merged into: 26.11.1.1361-master (included in 26.11 and later)

… and EXPLAIN SYNTAX like SELECT does

A stored query writes `db.view(...)` as `` `db.view`(...) ``, which parses
back as a one-part name without the parser's compound-name flag (Replicated
database DDL entries, Atomic metadata after a restart or ATTACH). The analyzer
splits such a name on the dot with extractDatabaseAndTableNameForParameterizedView,
but Context::executeTableFunction and the EXPLAIN SYNTAX view inlining split it
only when the flag is set, so they looked for a view literally named `db.view`
in the current database and failed with UNKNOWN_FUNCTION.

INSERT ... SELECT reaches executeTableFunction through
JoinedTables::getLeftTableStorage whenever parallel_distributed_insert_select is
not 0 (the default): the replicated and Distributed destination checks resolve
the source there. So an INSERT into ReplicatedMergeTree or Distributed, and the
refresh of a refreshable materialized view into a replicated table, failed.

Both places now call the analyzer's helper. Names with three or more parts
still fall through to the table function factory, as before.

Closes ClickHouse#128872
Related: ClickHouse#119027, ClickHouse#118193

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

groeneai commented Nov 3, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 0 findings) plus my own cold review of the same head (0 findings).

# Sev Finding Verdict Evidence / action
- - no findings - -

Severity: ❌ blocker / ⚠️ major / 💡 nit.

Session id: cron:clickhouse-review-slot-8:20261103-124500

@groeneai

groeneai commented Nov 3, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. On master the issue's script (single server, embedded Keeper) fails every time with REFRESH_FAILED ... UNKNOWN_FUNCTION, in a Replicated database and in an Atomic one after a restart; the new test fails on all 5 cases.
b Root cause explained? A stored query writes db.view(...) as `db.view`(...), a one-part name after parsing. The analyzer splits it on the dot; Context::executeTableFunction and the EXPLAIN SYNTAX inlining split only parser-marked compound names, so they look up a view literally named db.view.
c Fix matches root cause? Yes. Both places now use the analyzer's extractDatabaseAndTableNameForParameterizedView, so the two resolvers agree; no guard at the call sites.
d Test intent preserved / new tests added? New test 05493_parameterized_view_qualified_name_insert_select.sh: INSERT ... SELECT into ReplicatedMergeTree and into Distributed, a refreshable view reloaded by DETACH/ATTACH feeding an ordinary materialized view, a refreshable view in a Replicated database, EXPLAIN SYNTAX.
e Both directions demonstrated? Yes. Master: all 5 cases fail (UNKNOWN_FUNCTION x2, REFRESH_FAILED x2, EXPLAIN not inlined). Fix: passes, 50 of 50 randomized runs; the issue's script and the restart variant pass too.
f Fix is general across code paths? No other code reads the compound-name flag outside the parser and formatter. QueryAnalyzer::resolveTableFunction and DESCRIBE already used the helper; every legacy caller (InterpreterInsertQuery, StorageDistributed, WhatIfEstimator, interpretSubquery, getTableExpressions) goes through executeTableFunction.
g Fix generalizes across inputs (params/datatypes/wrappers)? One-part names unchanged; two-part names, quoted or not, fixed; 3+ parts, a missing database, a non-view table and a view literally named a.b give the same UNKNOWN_FUNCTION as before. Type wrappers: N/A (name resolution only).
h Backward compatible? (maintainer-approved exception only) Yes. No setting, format or protocol change; stored definitions keep their text and start resolving.
i Invariants and contracts preserved? executeTableFunction still returns the view storage for a parameterized view and otherwise the table function or the same UNKNOWN_FUNCTION, with the same default database. EXPLAIN SYNTAX returns early on the same unsplittable names.

Session id: cron:clickhouse-impl-slot-40:20261103-112900

@clickhouse-gh

clickhouse-gh Bot commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [3e8fc3b]

Summary: ✅


AI Review

Summary

Reviewed PR #128992 at 3e8fc3b8941932954a8390709e0c30535c11ffc8. The change fixes qualified parameterized-view lookup in INSERT ... SELECT and EXPLAIN SYNTAX, and preserves qualified names when formatting queries. The earlier dotted-name and keyword concerns are addressed; no new actionable findings.

Consumers traced: parser/formatter round trips preserve the function-name string; QueryAnalyzer and DESCRIBE retain their existing name splitting; Context::executeTableFunction and JoinedTables accept stored qualified names; EXPLAIN SYNTAX retains literal dotted-name lookup; stored/replicated definitions and distributed queries receive separately formatted name parts; IN set hashing retains the same names and arguments.

Missing context / blind spots
  • ⚠️ No local build or runtime tests were run. Runtime evidence comes from the author's recorded before/after reproductions and the available CI reports, which show no failures; the filtered CI results did not separately identify the new regression test.
Final Verdict

Status: ✅ Approve. No new inline findings to post.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Nov 3, 2026
@groeneai

groeneai commented Nov 3, 2026

Copy link
Copy Markdown
Collaborator Author

cc @SmitaRKulkarni, could you review this and add the can be tested label so CI runs? Context::executeTableFunction and the EXPLAIN SYNTAX inlining split a parameterized view name on the dot only when the parser flagged it as compound, which a stored `db.view`(...) never is; both now use the analyzer's extractDatabaseAndTableNameForParameterizedView.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Nov 3, 2026
@PedroTadim PedroTadim self-assigned this Nov 3, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-view Logical (non-materialized) views. label Nov 3, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 3e8fc3b89 with master c8383042c (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of b306e87de; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

10 translation units recompiled, 56 s compile time in total, 10 of them have a recent master baseline.

Job report

@PedroTadim

Copy link
Copy Markdown
Member

🕵️ @groeneai

Using the analyzer's split in executeTableFunction and in the EXPLAIN SYNTAX inlining makes all three readers agree, and it fixes views already stored as `db.view`(...) without touching their metadata. A few points:

  1. The formatter is where the name breaks. ASTFunction::formatImpl writes the compound name through backQuoteIfNeed(name), so db.view(...) comes out as `db.view`(...) and is_compound_name is lost on the next parse. This PR fixes the readers, which is needed anyway for definitions already stored. But every query formatted again (stored views, queries forwarded to shards by parallel_distributed_insert_select, replicated DDL) still carries the ambiguous spelling, and a server without this patch, for example an older shard in a mixed-version cluster, still throws UNKNOWN_FUNCTION. Writing `db`.`view`(...) when isCompoundName() is set would remove the ambiguity at the source. Could that go here or in a follow-up? After this PR nothing reads isCompoundName(), so otherwise the flag is dead.

  2. A view whose own name contains a dot. `v.x`(p = 1) used to resolve in executeTableFunction as {current_db, 'v.x'}; now it is always split into {v, x}, and there is no fallback to the literal name. The analyzer already behaved this way, so it is consistent, but with enable_analyzer = 0 such a view used to work and now throws UNKNOWN_FUNCTION. If that is intended, a line in the description would help; otherwise, trying the literal name when the split lookup finds nothing would keep it.

  3. Pre-existing, not from this PR: tryExpandTableExpression inlines the view body for EXPLAIN SYNTAX without any access check, so EXPLAIN SYNTAX SELECT * FROM secret_db.pv(p = 1) prints the definition to a user who could not run SHOW CREATE on it. The backquoted spelling now reaches that path too. It may be worth a separate issue.

…ormatting

The formatter wrote the compound name of `db.view(...)` as one quoted
identifier, `` `db.view`(...) ``, which parses back as a one-part name. Stored
definitions, Replicated database DDL and queries sent to other servers then
carried the ambiguous spelling, and a server that splits such a name only for
a compound identifier (any release before the previous commit) failed with
UNKNOWN_FUNCTION.

ASTFunction now writes a compound name part by part, and TableFunctionNode
marks a two-part parameterized view name as compound when the analyzer
converts the query tree back to an AST.

Context::executeTableFunction and the EXPLAIN SYNTAX view inlining also fall
back to the whole name in the current database when the split name does not
resolve, so a view whose own name contains a dot, `` `v.x`(...) ``, is still
found where it was before (the old analyzer on releases that still have it).

Related: ClickHouse#119027

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

groeneai commented Nov 3, 2026

Copy link
Copy Markdown
Collaborator Author

Thanks, all three are addressed in 0a69293.

  1. Done here. ASTFunction now writes a compound name part by part (db.view(...), `my-db`.view(...); a one-part `db.view`(...) stays as is), and TableFunctionNode::toASTImpl marks a two-part parameterized view name compound, so the IN subquery the analyzer sends to a shard now reads db.pv(...) instead of `db.pv`(...) (checked in system.query_log). New definitions and Replicated DDL keep the two parts. Definitions stored before still rely on the readers from the first commit, so the refresh cases in the test now create the view with the backquoted spelling.

  2. I added the fallback instead of a description line: when the split name does not exist, executeTableFunction and the EXPLAIN SYNTAX inlining try the whole name in the current database, so a view whose own name has a dot is still found there. Measured: `v.x`(p = 3) works with enable_analyzer = 0 on 26.8.18 and 26.3.42 and fails with the analyzer on both. On master it already fails before this PR (SELECT, INSERT SELECT, CREATE VIEW, DESCRIBE), so the fallback matters for the old analyzer in backports. The test covers the EXPLAIN SYNTAX side; on master no other reader reaches it.

  3. Confirmed on master: a user with no grant on secret_db gets the body of secret_db.pv(p = 1), literals included, from EXPLAIN SYNTAX, while SHOW CREATE returns ACCESS_DENIED. Check access rights in EXPLAIN QUERY TREE and EXPLAIN SYNTAX #110180 tried a general access check for EXPLAIN and was closed by its author, who asked for the check where the information is obtained; for this path that is tryExpandTableExpression. I'll send it as a separate PR and link it here.

The new test cases fail on master and pass with the fix (50/50 randomized runs), and the parameterized view and EXPLAIN SYNTAX suites pass. The description is updated.

@PedroTadim

Copy link
Copy Markdown
Member

🕵️ @groeneai

Thanks, the formatter change is what I hoped for, and the v.x fallback is a good addition. One problem with the new writeFunctionName, though:

A keyword part makes the query unparsable. Each part goes through backQuoteIfNeed, which does not quote keywords. The parser sets is_compound_name on every a.b(...) call, not only on table functions. So `null`.pv(1) now comes out as null.pv(1), and in expression context that does not parse. On master's parser:

SELECT 1 IN null.pv(1)   -- Syntax error
SELECT 1 IN not.pv(1)    -- Syntax error
SELECT 1 IN true.pv(1)   -- Syntax error
SELECT null.f(1)         -- Syntax error, the same for not, all, distinct, true

Before this commit, all of them were written as `null.pv`(1) and parsed back. Now:

  • the IN subquery the analyzer sends to a shard for a view in such a database does not parse there;
  • a view stored with x IN `null`.pv(p = 1) would not load after a restart;
  • in debug builds, the round-trip check in executeQuery turns the SYNTAX_ERROR into LOGICAL_ERROR "Inconsistent AST formatting" for every such query, so the fuzzers will hit it.

ASTIdentifier already handles this for compound names: it writes each part with settings.writeIdentifier(ostr, part, /*ambiguous=*/false), which keeps `null`.x quoted, and it also follows always_quote_identifiers and the quoting style. Using the same call per part in writeFunctionName should fix it. Could you add `null`.pv(...) and `not`.pv(...) (in FROM and in IN) to the test?

Write each part of a compound function name with
`FormatSettings::writeIdentifier`, as `ASTIdentifier` does, so the
quoting rule and style apply to it as well. A part that is a keyword is
passed as ambiguous and stays quoted: after the per-part change in the
previous commit, `1 IN \`partition\`.pv(1)` was formatted as
`1 IN partition.pv(1)`, which does not parse (the expression parser
stops before `IN PARTITION`), and a debug build aborted on it in the
format round-trip check of `executeQuery`.

A sweep of every single-word keyword in 44 expression and FROM contexts
finds no other part that breaks the round trip, before or after this
change; `null`, `not`, `true`, `all` and `distinct` were already quoted
by `backQuoteIfNeed`. The test checks `null` and `not` in FROM and IN,
and `partition` in IN.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

groeneai commented Nov 3, 2026

Copy link
Copy Markdown
Collaborator Author

The EXPLAIN SYNTAX access check from point 3 of the earlier review is in #129074.

The literal-name fallback in `Context::executeTableFunction` and in the
`EXPLAIN SYNTAX` view inlining exists for a view whose own name has a
dot, written `` `v.x`(...) ``. For an unquoted `v.x(...)` the parser
already says the name is the view `x` of database `v`, which is what
the analyzer resolves and what both places resolved before; retrying it
as a view named `v.x` in the current database made `EXPLAIN SYNTAX`
inline a view that `SELECT` rejects with `UNKNOWN_FUNCTION`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

groeneai commented Nov 3, 2026

Copy link
Copy Markdown
Collaborator Author

Thanks, fixed in 5509515, with one related change in 7f0ac12.

  • Each part now goes through settings.writeIdentifier, so always_quote_identifiers and the quoting style apply to it. On the previous head the null, not, true, all and distinct parts were already quoted, because backQuoteIfNeed uses the same writeProbablyBackQuotedString word list (SELECT 1 IN `null`.pv(1) came back unchanged). So the call with ambiguous = false alone would not have changed anything. I swept every keyword in system.keywords through 44 expression and FROM contexts (format, parse back, compare). Only one part broke: partition after IN, because the expression parser stops before IN PARTITION. SELECT 1 IN `partition`.pv(1) was written as partition.pv(1), and a debug build aborted on it in the round-trip check. A part that is a keyword is now passed as ambiguous, so it stays quoted, and the sweep finds nothing after the change.
  • The test now has `null`.pv and `not`.pv in FROM and IN, plus `partition`.pv in IN, each checked to parse back to the same text. The partition line fails on the previous head.
  • The v.x fallback now applies only to a name the parser did not split. An unquoted v.x(...) is the view x of database v, as before this PR, so EXPLAIN SYNTAX no longer inlines a view named v.x that SELECT rejects. A test line covers it.

@PedroTadim

Copy link
Copy Markdown
Member

🕵️ @groeneai One corner case in the new fallback in Context::executeTableFunction, and the same one in the EXPLAIN SYNTAX view inlining.

The current database is tried only when the split lookup finds no table at all (if (!table && ...)). If the split names a table that exists but is not a parameterized view, the fallback is skipped. On master, the same query would have resolved the view through the current database:

CREATE DATABASE v;
CREATE TABLE v.x (a UInt8) ENGINE = Memory;
CREATE VIEW `v.x` AS SELECT {p:UInt8} AS a;   -- in the current database
INSERT INTO dst SELECT * FROM `v.x`(p = 1);   -- now UNKNOWN_FUNCTION

This only matters where a view named `v.x` resolves at all: the old analyzer of the 26.3 and 26.8 backports, and INSERT ... SELECT through executeTableFunction. Falling back also when the table found is not a parameterized view would keep it:

auto is_parameterized_view = [](const StoragePtr & storage)
{
    const auto * view = storage ? storage->as<StorageView>() : nullptr;
    return view && view->isParameterizedView();
};
if (!is_parameterized_view(table) && !function->isCompoundName() && table_name != function->name)

Apart from that, I don't see a regression in other places. The parser reads back every form the formatter now writes under any quoting setting (`db`.`pv`(...), "db"."pv"(...), a keyword part like `partition`.pv(...)). Older shards and replicas split the compound db.view(...) correctly.

…a parameterized view

A stored `v.x`(...) is first read as the view `x` of database `v`. If that
names a table that exists but is not a parameterized view, the lookup in
`Context::executeTableFunction` and the `EXPLAIN SYNTAX` inlining skipped the
current-database view `v.x`, which master resolved there. Fall back to the
literal name whenever the split does not find a parameterized view.

Reported by @ PedroTadim in
ClickHouse#128992 (comment)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

groeneai commented Nov 4, 2026

Copy link
Copy Markdown
Collaborator Author

Thanks, fixed in 3e8fc3b: Context::executeTableFunction and the EXPLAIN SYNTAX inlining now try the whole name in the current database whenever the split does not find a parameterized view, with your is_parameterized_view check.

With your fixture, EXPLAIN SYNTAX SELECT * FROM `v.x`(p = 1) inlines the view on master and with this commit, and did not on the previous head. The new test arm is the same case (a view `<db>.src` in the current database, where <db>.src is a MergeTree table) and fails only on the previous head. I updated the description.

@PedroTadim
PedroTadim enabled auto-merge November 4, 2026 15:12
@PedroTadim
PedroTadim added this pull request to the merge queue Nov 4, 2026
Merged via the queue into ClickHouse:master with commit 6398caf Nov 4, 2026
185 checks passed
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 4, 2026
middas-0706 pushed a commit to middas-0706/ClickHouse that referenced this pull request Nov 4, 2026
… definition

`ExpandParameterizedViewsMatcher::tryExpandTableExpression` replaced a
parameterized view call with the view's stored query before any analysis and
without any access check. A user refused `SHOW CREATE` on the view (no
`SHOW COLUMNS`) therefore read the whole definition, literals included, from
`EXPLAIN SYNTAX` or `EXPLAIN AST optimize = 1`. With the default
`run_query_tree_passes = 0` nothing checks access afterwards; with
`run_query_tree_passes = 1` only the tables behind the view are checked.

Require `SHOW COLUMNS` on the view at the point the definition is read, the
privilege `SHOW CREATE`, `system.tables.create_table_query` and
`DESCRIBE pv(...)` already require, and otherwise leave the call as written,
like the existing `SQL SECURITY DEFINER` branch. Not throwing keeps an
inaccessible view printing like an unknown name in the default mode, as
`DESCRIBE` does. The check is keyed on the resolved storage rather than the
parsed name.

Reported by PedroTadim in the review of ClickHouse#128992.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
AdeilH pushed a commit to AdeilH/ClickHouse that referenced this pull request Nov 5, 2026
… a dot

The parser joins the parts of a compound function name with a dot and keeps
only the joined string plus the compound flag. A back-quoted part may itself
contain dots. Since ClickHouse#128992 the formatter writes a compound name part by part
and split the joined name on every dot, so `..` inside a part, or a part that
starts or ends with a dot, produced an empty part, written as an empty quoted
identifier that ParserIdentifier rejects:

    SELECT `a..b`.f(1)  ->  SELECT a.``.b.f(1)

The debug-build round trip in executeQuery then throws LOGICAL_ERROR
"Inconsistent AST formatting". The AST fuzzer reaches it through `{N..M}`
globs turned into quoted identifiers (STID 1941-26fa, 1941-1bfa).

The original part boundaries are not recoverable from the joined name, so
choose them leftmost-greedy: a dot separates two parts only when the part
before it is non-empty and text follows it. Every name the parser produces
(at least two non-empty parts) still gets at least two parts with the same
joined name, so it parses back as a compound name; Context::executeTableFunction
and the EXPLAIN SYNTAX view inlining take a different path for a non-compound
name, so writing such a name as one quoted token would change their decision
after a round trip. Names without an empty part are written exactly as before.
A name with no compound spelling (`v.`, only from AST JSON or the analyzer)
is written as one quoted token, as before ClickHouse#128992.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-view Logical (non-materialized) views. pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Refreshable materialized view reading a database-qualified parameterized view into a ReplicatedMergeTree table fails with UNKNOWN_FUNCTION

3 participants