Skip to content

Add the experimental Trino SQL dialect - #115383

Merged
alexey-milovidov merged 24 commits into
masterfrom
trino-dialect
Sep 10, 2026
Merged

alexey-milovidov merged 24 commits into
masterfrom
trino-dialect

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 19, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Experimental Feature

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

Added an experimental trino value of the dialect setting (gated by allow_experimental_trino_dialect): queries written in Trino SQL are translated to ClickHouse SQL, including Trino-specific syntax (ARRAY[...] literals, TRY_CAST, UNNEST, ROW constructors and types, VALUES tables, OFFSET before LIMIT, FETCH) and a mapping of several hundred Trino function names and argument conventions to their ClickHouse equivalents.

Since Trino SQL is close to ClickHouse SQL (which already parses AT TIME ZONE, FILTER (WHERE ...), IS DISTINCT FROM, DATE/TIMESTAMP literals, GROUPING SETS, NULLS FIRST/LAST, WITH RECURSIVE, ...), the dialect is not a separate grammar. It works in three stages in src/Parsers/Trino/:

  1. Token-level syntax translation (TrinoSyntaxTranslator): ARRAY[1, 2] -> [1, 2], TRY_CAST(x AS t) -> accurateCastOrNull(x, 't'), ROW(...) -> tuple(...) / Tuple(...), UNNEST in FROM -> ARRAY JOIN (LEFT JOIN UNNEST ... ON TRUE -> LEFT ARRAY JOIN, WITH ORDINALITY -> arrayEnumerate, maps -> mapKeys/mapValues), (VALUES ...) -> a subquery over SQLStandardValues, OFFSET n LIMIT m -> LIMIT m OFFSET n, FETCH FIRST n ROWS ONLY/WITH TIES -> LIMIT, TIMESTAMP(p) [WITH TIME ZONE] type -> DateTime64(p), lambdas are parenthesized (the ClickHouse parser cannot parse a lambda after a literal argument), and backslashes in string literals are escaped (in Trino a backslash is a regular character).
  2. The standard ClickHouse parser parses the result. If nothing needed translation, the original buffer is parsed directly, and INSERT statements with inline data (VALUES/FORMAT) are always delegated as-is so that the zero-copy data pointers stay valid.
  3. AST-level function mapping (TrinoFunctionMapper): ~100 renames plus ~50 structural rewriters built from a review of all ~340 functions in the Trino documentation. This includes argument reordering for every higher-order function (Trino passes lambdas last, ClickHouse first: transform(arr, f) -> arrayMap(f, arr)), parametric-aggregate conversion (approx_percentile(x, p) -> quantileTDigest(p)(x), listagg(x, sep) -> groupConcat(sep)(x)), and — most importantly — the names that resolve in ClickHouse with different semantics and would silently return wrong results if passed through: to_unixtime (an alias of parseDateTime in ClickHouse), date_diff (boundary crossings vs complete units -> age), week (non-ISO mode 0 -> toISOWeek), from_unixtime(u, x) (format string vs time zone), rand/random -> randCanonical, transform, repeat, histogram, map(karr, varr) -> mapFromArrays, format -> printf, and the varchar family (length, substr, upper, lower, strpos, lpad, ...) which is code-point-based in Trino and byte-based in ClickHouse (-> ...UTF8 variants).

The feature gate follows the polyglot pattern: SET queries are handled before the gate inside the parser, so a misconfigured profile can always be recovered with SET dialect = 'clickhouse'. ClickHouse functions whose names do not collide with Trino names remain accessible from the dialect. Unsupported constructs (TABLESAMPLE, TRY(...), comparator array_sort, ...) throw explicit NOT_IMPLEMENTED/BAD_ARGUMENTS errors instead of misbehaving, and semantics that cannot be fixed by translation at the query level (integer division /, round banker's rounding on Float, greatest/least NULL handling) are documented.

The translation is observable with EXPLAIN SYNTAX.

Note: polyglot_dialect = 'trino' already exists via the polyglot transpiler, but it performs no function mapping and passes ARRAY[...] through untranslated; this first-class dialect provides a much more complete translation.

BETWEEN SYMMETRIC is translated to BETWEEN least(a, b) AND greatest(a, b), and the Trino JSON type family is mapped to the ClickHouse JSON type, accepting that only objects are supported: JSON '...' literals and json_parse become casts to JSON, json_format becomes toJSONString, and json_extract, json_extract_scalar, json_value, json_query, json_exists, json_size, json_array_contains and is_json_scalar are translated to the ClickHouse JSON functions (the string-based JSONPath functions do not accept the JSON type, so casts flowing directly into them are unwrapped back to the JSON text; non-object documents are rejected when materialized as JSON values).

Validation: the translation was exercised against four corpora derived from Trino's own tests and documentation:

  • 732 self-contained query/expected pairs extracted from Trino's functional tests (core/trino-main/src/test/java/io/trino/sql/query/Test*.java): 206 produce identical results; of the rest, ~270 need ClickHouse engine features (LATERAL joins alone gate 139, plus correlated-subquery decorrelation shapes and non-integer window frame offsets) and the remainder are unsupported constructs or documented semantic differences. 75 order-deterministic pairs are committed as 05021_trino_conformance (following the KQL conformance-test precedent), and three more conformance tests pin the adopted corpora: 05022_trino_conformance_presto_scalar (1054 Presto scalar-function assertions), 05023_trino_conformance_tempto (119 Tempto product-test queries running against their fixture tables inlined into the test), and 05024_trino_conformance_impala (44 generic-SQL Impala expressions) — every adopted query verified to produce the documented result and to be stable under randomized time zones, thread counts and block sizes.
  • 43 convention-based Tempto product tests (testing/trino-product-tests at tag 455, .sql/.result pairs): 30 of the 34 runnable ones match (using the fixed 25-row nation/5-row region TPC-H tables).
  • 294 SELECT-with-expected-result examples from the official function documentation: 142 match.
  • The 22 TPC-H queries in Trino dialect from testing/trino-benchmark-queries: all parse and translate.
  • 1689 scalar-function assertions scraped from prestodb/presto unit tests (assertFunction("expr", TYPE, value) style) plus the 130 Tempto product tests Presto kept after the fork, executed against real TPC-H sf0.01 data and the datatype/workers fixture tables: 1059 and 91 match respectively (most of the rest use Presto-only functions that do not exist in current Trino). The 43 Trino-era Tempto tests reach 38/43 with the data available.
  • 146 expression tests from apache/impala as a generic-SQL cross-check (Impala is a different dialect; 44 match, and the divergences are Impala-specific by design — e.g. Impala's LIKE treats a backslash as an escape character while Trino treats it literally).

These corpora drove another round of semantic fixes: outer joins produce NULLs (join_use_nulls), sum/avg/min/max over an empty set return NULL (-OrNull variants), count returns a signed bigint, greatest/least propagate NULL arguments, LIKE backslash literalness, minute-precision TIMESTAMP literals, reduce output lambdas, bit_count arbitrary widths, width_bucket over an array of bounds, and json_array_get. Of the 294 examples, 142 produce results matching the documentation (plus a few that differ only by printing the current time or the session time zone); most of the rest use deliberately unsupported constructs (SQL:2016 MATCH/UNIQUE predicates, U&'...' literals, functions with no ClickHouse counterpart, non-object JSON documents per the design above).


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

alexey-milovidov and others added 2 commits August 19, 2026 00:49
SET dialect = 'trino' (gated by allow_experimental_trino_dialect) translates
Trino SQL into ClickHouse SQL in three stages: token-level syntax rewriting
(ARRAY[...] literals, TRY_CAST -> accurateCastOrNull, UNNEST -> ARRAY JOIN,
ROW -> Tuple/tuple, VALUES -> SQLStandardValues, OFFSET before LIMIT, FETCH,
lambda parenthesization, backslash-literal strings, .5-style numeric literals),
then the standard ClickHouse parser, then an AST pass that maps Trino function
names and argument conventions to ClickHouse equivalents - including names
that resolve in ClickHouse with different semantics (to_unixtime, date_diff,
week, rand, transform, repeat, histogram, map, format, and the code-point
based varchar functions).

Co-Authored-By: Claude Fable 5 <[email protected]>
Running the 294 documented examples of the Trino function docs against the
dialect surfaced these gaps, now fixed:
- `x AT LOCAL` failed: the parser desugars it into a zero-argument `timeZone()`
  call, which the `timezone` rewriter rejected (exception);
- `TIMESTAMP` literals silently dropped fractional seconds and did not accept
  region time zone names (`TIMESTAMP '2024-01-01 12:00:00 Asia/Tokyo'`);
- `DECIMAL '123.45'` typed literals did not parse;
- `current_timestamp(p)` and `localtimestamp(p)` with a precision argument;
- the standard `TRIM('x' FROM s)` and `TRIM(LEADING FROM s)` forms;
- `.06`-style numeric literals without the leading zero (used by TPC-H);
- `bitwise_not` on small literals used a narrow unsigned type instead of the
  64-bit two's complement of Trino;
- `translate` was byte-based (now `translateUTF8`).

Co-Authored-By: Claude Fable 5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [e6ad0f8]

Summary: ✅


AI Review

Summary

Adds an experimental trino SQL dialect with token-level syntax translation, AST-level function mapping, documentation, and a large conformance suite. Several earlier review issues were fixed, but the current head still misses a few semantics-critical cases, so I would not approve it yet.

Findings

❌ Blockers

  • [src/Parsers/Trino/TrinoSyntaxTranslator.cpp:467-485] and [src/Parsers/Trino/TrinoFunctionMapper.cpp:297-314] The VARBINARY overload rewrite still only fires for syntactically recognizable producers and casts. Once a binary value is read through a column or alias, the AST pass still rewrites length / substr / lpad / rpad to the UTF-8 text versions and silently changes byte-counting semantics.
    Suggested fix: carry a VARBINARY marker through aliases and columns to the AST pass, or reject these overloads whenever the translator can no longer distinguish text from binary.
  • [src/Parsers/Trino/TrinoFunctionMapper.cpp:134-138] and [src/Parsers/Trino/TrinoFunctionMapper.cpp:1050-1092] The JSON path rewrites only unwrap a direct CAST(... AS JSON). Materialized JSON values still reach JSON_VALUE / JSON_QUERY / JSON_EXISTS as a non-String first argument, and JSONExtractRaw / JSONLength on a JSON column only accept string-key navigation. Valid queries over a JSON column or alias therefore fail even though the same paths work on literals.
    Suggested fix: serialize JSON-typed inputs back to text before the path-function rewrite, or reject materialized JSON inputs explicitly until there is a correct translation.
  • [src/Parsers/Trino/TrinoSyntaxTranslator.cpp:923-945] The set-operation wrapper fix still whitelists only EXPLAIN and INSERT. Query bodies under CREATE TABLE ... AS, CREATE VIEW ... AS, and CREATE MATERIALIZED VIEW ... AS still skip the SELECT * FROM (...) wrapper, so a trailing ORDER BY / LIMIT / OFFSET / FETCH binds to the last arm instead of the whole set operation and can materialize the wrong rows.
    Suggested fix: generalize wrapper detection to find the first top-level query body after any statement preamble, not only EXPLAIN and INSERT.
  • [src/Parsers/Trino/TrinoFunctionMapper.cpp:297-315] [dismissed by author -- https://github.com/Add the experimental Trino SQL dialect #115383#discussion_r3886376314] Several advertised Trino text functions still use byte or ASCII ClickHouse implementations: lower / upper stay on ASCII-only functions, reverse is not remapped, and hamming_distance becomes byteHammingDistance. Non-ASCII input therefore returns wrong answers without an exception.
    Suggested fix: use lowerUTF8 / upperUTF8 / reverseUTF8, and either implement a code-point-aware hamming_distance rewrite or throw NOT_IMPLEMENTED.
Tests
  • ⚠️ Add a regression where a VARBINARY value is first aliased or materialized (SELECT length(v) FROM (VALUES to_utf8('𐐭𐐭')) AS t(v)) before calling length / substr.
  • ⚠️ Add a JSON-column case that exercises path functions on a materialized JSON value, not only on literals and direct casts.
  • ⚠️ Add a CREATE TABLE ... AS SELECT ... UNION ... ORDER BY / LIMIT case so the set-operation tail binding is covered outside INSERT and EXPLAIN.
  • ⚠️ Add non-ASCII cases for upper, lower, reverse, and hamming_distance; the current suite only covers ASCII or NULL there.
Final Verdict

Not ready to merge. The dialect still breaks VARBINARY overload semantics once values flow through identifiers, path functions do not work on materialized JSON values, set-operation tail clauses still mis-bind under CREATE ... AS wrappers, and several non-ASCII text functions remain byte or ASCII-only.

LLVM Coverage Report

Measured on commit e6ad0f8.

Metric Baseline Current Δ
Lines 88.90% 88.90% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.30% 81.30% +0.00%

Changed lines: Changed C/C++ lines covered: 1935/2234 (86.62%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-experimental Experimental Feature label Aug 19, 2026
alexey-milovidov and others added 8 commits August 19, 2026 01:38
- `x BETWEEN SYMMETRIC a AND b` is translated to
  `x BETWEEN least(a, b) AND greatest(a, b)` (and `BETWEEN ASYMMETRIC`,
  the explicit default, is accepted);
- Trino JSON values are mapped to the ClickHouse `JSON` type, accepting
  that only objects are supported: `JSON '...'` literals and `json_parse`
  become casts to `JSON`, `json_format` becomes `toJSONString`, and
  `json_extract`, `json_extract_scalar`, `json_value`, `json_query`,
  `json_exists`, `json_size`, `json_array_contains` and `is_json_scalar`
  are translated to the ClickHouse JSON functions. The string-based JSONPath
  functions do not accept the `JSON` type, so a cast flowing directly into
  them is unwrapped back to the JSON text; simple constant paths of
  `json_extract`/`json_size` become `JSONExtractRaw`/`JSONLength` arguments
  (returning bare elements like Trino), general paths fall back to
  `JSON_QUERY` with its SQL-standard array wrapper.

Co-Authored-By: Claude Fable 5 <[email protected]>
…ce test

Running 732 self-contained query/expected pairs extracted from Trino's own
functional tests (core/trino-main/src/test/java/io/trino/sql/query/Test*.java)
plus the convention-based Tempto product tests (tag 455) surfaced these gaps,
now fixed:
- typed literals: BIGINT '1', VARCHAR 'x', REAL '1.5', UUID '...', ... -> CAST;
- set operations default to DISTINCT in Trino (an explicit mode is emitted, so
  compound set operations no longer depend on `union_default_mode`), and a
  trailing ORDER BY/LIMIT/OFFSET/FETCH after a set operation applies to the
  whole operation (wrapped into a subquery) instead of the last SELECT;
- VALUES as a set-operation arm, and explicit ROW constructors in VALUES rows;
- CAST targets are wrapped in Nullable (all Trino types are nullable), so
  CAST(NULL AS INTEGER) works;
- aggregates with an inline ORDER BY: array_agg(x ORDER BY k [DESC]) and
  listagg(x, sep) WITHIN GROUP (ORDER BY k) are rewritten through arraySort
  over (value, key) tuples (preserving FILTER/OVER clauses); for
  order-insensitive aggregates the clause is dropped;
- GROUP BY AUTO -> GROUP BY ALL, the TABLE t query shorthand, standalone
  UNNEST without column aliases (synthesized names, so SELECT * works);
- row field expansion (expr).* -> untuple (previously the expression was
  silently lost by the parser), other .* forms fail loudly;
- window functions were silently dropped when an aggregate rewriter replaced
  the node: max(x, n) OVER now transfers the window to the inner aggregate,
  attachParameters keeps the window definition (min(x, n) OVER, listagg OVER),
  and the remaining composite rewriters reject window usage explicitly.

The new test 05021_trino_conformance pins 75 order-deterministic queries
derived from the Trino test suite (Apache License 2.0), following the KQL
conformance-test precedent.

Co-Authored-By: Claude Fable 5 <[email protected]>
Running 1689 scalar-function assertions scraped from prestodb/presto unit
tests, the 130 Tempto product tests that Presto kept after the fork (executed
against real TPC-H sf0.01 data plus the datatype/workers fixture tables), and
146 expression tests from apache/impala surfaced these gaps, now fixed:
- outer joins padded non-matched columns with type defaults instead of NULL:
  translated queries now carry `SETTINGS join_use_nulls = 1` (and
  `use_variant_as_common_type = 0` so set operations use numeric supertypes);
- `sum`/`avg`/`min`/`max` over an empty set (or an empty window frame)
  returned type defaults instead of NULL: mapped to the `-OrNull` variants;
- `count`/`count_if`/`count(DISTINCT)` return bigint in Trino: wrapped in
  `toInt64`, so a UNION of `count()` with signed integers works;
- `greatest`/`least` must return NULL when any argument is NULL;
- LIKE patterns: Trino has no default escape character, so a backslash in a
  pattern is a literal character (doubled once more at the LIKE level, unless
  an explicit ESCAPE clause is present);
- minute-precision `TIMESTAMP '2012-08-08 01:00'` literals;
- `reduce` with a non-identity output lambda (inlined by parameter
  substitution), `bit_count` with arbitrary widths (2..64),
  `width_bucket(x, bins_array)`, and `json_array_get` (negative indexes).

Co-Authored-By: Claude Fable 5 <[email protected]>
Converts the harvested external test corpora into stateless tests, following
the precedent of 05021_trino_conformance (and of the KQL conformance tests):
- 05022_trino_conformance_presto_scalar: 1054 scalar-function assertions from
  the Presto unit tests (the shared Presto/Trino function surface);
- 05023_trino_conformance_tempto: 119 queries from the convention-based
  (Tempto) product tests of Presto and Trino, executed against their fixture
  tables inlined into the test (the TPC-H `nation`/`region` tables are
  scale-independent, `datatype`/`workers` ship with the Presto tests);
- 05024_trino_conformance_impala: 44 generic-SQL expressions from the
  Apache Impala functional tests that are also valid Trino SQL.

All sources are Apache License 2.0, attributed in the test headers. Only
queries with verified matching results were adopted; unordered multi-row
queries are wrapped in ORDER BY ALL, and every query was checked to produce
identical output under different session time zones, thread counts and block
sizes (the references survive the CI randomization).

Co-Authored-By: Claude Fable 5 <[email protected]>
…t` test

The fast test builds with `-DENABLE_LIBRARIES=0`, so `base64Encode`/`base64Decode`
(simdutf), `normalizeUTF8*` (ICU), and `stem` (libstemmer) are not registered
there, which made `05019_trino_dialect` and
`05022_trino_conformance_presto_scalar` fail with `UNKNOWN_FUNCTION`.

The queries using them are moved into the new
`05028_trino_dialect_icu_base64` test tagged `no-fasttest`, so the rest of the
conformance coverage keeps running in the fast test.
@clickhouse-gh

clickhouse-gh Bot commented Aug 21, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing e6ad0f8e6 with master 1e7129b5d (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

⚠️ Significant changes: object file sizes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes ⚠️

13 object files changed (+780.66 KiB total), 3 added.

Object file Master PR Δ
src/Parsers/CMakeFiles/clickhouse_parsers.dir/Trino/TrinoFunctionMapper.cpp.o new 489.09 KiB +489.09 KiB
src/Parsers/CMakeFiles/clickhouse_parsers.dir/Trino/TrinoSyntaxTranslator.cpp.o new 208.55 KiB +208.55 KiB
src/Parsers/CMakeFiles/clickhouse_parsers.dir/Trino/ParserTrinoQuery.cpp.o new 76.17 KiB +76.17 KiB

716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

1895 translation units recompiled, 11342 s compile time in total, 1892 of them have a recent master baseline.

Job report

@mintlify

mintlify Bot commented Aug 22, 2026 •

Copy link
Copy Markdown
Contributor

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

Project Status Preview Updated (UTC)
ClickHouse-docs 🟢 Ready View Preview Aug 22, 2026, 4:58 PM

…oined `UNNEST` and the NULL-preserving aggregates

- The settings that align the semantics with Trino (`join_use_nulls`,
  `use_variant_as_common_type`) were injected into the query text and were
  therefore skipped for a query that already had a `SETTINGS` clause and for
  wrappers such as `INSERT ... SELECT` or `EXPLAIN SELECT`. They are now applied
  to the query context, together with `enable_analyzer` - the column alias lists
  (`AS t (x, y)`) and the type resolution that the translation relies on do not
  work without the analyzer.
- `LEFT JOIN UNNEST(...) ON TRUE` filled empty inputs with the default value of
  the element type instead of `NULL`; the elements are now made `Nullable`.
- A joined `UNNEST` of several arrays required them to be aligned; it now zips
  them with `arrayZipUnaligned`, as the standalone form already did, so uneven
  inputs are padded with `NULL`.
- The table alias of a joined `UNNEST` (`AS t (x)`) was parsed but dropped, so
  `t.x` did not resolve after the translation; the qualified references are now
  rewritten to the emitted `ARRAY JOIN` aliases.
- `array_agg` and `array_agg(DISTINCT ...)` resolved to the ClickHouse
  `groupArray`, which drops `NULL` elements; they are rewritten through a tuple
  so that the elements are kept.
- The `OrNull` rewrite of `sum`/`avg`/`min`/`max` now also applies through the
  `Distinct` combinator, so `sum(DISTINCT x)` over an empty set returns `NULL`.

The new test `05045_trino_dialect_semantics` covers all of the above.

CI fixes in the same change:
- `05022_trino_conformance_presto_scalar` exceeded the 180 second test limit in
  the debug and sanitizer builds; it is split into three tests.
- The 29-level nested union adopted from the Impala `union.test` exhausted the
  stack (`TOO_DEEP_RECURSION`) in the debug and TSan builds; the nesting is
  reduced.
- The failures under the old analyzer are fixed by requiring the analyzer.
Comment thread src/Parsers/Trino/ParserTrinoQuery.cpp Resolved
{"ends_with", "endsWith"},
{"format", "printf"},
{"hamming_distance", "byteHammingDistance"},
{"length", "lengthUTF8"},

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This rewrite happens before type analysis, so it loses the VARCHAR vs VARBINARY overload distinction. length(to_utf8('𐐭')) is a valid Trino VARBINARY call that must return 4, but to_utf8 is translated to the identity and this line turns it into lengthUTF8('𐐭'), which returns 1. The same problem applies to the other unconditional UTF-8 rewrites in this block (substr, position, and friends).

These mappings need to be type-aware, or the binary overloads need separate handling instead of always routing through the UTF-8 string functions.

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.

🕵 Fixed in b2c2c01: when the first argument is a syntactically recognizable VARBINARY expression (a call to a binary-producing function such as to_utf8, a CAST to VARBINARY, or a byte-preserving function over such an expression), length/substr/substring/lpad/rpad are translated to the byte-based ClickHouse functions (OCTET_LENGTH, byteSlice, leftPad, rightPad) instead of the UTF8 variants. length(to_utf8('𐐭')) now returns 4. Covered in 05046_trino_dialect_review_regressions.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is only partially fixed. The new token-level branch in src/Parsers/Trino/TrinoSyntaxTranslator.cpp:467-485 picks the byte-based function only when the first argument is a syntactically recognizable VARBINARY producer or cast. As soon as the binary value is stored behind an identifier or a column, the fallback rename in src/Parsers/Trino/TrinoFunctionMapper.cpp:301-311 is still unconditional.

Concrete trace: SELECT length(v) FROM (VALUES to_utf8('𐐭𐐭')) AS t(v). Here v is a valid Trino VARBINARY value, but isBinaryExpressionAt returns false for the identifier, so the AST pass still rewrites length(v) to lengthUTF8(v) and counts code points instead of bytes. The same gap remains for substr / lpad / rpad once the VARBINARY value comes from a column or alias.

So the original overload-distinction bug is still present unless VARBINARY-ness survives identifiers and columns, or these overloads are rejected once the translator can no longer distinguish text from binary.

A top-level bareword `VALUES` or `FORMAT` after `INSERT` delegated the whole
statement to the standard parser, so valid `INSERT ... SELECT` queries with the
`format` function or a column named `values` in the select list skipped the
Trino translation. Now the inline-data tail is recognized only before any
top-level `SELECT`/`WITH`, and `FORMAT` must be followed by a bare format name.
…e-based functions

`length`, `substr`, `substring`, `lpad` and `rpad` were unconditionally mapped
to the UTF8 (code point) variants, which broke the VARBINARY overloads:
`length(to_utf8('𐐭'))` must return 4 bytes, not 1 code point. When the first
argument is a syntactically recognizable VARBINARY expression (a call to a
binary-producing function such as `to_utf8`, a `CAST` to `VARBINARY`, or a
byte-preserving function over such an expression), the byte-based ClickHouse
function (`OCTET_LENGTH`, `byteSlice`, `leftPad`, `rightPad`) is emitted instead.

Also bind the column aliases of a joined UNNEST to the query scope that
introduced them: the second-pass `t.x` -> `x` rewrite was global over the whole
statement, so it also rewrote qualified references inside nested subqueries and
CTEs that reuse the same table alias, turning them into ambiguous unqualified
ones. The scope is the innermost enclosing subquery parenthesis.
…ack in the Trino dialect

`JSON_QUERY` wraps scalar matches in an array (the SQL standard ARRAY WRAPPER),
so the implicit fallback silently changed valid Trino `json_extract` results:
`json_extract('{"hello": 2}', '$["hello"]')` returned `[2]` instead of `2`.
The simple-path parser now also understands bracket-quoted member keys
(`$["key"]`, $['key']`), and everything it cannot parse is rejected with a
clear `NOT_IMPLEMENTED` error suggesting `json_query` explicitly.
Covers the inline-data tail of `INSERT ... SELECT`, the VARBINARY overloads of
`length`/`substr`/`lpad`/`rpad`, `json_extract` with bracket-quoted paths and
the rejection of unsupported ones, and the scoping of qualified references to
joined `UNNEST` aliases.
Master reworked the KQL dialect and moved its scaffolding, so every hunk here was
"this branch's Trino line next to a Kusto line master has removed":

- `src/Parsers/CMakeLists.txt`: kept the `./Trino` sources line, dropped the
  `./Kusto/KustoFunctions` line master removed.
- includes in `ClientBase.cpp`, `LocalConnection.cpp`, `executeQuery.cpp`: kept only
  the Trino header. Master relocated the Kusto headers and already includes PRQL,
  so re-adding this branch's copies would have duplicated includes, which
  clang-tidy fails on.
- `LocalConnection.cpp` parser selection: took master's `state->`-based promql line
  and rewrote the Trino branch in the same style
  (`state->max_query_size`/`max_parser_depth`/`max_parser_backtracks`), keeping
  `settings[Setting::allow_experimental_trino_dialect]` for the gate.
- `programs/client/FuzzLoop.cpp`: master replaced the per-dialect fuzzing skip with
  a generic "do not let a corpus query change the session dialect" guard and now
  accepts fuzzing under a translated dialect such as `kusto`. Trino follows that
  same treatment, so this branch's separate skip is dropped rather than re-added.

The Trino dispatch in `ClientBase.cpp`, `LocalConnection.cpp` and
`executeQuery.cpp` is intact, and all three translation units were compiled after
the resolution.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…oping, NULLS placement

- `all_match` / `any_match` / `none_match` are three-valued in Trino, while `arrayAll` and
  `arrayExists` coerce a `NULL` predicate result to `false`. The predicate is now evaluated into an
  array of codes (0 - false, 1 - true, 2 - NULL) and the answer is assembled with `multiIf`, so
  `any_match(ARRAY[NULL], x -> x)` returns `NULL` instead of `false`.
- `zip_with` zips to the longer input and pads the shorter side with `NULL` in Trino, so it is
  rewritten through `arrayZipUnaligned` and tuple destructuring instead of a plain `arrayMap`,
  which requires arrays of equal size.
- the inlining of the output lambda of `reduce` no longer descends into a nested lambda that
  shadows the substituted parameter, and never rewrites a lambda parameter tuple.
- explicit `NULLS FIRST` / `NULLS LAST` of an ordered aggregate was parsed and dropped. Both
  `arraySort` and `arrayReverseSort` place `NULL`s last, while Trino places them last for `ASC` and
  first for `DESC`, so a NULLs-first ordering (requested or default for `DESC`) is now expressed
  with a leading null group in the synthetic sort key.
- `clickhouse-local` snapshots `allow_experimental_trino_dialect` together with the dialect, so a
  query that turns the gate off in its own `SETTINGS` clause is not rejected when the `input()`
  initializer reparses it.

Tests: the requested `EXPLAIN` wrapper case and the negative `LEFT JOIN UNNEST` case for an element
type that cannot be `Nullable` in `05045`, and the `$['key']` `json_extract` spelling together with
the regressions above in `05046`.
Comment thread src/Parsers/Trino/ParserTrinoQuery.cpp Resolved
Comment thread src/Parsers/Trino/ParserTrinoQuery.h Resolved
@clickhouse-gh clickhouse-gh Bot added the comp-sql-syntax SQL/grammar parsing, AST nodes, syntax-level features. label Sep 4, 2026
alexey-milovidov and others added 2 commits September 9, 2026 12:11
…rappers

Three findings from the review of the Trino dialect:

- The `ParserSetQuery` shortcut in front of the feature gate swallowed
  `SET ROLE ...` (read as an assignment to a setting named `ROLE`) and the
  Trino `SET SESSION name = value` form (read as an assignment to `SESSION`).
  `ParserSetRoleQuery` is now tried first, the same way `ParserQuery` does it,
  and `SET SESSION` is excluded from the shortcut so that the translator
  rewrites it into a plain `SET`.

- `ParserTrinoQuery` did not carry the parser-affecting settings
  `allow_settings_after_format_in_insert` and `implicit_select` over to the
  `ParserQuery` instances it delegates to, so the accepted syntax changed as
  soon as `dialect = 'trino'`. Both are threaded through from `executeQuery`,
  `ClientBase` and `LocalConnection`.

- The detection of a trailing `ORDER BY` / `LIMIT` / `OFFSET` / `FETCH` after a
  set operation - which must be bound to the whole set operation, not to its
  last arm - only recognized a statement that already starts with `SELECT`,
  `VALUES`, `WITH` or `(`. It now follows the query body inside the `EXPLAIN`
  and `INSERT INTO t ...` wrappers and accepts the `TABLE t` shorthand, which
  is rewritten into a `SELECT` only later.

Test: `05153_trino_dialect_wrappers_and_set`.

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

void unwrapJSONArgument(ASTs & arguments)
{
if (!arguments.empty())

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This only unwraps a direct CAST(... AS JSON). Once a Trino JSON value has been materialized behind an identifier or a column, the mapped path functions still receive a JSON-typed first argument.

That breaks the advertised JSON type family in two ways: JSON_VALUE / JSON_QUERY / JSON_EXISTS reject non-String first arguments outright (src/Functions/FunctionSQLJSON.h:147-152), and JSONExtractRaw / JSONLength switch to the object-column fast path that accepts only constant string keys, not numeric path steps (src/Functions/FunctionsJSON.cpp:115-117,221-242). A query like SELECT json_extract(j, '$.a[0]') FROM t on t(j JSON) therefore fails even though the same path works on a literal.

The translator needs to serialize materialized JSON values back to text before calling these functions, or reject those shapes explicitly instead of only handling direct casts.

/// Statement wrappers whose query body is a set operation of its own:
/// the trailing clauses still belong to the whole set operation there.
size_t begin = 0;
if (tokenIsKeyword(tokens[0], "EXPLAIN") || tokenIsKeyword(tokens[0], "INSERT"))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This wrapper list is still incomplete for the invariant you are preserving here. Trino query bodies can also appear under CREATE ... AS <query> / CREATE VIEW ... AS <query> / CREATE MATERIALIZED VIEW ... AS <query>, but those statements still enter here with begin = 0 and fall through at line 956 because they do not start with SELECT / WITH / VALUES / (.

So CREATE TABLE dst ENGINE = Memory AS SELECT 30 UNION ALL SELECT 10 ORDER BY 1 LIMIT 1 keeps ClickHouse's "tail binds to the last arm" behavior and materializes the wrong rows. The detection needs a generic "find the top-level query body after statement wrappers" path, not a whitelist of EXPLAIN and INSERT.

@clickgapai

Copy link
Copy Markdown
Contributor

@alexey-milovidov — ClickGap found the following in this PR:

Close anything that's wrong or already addressed.

@fm4v

fm4v commented Sep 14, 2026

Copy link
Copy Markdown
Member

@groeneai look why tests that check setting naming convention havent failed on: allow_experimental_trino_dialect . create a PR that renames the setting to enable_trino_dialect

@groeneai

Copy link
Copy Markdown
Collaborator

Acknowledged. I'm checking which setting-name check should have rejected allow_experimental_trino_dialect and why it stayed green, and I'll follow up here with a PR renaming the setting to enable_trino_dialect (or with my findings, if the rename needs a different shape).

@groeneai

Copy link
Copy Markdown
Collaborator

@fm4v No test checks the shape of a setting name, so nothing could have failed. The one
prefix-sensitive check in the tree, ci/jobs/scripts/check_style/check_cpp.sh:374-376, is a
registration check, not a naming check: it asks only whether every allow_* token in
Settings.cpp also appears in enableAllExperimentalSettings.cpp or in
experimental_settings_ignore.txt. It did fire when the dialect landed, and it was answered on
2026-08-19 by 0f8a47380ad509 ("Fix Trino dialect CI failures") adding the name to
enableAllExperimentalSettings.cpp, where, unlike the kusto, prql and polyglot gates, it
does not belong. Even answered the other way it would never have objected to the name itself. The
sharpest illustration: enable_json_ast_dialect (Settings.cpp:9124) and
allow_experimental_trino_dialect (:9143) sit 19 lines apart, both EXPERIMENTAL-tier dialect
gates, opposite conventions, and nothing in CI compares them. This covers the public tree only; I
cannot see a cloud or private-repo check.

The rename is #120007. Plain rename following your #113480, with no alias: no released version
carries the old name (checked 26.8, 26.7 and 26.6), and the history record is in the
unreleased 26.9 block. I deleted the enableAllExperimentalSettings entry rather than renaming
it, for the reason you gave in #113480. Anyone already setting the old name on master or nightly
will get UNKNOWN_SETTING; I can add an alias instead if you prefer.

The PR does not add a naming check. 24 canonical allow_experimental_* names remain after it, so
a check needs a grandfather list. Do you want one, and should those 24 be renamed or
grandfathered? I will open it if you want one.

pull Bot pushed a commit to sonvt1710/ClickHouse that referenced this pull request Sep 15, 2026
Requested by @fm4v on ClickHouse#115383, which added the setting.

The `allow_experimental_` prefix is the pre-tier way of gating a feature. The `EXPERIMENTAL`
tier in the declaration already carries that information and is exposed as `tier` in
`system.settings`, so the prefix duplicates it in the one place that is expensive to change
later, the name. This follows ClickHouse#113480, which renamed the sibling dialect gate
`allow_experimental_json_ast_dialect` to `enable_json_ast_dialect`.

Plain rename with no alias, because no released version carries the old name:
`src/Core/Settings.cpp` on the 26.8, 26.7 and 26.6 branches contains it 0 times, the newest
stable tag is v26.8.3.105-lts, and its history record is in the unreleased 26.9 block. The
record is therefore renamed in place rather than a second one being added: an in-place rename
keeps the value signature and reason text identical, which is what makes
`parse_settings_history_changes` recognize it as a rename and report it under the new name
only, and what keeps `03999_stateless_settings_history` from seeing a record naming a setting
that no longer exists. Users on master or nightly who already set the old name will get
UNKNOWN_SETTING.

The `enableAllExperimentalSettings` entry is deleted rather than renamed. That helper enables
experimental features that can be used in a CREATE query, so that
`DatabaseReplicated::recoverLostReplica` can re-create tables from stored metadata; `dialect`
is a session setting governing how query text is parsed and cannot appear in a CREATE query,
which is why the kusto, prql and polyglot gates are entries in
`experimental_settings_ignore.txt` instead. Trino was the only one registered in the helper,
added by 0f8a473 ("Fix Trino dialect CI failures") to satisfy the `allow_*`
registration check in check_cpp.sh rather than to fix a recovery failure. No ignore-list entry
replaces it: that check compares `allow_*` tokens only, and the renamed setting no longer has
such a token, so an entry would be unused and would fail the same check.

The autogenerated settings documentation is left to the nightly docs job, which regenerates it
from `src/Core/Settings.cpp`.

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

This branch was successfully deployed

1 active deployment
staging - docs — e6ad0f8e Deployed Sep 9, 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-experimental Experimental Feature 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