Repository navigation
Fix SELECT * REPLACE/APPLY and positional arguments with group_by_use_nulls - #118476
alexey-milovidov wants to merge 82 commits into
Conversation
…se_nulls` With `group_by_use_nulls`, the projection is resolved after all other clauses so that the expressions equal to a `GROUP BY` key become `Nullable`. Matchers were deferred along with it, so `SELECT * REPLACE (expr AS c)` could no longer rewrite `c` in `WHERE`, `GROUP BY`, `HAVING` and `ORDER BY` (they were already resolved), positional arguments pointed at the whole unexpanded matcher, and the result of `APPLY` used as a `GROUP BY` key was not converted to `Nullable`, which made an aggregate function over it fail with `Bad cast from type ColumnNullable to ColumnString`. Now matchers of the projection are expanded right away, exactly as without the setting, and the expanded expressions are resolved again after `GROUP BY`. A `GROUP BY` key resolved inside an aggregate function keeps its type and must not be remembered in `resolved_expressions`: the same node can be shared with an expression outside of aggregate functions (`SELECT * APPLY x -> tuple(sum(x), x)`), where it has to become `Nullable`. Related: #104350 Co-Authored-By: Claude Fable 5.1 <[email protected]>
|
Posting these at the request in #104350 (comment). I have not built this branch, so all of the below is about test coverage, not a claim about the code here.
1. Correlated subqueries:
|
…lls-matchers # Conflicts: # src/Analyzer/Resolve/QueryAnalyzer.cpp
`05104_group_by_use_nulls_projection_matchers` pins the matcher, `REPLACE`, `APPLY` and positional-argument shapes this branch fixes, but not the differential ones: running the same query at `group_by_use_nulls = 0` and at `= 1` and requiring the two to agree, on `EXCEPT` before `REPLACE`, a qualified `t1.*`, a `MATERIALIZED` column hidden from `*`, `WITH FILL` bounds, and a `REPLACE` name colliding with a lambda argument or a subquery-local column. Measured against a `master` binary built from this branch's merge base with only `QueryAnalyzer.cpp` reverted, 21 of the file's 44 output sections differ. On `master` five `* APPLY x -> grouping(x)` shapes raise `GROUPING function argument number is not in GROUP BY keys`, `SELECT minOrNull(*) FROM (SELECT * APPLY toTypeName FROM (SELECT 1 AS c) GROUP BY GROUPING SETS ((), (1)))` aborts the server on a libc++ hardening assertion in `SingleValueData` reached through `AggregateFunctionOrFill::addBatchSinglePlace`, and the rest return wrong results with no error: a `REPLACE` reference in `WHERE`, `HAVING`, `ORDER BY` or a named `WINDOW` is not rewritten, a `REPLACE` reference in a `GROUP BY` key duplicates rows, and an `APPLY`-result grouping key stays non-`Nullable`. All 44 sections match on this branch. The queries and the reference are taken unchanged from #104350, which proposes a different fix for the same issue; only the header comment is rewritten so that it describes the invariants rather than that pull request's implementation. The reference needed no regeneration, so the file also serves as a cross-check between the two fixes. Related: #104350 Related: #118476 Related: #91119 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01DXyzRWEoUWDezR4ioysQdd
|
Workflow [PR], commit [99d4632] Summary: ❌
AI Review
|
|
Alexey, sorry for intervening. feel free to remove my commits if they're not wanted. |
…p_by_use_nulls` A matcher does not have to be the root of a projection item: `untuple((* REPLACE (-c AS c),))` consumes its output as a tuple. Resolving a matcher is what registers its `REPLACE` mappings in the sibling clauses of the query, so with `group_by_use_nulls`, where the projection is resolved after them, such a nested matcher has to be expanded in advance as well - otherwise the mappings never reach GROUP BY, HAVING, WHERE and ORDER BY, and the query returns a different result than the same query without the setting: ``` SELECT untuple((* REPLACE (100 - c AS c),)) FROM (SELECT number AS c FROM numbers(3)) GROUP BY c WITH ROLLUP HAVING c > 98 ORDER BY c NULLS LAST; ``` returned `99`, `100` with `group_by_use_nulls = 0` and nothing with `group_by_use_nulls = 1`, because GROUP BY and HAVING kept referring to the source column `c` instead of `100 - c`. Only the arguments of ordinary functions are visited: matchers of lambdas and of subqueries belong to a different scope, and `count` drops an unqualified matcher instead of expanding it. That condition is extracted from `resolveFunction` into `functionDropsUnqualifiedMatcherArgument` and shared by both places, so the two cannot diverge. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
🕵 Pushed 1e06736: merged @nickitat, thank you - your commits stay, the The blocker was real: The only CI red on the previous commit was |
Build profile diff (arm_release)Commit See the job log for details. |
…use_nulls`
Address the AI review of the previous commit.
`count` and `countState` (with combinators) drop only an *unqualified* matcher argument in
`resolveFunction`, so the pre-pass must skip exactly those arguments instead of the whole function:
a qualified matcher such as `count(t.COLUMNS('^c$') REPLACE (100 - c AS c))` stays a real argument
and has to be expanded early, otherwise its `REPLACE` mappings never reach `GROUP BY`/`HAVING`.
The pre-pass also descends into a window definition written in place now
(`count() OVER (PARTITION BY max(* REPLACE (100 - c AS c)))`), whose `PARTITION BY` and `ORDER BY` are
resolved in the scope of the query, exactly as the projection expression carrying them.
New differential test `05229_group_by_use_nulls_matcher_carriers`.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
🕵 Pushed
New differential test Known divergence left for a follow-up, documented in the thread: a projection item written before a nested matcher picks up the |
…nulls` A named window (`OVER w`, `OVER (w ORDER BY ...)`) is resolved from a copy of its definition in the `WINDOW` clause while the projection is resolved, so without `group_by_use_nulls` the `REPLACE` mappings of a matcher in that definition reach `HAVING`. The pre-pass under `group_by_use_nulls` now expands the matchers of the referenced definition as well. Addresses review: #118476 (comment) Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
|
🕵 Merged
|
…ulls` The early expansion of the projection matchers resolves the expressions produced by the `APPLY` and `REPLACE` transformers before the GROUP BY keys are registered as Nullable, and functions folded into constants on resolution (`toTypeName`, `isNull`) are not re-resolved later: `SELECT * APPLY isNull ... GROUP BY k WITH ROLLUP` returned `0` for the total row, and `05076_window_function_group_by_use_nulls_not_an_aggregate` failed in Fast test with `String` instead of `Nullable(String)`. Keep the unexpanded projection and, right after GROUP BY, expand its matchers for the second time. The other clauses, already rewritten by `REPLACE` in the first expansion, are not rewritten again. The matchers nested inside an aggregate or `grouping` function are expanded with the function on the expression stack, and `grouping` in an `APPLY` expression keeps the matched keys in their original type, as an aggregate function does. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118476&sha=6fc030523f0597573565ee3727a838a1f27a8275&name_0=PR&name_1=Fast%20test #118476 Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Pushed a9e86e9: merged Cause: the early matcher expansion under Fix: keep the unexpanded projection and expand its matchers a second time right after GROUP BY. In this second pass I ran it locally against a server: all 66 |
Master already includes it further down; clang-tidy reported `readability-duplicate-include` in the `arm_tidy` build. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118476&sha=a9e86e9e5916f8c88eec1cdcacc5b26ebbe2c0b0&name_0=PR&name_1=Build%20%28arm_tidy%29 #118476 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…pansion With `group_by_use_nulls`, the first expansion of the projection matchers also expands the matchers of the named windows referenced by the projection, in place in the `WINDOW` clause. Their `APPLY` / `REPLACE` outputs were resolved before the GROUP BY keys became Nullable, so `WINDOW w AS (PARTITION BY * APPLY isNull)` was folded into `PARTITION BY 0`. Snapshot the `WINDOW` clause together with the projection, restore both after GROUP BY (rebuilding the name-to-window mapping), and let the `REPLACE` rewrite of the second expansion apply to the restored `WINDOW` clause as well. #118476 Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
The fix for the second cause ( |
…ee hash A lookup in `nullable_group_by_keys` computes the tree hash of the node, which also covers the sources of its columns, so for a column of a wide subquery every lookup hashed the whole subquery. The shallow hash only rejected the nodes that are not keys; the aggregate arguments that are equal to a key, as in `sumIf(t.k + 1, t.flag = 0) ... GROUP BY t.k + 1`, still paid for the full hash in the new aggregate-context lookup. `IdentifierResolveScope::findNullableGroupByKey` now groups the key shapes by the shallow hash and compares the candidates with `isEqual`, which does not go into a column source that is the same node on both sides. All lookups use it. The performance test gets the actual-key shape. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…nder `group_by_use_nulls`
`expandMatchersInsideProjectionExpression` does not go into lambdas, so a
lambda passed to an ordinary function, as in
`arrayMap(x -> COLUMNS('c') REPLACE (1 AS c), [1])`, is resolved with the
rest of the projection, after `GROUP BY`, and its `REPLACE` cannot turn a
`GROUP BY` key into a positional argument. The dependency walk still
counted it, which disabled the deferral of an unrelated `APPLY`, and
`t.* APPLY (x -> getSubcolumn(x, 'null'))` failed with `ILLEGAL_COLUMN`.
Lambdas inside the transformers of a matcher are still visited, because
they are resolved when the matcher is expanded.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
One more cause, from The main thread waits in Stopping the drop at the next part when the server shuts down, as in-flight merges are cancelled now, would leave the remaining parts to the drop after the restart. It would not bound this run by itself: the shutdown still waits for the round in flight (its Azure requests had 22-30 s left on their receive timeout), and @alexey-milovidov, which do you prefer: (1) I send a PR that stops a background table drop at the next part on shutdown, or (2) leave it as expected with a slow Azurite? |
…former bodies under `group_by_use_nulls`
When the columns a matcher produces are known (an asterisk or a `COLUMNS` regexp,
unqualified or qualified by a table expression of the query, without `ARRAY JOIN`),
simulate `resolveMatcher` for each column: every `APPLY` is executed, and an `EXCEPT`
or a `REPLACE` is ignored after a transformer was used for the column. Only the
expressions of the executed transformers are visited for matchers whose `REPLACE`
may rewrite `GROUP BY`, so a matcher inside a discarded body, as in
`* EXCEPT (c) REPLACE (identity(COLUMNS('c') REPLACE (1 AS c)) AS c)`, no longer
disables deferring the transformers of the other matchers.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…nder `group_by_use_nulls` Matching the duplicated aliases with projection nodes hashed every aliased projection node, and the hash of a column includes its source query, so many matcher-expanded aliased expressions over a wide subquery took quadratic time. Only the nodes whose subtree carries a snapshot of a named window are looked up now, because the snapshots are the only thing copied from them. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 @groeneai, thanks for the analysis. The |
|
Opened #129908 with this analysis and the open question. |
# Conflicts: # src/Analyzer/Resolve/QueryAnalyzer.cpp
…e_cte_retry` after merging master The `ROLLUP` total row evaluates the correlated scalar subquery `(SELECT getSubcolumn(t.c, 'null'))` for a NULL outer value. Since 8e44937 ("Fix correlated scalar and EXISTS subqueries ignoring the rows produced for a NULL outer value") on master, it returns `1` instead of `NULL`, which is correct. The test is about the CTE being found on the retry after `GROUP BY`, which still holds. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Thanks, @groeneai, for opening #129908. Merged master into this PR (one conflict in |
…n collecting `REPLACE` targets under `group_by_use_nulls` The census of the columns an unqualified matcher produces included every table expression of the query, while `resolveUnqualifiedMatcher` skips the side of a SEMI/ANTI JOIN hidden by `semi_join_include_columns_from_both_sides = 0` or `anti_join_include_columns_from_both_sides = 0`. A `REPLACE` target present only on the hidden side was then counted as a possible positional `GROUP BY` key and disabled the deferral of unrelated `APPLY` transformers, which raised `ILLEGAL_COLUMN`. Use `IdentifierResolver::isTableExpressionHiddenBySemiAntiJoin`, which the identifier resolution uses for the same purpose. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…n_hidden_side` Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Status of the red checks at
Also merged |
| if (defer_transformer_expressions) | ||
| continue; |
There was a problem hiding this comment.
[Major] Preserve nested matcher registration when deferring APPLY
This skips the entire APPLY expression, including nested matchers whose REPLACE mappings must reach sibling clauses before they resolve. The deferred REPLACE path visits its nested matchers in a discarded copy, but this carrier has no corresponding registration pass. Its mappings first run in the second expansion, where query_with_replaced_clauses suppresses the sibling rewrites.
SELECT * APPLY (x -> max(COLUMNS('c') REPLACE (100 - c AS c)))
FROM (SELECT number AS c FROM numbers(3)) AS t
GROUP BY GROUPING SETS ((t.c))
HAVING c > 98
ORDER BY ALL
SETTINGS group_by_use_nulls = 1;The current head's Fast test binary returns no rows; changing only the setting to 0 returns 99, 100. Function-form APPLY parameters have the same gap: replacing the projection with * APPLY quantile(toFloat64(COLUMNS('c') REPLACE (0.5 AS c))) and the predicate with HAVING c = 0.5 returns no rows at 1, versus 0, 1, 2 at 0. Both differences also exist in the exact base 4faf44db0e68, so these supported APPLY carriers remain outside the promised matcher fix.
Preserve nested matchers' binding effects for all executed transformer expressions while deferring their type-dependent validation, including APPLY lambda bodies and function parameters. Please cover both carriers with focused differential tests.
There was a problem hiding this comment.
🕵 Fixed in 01d6562. A deferred APPLY now expands the matchers inside its expression in a discarded copy, as a deferred REPLACE already does. For a lambda, that is the body, resolved in a lambda scope with the argument bound to the matched column. For a function, it is the parameters and arguments. Their REPLACE mappings therefore rewrite the other clauses before the second expansion. With group_by_use_nulls = 1, * APPLY (x -> max(COLUMNS('c') REPLACE (100 - c AS c))) ... HAVING c > 98 returns 99, 100, and * APPLY quantile(toFloat64(COLUMNS('c') REPLACE (0.5 AS c))) ... HAVING c = 0.5 returns 0, 1, 2. Both match group_by_use_nulls = 0 and are covered in 05617_group_by_use_nulls_matchers_nonconstant_replace_and_deferred_apply.
There was a problem hiding this comment.
The nested-matcher registration issue still occurs at 01d6562cc9f9 when the lambda body is itself a matcher:
SELECT * APPLY (x -> COLUMNS('c') REPLACE (100 - c AS c))
FROM (SELECT number AS c FROM numbers(3)) AS t
GROUP BY GROUPING SETS ((t.c))
HAVING c > 98
ORDER BY ALL
SETTINGS group_by_use_nulls = 1;The current Fast test binary returns no rows; changing only the setting to 0 returns 99, 100. This mismatch also exists on the exact base, so this is a remaining gap in the claimed fix.
At src/Analyzer/Resolve/QueryAnalyzer.cpp:3310, the lambda body is passed to expandMatchersInsideProjectionExpression, but lines 3883–3885 return immediately for its root MatcherNode. Its replacement mapping therefore still reaches HAVING only in the second expansion, where sibling rewrites are suppressed. Handle a matcher at the lambda-body root as well as matchers inside function arguments, with a focused differential test.
There was a problem hiding this comment.
🕵 Fixed in e5b83ed. When the body of a deferred APPLY lambda is a matcher at its root, it is now resolved in the lambda scope, in the discarded copy, instead of being passed to expandMatchersInsideProjectionExpression. Its REPLACE mappings therefore reach HAVING before the second expansion. * APPLY (x -> COLUMNS('c') REPLACE (100 - c AS c)) ... HAVING c > 98 now returns 99, 100 with group_by_use_nulls = 1, the same as with 0. Covered in 05618_group_by_use_nulls_matchers_simultaneous_replace_and_deferred_chains.
There was a problem hiding this comment.
[Major] The root-body example is fixed, but nested replacement registration is still skipped at src/Analyzer/Resolve/QueryAnalyzer.cpp:3342–3343 when a later transformer uses both its argument and an independent matcher:
SELECT * APPLY (x -> tuple(x))
APPLY (x -> tuple(x, max(COLUMNS('c') REPLACE (100 - c AS c))))
FROM (SELECT number AS c FROM numbers(3)) AS t
GROUP BY GROUPING SETS ((t.c))
HAVING c > 98
ORDER BY ALL
SETTINGS group_by_use_nulls = 1;On the exact e5b83edd3136 Fast test binary this returns no rows; changing only the setting to 0 returns ((0),100) and ((1),99). The new guard skips the entire lambda body after the first deferred transformer, including the independent COLUMNS('c') replacement. That matcher first expands after HAVING has bound c, with sibling rewrites suppressed. Please retain the independent nested matcher's registration while deferring the parts that need the transformed argument, and cover this mixed body in the regression test.
There was a problem hiding this comment.
🕵 Fixed in 7639f21. When a preceding transformer of the chain is deferred, the body of the following APPLY lambda is no longer skipped as a whole. Only the matchers qualified by the argument (x.*) are left out of the discarded copy, since they depend on the unknown result of the preceding transformer. Independent matchers such as max(COLUMNS('c') REPLACE (100 - c AS c)) are now expanded, so their mappings reach HAVING. Your query now returns ((0),100), ((1),99) with group_by_use_nulls = 1, the same as with 0. The same holds for the x.* form tuple(x.*, max(COLUMNS('c') REPLACE (100 - c AS c))). Both are covered in 05828_group_by_use_nulls_matchers_mixed_deferred_apply_body.
There was a problem hiding this comment.
[Major] The nested-registration issue remains at 99d46321d91d when the independent matcher is inside a transformer of x.*. At src/Analyzer/Resolve/QueryAnalyzer.cpp:406–407, replaceMatchersQualifiedByIdentifier discards the entire qualified matcher, including that independent transformer body:
SELECT * APPLY (x -> tuple(x))
APPLY (x -> tuple(x.* APPLY
(y -> max(COLUMNS('c') REPLACE (100 - c AS c)))))
FROM (SELECT number AS c FROM numbers(3)) AS t
GROUP BY GROUPING SETS ((t.c))
HAVING c > 98
ORDER BY ALL
SETTINGS group_by_use_nulls = 1;The current Fast test binary returns no rows; changing only group_by_use_nulls to 0 returns (99), (100). A nested REPLACE on x.* reproduces the same gap. The independent mapping first runs after HAVING has resolved, when sibling rewrites are suppressed. Preserve independent transformer descendants when postponing the argument-dependent selector, with a differential regression.
…eys and register nested matchers of deferred `APPLY` under `group_by_use_nulls`
An identifier key of `GROUP BY` that a `REPLACE` transformer rewrites becomes a positional argument
only if the replacement is an integer literal (possibly through another replaced identifier).
Previously any replaced key disabled the deferral of all transformer expressions, so
`SELECT t.c, t.* APPLY (x -> getSubcolumn(x, 'null')), * REPLACE (t.c AS c) ... GROUP BY c WITH ROLLUP`
threw `ILLEGAL_COLUMN`. Now a literal replacement contributes its own position, as a written
positional argument does, and other replacements do not refer to any projection item.
A deferred `APPLY` transformer now expands the matchers inside its expression (the body of a lambda,
with its argument bound to the matched column, or the parameters and arguments of a function) in a
discarded copy, like a deferred `REPLACE`, so that their `REPLACE` mappings rewrite the other clauses,
as `HAVING c` in `SELECT * APPLY (x -> max(COLUMNS('c') REPLACE (100 - c AS c))) ... HAVING c > 98`.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
… track deferred chains under `group_by_use_nulls`
- A matcher replaces a GROUP BY identifier at most once (see `replaceIdentifiersWithTransformerMappings`),
so the chain of replacements that may turn a key into a positional argument continues only through
the replacements of another matcher. `* REPLACE (d AS c, 1 AS d) ... GROUP BY c` no longer makes `c`
positional, and an unrelated `APPLY` stays deferred.
- A deferred `APPLY` lambda whose body is itself a matcher, as `x -> COLUMNS('c') REPLACE (100 - c AS c)`,
now expands that matcher in advance, so its `REPLACE` mappings rewrite the other clauses.
- After a deferred transformer of a chain, the input of a following `APPLY` lambda is unknown; a body that
refers to the lambda argument (`x -> tuple(x.*)`) is not expanded in advance then, instead of being
expanded against the original column.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…Y` and keep the replacement walk linear
- When a preceding transformer of the chain is deferred, the body of a following `APPLY` lambda
is no longer skipped as a whole if it refers to the argument. Only the matchers qualified by the
argument (as `x.*`) are left out; the other matchers, as `COLUMNS('c') REPLACE (100 - c AS c)`,
are expanded in the discarded copy, so their `REPLACE` mappings reach `HAVING` as without
`group_by_use_nulls`.
- The walk over the `REPLACE` chains that looks for positional arguments of `GROUP BY` follows the
replacements of each name at most twice, instead of once per producing matcher. With 4000
matchers `* REPLACE (c AS c)` it was quadratic in time and memory.
- Pass the context to `QueryExpressionsAliasVisitor`, whose constructor changed on master.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
`modernize-use-nodiscard` is enabled on master now, and the `arm_tidy` build failed on three declarations this PR adds or makes const: `MatcherNode::isMatchingColumn`, `IdentifierResolveScope::findNullableGroupByKey` and `IdentifierResolveScope::hasFunctionAlias`. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118476&sha=7639f21316530c21fbd09ed5ec855f2058e12bb0&name_0=PR&name_1=Build%20%28arm_tidy%2C%201%2F4%29 #118476 Co-Authored-By: Claude Fable 5.2 <[email protected]>
|
🕵 Pushed 99d4632: merged The remaining open review thread (matchers inside an in-place |
| @@ -4464,7 +5189,8 @@ ProjectionNames QueryAnalyzer::resolveExpressionNode( | |||
| } | |||
| } | |||
|
|
|||
| resolved_expressions.emplace(node, result_projection_names); | |||
| if (!is_nullable_group_by_key_in_aggregate_function) | |||
There was a problem hiding this comment.
[Blocker] Preserve pre-aggregation types across a chain of APPLY transformers
The aggregate-context protection still misses a scalar transformer whose output is consumed by a later aggregate. resolveMatcher resolves the first transformer outside the aggregate at QueryAnalyzer.cpp:3393–3407, so toInt64(number) already contains a nullable grouping key when it becomes the argument of sum. Excluding only a grouping key resolved inside an aggregate from resolved_expressions cannot recover that already-resolved intermediate.
SELECT * APPLY toInt64 APPLY sum
FROM numbers(3)
GROUP BY number WITH ROLLUP
SETTINGS group_by_use_nulls = 1;Both the current Fast test binary and exact base 521c4bcb7b94 terminate with SIGSEGV in AggregateFunctionNullUnary::addBatchWithNonNullPlaces. The same query with group_by_use_nulls = 0, and the equivalent explicit SELECT sum(toInt64(number)), succeed. APPLY abs APPLY sum reproduces it too. This is pre-existing, but directly exercises the transformer/context invariant being fixed here; it requires no lambda aliases or SQL UDFs, unlike #125852.
Resolve the composed transformer chain in its final aggregate context and add a focused stateless regression, or link a dedicated tracking issue if this pre-existing case is deliberately deferred.
With
group_by_use_nulls = 1, the analyzer resolves the projection after all other clauses of the query, so that the expressions equal to aGROUP BYkey can be wrapped intoNullable. This deferred the matchers (*,COLUMNS(...)) together with the rest of the projection, and everything a matcher does for its sibling clauses stopped working, because those clauses were already resolved by the time the matcher was expanded:SELECT * REPLACE (expr AS c) ... WHERE / GROUP BY / HAVING / ORDER BY / WINDOW w AS (ORDER BY c)keptcbound to the source column instead ofexpr(theREPLACErewrite of the other clauses only works on unresolved identifiers), so the setting silently changed query results.GROUP BYreferred to the whole unexpanded matcher rather than to the expanded column.APPLYthat was itself aGROUP BYkey (SELECT * APPLY toTypeName FROM t GROUP BY GROUPING SETS ((1), ())) was not converted toNullable, and an aggregate function over it in an outer query raisedBad cast from type DB::ColumnNullable to DB::ColumnString(in a hardened build, an assertion insidestring_view).SELECT * APPLY x -> grouping(x)failed withGROUPING function argument number is not in GROUP BY keys.The fix expands the matchers of the projection before the other clauses are resolved, exactly as without the setting, and lets the deferred projection resolution re-resolve the expanded expressions after
GROUP BY. This removes the ordering difference between the two modes instead of re-implementing theREPLACErewrite in a separate pre-pass as #104350 does.One more thing had to change for this to work: a
GROUP BYkey resolved inside an aggregate function keeps its type, and such a node must not be remembered inresolved_expressions, because the same node can be shared with an expression outside of aggregate functions (SELECT * APPLY x -> tuple(sum(x), x),SELECT * APPLY sum, *), where it has to becomeNullable.Related: #104350
Related: #91119
Related: #108931
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix
SELECT * REPLACE (...),APPLYand positional arguments withgroup_by_use_nulls = 1: the replaced columns were not visible inWHERE,GROUP BY,HAVINGandORDER BY, and an aggregate function over the result ofAPPLYused as aGROUP BYkey raised aBad castexception.Workflow [PR]
Sync PR [sync-upstream/pr/118476]