Repository navigation
Qualify a parameterized view's name when rendering it for another server - #113550
Conversation
A parameterized view referenced unqualified in a query that is shipped to a shard arrived at the shard without its database, because TableFunctionNode::toASTImpl emitted table_function_name -- the identifier as the user wrote it -- and never consulted storage_id. The shard then re-resolved the name against its own default database. Measured on a two-shard cluster with the session database set to the view's database and the call unqualified: non-GLOBAL IN through a Distributed table, JOIN ... ON, JOIN ... USING and remote() all failed with UNKNOWN_FUNCTION raised by the remote shard. When the shard's default database happened to hold a same-named parameterized view the query instead returned a silently wrong answer -- 3 rows where 6 is correct, with the failing shard contributing none and nothing on stderr. Before ClickHouse#68978 a parameterized view became a TableNode, whose toASTIdentifier qualifies from storage_id, so this path is the one that lost the database. The initiator's database is the correct target. A parameterized view is expanded against the initiator's catalog and storage_id can never lack a database, since extractDatabaseAndTableNameForParameterizedView defaults it to the current database. The cross-replication case that TableNode::toASTIdentifier guards against is expressed by Cluster::maybeCrossReplication, which buildQueryTreeForShard consults to hand TableNode a deliberately empty database; no cluster or context reaches toASTImpl, so that signal cannot apply here. The parameterized-view discriminator is required rather than decorative: a regular table function also carries a real storage id, so unconditional qualification would render numbers(3) as system.numbers(3). Qualification is also skipped unless the result is a two-part identifier, because extractDatabaseAndTableNameForParameterizedView resolves only one or two parts -- a database whose name contains a dot has no resolvable qualified spelling and is left as it is today. The change is confined to rendering, so query-tree identity is untouched: EXPLAIN QUERY TREE and EXPLAIN SYNTAX are byte-identical before and after, which is why the name is not rewritten at resolve time. Closes ClickHouse#65318
Internal second-model review (click to expand)An independent cold code review plus a second-model review pass ran against this change before it
The dotted-database row relies on an error-message substring, which is brittler than a structural Session id: cron:clickhouse-review-slot-48:20260805-163002 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-41:20260805-121400 |
|
cc @vdimir @devcrafter, could you review this? A parameterized view referenced unqualified lost its database when the query was rendered for a shard, because TableFunctionNode::toASTImpl emitted the name the user typed and never consulted storage_id, so the shard re-resolved it against its own default database and either failed with UNKNOWN_FUNCTION or silently read a same-named view. |
|
Workflow [PR], commit [29fb308] Summary: ❌
AI ReviewSummaryThis PR tries to keep an unqualified parameterized view bound to the initiator's database when a distributed query is rendered for another server. The current fix is not correct yet: it synthesizes Findings❌ Blockers
Final Verdict❌ Changes requested. LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 8/8 (100.00%) · Uncovered code |
| { | ||
| const auto database_name = storage_id.getDatabaseName(); | ||
| if (Identifier{database_name}.getPartsSize() == 1) | ||
| table_function_ast->name = database_name + "." + storage_id.getTableName(); |
There was a problem hiding this comment.
This builds a qualified parameterized-view name as plain text, but the shard path still serializes the query back to SQL through formattedAST (src/Processors/QueryPlan/ReadFromRemote.cpp:178-189). ASTFunction::formatImplWithoutAlias prints name as a single identifier via backQuoteIfNeed(name) (src/Parsers/ASTFunction.cpp:937-945), so the new value here is emitted as `db.view`(...) instead of db.view(...).
That is still resolved incorrectly on the remote side: Context::executeTableFunction only splits database and table when isCompoundName() is set (src/Interpreters/Context.cpp:2980-2989). Since TableFunctionNode only stores a String, this new path drops the compound-name structure entirely, so a distributed query can still hit the current database or throw Unknown table function.
The fix needs to preserve a real compound function name through the AST/formatter path, not just concatenate database + "." + table into ASTFunction::name.
There was a problem hiding this comment.
You are right that the name is emitted as a single backquoted token, and wrong that it then
resolves incorrectly. I measured both halves on this head.
The shard really does receive the backquoted form. This is the shard's own system.query_log row
(is_initial_query = 0) for the distributed query:
SELECT shardNum() AS `_shard_num`, count() FROM `probe15`.`local_data` AS `__table1`
WHERE `__table1`.`tenant_id` IN (
SELECT ... FROM `probe15.pv`(`tenants` = _CAST(['t1'], 'Array(String)')) AS `__table1`)
It resolves anyway, because the analyzer does not use isCompoundName(). A parameterized view is
resolved at QueryAnalyzer.cpp:4512 through extractDatabaseAndTableNameForParameterizedView
(src/Analyzer/Utils.cpp:1194), which re-splits the name string itself:
Identifier table_identifier{table_function_name}; // Utils.cpp:1199, splits on '.'
if (getPartsSize() == 2) { database_name = table_identifier[0]; table_name = table_identifier[1]; }So the backquoting is lossless here: `db.pv` parses back to the name db.pv with
is_compound_name = false, and the analyzer splits the string regardless.
Context::executeTableFunction, which you cite, is the old-analyzer path.
End to end on a two-shard cluster, with a same-named view in default so an incorrect resolution
shows up as a wrong answer rather than an error:
| binary | name the shard received | per-shard rows | total |
|---|---|---|---|
| master before this PR | pv(...) |
1 3 only |
3, wrong |
| this PR | `probe15.pv`(...) |
1 3 and 2 3 |
6, correct |
One asymmetry is real but not introduced here: with enable_analyzer = 0 the backquoted spelling
does fail with Code: 46, since that path is keyed on the parser flag. It is unreachable from the
initiator, because enable_analyzer is not shipped to the shard (I set it to 0 and to 1 on the
initiator and the secondary query's own Settings map carried no entry either time, so the shard
uses its own default). And with enable_analyzer = 0 there is no query tree, toASTImpl never
runs, the name is never qualified, and the per-shard result is 1 3 on both binaries, which is
the pre-existing bug this PR does not change.
CI finish ledger — 29fb308Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
CI is otherwise finished on this head: 175 check-runs, 0 incomplete, None of the three is caused by this PR. Its diff is confined to
Session id: cron:our-pr-ci-monitor:20260806-020000 |
203da0b
…ch on shards An `IN` set is named `__set_<tree hash of its subquery>`, and that name is part of every column a shard returns whose expression contains the `IN` (an aggregate argument, a `GROUP BY` key, a `SELECT` item); the initiator matches those columns by name. `TableFunctionNode::updateTreeHashImpl` hashed a parameterized view call as typed (`pv`), while `toASTImpl` sends it qualified (`default.pv(...)`, ClickHouse#113550), so each shard hashed a different name and the query failed with `NOT_FOUND_COLUMN_IN_BLOCK`, or `THERE_IS_NO_COLUMN` with `serialize_query_plan = 1`. A resolved parameterized view is now hashed by `storage_id.getFullNameNotQuoted()`, the way `TableNode` hashes its storage. For a call typed qualified the hash bytes are unchanged, so a fixed initiator works with 26.9 and unfixed master shards and a 26.9 initiator behaves as before. Hashing only the storage id (without the name bytes) also fixes a single-version cluster, but breaks the qualified spelling against 26.9 and unfixed master shards in both directions (measured), so the name bytes are kept. `isEqualImpl`, `toASTImpl` and `dumpTreeImpl` are unchanged, so `EXPLAIN QUERY TREE` and `EXPLAIN SYNTAX` output does not change. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Closes: #65318
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed a parameterized view losing its database when a query referencing it unqualified is sent to a shard, so the shard resolved the name against its own default database. Depending on what that database contained, the query either failed with
UNKNOWN_FUNCTIONor silently returned rows from a different view. AffectsIN,JOINandremote()through aDistributedtable.Description
TableFunctionNode::toASTImplemitted the function name fromtable_function_name, the identifier as the user wrote it, and never consultedstorage_id. An unqualified parameterized-view call therefore stayed unqualified all the way to the shard, which re-resolved it against its own default database.Measured on a two-shard cluster with the session database set to the view's database and the call unqualified:
IN,JOIN ... ON,JOIN ... USINGandremote()all failed withCode: 46 ... Received from 127.0.0.2 ... Unknown table function pv, raised by the remote shard, which is direct evidence the name arrived unqualified. When that shard's default database held a same-named parameterized view, the query instead returned a wrong answer with nothing on stderr: 3 rows where 6 is correct. A qualifieddb.pv(...)call has always worked: the existing workaround.Before #68978 a parameterized view became a
TableNode, whosetoASTIdentifierqualifies fromstorage_id; keeping it a resolvedTableFunctionNodeis what lost the database.The initiator's database is the correct target. A parameterized view is expanded against the initiator's catalog, and its
storage_idalways has a database, sinceextractDatabaseAndTableNameForParameterizedViewdefaults it to the current one. The cross-replication case thatTableNode::toASTIdentifierguards against is expressed byCluster::maybeCrossReplication, whichbuildQueryTreeForShardconsults to handTableNodean empty database; no cluster or context reachestoASTImpl, so that signal cannot apply here.Two conditions keep the change narrow. The parameterized-view discriminator is required: a regular table function also carries a storage id, whose database is the internal
_table_function, so unconditional qualification rendersnumbers(3)as_table_function.numbers(3), and a test pins that. Qualification is also skipped unless the result is a two-part identifier, since that helper resolves only one or two parts, so a dotted database name is left as it is today.The change is render-only:
EXPLAIN QUERY TREEandEXPLAIN SYNTAXare byte-identical before and after.Version info
26.8.1.902(included in26.8and later)