Skip to content

Support SOME/ALL on array expressions - #105129

Merged
alexey-milovidov merged 19 commits into
masterfrom
any-all-on-arrays
Jun 14, 2026
Merged

alexey-milovidov merged 19 commits into
masterfrom
any-all-on-arrays

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented May 16, 2026 •

Copy link
Copy Markdown
Member

PostgreSQL accepts two distinct right-hand sides for expr OP SOME(...) / expr OP ALL(...):

  • A subquery, with IN/NOT IN-style semantics. ClickHouse already rewrites that to IN/NOT IN(SELECT singleValueOrNull/min/max(*) ...) via modifyAST. This applies to ANY / SOME / ALL alike and is unchanged by this PR.
  • An array expression (literal, column, or function call returning an array). Previously this form failed to parse, and PostgreSQL-dialect queries had to be rewritten by hand to has/arrayExists.

After the keyword (SOME/ALL), if the parenthesised content is not a valid subquery, try parsing it as a regular expression. If that succeeds, rewrite at parse time:

  • expr = SOME(arr) -> has(arr, expr)
  • expr <> ALL(arr) -> NOT has(arr, expr)
  • expr OP SOME(arr) -> arrayExists(_a -> expr OP _a, arr) for any other comparison operator
  • expr OP ALL(arr) -> arrayAll(_a -> expr OP _a, arr)

ANY is intentionally not accepted for the array form: any is also an aggregate function, so expr = any(x) keeps its function-call meaning. This avoids a backward-incompatible parse change (e.g. sum(number) = any(number) stays a comparison of two aggregates). SOME is the SQL synonym for the existential quantifier, so use SOME for arrays. Because only SOME/ALL (never ANY, the sole ambiguous keyword) trigger the array rewrite, no left-hand-side disambiguation is needed and the code is simpler.

The =/<> cases are special-cased to has/NOT has because that has an optimized implementation; the general form falls back to the higher-order lambda functions. The lambda variable name is suffixed (_a, _a1, _a2, ...) to avoid collision with any identifier the left-hand side references (including the bound prefix of a compound identifier such as _a.x).

Changelog category (leave one):

  • Improvement

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

PostgreSQL-style expr OP SOME(array) / expr OP ALL(array) (non-subquery right-hand side) is now supported and rewritten to has / NOT has for =/<>, or to arrayExists / arrayAll lambdas for other comparison operators. ANY is not accepted for the array form because any is also an aggregate function; use SOME instead. The subquery form of ANY/SOME/ALL continues to be lowered to IN / NOT IN.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.6.1.789

alexey-milovidov and others added 2 commits May 16, 2026 15:53
PostgreSQL accepts two distinct right-hand sides for `expr OP ANY(...)` /
`expr OP ALL(...)`:

- a subquery, with `IN`/`NOT IN`-style semantics. ClickHouse already
  rewrites that to `IN`/`NOT IN(SELECT singleValueOrNull/min/max(*) ...)`
  via `modifyAST`.
- an array expression (literal, column, or function call returning an
  array). Previously this form failed to parse, and PostgreSQL-dialect
  queries had to be rewritten by hand to `has`/`arrayExists`.

After the keyword (ANY/SOME/ALL), if the parenthesised content is not a
valid subquery, try parsing it as a regular expression. If that
succeeds, rewrite at parse time:

- `expr = ANY(arr)`  -> `has(arr, expr)`
- `expr <> ALL(arr)` -> `NOT has(arr, expr)`
- `expr OP ANY(arr)` -> `arrayExists(_a -> expr OP _a, arr)` for any
  other comparison operator
- `expr OP ALL(arr)` -> `arrayAll(_a -> expr OP _a, arr)`

The `=`/`<>` cases are special-cased to `has`/`NOT has` because that has
an optimized implementation; the general form falls back to the lambda
higher-order functions. The lambda variable name (`_a`) is chosen to be
unlikely to collide with user identifiers in `expr`.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
When `expr OP ANY(arr)` / `expr OP ALL(arr)` is rewritten to
`arrayExists`/`arrayAll`, the lambda parameter would shadow any
identifier in `expr` that happens to share its name, silently producing
wrong results. Scan `expr` for identifier references and pick a lambda
variable name (suffixed `_a`, `_a1`, `_a2`, ...) that does not collide
with any of them.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented May 16, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [7ffcbf2]

Summary: ✅


AI Review

Summary

This PR adds parser-level support for expr OP SOME(array) and expr OP ALL(array), rewrites those forms to has / NOT has or arrayExists / arrayAll, documents the intentional ANY exclusion and NULL semantics, and adds focused stateless coverage. I did not find any remaining correctness, compatibility, or documentation issues in the current head.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label May 16, 2026
Comment thread src/Parsers/ExpressionListParsers.cpp Resolved
The reference was one line short — the test runs 25 SELECT queries but
the file listed 24 expected lines. Regenerated from the actual output.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
alexey-milovidov added a commit that referenced this pull request May 16, 2026
Recent compatibility PRs added case-insensitive aliases and parser sugar
that make several of the SQLStorm rewrites unnecessary:

  - `STDDEV`            -> `stddevPop`            (#105120)
  - `array_to_string`   -> `arrayStringConcat`    (#105121)
  - `REGEXP_SUBSTR`     -> `regexpExtract`        (#105122)
  - `CARDINALITY`       -> `length`               (#105123)
  - `unnest()` function -> `arrayJoin()`          (#105124)
  - `STRING_AGG`        -> `groupConcat`          (#105125)
  - `date_part(unit,e)` -> `EXTRACT(unit FROM e)` (#105127)
  - `expr OP ANY/ALL(array_literal)`              (#105129)

`ARRAY_AGG`, `TRANSLATE`, and `EXTRACT(EPOCH|DOW|... FROM ...)` were
already supported by ClickHouse before these PRs.

Removed the corresponding rewrite calls and helper functions
(`rewrite_string_agg`, `rewrite_array_agg`, `rewrite_date_part`,
`rewrite_stddev`, `rewrite_extract_epoch`, the EXTRACT(DOW) inline
rewrite, `rewrite_any_comparison`, and the trailing
`unnest(...) -> arrayJoin(...)` substitution). Also dropped the
unreferenced no-op helpers (`rewrite_extract_unit`, `rewrite_fetch_offset`,
`rewrite_interval`, `rewrite_cast_timestamp`, `rewrite_current_timestamp`,
`rewrite_bool_literals`, `rewrite_ilike`, `rewrite_no_supertype`).

The PostgreSQL `LATERAL` / `CROSS JOIN UNNEST(...)` table-source forms,
`arrayJoin(...)` in JOIN position, PG-specific casts, `AT TIME ZONE`,
`STRING_AGGDistinct` (a mangled-name artifact), and the still-unsupported
function rewrites (`string_to_array`, `regexp_split_to_array`, `RANDOM`,
`TO_TIMESTAMP`, `ARRAY_LENGTH`, `SPLIT_PART`, `age`) are still rewritten.

Net change: -329 lines from rewrite_queries.py and -75 lines from the
tests (the `TestRewriteAnyComparison` class is removed since the rewrite
it covered no longer exists).

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

Copy link
Copy Markdown
Contributor

It would also be great for indexes to work if OP is an index-using function. For example ANY(arr) LIKE '% foo %' could use a Text or bloom filter index. It would maybe obviate #104499 (or help to implement it)

alexey-milovidov and others added 2 commits May 17, 2026 04:01
When the left-hand side of a comparison was itself an `any`/`some`/`all`
aggregate function call, the new `ANY/ALL` parser would greedily rewrite
the right-hand side as PostgreSQL-style ANY (e.g. `any(0) = any(1)` ->
`has(1, any(0))`), changing the meaning of aggregate-vs-aggregate
comparisons that were valid before this PR.

Detect that shape at parse time by peeking at the top of the operand
stack before applying the rewrite — if the LHS is `any/some/all(...)`,
back out and let the `any(...)` on the right parse as a regular function
call. The PostgreSQL rewrite continues to apply for ordinary cases like
`col = ANY([1, 2, 3])` and `(number + 1) = ANY(arr)`.

Also update `02007_test_any_all_operators` to use unambiguous shapes:
`sum(number) = any(number)` is replaced by `sum(number) = max(number)`
(LHS is a different aggregate, not `any/some/all`, so it would still be
rewritten), and `1 == any (1)` is replaced by `1 == any (select 1)` (the
non-subquery `any(1)` cannot keep its old function-call meaning under
PostgreSQL semantics — `has(1, 1)` is a type error).

CI report (before fix): https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=105129&sha=038ecbfa3c02afccdba3ca2d86e1d838208ed5a5&name_0=PR&name_1=Fast%20test

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

This was fixed by #105146. Let's update the branch.

`expr <> ALL(arr)` was rewritten to an AST built with
`makeASTFunction("not", ...)`, which omits the `is_operator` flag. That
node printed as `not(...)` (function-call form), while the same query
re-parsed produced `NOT (...)` (unary operator form). The
parse-format-roundtrip check in `executeQuery` then reports
`Inconsistent AST formatting between 'ExpressionList' and
'ExpressionList'` and aborts in the debug build.

Build the `not` node via `makeASTOperator` so it carries the
`is_operator` flag and formats with the same operator path the parser
uses, making the formatted output stable across the roundtrip.

Also adds shadowing regression cases for the lambda-variable suffixing
in `04241_any_all_on_arrays`.

CI fuzzer report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=105129&sha=4581cac8877a4fbbc8c9c82811df7fb58b2c10d1&name_0=PR
@alexey-milovidov

Copy link
Copy Markdown
Member Author

@groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=105129&sha=3d822d8ce62cde9df597877d8d0c241ab1c422c8&name_0=PR&name_1=Integration%20tests%20%28amd_asan_ubsan%2C%20db%20disk%2C%20old%20analyzer%2C%206%2F6%29 and provide a fix in a separate PR. If the fix is already in progress, link it here.

test_paimon_incremental_read/test.py::test_paimon_to_mergetree_via_refresh_mv crashed inside DB::PaimonTableClient::getLatestTableSnapshotInfo -> readStringUntilEOFInto -> ReadBuffer::next on a background refresh thread (PaimonMetadata::runBackgroundRefresh). It is unrelated to this PR (parser-only change) — CIDB shows the same test failing in master CI on 2026-05-19 and 2026-05-11 and on unrelated PRs (#100185, #102343, #102031).

@groeneai

Copy link
Copy Markdown
Collaborator

@alexey-milovidov confirmed unrelated to this PR. Investigation summary below.

Cross-PR distribution (CIDB, 30d, test_paimon_incremental_read):

pull_request_number cnt window
0 (master, head_ref = 'master') 4 2026-05-11, 2026-05-19
#100185 (your IColumn assertions PR) 12 2026-05-14
#102343 (Paimon re-add, merged 2026-05-08) 2 2026-04-30
#105123 (your CARDINALITY alias PR) 2 2026-05-18
#105129 (this PR) 1 2026-05-18

The four implicated unrelated PRs are all parser-only or assertion-tightening changes that do not touch Paimon code paths. This is a chronic master flake.

Root cause:

The exception is the file_offset_of_buffer_end <= getFileSize() chassert at src/Disks/IO/AsynchronousBoundedReadBuffer.cpp:291, hit from PaimonTableClient::getLatestTableSnapshotInfo (PaimonClient.cpp:178) reading the LATEST hint file via readStringUntilEOF. AsynchronousBoundedReadBuffer caches the file size from S3 metadata at open time. PaimonMetadata::runBackgroundRefresh fires every paimon_metadata_refresh_interval_sec (default 30s), so its reads race the test workload, which atomically replaces the LATEST hint after every commit. When the file is replaced with a different size between the getObjectMetadata call and the prefetch landing, the buffer's file_offset_of_buffer_end can exceed the cached size and trip the assertion. The existing try/catch in getLatestTableSnapshotInfo does not catch it because chassert routes through abortOnFailedAssertion rather than throwing.

Precedent for fix:

#100763 (merged 2026-03-28, by you, closes #82555) fixed the same assertion class for Log/StripeLog on S3 by calling setReadUntilPosition(file_size) after opening the buffer. The same pattern applies here: capture size at getObjectMetadata, then clamp the buffer with setReadUntilPosition. For Paimon the race is concurrent replacement rather than concurrent growth, but the assertion mechanism is identical.

Existing trackers:

None. No GitHub issue or open fix PR mentions getLatestTableSnapshotInfo or this assertion in the Paimon path.

cc @Binnn-MX (Paimon author), @kssenii @alesapin (comp-datalake / FS cache)

I will follow up with a fix PR following the setReadUntilPosition pattern, gated on local repro and the pre-PR validation checklist. Tracking on my side under task 2026-05-19-github-clickhouseclickhouse105129--.

@PedroTadim PedroTadim self-assigned this May 20, 2026
…regressions

Per @PedroTadim's request, re-add the two queries that were dropped from
`02007_test_any_all_operators` when the parser started rewriting the
non-subquery `expr OP ANY/ALL(...)` form as PostgreSQL quantifiers.

- `select sum(number) = any(number) from numbers(1) group by number;`
- `select 1 == any (1);`

Both used to succeed because `any(...)` was parsed as the aggregate
function call. They now route through the new `ANY(array)` path and the
analyzer rejects them with `ILLEGAL_TYPE_OF_ARGUMENT` because `has` /
`arrayExists` / `arrayAll` require an array on the left-hand side. The
two queries are kept under `-- { serverError ILLEGAL_TYPE_OF_ARGUMENT }`
to document the regression rather than silently dropping coverage.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

It is essential to keep current queries working.

@alexey-milovidov
alexey-milovidov marked this pull request as draft May 21, 2026 04:17
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Yes, unfortunately, we have to disambiguate using data types.

Given x op ANY(expr), we should check if the array dimensionality of the expr is deeper by one than the dimensionality of x. If it is the case, resolve like a higher-order function.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

Pushed master merge.

On dim-based disambiguation: parser has no types, so it must be analyzer-time. But equals(Int, Array(Int)) from 1 = ANY([1,2,3]) would fail in QueryAnalysisPass before any later pass could intervene. Approach I'm proposing:

  1. Internal marker __pgQuantifierEqAny(lhs, rhs) (permissive args, UInt8 return) emitted by the parser for lhs =/== ANY/SOME(non-subquery).
  2. New post-QueryAnalysisPass pass: if dim(rhs) == dim(lhs) + 1 → has(rhs, lhs); if dim(rhs) == dim(lhs) → equals(lhs, any(rhs)) (legacy aggregate).

This covers both regressions you flagged (sum(number) = any(number), 1 == any(1)) because both have dim diff == 0 and fall to the aggregate path.

Extending to <> ANY / = ALL (general ops needing arrayExists/arrayAll) requires post-analysis lambda construction, which is more intricate. Start with = ANY/SOME scope, or commit to the full coverage?

Comment thread src/Parsers/ExpressionListParsers.cpp Resolved
Comment thread src/Parsers/ExpressionListParsers.cpp Resolved
Comment thread src/Parsers/ExpressionListParsers.cpp Resolved
…rs in ANY/ALL on arrays

When `expr OP ANY(array)` / `expr OP ALL(array)` is rewritten to an
`arrayExists` / `arrayAll` lambda, the lambda variable name is chosen to
avoid colliding with identifiers referenced on the left-hand side. The
collision check only inserted the full identifier name, so for a
table-qualified compound identifier such as `_a.x` it recorded `_a.x` but
not `_a`. The analyzer binds the first part (`_a`) of a compound identifier,
so the generated lambda variable `_a` shadowed the table alias and the
expression resolved incorrectly.

Record every name part of an identifier (not just the full name), so the
lambda variable also avoids the bound prefix.

Also document, as part of the test contract, the NULL handling of the array
form: it follows `has` (two-valued) for `=`/`<>` and `arrayExists` /
`arrayAll` (which fold unknown to `0`) for other operators. The rewrite is
done at parse time, where settings are unavailable and a per-row array
column cannot use the analyzer's null-safe `IN` path, so it can differ from
the subquery form whose NULL handling depends on `transform_null_in`.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Comment thread src/Parsers/ExpressionListParsers.cpp Resolved
@alexey-milovidov
alexey-milovidov marked this pull request as ready for review June 7, 2026 02:51
alexey-milovidov and others added 2 commits June 7, 2026 03:23
Address review: the new PostgreSQL-style array quantifier syntax was
not described in `docs/en/sql-reference/operators/index.md`, which only
covered the subquery form.

Add an `ANY / ALL on arrays` section documenting the array right-hand
side form, its rewrite to `has` / `NOT has` (for `=` / `<>`) and
`arrayExists` / `arrayAll` (for other comparison operators), the
two-valued `NULL` handling and how it can differ from the subquery
form (which depends on `transform_null_in`), and the change in parsing
of ambiguous `any(...)` / `all(...)` function-call shapes.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

The sole CI failure (AST fuzzer arm_asan_ubsan, UndefinedBehaviorSanitizer at src/Functions/compareSubstrings.cpp:328) is unrelated to this PR: it is a pre-existing out-of-bounds pointer-arithmetic UB in compareSubstrings that the fuzzer happened to hit while mutating unrelated queries (e.g. compareSubstrings(s1, s2, 4, 4, 1048577) over FixedString(3) columns). This PR only changes ANY/ALL parsing in ExpressionListParsers.cpp and does not touch compareSubstrings; the triggering query has no ANY/ALL syntax.

Fix submitted separately: #106733

@alexey-milovidov alexey-milovidov left a comment

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.

I propose a compromise: implement only ALL and SOME. Skip ANY due to ambiguity. Simplify the code.

Following the review compromise, only `SOME` and `ALL` accept a
non-subquery array right-hand side; `ANY` is no longer rewritten for the
array form. Because `any` is also an aggregate function, an expression
such as `expr = any(x)` keeps its function-call meaning, which removes
the backward-incompatible parse change that previously turned
`sum(number) = any(number)` into `has(number, sum(number))`.

This also lets us drop the left-hand-side-peek backward-compatibility
shim (and the `peekOperand` helper) that only existed to special-case
`any(x) OP any(y)`: since `ANY` no longer triggers the array rewrite, the
disambiguation is unnecessary. The subquery form of `ANY`/`SOME`/`ALL`
is unchanged.

`02007_test_any_all_operators` is reverted to its original form (the
`any(...)` function-call queries are valid again), and
`04241_any_all_on_arrays` is reworked to use `SOME` for the array form,
with a regression assertion that `1 = any([1, 2, 3])` stays the aggregate
and fails the type check. The operator documentation is rewritten to
describe the `SOME`/`ALL` array form and drops the ambiguous-parsing note.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Comment thread src/Parsers/ExpressionListParsers.cpp Resolved
alexey-milovidov and others added 2 commits June 14, 2026 12:21
The `SOME` / `ALL` array form is rewritten only when the pending operator
is tagged `OperatorType::Comparison` (`=`, `==`, `!=`, `<>`, `<=>`, `<`,
`<=`, `>`, `>=`). Operators such as `LIKE`, `ILIKE`, `NOT LIKE`, `REGEXP`,
and `IN` are not tagged as comparison operators, so they fall through and
keep their ordinary meaning instead of becoming `arrayExists` / `arrayAll`.

Narrow the documentation to enumerate the supported operators explicitly
and state that the other array-accepting operators are not part of the
array-quantifier syntax, matching the implementation.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jun 14, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.80% 84.70% -0.10%
Functions 92.40% 92.30% -0.10%
Branches 77.30% 77.30% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 51/56 (91.07%) | Lost baseline coverage (was covered on master, now uncovered in this PR): 2 line(s) · Uncovered code

Full report · Diff report

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jun 14, 2026
@alexey-milovidov alexey-milovidov changed the title Support ANY/SOME/ALL on array expressions Support SOME/ALL on array expressions Jun 14, 2026
Merged via the queue into master with commit ce696b9 Jun 14, 2026
166 checks passed
@alexey-milovidov
alexey-milovidov deleted the any-all-on-arrays branch June 14, 2026 17:33
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 14, 2026
pull Bot pushed a commit to Mu-L/ClickHouse that referenced this pull request Jun 27, 2026
…L` array quantifier

Follow-up to ClickHouse#105129, which added the PostgreSQL-style `expr OP SOME(array)` /
`expr OP ALL(array)` array quantifier but only for operators tagged
`OperatorType::Comparison` (`=`, `==`, `!=`, `<>`, `<=>`, `<`, `<=`, `>`, `>=`).

The keyword predicates `IS DISTINCT FROM` and `IS NOT DISTINCT FROM` carry the
default `OperatorType::None`, so they were never routed through the rewrite, even
though they are comparison predicates - `1 IS DISTINCT FROM ALL([2, 3])` was not
recognised as the array quantifier.

Route `IS DISTINCT FROM` / `IS NOT DISTINCT FROM` through the `arrayExists` /
`arrayAll` lambda form as well, by peeking at the pending operator's function name
(new `Layer::previousOperator`) in addition to its `OperatorType`. The subquery ->
`IN` / `NOT IN` path stays restricted to symbolic comparison operators, where it
has meaning.

The string-search predicates `LIKE`, `ILIKE`, `NOT LIKE`, `NOT ILIKE`, and `REGEXP`
are deliberately excluded from the array form: their implementation (`MatchImpl`)
does not support a constant haystack with a non-constant needle, so
`'abc' LIKE SOME([...])` would throw `ILLEGAL_COLUMN`. The operator documentation
now lists the exact supported operators and explains that these predicates must be
written out with `arrayExists` / `arrayAll`.

Addresses the review on ClickHouse#105129:
ClickHouse#105129 (comment)

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-improvement Pull request with some product improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants