Skip to content

Support hierarchical (dotted) database and table names - #118193

Closed
alexey-milovidov wants to merge 106 commits into
masterfrom
hierarchical-names
Closed

alexey-milovidov wants to merge 106 commits into
masterfrom
hierarchical-names

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Sep 5, 2026 •

Copy link
Copy Markdown
Member

Closes: #71171

Database and table names can contain dots, and such names can now be written without quotes. A qualified name a.b.c has 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.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: a."b.c", "a.b".c and a.b.c are the same name. This is how the tables of a data lake catalog, named namespace.table, are addressed: SELECT * FROM catalog.namespace.table.

The current database is hierarchical as well: USE a.b is allowed when the database a.b exists, when the database a has tables named b.* (then SELECT * FROM c reads a.b.c), or when there are databases named a.b.* (then SELECT * FROM c.d reads the table d of the database a.b.c). Unqualified names inside such a session resolve relatively, including the SELECT and TO target of a materialized view. SHOW TABLES lists the tables under the selected name with names relative to it. currentDatabase() returns the name as selected. The database setting and the HTTP database parameter accept the same names.

Column qualifiers follow: SELECT a.b.c.x FROM a.b.c and SELECT b.c.x FROM a.b.c work with the table a.b.c, and inside USE a.b also SELECT c.x FROM c. SHOW COLUMNS, SHOW INDEXES, joinGet and dictGet (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.c creates the table a.b.c only when the database a already has tables named b.*, otherwise it fails with UNKNOWN_DATABASE as before. This protects against typos in database names (CREATE TABLE defualt.t does not silently create default.defualt.t). The first table of a namespace is created by quoting its name: CREATE TABLE a."b.c". RENAME TABLE targets 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.b and SYSTEM SYNC/RESTORE DATABASE REPLICA a.b.

Implementation: the resolution is centralized in DatabaseCatalog (resolveHierarchicalName, resolveHierarchicalNameForCreation, resolveHierarchicalDatabase) and used by Context::resolveStorageID, AddDefaultDatabaseVisitor and the CREATE/DROP/RENAME/EXISTS/SHOW TABLES interpreters. ASTTableIdentifier keeps any number of parts; all the parsers that hand-rolled [db.]table now share parseDatabaseAndTableAsAST. 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, SYSTEM and 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 the TO targets of a view), and getRequiredAccess sees the resolved names, also on the ON CLUSTER path, so a grant on the nonexistent database a.b does not authorize anything in the database a. The resolution probes which candidate databases and namespaces exist before the access check, so the error a user without grants gets tells a.b.c from a.b.c; this is the same information that UNKNOWN_DATABASE from Context::resolveStorageID reveals 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 executed ON CLUSTER resolves 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 corresponding REVOKE, CHECK GRANT, DROP, MOVE and SHOW statements. 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 a SELECT - a longest-prefix split alone would store the grant on the phantom database catalog.namespace and 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 b inside a (the client mirrors USE into the database it reconnects with, so it would need protocol-level support), and translating GRANT/REVOKE on a name prefix into wildcard grants. Both can be done on top of the DatabaseCatalog helpers.

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 with UNKNOWN_DATABASE / UNKNOWN_IDENTIFIER / BAD_ARGUMENTS (a dictionary that is not found) instead, so their expectations were updated. The new tests are 05077_hierarchical_names, 05079_hierarchical_names_access (the access checks of CREATE, RENAME and DROP with grants on the phantom database only, and the exact hierarchical names of GRANT, REVOKE, CHECK GRANT and the row policies), 05080_hierarchical_names_metadata_and_functions, 05182_hierarchical_names_on_cluster, 05183_hierarchical_database_names_admin and 05227_hierarchical_names_access_ddl (OPTIMIZE, SYSTEM, ALTER, DELETE and the row policies with grants on the phantom database only, locally and ON CLUSTER). 05333_hierarchical_names_bind_function_arguments checks that the qualified names of joinGet and dictGet are bound to the objects they denote (in a stored view and in the query sent to the shards), and that SHOW TABLES of 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 database db.ns appears later. merge accepts a namespace of tables as its database (merge('db.ns', ...), or merge('regexp') inside USE db.ns). 05441_hierarchical_names_review_followups covers the unqualified joinGet / dictGet names inside a namespace, mutations, DROP ... ON CLUSTER and EXCHANGE TABLES access binding, the GRANTS of authentication methods, USE access checks, and merge over a namespace. 05447_hierarchical_names_alias_and_quoted_qualifiers checks 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 test test_access_control_on_cluster::test_hierarchical_name_bound_on_cluster checks on two hosts that a host replaying an ON CLUSTER query does not pick another split of a bound name. 05446_hierarchical_names_exact_lookup covers the exact lookup with the name resolved before the access check (hasColumnInTable), computed constant names of joinGet / dictGet bound in a view, and a short ATTACH of the last detached table of a namespace. The statement documentation for USE and SHOW TABLES is updated in the parsers' doc strings (the pages are autogenerated from them).

05452_hierarchical_names_review_followups_2 covers an exact database/table qualifier being preferred over a quoted one crossing the boundary, the source of CLONE AS resolved before the new table exists, MODIFY QUERY bound before it is replayed ON CLUSTER or by a Replicated database, hierarchical names of parameterized views, the isolation of _temporary_and_external_tables, the old analyzer keeping the split of bound joinGet / dictGet names, 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_access checks that predictXGBoost checks the access on the dictionary it loads. 05454_hierarchical_names_review_followups_3 covers a later element of a multi-table RENAME seeing the tables moved by the earlier ones, RENAME TABLE IF EXISTS of an absent table staying a no-op, the exact-boundary preference in qualified asterisks, and the argument of the Dictionary engine bound to the dictionary it denotes (dependencies and renamed restore). dictGet and predictXGBoost check the access again when a name loads another dictionary (after a rename between blocks), and ATTACH PARTITION ... FROM checks SELECT on the source actually read if it differs from the bound one.

05498_hierarchical_names_review_followups_6 covers: a name relative to the current database giving way to the alias of another source (both analyzer compatibility modes); a compound IN operand that may be a subcolumn staying an expression in heavy ALTER UPDATE and lightweight UPDATE; 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 of ALTER ... ON CLUSTER bound before it is shipped; an unqualified GRANT or row policy target getting the current database only once; a compound joinGet argument that may be an expression; and the MySQL COM_INIT_DB access check for the database a hierarchical name denotes.

05617_hierarchical_names_review_followups_8 covers: 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 compound IN operand or joinGet name is an expression or a table; CREATE TABLE ... AS SELECT in a Replicated database bound before it is enqueued; and ALTER ... ON CLUSTER UPDATE ... IN m.n with a subcolumn m.n validated with the mutated table in scope.

Changelog category (leave one):

  • New Feature

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.table resolves against the existing databases and tables (catalog.namespace.table, catalog.namespace.table, or the table catalog.namespace.table of the current database), USE catalog.namespace selects a namespace of tables inside a database or a group of databases with a common prefix, and SHOW TABLES lists the tables under it. Closes #71171.


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

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]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [2b84d2e]

Summary: ❌

job_name test_name status info comment
Style check FAIL
various FAIL cidb
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL
Code Review DROPPED
Build (amd_debug) DROPPED
Build (amd_asan_ubsan) DROPPED
Build (amd_tsan) DROPPED
Build (amd_msan) DROPPED
Build (amd_binary) DROPPED
Build (arm_asan_ubsan) DROPPED
Build (arm_binary) DROPPED

@clickhouse-gh clickhouse-gh Bot added pr-feature Pull request with new product feature comp-database-engines Database engine implementations (e.g., Atomic/Replicated) and database-level behavior. labels Sep 5, 2026
@zlareb1

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]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 93dd6d439 with master c4912eaaf (stripped binary size, per-symbol sizes and ThinLTO time; 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.

Object file sizes

76 object files changed (+1.01 MiB total), 1 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Interpreters/InterpreterCreateQuery.cpp.o 1.18 MiB 1.26 MiB +87.18 KiB (+7.23%)
src/CMakeFiles/dbms.dir/Interpreters/InterpreterAlterQuery.cpp.o 475.73 KiB 559.19 KiB +83.46 KiB (+17.54%)
src/CMakeFiles/dbms.dir/Interpreters/InterpreterUpdateQuery.cpp.o 208.22 KiB 281.86 KiB +73.64 KiB (+35.37%)
src/CMakeFiles/dbms.dir/Storages/IStorageCluster.cpp.o 393.31 KiB 466.93 KiB +73.62 KiB (+18.72%)
src/CMakeFiles/dbms.dir/Storages/SelectQueryDescription.cpp.o 145.21 KiB 217.32 KiB +72.10 KiB (+49.65%)
src/CMakeFiles/dbms.dir/Interpreters/InterpreterShowTablesQuery.cpp.o 119.45 KiB 187.76 KiB +68.31 KiB (+57.18%)
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/FunctionsExternalDictionaries.cpp.o 2.63 MiB 2.70 MiB +68.02 KiB (+2.53%)
src/CMakeFiles/dbms.dir/Interpreters/DatabaseCatalog.cpp.o 891.63 KiB 956.43 KiB +64.80 KiB (+7.27%)
src/CMakeFiles/dbms.dir/Interpreters/MutationsInterpreter.cpp.o 996.02 KiB 1.03 MiB +60.82 KiB (+6.11%)
src/CMakeFiles/dbms.dir/Databases/DatabaseOnDisk.cpp.o 592.66 KiB 651.82 KiB +59.17 KiB (+9.98%)
src/CMakeFiles/dbms.dir/Storages/StorageMaterializedView.cpp.o 779.91 KiB 836.67 KiB +56.76 KiB (+7.28%)
src/CMakeFiles/dbms.dir/Interpreters/InterpreterRenameQuery.cpp.o 125.06 KiB 163.95 KiB +38.89 KiB (+31.09%)
src/Parsers/CMakeFiles/clickhouse_parsers.dir/ParserShowIndexesQuery.cpp.o 26.78 KiB 61.72 KiB +34.94 KiB (+130.49%)
src/Parsers/CMakeFiles/clickhouse_parsers.dir/ParserShowColumnsQuery.cpp.o 29.94 KiB 64.34 KiB +34.39 KiB (+114.87%)
src/Parsers/CMakeFiles/clickhouse_parsers.dir/parseDatabaseAndTableName.cpp.o 34.12 KiB 55.36 KiB +21.23 KiB (+62.21%)
src/CMakeFiles/dbms.dir/Interpreters/InterpreterUndropQuery.cpp.o 70.61 KiB 91.25 KiB +20.64 KiB (+29.23%)
src/CMakeFiles/dbms.dir/Server/MySQLHandler.cpp.o 472.49 KiB 490.02 KiB +17.53 KiB (+3.71%)
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/FunctionPredictXGBoost.cpp.o 340.92 KiB 358.38 KiB +17.45 KiB (+5.12%)

719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

643 translation units recompiled, 3993 s compile time in total, 642 of them have a recent master baseline.

Job report

alexey-milovidov and others added 3 commits September 5, 2026 16:26
`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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Thank you, both are fixed in 17bbab5 and covered by 05079_hierarchical_names_access.

CREATE and RENAME now follow the DROP shape: the names are resolved first (InterpreterCreateQuery::resolveHierarchicalNames, InterpreterRenameQuery::resolveHierarchicalNames, rewriting the query, including the TO targets of a view), and getRequiredAccess sees the resolved names. Your two scripts are the test: CREATE TABLE a.b.c with CREATE TABLE ON \a.b`. only is denied with the grant that is actually needed named (CREATE TABLE ON a.`b.c`), and RENAME TABLE a.b.c TO mine.stolenwithSELECT, DROP TABLE ON `a.b`.` is denied too, in both directions (the destination is checked as the table it is placed as).

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 a.b.c from a.b.c by the error. This is the same information that UNKNOWN_DATABASE from Context::resolveStorageID reveals for plain names today (it is thrown before any access check for SELECT too), so I kept it deliberate: the name is a lookup key, and the check is done on what it resolves to. I have written this down in the description.

… 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
Comment thread src/Parsers/ParserDropQuery.cpp Resolved
@novikd novikd self-assigned this Sep 8, 2026
alexey-milovidov and others added 3 commits September 11, 2026 04:31
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]>
alexey-milovidov and others added 3 commits September 18, 2026 10:58
# 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]>
@alexey-milovidov alexey-milovidov mentioned this pull request Sep 20, 2026
47 of 72 tasks
Comment thread src/Parsers/ParserUndropQuery.cpp Resolved
alexey-milovidov and others added 2 commits October 2, 2026 15:28
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]>
@groeneai

groeneai commented Nov 4, 2026

Copy link
Copy Markdown
Collaborator

This run (2026-11-03 07:16 UTC) predates #128774 (merged 09:28 UTC). Its effective_config0.xml has no shutdown_wait_backups_and_restores, so the server waited for backups without a time limit. The synchronous BACKUP DATABASE d2 ON CLUSTER 'default' (fuzzerout.sql line 505) had failed under the session's backup_restore_keeper_fault_injection_probability = 1, and its thread was still in BackupStarter::onException -> BackupCoordinationStageSync::setError, sleeping in the Keeper retry loop. The main thread was in Context::waitAllBackupsAndRestores -> BackupsWorker::waitAll.

#128774 pins shutdown_wait_backups_and_restores to 0 and caps shutdown_wait_unfinished, so shutdown cancels the operation inside the 30 s window. The current head ee3c3c1 contains it, so I don't think a new PR is needed for this one.

On the 14-day count: 7 of the 10 master failures are before #128774. The 3 after it have other causes: the ProcessList::killAllQueries deadlock with distributed plans (#128832, open), trace_log symbolization during flush on TSAN (#129036, merged), and an async insert into remote() with max_distributed_connections = 0 that hangs in DistributedSink::waitForJobs. I'm fixing that last one, plus a DDLWorker::shutdown wait on OPTIMIZE ... ON CLUSTER seen on one PR, and will link both PRs on #118476.

alexey-milovidov pushed a commit to chiranmoyf/ClickHouse that referenced this pull request Nov 4, 2026
… 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]>
alexey-milovidov and others added 7 commits November 6, 2026 17:20
# 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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, thanks for the analysis of the amd_tsan shutdown: understood, it is covered by #128774, and the branch now includes current master.

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. La Casa Del Dolor (amd_msan), Server shutdown: the main thread waits in DDLWorker::shutdown while the DDLWorkerExec thread runs a TRUNCATE from the DDL queue (InterpreterDropQuery::executeToTableImpl -> StorageMergeTree::truncate -> MergeTreeData::clearEmptyParts -> dropPartNoWaitNoThrow -> clearOldPartsFromFilesystem -> grabOldParts -> getCoveredOutdatedParts), which is slow under MSan (see gdb.log). This PR does not touch that code. It may be the same family as the DDLWorker::shutdown wait on OPTIMIZE ... ON CLUSTER you mentioned above.

if (scope.select)
collectExpressionScopeNames(scope);
if ((scope.unknown && unknown_sources_may_be_expression) || scope.names.contains(first_part))
return true;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🕵 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 as 1 IN r.`ns.s` and keeps reading it after a database ns with a table s is created.
  • joinGet(p.q, ...) FROM (SELECT CAST(...) AS p) is no longer bound to the table r.p.q. Note that the direct query does not return 'j_one' but fails with ILLEGAL_TYPE_OF_ARGUMENT (the first argument of joinGet must 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_))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🕵 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.

@groeneai

groeneai commented Nov 6, 2026

Copy link
Copy Markdown
Collaborator

Acknowledged. I'm investigating the amd_msan Server shutdown on ee3c3c1 (DDLWorker::shutdown waiting for the queued TRUNCATE in getCoveredOutdatedParts). It is a different wait from #129283, which only made the ReplicatedMergeTree replication-queue wait cancellable; this TRUNCATE is on a plain MergeTree. I'll follow up here with a PR (or my findings) shortly.

@groeneai

groeneai commented Nov 6, 2026

Copy link
Copy Markdown
Collaborator

The fix is #129845. clearEmptyParts ran a full outdated-parts cleanup after every dropped empty part, so the TRUNCATE of that table (partitioned by moduloOrZero(Float64, 250), hundreds of partitions) was quadratic in the partition count and was still running when DDLWorker::shutdown waited for it; it now runs one cleanup per batch. The same loop also showed up on master in La Casa Del Dolor (amd_debug). The PR needs the can be tested label to run CI.

@clickhouse-gh

clickhouse-gh Bot commented Nov 9, 2026

Copy link
Copy Markdown
Contributor

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.

alexey-milovidov and others added 9 commits November 10, 2026 10:42
# Conflicts:
#	ci/jobs/scripts/workflow_hooks/feature_docs.py
#	src/Interpreters/InterpreterAlterQuery.cpp
#	src/Interpreters/WhatIf/InterpreterHypotheticalObjectQuery.cpp
`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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @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.

AST fuzzer (amd_debug, targeted): Logical error: Invalid number of columns in chunk pushed to OutputPort. Expected 0, found 1 (STID 2270-3afe), with a window function over cluster(..., view(SELECT NULL AS a GROUP BY ALL WINDOW ...)). The same STID failed in other PRs in the last 30 days (#95355, #126880, #112637, #109052), so it is not caused by this PR, and I found no open issue for it.

The DBReplicated failure of 05564_hierarchical_names_review_followups_7 was caused by this PR (a multi-table RENAME) and is fixed in 24c8989. Master is merged, and the open review threads are addressed in the new commits.

@groeneai

Copy link
Copy Markdown
Collaborator

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 indexHint reads, under a window function, over 2 or more shards. The initiator expects an empty header from the shards, but each shard sends the column, so RemoteSource pushes a 1-column chunk into a 0-column port. Minimal repro on master:

SELECT indexHint(t1.a = 1), count() OVER ()
FROM cluster('test_cluster_two_shards_internal_replication', view(SELECT NULL AS a)) AS t1

I ran this report's fuzzer query verbatim (including the * ... APPLY lambda(tuple(x), isNull(x)) part): the master debug build 41a73dec3078 aborts with the same Expected 0, found 1, and master ae69c2a725d2 with #124982 cherry-picked (it applies cleanly) returns 2 rows, one per shard. The test from #124982 also passes there.

@alexey-milovidov alexey-milovidov added the hold Skip for auto-updating. label Nov 10, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Will reopen in one month if the feature is not implemented.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-database-engines Database engine implementations (e.g., Atomic/Replicated) and database-level behavior. hold Skip for auto-updating. pr-feature Pull request with new product feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Support arbitrary nesting in database and table names.

4 participants