Repository navigation
Support parts of the Trino SQL dialect in ClickHouse SQL - #124763
Conversation
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]>
|
Preview deployment for your docs. Learn more about Mintlify Previews.
|
|
Remove "ROW" because we might end up with a different Row data type in the future. |
# Conflicts: # src/Parsers/ExpressionListParsers.cpp
|
Workflow [PR], commit [a4d4b78] Summary: ✅
AI ReviewSummaryThis PR adds Missing context / blind spots
Findings❌ Blockers
Tests
Final Verdict❌ Block. Preserve existing scoped-function calls, correct or omit the incompatible aliases above, and add focused regression coverage for retained behavior. |
`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]>
|
🕵 Removed |
…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]>
Build profile diff (arm_release)Commit 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]>
|
🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/PRs/124763/4beef0a765dd2994efaaa27c9764dfdc952fa341/pr/stateless_tests_arm_asan_ubsan_azure_sequential/job.log — |
|
This is the same job-level overrun that #123849 (mine, open) fixes by splitting 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. |
…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]>
|
🕵 @groeneai, investigate the failures: |
|
Neither is caused by this PR, and both already have a fix:
|
…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]>
|
🕵 Status after f9fe7ff (merged
|
…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]>
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]>
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]>
|
We will intentionally keep these differences in behavior in corner cases to Trino. |
alexey-milovidov
left a comment
There was a problem hiding this comment.
Mostly aliases. Only the ARRAY[...] case was unusual. LGTM.
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]>
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)(alsoTRY_CAST(x, 'T')) is parsed asaccurateCastOrNull(x, 'T'). The same syntax exists in Spark, Snowflake, DuckDB, and SQL Server.ARRAY[a, b, ...]andARRAY[]construct an array, as in the SQL standard, PostgreSQL, and Trino. A single-elementARRAY[x]can't be told apart from subscripting a column namedARRAY, so the parser keeps it as a subscript. The analyzer turns it into the constructor only when no column, alias, or lambda argument namedARRAYresolves, so existing queries such asSELECT array[1] FROM tbehave as before.ARRAY(T)andMAP(K, V)are accepted case-insensitively and normalized toArrayandMapin the AST.ROWis intentionally not supported, because a differentRowdata 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:
starts_with,ends_with,levenshtein_distance,regexp_like(with RE2 syntax, as the existingREGEXP_MATCHES,REGEXP_REPLACE, andREGEXP_EXTRACTaliases)is_nan,is_finite,is_infiniteday_of_month,day_of_week,day_of_year,week_of_year,year_of_week,last_day_of_month,current_timezone,format_datetimearray_union,slice,zip,map_keys,map_valuesurl_extract_host(an alias ofdomainRFC, which handles userinfo as Trino does),url_extract_protocol,url_encode,url_decodebitwise_and,bitwise_or,bitwise_xor,to_hex,from_hex,to_base32,from_base32,to_base64url,from_base64url,uuidarbitrary,bool_and,bool_or,bitwise_and_agg,bitwise_or_agg,bitwise_xor_aggThese were left out on purpose because a plain alias would silently give different results:
contains: a string function in Spark and Snowflake.strposandarray_intersect: their 3-argument and 1-argument Trino forms mean something else.array_except: Trino removes duplicates from the first argument,arrayExceptkeeps them.to_unixtime: already an alias ofparseDateTime.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.murmur3andxxhash64: the binary result layout differs.arrays_overlap: Trino returnsNULLwhen there is no common non-NULLelement but one side containsNULL.date_parseandparse_datetime: they returntimestamp(3)and a timestamp with time zone, notDateTime.url_extract_parameter:extractURLParameteralso reads parameters from the fragment, while Trino reads only the query string.url_extract_path,url_extract_query, andurl_extract_fragment: the ClickHouse extractors return raw substrings, while Trino decodes the components and parses URI boundaries.array_distinct:arrayDistinctdropsNULLelements, while Trino keeps one.array_minandarray_max: Trino returnsNULLfor an array with aNULLelement and for an empty array.regexp_count:countMatchesskips zero-length matches, while Trino counts them.Not included:
element_at(arrayElementOrNullreturns a default value rather thanNULLfor a missing position or key when the element type can't be insideNullable) andarray_position(already a PostgreSQL-compatible function, which returnsNULLrather than Trino's0for a missing element). As with every ClickHouse aggregate function, the aggregate aliases return the default value on empty input unlessaggregate_functions_null_for_emptyis enabled.A known limitation:
TRY_CASTto a type that can't be insideNullable, such asArray, throws, asaccurateCastOrNulldoes.Changelog category (leave one):
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), theARRAY[...]array constructor, the type namesARRAY(T)andMAP(K, V), and aliases for Trino functions such asstarts_with,slice,regexp_like,day_of_week,url_extract_host,bitwise_and,arbitrary, andbool_and.🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/124763]
Version info
26.10.1.2448-master(included in26.10and later)