Skip to content

Add compatibility setting to qualify column names as the old analyzer did with multiple joins - #110746

Merged
novikd merged 17 commits into
masterfrom
analyzer-multiple-joins-compat-names
Aug 6, 2026
Merged

novikd merged 17 commits into
masterfrom
analyzer-multiple-joins-compat-names

Conversation

@novikd

@novikd novikd commented Jul 16, 2026 •

Copy link
Copy Markdown
Member

Related: https://github.com/ClickHouse/clickhouse-private/issues/55715
Related: #107449

Motivation

The old analyzer's multiple-joins rewrite (JoinToSubqueryTransformVisitor, active when the FROM clause has two or more JOINs) had a naming side effect: * was expanded into fully qualified identifiers per table, and the rewrite restored the original qualified spelling as an alias on every top-level column. As a result, a derived table exposed columns literally named ll.Date or a.x, and outer queries could reference an alias hidden inside the derived table:

SELECT ll.Date
FROM (SELECT * FROM t AS ll LEFT JOIN t1 ON ll.k = t1.k LEFT JOIN t2 ON ll.k = t2.k);

The analyzer now names such columns minimally (Date), so these queries fail with UNKNOWN_IDENTIFIER. This is one of the highest-impact patterns blocking analyzer migration of BI-generated workloads ("Cluster B, Family 2" in the linked issue). Per the SQL standard the reference is invalid (ll is not in scope outside the derived table), so the fix is an opt-in compatibility mode rather than a default change.

Changes

New setting analyzer_compatibility_multiple_joins_qualify_column_names (default false). When enabled and a query's FROM clause contains two or more JOINs (comma-separated tables count, ARRAY JOIN does not — matching the old rewrite's trigger):

  • Matcher-expanded columns (*, t.*, COLUMNS('<regexp>')) get projection names <qualifier>.<column> for every column, where the qualifier is the table expression's alias, else the bare table name (no database), else the CTE name; columns of an unaliased joined subquery stay unqualified (old-analyzer parity). The identifier-list form COLUMNS(col1, col2) is not a matcher expansion and keeps column names exactly as written, matching the old analyzer.
  • A top-level unaliased column reference in the SELECT list keeps its name exactly as written (SELECT a.x produces a column named a.x even when x is unambiguous), mimicking the old rewrite's name restoration for top-level identifiers.

With the setting disabled (default), behavior is unchanged.

Intended deviations from the old analyzer (all pinned in the test)

  • Function projection names do not leak the old rewrite's internal names: plus(ll.k, 1), not plus(--ll.k, 1).
  • SELECT * over JOIN ... USING keeps merge semantics (one merged column). The merged key keeps its bare name (k), because it belongs to the join rather than to a single table; the old rewrite unmerged USING into ON and produced per-table qualified columns.
  • Shapes the old analyzer rejected with NOT_IMPLEMENTED (ARRAY JOIN mixed with multiple JOINs, multiple USING chains) work, but the array-joined column and the merged USING key keep their bare names, because neither belongs to a single table expression. Everything else in those shapes is qualified as usual.
  • An explicit alias colliding with a forced qualified name produces duplicate result names instead of the old MULTIPLE_EXPRESSIONS_FOR_ALIAS error.

Note: a VIEW carries this behavior only when its definition includes the SETTINGS clause; a session-level setting at CREATE time is not persisted (standard compatibility-setting semantics).

Fix: matcher projection names survived the group_by_use_nulls rewrite

Also fixes a pre-existing analyzer bug found while reviewing the above. When group_by_use_nulls = 1 is combined with ROLLUP, CUBE or GROUPING SETS, resolveMatcher rebuilds every matcher-expanded column as a nullable clone and dropped the projection name assigned to the original node, unlike the neighbouring join_use_nulls path which transfers it. Two consequences, both fixed here:

  • With the new setting enabled the forced qualification was lost, so SELECT ll.Date FROM (SELECT * FROM ... GROUP BY ROLLUP(...)) failed with UNKNOWN_IDENTIFIER — the setting did not work in that aggregation mode.
  • Independently of the setting, the ordinary qualification that disambiguates columns of joined table expressions was lost too, so SELECT * over a single JOIN produced duplicate result column names (two columns called k instead of k and t1.k), and an outer reference to t1.k failed while the old analyzer resolved it.

Changelog category (leave one):

  • Improvement

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

Added the setting analyzer_compatibility_multiple_joins_qualify_column_names (default false). When enabled and the FROM clause of a query contains two or more JOINs, result column names produced by the analyzer mimic the old analyzer's multiple-joins rewrite: columns expanded from * are named <alias-or-table>.<column>, and an unaliased column reference in the SELECT list keeps its name exactly as written. This makes outer queries that reference such qualified names, like SELECT ll.Date FROM (SELECT * FROM t AS ll JOIN t1 ON ... JOIN t2 ON ...), work as they did with the old analyzer. Also fixed the analyzer losing qualified result column names for columns expanded from * when group_by_use_nulls is combined with ROLLUP, CUBE or GROUPING SETS, which produced duplicate result column names and broke outer references to those columns.

🤖 Generated with Claude Code

Version info

  • Merged into: 26.8.1.907 (included in 26.8 and later)
  • Backported to: 26.7.4.5, 26.6.3.23

novikd and others added 4 commits July 16, 2026 19:21
…g (RED test)

Introduces the opt-in setting `analyzer_compatibility_multiple_joins_qualify_column_names`,
its `26.7` settings-changes-history entry, and a stateless test
(04603_analyzer_compatibility_multiple_joins_qualify_column_names) that encodes the
final expected behavior: when the FROM clause has two or more JOINs, the new analyzer
should name result columns the way the old analyzer's multiple-joins rewrite did, so
that outer queries referencing hidden inner aliases (e.g. `SELECT ll.Date FROM (SELECT *
FROM t AS ll LEFT JOIN t1 ... LEFT JOIN t2 ...)`) resolve again.

This is intentionally a RED test: the setting exists but the analyzer hooks that
implement it land in a follow-up change, so every "setting ON" section is expected to
fail for now. Setting-OFF and old-analyzer expectations were verified against a
prebuilt clickhouse binary; setting-ON DESCRIBE expectations mirror the verified
old-analyzer column names except for two documented deviations (function projection
names, and JOIN ... USING merge semantics) which are pinned to new, deliberately
different behavior.

Co-Authored-By: Claude Fable 5 <[email protected]>
Add the analyzer hook for `analyzer_compatibility_multiple_joins_qualify_column_names`.
In `QueryAnalyzer::qualifyColumnNodesWithProjectionNames`, when the setting is
enabled and the current query scope has two or more JOINs
(`scope.joins_count >= 2`), every matcher-expanded column (`*`, `t.*`,
`COLUMNS(...)`) is unconditionally given a single-part `<qualifier>.<column>`
projection name, bypassing the ambiguity bind-check. The qualifier is the table
expression alias, else a temporary table name, else the bare table name (without
database), else a CTE name; if none is available (e.g. an unaliased joined
subquery) the column keeps its unqualified name.

This mimics the old analyzer's multiple-joins rewrite
(`JoinToSubqueryTransformVisitor` with `multiple_joins_try_to_keep_original_names = false`).
The non-forced path is left byte-identical.

Also correct one hand-derived reference value in test 04603: for
`SELECT *` over a `JOIN ... USING (k)`, the merged USING key stays bare `k`
(it is not attributable to a single table expression) rather than `ll.k`.
Verified: with the setting OFF the merged key is already bare `k`; enabling the
setting only qualifies the attributable `Date` column to `ll.Date`.

Co-Authored-By: Claude Fable 5 <[email protected]>
…iple joins

Under analyzer_compatibility_multiple_joins_qualify_column_names, a top-level
SELECT-list expression that is an unaliased public identifier resolved from the
join tree into a plain ColumnNode keeps its projection name exactly as written
(a.x -> a.x), when the nearest query scope's FROM has two or more JOINs. This
mimics the old analyzer's restoreName. Function names, matcher naming, aliases,
and all internal naming stay untouched.

Co-Authored-By: Claude Fable 5 <[email protected]>
Task 4 verification confirmed that the hidden-alias outer reference
survives a shard boundary: `SELECT ll.Date FROM remote(...)` with
`analyzer_compatibility_multiple_joins_qualify_column_names = 1`
resolves and returns one 'D' row per shard, since the qualifier is
attached in `toAST` before the query is sent to remote replicas.
Add this as a pinned case to test 04603.

Co-Authored-By: Claude Fable 5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 16, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ac057ee]

Summary: ✅


AI Review

Summary

This PR adds analyzer_compatibility_multiple_joins_qualify_column_names and fixes the matcher-projection-name loss through the group_by_use_nulls nullable rewrite. Most of the earlier review gaps are now addressed, but there is still one remaining correctness hole: the advertised top-level name restoration is bypassed when group_by_use_nulls is combined with ORDER BY ALL.

Findings

⚠️ Majors

  • src/Analyzer/Resolve/QueryAnalyzer.cpp:3223 src/Analyzer/Resolve/QueryAnalyzer.cpp:6531 The compatibility contract says a top-level identifier such as a.x keeps its written projection name under two or more JOINs, but ORDER BY ALL still resolves the projection nodes before the final projection pass in group_by_use_nulls queries. expandOrderByAll reuses the original projection nodes, resolveSortNodeList caches them with is_top_level_projection = false, and the later projection pass returns the cached minimized name x instead of a.x. A query like SELECT a.x FROM (...) GROUP BY ROLLUP(...) ORDER BY ALL therefore still exposes x, so an outer SELECT a.x FROM (...) fails even with analyzer_compatibility_multiple_joins_qualify_column_names = 1. Suggested fix: separate the cache for top-level vs non-top-level resolution, or stop ORDER BY ALL from resolving the original projection nodes before the final projection pass, and add a focused regression for this clause combination.
Tests
  • ⚠️ The new coverage exercises ROLLUP/CUBE/GROUPING SETS and the COLUMNS(...) clone paths, but it still misses the group_by_use_nulls + ORDER BY ALL clause-order case above, which is why this cache bug survives.
Final Verdict

Changes requested. The remaining ORDER BY ALL cache interaction still breaks the main compatibility promise for a supported grouped-query shape.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.80% +0.10%

Changed lines: Changed C/C++ lines covered: 86/90 (95.56%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Jul 16, 2026
The style check bans the phrase "new analyzer" (the analyzer is enabled
by default since 24.3 and is no longer new). Reword the setting
description, the settings-changes-history entry, and test comments.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110746&sha=latest&name_0=PR
PR: #110746

Co-Authored-By: Claude Fable 5 <[email protected]>
Comment thread src/Analyzer/Resolve/QueryAnalyzer.cpp Resolved
…ting and pin parity tests

Addresses review comment #110746 (comment):
the COLUMNS_LIST fast path (identifier-list form COLUMNS(col1, col2)) is correct
as-is and does not need qualification, since the old analyzer never qualified
that form either -- only the regexp form COLUMNS('<regexp>') was qualified, and
this implementation qualifies it too. This commit only clarifies the setting
description in Settings.cpp to say COLUMNS('<regexp>') instead of the
over-generic COLUMNS(...), and adds test coverage pinning both forms' behavior
under analyzer_compatibility_multiple_joins_qualify_column_names. No analyzer
code changes.

Co-Authored-By: Claude Fable 5 <[email protected]>
Comment thread src/Analyzer/Resolve/QueryAnalyzer.cpp Resolved
Comment thread src/Analyzer/Resolve/QueryAnalyzer.cpp Resolved
@novikd
novikd requested a review from yakov-olkhovskiy July 22, 2026 11:44

@yakov-olkhovskiy yakov-olkhovskiy left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM, see couple suggestions regarding tests

novikd and others added 3 commits July 29, 2026 16:03
Remove the leftover note in `04603` claiming the analyzer hooks land in a
later change - the setting and the hooks are both in this pull request, so
no "setting ON" section is expected to fail.

Add the reviewer's suggested cases for a CTE used as a joined table
expression under two `JOIN`s: the qualifier is the CTE name, for both a
plain CTE and a `UNION ALL` CTE, together with the outer references that
the qualified names make resolvable.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Conflict in `src/Core/Settings.cpp`: master added
`analyzer_compatibility_apply_final_to_all_joined_tables` at the same place
in the `analyzer_compatibility_*` group where this branch added
`analyzer_compatibility_multiple_joins_qualify_column_names`. Kept both
declarations.

Master has opened 26.8, so the settings history entry for
`analyzer_compatibility_multiple_joins_qualify_column_names` moved from the
now-released 26.7 section to 26.8, where the setting is actually introduced.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Comment thread src/Analyzer/Resolve/QueryAnalyzer.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Jul 31, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.60% -0.10%

Changed lines: Changed C/C++ lines covered: 65/66 (98.48%) · Uncovered code

Full report · Diff report

`resolveMatcher` rebuilds every matcher-expanded column as a nullable clone
when `group_by_use_nulls` is combined with `ROLLUP`, `CUBE` or
`GROUPING SETS`, but dropped the projection name assigned to the original
node, unlike the neighbouring `join_use_nulls` path which transfers it.

Two consequences, both fixed by carrying the name over to the clone:

- the qualification forced by
  `analyzer_compatibility_multiple_joins_qualify_column_names` was lost, so
  `SELECT ll.Date FROM (SELECT * FROM ... GROUP BY ROLLUP(...))` threw
  `UNKNOWN_IDENTIFIER` and the setting did not work in that aggregation mode;
- independently of that setting, the qualification that disambiguates columns
  of joined table expressions was lost too, so `SELECT *` over a single `JOIN`
  produced duplicate result column names (`k` twice instead of `k` and
  `t1.k`) and an outer reference to `t1.k` failed, while the old analyzer
  resolved it.

Names and data now match `enable_analyzer = 0` for both shapes.

Also pin the multiple-`USING` chain naming in `04603`, as asked in review: the
shape works and the merged `USING` key keeps its bare name.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

/// Old-analyzer parity: under multiple JOINs a top-level unaliased public identifier
/// resolved into a plain column keeps its projection name exactly as written (`a.x` -> `a.x`).
if (is_top_level_projection

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.

is_top_level_projection only affects the first resolution of a node, but resolved_expressions is still keyed just by the node pointer. In group_by_use_nulls queries the projection is intentionally resolved after GROUP BY; expandOrderByAll wires ORDER BY ALL to the same projection nodes, and resolveSortNodeList resolves them first with is_top_level_projection = false. That caches the minimized name (x) for a.x, so the later projection pass hits the cache at the top of resolveExpressionNode and never executes this compatibility branch.

A query like SELECT a.x FROM (...) GROUP BY ROLLUP(...) ORDER BY ALL will therefore still expose x, and an outer SELECT a.x FROM (...) fails even with analyzer_compatibility_multiple_joins_qualify_column_names = 1. Please either separate the cache for top-level vs non-top-level naming or stop ORDER BY ALL from reusing the projection nodes, and add a focused regression.

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.

The structural premise is right, but the conclusion does not follow, and the symptom does not reproduce.

Correct parts: with group_by_use_nulls the projection is not resolved in the usual place — resolveQuery skips it under if (!scope.group_by_use_nulls) and resolves it only after ORDER BY, and expandOrderByAll really does wrap the same projection node pointers in SortNodes rather than cloning them. resolveGroupByNode also clears resolved_expressions for the ROLLUP/CUBE/GROUPING SETS case.

What breaks the chain is the cache key. resolved_expressions.emplace(node, result_projection_names) runs at the end of resolveExpressionNode, by which point node has been replaced in place by the resolved ColumnNode, so the entry is keyed by the resolved node, not by the identifier that was passed in. Resolving the sort list rewrites the pointer stored inside the SortNode, while the projection list still holds the original IdentifierNode. The later projection pass therefore looks up a key that was never inserted, misses the cache, runs the identifier branch with is_top_level_projection = true, and the compatibility branch does execute.

Verified on the current branch head, setting on, two joins:

  • DESCRIBE (SELECT a.x FROM ... GROUP BY ROLLUP(a.x) ORDER BY ALL) → a.x, and the outer SELECT a.x FROM (...) returns X, \N.
  • Plain GROUP BY a.x ORDER BY ALL with group_by_use_nulls = 1 (deferred projection resolution, no cache clear) → a.x; outer reference returns X.
  • Two unaliased qualified columns with CUBE + ORDER BY ALL → a.x, b.k. GROUPING SETS + ORDER BY ALL DESC → a.x, b.k.
  • The other constructs that reuse projection nodes the same way, via replaceNodesWithPositionalArguments — ORDER BY 1 and LIMIT 1 BY 1 — plus explicit ORDER BY a.x: all a.x, outer reference returns X, \N.

So neither a separate cache namespace for top-level naming nor rewiring ORDER BY ALL is needed.

Unrelated aside for anyone testing this shape: SELECT * combined with ORDER BY ALL throws NOT_IMPLEMENTED: Expression ORDER BY * is not supported, matcher expression can only contain single column, identically with the setting off, so the matcher form cannot be used as a probe here.

Happy to pin the ORDER BY ALL + group_by_use_nulls cases in 04695_analyzer_group_by_use_nulls_matcher_projection_names if it is worth locking the interaction down.

Comment thread src/Core/Settings.cpp Resolved
Comment thread src/Analyzer/Resolve/QueryAnalyzer.cpp Resolved
novikd added 2 commits August 5, 2026 15:32
The description of `analyzer_compatibility_multiple_joins_qualify_column_names`
promised `<qualifier>.<column>` for every column expanded from a matcher, but a
column produced by `ARRAY JOIN` and a key merged by `JOIN ... USING` keep their
bare name, because neither belongs to a single table expression. Both are
already pinned in
`04603_analyzer_compatibility_multiple_joins_qualify_column_names` and stated in
the pull request description; fold them into the user-facing setting text.

Also correct the identifier-list `COLUMNS` bullet: each column keeps the name
exactly as its identifier was written, which is what the next commit implements
for qualified items.
The `MatcherNodeType::COLUMNS_LIST` fast path in `resolveUnqualifiedMatcher`
named every item after the resolved column, dropping the qualifier the user
wrote. With two or more `JOIN`s the old analyzer kept it, so
`SELECT a.x FROM (SELECT COLUMNS(a.x) FROM ... JOIN ... JOIN ...)` returned a
row with `enable_analyzer = 0` and threw `UNKNOWN_IDENTIFIER` with
`analyzer_compatibility_multiple_joins_qualify_column_names = 1`.

Record the written identifier in `node_to_projection_name` under the same gate
the other compatibility branches use. The name returned from the branch stays
the bare column name, because `EXCEPT` and `REPLACE` transformers match against
it - on the old analyzer too.

Uses the cloning variant: `tryResolveIdentifier` returns the same shared
`ColumnNode` for every reference to a given column within a query, including
unrelated sibling expressions (e.g. `SELECT COLUMNS(a.x), toString(a.x)`).
Recording the qualified name directly on that shared node leaked it into
`toString`'s own, ambiguity-driven projection name. Cloning the node before
tagging it keeps the override local to the matcher's own output, matching how
the star and regexp matcher forms already build fresh `ColumnNode`s.
novikd added 2 commits August 5, 2026 16:54
Review follow-up, no behaviour change. Trim the comment in
`resolveUnqualifiedMatcher` to the repository's two-line limit and scope the
claim in the test's `COLUMNS` section header to the setting being on.

Adds the two interactions the previous commit left untested: a qualified
list-form `COLUMNS` item under `group_by_use_nulls` with `ROLLUP` - the rewrite
that the preceding commit on this branch had to be taught to carry projection
names through - and an item resolving through a `SELECT`-list alias. Both match
`enable_analyzer = 0`.
…ames' into analyzer-multiple-joins-compat-names
@novikd
novikd added this pull request to the merge queue Aug 6, 2026
Merged via the queue into master with commit 737b211 Aug 6, 2026
353 of 354 checks passed
@novikd
novikd deleted the analyzer-multiple-joins-compat-names branch August 6, 2026 11:51
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Aug 6, 2026
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 6, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

Hi @novikd @yakov-olkhovskiy — a couple of suggestions to make this PR easier for reviewers and the changelog reader.

Description (currently incomplete):

  • Why: The body states "the fix is an opt-in compatibility mode rather than a default change", but the resolveMatcher hunk applies with the setting off. Verified on the PR build: DESCRIBE (SELECT * FROM (SELECT 1 AS k, 'D' AS Date) AS ll LEFT JOIN (SELECT 1 AS k) AS t1 ON ll.k=t1.k LEFT JOIN (SELECT 1 AS k) AS t2 ON ll.k=t2.k GROUP BY ROLLUP(ll.k, ll.Date, t1.k, t2.k)) with group_by_use_nulls=1 and the setting OFF now returns ll.k, Date, t1.k, t2.k; without the new node_to_projection_name.emplace the fallback at QueryAnalyzer.cpp:2573 yields the bare ColumnNode name for each cloned column. Given the v26.4-must-backport label this ships to a stable branch, so it deserves an explicit sentence.

  • Suggested addition:

    Behavior change that is not gated by the setting

    resolveMatcher now carries the projection name computed for a matcher-expanded column across the clone that group_by_use_nulls makes for ROLLUP / CUBE / GROUPING SETS. This applies with analyzer_compatibility_multiple_joins_qualify_column_names = 0 as well: such queries previously lost the qualification and produced colliding result columns (e.g. two columns named k), and now keep ll.k / t1.k. This is what 04695_analyzer_group_by_use_nulls_matcher_projection_names.sql pins. Since the PR is labelled v26.4-must-backport, please confirm this part is intended for the backport too.

Ignore this if the current title/body is intentional.

@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Aug 7, 2026
clickhouse-gh Bot pushed a commit that referenced this pull request Aug 7, 2026
… names as the old analyzer did with multiple joins
clickhouse-gh Bot added a commit that referenced this pull request Aug 7, 2026
Backport #110746 to 26.7: Add compatibility setting to qualify column names as the old analyzer did with multiple joins
novikd added a commit that referenced this pull request Aug 10, 2026
Backport #110746 to 26.6: Add compatibility setting to qualify column names as the old analyzer did with multiple joins
VighneshPath pushed a commit to VighneshPath/ClickHouse that referenced this pull request Sep 16, 2026
…ify column names as the old analyzer did with multiple joins
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-improvement Pull request with some product improvements pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.4-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants