Repository navigation
Support hierarchical (dotted) database and table names - #118193
alexey-milovidov wants to merge 106 commits into
Conversation
Implements #71171. A qualified name `a.b.c` is resolved against the catalog: as written, then the longest database prefix first (`a.b` with the table `c`, then `a` with the table `b.c`), then the table `a.b.c` of the current database. Quoting does not matter. `USE a.b` selects the database `a.b`, the namespace of tables `b.*` of the database `a`, or the databases `a.b.*`; unqualified names inside such a session resolve relatively, and `SHOW TABLES` lists the tables under the selected name. The unquoted parts of a name never create a new namespace: `CREATE TABLE a.b.c` places the table into `a` as `b.c` only when `a` already has tables `b.*`. The resolution is centralized in `DatabaseCatalog` and used by `Context::resolveStorageID`, `DatabaseCatalog::getTableImpl`, `AddDefaultDatabaseVisitor` and the CREATE/DROP/RENAME/EXISTS/SHOW TABLES interpreters. `ASTTableIdentifier` keeps any number of parts; the parsers that hand-rolled `[db.]table` share `parseDatabaseAndTableAsAST`. Co-Authored-By: Claude Fable 5.1 <[email protected]>
|
Workflow [PR], commit [2b84d2e] Summary: ❌
|
This comment was marked as low quality.
This comment was marked as low quality.
- clang-tidy: bind the table name by const reference in `tryResolveTableIdentifier`. - 04339: a three-part `ASTTableIdentifier` in the JSON AST is a valid hierarchical name now, check the round trip instead of the rejection. - The statement documentation lives in the parsers' doc strings (`R"DOCS_MD(`), so count `src/Parsers/` as source-owned documentation in the feature docs hook. Co-Authored-By: Claude Fable 5.1 <[email protected]>
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes76 object files changed (+1.01 MiB total), 1 added.
719 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 units643 translation units recompiled, 3993 s compile time in total, 642 of them have a recent master baseline. |
`InterpreterCreateQuery` and `InterpreterRenameQuery` checked the access for the name as written (`a.b`.`c` for `CREATE TABLE a.b.c`) and then resolved it to the table it denotes (`a`.`b.c`), so a grant on the nonexistent database `a.b` authorized creating tables in, and renaming tables out of, the database `a`. The names are now resolved first, by `resolveHierarchicalNames`, rewriting the query, and `getRequiredAccess` sees the resolved names, the same way `DROP` already did. The targets of a view (`TO a.b.t`) are resolved the same way. For a query executed `ON CLUSTER`, the database may exist on the other hosts only (`test_external_cluster` creates `test_db.test_table` from a control node without the database), so the new `DatabaseCatalog::tryResolveHierarchicalNameForCreation` leaves such a name as written and every host resolves it against its own catalog. A name with an empty part (`.inner_id.x`, `t.`, `a..b`) is not hierarchical anymore: `SHOW TABLES FROM `.o r d i n a r y.`` split it into an empty database name and failed the `!database_name.empty()` assertion in `isDatabaseExist` (`test_convert_ordinary_to_atomic`). CI: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118193&sha=25b640ef04c6a7e8b878a1a82b2c5824b4ff0b4f&name_0=PR&name_1=Integration%20tests%20%28amd_asan_ubsan%2C%20db%20disk%2C%20old%20analyzer%2C%202%2F6%29 PR: #118193 Co-Authored-By: Claude Fable 5.1 <[email protected]>
…d qualified asterisks `SHOW COLUMNS` and `SHOW INDEXES` kept only the first part of a qualified name as the database, so `SHOW COLUMNS FROM db.ns.t` looked for `db`.`t`; they now take all the parts but the last as the database and resolve the name with `DatabaseCatalog::resolveHierarchicalName`, the same way as `DESCRIBE`. `joinGet` and the identifier form of `dictGet` rejected identifiers of more than two parts with `INVALID_IDENTIFIER`, and the string forms split the name with `QualifiedTableName`, which does not accept more than one dot: they use the new `DatabaseCatalog::parseHierarchicalName`, and the dictionaries loader resolves the name hierarchically. A qualified asterisk `ns.t.*` for the table `ns.t`, and a table expression lookup of a hierarchical name, are matched with `matchTableName`, like the column qualifiers. Converting an unresolved table identifier of more than two parts to AST threw a logical error. The test 01936 expected `INVALID_IDENTIFIER` for `dictGet(t.nest.a, ...)`; the name is valid now and the dictionary is not found. PR: #118193 Co-Authored-By: Claude Fable 5.1 <[email protected]>
|
🕵 Thank you, both are fixed in 17bbab5 and covered by
On the smaller note: the resolution does probe which candidate databases and namespaces exist before the access check, so a user without grants can tell |
… the current database `InterpreterCreateQuery::resolveHierarchicalNames` set the database of the query for every placement, so `CREATE TABLE t ON CLUSTER c` (no database written) was shipped as `current_db.t`. `executeDDLQueryOnCluster` tells a name without a database from a name with one: the hosts of a cluster may have their own default databases, and a mixed cluster must be rejected. The test `01152_cross_replication` created the table in the current database instead of failing with `INCONSISTENT_CLUSTER_DEFINITION`. The database is set only when the placement differs from the database as written, or from the current database when none was written (the case of `USE a.b`, which is not a database). Plain names take the same code paths as before, as `InterpreterRenameQuery::resolveHierarchicalNames` already does. CI: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118193&sha=3724928f1dfb5c022cc37fd0e45a6191a3c9a5e7&name_0=PR&name_1=Fast%20test
The test configuration sets `table_engines_require_grant`, so `CREATE TABLE ... ENGINE = Memory` by the test user was denied for the missing `TABLE ENGINE ON Memory` grant, and the following `RENAME` cases failed on the table that was not created. CI: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118193&sha=3724928f1dfb5c022cc37fd0e45a6191a3c9a5e7&name_0=PR&name_1=Fast%20test
The access-control family went through `parseDatabaseAndTableNameOrAsterisks`, which kept the two-part split, so an exact hierarchical name could not be written in a privilege (`GRANT SELECT ON catalog.namespace.table`), in a row policy, or in the corresponding `SHOW` statements, even though the same table is addressed as `catalog.namespace.table` everywhere else. The parser now accepts any number of dot-separated parts before the optional `.*`. A longest-prefix split alone would be wrong: the grant would land on the phantom database `catalog.namespace`, while a query on the same name reads `catalog`.`namespace.table`, so the privilege would name an object no query ever targets. The exact name of an access statement is therefore resolved against the catalog the same way as in a query (the new `resolveHierarchicalNamesForAccess`), so that a privilege or a policy names the object that the same name reads in a `SELECT`. Whole-database elements (`GRANT SELECT ON a.b.*`) and the wildcards are prefixes, not object names, and stay as written. The database-only statements kept reading a single identifier, so a database created as `a.b` could not be renamed or introspected with the same unquoted spelling. `parseDatabaseAsAST` (used by `SYSTEM SYNC/RESTORE DATABASE REPLICA`, `ALTER DATABASE` and `CHECK DATABASE`), `RENAME DATABASE`, and the database branch of `EXISTS DATABASE` / `SHOW CREATE DATABASE` now use the same compound-database parser as `USE`, `CREATE DATABASE` and `DROP DATABASE`. Tests: `05079_hierarchical_names_access` covers `GRANT`, `REVOKE`, `CHECK GRANT` and the row-policy round trip; the new `05183_hierarchical_database_names_admin` covers one dotted case per database-admin statement family. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`02963_invalid_identifier` expected `UNKNOWN_IDENTIFIER` for `t.t.t.*`, but the old analyzer still threw `INVALID_IDENTIFIER`: the `ASTIdentifier` constructor of `DatabaseAndTableWithAlias` rejected more than two name parts, while its `ASTTableIdentifier` counterpart already splits a hierarchical name into the longest database prefix and the last part. It now splits the same way, so both analyzers report the same error for a qualifier that matches no table. A column qualified with the whole hierarchical name of its table (`db.sales.orders.x`) has four parts, which the old analyzer cannot resolve: those two queries of `05077_hierarchical_names` are pinned to `enable_analyzer = 1`. `ON CLUSTER` is not allowed for a `Replicated` database, so the `ON CLUSTER` section of `05080_hierarchical_names_metadata_and_functions` is moved out into the new `05182_hierarchical_names_on_cluster`, tagged `no-replicated-database`, instead of failing the whole test in the `DBReplicated` runs. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
# Conflicts: # src/Interpreters/ExternalDictionariesLoader.cpp # tests/queries/0_stateless/04339_ast_json_review_followup_hardening.reference
…E` and `UPDATE` `InterpreterAlterQuery` (and `DELETE FROM`, `UPDATE`) pinned only the database of the resolved table into the query, so `ALTER TABLE sales.customers ...` inside `USE db` became `db`.`customers` for everything that re-read the query, and `DatabaseReplicated::shouldReplicateQuery` failed with `UNKNOWN_TABLE` in the `DBReplicated` run of `05077_hierarchical_names`. Both parts are set now. The analyzer is mandatory since 26.9, so the old-analyzer query and the `enable_analyzer = 1` pins are dropped from the test. CI: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118193&sha=a73cf98b195e3200fb26bc4f7c05159e88be4fa2&name_0=PR&name_1=Stateless%20tests%20%28amd_llvm_coverage%2C%20old%20analyzer%2C%20s3%20storage%2C%20DBReplicated%2C%20parallel%2C%202%2F3%29 PR: #118193 Co-Authored-By: Claude Fable 5.1 <[email protected]>
…in `OPTIMIZE`, `SYSTEM`, the row policies and the hypothetical objects The statements whose target comes from the widened `[db.]table` parser checked the access on the name as written and then resolved it: a grant on the nonexistent database `db.ns` authorized `OPTIMIZE TABLE db.ns.t`, `SYSTEM ... db.ns.t` (also `ON CLUSTER`, whose fast path returned before any resolution), and `CREATE`/`DROP`/`MOVE`/`SHOW CREATE ROW POLICY ... ON db.ns.t` for the table `ns.t` of the database `db`. The names are now resolved and rewritten into the query before the required access is built, so the check and the operation agree on the table, and the bound query is the one dispatched `ON CLUSTER`. `resolveHierarchicalNameForAccess` also resolves a name without dots (`sales.customers` inside `USE db` is `db`.`sales.customers`). `SHOW COLUMNS` / `SHOW INDEXES` decide the visibility of a remote database from the database the table was resolved to, not from the prefix as written. New test `05227_hierarchical_names_access_ddl` runs every statement with grants on the phantom database only (denied) and then with grants on the real database (allowed). Co-Authored-By: Claude Fable 5.1 <[email protected]>
…adata_and_functions` The analyzer is mandatory since v26.9 and disabling it throws `SETTING_CONSTRAINT_VIOLATION`, which failed the Fast test: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118193&sha=90fd9241dd42588bd7ab3c4c3d11b13aefaa9215&name_0=PR&name_1=Fast%20test #118193 Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Conflicts in `ExternalDictionariesLoader`: master made the context overloads of `resolveDictionaryName` record the dictionary via `addDistributedPlanLocalObject` and return `ResolvedDictionaryName` from the internal resolution; this branch resolves hierarchical names against the current database. Both are kept: the `QualifiedTableName` resolution now also returns `ResolvedDictionaryName`, and the recorded name is the one the hierarchical resolution found.
`UNDROP TABLE db.ns.t` looked for the dropped table in the database `db.ns` even when it was the table `ns.t` of the database `db`, and inside `USE db.ns` `UNDROP TABLE t` looked in the synthetic current database `db.ns`. The name is now bound before the query is dispatched `ON CLUSTER` and executed: to the first candidate of `DatabaseCatalog::getHierarchicalNameCandidates` that has a dropped table (with the given UUID, if any), or else to the placement of the name. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
This run (2026-11-03 07:16 UTC) predates #128774 (merged 09:28 UTC). Its #128774 pins On the 14-day count: 7 of the 10 master failures are before #128774. The 3 after it have other causes: the |
… 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]>
# Conflicts: # src/Analyzer/Resolve/TableExpressionData.cpp # src/Interpreters/Context.cpp
…erarchical names The test came from master with the merge. Its last case pins that an unquoted `v.x(...)` is the view `x` of the database `v` and never the view `v.x` of the current database. With hierarchical names (see `05077_hierarchical_names`), quoting does not matter, so without a database `v` the name is the view `v.x` of the current database, the same as for an ordinary table reference. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…essions on every binding pass A compound right argument of `IN` that starts with an argument of an enclosing lambda (`a -> x IN a.b`) is a field of the argument, not a table, so the binding visitors no longer convert it to a table identifier bound to another split (`r`.`a.b`). Both traversals (`visit` and `visitTableExpressions`) track the lambda arguments. The second binding pass of `CREATE` (`visitTableExpressions` of the column list) now has the same unknown-column scope as the first one, so a column default `1 IN a.b` with a tuple column `a` stays an expression. The binding scope of `ALTER` also includes the columns added or renamed by the commands of the same query. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…initions A stored call `ns.pv(...)` of the view `db`.`ns.pv` was persisted as written and resolved again on every read, against the current database of the reading query, so a database `ns` created later took it over. The binding visitor (`visitTableFunction`, also used by the previous commit) now rewrites a qualified name that denotes an existing parameterized view to the name qualified with its database (`db.ns.pv`), with the new helper `tryBindQualifiedParameterizedViewName`. `TableFunctionNode::isSentQualified` now agrees with the hierarchical lookup: a parameterized view is sent qualified with its database also when the database or the name has dots, so a shard resolves it the same way. `04678_parameterized_view_database_on_shard` pinned that a view of a dotted database is not qualified for the shard and fails there; it now resolves. Co-Authored-By: Claude Opus 5.5 <[email protected]>
… columns For `SELECT a.b.c FROM r.`a.b` CROSS JOIN r.a`, `a` used to qualify the tuple field `b.c` of the table `a`. The hierarchical table name `a.b` of the other source no longer takes precedence over it: `isQualifiedByOtherTableExpression` treats a single-part table name of another source equal to the first part the same way as its alias. Co-Authored-By: Claude Opus 5.5 <[email protected]>
… the earlier elements `RENAME TABLE a.x TO a.`ns.y`, a.z TO a.ns.t` failed with `UNKNOWN_DATABASE`: the placement of the second destination checked the namespace `ns.` against the catalog before the query. `resolveHierarchicalNameForCreation` takes an optional check of the namespace, and `RENAME` passes one that applies the moves of the preceding elements, the same simulation it already uses for the sources. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 @groeneai, thanks for the analysis of the Please investigate this failure on the previous head ee3c3c1 and fix it in a separate PR, or link the fix here if one is already in progress: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118193&sha=ee3c3c1326ef3ed3bf3c955947df3de740b63820&name_0=PR&name_1=La%20Casa%20Del%20Dolor%20%28amd_msan%29. |
| if (scope.select) | ||
| collectExpressionScopeNames(scope); | ||
| if ((scope.unknown && unknown_sources_may_be_expression) || scope.names.contains(first_part)) | ||
| return true; |
There was a problem hiding this comment.
[P1] Resolve subquery expressions before binding object-name arguments
Every subquery is marked unknown without collecting its output columns. IN treats that as an expression, while isNameArgumentExpression explicitly ignores it for joinGet/dictGet. This produces both missed bindings and incorrect rewrites.
For a concrete incorrect rewrite, let r.j_one return 'one' and r.p.q return 'other', both Join tables with key 1. Inside USE r, compare the direct query with a view storing it:
SELECT joinGet(p.q, 'v', toUInt64(1)) AS v
FROM (SELECT CAST(tuple('j_one'), 'Tuple(q String)') AS p);The analyzer resolves the direct query's subquery column p.q to 'j_one'. This visitor cannot see that column, so view creation instead binds p.q to table r.p.q, changing the result to 'other'.
The opposite failure occurs for SELECT 1 IN ns.s FROM (SELECT 1 AS x): an actual Set table reference stays relative in the stored view, and creating a real database ns later retargets it. Schema inference analyzes a clone and cannot repair the stored AST.
Please make binding follow semantic expression-versus-table resolution across these carriers, rather than adding another lexical-scope exception. Add direct-versus-stored tests for subquery outputs and for a genuine table operand. These are source-level traces.
There was a problem hiding this comment.
🕵 Addressed in db0364f for subquery sources. A subquery no longer makes every name unknown. Its columns come from its select list: the aliases, and the identifiers by both their full and last part. Only a subquery whose columns cannot be seen there (an asterisk, a matcher, a set operation that is not a plain UNION branch) still makes any name a possible expression. Both of your examples now behave like the direct query:
SELECT 1 IN ns.s FROM (SELECT 1 AS x)in a view is stored as1 IN r.`ns.s`and keeps reading it after a databasenswith a tablesis created.joinGet(p.q, ...) FROM (SELECT CAST(...) AS p)is no longer bound to the tabler.p.q. Note that the direct query does not return'j_one'but fails withILLEGAL_TYPE_OF_ARGUMENT(the first argument ofjoinGetmust be a constant string), and creating the view now fails the same way, where it used to read'other'.
Both are covered by 05617. The binding is still lexical: it runs on the AST before the query is analyzed, because the bound AST is what gets stored and shipped. Moving the binding onto the analyzer query tree would be a larger redesign, so I am leaving this thread open for a reviewer to decide whether that is needed.
| return as_written; | ||
|
|
||
| bool has_other_candidates = as_written.database_name.contains('.') || as_written.table_name.contains('.'); | ||
| if (!has_other_candidates || database->isTableExist(as_written.table_name, context_)) |
There was a problem hiding this comment.
[P2] Do not stop at an empty database for a two-part relative name
A two-part name has relative candidates even when neither individual field contains a dot. With an existing database ns, no table ns.t, and an existing table r.ns.t, this returns the missing (ns, t) immediately:
USE r;
SELECT * FROM ns.t;The query therefore raises UNKNOWN_TABLE, while quoting the whole table name reads r.ns.t. Without database ns, the unquoted form also succeeds.
This violates the documented first-existing-table order: getHierarchicalNameCandidates includes (r, ns.t), but the fast path never reaches it. Only skip the existence check when the original name genuinely has no alternative candidates, and cover a real but empty prefix database.
There was a problem hiding this comment.
🕵 Not changed, on purpose. I tried it: also checking the existence of the table when the name is qualified and a current database is set breaks the access invariant that 05441 covers ("a resolved name is not reinterpreted as relative to the current database"). The interpreters resolve a name once, check the access on the result, and look it up again with the resolved StorageID. A missing (db, t) placement then became db.db.t on the second lookup: a user granted OPTIMIZE only on db.t could run OPTIMIZE on db.db.t (in my run the part count changed from 2 to 1).
So when the database of the name as written exists, the name is taken as written: ns.t is the table t of the database ns, also for CREATE TABLE ns.t and in the UNKNOWN_TABLE error. The relative split is only tried when no database ns exists. To support your case, the first resolution would have to be told apart from the lookup of an already resolved name, for example with a flag on StorageID. That changes the meaning of every resolveStorageID call site, so I am leaving it for a human decision. Until then, ns."t" cannot help here, but quoting the whole name ("ns.t") reads r.ns.t.
|
Acknowledged. I'm investigating the |
|
The fix is #129845. |
|
Dear @novikd, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself. |
# Conflicts: # ci/jobs/scripts/workflow_hooks/feature_docs.py # src/Interpreters/InterpreterAlterQuery.cpp # src/Interpreters/WhatIf/InterpreterHypotheticalObjectQuery.cpp
…icated` database A `Replicated` database does not support renaming several tables in one query, as in `05454`. https://s3.amazonaws.com/clickhouse-test-reports/PRs/118193/93dd6d43955ab27e13a9c699636e3aee13b15aff/pr/result_stateless_tests_arm_binary_s3_storage_dbreplicated_parallel_1_2.json Co-Authored-By: Claude Opus 5.5 <[email protected]>
`tryResolveTableIdentifier` retried a table whose UUID disappeared after `resolveStorageID` by the last part of the name as written. A hierarchical name may resolve to another split (`db`.`ns.t` for `db.ns.t`), so a concurrent rename could make the retry open the unrelated table `db`.`t`. Retry the resolved table name instead. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…rarchical table name The visible name of a materialized CTE is `cte_name`; its `table_name` is the generated name of the temporary table. `isQualifiedByOtherTableExpression` now takes it into account, so `a.b.c` with a materialized CTE `a` is not taken over by a table `a.b` of another source. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ctionary actually loaded The dictionary name is looked up for every block, and a hierarchical name may denote another dictionary after a rename. Remember the dictionary the access was checked for, as `dictGet` and `predictXGBoost` do, instead of a single flag. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…f `ALTER` commands `checkNoRowPolicyForSetOperands` found the mutated table only for a whole `DELETE` or `UPDATE` query. For a command of `ALTER` the validation clone had no source scope, so `UPDATE hit = 1 IN a.b` with a subcolumn `a.b` was checked as a table (`UNKNOWN_TABLE` before `ON CLUSTER`). The table is now passed explicitly. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ore a `Replicated` database enqueues it A `Replicated` database allows `CREATE TABLE ... AS SELECT` with a non-replicated engine, and the replicas take a qualified name exactly as shipped. The qualified names of the `SELECT` are now bound before the `Replicated` enqueue too, as before `ON CLUSTER`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
… list A subquery source made every compound name in the right argument of `IN` an expression, and was ignored for the name arguments of `joinGet` / `dictGet`. So `1 IN ns.s FROM (SELECT 1 AS x)` stayed relative in a stored view, and `joinGet(p.q, ...) FROM (SELECT ... AS p)` was bound to a table `p.q` although the analyzer reads the column `p`. The columns of a subquery are now taken from its select list (aliases and identifiers); a subquery whose columns are not known from it (an asterisk, a matcher) still makes any name possibly an expression. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118193&sha=93dd6d43955ab27e13a9c699636e3aee13b15aff&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%29 and provide a fix in a separate PR. If the fix is already in progress, link it here.
The |
|
The fix is in progress in my open #124982 (not reviewed yet). It is not caused by this PR: the same query fails on master. The trigger is a table column that only SELECT indexHint(t1.a = 1), count() OVER ()
FROM cluster('test_cluster_two_shards_internal_replication', view(SELECT NULL AS a)) AS t1I ran this report's fuzzer query verbatim (including the |
|
Will reopen in one month if the feature is not implemented. |
Closes: #71171
Database and table names can contain dots, and such names can now be written without quotes. A qualified name
a.b.chas no fixed split into a database and a table anymore: it is resolved against the catalog, trying the name as written, then the longest database prefix first (a.bwith the tablec, thenawith the tableb.c), then the tablea.b.cof the current database. Quoting does not matter:a."b.c","a.b".canda.b.care the same name. This is how the tables of a data lake catalog, namednamespace.table, are addressed:SELECT * FROM catalog.namespace.table.The current database is hierarchical as well:
USE a.bis allowed when the databasea.bexists, when the databaseahas tables namedb.*(thenSELECT * FROM creadsa.b.c), or when there are databases nameda.b.*(thenSELECT * FROM c.dreads the tabledof the databasea.b.c). Unqualified names inside such a session resolve relatively, including theSELECTandTOtarget of a materialized view.SHOW TABLESlists the tables under the selected name with names relative to it.currentDatabase()returns the name as selected. Thedatabasesetting and the HTTPdatabaseparameter accept the same names.Column qualifiers follow:
SELECT a.b.c.x FROM a.b.candSELECT b.c.x FROM a.b.cwork with the tablea.b.c, and insideUSE a.balsoSELECT c.x FROM c.SHOW COLUMNS,SHOW INDEXES,joinGetanddictGet(in the identifier and the string forms) and qualified asterisks (ns.t.*) accept hierarchical names the same way.The unquoted parts of a name never create a new namespace:
CREATE TABLE a.b.ccreates the tablea.b.conly when the databaseaalready has tables namedb.*, otherwise it fails withUNKNOWN_DATABASEas before. This protects against typos in database names (CREATE TABLE defualt.tdoes not silently createdefault.defualt.t). The first table of a namespace is created by quoting its name:CREATE TABLE a."b.c".RENAME TABLEtargets follow the same rule. A dotted database name is accepted unquoted by every statement that takes a database name:CREATE DATABASE a.b,DROP DATABASE a.b,USE a.b,RENAME DATABASE a.b TO c.d,EXISTS DATABASE a.b,SHOW CREATE DATABASE a.b,SHOW TABLES FROM a.b,ALTER DATABASE a.b,CHECK DATABASE a.bandSYSTEM SYNC/RESTORE DATABASE REPLICA a.b.Implementation: the resolution is centralized in
DatabaseCatalog(resolveHierarchicalName,resolveHierarchicalNameForCreation,resolveHierarchicalDatabase) and used byContext::resolveStorageID,AddDefaultDatabaseVisitorand theCREATE/DROP/RENAME/EXISTS/SHOW TABLESinterpreters.ASTTableIdentifierkeeps any number of parts; all the parsers that hand-rolled[db.]tablenow shareparseDatabaseAndTableAsAST. Names without dots take the same code paths as before, with no extra catalog lookups. The catalog lookup itself (DatabaseCatalog::getTable) stays exact: a name is resolved before the access is checked, and the lookup gets exactly the resolved table.The access of
CREATE,RENAME,DROP,ALTER,DELETE,UPDATE,OPTIMIZE,SYSTEMand the row-policy statements is checked for the tables the names resolve to: the interpreters resolve the names first, rewriting both parts of the name in the query (InterpreterCreateQuery::resolveHierarchicalNames,InterpreterRenameQuery::resolveHierarchicalNames, including theTOtargets of a view), andgetRequiredAccesssees the resolved names, also on theON CLUSTERpath, so a grant on the nonexistent databasea.bdoes not authorize anything in the databasea. The resolution probes which candidate databases and namespaces exist before the access check, so the error a user without grants gets tellsa.b.cfroma.b.c; this is the same information thatUNKNOWN_DATABASEfromContext::resolveStorageIDreveals for plain names, and it is deliberate: the name is a lookup key, and the check is done on what it resolves to. A query executedON CLUSTERresolves the name on the initiator when it can; when no database of the name exists there, the name is shipped as written. The hosts replaying the query use a qualified name exactly as shipped (DatabaseCatalog::isBoundHierarchicalName) and never pick another split of it, so they act on the object the access was checked for on the initiator. A name with an empty part (.inner_id.x,t.,a..b) is not hierarchical and is never split.The access statements take hierarchical names too:
GRANT SELECT ON catalog.namespace.table,CREATE ROW POLICY p ON catalog.namespace.table, and the correspondingREVOKE,CHECK GRANT,DROP,MOVEandSHOWstatements. The exact name of an access statement is resolved against the catalog the same way as in a query (resolveHierarchicalNamesForAccess), so that a privilege or a policy names the object the same name reads in aSELECT- a longest-prefix split alone would store the grant on the phantom databasecatalog.namespaceand silently grant nothing. Whole-database elements (GRANT SELECT ON a.b.*) and the wildcards are prefixes rather than object names, and are taken as written.Not included, to keep the change reviewable: a relative
USE binsidea(the client mirrorsUSEinto the database it reconnects with, so it would need protocol-level support), and translatingGRANT/REVOKEon a name prefix into wildcard grants. Both can be done on top of theDatabaseCataloghelpers.The tests 01936, 02041 and 02963 asserted that three-part identifiers are rejected with
INVALID_IDENTIFIER; three-part names are valid now and those queries fail withUNKNOWN_DATABASE/UNKNOWN_IDENTIFIER/BAD_ARGUMENTS(a dictionary that is not found) instead, so their expectations were updated. The new tests are05077_hierarchical_names,05079_hierarchical_names_access(the access checks ofCREATE,RENAMEandDROPwith grants on the phantom database only, and the exact hierarchical names ofGRANT,REVOKE,CHECK GRANTand the row policies),05080_hierarchical_names_metadata_and_functions,05182_hierarchical_names_on_cluster,05183_hierarchical_database_names_adminand05227_hierarchical_names_access_ddl(OPTIMIZE,SYSTEM,ALTER,DELETEand the row policies with grants on the phantom database only, locally andON CLUSTER).05333_hierarchical_names_bind_function_argumentschecks that the qualified names ofjoinGetanddictGetare bound to the objects they denote (in a stored view and in the query sent to the shards), and thatSHOW TABLESof a name prefix lists the tables of a remote database under it. A bound name in the string form keeps its split into the database and the table by quoting the parts with dots ('db.ns.j'), so that it is not retargeted when a databasedb.nsappears later.mergeaccepts a namespace of tables as its database (merge('db.ns', ...), ormerge('regexp')insideUSE db.ns).05441_hierarchical_names_review_followupscovers the unqualifiedjoinGet/dictGetnames inside a namespace, mutations,DROP ... ON CLUSTERandEXCHANGE TABLESaccess binding, theGRANTSof authentication methods,USEaccess checks, andmergeover a namespace.05447_hierarchical_names_alias_and_quoted_qualifierschecks that an explicit alias qualifies a column before a longer hierarchical table name and that a quoted qualifier may cross the boundary between the database and the table; the integration testtest_access_control_on_cluster::test_hierarchical_name_bound_on_clusterchecks on two hosts that a host replaying anON CLUSTERquery does not pick another split of a bound name.05446_hierarchical_names_exact_lookupcovers the exact lookup with the name resolved before the access check (hasColumnInTable), computed constant names ofjoinGet/dictGetbound in a view, and a shortATTACHof the last detached table of a namespace. The statement documentation forUSEandSHOW TABLESis updated in the parsers' doc strings (the pages are autogenerated from them).05452_hierarchical_names_review_followups_2covers an exact database/table qualifier being preferred over a quoted one crossing the boundary, the source ofCLONE ASresolved before the new table exists,MODIFY QUERYbound before it is replayedON CLUSTERor by aReplicateddatabase, hierarchical names of parameterized views, the isolation of_temporary_and_external_tables, the old analyzer keeping the split of boundjoinGet/dictGetnames, dependency checks and renamed restore of stored bound names, and context-dependent name expressions (getSetting) not being frozen in a view.05453_hierarchical_names_xgboost_accesschecks thatpredictXGBoostchecks the access on the dictionary it loads.05454_hierarchical_names_review_followups_3covers a later element of a multi-tableRENAMEseeing the tables moved by the earlier ones,RENAME TABLE IF EXISTSof an absent table staying a no-op, the exact-boundary preference in qualified asterisks, and the argument of theDictionaryengine bound to the dictionary it denotes (dependencies and renamed restore).dictGetandpredictXGBoostcheck the access again when a name loads another dictionary (after a rename between blocks), andATTACH PARTITION ... FROMchecksSELECTon the source actually read if it differs from the bound one.05498_hierarchical_names_review_followups_6covers: a name relative to the current database giving way to the alias of another source (both analyzer compatibility modes); a compoundINoperand that may be a subcolumn staying an expression in heavyALTER UPDATEand lightweightUPDATE; a source database not making an unrelated qualified name an expression (CREATE TABLE ... ON CLUSTER AS SELECT ... WHERE x IN db.ns.keys); a column default ofALTER ... ON CLUSTERbound before it is shipped; an unqualifiedGRANTor row policy target getting the current database only once; a compoundjoinGetargument that may be an expression; and the MySQLCOM_INIT_DBaccess check for the database a hierarchical name denotes.05617_hierarchical_names_review_followups_8covers: a materialized CTE qualifying its columns before a longer hierarchical table name; the columns of a subquery source (from its select list) deciding whether a compoundINoperand orjoinGetname is an expression or a table;CREATE TABLE ... AS SELECTin aReplicateddatabase bound before it is enqueued; andALTER ... ON CLUSTER UPDATE ... IN m.nwith a subcolumnm.nvalidated with the mutated table in scope.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Support hierarchical (dotted) database and table names written without quotes:
SELECT * FROM catalog.namespace.tableresolves against the existing databases and tables (catalog.namespace.table,catalog.namespace.table, or the tablecatalog.namespace.tableof the current database),USE catalog.namespaceselects a namespace of tables inside a database or a group of databases with a common prefix, andSHOW TABLESlists the tables under it. Closes #71171.Workflow [PR]
Sync PR [sync-upstream/pr/118193]