Repository navigation
Support UNIQUE predicate that tests for no duplicate rows in a subquery - #99877
ai-mountain wants to merge 91 commits into
Conversation
|
Workflow [PR], commit [ff0cbf5] Summary: ❌
AI ReviewSummaryAdds the Findings❌ Blockers
Tests
Final Verdict❌ Block — preserve interpolation through repeated projection overrides and conversion to shard SQL, with regression coverage for both. |
|
@alexey-milovidov Please review my PR again. Thanks. |
|
The current rewrite The key property of Proposed approachCreate an internal aggregate function The critical part: reuse the existing Today, Add two virtual methods to virtual bool isEarlyTerminable() const { return false; }
virtual bool shouldTerminateEarly(AggregateDataPtr place) const { return false; }After Analyzer rewrite becomes simply: Benefits
Implementation scope
The early termination interface is generic and reusable by future aggregate functions. |
|
@amosbird Thanks very much. I'll fix based on your suggestions. |
88ad14c to
d80e1de
Compare
574ed12 to
ef343a9
Compare
ef343a9 to
b275828
Compare
b275828 to
b00ff36
Compare
b00ff36 to
9e0dd1f
Compare
|
@alexey-milovidov Can you take another look on my PR please? Thanks. |
|
I would like to find a better name for this aggregate function, so it will be usable in normal scenarios. For example, |
40b1587 to
1e94863
Compare
The projection name of `UNIQUE(subquery)` was the internal function name `__unique`, which leaked into `DESCRIBE` and `TSVWithNames` headers. Worse, all predicates of one query shared that name, so `SELECT UNIQUE(<unique>), UNIQUE(<duplicates>)` failed with "Block structure mismatch ... different values of constants in column". Name each predicate `UNIQUE(__subquery_<hash>)` from the tree hash of its original subquery AST (the `ASTSubquery::getColumnName` scheme): stable across query tree cloning and between `only_analyze` and execution, distinct for different predicates. `04545_unique_predicate_projection_name` now asserts the exact header (with the hash masked) and the two-predicate query. Addresses review: ClickHouse#99877 (comment) Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…a subquery Address review: `getFunctionLayer` chose `UniqueLayer` as soon as the argument started like a subquery, so calls such as `unique((SELECT 1), 2)` or `unique((SELECT 1) + 1)` became syntax errors instead of ordinary function calls with a scalar subquery. The lookahead now finds the bracket closing a parenthesized subquery and accepts the predicate form only when it is followed by the closing bracket of the call or by a set operation (`UNION`, `EXCEPT`, `INTERSECT`). Co-Authored-By: Claude Opus 5.5 <[email protected]>
Address review: in only-analyze mode `UNIQUE` resolves to a `materialize` placeholder, which is rejected by functions requiring a constant argument (`getArgumentsThatAreAlwaysConstant`), e.g. the index of `tupleElement`. So `CREATE VIEW v AS SELECT tupleElement((1, 2), UNIQUE(SELECT ...))` failed although the query executes successfully. Such placeholders are now replaced by the real value of the predicate after the arguments are resolved. Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts: # src/Analyzer/Resolve/QueryAnalyzer.cpp
`UNIQUE(subquery)` is now rewritten into `ifNull((SELECT count() = uniqExact(*) FROM (subquery) WHERE and(1, * APPLY isNotNull)), 1)` and resolved through the regular scalar subquery path, as requested in the review: - Correlated subqueries are supported: the rewritten subquery is left to the planner for decorrelation, like any correlated scalar subquery. A missing correlated group (an empty inner relation) is decorrelated to NULL, and an empty input is vacuously unique, hence `ifNull`. - The projections of the subquery are not renamed anymore: the `NULL` filter uses an `APPLY` matcher instead of referring to the columns by name. - The projection name is built like for a correlated `EXISTS`, from the projection name of the subquery: `UNIQUE(_subquery_N)`. - The `only_analyze` placeholder (the `materialize` wrapper), the `constant_expression_in_resolve_process` flag in `LIMIT`/`OFFSET`/`LIMIT BY`/window frame/ `WITH FILL`/function parameter contexts, and the evaluation of placeholders in always-constant arguments are removed. In `only_analyze` mode `UNIQUE` now behaves exactly like any other scalar subquery; the tests that pinned the placeholder behaviour are removed. Document that rows are compared like `DISTINCT` does (floating-point values by their binary representation), and that correlated subqueries are supported. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Preview approval requiredThis pull request comes from a fork, so Mintlify won't build a preview until someone with write access approves commit |
…lt-ins The rewrite of `UNIQUE(subquery)` creates `count`, `uniqExact`, `equals`, `and`, `isNotNull` and `ifNull` nodes that are resolved in the scope of the query, so a lambda with the same name, e.g. `WITH (x -> 0) AS isNotNull`, replaced them and changed the result of the predicate. Such nodes are now marked with `FunctionNode::markAsBuiltin`, and their names are not looked up as lambdas or user defined functions. The parser-marked `__unique` operator is now recognized before the lambda lookup, so `WITH (x -> 42) AS __unique` cannot replace the predicate either, while an ordinary call `__unique(...)` is an ordinary function. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The token lookahead accepted an unparenthesized `SELECT`/`WITH`/`FROM` as the start of a subquery, so `unique(from + 1)` with a column named `from` became a syntax error instead of an ordinary function call. Now the argument is parsed with `ParserSelectWithUnionQuery` and must be followed by the closing bracket of the call; otherwise `unique` is a regular function name. The parsed subquery is handed over to `UniqueLayer`, so it is parsed only once and nested predicates stay linear. Formatting prints `__unique` as the `UNIQUE` keyword only for the operator produced by the parser, so an ordinary call `__unique((SELECT 1))` is printed as itself and keeps its meaning after a round trip. Co-Authored-By: Claude Opus 5.5 <[email protected]>
For an ordinary call such as `unique((SELECT ...), 2)`, the argument was first parsed speculatively as the subquery of the `UNIQUE` predicate. That parse failed only at the comma, and then the function call parsed the same argument again, so the work doubled at every nesting level. Now a linear token scan checks first whether a bracketed argument can be a whole subquery: after its first bracketed group, only the closing bracket of the call, a set operation, or `|>` can follow. The speculative parse also runs on the caller's `Pos`, so its backtracking counts against `max_parser_backtracks`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…on the legacy path The `TreeRewriter` gate rejected every AST function named `__unique`, so an ordinary call with that name (e.g. an executable UDF) failed with `NOT_IMPLEMENTED` on the legacy expression analysis (constraints, indexes), while the analyzer only dispatches the parser-marked operator. Gate it on `isOperator`, like `resolveFunction` and the formatter. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The rewrite `SELECT count() = uniqExact(*) FROM (subquery) WHERE and(1, * APPLY isNotNull)` reads the columns of the subquery with matchers, which refer to the columns by name. A `UNION` whose first query has several columns with the same name, e.g. `SELECT toNullable(1) AS x, toNullable(1) AS x UNION ALL SELECT NULL, 2`, made both the `NULL` filter and `uniqExact` read the first of them several times, giving a wrong result. Resolve the subquery before the rewrite, in a scope nested in the scope of the rewritten subquery (so that correlation still propagates), and give its columns the unique names `__unique_predicate_column_N` by position, in every query of a `UNION`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…IQUE` predicate `UserDefinedSQLFunctionVisitor`, which runs on the AST in `CREATE VIEW`, `ALTER TABLE ... DELETE`, `DELETE FROM` and similar statements, replaced the operator `__unique` produced by the parser for `UNIQUE(subquery)` with a SQL user defined function of the same name. Skip the operator form; an ordinary call `__unique(...)` is still expanded. Co-Authored-By: Claude Opus 5.5 <[email protected]>
| query_node->setProjectionAliasesToOverride(std::move(unique_names)); | ||
| query_node->resolveProjectionColumns(std::move(projection_columns)); |
There was a problem hiding this comment.
[Blocker] Preserve INTERPOLATE when renaming the subquery projection
Renaming the resolved projection leaves InterpolateNode::getExpressionName holding the original name. QueryNode::removeUnusedProjectionColumns subsequently compares that name with the renamed projection and removes the explicit interpolation item, changing the rows whose uniqueness is tested.
Reproduced on the CI binary for 2680b43172f6:
SELECT UNIQUE(
SELECT number + 10 AS x
FROM numbers(2)
ORDER BY number WITH FILL TO 4
INTERPOLATE (x AS x + 1)
); -- 0; expected 1The standalone subquery produces [10,11,12,13], and adding SELECT x FROM (...) around that same subquery makes the predicate correctly return 1. Please preserve the dependent interpolation metadata when applying positional names, and add this case as a regression test.
There was a problem hiding this comment.
🕵 Fixed in ff0cbf5. This was a general bug, not specific to UNIQUE: the column aliases of a CTE WITH t(y) AS (... INTERPOLATE (x AS x + 1)) SELECT * FROM t and of FROM (...) AS t(y) lost the interpolation the same way on master. QueryNode now keeps the projection column names before the override (getProjectionColumnNamesBeforeOverride); removeUnusedProjectionColumns matches the INTERPOLATE targets by them, and so does the planner when it routes the interpolated values to the result columns (it also matched by the overridden display alias). 05816_unique_predicate_interpolate covers your reproducer and the CTE / table alias cases.
There was a problem hiding this comment.
[Blocker] The local reproducer is fixed, but the same projection/INTERPOLATE mismatch remains when the subquery reads a remote source on ff0cbf575c7:
SELECT UNIQUE(
SELECT number + 10 AS x
FROM remote('127.0.0.1:9000', numbers(2))
ORDER BY number WITH FILL TO 4
INTERPOLATE (x AS x + 1)
);With the PR fast-test binary on both ends (tested on port 19000), this throws UNKNOWN_IDENTIFIER for x instead of returning 1. QueryNode::toASTImpl still writes the overridden projection name at src/Analyzer/QueryNode.cpp:605 and emits the original interpolation target at :636-637: the shard receives SELECT number + 10 AS __unique_predicate_column_0 ... INTERPOLATE (x AS x + 1). The new name mapping is consumed by pruning and the local planner, but is lost during conversion to shard SQL. Please preserve it through that conversion too; the CTE column-alias form over remote fails the same way.
An ordinary call whose argument starts with an identifier that can start a subquery, e.g. `unique(with + 1)` with a column named `with`, was first parsed as a subquery, which read the nested expression before failing, and then parsed again as an ordinary call. Nesting such calls doubled the work at every level, and `max_parser_backtracks` was exhausted at depth 18. The outcome of the speculative parse depends only on the tokens, so a failure is now remembered in `Tokens` by the index of the first token of the argument, and is not repeated when an enclosing expression is parsed again. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The `UNIQUE` predicate (the operator `__unique`) and an ordinary call `__unique(...)` had the same AST hash, so the query cache served the result of one for the other. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ion check While expanding a SQL UDF named `__unique`, the predicate in its body was mistaken for a recursive call, so `CREATE VIEW` rejected it. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…named from outside `INTERPOLATE` items name their targets by the names the columns have in the query. When the projection columns got other names from outside (by the positional renaming of the `UNIQUE` subquery, or by the column aliases of a CTE `t(y)` or of a subquery in `FROM ... AS t(y)`), `QueryNode::removeUnusedProjectionColumns` dropped the items, and the planner did not route the interpolated values to the result columns, so the filled rows had default values. `QueryNode` now keeps the names of the projection columns before the override, and both places use them to match the `INTERPOLATE` targets. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
|
||
| void QueryNode::resolveProjectionColumns(NamesAndTypes projection_columns_value) | ||
| { | ||
| projection_column_names_before_override.clear(); |
There was a problem hiding this comment.
[Blocker] Preserve the original names across a second projection override
This clears the saved names on every call and then records the already overridden projection names. The IN-to-join rewrite calls resolveProjectionColumns again for a resolved CTE, so a CTE column alias replaces the original INTERPOLATE target in this mapping. removeUnusedProjectionColumns then silently removes the interpolation item.
Reproduced on ff0cbf575c7:
WITH t(y) AS (
SELECT number + 10 AS x
FROM numbers(2)
ORDER BY number WITH FILL TO 4
INTERPOLATE (x AS x + 1)
)
SELECT number, number IN t
FROM numbers(12, 2)
ORDER BY number
SETTINGS rewrite_in_to_join = 1;This returns (12, 0), (13, 0), although t contains 10, 11, 12, 13. With the rewrite disabled, or with the CTE column alias removed, both membership results are 1. Preserve the earliest projection names through subsequent renames (and pruning), and add this case to the regression test.
Implement the SQL standard
UNIQUEpredicate that returns true when all rows in a subquery are distinct and false when duplicates exist. Empty subqueries return true (vacuously unique).The implementation follows the same pattern as
EXISTS:UniqueLayerclass parsesUNIQUE(subquery)syntaxifNull((SELECT count() = uniqExact(*) FROM (subquery) WHERE and(1, * APPLY isNotNull)), 1), which is resolved like any other scalar subqueryUNIQUEwith a clear errorCloses: #99609
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Added
UNIQUE(subquery)predicate that returns true when all rows in the subquery are distinct. It behaves according to the SQL standard: duplicates yield false, empty subqueries yield true.Documentation entry for user-facing changes
Workflow [PR]
Sync PR [sync-upstream/pr/99877]