Repository navigation
Require a join subquery alias only when an identifier is actually ambiguous - #117792
alexey-milovidov wants to merge 48 commits into
Conversation
…iguous With `joined_subquery_requires_alias = 1` (the default) the analyzer rejected every unaliased subquery, table function or union in a multi-table join up front, in `QueryAnalyzer::validateJoinTableExpressionWithoutAlias`, even when the missing alias could not cause any ambiguity. An alias only serves to qualify a name, so the check is moved to the place where the analyzer actually decides between candidates: identifier resolution in `IdentifierResolver::tryResolveIdentifierFromJoin` and `tryResolveIdentifierFromCrossJoin`. When an identifier resolves to different expressions from several table expressions of a join and one of them belongs to a subquery or table function without an alias (and without a CTE name), the query fails with `ALIAS_REQUIRED` instead of `AMBIGUOUS_IDENTIFIER`, or instead of being silently resolved by `single_join_prefer_left_table`. The same rule is applied to matchers (`*`, `COLUMNS(...)`): if the expansion produces several columns with the same projection name and one of them comes from an unaliased subquery or table function, an alias is required, because such a column cannot be qualified. Identifiers that resolve from a single table expression never need an alias, so standard queries such as TPC-DS q14 now run with the default settings, and `joined_subquery_requires_alias = 0` is removed from the TPC-DS benchmark settings. The non-analyzer path keeps the strict behavior. Reimplements #109368 following the review at #109368 (review)
…uire an alias A single table expression may expose equally named columns, for example `SELECT * FROM (SELECT x, x FROM t)`, and they do not need any qualification. The matcher check now compares the column sources of equally named matched columns and requires an alias only when they differ and one of them is an unaliased subquery or table function. Found by test `03101_analyzer_identifiers_4`.
|
Workflow [PR], commit [80abc11] Summary: ✅
AI ReviewSummaryReviewed PR #117792 at Final VerdictStatus: ✅ Approve. |
This comment was marked as low quality.
This comment was marked as low quality.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes6 object files changed (+52.46 KiB total), 0 added.
711 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Slowest function optimization changes (ThinLTO)Median per-function time ratio to the master baseline:
Compile time of recompiled translation units23 translation units recompiled, 233 s compile time in total, 23 of them have a recent master baseline. |
`throwIfAmbiguousIdentifierFromUnaliasedTableExpression` ran only in the final `else` of `tryResolveIdentifierFromJoin` and `tryResolveIdentifierFromCrossJoin`, so the branch that handles two resolved identifiers that compare equal never reached it. That branch calls `choseSideForEqualIdenfifiersFromJoin`, which picks the side by which of the two table expressions carries an alias. Equal lineage is not equal values: an outer join default-fills the side that did not match, and a cross join pairs every row with every row. So the side choice is observable, and for an unaliased subquery or table function it depends on an alias that cannot be written for it - `SELECT number FROM numbers(2) AS x, numbers(2) WHERE x.number = 0` returned `0, 1` while the same query with an alias on the second `numbers(2)` returned `0, 0`. The screen now runs at the top of that branch in both functions. The pre-existing `INNER JOIN` equated-key relaxation is left where it is: inside the lineage-equal branch it is unreachable, because an unaliased subquery or table function cannot be named in an `ON` expression, so the only way to write the equality is a bare identifier whose own resolution hits the same screen first.
`validateMatchedColumnsFromJoinCanBeQualified` walked the whole join tree with `buildTableExpressionsStack` and returned as soon as it saw any `PASTE JOIN`, so a single `PASTE JOIN` switched the matcher-side alias check off for the entire query. In a mixed tree such as `SELECT * FROM (SELECT 1 AS a) PASTE JOIN (SELECT 2 AS b), (SELECT 3 AS a)` the duplicate `a` is produced by the comma join, not by the `PASTE JOIN`, and it still cannot be qualified - but the query skipped `ALIAS_REQUIRED` entirely. The same bypass applied to `COLUMNS(...)`. The exemption is now decided per duplicate pair: `findInnermostJoinCombiningTableExpressions` returns the innermost join that has the two columns' table expressions in different operands, and the pair is skipped only when that join is a `PASTE JOIN`. A `PASTE JOIN` elsewhere in the tree no longer says anything about its siblings, while the duplicates a `PASTE JOIN` creates itself keep being validated by `checkDuplicateTableNamesOrAliasForPasteJoin` as before.
Two sections in `05059_joined_subquery_alias_required_only_on_ambiguity`: - structurally identical table expressions on both legs (comma join and `LEFT JOIN`), where the side the identifier binds to would otherwise flip when an alias is added, plus the control that naming both sides makes the query run; - a `PASTE JOIN` wrapped by a comma join, for `*`, `COLUMNS(...)` and a bare identifier, plus the control that a duplicate the `PASTE JOIN` combines itself is still exempt and keeps its `AMBIGUOUS_COLUMN_NAME`.
…ransformers `validateMatchedColumnsFromJoinCanBeQualified` inferred the table expression of a matched column from the node the matcher finally produces, walking only the first function argument. A column transformer replaces that node with an arbitrary expression over the matched column, so the walk stopped at whatever sits in the first argument slot and returned `nullptr` for every column of the expansion: `SELECT * APPLY (x -> 1 + x) FROM (SELECT 1 AS a), (SELECT 2 AS a)` produced two columns both named `plus(1, a)` and silently succeeded, instead of requiring the alias like the same query without the transformer does. `resolveMatcher` now remembers the matched columns before the transformers replace them, in the same order as the projection names, and validates against those: the projection name of a transformed column is derived from the matched column, so the table expression that has to be qualified is the source of the matched column. `getMatchedColumnSource` also searches all function arguments now, so a subcolumn or `Nested` accessor that does not carry the column in its first argument is resolved as well. Reported in #117792 (comment)
…ble expression `tryResolveIdentifierFromArrayJoin` returns an array-joined column whose source is the `ArrayJoinNode`, so `getUnaliasedSubqueryOrTableFunctionSource` stopped there and the ambiguity screen did not see the unaliased subquery or table function wrapped into the `ARRAY JOIN`. `ARRAY JOIN` keeps the columns of the table expression it wraps, and an array-joined column is qualifiable only if that table expression is, so the source is now unwrapped through `ARRAY JOIN` before the alias and CTE checks. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…r_column_name_to_alias` The analyzer is mandatory since v26.9, so `enable_analyzer = 0` can no longer be set in the test and the "without the analyzer" paragraph is gone from the `joined_subquery_requires_alias` description. Master now lets an alias of the same name take over an identifier that is ambiguous between joined tables under `prefer_column_name_to_alias` (a tolerant lookup that reports the ambiguity instead of throwing). The merge honors this in the alias-required check as well: with the tolerant lookup the ambiguity from an unaliased subquery or table function is reported to the caller, and `ALIAS_REQUIRED` is thrown only when no alias took over. Co-Authored-By: Claude Fable 5.1 <[email protected]>
…S_IDENTIFIER` When an identifier is ambiguous between two aliased (or named) table expressions, no alias for a later unaliased subquery would make the query valid, so the plain ambiguity is the right error and the alias-required check does not need to scan past it. Cover the comma join and the nested `JOIN` shape. Co-Authored-By: Claude Fable 5.1 <[email protected]>
…as-lazy-check Conflicts in `QueryAnalyzer.cpp`/`QueryAnalyzer.h`: master extended the eager `validateJoinTableExpressionWithoutAlias` with exemptions for an inlined view and a parameterized view, while this branch removed that function in favour of the check at identifier resolution. Kept the removal and ported both exemptions to `getUnaliasedSubqueryOrTableFunctionTableExpression`: a parameterized view (`TableFunctionNode::isParameterizedView`) and a subquery whose table expression data carries a name (an inlined view) are qualifiable, so they need no alias. `getUnaliasedSubqueryOrTableFunctionSource` now takes the scope for that lookup. Master's untuple expansion in `resolveMatcher` pushes additional projection names per matched column; keep `matched_nodes_before_transformers` index-aligned with them. The eager `ALIAS_REQUIRED` controls of `04653_parameterized_view_own_name` and `05227_parameterized_view_own_name_qualifier` joined a table function without any ambiguous column; they now use an ambiguous column, which is when an alias is required. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
The pipe operators documentation still said the input of a comma join needs an alias whenever `joined_subquery_requires_alias` is enabled. Now it only needs one when an equally named column has to be told apart by qualifying it. Updated the source of the generated page (`ParserPipeOperators.cpp`). Also add `05257_joined_subquery_alias_not_required_for_named_views`: an ambiguous column of an inlined view or of a parameterized view is resolved as for a table instead of failing with `ALIAS_REQUIRED`. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
|
🕵 @zlareb1, catching up on your 2026-09-02 review. Both points are handled on the current head:
This pass also merged |
# Conflicts: # src/Analyzer/Resolve/IdentifierResolver.cpp
The table expression data of an inlined view is stored in the query scope that owns the table expression, but the matcher validation can run in a nested scope such as a lambda scope. The lookup then missed the view name and required an alias, e.g. for `arrayMap(x -> tuple(* REPLACE (0 AS a)), [1])` over `FROM v, t` with `analyzer_inline_views = 1`. Look through the enclosing scopes instead. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Merged |
|
🕵 Merged |
…PLY` introduces A matcher collision is reported as a missing alias only when qualification can resolve it: the matched columns themselves must be equally named, and the final projection name must still depend on the matched column. `SELECT * APPLY (x -> 0)` over columns `a` and `b` yields equally named results no matter how the inputs are qualified, so it must not throw `ALIAS_REQUIRED`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ore captured columns A collision is resolvable by qualification only if the final projection name depends on the matched column. Previously a prefix in a later `APPLY` re-enabled the check after an earlier lambda had already discarded the column name (`APPLY (x -> 0) APPLY (x -> x, 'f')` gives `f0` for every column), and a lambda using only captured columns of the same table expression (`x -> b + c`) was treated as using its argument. Now the flag is combined over the whole transformer chain, and a lambda counts as name-preserving only if its unresolved body uses the lambda argument. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…isplay name A prefixed `APPLY (x -> 0, 'f')` keeps a display name derived from the column (`fa`), but the fresh constant it produces is formatted by its own name, `0`, by a following unprefixed transformer. So `SELECT * APPLY (x -> 0, 'f') APPLY toString FROM (SELECT 1 AS a), (SELECT 2 AS a)` produced two `toString(0)` columns that qualification cannot tell apart, yet the check required an alias. Track separately whether the name the next transformer sees for its argument depends on the matched column. Co-Authored-By: Claude Opus 5.5 <[email protected]>
… in the lambda body `REPLACE (0 AS a)` displays the result as `a`, but the replacement node keeps its own name, which a following `APPLY toString` uses (`toString(0)` for every column), so the argument name of the next transformer no longer counts as derived from the matched column. An explicitly aliased subexpression of an `APPLY` lambda body is named by its alias (`x -> (x AS z)` gives `z`), so it does not carry the argument name either. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…hed column A named lambda (`WITH (y -> 0) AS f ... APPLY f`) or a SQL UDF that ignores its argument is replaced by its resolved body, so neither its result nor a following transformer is named after the matched column. Instead of only inspecting the unresolved lambda syntax, also check that the resolved expression (including the source expressions of folded constants) still contains the matched column. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ly from the call name The projection name of an `APPLY` call (`f(a)` for `WITH (y -> 0) AS f SELECT * APPLY f`) still contains the column name even when a named lambda or a SQL UDF is replaced by a body that ignores its argument, so a terminal call keeps requiring the subquery alias: qualification turns it into `f(a)` and `f(r.a)`. A following transformer, however, reads the cached name of the resolved body (`0`, or `z` for `(y -> (y + 1 AS z))`), so the dependence passed to it is now derived from the name actually read, with explicitly aliased subexpressions not carrying the column name. The SQL UDF cases move to a separate `.sh` test that puts the database name into the UDF names: UDFs are global, so the fixed name `f_05059_constant` failed in the flaky check when copies of the test ran concurrently. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117792&sha=21a925125ccf160ea859ecdc72601c3a7aa0b8a7&name_0=PR&name_1=Stateless%20tests%20%28amd_binary%2C%20flaky%20check%29 #117792 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…d column The name a following transformer reads can keep the names of nested calls of named lambdas or SQL UDFs (`plus(f(a), 1)`) even when their resolved bodies fold to a constant (`plus(0, 1)`). Checking only the resolved expression dropped the dependence on the matched column, so `joined_subquery_requires_alias` did not reject `WITH (y -> 0) AS f, (y -> f(y) + 1) AS g SELECT * APPLY g APPLY toString` over two unaliased subqueries, although aliases resolve the collision. Check the cached name for the column name as well. Co-Authored-By: Claude Opus 5.5 <[email protected]>
… nested call After a prefix (`APPLY (x -> x, 'p_')`), the cached name a following transformer reads is `plus(f(p_a), 1)`, which contains the name the transformer read for its argument (`p_a`) but not the column name `a` at identifier boundaries. So the dependence on the matched column was dropped and `joined_subquery_requires_alias` did not reject `WITH (y -> 0) AS f, (y -> f(y) + 1) AS g SELECT * APPLY (x -> x, 'p_') APPLY g APPLY toString` over two unaliased subqueries, although aliases resolve the collision. Track the name each transformer reads for its argument and look for it in the cached name as well. Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts: # src/Analyzer/Resolve/IdentifierResolver.h
|
🕵 Merged |
|
🕵 Merged The only CI failure on |
|
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. |
|
🕵 Merged |
Related: #109368
Reimplementation of #109368 following the review in #109368 (review): the check is moved from
QueryAnalyzer::validateJoinTableExpressionWithoutAliasinto identifier resolution.joined_subquery_requires_alias = 1(the default) rejected every unaliased subquery, table function or union used in a multi-table join up front, even when the missing alias could not cause any ambiguity. An alias only serves to qualify a name, so the check now lives where the analyzer actually chooses between candidates:IdentifierResolver::tryResolveIdentifierFromJoinandtryResolveIdentifierFromCrossJoin: when an identifier resolves to a column of several table expressions of a join and one of them belongs to a subquery or table function without an alias and without a name of its own (a CTE name, a parameterized view, or a view inlined byanalyzer_inline_views, which are all named like a table), the query fails withALIAS_REQUIRED. Such a column cannot be qualified, so this replaces theAMBIGUOUS_IDENTIFIERerror, the silent resolution bysingle_join_prefer_left_table, and the silent side choicechoseSideForEqualIdenfifiersFromJoinmakes for two structurally identical table expressions. The last one matters as much as the others: that choice is made by which side carries an alias, and equal lineage is not equal values once an outer join default-fills the side that did not match or a cross join pairs every row with every row, sonumbers(2) AS x, numbers(2)andnumbers(2) AS x, numbers(2) AS ywould resolve a barenumberto different sides and return different rows.*,COLUMNS(...)): if the expansion produces several columns with the same projection name and one of them comes from an unaliased subquery or table function, an alias is required for the same reason (SELECT * FROM t, (SELECT 1 AS id)witht.idexisting).PASTE JOINconcatenates its operands positionally and is exempt, but only for the columns it combines itself: the exemption is decided per duplicate pair by the innermost join that has the two table expressions in different operands, so aPASTE JOINelsewhere in the tree does not switch the check off for its siblings.An identifier that resolves from a single table expression never needs the alias, so queries such as TPC-DS q14 (whose
cross_itemsderived table has no correlation name) run with default settings.joined_subquery_requires_alias = 0is removed fromtests/benchmarks/tpc-ds/settings.json; all 99 TPC-DS queries were analyzed against an empty schema with this change and none requires the alias any more (the previously failing q14 passes; five unrelated failures are identical to master with the setting disabled).The eager check is removed entirely, so nearly every query it rejected now runs. The change is error-ward only where the eager check could not see the subquery in the first place: it inspected the direct operands of a join, so a subquery wrapped into
ARRAY JOINescaped it.SELECT x FROM (SELECT [1] AS arr, 2 AS x) ARRAY JOIN arr INNER JOIN (SELECT 0 AS x) AS rhs ON truesucceeds onmasterand now requires the alias, because its barexis exactly the unqualifiable ambiguous column the setting is about.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
With
joined_subquery_requires_alias = 1(the default), the analyzer now requires an alias for a subquery or table function in a JOIN only when the alias is actually needed to qualify a name: an identifier that resolves to columns of several joined table expressions, or*producing several columns with the same name, where one of them belongs to the unaliased subquery or table function. Unambiguous queries, such as some standard TPC-DS queries, no longer need the alias.Documentation entry for user-facing changes
src/Core/Settings.cppand the pipe operators documentation source insrc/Parsers/ParserPipeOperators.cppare updated; the pages are generated from them)Workflow [PR]
Sync PR [sync-upstream/pr/117792]