Repository navigation
Fix identifier resolution when a table has the same name as its database - #110976
Conversation
When a table has the same name as the database it is in (e.g. `db1.db1`), the analyzer could not resolve fully qualified column names: `SELECT db1.db1.id FROM db1.db1` failed with `UNKNOWN_IDENTIFIER`. The identifier first part was bound to the table name, resolution of the rest of the identifier as a column failed, and an exception was thrown without attempting the other interpretations of the identifier. The same problem affected the qualified matcher, subcolumn access, and fully qualified column names of other tables joined with such a table. Now, when the identifier first part also matches the database name, resolution with a single-part qualifier is allowed to fail, and the remaining interpretations are attempted next: qualification with the database name and the table name, or resolution from another table expression. Closes #82084 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Workflow [PR], commit [aeb923e] Summary: ✅
AI ReviewSummaryThis PR fixes analyzer resolution for Final Verdict✅ No new findings. LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 140/168 (83.33%) · Uncovered code |
The fix is analyzer-only; the queries already succeed with the old infrastructure (`enable_analyzer = 0`). Force `SET enable_analyzer = 1` at the top of the test so it always exercises the resolver change in `IdentifierResolver`, per review feedback from `clickhouse-gh`. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Addressed the AI review / Also merged
|
…st part is a database name anywhere in scope The `can_be_not_found` gate only triggered when the identifier first part matched the current table expression's own `database_name`. When the first part matches the name of one table expression while being the database name of a different table expression in the same scope (a table named like another database), the single-part qualifier lookup still threw `UNKNOWN_IDENTIFIER` before the database-qualified interpretation could be attempted. Check the database names of all table expressions in the scope instead, and extend `04612_table_same_name_as_database` with this shape. Note: the review's alias example (`FROM (SELECT 1 AS id) AS db1 JOIN db1.other`) is not resolvable by the old analyzer either — the alias shadows the database name during table expression resolution — so only the table-name carrier is reachable and covered.
… `analyzer_compatibility_prefer_alias_over_subcolumn` When `analyzer_compatibility_prefer_alias_over_subcolumn = 1`, `tryResolveIdentifierFromJoin` restricts resolution to the JOIN side whose table name or alias matches the first identifier part. `qualifierBindsToJoinSubtree` did not consider that the same token can be the `database_name` of the other side, so for `SELECT db1.tbl.value FROM db1.db1 JOIN db1.tbl USING (id)` the right subtree was pruned and the `db.table.column` interpretation was never attempted. Now a leaf table expression also binds the qualifier when it matches its `database_name`, but only for identifiers with at least three parts, since a database-qualified column reference needs `db.table.column`. `04612_table_same_name_as_database` is extended with both join shapes under the setting.
|
@groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110976&sha=77008ff44e53b9a94ebe60e1a8860e9adebf528f&name_0=PR&name_1=Integration%20tests%20%28amd_tsan%2C%201%2F6%29 ( |
|
Confirmed unrelated to this PR. The banner is a genuine TSAN report in Keeper (
A fix is already in progress by @ al13n321: #107083 "Suppress TSAN error in NonblockingBoundedQueue" (follow-up to the closed #106801). It marks |
…related identifiers Resolution from a parent scope (a correlated identifier) is attempted only after the current scope returns no result, so `identifier_first_part_is_database_name_in_scope` must also account for tables of parent scopes: an inner table named like a database that exists only in the parent scope (e.g. `SELECT (SELECT count() FROM db2.db1 WHERE ...) FROM db1.tbl`) threw `UNKNOWN_IDENTIFIER` from `tryResolveIdentifierFromStorage` before the outer `db1.tbl.column` interpretation could be tried. Walk the parent scopes in the `can_be_not_found` gate and add a correlated regression test. Co-Authored-By: Claude Fable 5 <[email protected]>
…first identifier part is a database name in scope
A materialized CTE can have the same name as a database. When resolving a
fully qualified `db.table.column`, if the first identifier part matched a
materialized CTE named like the database, the `isMaterializedCTE` branch
retried the one-part qualifier with `can_be_not_found = false` and threw before
the `db.table.column` interpretation could reach the real table in that
database.
Make that branch honor `identifier_first_part_is_database_name_in_scope` the
same way the table-name / alias branch above it does: allow the lookup to fail
and fall through so the database-qualified interpretation is attempted next.
Repro (previously threw `UNKNOWN_IDENTIFIER`):
CREATE DATABASE db1;
CREATE TABLE db1.tbl (id Int32, value Int32) ENGINE = Memory;
WITH db1 AS MATERIALIZED (SELECT 42 AS id)
SELECT db1.tbl.value FROM db1 JOIN db1.tbl USING (id)
SETTINGS enable_analyzer = 1, enable_materialized_cte = 1;
Extended `04612_table_same_name_as_database` with the materialized-CTE shape.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ed-CTE case to a `.sh` test
The materialized-CTE-named-like-a-database query used a query parameter
(`{CLICKHOUSE_DATABASE:Identifier}`) as the CTE name, but the parser does
not accept a query parameter in the CTE-name position of a `WITH` clause
(`ParserWithElement` uses `ParserIdentifier` with `allow_query_parameter = false`),
so the query failed to parse with `SYNTAX_ERROR` at the CTE subquery's opening
bracket. Because that query is run in the middle of the multi-query `.sql` test,
it aborted the whole test - and, since #110976 is a bug-fix PR, it also left the
per-arch Bugfix Validation jobs with nothing to validate.
Move that single scenario into a companion shell test
`04613_materialized_cte_same_name_as_database.sh`, where the database name is
substituted into the query text by the shell so the CTE name is a literal
identifier, and drop the corresponding line from the `.sql` reference.
CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110976&sha=4520626d0f3e701c53f0488bc2cce53c925b5672&name_0=PR&name_1=Fast%20test
…didate The retry after a failed lookup behind a table name (or a materialized CTE name) was keyed only to the first identifier part matching any database name in scope, so it also fired when no database-and-table interpretation existed: a two-part `db.x` against the table `db.db` could fall through and resolve a sibling column literally named `db.x` instead of throwing `UNKNOWN_IDENTIFIER`. Allow the lookup to fail only when some table expression in this scope or in a parent scope is the table `identifier[1]` inside the database `identifier[0]` (for a two-part identifier that interpretation is the table itself, e.g. a matcher qualifier `db.db.*`; for three and more parts it is `db.table.column`). The same gate applies to the materialized-CTE branch. Add `04614_two_part_identifier_table_same_name_as_database` covering the two-part and three-part dotted-column shapes. Addresses the AI review blocker. Co-Authored-By: Claude Fable 5 <[email protected]>
…review A plain two-part identifier such as `db.db` selected from the table `db.db` has no expression-level `db.table.column` interpretation (the database-and-table interpretation is the table expression itself, not a column), so a failed qualifier lookup must throw `UNKNOWN_IDENTIFIER` as before instead of falling through and letting a sibling column literally named `db.db` win. The only context that needs the two-part miss to fall through is the qualifier of a qualified matcher (`db.db.*`), which is resolved as an expression first and then as a table expression: such lookups are now marked with `IdentifierLookup::is_matcher_qualifier`. Also address review comments from novikd: - The database-and-table candidate check is no longer computed for every table expression analysis: the qualifier lookup always runs with `can_be_not_found = true` first, and the scope-chain scan runs lazily, only after a failed lookup. When no candidate exists, the lookup is repeated with `can_be_not_found = false` to throw the proper exception. - `qualifierBindsToJoinSubtree` takes the identifier instead of a `qualifier_can_be_database_name` flag and binds a leaf on its database name only when the table name also matches the second identifier part. - The `identifier_first_part_matches_database_name` flag declared far from its single use is inlined into the condition. Extended `04614_two_part_identifier_table_same_name_as_database` with the two-part `db.db` sibling-column regression and the qualified-matcher shape that must keep working.
…t a competing binding Under `analyzer_compatibility_prefer_alias_over_subcolumn = 1`, `qualifierBindsToJoinSubtree` treated a database-qualified match (`db.table.column` against a side's database and table names) as an equal competitor to an alias / table-name match on the other side. When the lookup behind the table-name qualifier succeeded (a real Tuple subcolumn), both sides resolved and the query threw `AMBIGUOUS_IDENTIFIER` instead of honoring the precedence the setting establishes: `SELECT db1.tbl.value FROM default.db1 JOIN db1.tbl USING (id)` with `default.db1` having a column `tbl Tuple(value Int32)`. The database-qualified binding is now attempted only when the alias / table-name pruning restricted resolution to one side and that side produced no result. Extended `04612_table_same_name_as_database` with the successful-subcolumn shape. Addresses the AI review finding in #110976
…in JOIN-side pruning Under `analyzer_compatibility_prefer_alias_over_subcolumn = 1`, `qualifierBindsToJoinSubtree` matched only aliases and table names, and a materialized CTE is registered in `table_expression_node_to_data` under its internal temporary table name. The visible `cte_name` therefore never bound as a qualifier, so for `WITH db1 AS MATERIALIZED (...) SELECT db1.tbl.value FROM db1 JOIN db1.tbl USING (id)` both JOIN sides were searched, and when the CTE side resolved the identifier the database-qualified side competed with it, ending in `AMBIGUOUS_IDENTIFIER` (observable with `single_join_prefer_left_table = 0`; the default silently preferred the left side). Now the CTE name binds like a table name, resolution is pruned to the CTE side, and the database-qualified interpretation stays a miss-only rescue. Extended `04613_materialized_cte_same_name_as_database.sh` with the shape (a column literally named `tbl.value` rather than a Tuple subcolumn, because selecting a Tuple subcolumn out of a materialized CTE through a JOIN hits a pre-existing planner limitation - `NOT_FOUND_COLUMN_IN_BLOCK`, reproducible on 26.7 with a collision-free CTE name - that is unrelated to identifier resolution). Co-Authored-By: Claude Fable 5 <[email protected]>
… name `tryBindIdentifierToTableExpression` recognized only `table_expression_data.table_name`, the alias and `database.table`. A materialized CTE is registered under an internal temporary table name, so the binder did not see a CTE named like a table: - a matcher-expanded column of another table expression stopped one qualification step too early (`tbl.id` instead of `db.tbl.id`, colliding with the CTE's own qualified name), and - a qualifier matching both a materialized CTE and a table was not reported as ambiguous, so `tbl.*` silently picked the table, unlike the same query with a regular CTE. The CTE name is now accepted there as well, both for table expression lookups and for the generic multi-part binding. Regression tests added to `04613_materialized_cte_same_name_as_database.sh`.
|
CI triage for f1f800d — all three failures are unrelated to this PR (it only touches analyzer identifier resolution):
@groeneai, could you investigate the AST fuzzer double-free (https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110976&sha=f1f800dd52062e379a722146b714f740fdbab393&name_0=PR&name_1=AST%20fuzzer%20%28arm_asan_ubsan%29) and provide a fix in a separate PR? If a fix is already in progress, please link it here. There is no tracking issue for it yet. Also pushed: the round-12 review fix (materialized CTE visible name in |
|
Yes, a fix is in progress, and it is not the PR you found: #111622 (open, mine). Mechanism. if (enable_remove_parts_from_snapshot_optimization || query_info.isStream())
{
...
storage_snapshot->data = std::move(stripped_snapshot_data); // master, ReadFromMergeTree.cpp:4060
}
The reproduction of this exact STID is already on record in #111622's CI rather than asserted. Its 45-day CIDB has three rows for the STID: master On #109932, which you named: it fixes the shared No action needed on the other two failures, both attributions look right to me. I have not filed a tracking issue; the analysis lives on #111622. Happy to open one if you prefer it tracked separately. |
|
CI triage for
Merged The only remaining unresolved thread is @novikd's CTE-priority design question, which is his call. |
…-as-database # Conflicts: # src/Analyzer/Resolve/IdentifierResolver.cpp
…lity path Address review: under `analyzer_compatibility_prefer_alias_over_subcolumn = 1`, `tryResolveIdentifierFromTableExpression` took the alias-prefix strip path only when the first identifier part matched `table_expression_data.table_name` or the table expression alias. A materialized CTE is stored under an internal temporary table name, so its visible CTE name never matched and the compatibility path was never taken for it. As a result `WITH cte AS MATERIALIZED (SELECT 1 AS id, CAST(tuple(2), 'Tuple(id Int32)') AS cte) SELECT cte.id FROM cte` preferred the `id` element of the CTE column `cte` over the qualified column `id`, while the same shape with a regular CTE or a subquery alias preferred the qualified column. In this particular shape the subcolumn interpretation is not even executable and the query failed with `NOT_FOUND_COLUMN_IN_BLOCK`. The visible `getMaterializedCTE()->cte_name` is now accepted there as a third qualifier carrier, matching the other places in this file where a materialized CTE is addressable by its CTE name. Extended `04613_materialized_cte_same_name_as_database.sh` with the alias-vs-subcolumn shape and with the regular-CTE baseline it has to match.
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 127/141 (90.07%) · Uncovered code |
Address review: the `analyzer_compatibility_multiple_joins_qualify_column_names` forced-qualification branch of `qualifyColumnNodesWithProjectionNames` still used `getTemporaryTableName` for a `TableNode` backed by a materialized CTE, so with two or more JOINs the matcher expansion leaked the internal temporary table name (`_materialized_cte_cte_<random>.k`) into projection names, and an outer reference such as `cte.Date` over such a subquery threw `UNKNOWN_IDENTIFIER`. The branch now uses `getMaterializedCTE()->cte_name`, the same as the normal qualification path. Extended `04613_materialized_cte_same_name_as_database.sh` with the outer-reference shape, its regular-CTE baseline, and a `TSVWithNames` header check. Co-Authored-By: Claude Fable 5 <[email protected]>
|
🕵 CI triage for 9413b0d (report): all three failures are unrelated to this PR (analyzer identifier resolution).
None of these have a fix merged into |
|
Both failures you flagged for me already have an open fix PR, and you are right that neither is merged, so there is nothing to pull in by re-merging.
The failing row is the One thing worth flagging: there is a second open PR of yours for the same test and the same root cause, #113938 (08-08, "poll for the log level change"). Neither references the other, so one is likely redundant. My own measurement matches your figures: 24 failing rows across 24 distinct PRs on 08-07, 20 rows across 19 PRs plus one master run on 08-06, and 9 rows so far on 08-08. I am not opening a duplicate.
This row is STID 4488-4e11, and the fix in progress is mine: #109393 (open since 07-04, awaiting review). The stack frame is Over the last 30 days I measure 19 rows across 19 distinct PRs for 4488-4e11, plus 15 more rows for two sibling STIDs of the same message family (4488-4a91, 4488-4590), all on PRs and none on master in that window. The varying port counts (1 and 8, 1 and 4, 3 and 1 here) are just the stream counts at build time, so they do not indicate separate defects. #109393 is currently 5715 commits behind master, so I will rebase it and re-run CI to get it back into a reviewable state. |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction. Compile time of recompiled translation units23 translation units recompiled, 125 s compile time in total, 23 of them have a recent master baseline. Median compile-time ratio to the baselines is ×0.92 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio. |
|
🕵 CI triage for 561948e (report): the only two reds are both |
…-as-database Pulls in the merged fix #112849 for the unrelated AST fuzzer failure #112848 (`Cannot serialize FutureSetFromSubquery with no query plan`) seen in https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110976&sha=561948e08e41b94066e8b88d5cb43cc1bf4c8d6e&name_0=PR
alexey-milovidov
left a comment
There was a problem hiding this comment.
I didn't like the complications, but all the feedback has been addressed.
Closes: #82084
When a table has the same name as the database it is in (e.g.
db1.db1), the analyzer could not resolve fully qualified column names:SELECT db1.db1.id FROM db1.db1failed withUNKNOWN_IDENTIFIER. The first part of the identifier was bound to the table name, resolution of the rest (db1.id) as a column failed, and an exception was thrown without attempting the other interpretations of the identifier. The same problem affected the qualified matcher (SELECT db1.db1.* FROM db1.db1), subcolumn access (SELECT db1.db1.t.x FROM db1.db1), and fully qualified column names of other tables joined with such a table (SELECT db1.tbl.id FROM db1.db1 JOIN db1.tbl USING (id)). All these queries work with the old infrastructure (enable_analyzer = 0).Now, when the identifier first part also matches the database name, resolution with a single-part qualifier is allowed to fail, and the remaining interpretations are attempted next: qualification with the database name and the table name, or resolution from another table expression.
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixes the resolution of fully qualified column names such as
db.table.columnin the analyzer for tables that have the same name as their database. Closes #82084.Version info
26.8.1.1149(included in26.8and later)