Skip to content

Support parts of the Trino SQL dialect in ClickHouse SQL - #124763

Merged
alexey-milovidov merged 16 commits into
masterfrom
trino-compatible-syntax
Oct 15, 2026
Merged

alexey-milovidov merged 16 commits into
masterfrom
trino-compatible-syntax

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Oct 8, 2026 •

Copy link
Copy Markdown
Member

Adds the parts of the Trino SQL dialect that fit into ClickHouse SQL without changing the meaning of any query that was valid before. Users no longer need the experimental Trino dialect (dialect = 'trino') for the most common Trino idioms.

Syntax:

  • TRY_CAST(x AS T) (also TRY_CAST(x, 'T')) is parsed as accurateCastOrNull(x, 'T'). The same syntax exists in Spark, Snowflake, DuckDB, and SQL Server.
  • ARRAY[a, b, ...] and ARRAY[] construct an array, as in the SQL standard, PostgreSQL, and Trino. A single-element ARRAY[x] can't be told apart from subscripting a column named ARRAY, so the parser keeps it as a subscript. The analyzer turns it into the constructor only when no column, alias, or lambda argument named ARRAY resolves, so existing queries such as SELECT array[1] FROM t behave as before.
  • The type names ARRAY(T) and MAP(K, V) are accepted case-insensitively and normalized to Array and Map in the AST. ROW is intentionally not supported, because a different Row data type may be added in the future.

The parser-level rewrites produce the existing functions and type names, so queries sent to older remote servers keep working.

Function aliases (case-insensitive) are added only where the Trino function has the same argument order and semantics as an existing ClickHouse function:

  • Strings: starts_with, ends_with, levenshtein_distance, regexp_like (with RE2 syntax, as the existing REGEXP_MATCHES, REGEXP_REPLACE, and REGEXP_EXTRACT aliases)
  • Math: is_nan, is_finite, is_infinite
  • Date and time: day_of_month, day_of_week, day_of_year, week_of_year, year_of_week, last_day_of_month, current_timezone, format_datetime
  • Arrays and maps: array_union, slice, zip, map_keys, map_values
  • URLs: url_extract_host (an alias of domainRFC, which handles userinfo as Trino does), url_extract_protocol, url_encode, url_decode
  • Bits and encodings: bitwise_and, bitwise_or, bitwise_xor, to_hex, from_hex, to_base32, from_base32, to_base64url, from_base64url, uuid
  • Aggregate functions: arbitrary, bool_and, bool_or, bitwise_and_agg, bitwise_or_agg, bitwise_xor_agg

These were left out on purpose because a plain alias would silently give different results:

  • contains: a string function in Spark and Snowflake.
  • strpos and array_intersect: their 3-argument and 1-argument Trino forms mean something else.
  • array_except: Trino removes duplicates from the first argument, arrayExcept keeps them.
  • to_unixtime: already an alias of parseDateTime.
  • approx_distinct: its second argument is an error bound.
  • count_if: an alias to a combinator is not possible.
  • bitwise_not: literal width.
  • hamming_distance: code points vs. bytes.
  • murmur3 and xxhash64: the binary result layout differs.
  • arrays_overlap: Trino returns NULL when there is no common non-NULL element but one side contains NULL.
  • date_parse and parse_datetime: they return timestamp(3) and a timestamp with time zone, not DateTime.
  • url_extract_parameter: extractURLParameter also reads parameters from the fragment, while Trino reads only the query string.
  • url_extract_path, url_extract_query, and url_extract_fragment: the ClickHouse extractors return raw substrings, while Trino decodes the components and parses URI boundaries.
  • array_distinct: arrayDistinct drops NULL elements, while Trino keeps one.
  • array_min and array_max: Trino returns NULL for an array with a NULL element and for an empty array.
  • regexp_count: countMatches skips zero-length matches, while Trino counts them.

Not included: element_at (arrayElementOrNull returns a default value rather than NULL for a missing position or key when the element type can't be inside Nullable) and array_position (already a PostgreSQL-compatible function, which returns NULL rather than Trino's 0 for a missing element). As with every ClickHouse aggregate function, the aggregate aliases return the default value on empty input unless aggregate_functions_null_for_empty is enabled.

A known limitation: TRY_CAST to a type that can't be inside Nullable, such as Array, throws, as accurateCastOrNull does.

Changelog category (leave one):

  • Improvement

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

Support parts of the Trino SQL dialect in regular ClickHouse SQL: TRY_CAST(x AS T), the ARRAY[...] array constructor, the type names ARRAY(T) and MAP(K, V), and aliases for Trino functions such as starts_with, slice, regexp_like, day_of_week, url_extract_host, bitwise_and, arbitrary, and bool_and.

🤖 Generated with Claude Code


Workflow [PR]
Sync PR [sync-upstream/pr/124763]

Version info

  • Merged into: 26.10.1.2448-master (included in 26.10 and later)

These additions don't change the meaning of any query that was valid before:
- `TRY_CAST(x AS T)` is parsed as `accurateCastOrNull(x, 'T')`.
- `ARRAY[a, b, ...]` and `ARRAY[]` are the array constructor. A single
  element `ARRAY[x]` still subscripts a column or alias named `ARRAY` if
  there is one; otherwise the analyzer treats it as the constructor.
- `ROW(a, b)` is `tuple(a, b)`.
- The data types `ARRAY(T)`, `MAP(K, V)`, and `ROW(name T, ...)` are
  accepted case-insensitively.
- Case-insensitive aliases are added for Trino functions whose semantics and
  argument order match an existing ClickHouse function: `starts_with`,
  `ends_with`, `levenshtein_distance`, `regexp_like`, `regexp_count`,
  `is_nan`, `is_finite`, `is_infinite`, `day_of_month`, `day_of_week`,
  `day_of_year`, `week_of_year`, `year_of_week`, `last_day_of_month`,
  `current_timezone`, `format_datetime`, `parse_datetime`, `date_parse`,
  `array_distinct`, `array_union`, `array_except`, `array_max`, `array_min`,
  `array_position`, `arrays_overlap`, `element_at`, `slice`, `zip`,
  `map_keys`, `map_values`, `url_extract_*`, `url_encode`, `url_decode`,
  `bitwise_and`, `bitwise_or`, `bitwise_xor`, `to_hex`, `from_hex`,
  `to_base32`, `from_base32`, `to_base64url`, `from_base64url`, `uuid`,
  and the aggregate functions `arbitrary`, `bool_and`, `bool_or`,
  `bitwise_and_agg`, `bitwise_or_agg`, `bitwise_xor_agg`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@mintlify

mintlify Bot commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

Preview deployment for your docs. Learn more about Mintlify Previews.

Project Status Preview Updated
ClickHouse-docs 🟢 Ready View Preview Oct 14, 2026, 2:28 PM

@clickhouse-gh clickhouse-gh Bot added the comp-sql-syntax SQL/grammar parsing, AST nodes, syntax-level features. label Oct 8, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Remove "ROW" because we might end up with a different Row data type in the future.

# Conflicts:
#	src/Parsers/ExpressionListParsers.cpp
@clickhouse-gh

clickhouse-gh Bot commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a4d4b78]

Summary: ✅


AI Review

Summary

This PR adds TRY_CAST, ARRAY[...], composite-type spellings, and Trino function aliases to regular ClickHouse SQL. Seven issues remain: the parser breaks existing scoped try_cast calls, four aliases change results for supported inputs, and two aliases reject supported Trino inputs. These violate the promised compatibility; changes are required before merge.

Missing context / blind spots
  • ⚠️ No local PR binary was available. Boundary probes used the existing canonical functions on the public ClickHouse server (26.10.1.448); the PR's alias mappings and parser changes were verified in the checked-out source. Run the focused cases below against the PR binary to complete runtime validation.
Findings

❌ Blockers

⚠️ Majors

Tests
  • ⚠️ Add focused stateless coverage for scoped try_cast, empty/Unicode edit-distance inputs in both argument orders and with materialized columns, negative slice offsets preceding the array, URL encoding of * and ~, and Base64 URL input lengths requiring one and two padding characters. The current Base64 reference needs correction if the alias remains.
  • ⚠️ If zip and from_base32 remain, cover nested element types and unpadded final Base32 chunks, respectively. Retain malformed-input checks when implementing decoder compatibility.
Final Verdict

❌ Block. Preserve existing scoped-function calls, correct or omit the incompatible aliases above, and add focused regression coverage for retained behavior.

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Oct 9, 2026
`ROW` is reserved because a different `Row` data type may be added in the future.
`ROW(...)` is no longer parsed as `tuple(...)`, and the `ROW(name T, ...)` type name
is no longer normalized to `Tuple`.

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

Copy link
Copy Markdown
Member Author

🕵 Removed ROW: it is no longer parsed as tuple(...), and the ROW(name T, ...) type name is no longer normalized to Tuple (commit 4c79032). Also merged master to resolve the conflict in ExpressionListParsers.cpp. The PR description is updated.

alexey-milovidov and others added 2 commits October 10, 2026 05:55
…hecks out of the fast test

`exactArgument` read `type_text` unsequenced with `std::move(type_text)`.
`base64URLEncode` requires `simdutf`, which is absent in the fast test build.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=124763&sha=latest&name_0=PR
#124763

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Functions/array/hasAny.cpp Resolved
Comment thread src/Functions/match.cpp Resolved
Comment thread src/Functions/parseDateTime.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit a4d4b78ddf92890dca40aa31fa51cb7d069b2f09 was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception).

See the job log for details.

…e` aliases

Their Trino semantics differ from the ClickHouse functions they were mapped to:
`arrays_overlap` uses three-valued logic with `NULL` while `hasAny` does not,
`date_parse` returns `timestamp(3)` and `parse_datetime` returns a timestamp
with time zone, while `parseDateTime` and `parseDateTimeInJodaSyntax` return
`DateTime`.

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

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/PRs/124763/4beef0a765dd2994efaaa27c9764dfdc952fa341/pr/stateless_tests_arm_asan_ubsan_azure_sequential/job.log — Stateless tests (arm_asan_ubsan, azure, sequential) hit the job timeout at test 1176/1180 with no failed tests (unrelated to this PR, which only adds parser rewrites and function aliases), and provide a fix in a separate PR. If the fix is already in progress, link it here.

@groeneai

Copy link
Copy Markdown
Collaborator

This is the same job-level overrun that #123849 (mine, open) fixes by splitting Stateless tests (arm_asan_ubsan, azure, sequential) into 2 hash batches. @ Algunenano asked me not to push to it and is merging it himself; it currently conflicts with master.

On 4beef0a the job ran out of time but did not hang: 1176 / 1180 tests reached (1078 OK, 98 skipped, 0 failed), and the kill came 11 s after the last test finished. Nothing in this PR needs to change.

Comment thread src/Parsers/ExpressionListParsers.cpp Resolved
Comment thread src/Functions/array/arrayElement.cpp Resolved
alexey-milovidov and others added 3 commits October 11, 2026 21:42
…function on master

Master now has a PostgreSQL-compatible `array_position` function, so registering
the alias made the server throw `LOGICAL_ERROR` at startup after the merge.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… alias

`TRY_CAST` now passes a literal argument through `exactCastArgument` like `CAST`
does, so `TRY_CAST(0.1 AS Decimal256(76))` and wide integer literals are not
rounded through `Float64` before `accurateCastOrNull`.

`element_at` is removed: `arrayElementOrNull` returns the default value instead
of `NULL` for a missing position or key when the element type cannot be inside
`Nullable` (nested arrays, maps), which differs from Trino.

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

Copy link
Copy Markdown
Member Author

@groeneai

Copy link
Copy Markdown
Collaborator

Neither is caused by this PR, and both already have a fix:

Comment thread src/Functions/URL/domain.cpp Resolved
alexey-milovidov and others added 2 commits October 12, 2026 18:28
…extract_parameter`

`domain` returns an empty string for URLs with userinfo, while Trino's
`url_extract_host` returns the host, so alias it to the RFC 3986 conformant
`domainRFC` instead.

`extractURLParameter` also reads parameters from the fragment, while Trino's
`url_extract_parameter` reads only the query string, so remove that alias.

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

Copy link
Copy Markdown
Member Author

🕵 Status after f9fe7ff (merged master, addressed the review on url_extract_host / url_extract_parameter). The CI failures on 80aed35 are unrelated to this PR:

alexey-milovidov pushed a commit to raimannma/ClickHouse that referenced this pull request Oct 12, 2026
…ability

Stress test (amd_debug) on ClickHouse#124763 could not restart the server: the load of
`test_7.reader_hard_links__fuzz_4` failed with `Code: 4 ... primary.cidx is
unexpectedly long`. That table is a clone of the test's read-only reader made
by the server-side AST fuzzer (`ast_fuzzer_any_query = true` in Stress) with
`key Array(Int32)` over the writer's `Int32` part. The clone's CREATE passed
only because its primary index prewarm hit the original reader's cache entry,
which is keyed by disk name and part path; after the restart the cache is
empty and the clone's own index load fails. Such a misdeclared `table_disk`
reader is documented as unsupported.

The part survived because the cleanup aborted at its first statement: the
fault-injected `ignore_drop_queries_probability = 0.2` turns `DROP TABLE
reader SYNC` on a read-only table into a TRUNCATE, which fails with
`Code: 774`, so the writers were never dropped.

Set `ast_fuzzer_any_query = 0, ignore_drop_queries_probability = 0` in the
two sessions that create the tables and `ignore_drop_queries_probability = 0`
in the cleanup session, as for 05104, 05227 and 05228. SELECTs, hypothetical
indexes and the cleanup DROPs stay fuzzed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… constructor

An explicit `arrayElement(array, 1)` call must still raise `UNKNOWN_IDENTIFIER`
when `array` is not resolved, so gate the rewrite on `FunctionNode::isOperator`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Functions/array/arrayExcept.cpp Resolved
alexey-milovidov and others added 2 commits October 13, 2026 22:03
Trino's `array_except` removes duplicates from the first argument, while
`arrayExcept` preserves them, so the alias would silently change results.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Functions/array/arrayDistinct.cpp Resolved
Comment thread src/Functions/URL/path.cpp Resolved
Comment thread src/Functions/countMatches.cpp Resolved
alexey-milovidov and others added 2 commits October 14, 2026 13:18
Remove `array_distinct` (Trino keeps one `NULL` element), `array_min` and
`array_max` (Trino returns `NULL` for arrays with `NULL` elements and for
empty arrays), `url_extract_path`, `url_extract_query`, `url_extract_fragment`
(Trino decodes the components and parses URI boundaries), and `regexp_count`
(Trino counts zero-length matches). The experimental Trino dialect keeps its
own mappings.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Parsers/ExpressionListParsers.cpp Resolved
Comment thread src/Functions/array/arraySlice.cpp Resolved
Comment thread src/Functions/base64URLEncode.cpp Resolved
Comment thread src/Functions/array/arrayZip.cpp Resolved
Comment thread src/Functions/base32Decode.cpp Resolved
@alexey-milovidov

Copy link
Copy Markdown
Member Author

We will intentionally keep these differences in behavior in corner cases to Trino.

@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.

Mostly aliases. Only the ARRAY[...] case was unusual. LGTM.

@alexey-milovidov alexey-milovidov self-assigned this Oct 15, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 15, 2026
Merged via the queue into master with commit 57332cc Oct 15, 2026
177 checks passed
@alexey-milovidov
alexey-milovidov deleted the trino-compatible-syntax branch October 15, 2026 04:35
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 15, 2026
punithns97 pushed a commit to punithns97/ClickHouse that referenced this pull request Nov 3, 2026
isArrayConstructorWithKeyword (added in ClickHouse#124763) decides whether `ARRAY[`
starts the array constructor by scanning forward for a depth-0 comma or
closing bracket. The scan did not stop at `;`, so for an `ARRAY[` that is
not closed in its own statement it read tokens of the next statement.
Tokens::max() follows every token a parser looks at and is what
tryParseQuery reports as the error position, while the generic error
branch passes the end of the first statement as the end of the excerpt.
writeQueryAroundTheError then computed `end - begin` with begin > end, and
the unsigned length wrapped: the message contained bytes read past the end
of the query text, and ASan builds aborted (found by select_parser_fuzzer,
heap-buffer-overflow in UTF8::computeBytesBeforeWidth).

A `;` token cannot be inside the brackets of one statement, so the scan now
returns false there: such an `ARRAY[` is not an array constructor, and the
parser fails at the `;` exactly as before ClickHouse#124763. Valid queries are not
affected.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

This branch was successfully deployed

1 active deployment
staging - docs — a4d4b78d Deployed Oct 14, 2026 by mintlify[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-sql-syntax SQL/grammar parsing, AST nodes, syntax-level features. 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.

3 participants