:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(hogql): expand trino query compatibility (#98040)
Eric Duongf06d709f740a
diff --git a/docs/internal/hogql-trino-compiler.md b/docs/internal/hogql-trino-compiler.mdindex 093d0a9ba199..bb563805f649 100644--- a/docs/internal/hogql-trino-compiler.md+++ b/docs/internal/hogql-trino-compiler.md@@ -8,7 +8,7 @@ Call `prepare_and_print_ast(node, context, "trino")` explicitly for standalone cThe returned SQL uses named placeholders, with values stored in `context.values`. The direct Trino adapter converts them into positional placeholders and submits the ordered values to the Trino client.-The final Trino transpiler accepts a prepared AST plus frozen snapshots of bindings, table locators, modifiers, limits, timezone, and week start. It clones the AST and creates a fresh print context without a team, user, or schema database before final lowering, validation, and printing.+The final Trino transpiler accepts a prepared AST plus frozen snapshots of bindings, table locators, modifiers, limits, timezone, and week start. The prepared AST retains resolved table metadata for expanded saved queries. The transpiler clones the AST and creates a fresh print context without a team, user, or schema database before final lowering, validation, and printing.`transpile_hogql_to_trino(...)` is the restricted, manifest-backed front end. Its immutable manifest allowlists logical tables, physical Trino locators, and warehouse column types. `events` and `persons` use fixed built-in schemas. The function resolves and prints with no team, user, Django model, saved query, or lazy database callback, and its tests assert that it executes zero Django queries.@@ -24,6 +24,39 @@ second = catalog.transpile("SELECT count() FROM events")Pure transpilation accepts caller-supplied constant values. It rejects unresolved placeholders, action and cohort references, tables absent from the manifest, non-leaf warehouse column types, and invalid or incomplete manifest entries. Callers needing Django-backed semantics must select the explicit expansion mode described below.+## Curated warehouse fields in manifests++Physical imports can expose different names and types from the HogQL schema. Supply+`TrinoManifestTable.field_overrides` to retain logical aliases and computed fields in+addition to the physical `columns`. The catalog copies these definitions when it is+prepared; subsequent changes to the caller's definitions do not mutate that catalog.+Core `events` and `persons` manifests still use their fixed schemas and reject overrides.++For example, a logical `customer_id` can be a `StringDatabaseField(name="customer")`,+while `created_at` can be an `ExpressionField` over a raw epoch column. Set+`isolate_scope=True` on computed fields that reference columns of their own table.+Warehouse callers can obtain curated definitions from `resolve_external_table_fields`+using the source resource name and the columns actually present in the import.+Supplying raw column metadata alone omits these semantic mappings.++When a logical field maps to a different physical column, Trino keeps the source qualifier after rewriting the field.+This lets a query join tables that share the physical column name while selecting the intended logical field.+`JOIN ... USING` becomes an `ON` condition with both sources qualified, including joins between CTEs and subqueries.++Trino lowering supports keyed `JSONExtractArrayRaw` as an array of serialized JSON+values, numeric epoch arguments to `toDateTime`, array literal membership, and shared+CTEs across UNION branches. Day-time intervals use native interval arithmetic.+`JSONExtractRaw` also accepts dynamic string keys with JSON-escaped path construction.+Nested array indexes preserve JSON values between path steps, including after an object key.+Numeric JSON path components use Trino `element_at` so one-based and negative indexes+retain ClickHouse array semantics.++An executable SELECT is not sufficient to establish materialization compatibility:+connectors may reject anonymous nested row fields or untyped NULL output columns.+Callers must validate the intended CREATE TABLE AS operation and its output contract.+A successful build does not establish cross-engine result parity, particularly when+inputs are bounded or the caller applies explicit experimental rewrites.+## Query Editor connection integrationThe connection integration advertises `TrinoAdapter.dialect = "trino"`. Selecting a Trino connection for a HogQL query calls the same pure transpiler as managed compilation, handing it the connection-scoped database directly. It does not enable Django semantic expansion. Catalog introspection through `system.information_schema` keeps running on the ClickHouse path. Editor validation prints with the same dialect and rejects the same unsupported features, so a query that validates also compiles.@@ -54,6 +87,24 @@ For ordinary `GROUP BY`, an expression that matches a selected expression uses tA top-level `ORDER BY` reference to a selected alias also uses that output's ordinal. This avoids repeating bound parameters from the selected expression and keeps grouped queries valid. Ordering direction and explicit source ordinals remain unchanged; aliases inside larger sort expressions still expand normally.+Scalar `WITH` and SELECT alias expansion share a budget of 10,000 visited or copied expression nodes per normalization pass.+Queries that exceed it fail with `TRINO_AST_EXPANSION_LIMIT`; simplify the expressions or use subqueries.+The printer checks each rendered expression against a 1,000,000-character SQL limit and raises `TRINO_SQL_SIZE_LIMIT` before enclosing expressions can repeatedly expand it.+`arraySlice` and dynamic `range` bind their arguments once so nesting does not multiply their generated SQL.+Scalar CTE substitution preserves resolved column bindings, including columns that share a CTE name.++`numbers()` uses Trino's scalar `sequence`, which supports at most 10,000 entries.+Constant counts above this limit fail during compilation; dynamic counts are clamped to the range from zero to 10,000.++`convertCurrency` requires an explicit `exchange_rate` table locator or manifest entry supplied by the caller.+Managed warehouse compilation does not assume that this table exists.+The rewrite emits three correlated scalar lookups per row, including a repeated source-rate lookup, and can be expensive on large inputs.+A future relational rewrite must preserve zero-rate and NULL behavior; wrapping these correlated lookups in a lambda fails in Trino.++`PIVOT` accepts explicit field grouping keys.+`LIMIT PERCENT` resolves ordinal sort keys to projected fields before ranking rows.+`RIGHT ANY`, `RIGHT SEMI`, and `RIGHT ANTI` support two-table queries; longer join chains return `TRINO_RIGHT_JOIN_CHAIN_UNSUPPORTED`.+## Why some shared integration is necessaryThe backend owns its function mappings, structural rewrites, validation, and table rendering. These shared extension points let it reuse the existing compiler without duplicating its semantic pipeline:@@ -120,6 +171,330 @@ The data modeling shadow path uses these results as an eligibility gate. It requ## Validation+The Trino printer supports `countDistinctIf`, `replaceOne`, `toFloat64OrNull`,+`arrayCount` with a predicate lambda, `countEqual`, `arraySlice`, `arraySort` with+a single-array key lambda, `arrayLastIndex` with a predicate lambda, and+`multiSearchAnyCaseInsensitive`. `arrayLastIndex` returns the last matching+one-based position, or zero when no element matches. Simple `CASE`+expressions and numeric conditions in `if`/`multiIf` use native Trino conditionals.+Aliases inside expressions are omitted from SQL; projection aliases are retained.+String inputs to `toInt` use `TRY_CAST`, returning NULL for strings that do not+represent an integer. Numeric aggregate-filter conditions are cast to BOOLEAN.++Additional mappings cover common mathematical functions, array transforms,+base64 strings, maps, URLs, date arithmetic, vector operations, and statistical+aggregates. The printer removes ClickHouse `GLOBAL` distribution modifiers from+joins and membership tests. Trino plans data distribution for these operations.++`test_tracks_every_registered_function_without_a_trino_mapping` snapshots every+registered function that has no Trino mapping. The snapshot separates scalar,+aggregate, and PostHog functions. A new registry function must receive a mapping+or appear in this explicit gap inventory.++The registry has 1,180 names. Trino mode maps 850 of these names. The explicit+gap inventory has 330 names: 149 scalar functions, 155 aggregate functions, and+26 PostHog functions. Aliases count as separate names.++A live differential QA pass used one typed fixture for each mapped name. ClickHouse+and Trino returned equal results for 836 names. Seven time-dependent, random, or+unordered results were not directly comparable. `toTypeName`, `bitNot`, and+`cityHash64` now return explicit errors because the prior rewrites changed results.+Trino-only checks cover `percentile_cont` and `percentile_disc`, because ClickHouse+rejects this syntax. `aggregate_funnel_trends` remains unsupported until its Trino behavior can be verified against the ClickHouse UDF.+ClickHouse also rejects the registered+`toIntervalQuarter` function because that function does not exist in ClickHouse.++Some workarounds need additional rules. `arrayResize` supports an explicit fill+value. Its two-argument form uses the resolved array item type to supply the default value.+Unknown item types keep an explicit error. `generateSeries` stays unsupported because it is+a table function, while a scalar `sequence` result would change the row shape.+Array index functions apply their predicate with `transform` because Trino does+not have `find_first_index` or `find_last_index`. Bit shifts use Trino's two-+argument signatures, and signed right shifts use the arithmetic variant.++`JSONExtractKeysAndValues` converts values individually and excludes entries that+cannot be converted, so a mixed JSON object does not fail a numeric extraction.+Typed `JSONExtract` maps convert individual scalar values too, but retain keys+and use the requested type's default for values that cannot be converted.+`splitByChar`/`splitByString` support an optional maximum substring count with the+ClickHouse default behavior of excluding the remaining suffix.++`parseDateTimeBestEffort` supports ISO timestamps with explicit offsets, ordinary+date/timestamp strings, day-abbreviated-month-two-digit-year strings, and 9–10 digit Unix-second strings. An optional timezone+controls interpretation of unzoned strings and the returned wall-clock timestamp.+Other ClickHouse best-effort formats remain unsupported at execution; invalid+strings raise an error rather than becoming NULL. `toStartOfInterval` supports+positive constant intervals from seconds through years. It also supports a custom+origin. Hour intervals without an origin reset at the start of each day.++Two-argument `floor`/`ceil` scale by a power of ten before rounding, using Trino+floating-point arithmetic. `roundBankers` supports constant precision from -18 to+18, using decimal rounding increments and ties-to-even correction. Its input is+evaluated once, outside the correction lambda, so aggregate arguments remain valid.+`intDiv` supports integer operands through BIGINT division without floating-point+conversion. Non-integer operands remain rejected. `median` uses `approx_percentile`+at 0.5, following the existing approximate `quantile` translation; the algorithms+do not guarantee identical estimates between engines.++URL query, fragment, path, and parameter functions preserve percent-encoded text.+`extractURLParameter` returns the first matching parameter, or an empty string when absent.+The URL parameter array functions keep duplicates and parameters without values.+`arrayZip` supports two to five arrays.+Dynamic arrays receive an equal-length guard instead of Trino's NULL padding.+The regex group functions support constant patterns with 1–20 capture groups.+They support one-match, vertical, and horizontal result shapes.+`regexpExtract` supports a constant pattern and an optional constant group index.+`replaceRegexpOne` supports constant+patterns and replacements, including numbered replacement captures. Lookarounds,+inline flags, and pattern backreferences remain rejected for first-only replacement.+These regex translations use Trino's regex engine, so engine-specific regex syntax+is not universally portable.++Extended decimal arithmetic (`multiplyDecimal`/`divideDecimal`), additional hash+algorithms, full public-suffix domain rules, and frame-sensitive window functions+still require their own compatible implementations; these mappings do not remove the+existing rejection guards.++Additional build-oriented mappings cover UTF-8 string aliases, URL encoding,+array enumeration and predicates, supported hashes and domain extraction, UUID+conversion, dynamic JSON paths, and scalar tuple membership. Numeric+and UUID values are aligned with string branches in subqueries and set operations.+Date/time inputs to `toFloat` and `_toUInt64` use Unix epoch conversion rather than+casts that Trino rejects.+String rewrites also cover byte-based `locate`, Unicode tokens, subsequences,+ASCII case folding, form URL encoding, regex quoting, and `initcap`.+The IPv4 rewrites cover validation, integer conversion, text conversion, CIDR membership, and CIDR ranges.+IPv6 support currently covers validation and CIDR membership.+Constant `defaultValueOfTypeName` calls support primitive, nullable, array, and string-keyed map types.+The date rewrites now include `dateName`, slots, time extraction, integer Unix timestamps, and interval arithmetic.+Token predicates use ClickHouse's ASCII token boundaries and ASCII-only case folding.+`netloc` preserves user information, ports, and scheme-free authority strings.+URL hierarchy functions preserve path, query, and fragment boundaries for absolute URLs.+`cutURLParameter` removes the first matching key/value parameter and keeps URL delimiters.+XML component functions support named entities and decimal or hexadecimal numeric entities.+`JSONType` supports up to five constant or dynamic path items and returns ClickHouse type names.+The readable size and quantity functions preserve source units, rounding, NaN, and infinity output.+`roundToExp2` uses exact bit shifts for integers and signed powers for floats.+`gcd` and `lcm` use a bounded Euclidean reduction and preserve zero-input errors.+`date_bin` supports positive constant intervals from seconds through years with a custom origin.+It rejects a timestamp before its origin, as the ClickHouse expansion does.+`arrayAUC` uses a sorted linear scan with exact tie handling and nonzero positive labels.+`UUIDv7ToDateTime` reads the 48-bit Unix millisecond prefix.+The timestamp constructors truncate fractional seconds and preserve named timezone instants.+`tupleToNameValuePairs` uses resolved tuple field names and evaluates its tuple once.+`pointInEllipses` supports one or more inclusive ellipses.+`ifNotFinite` now has its correct two-argument registry contract.+`sortablesemver` returns three numeric parts or a nullable invalid sentinel.+`ngrams` uses Unicode character positions. Token-array predicates require at least one valid token.+Map-form `mapPopulateSeries` supports a source map and optional maximum key.+IPv4 substring extraction preserves the source handling of invalid leading octets.+The four `maxIntersections` forms use a half-open endpoint sweep.+They return the first position that reaches the maximum and support window clauses.++Select aliases used by generated `UNNEST` table arguments are expanded before the+query is re-resolved. Dynamic `mapFromArrays` inputs retain their original keys and+fail when Trino cannot represent duplicate or null keys.+The n-gram rewrites use byte four-grams or Unicode three-grams. Search divides+the multiset intersection by the second argument's gram count. ASCII-insensitive+forms use ASCII case folding. Unicode case-insensitive forms remain unsupported.+`cityHash64` remains unsupported because Trino does not provide its exact algorithm.++`accurateCast` and `accurateCastOrNull` reject fractional integer conversions and+unsigned overflow. `base58Encode` uses an arbitrary-length digit array, so it does+not lose large inputs. `format` supports constant templates with empty placeholders,+escaped braces, and values that have the same text form in both engines. HogQL's+`to_char` alias uses the existing `formatDateTime` handler. `bar` preserves the+one-eighth horizontal block output.++The week rewrites support all ten ClickHouse week modes. `toStartOfWeek` supports+the related Sunday and Monday starts. `toStartOfISOYear` computes the Monday that+starts the ISO year. `timeZoneOffset` uses the timestamp's stored zone offset.++The remaining function gaps fall into these groups:++- ClickHouse aggregate states, remaining combinators, bitmap aggregates, and specialized+ estimators have no portable Trino state format.+- H3, bitmap, remaining IP, and block-level functions need connector functions or target+ types that the compiler manifest does not guarantee.+- Remaining tuple, map, and array functions that depend on a dynamic return type need+ type-aware AST lowering. A string-only function handler cannot preserve them.+- Table functions, including `generateSeries`, need relational lowering. A+ scalar array workaround would change the number of result rows.+- PostHog display functions produce HogQLX output instead of relational values.+ Other PostHog functions must expand before the detached Trino compiler runs.+- Exact hashes, quantiles, regex engines, and public-suffix functions stay blocked+ when a similar Trino function has different results.++### Aggregate and typed function rewrites++`avg`, `sum`, `min`, `max`, `count`, `countDistinct`, and `median` support the registered `OrDefault`, `OrNull`, `Array`, `ForEach`, `Map`, `ArgMin`, and `ArgMax` combinations, including `If` suffixes.+Standard `FILTER` predicates combine with `If` predicates.+The compiler distinguishes an empty group from a group that contains an empty array.+Nullable values keep their null defaults. `avgArray` keeps HogQL's `avgArrayOrNull` mapping.+For window calls, HogQL prints the native `avgArray` name. Its empty non-null input result is NaN, not NULL.+Array aggregates collect values within each group before reduction. Large groups can require substantial memory.+Numeric array reductions require integer or float items. State and merge combinators remain separate gaps.+These aggregate forms also support window clauses. Additional aggregate modifiers retain explicit errors.++`ArgMin` and `ArgMax` aggregate every value tied at the extreme selection key.+Null values and null keys do not select the extreme key. The one-argument `count` form counts keys alone.+Selection keys can be integers, floats, strings, dates, timestamps, or booleans.+NaN selection keys and NaN values for `min` and `max` retain runtime errors.+UUID and container selection keys remain blocked because their ordering needs additional checks.++`medianExact`, `medianExactLow`, and `medianExactHigh` support plain and `If` forms, including window clauses.+Exact quantiles and medians exclude null and NaN input values.+These rewrites collect and sort every value in each group with `array_agg`, so memory use grows with group size and can exceed Trino's query memory limit.+Use `quantile` or `quantiles` when approximate results are acceptable, or reduce the input before using exact aggregates.+Empty integer and date inputs use their type defaults. Empty float inputs return NaN.+Nullable inputs return NULL when no non-null value passes the filter. An input with only NaN values returns NaN.+Low medians select the lower middle value. Exact and high medians select the upper middle value.++The `median` combinator family uses exact interpolation between the two middle values.+It supports aggregate and window forms. It also excludes null and NaN values.+Empty Map and ForEach results remain non-null containers, including `OrNull` forms.+ClickHouse uses a reservoir estimator for large inputs, so large-group estimates can differ.++`medianExactWeighted` and `medianExactWeightedIf` support aggregate and window forms.+They accept numeric or date values with non-negative integer weights.+They exclude null values and NaN values. A negative weight raises an error.++`quantiles` and `quantilesIf` accept one or more constant percentiles from zero through one.+They return a Trino `approx_percentile` array and exclude null and NaN values.+An empty result contains one NaN for each requested percentile.+The two engines can produce different approximate estimates.++`avgWeighted` and `avgWeightedIf` support aggregate and window forms.+They exclude a row when its value or weight is null. Empty nullable inputs return NULL; other empty inputs return NaN.+Float weights support negative values and weights. A zero weight sum can produce infinity or NaN.+Integer weights require non-negative finite values and non-negative weights. Fractional values truncate before multiplication, as in ClickHouse.+Integer sums and products must fit a signed 64-bit integer. Overflow fails instead of applying an uncertain unsigned wrap rule.++`skewPop`, `skewSamp`, `kurtPop`, and `kurtSamp` use ClickHouse's raw-moment formulas.+`simpleLinearRegression` uses the same five accumulated values as ClickHouse.+These functions support `If`, aggregate filters, null values, empty groups, and window frames.++`groupUniqArrayArray` flattens arrays, removes null values, and keeps distinct values.+Its optional positive limit and its `If` form also work in window frames.+`groupArrayInsertAt` creates typed defaults for missing positions and removes null inputs.+Positions above Trino's array limit retain an explicit error.++`groupArrayMovingSum`, `groupArrayMovingAvg`, and `deltaSum` retain input-order semantics.+Their `If` forms and window forms are supported.+Plain aggregate calls can differ when the two engines process unordered rows differently.+Use a window with an `ORDER BY` clause when the result requires a stable order.++`ForEach` aggregates each array position across the group. Shorter arrays do not supply a value for a missing position.+`Map` aggregates each key across the group and sorts the output keys.+These two families return empty containers for empty groups, including `OrNull` forms.+Map inputs must already have a Trino-compatible map type. Legacy map forms with separate key/value arrays remain blocked.+`arrayReduce` supports constant `count`, `sum`, `min`, `max`, and `avg` names, and their `Map` variants.+Other aggregate names and aggregate states retain explicit errors.++`arrayCumSum` and `arrayCumSumNonNegative` support one array and an optional single-argument lambda.+Cumulative values require non-null integer or float types. Fractional lambda results use floating-point accumulation.+`arrayFill`, `arrayReverseFill`, `arraySplit`, and `arrayReverseSplit` support one array and one predicate lambda.+The rewrites preserve the first or last element, null values, empty arrays, and the direction of each split.+Scans build intermediate arrays. Large arrays can require substantial copying and memory.++`LpNorm` and `LpDistance` support non-null numeric arrays and tuples. Distance inputs must have equal lengths and the same container type.+The four normalization functions support numeric tuples, matching the source functions' input contract.+Their results contain floating-point values. Zero norms preserve NaN results.+Lp exponents below one or infinite exponents raise an error. A NaN exponent keeps its NaN result.+Floating-point results can differ at machine precision between engines.++`factorial` accepts integers no greater than 20. Inputs at or below zero return one.+`roundAge` and `roundDuration` use the source engine's fixed buckets.+`roundDown` requires a non-empty boundary array and preserves a NaN input.+These numeric functions preserve null inputs.++Tuple addition, subtraction, multiplication, division, negation, and scalar multiplication/division use resolved tuple sizes.+Arithmetic supports integer and float items. Division uses floating-point arithmetic.+Tuple Hamming distance preserves null comparison results.+`arrayLast` uses the resolved item type for the no-match default. `arrayFirst` also preserves nullable defaults.++The `multiSearch` position, index, and predicate families have byte-position and UTF-8 rewrites.+First index means the first matching needle in input order, not the earliest position in the text.+Empty text, missing matches, and empty needle lists keep their separate results.+Byte-based case-insensitive search folds ASCII letters only.+UTF-8 case-insensitive search rejects text or needles whose lowercase conversion changes a character's byte length, because engine behavior differs for these characters.++Trino set operations retain the types of unnamed branch expressions.+This prevents a non-null UNION column from receiving a nullable aggregate default.+Trino division also receives a floating-point result type, so cumulative lambdas do not use an integer accumulator for fractional values.++### Relational compatibility rewrites++The ASOF result test uses one DuckDB thread.+Repeated parallel execution on DuckDB 1.5.2 dropped duplicate rows and crashed for the generated nested-window query.+The same SQL passed repeated single-threaded DuckDB and Trino checks.+This test setting does not change production SQL or Trino execution.++The compiler rewrites these forms before it prints Trino SQL:++- `QUALIFY` can contain inline window functions and unprojected predicate fields.+ Helper columns stay inside the generated subqueries. The compiler preserves+ the original output columns and applies `DISTINCT` after the predicate.+- `QUALIFY` can precede `LIMIT BY`. Window expressions in `LIMIT BY` partitions+ or ordering run in a separate input stage. The final limit runs last.+- `UNION ... BY NAME` aligns resolved columns before type unification. Trino also+ accepts uniform `INTERSECT` and `EXCEPT` chains by name. Every branch must have+ the same unique column names. Mixed operator families require explicit+ subqueries. The compiler preserves positional references when it reorders columns.+- Equi-key `SEMI` joins use a distinct right-key relation. `ANTI` joins use a left+ join to that relation and test an equality key for null. Both preserve duplicate+ left rows. Right-side output references and computed right keys remain blocked.+- Two-table `RIGHT ANY`, `RIGHT SEMI`, and `RIGHT ANTI` joins reverse their inputs+ before the existing left-side rewrite. Longer right-join chains remain blocked.+- Two-table `INNER ASOF` and `LEFT ASOF` forms use a join followed by ranking.+ The constraint needs equality keys and exactly one field-to-field inequality.+ Each left input row gets an internal identifier, so duplicate left rows survive.+ Input columns must be complete. Subqueries outside the inputs and indirect+ output properties remain blocked. Equal nearest timestamps have no specified+ tie order. Candidate joins can be large; use selective keys and bounded inputs.+- Static `PIVOT` uses filtered aggregates. This version accepts one key and one+ `count`, `sum`, `avg`, `min`, or `max` aggregate. Pivot values must be string or+ integer constants. Output aliases are supported; duplicate names are rejected.+- `UNPIVOT` uses one input scan and an array of rows. It preserves the null mode.+ This version accepts one scalar value/name pair and field inputs. Tuple outputs,+ input aliases, multiple column groups, and incompatible value types remain blocked.+- `LEFT ARRAY JOIN` inserts a typed default row when the input arrays are empty.+ Supported defaults include strings, integers, floats, booleans, nullable items,+ arrays, and supported tuples. Other item types keep explicit errors. Multiple+ arrays still need equal lengths. Internal `ARRAY JOIN` ASTs can omit `FROM`,+ although the source parser can reject that form.+- A constant percentage limit uses counting and ranking after the input query.+ It rounds up and calculates the row count before the offset. Percentages must+ be between zero and 100. Percentage limits with ties remain blocked. This also+ supports internal `limit_percent` ASTs when a parser does not accept `PERCENT`.+- Integer addition, subtraction, and multiplication can supply `LIMIT`, `OFFSET`,+ and `LIMIT BY` counts. Arithmetic must stay within the signed 64-bit range.++The Trino printer preserves `FILTER` on the standard aggregates used by `PIVOT`+and on `countDistinct`. Filter values use the existing predicate conversion.++`WITH FILL`, `INTERPOLATE`, `FINAL`, nontrivial `SAMPLE`, `POSITIONAL JOIN`, and+recursive `USING KEY` still have no general rewrite. Complex ASOF forms, full ANY+joins, dynamic pivot schemas, and set-query limits with ties also retain explicit+errors. The compiler does not remove clauses or switch execution engines silently.+Run the Trino printer, semantic expansion, and parameter-helper tests. Run the existing printer/resolver and direct-adapter tests to check shared behavior, and the startup-import guards to check initialization. Do not regenerate existing dialect snapshots simply to make a regression pass.Compilation success is not proof of target schema compatibility or equivalent results. Validate printed SQL separately against the intended Trino schema and compare results only where the source and target data are comparable.++## Dialect isolation++The expanded function signatures, date aliases, lambda resolution, and return-type inference apply only to Trino.+ClickHouse and the other dialects retain their existing function registry, validation, sorting behavior, and type inference.+`DATE`, `Date`, and `date` resolve to the date conversion in Trino.+Trino's weighted median takes a value and weight, and its `If` form also takes a condition.+Trino's `quantiles` and `quantilesIf` take percentile parameters separately from value arguments.+Trino's `ifNotFinite` takes the value and its replacement.+Manifest compilation with `include_hogql=True` uses Trino resolution and preserves function-call syntax in the diagnostic HogQL and column names.+The Trino compiler validates function support and arguments; diagnostic rendering does not consult the ClickHouse registry.+Enabling these diagnostics preserves the generated Trino SQL and bound values.+Saved-query table metadata is captured eagerly only for Trino's detached compilation; other dialects retain lazy lookup and explicit missing-database errors.++Trino set operations use a common type for each output position and can coerce mixed strings and numbers to strings.+For example, `SELECT 'a' UNION ALL SELECT 1` returns strings on Trino, while ClickHouse rejects the incompatible types.+Hidden aliases still project their underlying expressions, so UNION type alignment follows physical projection positions, including unnamed outputs.diff --git a/posthog/hogql/ast.py b/posthog/hogql/ast.pyindex 6e9bfb458f14..630dccb03850 100644--- a/posthog/hogql/ast.py+++ b/posthog/hogql/ast.py@@ -424,10 +424,11 @@ class SelectSetQueryType(Type):return self.types[0].resolve_constant_type(context)-@dataclass(kw_only=True, slots=True)+@dataclass(kw_only=True, slots=True, frozen=False)class SelectViewType(BaseTableType):view_name: stralias: str+ table: Table | None = Noneselect_query_type: SelectQueryType | SelectSetQueryTypedef has_child(self, name: str, context: HogQLContext) -> bool:@@ -438,6 +439,8 @@ class SelectViewType(BaseTableType):return Falsedef resolve_database_table(self, context: HogQLContext) -> Table:+ if self.table is not None:+ return self.tableif context.database is None:raise ResolutionError("Database must be set for queries with views")return context.database.get_table(self.view_name)diff --git a/posthog/hogql/database/trino_unnest_table.py b/posthog/hogql/database/trino_unnest_table.pyindex f4e0fcbbca31..090abe6d312a 100644--- a/posthog/hogql/database/trino_unnest_table.py+++ b/posthog/hogql/database/trino_unnest_table.py@@ -16,7 +16,13 @@ TRINO_UNNEST_TABLE_NAME = "__trino_unnest"class TrinoUnnestTable(FunctionCallTable, DANGEROUS_NoTeamIdCheckTable):name: str- fields: dict[str, FieldOrTable] = {"value": UnknownDatabaseField(name="value")}+ fields: dict[str, FieldOrTable] = {+ "value": UnknownDatabaseField(name="value"),+ "value_2": UnknownDatabaseField(name="value_2"),+ "value_3": UnknownDatabaseField(name="value_3"),+ "value_4": UnknownDatabaseField(name="value_4"),+ "value_5": UnknownDatabaseField(name="value_5"),+ }min_args: int = 1max_args: int = 1diff --git a/posthog/hogql/printer/test/__snapshots__/test_trino_printer.ambr b/posthog/hogql/printer/test/__snapshots__/test_trino_printer.ambrindex 4e5cbab871ec..0474ced1bced 100644--- a/posthog/hogql/printer/test/__snapshots__/test_trino_printer.ambr+++ b/posthog/hogql/printer/test/__snapshots__/test_trino_printer.ambr@@ -15,7 +15,7 @@# ---# name: test_grouping_does_not_replace_different_or_nested_expressions[SELECT properties.color, count() FROM users GROUP BY properties.shape]tuple(- 'SELECT json_extract_scalar("users"."properties", %(hogql_val_0)s), count(*) FROM "ducklake"."analytics"."users" AS "users" GROUP BY json_extract_scalar("users"."properties", %(hogql_val_1)s)',+ 'SELECT json_extract_scalar("users"."properties", %(hogql_val_0)s) AS "color", count(*) FROM "ducklake"."analytics"."users" AS "users" GROUP BY json_extract_scalar("users"."properties", %(hogql_val_1)s)',dict({'hogql_val_0': '$["color"]','hogql_val_1': '$["shape"]',@@ -92,7 +92,7 @@# ---# name: test_lowered_property_timestamp_is_not_constanttuple(- 'SELECT CAST(json_extract_scalar("users"."properties", %(hogql_val_0)s) AS TIMESTAMP) FROM "ducklake"."analytics"."users" AS "users"',+ 'SELECT coalesce(TRY_CAST(json_extract_scalar("users"."properties", %(hogql_val_0)s) AS TIMESTAMP), CAST(TRY(from_iso8601_timestamp(json_extract_scalar("users"."properties", %(hogql_val_0)s))) AS TIMESTAMP), CAST(from_unixtime(TRY_CAST(json_extract_scalar("users"."properties", %(hogql_val_0)s) AS DOUBLE)) AS TIMESTAMP)) FROM "ducklake"."analytics"."users" AS "users"',dict({'hogql_val_0': '$["cutoff"]',}),@@ -100,7 +100,7 @@# ---# name: test_prepared_trino_transpiler_does_not_rebuild_the_schema_database[SELECT properties.color, count() FROM users GROUP BY properties.color]tuple(- 'SELECT json_extract_scalar("users"."properties", %(hogql_val_0)s), count(*) FROM "ducklake"."analytics"."users" AS "users" GROUP BY 1',+ 'SELECT json_extract_scalar("users"."properties", %(hogql_val_0)s) AS "color", count(*) FROM "ducklake"."analytics"."users" AS "users" GROUP BY 1',dict({'hogql_val_0': '$["color"]',}),@@ -137,6 +137,346 @@}),)# ---+# name: test_tracks_every_registered_function_without_a_trino_mapping+ dict({+ 'aggregate': list([+ 'anyHeavy',+ 'anyHeavyIf',+ 'anyLastIf',+ 'argMaxMerge',+ 'argMaxState',+ 'argMinMerge',+ 'argMinState',+ 'avgMapMerge',+ 'avgMapMergeIf',+ 'avgMapState',+ 'avgMerge',+ 'avgMergeIf',+ 'avgMergeOrDefault',+ 'avgMergeOrDefaultIf',+ 'avgMergeOrNull',+ 'avgMergeOrNullIf',+ 'avgState',+ 'avgStateIf',+ 'avgStateOrDefault',+ 'avgStateOrDefaultIf',+ 'avgStateOrNull',+ 'avgStateOrNullIf',+ 'contingency',+ 'contingencyIf',+ 'countDistinctMerge',+ 'countDistinctMergeIf',+ 'countDistinctMergeOrDefault',+ 'countDistinctMergeOrDefaultIf',+ 'countDistinctMergeOrNull',+ 'countDistinctMergeOrNullIf',+ 'countDistinctState',+ 'countDistinctStateIf',+ 'countDistinctStateOrDefault',+ 'countDistinctStateOrDefaultIf',+ 'countDistinctStateOrNull',+ 'countDistinctStateOrNullIf',+ 'countMerge',+ 'countMergeIf',+ 'countMergeOrDefault',+ 'countMergeOrDefaultIf',+ 'countMergeOrNull',+ 'countMergeOrNullIf',+ 'countState',+ 'countStateIf',+ 'countStateOrDefault',+ 'countStateOrDefaultIf',+ 'countStateOrNull',+ 'countStateOrNullIf',+ 'cramersV',+ 'cramersVBiasCorrected',+ 'cramersVBiasCorrectedIf',+ 'cramersVIf',+ 'deltaSumTimestamp',+ 'deltaSumTimestampIf',+ 'groupArraySample',+ 'groupArraySampleIf',+ 'groupBitmap',+ 'groupBitmapAnd',+ 'groupBitmapAndIf',+ 'groupBitmapAndState',+ 'groupBitmapIf',+ 'groupBitmapOr',+ 'groupBitmapOrIf',+ 'groupBitmapOrState',+ 'groupBitmapState',+ 'groupBitmapXor',+ 'groupBitmapXorIf',+ 'maxMerge',+ 'maxMergeIf',+ 'maxMergeOrDefault',+ 'maxMergeOrDefaultIf',+ 'maxMergeOrNull',+ 'maxMergeOrNullIf',+ 'maxState',+ 'maxStateIf',+ 'maxStateOrDefault',+ 'maxStateOrDefaultIf',+ 'maxStateOrNull',+ 'maxStateOrNullIf',+ 'medianBFloat16',+ 'medianBFloat16If',+ 'medianDeterministic',+ 'medianDeterministicIf',+ 'medianMerge',+ 'medianMergeIf',+ 'medianMergeOrDefault',+ 'medianMergeOrDefaultIf',+ 'medianMergeOrNull',+ 'medianMergeOrNullIf',+ 'medianState',+ 'medianStateIf',+ 'medianStateOrDefault',+ 'medianStateOrDefaultIf',+ 'medianStateOrNull',+ 'medianStateOrNullIf',+ 'medianTDigest',+ 'medianTDigestIf',+ 'medianTDigestWeighted',+ 'medianTDigestWeightedIf',+ 'medianTiming',+ 'medianTimingIf',+ 'medianTimingWeighted',+ 'medianTimingWeightedIf',+ 'minMerge',+ 'minMergeIf',+ 'minMergeOrDefault',+ 'minMergeOrDefaultIf',+ 'minMergeOrNull',+ 'minMergeOrNullIf',+ 'minState',+ 'minStateIf',+ 'minStateOrDefault',+ 'minStateOrDefaultIf',+ 'minStateOrNull',+ 'minStateOrNullIf',+ 'quantilesMerge',+ 'quantilesMergeIf',+ 'quantilesState',+ 'quantilesStateIf',+ 'sumForEachMerge',+ 'sumForEachState',+ 'sumMapMerge',+ 'sumMapMergeIf',+ 'sumMerge',+ 'sumMergeIf',+ 'sumMergeOrDefault',+ 'sumMergeOrDefaultIf',+ 'sumMergeOrNull',+ 'sumMergeOrNullIf',+ 'sumState',+ 'sumStateIf',+ 'sumStateOrDefault',+ 'sumStateOrDefaultIf',+ 'sumStateOrNull',+ 'sumStateOrNullIf',+ 'sumWithOverflow',+ 'sumWithOverflowIf',+ 'theilsU',+ 'theilsUIf',+ 'uniqCombined',+ 'uniqExactMerge',+ 'uniqExactState',+ 'uniqHLL12',+ 'uniqHLL12If',+ 'uniqMap',+ 'uniqMapMerge',+ 'uniqMapMergeIf',+ 'uniqMerge',+ 'uniqMergeIf',+ 'uniqState',+ 'uniqStateIf',+ 'uniqTheta',+ 'uniqThetaIf',+ 'uniqUpToMerge',+ 'windowFunnel',+ ]),+ 'posthog': list([+ '__preview_getBotName',+ '__preview_getBotOperator',+ '__preview_getBotType',+ '__preview_getTrafficCategory',+ '__preview_getTrafficType',+ '__preview_isBot',+ '_defaultChannelType',+ '_domainType',+ 'embedText',+ 'explainCSPReport',+ 'getBotName',+ 'getBotOperator',+ 'getBotType',+ 'getSurveyResponse',+ 'getTrafficCategory',+ 'getTrafficType',+ 'isLikelyBot',+ 'lookupDomainType',+ 'lookupOrganicMediumType',+ 'lookupOrganicSourceType',+ 'lookupPaidMediumType',+ 'lookupPaidSourceType',+ 'matchesAction',+ 'recordingButton',+ 'sparkline',+ 'uniqueSurveySubmissionsFilter',+ ]),+ 'scalar': list([+ 'IPv4ToIPv6',+ 'IPv6CIDRToRange',+ 'IPv6NumToString',+ 'IPv6StringToNum',+ 'IPv6StringToNumOrDefault',+ 'IPv6StringToNumOrNull',+ '_finalizeAggregation',+ '_toUInt128',+ 'aggregate_funnel',+ 'aggregate_funnel_array',+ 'aggregate_funnel_array_json',+ 'aggregate_funnel_array_trends',+ 'aggregate_funnel_array_trends_json',+ 'aggregate_funnel_array_trends_test',+ 'aggregate_funnel_cohort',+ 'aggregate_funnel_cohort_json',+ 'aggregate_funnel_cohort_trends',+ 'aggregate_funnel_cohort_trends_json',+ 'aggregate_funnel_json',+ 'aggregate_funnel_test',+ 'aggregate_funnel_trends_json',+ 'arrayJoin',+ 'base58Decode',+ 'bitRotateLeft',+ 'bitRotateRight',+ 'bitSlice',+ 'bitmapAnd',+ 'bitmapAndCardinality',+ 'bitmapAndnot',+ 'bitmapAndnotCardinality',+ 'bitmapBuild',+ 'bitmapCardinality',+ 'bitmapContains',+ 'bitmapHasAll',+ 'bitmapHasAny',+ 'bitmapMax',+ 'bitmapMin',+ 'bitmapOr',+ 'bitmapOrCardinality',+ 'bitmapSubsetInRange',+ 'bitmapSubsetLimit',+ 'bitmapToArray',+ 'bitmapTransform',+ 'bitmapXor',+ 'bitmapXorCardinality',+ 'convertCharset',+ 'cutIPv6',+ 'cutToFirstSignificantSubdomainWithWWW',+ 'dynamicType',+ 'erf',+ 'erfc',+ 'extractTextFromHTML',+ 'firstSignificantSubdomain',+ 'generateSeries',+ 'geoDistance',+ 'geoToH3',+ 'geohashDecode',+ 'geohashEncode',+ 'geohashesInBox',+ 'greatCircleAngle',+ 'greatCircleDistance',+ 'h3CellAreaM2',+ 'h3CellAreaRads2',+ 'h3Distance',+ 'h3EdgeAngle',+ 'h3EdgeLengthKm',+ 'h3EdgeLengthM',+ 'h3ExactEdgeLengthKm',+ 'h3ExactEdgeLengthM',+ 'h3ExactEdgeLengthRads',+ 'h3GetBaseCell',+ 'h3GetDestinationIndexFromUnidirectionalEdge',+ 'h3GetFaces',+ 'h3GetIndexesFromUnidirectionalEdge',+ 'h3GetOriginIndexFromUnidirectionalEdge',+ 'h3GetPentagonIndexes',+ 'h3GetRes0Indexes',+ 'h3GetResolution',+ 'h3GetUnidirectionalEdge',+ 'h3GetUnidirectionalEdgeBoundary',+ 'h3GetUnidirectionalEdgesFromHexagon',+ 'h3HexAreaKm2',+ 'h3HexAreaM2',+ 'h3HexRing',+ 'h3IndexesAreNeighbors',+ 'h3IsPentagon',+ 'h3IsResClassIII',+ 'h3IsValid',+ 'h3Line',+ 'h3NumHexagons',+ 'h3PointDistKm',+ 'h3PointDistM',+ 'h3PointDistRads',+ 'h3ToCenterChild',+ 'h3ToChildren',+ 'h3ToGeo',+ 'h3ToGeoBoundary',+ 'h3ToParent',+ 'h3ToString',+ 'h3UnidirectionalEdgeIsValid',+ 'h3kRing',+ 'hop',+ 'hopEnd',+ 'hopStart',+ 'languageCodeToName',+ 'lgamma',+ 'make_interval',+ 'mapAdd',+ 'mapSubtract',+ 'multiFuzzyMatchAllIndices',+ 'multiFuzzyMatchAny',+ 'multiFuzzyMatchAnyIndex',+ 'multiMatchAllIndices',+ 'multiMatchAny',+ 'multiMatchAnyIndex',+ 'ngramDistanceCaseInsensitiveUTF8',+ 'ngramSearchCaseInsensitiveUTF8',+ 'nowInBlock',+ 'pointInPolygon',+ 'reinterpretAsFloat32',+ 'reinterpretAsFloat64',+ 'reinterpretAsInt128',+ 'reinterpretAsInt16',+ 'reinterpretAsInt256',+ 'reinterpretAsInt32',+ 'reinterpretAsInt64',+ 'reinterpretAsInt8',+ 'reinterpretAsUInt128',+ 'reinterpretAsUInt16',+ 'reinterpretAsUInt256',+ 'reinterpretAsUInt32',+ 'reinterpretAsUInt64',+ 'reinterpretAsUInt8',+ 'rowNumberInAllBlocks',+ 'rowNumberInBlock',+ 'stringToH3',+ 'subBitmap',+ 'tgamma',+ 'toDateTimeUS',+ 'toIPv6',+ 'toIPv6OrDefault',+ 'toIPv6OrNull',+ 'toIPv6OrZero',+ 'tryBase58Decode',+ 'tumble',+ 'tumbleEnd',+ 'tumbleStart',+ 'unhex',+ 'untuple',+ ]),+ })+# ---# name: test_wrapper_sort_projections_preserve_output[SELECT a.created_at FROM users a JOIN users b ON a.user_id = b.user_id ORDER BY b.created_at DESC LIMIT 2 BY a.user_id]tuple('SELECT "__hogql_trino_source_0"."created_at" FROM (SELECT "a"."created_at" AS "created_at", row_number() OVER (PARTITION BY "a"."user_id" ORDER BY "b"."created_at" DESC) AS "__hogql_limit_by_row_0", "b"."created_at" AS "__hogql_order_0" FROM "ducklake"."analytics"."users" AS "a" JOIN "ducklake"."analytics"."users" AS "b" ON ("a"."user_id" = "b"."user_id")) AS "__hogql_trino_source_0" WHERE ("__hogql_trino_source_0"."__hogql_limit_by_row_0" <= 2) ORDER BY "__hogql_trino_source_0"."__hogql_order_0" DESC',@@ -218,14 +558,14 @@# ---# name: test_wrapper_sort_projections_preserve_output[SELECT user_id, user_id = toString(1) AS bucket, row_number() OVER (ORDER BY user_id) AS rn FROM users QUALIFY rn > 0 ORDER BY user_id = toString(1.0) DESC LIMIT 1]tuple(- 'SELECT "__hogql_trino_source_0"."user_id", "__hogql_trino_source_0"."bucket", "__hogql_trino_source_0"."rn" FROM (SELECT "users"."user_id" AS "user_id", ("users"."user_id" = CAST(1 AS VARCHAR)) AS "bucket", row_number() OVER (ORDER BY "users"."user_id" ASC) AS "rn", ("users"."user_id" = CAST(1.0 AS VARCHAR)) AS "__hogql_order_0" FROM "ducklake"."analytics"."users" AS "users") AS "__hogql_trino_source_0" WHERE ("__hogql_trino_source_0"."rn" > 0) ORDER BY "__hogql_trino_source_0"."__hogql_order_0" DESC LIMIT 1',+ 'SELECT "__hogql_trino_source_0"."user_id", "__hogql_trino_source_0"."bucket", "__hogql_trino_source_0"."rn" FROM (SELECT "users"."user_id" AS "user_id", ("user_id" = CAST(1 AS VARCHAR)) AS "bucket", row_number() OVER (ORDER BY "user_id" ASC) AS "rn", ("user_id" = CAST(1.0 AS VARCHAR)) AS "__hogql_order_0" FROM "ducklake"."analytics"."users" AS "users") AS "__hogql_trino_source_0" WHERE ("__hogql_trino_source_0"."rn" > 0) ORDER BY "__hogql_trino_source_0"."__hogql_order_0" DESC LIMIT 1',dict({}),)# ---# name: test_wrapper_sort_projections_preserve_output[SELECT user_id, user_id = toString(1) AS bucket, row_number() OVER (ORDER BY user_id) AS rn FROM users QUALIFY rn > 0 ORDER BY user_id = toString(true) DESC LIMIT 1]tuple(- 'SELECT "__hogql_trino_source_0"."user_id", "__hogql_trino_source_0"."bucket", "__hogql_trino_source_0"."rn" FROM (SELECT "users"."user_id" AS "user_id", ("users"."user_id" = CAST(1 AS VARCHAR)) AS "bucket", row_number() OVER (ORDER BY "users"."user_id" ASC) AS "rn", ("users"."user_id" = CAST(true AS VARCHAR)) AS "__hogql_order_0" FROM "ducklake"."analytics"."users" AS "users") AS "__hogql_trino_source_0" WHERE ("__hogql_trino_source_0"."rn" > 0) ORDER BY "__hogql_trino_source_0"."__hogql_order_0" DESC LIMIT 1',+ 'SELECT "__hogql_trino_source_0"."user_id", "__hogql_trino_source_0"."bucket", "__hogql_trino_source_0"."rn" FROM (SELECT "users"."user_id" AS "user_id", ("user_id" = CAST(1 AS VARCHAR)) AS "bucket", row_number() OVER (ORDER BY "user_id" ASC) AS "rn", ("user_id" = CAST(true AS VARCHAR)) AS "__hogql_order_0" FROM "ducklake"."analytics"."users" AS "users") AS "__hogql_trino_source_0" WHERE ("__hogql_trino_source_0"."rn" > 0) ORDER BY "__hogql_trino_source_0"."__hogql_order_0" DESC LIMIT 1',dict({}),)diff --git a/posthog/hogql/printer/test/test_trino_printer.py b/posthog/hogql/printer/test/test_trino_printer.pyindex 41dc03a2aff7..41319f2ef6c1 100644--- a/posthog/hogql/printer/test/test_trino_printer.py+++ b/posthog/hogql/printer/test/test_trino_printer.py@@ -4,23 +4,42 @@ from contextlib import closingimport pytestfrom unittest import mock+import duckdbfrom syrupy.assertion import SnapshotAssertionfrom posthog.schema import HogQLQueryModifiersfrom posthog.hogql import ast-from posthog.hogql.constants import HogQLQuerySettings+from posthog.hogql.constants import HogQLDialect, HogQLQuerySettingsfrom posthog.hogql.context import HogQLContextfrom posthog.hogql.database.database import Databasefrom posthog.hogql.database.direct_trino_table import DirectTrinoTable-from posthog.hogql.database.models import DateTimeDatabaseField, StringDatabaseField, StringJSONDatabaseField, TableNode+from posthog.hogql.database.models import (+ DateTimeDatabaseField,+ ExpressionField,+ IntegerDatabaseField,+ SavedQuery,+ StringDatabaseField,+ StringJSONDatabaseField,+ TableNode,+ UUIDDatabaseField,+)from posthog.hogql.errors import QueryErrorfrom posthog.hogql.escape_sql import escape_trino_identifier+from posthog.hogql.functions.mapping import HOGQL_AGGREGATIONS, HOGQL_CLICKHOUSE_FUNCTIONS, HOGQL_POSTHOG_FUNCTIONSfrom posthog.hogql.helpers.timestamp_visitor import is_time_or_interval_constant-from posthog.hogql.parser import parse_select+from posthog.hogql.parser import parse_expr, parse_selectfrom posthog.hogql.printer import prepare_and_print_ast, prepare_ast_for_printing, print_prepared_ast+from posthog.hogql.printer.trino_functions import (+ TRINO_AGGREGATE_COMBINATORS,+ TRINO_FUNCTION_HANDLERS_LOWER,+ TRINO_FUNCTION_RENAMES_LOWER,+ TRINO_PASSTHROUGH_FUNCTIONS,+)+from posthog.hogql.resolver import resolve_typesfrom posthog.hogql.transforms.trino.errors import TrinoLoweringErrorfrom posthog.hogql.transforms.trino.transpiler import TrinoTranspilerInput, transpile_prepared_hogql_to_trino+from posthog.hogql.transforms.trino.validate import _SPECIAL_CALLSfrom posthog.hogql.trino_parameters import convert_pyformat_placeholdersfrom posthog.schema_enums import PersonsOnEventsMode@@ -38,7 +57,9 @@ def _context_with_trino_table() -> HogQLContext:table=DirectTrinoTable(name="users",fields={+ "id": IntegerDatabaseField(name="id", nullable=False),"user_id": StringDatabaseField(name="user_id", nullable=False),+ "uuid": UUIDDatabaseField(name="uuid", nullable=False),"created_at": DateTimeDatabaseField(name="created_at", nullable=False),"properties": StringJSONDatabaseField(name="properties", nullable=False),},@@ -59,6 +80,56 @@ def _context_with_trino_table() -> HogQLContext:)+def test_star_projection_preserves_logical_name_for_physical_column_alias() -> None:+ database = Database(include_posthog_tables=False)+ database.tables.add_child(+ TableNode(+ name="subscriptions",+ table=DirectTrinoTable(+ name="subscriptions",+ fields={+ "customer": StringDatabaseField(name="customer"),+ "customer_id": StringDatabaseField(name="customer"),+ "created": IntegerDatabaseField(name="created"),+ "created_at": ExpressionField(name="created_at", expr=parse_expr("toDateTime(created)")),+ },+ external_data_source_id="source-id",+ trino_catalog="ducklake",+ trino_schema="billing",+ trino_table_name="subscriptions",+ has_complete_columns=True,+ ),+ )+ )+ context = HogQLContext(+ database=database,+ modifiers=_trino_modifiers(),+ enable_select_queries=True,+ limit_top_select=False,+ restricted_properties=set(),+ )++ sql, _ = prepare_and_print_ast(+ parse_select("SELECT customer_id FROM (SELECT * FROM subscriptions)"),+ context,+ "trino",+ )++ assert sql.startswith('SELECT "customer_id" FROM (SELECT "subscriptions"."customer", ')+ assert '"subscriptions"."customer" AS "customer_id"' in sql+ assert 'AS "created_at" FROM "ducklake"."billing"."subscriptions"' in sql++ window_sql, _ = prepare_and_print_ast(+ parse_select(+ "SELECT customer_id AS customer_id, "+ "row_number() OVER (PARTITION BY customer_id ORDER BY customer_id) AS row_number FROM subscriptions"+ ),+ context,+ "trino",+ )+ assert 'PARTITION BY "subscriptions"."customer" ORDER BY "subscriptions"."customer" ASC' in window_sql++def test_prints_resolved_query_with_explicit_trino_locator_and_bound_value() -> None:context = _context_with_trino_table()@@ -75,6 +146,33 @@ def test_prints_resolved_query_with_explicit_trino_locator_and_bound_value() ->assert context.values == {"hogql_val_0": "person-1"}+def test_prints_expanded_saved_query_after_detaching_from_database() -> None:+ context = _context_with_trino_table()+ assert context.database is not None+ context.database.tables.add_child(+ TableNode(+ name="accounts",+ table=SavedQuery(+ id="accounts",+ name="accounts",+ query="SELECT user_id AS account_id FROM users",+ fields={"account_id": StringDatabaseField(name="account_id")},+ ),+ )+ )++ sql, _ = prepare_and_print_ast(+ parse_select("SELECT account_id FROM accounts"),+ context,+ "trino",+ )++ assert sql == (+ 'SELECT "accounts"."account_id" FROM '+ '(SELECT "users"."user_id" AS "account_id" FROM "ducklake"."analytics"."users" AS "users") AS "accounts"'+ )++@pytest.mark.parametrize("query",[@@ -158,23 +256,75 @@ def test_normalizes_prewhere_before_validation() -> None:assert sql.count('"users"."user_id" !=') == 2-def test_distinct_limit_by_returns_stable_lowering_error() -> None:- with pytest.raises(TrinoLoweringError) as error:- prepare_and_print_ast(- parse_select("SELECT DISTINCT user_id FROM users LIMIT 1 BY user_id"),- _context_with_trino_table(),- "trino",- )+def test_lowers_distinct_limit_by_after_distinct_projection() -> None:+ sql, _ = prepare_and_print_ast(+ parse_select("SELECT DISTINCT user_id FROM users ORDER BY user_id LIMIT 1 BY user_id"),+ _context_with_trino_table(),+ "trino",+ )- assert error.value.feature_code == "TRINO_LIMIT_BY_DISTINCT_UNSUPPORTED"+ assert 'SELECT DISTINCT "users"."user_id" AS "user_id"' in sql+ assert 'row_number() OVER (PARTITION BY "__hogql_trino_distinct_0"."user_id"' in sql+ assert 'WHERE ("__hogql_trino_source_1"."__hogql_limit_by_row_1" <= 1)' in sql+++def test_ignores_clickhouse_cte_materialization_hint() -> None:+ sql, _ = prepare_and_print_ast(+ parse_select("WITH chosen AS MATERIALIZED (SELECT user_id FROM users) SELECT user_id FROM chosen"),+ _context_with_trino_table(),+ "trino",+ )++ assert 'WITH "chosen" AS (SELECT "users"."user_id" FROM "ducklake"."analytics"."users" AS "users")' in sql+ assert "MATERIALIZED" not in sql@pytest.mark.parametrize(("expression", "expected"),[+ (+ "intDiv(toInt(user_id), 1000)",+ '(CAST(TRY_CAST("users"."user_id" AS BIGINT) AS BIGINT) / CAST(1000 AS BIGINT))',+ ),+ ("arrayZip([1, 2], [3, 4])", "zip(ARRAY[1, 2], ARRAY[3, 4])"),+ (+ "arrayZip(groupArray(user_id), groupArray(created_at))",+ 'IF(cardinality(array_agg("users"."user_id")) = cardinality(array_agg("users"."created_at")), zip(',+ ),+ ("extractURLParameter(user_id, 'ref')", "coalesce(substr(element_at(filter(split(IF(strpos("),+ ("extractAllGroups(user_id, '([a-z]+)')", "__hogql_index -> ARRAY[coalesce(element_at("),+ (+ "extractAllGroups(user_id, '([a-z]+)=([0-9]+)')",+ "__hogql_index -> ARRAY[coalesce(element_at(",+ ),+ (+ "replaceRegexpOne(user_id, '([a-z]+)', 'x')",+ "__hogql_match -> __hogql_match[1] || %(hogql_val_0)s || __hogql_match[4]",+ ),+ (+ "roundBankers(sum(length(user_id)), -1)",+ 'transform(ARRAY[sum(length("users"."user_id"))], __hogql_round_value ->',+ ),+ ("median(length(user_id))", 'approx_percentile(length("users"."user_id"), 0.5)'),+ (+ "medianIf(length(user_id), length(user_id) > 1)",+ 'approx_percentile(length("users"."user_id"), 0.5) FILTER (WHERE',+ ),("arrayMap(value -> value + 1, [1, 2])", 'transform(ARRAY[1, 2], "value" -> ("value" + 1))'),+ (+ "arrayMap((left, right) -> left + right, [1, 2], [3, 4])",+ 'zip_with(ARRAY[1, 2], ARRAY[3, 4], ("left", "right") -> ("left" + "right"))',+ ),("arrayFilter(value -> value > 1, [1, 2])", 'filter(ARRAY[1, 2], "value" -> ("value" > 1))'),+ ("arrayFold((state, value) -> state + value, [1, 2], 0)", "reduce(ARRAY[1, 2], 0,"),+ ("arrayReverseSort(value -> value, [1, 2])", "reverse(transform(array_sort("),("arrayElement([1, 2], 1)", "element_at(ARRAY[1, 2], 1)"),+ ("indexOf([1, 2], 2)", "array_position(ARRAY[1, 2], 2)"),+ ("leftPad(user_id, 4, '0')", 'lpad("users"."user_id", 4,'),+ ("right(user_id, 2)", 'substr("users"."user_id", -(2))'),+ ("upperUTF8(user_id)", 'upper("users"."user_id")'),+ ("fromUnixTimestamp64Milli(1000)", "from_unixtime((CAST(1000 AS DOUBLE) / 1000e0))"),+ ("TRUNC(1.234, 2)", "truncate(1.234, 2)"),("hasAny([1, 2], [2, 3])", "(cardinality(array_intersect(ARRAY[1, 2], ARRAY[2, 3])) > 0)"),("range(2, 5)",@@ -191,6 +341,144 @@ def test_distinct_limit_by_returns_stable_lowering_error() -> None:("toIntervalMonth(3)", "(CAST(3 AS BIGINT) * INTERVAL '1' MONTH)"),("toInt(toDate('2022-01-01'))", "date_diff('day', DATE '1970-01-01', CAST("),("toInt(created_at)", 'CAST(to_unixtime("users"."created_at") AS BIGINT)'),+ ("arrayCount(x -> x > 1, [1, 2, 3])", 'cardinality(filter(ARRAY[1, 2, 3], "x" -> ("x" > 1)))'),+ (+ "countEqual([1, 2, 1], 1)",+ "element_at(transform(ARRAY[ROW(ARRAY[1, 2, 1], 1)], __hogql_args -> cardinality(filter(",+ ),+ (+ "countEqual(groupArray(user_id), any(user_id))",+ 'ARRAY[ROW(array_agg("users"."user_id"), arbitrary("users"."user_id"))]',+ ),+ ("coalesce(properties.enabled, false) = 0", "CAST(coalesce(CAST(json_extract_scalar("),+ ("countDistinctIf(user_id, user_id != '')", 'count(DISTINCT "users"."user_id") FILTER (WHERE'),+ ("multiSearchAnyCaseInsensitive(user_id, ['a']) = 1", "CAST(any_match("),+ ("toFloat64OrNull(user_id)", 'TRY_CAST("users"."user_id" AS DOUBLE)'),+ ("accurateCastOrNull(user_id, 'Int64')", "TRY_CAST(__hogql_accurate_cast_value AS DECIMAL(38, 18))"),+ ("DATE(created_at)", 'CAST("users"."created_at" AS DATE)'),+ ("domain(user_id)", "coalesce(TRY(url_extract_host(CAST("),+ ("multiplyDecimal(1, 2)", "CAST((1 * 2) AS DECIMAL(38, 0))"),+ ("quantileExact(0.9)(length(user_id))", "filter(coalesce(array_agg(length("),+ ("ngramDistance(user_id, 'abc')", "MAP(VARBINARY, BIGINT)"),+ ("formatReadableTimeDelta(3661)", "'hour', 'hours'"),+ (+ "multiSearchAnyCaseInsensitive(user_id, ['Ab'])",+ "any_match(ARRAY[%(hogql_val_0)s], __hogql_needle -> strpos(lower(",+ ),+ (+ "replaceOne(user_id, 'a', 'b')",+ 'CASE WHEN length(%(hogql_val_0)s) = 0 OR strpos("users"."user_id", %(hogql_val_0)s) = 0',+ ),+ ("floor(1.234, 2)", "(floor(1.234 * power(10, 2)) / power(10, 2))"),+ ("ceil(-1.234, 2)", "(ceil(-1.234 * power(10, 2)) / power(10, 2))"),+ ("md5(user_id AS TEXT)", 'to_hex(md5(to_utf8(CAST("users"."user_id" AS VARCHAR))))'),+ ("splitByString(',', user_id, 2)", 'ELSE slice(split("users"."user_id", %(hogql_val_0)s), 1, 2) END'),+ ("arraySlice([1, 2, 3], -2, -1)", "element_at(transform(ARRAY[ROW(ARRAY[1, 2, 3], -2, -1)]"),+ ("arraySort(x -> -x, [1, 3, 2])", 'transform(array_sort(transform(ARRAY[1, 3, 2], "x" -> ROW('),+ ("toStartOfInterval(created_at, INTERVAL 10 MINUTE)", " / 600e0) AS BIGINT) * 600"),+ ("toStartOfInterval(created_at, INTERVAL 2 MONTH)", "date_diff('month', TIMESTAMP '1900-01-01"),+ (+ "toStartOfInterval(created_at, INTERVAL 3 HOUR, toDateTime('2024-01-01'))",+ "date_diff('second', CAST(%(hogql_val_0)s AS TIMESTAMP)",+ ),+ ("parseDateTimeBestEffort(user_id)", 'CAST(at_timezone(coalesce(IF(regexp_like("users"."user_id",'),+ (+ "dateDiff('day', user_id, created_at)",+ 'date_diff(%(hogql_val_0)s, CAST("users"."user_id" AS TIMESTAMP), "users"."created_at")',+ ),+ ("CASE user_id WHEN 'a' THEN 1 ELSE 2 END", 'CASE "users"."user_id" WHEN %(hogql_val_0)s THEN 1 ELSE 2 END'),+ ("if(2, 3, 4)", "CASE WHEN CAST(2 AS BOOLEAN) THEN 3 ELSE 4 END"),+ ("NOT properties.enabled", "NOT CAST(json_extract_scalar("),+ ("log(2)", "ln(2)"),+ ("toInt(user_id)", 'TRY_CAST("users"."user_id" AS BIGINT)'),+ ("countDistinctIf(user_id, 1)", "FILTER (WHERE CAST(1 AS BOOLEAN))"),+ ("coalesce(properties.enabled, false)", "coalesce(CAST(json_extract_scalar("),+ ("positionCaseInsensitive(user_id, 'ab')", 'strpos(lower("users"."user_id"), lower('),+ ("lowerUTF8(user_id)", 'lower("users"."user_id")'),+ ("arrayEnumerate([10, 20])", "sequence(1, cardinality(ARRAY[10, 20]))"),+ ("arrayExists(x -> x > 1, [1, 2])", 'any_match(ARRAY[1, 2], "x" -> ("x" > 1))'),+ ("cutToFirstSignificantSubdomain(user_id)", "array_join(slice(filter(split(lower(trim(TRAILING '.' FROM"),+ ("mapFromArrays([user_id], [1])", "map(__hogql_args[1], __hogql_args[2])"),+ ("equals(length(user_id), '3')", 'length("users"."user_id") = CAST('),+ ("sum(user_id)", 'sum(TRY_CAST("users"."user_id" AS DOUBLE))'),+ ("lengthUTF8(user_id)", 'length("users"."user_id")'),+ ("hex(user_id)", 'to_hex(to_utf8(CAST("users"."user_id" AS VARCHAR)))'),+ ("toUUIDOrDefault(user_id, user_id)", 'coalesce(TRY_CAST("users"."user_id" AS UUID)'),+ ("toFloat(created_at)", 'to_unixtime("users"."created_at")'),+ ("coalesce(user_id, 1)", 'coalesce("users"."user_id", CAST(1 AS VARCHAR))'),+ ("toString([1, 2])", "json_format(CAST(ARRAY[1, 2] AS JSON))"),+ ("created_at = 0", '"users"."created_at" = from_unixtime(CAST(0 AS DOUBLE))'),+ ("_toUInt64(user_id)", 'CAST("users"."user_id" AS BIGINT)'),+ ("_toUInt64(created_at)", 'CAST(to_unixtime("users"."created_at") AS BIGINT)'),+ ("encodeURLComponent(user_id)", 'url_encode("users"."user_id")'),+ ("in(user_id, tuple('one'))", '("users"."user_id" IN (%(hogql_val_0)s))'),+ ("max2(1, 2)", "greatest(1, 2)"),+ ("min2(1, 2)", "least(1, 2)"),+ ("positiveModulo(-3, 2)", "mod(mod(-3, 2) + 2, 2)"),+ ("arrayPopFront([1, 2])", "slice(ARRAY[1, 2], 2, greatest(cardinality(ARRAY[1, 2]) - 1, 0))"),+ ("arrayPopBack([1, 2])", "slice(ARRAY[1, 2], 1, greatest(cardinality(ARRAY[1, 2]) - 1, 0))"),+ ("arrayPushFront([1], 2)", "concat(ARRAY[2], ARRAY[1])"),+ ("arrayPushBack([1], 2)", "concat(ARRAY[1], ARRAY[2])"),+ ("arrayDifference([1, 3])", "ARRAY[1, 3][__hogql_index] - ARRAY[1, 3][__hogql_index - 1]"),+ ("arrayUniq([1, 1, 2])", "cardinality(array_distinct(ARRAY[1, 1, 2]))"),+ ("arrayWithConstant(2, 7)", "repeat(7, CAST(2 AS BIGINT))"),+ ("base64Encode(user_id)", 'to_base64(to_utf8("users"."user_id"))'),+ ("base64Decode(user_id)", 'from_utf8(from_base64("users"."user_id"))'),+ ("ascii(user_id)", 'from_base(to_hex(substr(to_utf8("users"."user_id"), 1, 1)), 16)'),+ ("left(user_id, 2)", 'substr("users"."user_id", 1, 2)'),+ ("mapContains(mapFromArrays(['a'], [1]), 'a')", "contains(map_keys(map(ARRAY["),+ ("json_agg(user_id)", 'json_format(CAST(array_agg("users"."user_id") AS JSON))'),+ ("string_agg(user_id, ',')", 'array_join(array_agg("users"."user_id"),'),+ ("every(length(user_id) > 0)", "bool_and(CAST((length("),+ ("stddevPop(length(user_id))", 'stddev_pop(length("users"."user_id"))'),+ ("varSamp(length(user_id))", 'var_samp(length("users"."user_id"))'),+ ("monthName(created_at)", 'date_format("users"."created_at", \'%M\')'),+ ("toUnixTimestamp64Milli(created_at)", 'CAST(to_unixtime("users"."created_at") * 1000 AS BIGINT)'),+ ("isValidJSON(user_id)", 'TRY(json_parse(CAST("users"."user_id" AS VARCHAR))) IS NOT NULL'),+ ("exp2(3)", "power(2, 3)"),+ ("log1p(3)", "ln(1 + 3)"),+ ("bitAnd(3, 1)", "bitwise_and(3, 1)"),+ ("arrayAvg([1, 2, 3])", "reduce(ARRAY[1, 2, 3], DOUBLE '0'"),+ ("arrayCompact([1, 1, 2])", "element_at(__hogql_result, -1) IS DISTINCT FROM __hogql_value"),+ (+ "arrayEnumerateDense([10, 20, 10])",+ "array_position(transform(array_distinct(slice(ARRAY[10, 20, 10]",+ ),+ (+ "arrayEnumerateUniq([10, 20, 10], [1, 1, 1])",+ "cardinality(filter(slice(zip(ARRAY[10, 20, 10], ARRAY[1, 1, 1])",+ ),+ ("arrayFirstIndex(x -> x > 1, [1, 2])", 'coalesce(array_position(transform(ARRAY[1, 2], "x" ->'),+ (+ "arrayLastIndex(x -> x > 1, [1, 2])",+ 'reduce(transform(ARRAY[1, 2], "x" ->',+ ),+ ("arrayRotateLeft([1, 2, 3], 1)", "concat(slice(ARRAY[1, 2, 3]"),+ ("arrayRotateRight([1, 2, 3], 1)", "mod(mod(-(1), cardinality(ARRAY[1, 2, 3]))"),+ ("hasSubstr([1, 2, 3], [2, 3])", "contains_sequence(ARRAY[1, 2, 3], ARRAY[2, 3])"),+ (+ "appendTrailingCharIfAbsent(user_id, '/')",+ "fail('appendTrailingCharIfAbsent expects one character')",+ ),+ ("countMatches(user_id, 'a')", 'cardinality(regexp_extract_all("users"."user_id"'),+ ("countSubstrings(user_id, 'a')", "__hogql_substrings -> IF(length(__hogql_substrings[2])"),+ ("splitByRegexp('-', user_id)", 'regexp_split("users"."user_id"'),+ ("mapContainsKeyLike(mapFromArrays(['a'], [1]), 'a%')", "cardinality(map_filter(map(ARRAY["),+ ("bitTest(4, 2)", "bitwise_and(4, bitwise_left_shift(BIGINT '1', 2)) <> 0"),+ ("bitTestAll(6, 1, 2)", "bitwise_and(6, bitwise_left_shift(BIGINT '1', 1)) <> 0 AND"),+ ("bitShiftRight(-8, 1)", "bitwise_right_shift_arithmetic(-8, 1)"),+ ("bitHammingDistance(5, 1)", "bit_count(bitwise_xor(5, 1), 64)"),+ ("L2Distance([1, 2], [3, 4])", "euclidean_distance(ARRAY[1, 2], ARRAY[3, 4])"),+ ("port('https://example.com', 443)", "coalesce(url_extract_port("),+ ("age('day', created_at, created_at)", "date_diff("),+ ("arrayResize([1, 2], -3, 0)", "concat(repeat(0, greatest(-("),+ ("groupBitAnd(length(user_id))", 'bitwise_and_agg(length("users"."user_id"))'),+ ("domainWithoutWWW('https://www.example.com')", "regexp_replace(coalesce(url_extract_host("),+ ("topLevelDomain('https://www.example.com')", "element_at(split(coalesce(url_extract_host("),+ ("L1Distance([1, 2], [3, 5])", "reduce(zip_with(ARRAY[1, 2], ARRAY[3, 5]"),+ ("L2Norm([3, 4])", "sqrt(dot_product(ARRAY[3, 4], ARRAY[3, 4]))"),+ ("toModifiedJulianDay(created_at)", "date_diff('day', DATE '1858-11-17'"),+ ("fromModifiedJulianDay(60000)", "date_add('day', CAST(60000 AS BIGINT), DATE '1858-11-17')"),],)def test_prints_core_trino_expression_mappings(expression: str, expected: str) -> None:@@ -201,6 +489,126 @@ def test_prints_core_trino_expression_mappings(expression: str, expected: str) -assert expected in sql+def test_drops_clickhouse_global_distribution_modifiers() -> None:+ membership_query = parse_select("SELECT user_id FROM users WHERE user_id IN ['a']")+ assert isinstance(membership_query, ast.SelectQuery)+ assert isinstance(membership_query.where, ast.CompareOperation)+ membership_query.where.op = ast.CompareOperationOp.GlobalIn+ membership_sql, _ = prepare_and_print_ast(+ membership_query,+ _context_with_trino_table(),+ "trino",+ )+ assert "GLOBAL" not in membership_sql+ assert '"users"."user_id" IN (%(hogql_val_0)s)' in membership_sql++ query = parse_select("SELECT users.user_id FROM users LEFT JOIN users AS other ON users.user_id = other.user_id")+ assert isinstance(query, ast.SelectQuery)+ assert isinstance(query.select_from, ast.JoinExpr)+ assert query.select_from.next_join is not None+ query.select_from.next_join.join_type = "GLOBAL LEFT JOIN"+ join_sql, _ = prepare_and_print_ast(query, _context_with_trino_table(), "trino")+ assert "GLOBAL" not in join_sql+ assert "LEFT JOIN" in join_sql+++def test_tracks_every_registered_function_without_a_trino_mapping(snapshot: SnapshotAssertion) -> None:+ supported = {+ *TRINO_FUNCTION_HANDLERS_LOWER,+ *TRINO_FUNCTION_RENAMES_LOWER,+ *TRINO_PASSTHROUGH_FUNCTIONS,+ *_SPECIAL_CALLS,+ }+ registries = {+ "scalar": HOGQL_CLICKHOUSE_FUNCTIONS,+ "aggregate": HOGQL_AGGREGATIONS,+ "posthog": HOGQL_POSTHOG_FUNCTIONS,+ }+ unsupported = {+ group: sorted(name for name in registry if name.lower() not in supported)+ for group, registry in registries.items()+ }++ assert unsupported == snapshot+++ "expression, feature_code",+ [+ ("tuplePlus((1, 2), tuple(1))", "TRINO_FUNCTION_ARGUMENTS_UNSUPPORTED"),+ ("tuplePlus(('a', 2), ('b', 3))", "TRINO_FUNCTION_ARGUMENTS_UNSUPPORTED"),+ ("sumArray(user_id)", "TRINO_FUNCTION_ARGUMENTS_UNSUPPORTED"),+ ("sumOrNull(DISTINCT created_at)", "TRINO_FUNCTION_ARGUMENTS_UNSUPPORTED"),+ ("sumForEach(user_id)", "TRINO_FUNCTION_ARGUMENTS_UNSUPPORTED"),+ ("sumMap([1, 2])", "TRINO_FUNCTION_ARGUMENTS_UNSUPPORTED"),+ ("sumArgMin(id, uuid)", "TRINO_FUNCTION_ARGUMENTS_UNSUPPORTED"),+ ("sumArgMax(id, [1, 2])", "TRINO_FUNCTION_ARGUMENTS_UNSUPPORTED"),+ ("medianExact(user_id)", "TRINO_FUNCTION_ARGUMENTS_UNSUPPORTED"),+ ("medianExact(DISTINCT id)", "TRINO_FUNCTION_ARGUMENTS_UNSUPPORTED"),+ ("avgWeighted(id, user_id)", "TRINO_FUNCTION_ARGUMENTS_UNSUPPORTED"),+ ("toNullableString(1.5)", "TRINO_FUNCTION_ARGUMENTS_UNSUPPORTED"),+ ("groupUniqArrayArray(0)([1, 2])", "TRINO_FUNCTION_ARGUMENTS_UNSUPPORTED"),+ ("to_timestamp(1.5)", "TRINO_FUNCTION_ARGUMENTS_UNSUPPORTED"),+ ("lagInFrame(id)", "TRINO_FUNCTION_ARGUMENTS_UNSUPPORTED"),+ ("arrayCumSum([1, NULL])", "TRINO_FUNCTION_ARGUMENTS_UNSUPPORTED"),+ ("L1Normalize([3, 4])", "TRINO_FUNCTION_ARGUMENTS_UNSUPPORTED"),+ ("factorial(3.5)", "TRINO_FUNCTION_ARGUMENTS_UNSUPPORTED"),+ ("intDiv(1.5, 2)", "TRINO_INT_DIV_TYPE_UNSUPPORTED"),+ ("roundBankers(1, length(user_id))", "TRINO_ROUND_BANKERS_PRECISION_UNSUPPORTED"),+ ("roundBankers(1, 19)", "TRINO_ROUND_BANKERS_PRECISION_UNSUPPORTED"),+ ("arrayZip([1], [2, 3])", "TRINO_FUNCTION_ARGUMENTS_UNSUPPORTED"),+ ("arrayZip([1], [2], [3], [4], [5], [6])", "TRINO_ARRAY_ZIP_DYNAMIC_UNSUPPORTED"),+ ("extractAllGroups(user_id, user_id)", "TRINO_REGEX_CONSTANT_REQUIRED"),+ (+ "extractAllGroups(user_id, '(a)(b)(c)(d)(e)(f)(g)(h)(i)(j)(k)(l)(m)(n)(o)(p)(q)(r)(s)(t)(u)')",+ "TRINO_REGEX_GROUPS_UNSUPPORTED",+ ),+ ("replaceRegexpOne(user_id, 'a', user_id)", "TRINO_REGEX_CONSTANT_REQUIRED"),+ ("cityHash64(user_id)", "TRINO_FUNCTION_UNSUPPORTED"),+ ("toTypeName(user_id)", "TRINO_FUNCTION_UNSUPPORTED"),+ ("bitNot(id)", "TRINO_FUNCTION_UNSUPPORTED"),+ ],+)+def test_rejects_unsupported_printer_function_variants(expression: str, feature_code: str) -> None:+ with pytest.raises(TrinoLoweringError) as error:+ prepare_and_print_ast(parse_select(f"SELECT {expression} FROM users"), _context_with_trino_table(), "trino")++ assert error.value.feature_code == feature_code+++def test_first_regex_replacement_preserves_capture_indices_and_literal_dollars() -> None:+ context = _context_with_trino_table()+ sql, _ = prepare_and_print_ast(+ parse_select(r"SELECT replaceRegexpOne(user_id, '([a-z])([0-9])', '\\2$\\1') FROM users"), context, "trino"+ )++ assert r"(?s)\A(.*?)(([a-z])([0-9]))(.*)\z" in context.values.values()+ assert "$" in context.values.values()+ assert "coalesce(__hogql_match[4], '') || %(hogql_val_0)s || coalesce(__hogql_match[3], '')" in sql+ assert "__hogql_match[5]" in sql+++def test_first_regex_replacement_preserves_inline_flags() -> None:+ context = _context_with_trino_table()+ prepare_and_print_ast(parse_select("SELECT replaceRegexpOne(user_id, '(?i)a', 'b') FROM users"), context, "trino")++ assert r"(?s)\A(.*?)((?i)a)(.*)\z" in context.values.values()+++ "query, expected",+ [+ ("SELECT (user_id AS inner_name) AS result FROM users", 'AS "result"'),+ ("SELECT user_id FROM users GROUP BY user_id HAVING count() > 0 AS keep", "HAVING (count(*) > 0)"),+ ],+)+def test_omits_expression_aliases_outside_select_projections(query: str, expected: str) -> None:+ sql, _ = prepare_and_print_ast(parse_select(query), _context_with_trino_table(), "trino")+ assert expected in sql+ assert 'AS "inner_name"' not in sql+ assert 'AS "keep"' not in sql++def test_coerces_strict_trino_types_after_property_lowering() -> None:context = _context_with_trino_table()@@ -261,17 +669,29 @@ def test_uses_trino_array_cardinality_and_lax_json_paths() -> None:assert 'json_value("users"."properties", \'strict $.items\')' in sql-def test_prints_json_paths_as_bound_values() -> None:+def test_preserves_clickhouse_json_array_indexing() -> None:context = _context_with_trino_table()sql, _ = prepare_and_print_ast(- parse_select("SELECT JSONExtractString(user_id, 'key.with.dot', 2) FROM users"),+ parse_select(+ "SELECT JSONExtractString(user_id, 'key.with.dot', 2), "+ "JSONExtractRaw(properties, length(user_id)), "+ "JSONExtract(properties, 1, 'Map(String, String)'), "+ "JSONHas(properties, 1), JSONLength(properties, 1), "+ "JSONExtractKeys(properties, 1), JSONExtractRaw(properties, 'items', 1), "+ "JSONExtractRaw(properties, 1, 1) FROM users"+ ),context,"trino",)- assert 'json_extract_scalar("users"."user_id", %(hogql_val_0)s)' in sql- assert context.values == {"hogql_val_0": '$["key.with.dot"][2]'}+ assert "element_at(CAST(json_extract(" in sql+ assert "AS ARRAY(JSON)), 2)" in sql+ assert 'AS ARRAY(JSON)), CAST(length("users"."user_id") AS INTEGER))' in sql+ assert sql.count("element_at(") == 9+ assert 'CAST(json_extract("users"."properties", %(hogql_val_1)s) AS ARRAY(JSON))' in sql+ assert "CAST(TRY(element_at(" in sql+ assert context.values == {"hogql_val_0": '$["key.with.dot"]', "hogql_val_1": '$["items"]'}def test_lowers_event_property_backed_fields_to_the_physical_json_column() -> None:@@ -360,6 +780,109 @@ def test_lowers_clickhouse_select_alias_references_to_expressions(assert values == expected_values[email protected]("depth", [1, 4])+def test_scalar_cte_chains_preserve_results(depth: int) -> None:+ ctes = ["1 AS c0", *[f"c{i - 1} + c{i - 1} AS c{i}" for i in range(1, depth + 1)]]+ sql, _ = prepare_and_print_ast(+ parse_select(f"WITH {', '.join(ctes)} SELECT c{depth}"), _context_with_trino_table(), "trino"+ )+ with duckdb.connect(":memory:") as connection:+ assert connection.execute(sql).fetchall() == [(2**depth,)]+++def test_rejects_excessive_scalar_cte_expansion() -> None:+ ctes = ["1 AS c0", *[f"c{i - 1} + c{i - 1} AS c{i}" for i in range(1, 15)]]+ with pytest.raises(TrinoLoweringError, match="TRINO_AST_EXPANSION_LIMIT"):+ prepare_and_print_ast(parse_select(f"WITH {', '.join(ctes)} SELECT c14"), _context_with_trino_table(), "trino")++[email protected]("length", ["", ", -1"])+def test_nested_array_slices_have_bounded_sql_size(length: str) -> None:+ expression = "[1, 2, 3]"+ for _ in range(4):+ expression = f"arraySlice({expression}, 1{length})"+ sql, _ = prepare_and_print_ast(parse_select(f"SELECT {expression}"), _context_with_trino_table(), "trino")+ assert len(sql) < 10_000+ assert sql.count("ARRAY[1, 2, 3]") == 1++[email protected]("projection", ["id", "users.id"])+def test_scalar_ctes_do_not_replace_real_columns(projection: str) -> None:+ sql, _ = prepare_and_print_ast(+ parse_select(f"WITH 1 AS id SELECT {projection} FROM users"), _context_with_trino_table(), "trino"+ )+ assert sql.startswith('SELECT "users"."id" FROM ')+++def test_rejects_excessive_select_alias_expansion() -> None:+ projections = ["1 AS a0", *[f"a{i - 1} + a{i - 1} AS a{i}" for i in range(1, 15)]]+ with pytest.raises(TrinoLoweringError, match="TRINO_AST_EXPANSION_LIMIT"):+ prepare_and_print_ast(parse_select(f"SELECT {', '.join(projections)}"), _context_with_trino_table(), "trino")+++def test_rejects_excessive_rendered_expression_size() -> None:+ expression = "user_id"+ for _ in range(6):+ expression = f"replaceOne({expression}, 'a', 'b')"+ with (+ mock.patch("posthog.hogql.printer.trino.MAX_TRINO_SQL_LENGTH", 10_000),+ pytest.raises(TrinoLoweringError, match="TRINO_SQL_SIZE_LIMIT"),+ ):+ prepare_and_print_ast(parse_select(f"SELECT {expression} FROM users"), _context_with_trino_table(), "trino")++[email protected]("count", [10_001, 20_000])+def test_rejects_numbers_above_the_trino_sequence_limit(count: int) -> None:+ with pytest.raises(TrinoLoweringError, match="TRINO_NUMBERS_ROW_LIMIT_EXCEEDED"):+ prepare_and_print_ast(+ parse_select(f"SELECT number FROM numbers({count})"), _context_with_trino_table(), "trino"+ )++[email protected]("name", ["date", "Date", "DATE"])[email protected]("dialect", ["clickhouse", "hogql", "trino"])+def test_date_alias_is_case_insensitive(name: str, dialect: HogQLDialect) -> None:+ context = _context_with_trino_table()+ context.team_id = 1+ query = resolve_types(parse_select(f"SELECT {name}('2026-01-01') AS day"), context, dialect)+ if dialect != "trino":+ with pytest.raises(QueryError, match="Unsupported function call"):+ print_prepared_ast(query, context, dialect)+ return+ sql = print_prepared_ast(query, context, dialect)+ expected_context = _context_with_trino_table()+ expected_context.team_id = 1+ expected = print_prepared_ast(+ resolve_types(parse_select("SELECT toDate('2026-01-01') AS day"), expected_context, dialect),+ expected_context,+ dialect,+ )+ assert sql+ assert sql == expected+++def test_inlines_scalar_ctes_for_trino() -> None:+ sql, _ = prepare_and_print_ast(+ parse_select("WITH '2025-01-01' AS cutoff SELECT user_id FROM users WHERE created_at >= toDateTime(cutoff)"),+ _context_with_trino_table(),+ "trino",+ )++ assert "WITH" not in sql+ assert '"users"."created_at" >= CAST(%(hogql_val_0)s AS TIMESTAMP)' in sql+++def test_lowers_dynamic_numbers_with_a_bounded_cardinality() -> None:+ sql, _ = prepare_and_print_ast(+ parse_select("SELECT number FROM numbers(dateDiff('day', toDate('2025-01-01'), today()))"),+ _context_with_trino_table(),+ "trino",+ )++ assert "least(greatest(" in sql+ assert "10000" in sql++@pytest.mark.parametrize("expression, expected",[@@ -429,13 +952,42 @@ def test_prints_empty_for_lowered_json_property_after_second_resolution() -> Nonassert context.values == {"hogql_val_0": '$["task_run_id"]'}-def test_rejects_function_argument_shapes_with_stable_error() -> None:+def test_lowers_nested_json_keys_and_values_raw() -> None:context = _context_with_trino_table()+ sql, _ = prepare_and_print_ast(parse_select("SELECT JSONExtractKeysAndValuesRaw('{}', 'teams')"), context, "trino")++ assert "map_entries(CAST(json_extract(" in sql+ assert context.values == {"hogql_val_0": "{}", "hogql_val_1": '$["teams"]'}++def test_lowers_currency_conversion_with_the_trino_exchange_rate_table() -> None:+ context = _context_with_trino_table()+ context.trino_table_locators = {+ **context.trino_table_locators,+ "exchange_rate": ("ducklake", "posthog", "exchange_rate"),+ }++ sql, _ = prepare_and_print_ast(+ parse_select("SELECT convertCurrency(user_id, 'USD', 100, DATE(created_at)) FROM users"),+ context,+ "trino",+ )++ assert "max_by(CAST(__hogql_from_rate.rate AS DECIMAL(38, 10)), __hogql_from_rate.date)" in sql+ assert 'FROM "ducklake"."posthog"."exchange_rate" AS __hogql_from_rate' in sql+ assert '__hogql_from_rate.date <= CAST(CAST("users"."created_at" AS DATE) AS DATE)' in sql+ assert "NULLIF" in sql+++def test_rejects_currency_conversion_without_an_exchange_rate_locator() -> None:with pytest.raises(TrinoLoweringError) as error:- prepare_and_print_ast(parse_select("SELECT JSONExtractKeysAndValuesRaw('{}', 'extra')"), context, "trino")+ prepare_and_print_ast(+ parse_select("SELECT convertCurrency(user_id, 'USD', 100) FROM users"),+ _context_with_trino_table(),+ "trino",+ )- assert error.value.feature_code == "TRINO_FUNCTION_ARGUMENTS_UNSUPPORTED"+ assert error.value.feature_code == "TRINO_EXCHANGE_RATE_TABLE_REQUIRED"@pytest.mark.parametrize(@@ -461,7 +1013,7 @@ def test_lowers_numbers_to_bounded_unnest(source: str, expected: str) -> None:assert 'AS "numbers" ("number")' in sql-def test_rejects_unbounded_numbers_input() -> None:+def test_bounds_dynamic_numbers_input() -> None:context = HogQLContext(database=Database(include_posthog_tables=True),modifiers=_trino_modifiers(),@@ -470,10 +1022,15 @@ def test_rejects_unbounded_numbers_input() -> None:restricted_properties=set(),)- with pytest.raises(TrinoLoweringError, match="constant integer arguments") as error:- prepare_and_print_ast(parse_select("SELECT number FROM numbers(number)"), context, "trino")+ sql, _ = prepare_and_print_ast(+ parse_select("SELECT number FROM numbers(dateDiff('day', toDate('2025-01-01'), today()))"),+ context,+ "trino",+ )- assert error.value.feature_code == "TRINO_NUMBERS_NON_CONSTANT_ARGUMENT"+ assert "least(greatest(" in sql+ assert "10000" in sql+ assert sql.count("date_diff(") == 1def test_lowers_single_array_join_to_cross_join_unnest() -> None:@@ -506,17 +1063,21 @@ def test_internal_unnest_function_is_not_shadowed_by_a_cte() -> None:assert 'AS "__trino_array_function_0" ("value_0")' in sql-def test_rejects_multi_array_join_with_different_cardinality_semantics() -> None:+def test_lowers_multi_array_join_with_equal_cardinality_guard() -> None:context = _context_with_trino_table()- with pytest.raises(TrinoLoweringError) as error:- prepare_and_print_ast(- parse_select("SELECT first FROM users ARRAY JOIN [1] AS first, [2] AS second"),- context,- "trino",- )+ sql, _ = prepare_and_print_ast(+ parse_select(+ "SELECT first, second FROM users "+ "ARRAY JOIN splitByChar(',', user_id) AS first, splitByChar(',', user_id) AS second"+ ),+ context,+ "trino",+ )- assert error.value.feature_code == "TRINO_ARRAY_JOIN_MULTIPLE_ARRAYS_UNSUPPORTED"+ assert "CROSS JOIN UNNEST(IF(cardinality(split(" in sql+ assert "= cardinality(split(" in sql+ assert 'AS "__trino_unnest_0" ("first", "second")' in sqldef test_lowers_array_join_function_to_cross_join_unnest() -> None:@@ -535,6 +1096,30 @@ def test_lowers_array_join_function_to_cross_join_unnest() -> None:)+def test_lowers_select_alias_inside_array_join_function() -> None:+ sql, _ = prepare_and_print_ast(+ parse_select("SELECT [user_id] AS ids, arrayJoin(ids) AS item FROM users"),+ _context_with_trino_table(),+ "trino",+ )++ assert 'UNNEST(transform(ARRAY["users"."user_id"]' in sql+ assert 'UNNEST(transform("ids"' not in sql+++def test_rejects_unverified_funnel_aggregation() -> None:+ with pytest.raises(TrinoLoweringError, match="TRINO_FUNCTION_UNSUPPORTED"):+ prepare_and_print_ast(+ parse_select(+ "SELECT groupArray(tuple(1, 2, user_id, '', [1, 2])) AS events_array, "+ "arrayJoin(aggregate_funnel_trends(1, 2, 2, 10, 'first_touch', 'ordered', [''], events_array)) "+ "AS funnel_result FROM users"+ ),+ _context_with_trino_table(),+ "trino",+ )++def test_lowers_limit_by_to_row_number_wrapper() -> None:context = _context_with_trino_table()@@ -567,6 +1152,353 @@ def test_lowers_qualify_alias_to_outer_filter() -> None:assert "QUALIFY" not in sql+ "query",+ [+ "SELECT user_id FROM users QUALIFY row_number() OVER (ORDER BY created_at) = 1",+ "SELECT user_id, row_number() OVER (ORDER BY created_at) AS rn FROM users QUALIFY rn = 1 AND id > 0",+ "SELECT user_id FROM users QUALIFY row_number() OVER (ORDER BY created_at) > 0 ORDER BY id LIMIT 1 BY user_id",+ "SELECT user_id, row_number() OVER (ORDER BY created_at) AS rn FROM users QUALIFY rn > 1 LIMIT 2 BY user_id LIMIT 3",+ "SELECT user_id FROM users ORDER BY row_number() OVER (ORDER BY created_at) LIMIT 1 BY user_id",+ "SELECT user_id, row_number() OVER (ORDER BY created_at) AS rn FROM users ORDER BY 2 LIMIT 1 BY user_id",+ "SELECT user_id, row_number() OVER (ORDER BY created_at) AS rn FROM users LIMIT 1 BY rn",+ ],+)+def test_lowers_staged_window_filters(query: str) -> None:+ sql, node = prepare_and_print_ast(parse_select(query), _context_with_trino_table(), "trino")+ assert "QUALIFY" not in sql+ assert "row_number() OVER" in sql+ assert isinstance(node, ast.SelectQuery)+ assert node.limit_by is None+ original = parse_select(query)+ assert isinstance(original, ast.SelectQuery)+ assert len(node.select) == len(original.select)+++ "operator",+ [+ "UNION ALL",+ "UNION DISTINCT",+ "INTERSECT",+ "INTERSECT ALL",+ "INTERSECT DISTINCT",+ "EXCEPT",+ "EXCEPT ALL",+ ],+)+def test_lowers_named_set_operations(operator: str) -> None:+ sql, _ = prepare_and_print_ast(+ parse_select(f"SELECT 1 AS first, 2 AS second {operator} BY NAME SELECT 2 AS second, 1 AS first"),+ _context_with_trino_table(),+ "trino",+ )+ assert "BY NAME" not in sql+ assert sql.count('1 AS "first", 2 AS "second"') == 2+++def test_folds_constant_row_counts() -> None:+ sql, _ = prepare_and_print_ast(+ parse_select("SELECT user_id FROM users LIMIT (2 + 3) * 2 OFFSET 3 - 1"),+ _context_with_trino_table(),+ "trino",+ )+ assert sql.endswith("OFFSET 2 ROWS LIMIT 10")+ sql, _ = prepare_and_print_ast(+ parse_select("SELECT user_id FROM users LIMIT 1 + 1 BY user_id"),+ _context_with_trino_table(),+ "trino",+ )+ assert "<= 2)" in sql++[email protected]("join", ["LEFT SEMI JOIN", "LEFT ANTI JOIN", "SEMI JOIN", "ANTI JOIN"])+def test_lowers_filter_joins(join: str) -> None:+ sql, _ = prepare_and_print_ast(+ parse_select(f"SELECT users.user_id FROM users {join} users AS other ON users.user_id = other.user_id"),+ _context_with_trino_table(),+ "trino",+ )+ assert "SEMI" not in sql+ assert "ANTI" not in sql+ assert 'SELECT DISTINCT "other"."user_id"' in sql+ if "ANTI" in join:+ assert '"other"."user_id" IS NULL' in sql++[email protected]("join", ["RIGHT ANY JOIN", "RIGHT SEMI JOIN", "RIGHT ANTI JOIN"])[email protected]("position", [1, 2])+def test_rejects_right_modes_in_join_chains(join: str, position: int) -> None:+ joins = ["INNER JOIN", "INNER JOIN"]+ joins[position - 1] = join+ query = (+ f"SELECT third.user_id FROM users {joins[0]} users AS other ON users.user_id = other.user_id "+ f"{joins[1]} users AS third ON other.user_id = third.user_id"+ )+ with pytest.raises(TrinoLoweringError, match="TRINO_RIGHT_JOIN_CHAIN_UNSUPPORTED"):+ prepare_and_print_ast(parse_select(query), _context_with_trino_table(), "trino")++[email protected]("join", ["RIGHT ANY JOIN", "RIGHT SEMI JOIN", "RIGHT ANTI JOIN"])+def test_lowers_right_join_by_reversing_inputs(join: str) -> None:+ sql, _ = prepare_and_print_ast(+ parse_select(f"SELECT other.user_id FROM users {join} users AS other ON users.user_id = other.user_id"),+ _context_with_trino_table(),+ "trino",+ )+ assert "RIGHT" not in sql+ assert "ANY" not in sql+ assert "SEMI" not in sql+ assert "ANTI" not in sql+++ ("join", "comparison", "expected"),+ [+ ("LEFT ASOF JOIN", "lhs.ts >= rhs.ts", [(5, 40), (5, 40), (7, None)]),+ ("LEFT ASOF JOIN", "rhs.ts <= lhs.ts", [(5, 40), (5, 40), (7, None)]),+ ("LEFT ASOF JOIN", "lhs.ts <= rhs.ts", [(5, 60), (5, 60), (7, None)]),+ ("LEFT ASOF JOIN", "rhs.ts >= lhs.ts", [(5, 60), (5, 60), (7, None)]),+ ("ASOF INNER JOIN", "lhs.ts >= rhs.ts", [(5, 40), (5, 40)]),+ ],+)+def test_asof_rewrite_preserves_duplicate_left_rows(+ join: str, comparison: str, expected: list[tuple[int, int | None]]+) -> None:+ query = (+ "WITH left_rows AS (SELECT 1 AS key, 5 AS ts UNION ALL SELECT 1, 5 UNION ALL SELECT 3, 7), "+ "right_rows AS (SELECT 1 AS key, 2 AS ts, 20 AS amount UNION ALL SELECT 1, 4, 40 UNION ALL SELECT 1, 6, 60) "+ f"SELECT lhs.ts, rhs.amount FROM left_rows lhs {join} right_rows rhs "+ f"ON lhs.key = rhs.key AND {comparison} ORDER BY lhs.ts"+ )+ context = _context_with_trino_table()+ sql, node = prepare_and_print_ast(parse_select(query), context, "trino")+ assert "ASOF" not in sql+ assert "row_number() OVER" in sql+ assert isinstance(node, ast.SelectQuery)+ assert node.type is not None+ assert list(node.type.columns) == ["ts", "amount"]+ sql, values = convert_pyformat_placeholders(sql, context.values)+ with duckdb.connect(":memory:", config={"threads": 1}) as connection:+ assert connection.execute(sql, values).fetchall() == expected++[email protected]("array", ["[1, 2]", "['a', 'b']", "[true, false]", "[NULL, 1]"])+def test_lowers_left_array_join_with_typed_default(array: str) -> None:+ sql, _ = prepare_and_print_ast(+ parse_select(f"SELECT item FROM users LEFT ARRAY JOIN {array} AS item"),+ _context_with_trino_table(),+ "trino",+ )+ assert "LEFT ARRAY JOIN" not in sql+ assert "CROSS JOIN UNNEST(CASE WHEN" in sql+ assert "cardinality(" in sql++[email protected]("include_nulls", [False, True])+def test_lowers_unpivot_to_single_scan(include_nulls: bool) -> None:+ modifier = " INCLUDE NULLS" if include_nulls else ""+ sql, node = prepare_and_print_ast(+ parse_select(f"SELECT * FROM users UNPIVOT{modifier}(value FOR key IN (user_id))"),+ _context_with_trino_table(),+ "trino",+ )+ assert "UNPIVOT" not in sql+ assert sql.count('"ducklake"."analytics"."users"') == 1+ assert "CROSS JOIN UNNEST(ARRAY[ROW(" in sql+ assert ("IS NOT NULL" in sql) is not include_nulls+ assert isinstance(node, ast.SelectQuery)+ assert node.type is not None+ assert "user_id" not in node.type.columns+ assert {"value", "key"} <= node.type.columns.keys()+++ ("query", "code"),+ [+ (+ "SELECT other.id FROM users LEFT SEMI JOIN users other ON users.id = other.id",+ "TRINO_FILTER_JOIN_RIGHT_OUTPUT_UNSUPPORTED",+ ),+ (+ "SELECT users.id FROM users RIGHT ANY JOIN users other ON users.id = other.id JOIN users third ON users.id = third.id",+ "TRINO_RIGHT_JOIN_CHAIN_UNSUPPORTED",+ ),+ (+ "SELECT users.id FROM users LEFT ASOF JOIN users other ON users.id = other.id",+ "TRINO_ASOF_CONSTRAINT_UNSUPPORTED",+ ),+ (+ "SELECT users.id FROM users LEFT ASOF JOIN users other ON users.id = other.id AND users.created_at >= other.created_at AND users.id > other.id",+ "TRINO_ASOF_CONSTRAINT_UNSUPPORTED",+ ),+ ("SELECT * FROM users PIVOT(sum(id) FOR user_id IN ('a', 'a'))", "TRINO_PIVOT_OUTPUT_COLLISION"),+ ("SELECT * FROM users UNPIVOT(value FOR key IN (id, user_id))", "TRINO_UNPIVOT_TYPE_UNSUPPORTED"),+ (+ "SELECT user_id FROM users QUALIFY row_number() OVER (ORDER BY id) > 0 ORDER BY id WITH FILL LIMIT 1 BY user_id",+ "TRINO_WITH_FILL_UNSUPPORTED",+ ),+ ],+)+def test_relational_rewrites_reject_unsafe_shapes(query: str, code: str) -> None:+ with pytest.raises(TrinoLoweringError, match=code):+ prepare_and_print_ast(parse_select(query), _context_with_trino_table(), "trino")+++def test_internal_array_join_without_from() -> None:+ query = parse_select("SELECT 1")+ assert isinstance(query, ast.SelectQuery)+ query.select = [ast.Field(chain=["item"])]+ query.array_join_op = "LEFT ARRAY JOIN"+ query.array_join_list = [ast.Alias(alias="item", expr=parse_expr("arrayFilter(value -> false, [1])"))]+ sql, _ = prepare_and_print_ast(query, _context_with_trino_table(), "trino")+ assert "FROM UNNEST(" in sql+ assert "ROW(0)" in sql+++def test_qualify_uses_the_resolved_field_not_a_matching_output_name() -> None:+ query = (+ "WITH rows AS (SELECT 1 AS id UNION ALL SELECT 2) "+ "SELECT lhs.id, row_number() OVER (ORDER BY lhs.id) AS rn FROM rows lhs "+ "JOIN rows rhs ON lhs.id + 1 = rhs.id QUALIFY rhs.id = 2"+ )+ context = _context_with_trino_table()+ sql, _ = prepare_and_print_ast(parse_select(query), context, "trino")+ sql, values = convert_pyformat_placeholders(sql, context.values)+ with duckdb.connect(":memory:") as connection:+ assert connection.execute(sql, values).fetchall() == [(1, 1)]++[email protected]("aggregate", ["count()", "sum(id)", "avg(id)", "min(id)", "max(id)"])[email protected]("group_by", ["", " GROUP BY created_at"])+def test_lowers_static_pivot(aggregate: str, group_by: str) -> None:+ context = _context_with_trino_table()+ sql, node = prepare_and_print_ast(+ parse_select(+ f"SELECT * FROM (SELECT user_id, id, created_at FROM users) "+ f"PIVOT({aggregate} FOR user_id IN ('a', 'b'){group_by})"+ ),+ context,+ "trino",+ )+ assert "PIVOT" not in sql+ assert sql.count("FILTER (WHERE") == 2+ assert 'AS "a"' in sql+ assert 'AS "b"' in sql+ assert isinstance(node, ast.SelectQuery)+ assert node.type is not None+ assert "user_id" not in node.type.columns+++ "percentage, offset, expected",+ [+ (50, 0, [(1,), (2,), (3,)]),+ (50, 1, [(2,), (3,), (4,)]),+ (1, 0, [(1,)]),+ (0, 0, []),+ (100, 0, [(1,), (2,), (3,), (4,), (5,)]),+ ],+)[email protected]("order_by", ["id", "1"])+def test_percentage_limit_rounds_up(percentage: int, offset: int, expected: list[tuple[int]], order_by: str) -> None:+ context = _context_with_trino_table()+ query = parse_select(+ f"WITH rows AS (SELECT 3 AS id UNION ALL SELECT 1 UNION ALL SELECT 5 UNION ALL SELECT 2 UNION ALL SELECT 4) "+ f"SELECT id FROM rows ORDER BY {order_by} LIMIT {percentage} OFFSET {offset}"+ )+ assert isinstance(query, ast.SelectQuery)+ query.limit_percent = True+ sql, _ = prepare_and_print_ast(query, context, "trino")+ sql, values = convert_pyformat_placeholders(sql, context.values)+ assert "PERCENT" not in sql+ assert "OVER (ORDER BY 1" not in sql+ with duckdb.connect(":memory:") as connection:+ assert connection.execute(sql, values).fetchall() == expected+++ ("query", "expected"),+ [+ (+ "WITH rows AS (SELECT 1 AS id, 'a' AS name UNION ALL SELECT 2, 'a' UNION ALL SELECT 3, 'b') "+ "SELECT name FROM rows QUALIFY row_number() OVER (ORDER BY id) > 1 ORDER BY id DESC LIMIT 1 BY name",+ [("b",), ("a",)],+ ),+ (+ "WITH rows AS (SELECT 1 AS id, 'a' AS name UNION ALL SELECT 2, 'a' UNION ALL SELECT 3, 'b') "+ "SELECT name FROM rows ORDER BY row_number() OVER (ORDER BY id DESC) LIMIT 1 BY name",+ [("b",), ("a",)],+ ),+ (+ "WITH rows AS (SELECT 1 AS id, 'a' AS name UNION ALL SELECT 2, 'a' UNION ALL SELECT 3, 'b') "+ "SELECT DISTINCT name FROM rows QUALIFY row_number() OVER (ORDER BY id) > 0 ORDER BY name",+ [("a",), ("b",)],+ ),+ (+ "WITH left_rows AS (SELECT 1 AS id UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT NULL), "+ "right_rows AS (SELECT 1 AS id UNION ALL SELECT 1 UNION ALL SELECT NULL) "+ "SELECT lhs.id FROM left_rows lhs LEFT SEMI JOIN right_rows rhs ON lhs.id = rhs.id",+ [(1,), (1,)],+ ),+ (+ "WITH left_rows AS (SELECT 1 AS id UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT NULL), "+ "right_rows AS (SELECT 1 AS id UNION ALL SELECT 1 UNION ALL SELECT NULL) "+ "SELECT lhs.id FROM left_rows lhs LEFT ANTI JOIN right_rows rhs ON lhs.id = rhs.id",+ [(2,), (None,)],+ ),+ (+ "SELECT 1 AS first, 2 AS second UNION ALL BY NAME SELECT 2 AS second, 1 AS first",+ [(1, 2), (1, 2)],+ ),+ ],+)+def test_relational_rewrites_preserve_results(query: str, expected: list[tuple[object, ...]]) -> None:+ context = _context_with_trino_table()+ sql, _ = prepare_and_print_ast(parse_select(query), context, "trino")+ sql, values = convert_pyformat_placeholders(sql, context.values)+ with duckdb.connect(":memory:") as connection:+ assert connection.execute(sql, values).fetchall() == expected+++ "query, expected",+ [+ (+ "SELECT sumOrNull(value), sumOrDefault(value), avgOrDefault(value), countOrNull(), minOrDefault(value) "+ "FROM (SELECT 1 value) WHERE false",+ [(None, 0, 0, None, 0)],+ ),+ (+ "SELECT sumOrNullIf(value, value > 5), sumOrDefaultIf(value, value > 5), countDistinctOrNullIf(value, value > 5) "+ "FROM (SELECT 1 value UNION ALL SELECT 2)",+ [(None, 0, None)],+ ),+ (+ "SELECT sumOrNullIf(value, value > 1) FILTER (WHERE value < 3), countOrDefault(value), countDistinctOrNull(value) "+ "FROM (SELECT 1 value UNION ALL SELECT 2 UNION ALL SELECT 2 UNION ALL SELECT 3)",+ [(4, 4, 3)],+ ),+ (+ "SELECT minOrDefault(value), maxOrNull(value) FROM (SELECT 'value' AS value) WHERE false",+ [("", None)],+ ),+ (+ "SELECT sumOrDefault(value) FROM (SELECT 1 / 2 AS value UNION ALL SELECT 3 / 2)",+ [(2.0,)],+ ),+ ],+)+def test_aggregate_combinators_preserve_empty_and_filtered_results(+ query: str, expected: list[tuple[object, ...]]+) -> None:+ context = _context_with_trino_table()+ sql, _ = prepare_and_print_ast(parse_select(query), context, "trino")+ sql, values = convert_pyformat_placeholders(sql, context.values)+ with duckdb.connect(":memory:") as connection:+ assert connection.execute(sql, values).fetchall() == expected++def test_lowers_window_count_distinct_without_unsupported_distinct_window_aggregate() -> None:context = _context_with_trino_table()@@ -683,6 +1615,27 @@ def test_set_operand_preserves_branch_local_cte_scope(branch_is_set: bool, brancassert "(SELECT * FROM (WITH " in sql+def test_aligns_string_and_uuid_set_columns_as_varchar() -> None:+ sql, _ = prepare_and_print_ast(+ parse_select("SELECT user_id AS value FROM users UNION ALL SELECT uuid AS value FROM users"),+ _context_with_trino_table(),+ "trino",+ )++ assert 'CAST("users"."user_id" AS VARCHAR)' in sql+ assert 'CAST("users"."uuid" AS VARCHAR)' in sql+++def test_casts_numeric_value_for_string_in_subquery() -> None:+ sql, _ = prepare_and_print_ast(+ parse_select("SELECT id FROM users WHERE id IN (SELECT user_id FROM users)"),+ _context_with_trino_table(),+ "trino",+ )++ assert 'CAST("users"."id" AS VARCHAR) IN (SELECT "users"."user_id"' in sql++def test_rejects_non_literal_trino_limit() -> None:query = parse_select("SELECT user_id FROM users")assert isinstance(query, ast.SelectQuery)@@ -721,7 +1674,7 @@ def test_rejects_with_fill_before_printing_invalid_trino_sql() -> None:("date_part('year', created_at)", 'EXTRACT(YEAR FROM "users"."created_at")'),("JSONExtractKeysAndValues(properties, 'Float64')",- 'map_entries(CAST(json_extract("users"."properties", %(hogql_val_0)s) AS MAP(VARCHAR, DOUBLE)))',+ 'map_entries(transform_values(CAST(json_extract("users"."properties", %(hogql_val_0)s) AS MAP(VARCHAR, JSON))',),("['a', 'b'][2:]", "slice(ARRAY[%(hogql_val_0)s, %(hogql_val_1)s], 2, 2147483647)"),],@@ -736,10 +1689,294 @@ def test_prints_additional_semantics_safe_trino_expressions(expression: str, expassert expected in sql+ "expression, expected",+ [+ ("sumArray([1, 2])", "CAST(0 AS BIGINT)"),+ ("sumArgMin(3, 1)", "__hogql_arg_row[2] = __hogql_extreme"),+ ("maxArgMax('value', 2)", "array_max(transform(__hogql_value_rows"),+ ("countArgMin(1)", "array_agg(ROW(1, 1))"),+ ("countArgMinOrNull(NULL, 1)", "IF(cardinality(__hogql_value_rows) = 0, NULL"),+ ("countDistinctArgMinOrNull(NULL, 1)", "IF(cardinality(__hogql_value_rows) = 0, NULL"),+ ("avgArgMaxOrDefaultIf(3, 1, false)", "FILTER (WHERE (false))"),+ ("sumArgMin(1, 0.0 / 0.0)", "NaN selection keys are not supported"),+ ("minArgMin(0.0 / 0.0, 1)", "NaN argument-selection values are not supported"),+ ("medianExact(1)", "IF(cardinality(__hogql_quantile_values) = 0, 0"),+ ("medianExactLow(1)", "ceil(0.5 * cardinality(__hogql_quantile_values))"),+ ("medianExactHigh(1)", "floor(0.5 * cardinality(__hogql_quantile_values))"),+ ("medianExact(0.0 / 0.0)", "NOT is_nan(__hogql_quantile_value)"),+ ("quantileExact(0.5)(1.0)", "IF(cardinality(__hogql_quantile_values) = 0, nan()"),+ ("avgWeighted(1.5, 2)", "CAST(truncate(__hogql_pair[1]) AS BIGINT)"),+ ("avgWeighted(1, 2.0)", "ROW(numerator DOUBLE, denominator DOUBLE)"),+ ("avgWeightedIf(1, 2.0, false)", "FILTER (WHERE (false))"),+ ("skewPopIf(1, false)", "__hogql_state[4]"),+ ("skewSamp(1)", "__hogql_state[1] - 1e0"),+ ("kurtPop(1)", "__hogql_state[5]"),+ ("kurtSampIf(1, false)", "FILTER (WHERE (false))"),+ ("simpleLinearRegression(1, 2)", "ROW(n DOUBLE, sx DOUBLE, sy DOUBLE, sxx DOUBLE, sxy DOUBLE)"),+ ("locate('ç', 'éç', 2)", "to_hex(to_utf8(__hogql_locate[2]))"),+ ("hasSubsequence('abc', 'ac')", "__hogql_position + __hogql_relative"),+ ("hasSubsequenceCaseInsensitive('AbÇ', 'aBç')", "'ABCDEFGHIJKLMNOPQRSTUVWXYZ'"),+ ("hasSubsequenceUTF8('aéç', 'aç')", "regexp_extract_all(__hogql_subsequence[1], '(?s).')"),+ (+ "hasSubsequenceCaseInsensitiveUTF8('AbÇ', 'aBç')",+ "UTF-8 case conversion with a different byte length is not supported",+ ),+ (+ "countSubstringsCaseInsensitiveUTF8('ÄäA', 'ä', 1)",+ "length(to_utf8(lower(__hogql_character)))",+ ),+ ("splitByNonAlpha('é_foo-你好-42')", "'[\\p{L}\\p{N}]+'"),+ ("alphaTokens('é_foo-你好-42', 1)", "'[A-Za-z]+'"),+ ("tokens('é_foo-你好-42')", "'[\\p{L}\\p{N}]+'"),+ (+ "queryStringAndFragment('https://example.com/p?x#f')",+ "concat(coalesce(regexp_extract(split_part(__hogql_url, '#', 1), '\\?(.*)$', 1), ''), '#',",+ ),+ ("pathFull('https://example.com/p?#f')", "strpos(split_part(__hogql_url, '#', 1), '?') > 0"),+ ("btrim('xyxabcxy', 'xy')", "trim("),+ ("translateUTF8('héllo', 'élo', 'ÉXY')", "translate("),+ ("toNullableString(1)", "CAST(1 AS VARCHAR)"),+ ("extractURLParameters('/p?x=a%20b&flag')", "split(coalesce(regexp_extract("),+ ("extractURLParameterNames('/p?x=a%20b&flag')", "split_part(__hogql_parameter, '=', 1)"),+ ("defaultValueOfTypeName('UInt64')", "CAST(0 AS DECIMAL(20, 0))"),+ ("defaultValueOfTypeName('Array(Int64)')", "CAST(ARRAY[] AS ARRAY(BIGINT))"),+ ("groupUniqArrayArray([1, 2])", "array_distinct(filter(flatten(__hogql_arrays)"),+ ("groupUniqArrayArrayIf(1)([1, 2], false)", "slice(array_distinct("),+ ("groupArrayMovingSumIf(1, false)", "ROW(total BIGINT, items ARRAY(BIGINT))"),+ ("groupArrayMovingAvg(1)", "__hogql_total / cardinality(__hogql_moving_values)"),+ ("xor(1, 0, 1)", "reduce(ARRAY[CAST(1 AS BOOLEAN), CAST(0 AS BOOLEAN), CAST(1 AS BOOLEAN)]"),+ ("throwIf(0, 'stop')", "IF(CAST(0 AS BOOLEAN), fail("),+ ("isValidUTF8('abc')", "IS NULL, NULL, true"),+ ("regexpQuoteMeta('a.b')", "regexp_replace("),+ ("encodeURLFormComponent('a b')", "url_encode("),+ ("decodeURLFormComponent('a+b')", "url_decode("),+ ("isIPv4String('1.2.3.4')", "all_match(transform(split(__hogql_ip, '.')"),+ ("isIPv6String('::1')", "TRY_CAST(__hogql_ip AS IPADDRESS) IS NOT NULL"),+ ("isIPAddressInRange('1.2.3.4', '1.2.3.0/24')", "contains("),+ ("IPv4StringToNum('1.2.3.4')", "__hogql_total * 256 + __hogql_octet"),+ ("IPv4StringToNumOrDefault('bad')", "IF(regexp_like(__hogql_ip"),+ ("IPv4StringToNumOrNull('bad')", ", NULL)"),+ ("IPv4NumToString(16909060)", "array_join(transform(ARRAY[24, 16, 8, 0]"),+ ("to_timestamp(1704164645)", "CAST(from_unixtime(CAST(1704164645 AS DOUBLE)) AS TIMESTAMP)"),+ ("timeStampAdd(toDateTime('2024-01-02'), toIntervalDay(2))", " + "),+ ("timeStampSub(toDateTime('2024-01-02'), toIntervalHour(2))", " - "),+ ("timeSlot(toDateTime('2024-01-02 03:14:59'))", "-mod(minute("),+ ("toTime(toDateTime('2024-01-02 03:14:59'))", "TIMESTAMP '1970-01-02 00:00:00'"),+ ("timeSlots(toDateTime('2024-01-02 03:14:59'), 3600)", "BIGINT '1800'"),+ ("regexpExtract('abc123', '([a-z]+)([0-9]+)', 2)", "regexp_extract("),+ ("extractGroups('a1', '([a-z])([0-9])')", "IS NULL, ARRAY[], ARRAY["),+ ("extractAllGroupsVertical('a1 b2', '([a-z])([0-9])')", "__hogql_index -> ARRAY["),+ ("extractAllGroupsHorizontal('a1 b2', '([a-z])([0-9])')", "ARRAY[transform("),+ ("initcap('foo-bar_bAZ 123abc')", "ROW(at_word_start BOOLEAN, value VARCHAR)"),+ ("dateName('weekday', toDateTime('2024-01-02'))", "date_format(CAST("),+ (+ "date_bin(toIntervalMinute(15), toDateTime('2024-01-02 03:14:59'), toDateTime('2024-01-02 00:07:00'))",+ "date_diff('second', __hogql_date_bin[2], __hogql_date_bin[1]) / 900e0",+ ),+ ("hasToken('foo bar', 'bar')", "regexp_like(__hogql_token_args[1], concat("),+ ("hasTokenOrNull('foo', 'f.o')", "NULL"),+ ("hasTokenCaseInsensitive('Foo BAR', 'bar')", "translate(__hogql_token_args[1]"),+ ("hasTokenCaseInsensitiveOrNull('FOO', 'f_o')", "^[A-Za-z0-9\\P{ASCII}]+$"),+ ("netloc('https://u:[email protected]:8080/a')", "(?:[A-Za-z][A-Za-z0-9+.-]*:)?//"),+ ("URLHierarchy('https://example.com/a/b?x=1#f')", "__hogql_position IN"),+ ("URLPathHierarchy('https://example.com/a/b?x=1#f')", "__hogql_position - length(__hogql_authority)"),+ ("cutURLParameter('https://example.com/p?x=1&y=2', 'x')", "__hogql_match_position"),+ ("encodeXMLComponent('<a&b>')", "'''"),+ ("decodeXMLComponent('<A>')", "__hogql_xml_entity -> chr("),+ ("JSONType('{\"x\": 1}', 'x')", "WHEN __hogql_json_type IN ('true', 'false')"),+ (+ "UUIDv7ToDateTime(toUUID('01a09219-c11f-7429-a26e-794d5a382dd4'))",+ "from_base(substr(replace(CAST(",+ ),+ ("make_timestamp(2024, 1, 2, 3, 4, 5.25)", "CAST(truncate(5.25) AS BIGINT)"),+ (+ "make_timestamptz(2024, 1, 2, 3, 4, 5, 'America/New_York')",+ "with_timezone(IF(TRY_CAST(format(",+ ),+ ("sortablesemver('v1.2.3-beta')", "ARRAY[CAST(NULL AS BIGINT)]"),+ ("pointInEllipses(5.0, 5.0, 0.0, 0.0, 1.0, 1.0, 5.0, 5.0, 2.0, 2.0)", " OR power(("),+ ("ifNotFinite(0.0 / 0.0, 9.0)", "IF(is_finite(CAST("),+ ("ngrams('hello', 2)", "substr(__hogql_ngram_args[1], __hogql_position"),+ ("hasAllTokens('foo bar', ['foo', 'bar'])", "all_match(__hogql_token_array_args[2]"),+ ("hasAnyTokens('foo bar', ['x', 'bar'])", "any_match(__hogql_token_array_args[2]"),+ ("mapPopulateSeries(map(1, 10, 3, 30), 5)", "map_from_entries(transform("),+ ("extractIPv4Substrings('a 1.2.3.4 b 999.2.3.4')", "25[0-5]"),+ ("indexHint(1 = 1)", "SELECT 1"),+ ("accurateCast(255, 'UInt8')", "DECIMAL '255'"),+ ("accurateCastOrNull(1.5, 'Int64')", "= truncate("),+ ("base58Encode('PostHog')", "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),+ ("bar(5.5, 0, 10, 10)", "substr('▏▎▍▌▋▊▉'"),+ ("toIPv4('01.2.3.4')", "CAST(array_join(transform(ARRAY[24, 16, 8, 0]"),+ ("toIPv4(16909060)", "__hogql_ipv4 BETWEEN 0 AND 4294967295"),+ ("toIPv4OrDefault('bad', toIPv4('5.6.7.8'))", "fail('Invalid IPv4 address')"),+ ("toIPv4OrNull('bad')", "CAST(NULL AS IPADDRESS)"),+ ("toIPv4OrZero('bad')", "CAST('0.0.0.0' AS IPADDRESS)"),+ ("IPv4CIDRToRange(toIPv4('192.0.2.129'), 24)", "IPv4 CIDR prefix must be between 0 and 32"),+ ("format('{{}} {}', 12, 99)", "CAST(12 AS VARCHAR)"),+ ("ngramDistanceCaseInsensitive('ABCdef', 'bcDE')", "translate(CAST("),+ ("ngramDistanceUTF8('abcdef', 'bcde')", "MAP(VARCHAR, BIGINT)"),+ ("ngramSearch('abcdef', 'bcde')", "map_values(__hogql_ngram_maps[2])"),+ ("ngramSearchCaseInsensitive('ABCdef', 'bcDE')", "least("),+ ("ngramSearchUTF8('abcdef', 'abcf')", "substr(__hogql_ngram_args[1], __hogql_left_index, 3)"),+ ("timeZoneOffset(toDateTime('2024-01-01', 'America/New_York'))", "timezone_hour("),+ ("toWeek(toDate('2018-12-31'), 3)", "CASE __hogql_week[2]"),+ ("toYearWeek(toDate('2018-12-31'), 3)", "year(__hogql_week[1]) * 100"),+ ("to_char(toDateTime('2024-05-17 12:34:56'), '%Y-%m-%d')", "date_format("),+ ("toStartOfISOYear(toDate('2018-12-31'))", "year_of_week("),+ ("toStartOfWeek(toDate('2024-01-03'), 8)", "date_add('day', -1, date_trunc('week'"),+ ("toStartOfWeek(toDate('2024-01-03'), 9)", "date_trunc('week'"),+ ("formatReadableSize(1536)", "ARRAY['B', 'KiB', 'MiB'"),+ ("formatReadableDecimalSize(1500)", "ln(1000e0)"),+ ("formatReadableQuantity(1234567)", "'vigintillion'"),+ ("roundToExp2(7)", "reduce(sequence(0, 62), BIGINT '0'"),+ ("roundToExp2(-7.5)", "sign(__hogql_round_to_exp2) * power(2e0"),+ ("gcd(-48, 18)", "mod(__hogql_state[1], __hogql_state[2])"),+ ("lcm(-21, 6)", "abs(__hogql_integer_pair[1] /"),+ ("arrayAUC([0.1, 0.4, 0.35, 0.8], [0, 0, 1, 1])", "group_positive BIGINT"),+ ("maxIntersections(1, 2)", "maximum_count BIGINT"),+ ("maxIntersectionsIf(1, 2, false)", "FILTER (WHERE (false))"),+ ("maxIntersectionsPosition(1, 2)", "__hogql_intersection_state[3]"),+ ("maxIntersectionsPositionIf(1, 2, false)", "__hogql_intersection_state[3]"),+ ("medianExactWeighted(3, 2)", "ROW(total BIGINT, cumulative ARRAY(BIGINT))"),+ ("medianExactWeightedIf(3, 2, false)", "FILTER (WHERE (false))"),+ ("quantiles(0, 0.5, 1)(3)", "ARRAY[DOUBLE '0', DOUBLE '0.5', DOUBLE '1']"),+ ("quantilesIf(0.5)(3, false)", "FILTER (WHERE (false))"),+ ("deltaSumIf(3, false)", "ROW(seen BOOLEAN, previous BIGINT, total BIGINT)"),+ ("groupArrayInsertAtIf('x', 2, false)", "__hogql_row[2] = __hogql_position"),+ ("sumForEach([1, 2])", "cardinality(__hogql_row) >= __hogql_position"),+ ("avgForEachOrNullIf([1, NULL], 0)", "FILTER (WHERE (CAST(0 AS BOOLEAN)))"),+ ("countDistinctMap(map('a', 1))", "cardinality(array_distinct(__hogql_values))"),+ ("minMapOrDefault(map('a', 'value'))", "coalesce(array_min(__hogql_values), '')"),+ ("arrayReduce('sum', [1, 2])", "CAST(0 AS BIGINT)"),+ ("arrayReduce('sumMap', [map('a', 1), map('a', 2)])", "map_from_entries(transform("),+ ("arrayCumSum([1, -3, 2])", "ROW(total BIGINT, items ARRAY(BIGINT))"),+ ("arrayCumSumNonNegative([1, -3, 2])", "greatest(__hogql_scan_state[1] + __hogql_item, 0)"),+ ("arrayCumSum(value -> value / 2, [1, 2])", "ROW(total DOUBLE, items ARRAY(DOUBLE))"),+ ("arrayResize(arrayCumSum(value -> value / 2, [1, 2]), 4)", "repeat(DOUBLE '0',"),+ ("arrayFill(value -> value > 0, [0, 1, 0])", "element_at(__hogql_filled, -1)"),+ ("arrayReverseFill(value -> value > 0, [0, 1, 0])", "reverse(reduce(reverse(zip("),+ ("arraySplit(value -> value > 0, [0, 1, 0])", "element_at(__hogql_flags, __hogql_position)"),+ ("arrayReverseSplit(value -> value > 0, [0, 1, 0])", "element_at(__hogql_flags, __hogql_position - 1)"),+ ("L1Normalize((3, 4))", "element_at(__hogql_vectors[1], 2) / __hogql_norm"),+ ("L2Normalize((3, 4))", "__hogql_vectors[2]"),+ ("LinfNormalize((3, 4))", "array_max(transform("),+ ("LpNormalize((3, 4), 2)", "Lp exponent must be at least one and not infinite"),+ ("LpNorm([3, 4], 2)", "power(reduce("),+ ("LpNorm([3, 4], 0.0 / 0.0)", "is_nan(CAST(__hogql_vectors[2] AS DOUBLE))"),+ ("tuplePlus(L2Normalize((3, 4)), (1, 2))", "(__hogql_tuple_args[1][2] + __hogql_tuple_args[2][2])"),+ ("LpDistance((3, 4), (0, 0), 2)", "LpDistance requires equal vector lengths"),+ ("roundDown(7, [10, 0, 5])", "roundDown requires a non-empty boundary array"),+ ("roundDown(0.0 / 0.0, [0, 1, 5])", "IF(is_nan(CAST(__hogql_round[1] AS DOUBLE)), __hogql_round[1]"),+ ("roundAge(17)", "WHEN __hogql_age < 18 THEN 17"),+ ("roundDuration(15)", "WHEN __hogql_duration < 36000 THEN 18000"),+ ("factorial(20)", "2432902008176640000"),+ ("factorial(NULL)", "transform(ARRAY[NULL], __hogql_factorial"),+ ("avgArrayIf([1, 2], 1)", "FILTER (WHERE (CAST(1 AS BOOLEAN)))"),+ ("minArrayOrNullIf([1], false)", "IF(count(ARRAY[1]) FILTER (WHERE (false)) = 0, NULL"),+ ("countDistinctArray([1, 1, 2])", "cardinality(array_distinct(__hogql_values))"),+ ("arrayLast(value -> value > 1, [1, 2])", 'element_at(filter(ARRAY[1, 2], "value" -> ("value" > 1)), -1)'),+ ("arrayResize([1], 3)", "repeat(0,"),+ ("arrayResize([[1]], 3)", "repeat(ARRAY[],"),+ ("arrayResize([1, NULL], 3)", "element_at(ARRAY[1, NULL], cardinality(ARRAY[1, NULL]) + 1)"),+ ("tuplePlus((1, 2), (3, 4))", "(__hogql_tuple_args[1][2] + __hogql_tuple_args[2][2])"),+ ("tupleToNameValuePairs((1, 2))", "__hogql_named_tuple[2]"),+ ("tupleDivide((1, 2), (3, 4))", "CAST(__hogql_tuple_args[1][1] AS DOUBLE)"),+ ("tupleNegate(tuplePlus((1, 2), (3, 4)))", "(-__hogql_tuple_args[1][2])"),+ (+ "tupleHammingDistance((1, NULL), (2, NULL))",+ "CAST(__hogql_tuple_args[1][2] != __hogql_tuple_args[2][2] AS BIGINT)",+ ),+ ("multiSearchAllPositions('éx', ['x'])", "length(to_utf8(substr("),+ ("multiSearchFirstIndexUTF8('abc', ['c', 'a'])", "array_position(transform("),+ ("multiSearchFirstPositionUTF8('abc', ['c', 'a'])", "coalesce(array_min(filter("),+ (+ "multiSearchAnyCaseInsensitiveUTF8('İ', ['i'])",+ "UTF-8 case conversion with a different byte length is not supported",+ ),+ ],+)+def test_prints_type_aware_and_search_rewrites(expression: str, expected: str) -> None:+ sql, _ = prepare_and_print_ast(parse_select(f"SELECT {expression}"), _context_with_trino_table(), "trino")+ assert expected in sql+++ ("expression", "expected"),+ [+ ("arrayStringConcat(['a', 'b'])", "array_join(ARRAY["),+ ("endsWith(user_id, '1')", "substr("),+ ("appendTrailingCharIfAbsent(user_id, '/')", "substr("),+ ("tryBase64Decode(user_id)", "mod(length("),+ ("reinterpretAsUUID(id)", "format('%016x0000000000000000'"),+ ("cutToFirstSignificantSubdomain(user_id)", "cardinality("),+ ("path(user_id)", "strpos("),+ ("pathFull(user_id)", "strpos(__hogql_url, '/') = 0"),+ ("indexHint(id)", "SELECT 1 FROM"),+ ("JSONExtractInt(user_id)", "coalesce(TRY(CAST(json_extract_scalar("),+ ("JSONExtractKeys(user_id)", "coalesce(TRY(map_keys("),+ ("JSON_VALUE(user_id, '$.key')", "coalesce(TRY(json_value("),+ ("make_date(2, 2, 2)", "DATE '1970-01-01'"),+ ("make_timestamp(2, 2, 2, 2, 2, 2)", "TIMESTAMP '1970-01-01 00:00:00'"),+ ("stddevSamp(id)", "coalesce(stddev_samp("),+ ("toStartOfYear(created_at)", "CAST(date_trunc('year'"),+ (+ "mapApply((key, value) -> (concat(key, 'x'), value + 1), map('a', 1))",+ "map_from_entries(transform(map_entries(transform_values(",+ ),+ ("percentile_cont(0.5) WITHIN GROUP (ORDER BY id)", "__hogql_percentile_values"),+ ("percentile_disc(0.5) WITHIN GROUP (ORDER BY id)", "greatest(CAST(ceil("),+ ],+)+def test_prints_live_parity_regressions(expression: str, expected: str) -> None:+ sql, _ = prepare_and_print_ast(+ parse_select(f"SELECT {expression} FROM users"), _context_with_trino_table(), "trino"+ )+ assert expected in sql+++def test_preserves_legacy_clickhouse_array_reverse_sort_mapping() -> None:+ context = _context_with_trino_table()+ context.team_id = 1+ sql = print_prepared_ast(+ resolve_types(parse_select("SELECT arrayReverseSort([3, 1, 2]) AS values"), context, "clickhouse"),+ context,+ "clickhouse",+ )+ assert "arraySort([3, 1, 2])" in sql+++ "name",+ sorted(name for name in TRINO_AGGREGATE_COMBINATORS if name.startswith("median")),+)[email protected]("window", ["", " OVER ()"], ids=["aggregate", "window"])+def test_prints_all_median_aggregate_combinators(name: str, window: str) -> None:+ _, mode, _, conditional = TRINO_AGGREGATE_COMBINATORS[name]+ canonical_name = next(candidate for candidate in HOGQL_AGGREGATIONS if candidate.lower() == name)+ if mode in {"Array", "ForEach"}:+ args = ["[1.0, 2.0]"]+ elif mode == "Map":+ args = ["map('a', 1.0)"]+ elif mode in {"ArgMin", "ArgMax"}:+ args = ["1.0", "1"]+ else:+ args = ["1.0"]+ if conditional:+ args.append("true")++ sql, _ = prepare_and_print_ast(+ parse_select(f"SELECT {canonical_name}({', '.join(args)}){window}"), _context_with_trino_table(), "trino"+ )++ assert "array_sort(" in sql+ assert "median(" not in sql.lower()++@pytest.mark.parametrize(("expression", "expected"),[- ("endsWith(user_id, '1')", 'ends_with("users"."user_id", %(hogql_val_0)s)'),+ ("endsWith(user_id, '1')", 'substr("users"."user_id", -length(%(hogql_val_0)s)) = %(hogql_val_0)s'),("mapFromArrays(['a'], [1])", "map(ARRAY[%(hogql_val_0)s], ARRAY[1])"),("mapUpdate(mapFromArrays(['a'], [1]), mapFromArrays(['a'], [2]))",@@ -815,6 +2052,61 @@ def test_prints_additional_semantics_safe_trino_expressions(expression: str, exp("lpad(user_id, 3, '0')", 'lpad("users"."user_id", 3,'),("rpad(user_id, 3, '0')", 'rpad("users"."user_id", 3,'),("e()", "e()"),+ ("toIntervalDay(2)", "(CAST(2 AS BIGINT) * INTERVAL '1' DAY)"),+ ("JSONExtractArrayRaw(properties, 'items')", "transform(CAST(json_extract("),+ ("user_id IN ['a', 'b']", '"users"."user_id" IN ('),+ ("toDateTime(123)", "CAST(from_unixtime(CAST(123 AS DOUBLE)) AS TIMESTAMP)"),+ ("arrayMax([1, 2])", "array_max(ARRAY[1, 2])"),+ (+ "arrayLastIndex(x -> x = 'blue', ['red', 'blue', 'green', 'blue'])",+ "reduce(transform(ARRAY[%(hogql_val_0)s, %(hogql_val_1)s, %(hogql_val_2)s, %(hogql_val_3)s],",+ ),+ ("arraySum([1, 2])", "reduce(ARRAY[1, 2], CAST(0 AS DOUBLE)"),+ ("coalesce(nullIf(true, 0), false)", "coalesce(nullif(CAST(true AS INTEGER), 0), CAST(false AS INTEGER))"),+ ("not(2)", "NOT CAST(2 AS BOOLEAN)"),+ ("JSONHas(properties, user_id)", 'json_format(CAST(CAST("users"."user_id" AS VARCHAR) AS JSON))'),+ ("JSONExtractString(properties)", 'json_extract_scalar("users"."properties",'),+ ("created_at + 2", "date_add('second', CAST(2 AS BIGINT)"),+ ("['a'][3]", "element_at(ARRAY[%(hogql_val_0)s], 3)"),+ ("divideDecimal(toDecimal(1, 10), toDecimal(100, 10))", "(CAST(1 AS DECIMAL(38, 10)) /"),+ (+ "divideDecimal(toDecimal(1, 10), toDecimal(100, 10), 4)",+ "AS DECIMAL(38, 4))",+ ),+ ("arrayAll(x -> x > 0, [1, 2])", 'all_match(ARRAY[1, 2], "x" -> ("x" > 0))'),+ (+ "arrayIntersect([1, 2], [2, 3], [2, 4])",+ "array_intersect(array_intersect(array_distinct(ARRAY[1, 2]), ARRAY[2, 3]), ARRAY[2, 4])",+ ),+ (+ "positionCaseInsensitive(user_id, 'A', 2)",+ 'CASE WHEN strpos(lower(substr("users"."user_id", 2)), lower(%(hogql_val_0)s)) = 0 THEN 0',+ ),+ ("cutFragment(user_id)", "regexp_replace(\"users\".\"user_id\", '#.*$', '')"),+ (+ "cutQueryStringAndFragment(user_id)",+ "regexp_replace(\"users\".\"user_id\", '[?#].*$', '')",+ ),+ ("cutQueryString(user_id)", "regexp_replace(\"users\".\"user_id\", '\\?.*$', '')"),+ ("path(user_id)", 'url_extract_path("users"."user_id")'),+ ("decodeURLComponent(user_id)", 'url_decode("users"."user_id")'),+ ("trimLeft(user_id)", 'ltrim("users"."user_id")'),+ ("trimRight(user_id)", 'rtrim("users"."user_id")'),+ ("toFloatOrNull(user_id)", 'TRY_CAST("users"."user_id" AS DOUBLE)'),+ ("_toInt16(12)", "CAST(12 AS SMALLINT)"),+ ("to_date(created_at)", 'CAST("users"."created_at" AS DATE)'),+ ("map('key', 1)", "map(ARRAY[%(hogql_val_0)s], ARRAY[1])"),+ (+ "transform(user_id, ['a'], ['A'], 'other')",+ 'CASE WHEN contains(ARRAY[%(hogql_val_0)s], "users"."user_id") '+ "THEN element_at(ARRAY[%(hogql_val_1)s], array_position(",+ ),+ ("first_value(user_id)", 'arbitrary("users"."user_id")'),+ (+ "toStartOfDay(created_at, 'America/Toronto')",+ "date_trunc('day', at_timezone(with_timezone(CAST(",+ ),+ ("like(user_id, '%example')", '("users"."user_id" LIKE %(hogql_val_0)s)'),],)def test_prints_safe_pr_91053_function_mappings(expression: str, expected: str) -> None:@@ -834,7 +2126,9 @@ def test_prints_typed_json_map_and_trino_try_cast() -> None:sql, _ = prepare_and_print_ast(query, _context_with_trino_table(), "trino")- assert "AS MAP(VARCHAR, DOUBLE))" in sql+ assert "AS MAP(VARCHAR, JSON))" in sql+ assert "TRY_CAST(__hogql_json_value AS DOUBLE)" in sql+ assert "CAST(0 AS DOUBLE)" in sqlassert 'TRY_CAST("users"."user_id" AS BIGINT)' in sql@@ -860,13 +2154,22 @@ def test_rejects_map_from_arrays_with_duplicate_keys() -> None:assert error.value.feature_code == "TRINO_MAP_DUPLICATE_KEYS_UNSUPPORTED"+def test_guards_dynamic_map_from_arrays_without_discarding_keys() -> None:+ sql, _ = prepare_and_print_ast(+ parse_select("SELECT mapFromArrays([user_id, user_id], [1, 2]) FROM users"),+ _context_with_trino_table(),+ "trino",+ )++ assert "all_match(__hogql_args[1], __hogql_key -> __hogql_key IS NOT NULL)" in sql+ assert "cardinality(array_distinct(__hogql_args[1])) = cardinality(__hogql_args[1])" in sql+ assert "map(__hogql_args[1], __hogql_args[2])" in sql+ assert "fail('mapFromArrays requires equal-length arrays with unique, non-null keys')" in sql++@pytest.mark.parametrize("expression",[- "formatReadableTimeDelta(1)",- "intDiv(5, 2)",- "medianIf(1, true)",- "multiplyDecimal(1, 2)","_toInt16(40000)",],)@@ -896,6 +2199,34 @@ def test_rejects_trino_identifiers_that_can_collide_with_parameter_binding(ident"countIf(user_id != '') OVER ()",'count_if(("users"."user_id" != %(hogql_val_0)s)) OVER ()',),+ (+ "stddevPopIf(length(user_id), length(user_id) > 1) OVER ()",+ 'stddev_pop(IF((length("users"."user_id") > 1), length("users"."user_id"), NULL)) OVER ()',+ ),+ (+ "quantileExactIf(0.5)(length(user_id), length(user_id) > 1) OVER ()",+ "filter(coalesce(array_agg(IF(",+ ),+ ("medianExactLow(length(user_id)) OVER ()", "ceil(0.5 * cardinality(__hogql_quantile_values))"),+ ("medianExactHighIf(length(user_id), id > 1) OVER ()", "OVER ()"),+ ("sumArgMin(id, created_at) OVER ()", 'array_agg(ROW("users"."id", "users"."created_at")) OVER ()'),+ ("countArgMaxOrNullIf(id, created_at, id > 1) OVER ()", 'array_agg(IF((("users"."id" > 1)), ROW('),+ ("sumForEach([id]) OVER ()", 'array_agg(ARRAY["users"."id"]) OVER ()'),+ ("avgArrayOrNull([id]) OVER ()", 'count(ARRAY["users"."id"]) OVER ()'),+ ("avgArray([id]) OVER ()", "IF(cardinality(__hogql_values) = 0, nan()"),+ ("sumMap(map('a', id)) OVER ()", "map_from_entries(transform("),+ ("avgWeighted(id, 1.0) OVER ()", 'array_agg(ROW("users"."id", 1.0)) OVER ()'),+ ("skewPopIf(id, id > 1) OVER ()", 'array_agg(IF((("users"."id" > 1)), CAST('),+ ("simpleLinearRegression(id, id * 2) OVER ()", "__hogql_state[5] * __hogql_state[1]"),+ ("groupUniqArrayArrayIf([id], id > 1) OVER ()", 'array_agg(IF((("users"."id" > 1)), ARRAY['),+ ("groupArrayMovingSumIf(id, id > 1) OVER ()", 'array_agg(IF((("users"."id" > 1)), CAST('),+ ("groupArrayMovingAvg(id) OVER ()", "ROW(total DOUBLE, items ARRAY(DOUBLE))"),+ ("medianExactWeightedIf(id, 2, id > 1) OVER ()", "__hogql_weights[2]"),+ ("quantilesIf(0, 0.5, 1)(id, id > 1) OVER ()", "approx_percentile("),+ ("deltaSumIf(id, id > 1) OVER ()", 'array_agg(IF((("users"."id" > 1)), CAST('),+ ("groupArrayInsertAtIf(id, id, id > 1) OVER ()", "__hogql_insert_rows"),+ ("maxIntersectionsIf(id, id + 2, id > 1) OVER ()", "__hogql_intersection_state[2]"),+ ("maxIntersectionsPosition(id, id + 2) OVER ()", "__hogql_intersection_state[3]"),],)def test_prints_semantics_safe_trino_window_functions(expression: str, expected: str) -> None:@@ -908,6 +2239,96 @@ def test_prints_semantics_safe_trino_window_functions(expression: str, expected:assert expected in sql+ ("expression", "expected"),+ [+ ("uniqExact(user_id) OVER ()", 'count(DISTINCT "users"."user_id") OVER ()'),+ (+ "uniqExactIf(user_id, length(user_id) > 1) OVER ()",+ 'count(DISTINCT IF((length("users"."user_id") > 1), "users"."user_id", NULL)) OVER ()',+ ),+ ],+)+def test_prints_distinct_trino_window_functions(expression: str, expected: str) -> None:+ sql, _ = prepare_and_print_ast(+ parse_select(f"SELECT {expression} FROM users"),+ _context_with_trino_table(),+ "trino",+ )++ assert expected in sql+++ ("expression", "expected"),+ [+ (+ "formatDateTime(created_at, '%Y-%m-%d', 'UTC')",+ 'date_format(at_timezone(with_timezone(CAST("users"."created_at" AS TIMESTAMP), \'UTC\'),',+ ),+ (+ "toDateTime64('2026-01-02 03:04:05', 3, 'UTC')",+ "with_timezone(CAST(%(hogql_val_0)s AS TIMESTAMP(3)), %(hogql_val_1)s)",+ ),+ (+ "topK(2)(user_id)",+ 'transform(slice(array_sort(map_entries(histogram("users"."user_id"))',+ ),+ ],+)+def test_prints_extended_trino_function_forms(expression: str, expected: str) -> None:+ sql, _ = prepare_and_print_ast(+ parse_select(f"SELECT {expression} FROM users"),+ _context_with_trino_table(),+ "trino",+ )++ assert expected in sql+++def test_unqualifies_order_by_when_output_alias_shadows_relation_name() -> None:+ sql, _ = prepare_and_print_ast(+ parse_select(+ "WITH runs AS (SELECT created_at AS day FROM users) "+ "SELECT runs.day AS day, count() AS runs FROM runs GROUP BY day ORDER BY day DESC, runs DESC"+ ),+ _context_with_trino_table(),+ "trino",+ )++ assert "ORDER BY 1 DESC, 2 DESC" in sql+++def test_lowers_offset_in_frame_over_a_full_partition() -> None:+ sql, _ = prepare_and_print_ast(+ parse_select(+ "SELECT leadInFrame(user_id, 1, '') OVER ("+ "ORDER BY created_at ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING"+ ") FROM users"+ ),+ _context_with_trino_table(),+ "trino",+ )++ assert 'lead("users"."user_id", 1, %(hogql_val_0)s) OVER (ORDER BY "users"."created_at" ASC)' in sql+ assert "ROWS BETWEEN" not in sql+++def test_lowers_lag_in_frame_when_the_offset_is_inside_the_frame() -> None:+ sql, _ = prepare_and_print_ast(+ parse_select(+ "SELECT lagInFrame(created_at) OVER ("+ "ORDER BY created_at ROWS BETWEEN 1 PRECEDING AND CURRENT ROW"+ ") FROM users"+ ),+ _context_with_trino_table(),+ "trino",+ )++ assert 'lag("users"."created_at") OVER (ORDER BY "users"."created_at" ASC)' in sql+ assert "ROWS BETWEEN" not in sql++@pytest.mark.parametrize(("expression", "feature_code"),[@@ -916,7 +2337,6 @@ def test_prints_semantics_safe_trino_window_functions(expression: str, expected:"row_number() OVER (ORDER BY created_at ROWS BETWEEN 1 PRECEDING AND CURRENT ROW)","TRINO_WINDOW_FRAME_UNSUPPORTED",),- ("lagInFrame(user_id) OVER (ORDER BY created_at)", "TRINO_LAG_IN_FRAME_UNSUPPORTED"),],)def test_rejects_unsafe_trino_window_shapes(expression: str, feature_code: str) -> None:@@ -963,10 +2383,100 @@ def test_lowers_left_any_join_by_deduplicating_the_right_relation() -> None:assert ') AS "other" ON ("users"."user_id" = "other"."user_id")' in sql+def test_lowers_multi_key_any_join_with_a_right_expression() -> None:+ sql, _ = prepare_and_print_ast(+ parse_select(+ "SELECT users.user_id, other.created_at FROM users LEFT ANY JOIN users AS other "+ "ON users.user_id = toString(other.user_id) AND users.created_at = other.created_at"+ ),+ _context_with_trino_table(),+ "trino",+ )++ assert 'PARTITION BY CAST("__hogql_any_source_0"."user_id" AS VARCHAR), "__hogql_any_source_0"."created_at"' in sql+ assert '"users"."user_id" = CAST("other"."user_id" AS VARCHAR)' in sql+++def test_lowers_unaliased_left_any_join() -> None:+ context = _context_with_trino_table()+ assert context.database is not None+ context.database.tables.add_child(+ TableNode(+ name="people",+ table=DirectTrinoTable(+ name="people",+ fields={+ "user_id": StringDatabaseField(name="user_id", nullable=False),+ "created_at": DateTimeDatabaseField(name="created_at", nullable=False),+ },+ external_data_source_id="source-id",+ trino_catalog="ducklake",+ trino_schema="analytics",+ trino_table_name="people",+ has_complete_columns=False,+ ),+ )+ )+ sql, _ = prepare_and_print_ast(+ parse_select(+ "SELECT users.user_id, people.created_at FROM users LEFT ANY JOIN people ON users.user_id = people.user_id"+ ),+ context,+ "trino",+ )++ assert "LEFT ANY JOIN" not in sql+ assert ') AS "people" ON ("users"."user_id" = "people"."user_id")' in sql+++def test_lowers_any_join_to_the_deduplicated_trino_persons_relation() -> None:+ context = HogQLContext(+ database=Database(include_posthog_tables=True),+ modifiers=_trino_modifiers(),+ enable_select_queries=True,+ limit_top_select=False,+ restricted_properties=set(),+ trino_table_locators={+ "events": ("tenant", "posthog", "events"),+ "persons": ("tenant", "posthog", "persons"),+ "person_distinct_ids": ("tenant", "posthog", "person_distinct_ids"),+ "raw_person_distinct_ids": ("tenant", "posthog", "person_distinct_ids"),+ },+ )++ sql, _ = prepare_and_print_ast(+ parse_select(+ "SELECT persons.properties.email FROM events LEFT ANY JOIN persons ON events.person_id = persons.id"+ ),+ context,+ "trino",+ )++ assert "LEFT ANY JOIN" not in sql+ assert 'FROM "tenant"."posthog"."persons" GROUP BY 1) AS "persons"' in sql+ assert '"persons"."properties___email"' in sql+++def test_lowers_left_any_join_against_a_cte() -> None:+ sql, _ = prepare_and_print_ast(+ parse_select(+ "WITH right_rows AS (SELECT user_id, created_at FROM users) "+ "SELECT users.user_id, other.created_at FROM users "+ "LEFT ANY JOIN right_rows AS other ON users.user_id = other.user_id"+ ),+ _context_with_trino_table(),+ "trino",+ )++ assert "LEFT ANY JOIN" not in sql+ assert 'row_number() OVER (PARTITION BY "__hogql_any_source_0"."user_id")' in sql+ assert '"right_rows" AS "__hogql_any_source_0"' in sql++@pytest.mark.parametrize(("join", "constraint", "feature_code"),[- ("RIGHT ANY JOIN", "users.user_id = other.user_id", "TRINO_ANY_JOIN_MODE_UNSUPPORTED"),+ ("FULL ANY JOIN", "users.user_id = other.user_id", "TRINO_ANY_JOIN_MODE_UNSUPPORTED"),("LEFT ANY JOIN", "users.user_id < other.user_id", "TRINO_ANY_JOIN_EQUI_KEYS_REQUIRED"),],)@@ -1015,14 +2525,13 @@ def test_removes_noop_sample_one_for_trino() -> None:("query", "feature_code"),[("SELECT user_id FROM users SAMPLE 0.5", "TRINO_SAMPLE_UNSUPPORTED"),- ("WITH 1 AS scalar_value SELECT scalar_value FROM users", "TRINO_SCALAR_CTE_UNSUPPORTED"),(- "SELECT * FROM users PIVOT(count(user_id) FOR created_at IN ('2026-01-01'))",- "TRINO_PIVOT_UNSUPPORTED",+ "SELECT * FROM users PIVOT(uniq(user_id) FOR created_at IN ('2026-01-01'))",+ "TRINO_PIVOT_AGGREGATE_UNSUPPORTED",),(- "SELECT * FROM users UNPIVOT(value FOR key IN (user_id))",- "TRINO_UNPIVOT_UNSUPPORTED",+ "SELECT * FROM users UNPIVOT((value1, value2) FOR (key1, key2) IN ((user_id, id)))",+ "TRINO_UNPIVOT_SHAPE_UNSUPPORTED",),],)@@ -1118,18 +2627,6 @@ def test_wrapper_sort_projections_preserve_output(query: str, snapshot: Snapshot"FROM users QUALIFY rn > 0 ORDER BY user_id = toString(true)","TRINO_WRAPPER_ORDER_NOT_PROJECTED",),- (- "SELECT user_id FROM users ORDER BY row_number() OVER (ORDER BY created_at) LIMIT 1 BY user_id",- "TRINO_LIMIT_BY_WINDOW_UNSUPPORTED",- ),- (- "SELECT user_id, row_number() OVER (ORDER BY created_at) AS rn FROM users ORDER BY 2 LIMIT 1 BY user_id",- "TRINO_LIMIT_BY_WINDOW_UNSUPPORTED",- ),- (- "SELECT user_id, row_number() OVER (ORDER BY created_at) AS rn FROM users LIMIT 1 BY rn",- "TRINO_LIMIT_BY_WINDOW_UNSUPPORTED",- ),],)def test_wrapper_rejects_unsafe_sort_or_partition(query: str, feature_code: str) -> None:@@ -1204,3 +2701,56 @@ def test_grouping_does_not_replace_different_or_nested_expressions(query: str, sassert node.group_by is not Noneassert not isinstance(node.group_by[0], ast.PositionalRef)assert (sql, context.values) == snapshot+++ ("query", "expected"),+ [+ ("WITH items AS (SELECT ['a'] AS xs) SELECT empty(xs) FROM items", 'cardinality("items"."xs")'),+ ("WITH items AS (SELECT ['a'] AS xs) SELECT xs != '[]' FROM items", 'cardinality("items"."xs")'),+ (+ "WITH items AS (SELECT JSONExtractArrayRaw(properties, 'items') AS xs FROM users) SELECT empty(xs) FROM items",+ 'cardinality("items"."xs")',+ ),+ ],+)+def test_preserves_array_types_across_cte_boundaries(query: str, expected: str) -> None:+ sql, _ = prepare_and_print_ast(parse_select(query), _context_with_trino_table(), "trino")++ assert expected in sql+++def test_union_keeps_common_ctes_in_scope_for_every_branch() -> None:+ sql, _ = prepare_and_print_ast(+ parse_select(+ "WITH source AS (SELECT user_id FROM users) SELECT user_id FROM source UNION ALL SELECT user_id FROM source"+ ),+ _context_with_trino_table(),+ "trino",+ )++ assert sql.startswith('WITH "source" AS (')+ assert sql.count('FROM "source"') == 2+ assert ") UNION ALL (" in sql+++ "expression",+ [+ "ifNotFinite(1.0, 0.0)",+ "medianExactWeighted(3, 2)",+ "medianExactWeightedIf(3, 2, true)",+ "quantilesIf(0.25, 0.75)(3, true)",+ ],+)[email protected]("dialect", ["clickhouse", "hogql", "trino"])+def test_trino_signatures_do_not_change_other_dialect_validation(expression: str, dialect: HogQLDialect) -> None:+ context = _context_with_trino_table()+ context.team_id = 1+ query = parse_select(f"SELECT {expression}")+ if dialect == "trino":+ sql, _ = prepare_and_print_ast(query, context, dialect)+ assert sql+ else:+ with pytest.raises(QueryError, match="expects"):+ print_prepared_ast(resolve_types(query, context, dialect), context, dialect)diff --git a/posthog/hogql/printer/trino.py b/posthog/hogql/printer/trino.pyindex 741bf1aae1a9..197f6702d613 100644--- a/posthog/hogql/printer/trino.py+++ b/posthog/hogql/printer/trino.py@@ -1,5 +1,7 @@import refrom collections.abc import Callable, Iterable+from dataclasses import replace+from string import Formatterfrom typing import TYPE_CHECKING, ClassVar, NoReturnfrom posthog.hogql import ast@@ -11,15 +13,31 @@ from posthog.hogql.escape_sql import escape_trino_identifierfrom posthog.hogql.functions import find_hogql_aggregationfrom posthog.hogql.printer.postgres import PostgresPrinterfrom posthog.hogql.printer.trino_functions import (+ TRINO_AGGREGATE_COMBINATORS,+ TRINO_ARRAY_INSERT_AGGREGATES,+ TRINO_DELTA_AGGREGATES,+ TRINO_EXACT_QUANTILES,+ TRINO_EXACT_WEIGHTED_MEDIANS,TRINO_FUNCTION_HANDLERS_LOWER,TRINO_FUNCTION_RENAMES_LOWER,+ TRINO_INTERSECTION_AGGREGATES,+ TRINO_MOVING_ARRAY_AGGREGATES,TRINO_PASSTHROUGH_FUNCTIONS,+ TRINO_QUANTILES,+ TRINO_STATISTICAL_AGGREGATES,+ TRINO_TUPLE_OPERATORS,+ TRINO_UNIQUE_ARRAY_AGGREGATES,+ TRINO_VECTOR_REWRITES,+ TRINO_WINDOW_ONLY_FUNCTIONS,)from posthog.hogql.printer.types import JoinExprResponsefrom posthog.hogql.transforms.trino.errors import TrinoLoweringError+from posthog.hogql.transforms.trino.expressions import constant_integer+from posthog.hogql.transforms.trino.limits import MAX_TRINO_SQL_LENGTHfrom posthog.hogql.visitor import clone_exprfrom posthog.dataclasses import frozen+from posthog.exchange_rate_constants import EXCHANGE_RATE_DECIMAL_PRECISIONif TYPE_CHECKING:from posthog.hogql.database.models import Table@@ -110,6 +128,7 @@ _TRINO_WINDOW_FUNCTIONS = frozenset("rank","row_number","sum",+ "stddev_pop",})_TRINO_WINDOW_FUNCTION_RENAMES = {@@ -118,6 +137,7 @@ _TRINO_WINDOW_FUNCTION_RENAMES = {"argmax": "max_by","argmin": "min_by","grouparray": "array_agg",+ "stddevpop": "stddev_pop",}_TRINO_CONDITIONAL_WINDOW_FUNCTIONS = {"anyif": "arbitrary",@@ -127,6 +147,7 @@ _TRINO_CONDITIONAL_WINDOW_FUNCTIONS = {"maxif": "max","minif": "min","sumif": "sum",+ "stddevpopif": "stddev_pop",}_TRINO_NO_FRAME_WINDOW_FUNCTIONS = frozenset({"cume_dist", "dense_rank", "lag", "lead", "ntile", "percent_rank", "rank", "row_number"}@@ -166,6 +187,16 @@ class TrinoPrinter(PostgresPrinter):DIALECT_NAME: ClassVar[HogQLDialect] = "trino"DIALECT_LABEL: ClassVar[str] = "Trino"+ def visit(self, node: ast.AST | None) -> str:+ sql = super().visit(node)+ if len(sql) > MAX_TRINO_SQL_LENGTH:+ self._unsupported(+ "TRINO_SQL_SIZE_LIMIT",+ "The generated Trino SQL exceeds the compilation limit. Simplify the query.",+ node if isinstance(node, ast.Expr) else None,+ )+ return sql+def _print_identifier(self, name: str) -> str:return escape_trino_identifier(name)@@ -193,19 +224,15 @@ class TrinoPrinter(PostgresPrinter):@staticmethoddef _validate_row_count(value: ast.Expr, clause: str) -> int:- if (- not isinstance(value, ast.Constant)- or isinstance(value.value, bool)- or not isinstance(value.value, int)- or value.value < 0- ):+ count = constant_integer(value)+ if count is None or count < 0:raise TrinoLoweringError("TRINO_ROW_COUNT_NON_LITERAL",clause,value,- detail=f"{clause} must be a non-negative integer literal in Trino mode.",+ detail=f"{clause} must be a non-negative integer constant in Trino mode.",)- return value.value+ return countdef _append_select_limit_and_offset(self, clauses: list[str | None], node: ast.SelectQuery, limit: ast.Expr | None@@ -249,6 +276,7 @@ class TrinoPrinter(PostgresPrinter):return sql.rstrip() + separator + separator.join(suffixes)def visit_select_set_query(self, node: ast.SelectSetQuery) -> str:+ node = self._align_set_query_types(node)if not isinstance(node.initial_select_query, ast.SelectQuery) or not node.initial_select_query.ctes:return super().visit_select_set_query(node)ctes = node.initial_select_query.ctes@@ -283,8 +311,74 @@ class TrinoPrinter(PostgresPrinter):def _invalid_function_arguments(self, node: ast.Call, detail: str) -> NoReturn:self._unsupported("TRINO_FUNCTION_ARGUMENTS_UNSUPPORTED", detail, node)+ def _align_set_query_types(self, node: ast.SelectSetQuery) -> ast.SelectSetQuery:+ branches = self._set_query_branches(node)+ if not branches:+ return node+ width = min(len(branch.select) for branch in branches)+ targets: dict[int, str] = {}+ for index in range(width):+ expressions = [+ projection.expr if isinstance(projection := branch.select[index], ast.Alias) else projection+ for branch in branches+ ]+ types = [self._resolve_type(expression) for expression in expressions]+ if any(isinstance(value_type, ast.StringType) for value_type in types) and any(+ isinstance(+ value_type,+ (ast.IntegerType, ast.FloatType, ast.DecimalType, ast.BooleanType, ast.UUIDType),+ )+ for value_type in types+ ):+ targets[index] = "varchar"+ elif any(isinstance(value_type, ast.BooleanType) for value_type in types) and any(+ isinstance(value_type, (ast.IntegerType, ast.FloatType, ast.DecimalType)) for value_type in types+ ):+ targets[index] = "bigint"+ if not targets:+ return node+ lowered = clone_expr(node, clear_types=False)+ for branch in self._set_query_branches(lowered):+ for index, target in targets.items():+ projection = branch.select[index]+ expression = projection.expr if isinstance(projection, ast.Alias) else projection+ source_type = self._resolve_type(expression)+ cast_expression: ast.Expr = (+ ast.Call(name="toJSONString", args=[expression])+ if target == "varchar" and isinstance(source_type, (ast.ArrayType, ast.MapType, ast.TupleType))+ else ast.TypeCast(expr=expression, type_name=target)+ )+ if isinstance(projection, ast.Alias):+ projection.expr = cast_expression+ else:+ branch.select[index] = cast_expression+ return lowered++ def _set_query_branches(self, node: ast.SelectSetQuery) -> list[ast.SelectQuery]:+ branches: list[ast.SelectQuery] = []+ for branch in node.select_queries():+ if isinstance(branch, ast.SelectSetQuery):+ branches.extend(self._set_query_branches(branch))+ else:+ branches.append(branch)+ return branches++ def visit_alias(self, node: ast.Alias) -> str:+ parent = self.stack[-2] if len(self.stack) > 1 else None+ if isinstance(parent, ast.SelectQuery) and any(expr is node for expr in parent.select):+ return super().visit_alias(node)+ return self.visit(node.expr)+def visit_call(self, node: ast.Call) -> str:name = node.name.lower()+ if name in TRINO_WINDOW_ONLY_FUNCTIONS:+ self._invalid_function_arguments(node, f"{node.name} requires an OVER clause in Trino mode.")+ if name in TRINO_AGGREGATE_COMBINATORS:+ return self._visit_aggregate_combinator(node)+ if node.filter_expr is not None and name in {"count", "sum", "avg", "min", "max", "countdistinct"}:+ unfiltered = clone_expr(node, clear_types=False)+ unfiltered.filter_expr = None+ return f"{self.visit_call(unfiltered)} FILTER (WHERE {self._visit_predicate(node.filter_expr)})"if find_hogql_aggregation(node.name) is None and (node.distinct or node.within_group is not None or node.order_by is not None or node.filter_expr is not None):@@ -293,17 +387,394 @@ class TrinoPrinter(PostgresPrinter):f"Scalar function '{node.name}' does not accept aggregate modifiers in Trino mode.",node,)+ comparison_operators = {+ "equals": ast.CompareOperationOp.Eq,+ "notequals": ast.CompareOperationOp.NotEq,+ "greater": ast.CompareOperationOp.Gt,+ "greaterorequals": ast.CompareOperationOp.GtEq,+ "less": ast.CompareOperationOp.Lt,+ "lessorequals": ast.CompareOperationOp.LtEq,+ "like": ast.CompareOperationOp.Like,+ "ilike": ast.CompareOperationOp.ILike,+ "notlike": ast.CompareOperationOp.NotLike,+ "notilike": ast.CompareOperationOp.NotILike,+ }+ if name in TRINO_TUPLE_OPERATORS:+ return self._visit_tuple_arithmetic(node)+ if name == "tupletonamevaluepairs":+ return self._visit_tuple_to_name_value_pairs(node)+ if name in TRINO_VECTOR_REWRITES:+ return self._visit_vector_rewrite(node)+ if name == "arrayreduce":+ return self._visit_array_reduce(node)+ if name == "arrayauc":+ return self._visit_array_auc(node)+ if name == "mappopulateseries":+ return self._visit_map_populate_series(node)+ if name in {+ "arraycumsum",+ "arraycumsumnonnegative",+ "arrayfill",+ "arrayreversefill",+ "arraysplit",+ "arrayreversesplit",+ }:+ return self._visit_array_scan(node)+ if name == "factorial" and (+ len(node.args) != 1+ or not (+ isinstance(self._resolve_type(node.args[0]), ast.IntegerType)+ or isinstance(node.args[0], ast.Constant)+ and node.args[0].value is None+ )+ ):+ self._invalid_function_arguments(node, "factorial requires an integer argument in Trino mode.")+ if name == "roundtoexp2":+ if len(node.args) != 1:+ self._invalid_function_arguments(node, "roundToExp2 requires one numeric argument in Trino mode.")+ value_type = self._resolve_type(node.args[0])+ if not isinstance(value_type, (ast.IntegerType, ast.FloatType)):+ self._invalid_function_arguments(+ node, "roundToExp2 requires an integer or float argument in Trino mode."+ )+ target_type = "BIGINT" if isinstance(value_type, ast.IntegerType) else "DOUBLE"+ value = self.visit(node.args[0])+ if isinstance(value_type, ast.IntegerType):+ rounded = (+ "reduce(sequence(0, 62), BIGINT '0', (__hogql_result, __hogql_exponent) -> "+ "IF(__hogql_round_to_exp2 >= "+ "bitwise_left_shift(BIGINT '1', CAST(__hogql_exponent AS INTEGER)), "+ "bitwise_left_shift(BIGINT '1', CAST(__hogql_exponent AS INTEGER)), __hogql_result), "+ "__hogql_result -> __hogql_result)"+ )+ return (+ f"element_at(transform(ARRAY[CAST({value} AS {target_type})], __hogql_round_to_exp2 -> "+ f"{rounded}), 1)"+ )+ rounded = "sign(__hogql_round_to_exp2) * power(2e0, floor(ln(abs(__hogql_round_to_exp2)) / ln(2e0)))"+ return (+ f"element_at(transform(ARRAY[CAST({value} AS {target_type})], __hogql_round_to_exp2 -> "+ f"IF(__hogql_round_to_exp2 = 0, CAST(0 AS {target_type}), CAST({rounded} AS {target_type}))), 1)"+ )+ if name in {"gcd", "lcm"}:+ if len(node.args) != 2 or any(+ not isinstance(self._resolve_type(argument), ast.IntegerType) for argument in node.args+ ):+ self._invalid_function_arguments(node, f"{node.name} requires two integer arguments in Trino mode.")+ left, right = (self.visit(argument) for argument in node.args)+ state_type = "ROW(first_value BIGINT, second_value BIGINT)"+ gcd = (+ f"reduce(sequence(1, 64), CAST(ROW(abs(__hogql_integer_pair[1]), "+ f"abs(__hogql_integer_pair[2])) AS {state_type}), "+ "(__hogql_state, __hogql_step) -> IF(__hogql_state[2] = 0, __hogql_state, "+ f"CAST(ROW(__hogql_state[2], mod(__hogql_state[1], __hogql_state[2])) AS {state_type})), "+ "__hogql_state -> __hogql_state[1])"+ )+ result = gcd+ if name == "lcm":+ result = f"abs(__hogql_integer_pair[1] / ({gcd}) * __hogql_integer_pair[2])"+ result = (+ "IF(__hogql_integer_pair[1] = 0 OR __hogql_integer_pair[2] = 0, "+ f"fail('{node.name} does not accept zero'), {result})"+ )+ return (+ f"element_at(transform(ARRAY[CAST(ROW({left}, {right}) AS {state_type})], "+ f"__hogql_integer_pair -> {result}), 1)"+ )+ if name in comparison_operators:+ if len(node.args) != 2:+ self._invalid_function_arguments(node, f"{node.name} expects exactly 2 arguments in Trino mode.")+ return self.visit_compare_operation(+ ast.CompareOperation(op=comparison_operators[name], left=node.args[0], right=node.args[1])+ )+ if name in {"if", "multiif"}:+ if len(node.args) < 3 or len(node.args) % 2 == 0 or (name == "if" and len(node.args) != 3):+ self._invalid_function_arguments(node, f"{node.name} expects condition/value pairs and a default.")+ cases = [+ f"WHEN {self._visit_predicate(node.args[index])} THEN {self.visit(node.args[index + 1])}"+ for index in range(0, len(node.args) - 1, 2)+ ]+ return f"CASE {' '.join(cases)} ELSE {self.visit(node.args[-1])} END"+ if (+ name in {"countif", "countdistinctif", "uniqif", "uniqexactif", "sumif", "avgif", "minif", "maxif", "anyif"}+ and node.args+ ):+ if self._is_numeric(node.args[-1]) or self._is_dynamic_property(node.args[-1]):+ lowered = clone_expr(node, clear_types=False)+ lowered.args[-1] = ast.TypeCast(expr=lowered.args[-1], type_name="boolean")+ return super().visit_call(lowered)+ if (+ name in {"coalesce", "ifnull", "nullif"}+ and any(isinstance(self._resolve_type(arg), ast.BooleanType) for arg in node.args)+ and any(self._is_dynamic_property(arg) for arg in node.args)+ ):+ lowered = clone_expr(node, clear_types=False)+ lowered.args = [+ ast.TypeCast(expr=arg, type_name="boolean") if self._is_dynamic_property(arg) else arg+ for arg in lowered.args+ ]+ return self.visit_call(lowered)+ if (+ name in {"coalesce", "ifnull", "nullif"}+ and any(isinstance(self._resolve_type(arg), ast.BooleanType) for arg in node.args)+ and any(self._is_numeric(arg) for arg in node.args)+ ):+ coerced_args = [+ f"CAST({self.visit(arg)} AS INTEGER)"+ if isinstance(self._resolve_type(arg), ast.BooleanType)+ else self.visit(arg)+ for arg in node.args+ ]+ function = "nullif" if name == "nullif" else "coalesce"+ return f"{function}({', '.join(coerced_args)})"+ if (+ name in {"coalesce", "ifnull", "nullif"}+ and any(isinstance(self._resolve_type(arg), ast.StringType) for arg in node.args)+ and any(self._is_numeric(arg) for arg in node.args)+ ):+ coerced_args = [+ self.visit(arg)+ if isinstance(self._resolve_type(arg), ast.StringType)+ else f"CAST({self.visit(arg)} AS VARCHAR)"+ for arg in node.args+ ]+ function = "nullif" if name == "nullif" else "coalesce"+ return f"{function}({', '.join(coerced_args)})"+ if (+ name == "tostring"+ and len(node.args) == 1+ and isinstance(self._resolve_type(node.args[0]), (ast.ArrayType, ast.MapType, ast.TupleType))+ ):+ return f"json_format(CAST({self.visit(node.args[0])} AS JSON))"if name in {"empty", "notempty"}:return self._visit_empty(node, negated=name == "notempty")if name in {"in", "notin"}:if len(node.args) != 2:self._invalid_function_arguments(node, f"{node.name} expects exactly 2 arguments in Trino mode.")return self._visit_membership(node.args[0], node.args[1], negated=name == "notin")+ if name == "arraymax":+ return self._visit_unary_function(node, "array_max")+ if name == "arrayenumerate":+ value = self._visit_unary_arg(node)+ return f"IF(cardinality({value}) = 0, CAST(ARRAY[] AS ARRAY(BIGINT)), sequence(1, cardinality({value})))"+ if name in {"arrayexists", "arrayall"}:+ return self._visit_lambda_array_call(node, "any_match" if name == "arrayexists" else "all_match")+ if name == "intdiv":+ binary_args = self._visit_binary_args(node)+ if not all(isinstance(self._resolve_type(arg), ast.IntegerType) for arg in node.args):+ self._unsupported(+ "TRINO_INT_DIV_TYPE_UNSUPPORTED", "intDiv requires integer operands in Trino mode.", node+ )+ return f"(CAST({binary_args.left} AS BIGINT) / CAST({binary_args.right} AS BIGINT))"+ if name in {"accuratecast", "accuratecastornull"}:+ return self._visit_accurate_cast(node, nullable=name == "accuratecastornull")+ if name == "format":+ return self._visit_format(node)+ if name == "toipv4" and len(node.args) == 1 and isinstance(self._resolve_type(node.args[0]), ast.IntegerType):+ value = self.visit(node.args[0])+ address = (+ "CAST(array_join(transform(ARRAY[24, 16, 8, 0], __hogql_shift -> "+ "CAST(bitwise_and(bitwise_right_shift_arithmetic(__hogql_ipv4, __hogql_shift), 255) AS VARCHAR)), '.') "+ "AS IPADDRESS)"+ )+ result = f"IF(__hogql_ipv4 BETWEEN 0 AND 4294967295, {address}, fail('IPv4 number is out of range'))"+ return (+ f"element_at(transform(ARRAY[CAST({value} AS BIGINT)], __hogql_ipv4 -> "+ f"IF(__hogql_ipv4 IS NULL, NULL, {result})), 1)"+ )+ if name in {"_toint8", "_toint16", "_toint32", "_toint64"}:+ return self._visit_internal_integer_cast(node)+ if name == "multiplydecimal":+ return self._visit_multiply_decimal(node)+ if name == "dividedecimal" and len(node.args) == 3:+ return self._visit_divide_decimal_with_scale(node)+ if name == "roundbankers":+ return self._visit_round_bankers(node)+ if name == "extracturlparameter":+ binary_args = self._visit_binary_args(node)+ without_fragment = f"split_part({binary_args.left}, '#', 1)"+ query = f"IF(strpos({without_fragment}, '?') > 0, substr({without_fragment}, strpos({without_fragment}, '?') + 1), '')"+ parameter = f"element_at(filter(split({query}, '&'), __hogql_parameter -> split_part(__hogql_parameter, '=', 1) = {binary_args.right}), 1)"+ return f"coalesce(substr({parameter}, length({binary_args.right}) + 2), '')"+ if name == "arrayzip":+ if not 2 <= len(node.args) <= 5:+ self._unsupported(+ "TRINO_ARRAY_ZIP_DYNAMIC_UNSUPPORTED",+ "arrayZip requires two to five arrays in Trino mode.",+ node,+ )+ if (+ all(isinstance(arg, ast.Array) for arg in node.args)+ and len({len(arg.exprs) for arg in node.args if isinstance(arg, ast.Array)}) != 1+ ):+ self._invalid_function_arguments(node, "arrayZip requires equal-length arrays.")+ arrays = [self.visit(arg) for arg in node.args]+ zipped = f"zip({', '.join(arrays)})"+ if all(isinstance(arg, ast.Array) for arg in node.args):+ return zipped+ same_length = " AND ".join(f"cardinality({arrays[0]}) = cardinality({array})" for array in arrays[1:])+ return f"IF({same_length}, {zipped}, fail('arrayZip requires equal-length arrays'))"+ if name in {+ "extractallgroups",+ "extractallgroupshorizontal",+ "extractallgroupsvertical",+ "extractgroups",+ "regexpextract",+ "replaceregexpone",+ }:+ return self._visit_constant_regex(node)+ if name == "median":+ if node.distinct or node.order_by or node.filter_expr or node.params:+ self._unsupported(+ "TRINO_MEDIAN_MODIFIER_UNSUPPORTED", "median modifiers are not supported in Trino mode.", node+ )+ return f"approx_percentile({self._visit_unary_arg(node)}, 0.5)"+ if name == "medianif":+ if node.distinct or node.order_by or node.filter_expr or node.params or len(node.args) != 2:+ self._unsupported(+ "TRINO_MEDIAN_MODIFIER_UNSUPPORTED",+ "medianIf requires exactly one value and one condition in Trino mode.",+ node,+ )+ return f"approx_percentile({self.visit(node.args[0])}, 0.5) FILTER (WHERE {self._visit_predicate(node.args[1])})"+ if name == "topk":+ return self._visit_top_k(node)+ if name in {"avgweighted", "avgweightedif"}:+ return self._visit_weighted_average(node)+ if name == "tonullablestring":+ return self._visit_to_nullable_string(node)+ if name == "to_timestamp":+ return self._visit_to_timestamp(node)+ if name == "defaultvalueoftypename":+ return self._visit_default_value_of_type_name(node)+ if name == "datename":+ return self._visit_date_name(node)+ if name in TRINO_STATISTICAL_AGGREGATES:+ return self._visit_statistical_aggregate(node)+ if name in TRINO_INTERSECTION_AGGREGATES:+ return self._visit_max_intersections(node)+ if name in TRINO_UNIQUE_ARRAY_AGGREGATES:+ return self._visit_unique_array_aggregate(node)+ if name in TRINO_MOVING_ARRAY_AGGREGATES:+ return self._visit_moving_array_aggregate(node)+ if name in TRINO_DELTA_AGGREGATES:+ return self._visit_delta_sum(node)+ if name in TRINO_ARRAY_INSERT_AGGREGATES:+ return self._visit_group_array_insert_at(node)+ if name in TRINO_EXACT_QUANTILES:+ return self._visit_exact_quantile(node, filtered=name.endswith("if"))+ if name in TRINO_EXACT_WEIGHTED_MEDIANS:+ return self._visit_exact_weighted_median(node)+ if name in TRINO_QUANTILES:+ return self._visit_quantiles(node)+ if name in {+ "ngramdistance",+ "ngramdistancecaseinsensitive",+ "ngramdistanceutf8",+ "ngramsearch",+ "ngramsearchcaseinsensitive",+ "ngramsearchutf8",+ }:+ return self._visit_ngram(+ node,+ utf8=name.endswith("utf8"),+ case_insensitive="caseinsensitive" in name,+ search=name.startswith("ngramsearch"),+ )+ if name == "formatreadabletimedelta":+ return self._visit_format_readable_time_delta(node)+ if name == "convertcurrency":+ return self._visit_convert_currency(node)+ if name == "aggregate_funnel_trends":+ self._unsupported(+ "TRINO_FUNCTION_UNSUPPORTED",+ "aggregate_funnel_trends has no verified Trino implementation. Run this query on ClickHouse.",+ node,+ )+ if name == "cityhash64":+ self._unsupported(+ "TRINO_FUNCTION_UNSUPPORTED",+ f"{node.name} has no semantics-preserving Trino implementation.",+ node,+ )+ if name == "totypename":+ self._unsupported(+ "TRINO_FUNCTION_UNSUPPORTED",+ "toTypeName depends on ClickHouse physical types and has no semantics-preserving Trino implementation.",+ node,+ )+ if name == "bitnot":+ self._unsupported(+ "TRINO_FUNCTION_UNSUPPORTED",+ "bitNot depends on the signed width of its ClickHouse argument.",+ node,+ )+ if name == "domain":+ value = self._visit_unary_arg(node)+ return f"IF({value} IS NULL, NULL, coalesce(TRY(url_extract_host(CAST({value} AS VARCHAR))), ''))"+ if name == "hex":+ value = self._visit_unary_arg(node)+ return f"to_hex(to_utf8(CAST({value} AS VARCHAR)))"+ if name == "touuidordefault":+ binary_args = self._visit_binary_args(node)+ return f"coalesce(TRY_CAST({binary_args.left} AS UUID), TRY_CAST({binary_args.right} AS UUID))"+ if name == "reinterpretasuuid":+ value = self._visit_unary_arg(node)+ value_type = self._resolve_type(node.args[0])+ if not isinstance(value_type, ast.IntegerType):+ self._invalid_function_arguments(node, "reinterpretAsUUID requires an integer argument in Trino mode.")+ hexadecimal = f"format('%016x0000000000000000', CAST({value} AS BIGINT))"+ formatted = (+ f"concat(substr({hexadecimal}, 1, 8), '-', substr({hexadecimal}, 9, 4), '-', "+ f"substr({hexadecimal}, 13, 4), '-', substr({hexadecimal}, 17, 4), '-', "+ f"substr({hexadecimal}, 21, 12))"+ )+ return f"CAST({formatted} AS UUID)"+ if name == "cuttofirstsignificantsubdomain":+ value = self._visit_unary_arg(node)+ labels = f"filter(split(lower(trim(TRAILING '.' FROM {value})), '.'), __hogql_label -> __hogql_label <> '')"+ return f"IF(cardinality({labels}) < 2, '', array_join(slice({labels}, cardinality({labels}) - 1, 2), '.'))"+ if name in {"stddevsamp", "stddevsampif", "varsamp", "varsampif", "covarsamp", "covarsampif", "corr"}:+ return self._visit_sample_statistic(node)+ if name in {"percentile_cont", "percentile_disc"}:+ return self._visit_percentile_within_group(node, continuous=name == "percentile_cont")+ if name in {"tostartofyear", "tostartofquarter"}:+ unit = "year" if name == "tostartofyear" else "quarter"+ return f"CAST(date_trunc('{unit}', {self._visit_unary_arg(node)}) AS DATE)"+ if name in {"floor", "ceil"} and len(node.args) == 2:+ binary_args = self._visit_binary_args(node)+ scale = f"power(10, {binary_args.right})"+ return f"({name}({binary_args.left} * {scale}) / {scale})"+ if name == "tostartofinterval":+ return self._visit_start_of_interval(node)+ if name == "date_bin":+ return self._visit_date_bin(node)if name == "mapfromarrays":return self._visit_map_from_arrays(node)+ if name in {"datediff", "date_diff"} and len(node.args) == 3:+ unit_expr = node.args[0]+ if isinstance(unit_expr, ast.Constant) and isinstance(unit_expr.value, str):+ unit_expr = ast.Constant(value=unit_expr.value.lower().removesuffix("s"))+ rendered_args = [self.visit(unit_expr)]+ for arg in node.args[1:]:+ value = self.visit(arg)+ rendered_args.append(+ f"CAST({value} AS TIMESTAMP)" if isinstance(self._resolve_type(arg), ast.StringType) else value+ )+ return f"date_diff({', '.join(rendered_args)})"if name == "length" and node.args and isinstance(self._resolve_type(node.args[0]), ast.ArrayType):return self._visit_unary_function(node, "cardinality")- if name in {"toint", "tointorzero", "tointordefault"} and node.args:+ if name in {"sum", "avg"} and len(node.args) == 1 and not self._is_dynamic_property(node.args[0]):+ arg_type = self._resolve_type(node.args[0])+ if isinstance(arg_type, ast.StringType):+ lowered = clone_expr(node, clear_types=False)+ lowered.args[0] = ast.TryCast(expr=lowered.args[0], type_name="double")+ return super().visit_call(lowered)+ if isinstance(arg_type, ast.BooleanType):+ lowered = clone_expr(node, clear_types=False)+ lowered.args[0] = ast.TypeCast(expr=lowered.args[0], type_name="bigint")+ return super().visit_call(lowered)+ if name in {"toint", "tointorzero", "tointordefault", "_touint64"} and node.args:arg = node.args[0]arg_type = arg.type.resolve_constant_type(self.context) if arg.type is not None else Nonerendered = self.visit(arg)@@ -313,6 +784,28 @@ class TrinoPrinter(PostgresPrinter):return f"CAST(to_unixtime({rendered}) AS BIGINT)"if isinstance(arg_type, ast.BooleanType):return f"CASE WHEN {rendered} THEN 1 ELSE 0 END"+ if name == "toint" and isinstance(arg_type, ast.StringType):+ return f"TRY_CAST({rendered} AS BIGINT)"+ if name in {"tofloat", "tofloatorzero", "tofloatordefault"} and node.args:+ arg = node.args[0]+ arg_type = self._resolve_type(arg)+ if isinstance(arg_type, ast.DateType):+ return f"CAST(date_diff('day', DATE '1970-01-01', {self.visit(arg)}) AS DOUBLE)"+ if isinstance(arg_type, ast.DateTimeType):+ return f"to_unixtime({self.visit(arg)})"+ if (+ re.fullmatch(r"(?:add|subtract)(?:Seconds|Minutes|Hours|Days|Weeks|Months|Quarters|Years)", node.name)+ and node.args+ and isinstance(self._resolve_type(node.args[0]), ast.StringType)+ ):+ subtract = node.name.startswith("subtract")+ unit_name = node.name[8 if subtract else 3 : -1].lower()+ amount = self.visit(node.args[1])+ if subtract:+ amount = f"-({amount})"+ return f"date_add('{unit_name}', {amount}, CAST({self.visit(node.args[0])} AS TIMESTAMP))"+ if name == "tounixtimestamp" and node.args and self._is_numeric(node.args[0]):+ return f"CAST({self.visit(node.args[0])} AS BIGINT)"if name == "todatetime" and node.args:value_expr = node.args[0]if (@@ -328,6 +821,22 @@ class TrinoPrinter(PostgresPrinter):self._invalid_function_arguments(node, "toDateTime expects a value and optional timezone in Trino mode.")+ if self._is_numeric(value_expr) or (+ isinstance(value_expr, ast.Call)+ and value_expr.name.lower() == "tostring"+ and value_expr.args+ and self._is_numeric(value_expr.args[0])+ ):+ timestamp = f"from_unixtime(CAST({self.visit(value_expr)} AS DOUBLE))"+ return (+ f"at_timezone({timestamp}, {self.visit(node.args[1])})"+ if len(node.args) == 2+ else f"CAST({timestamp} AS TIMESTAMP)"+ )+ if isinstance(self._resolve_type(value_expr), ast.StringType) and not isinstance(value_expr, ast.Constant):+ value = self.visit(value_expr)+ timestamp = f"coalesce(TRY_CAST({value} AS TIMESTAMP), CAST(TRY(from_iso8601_timestamp({value})) AS TIMESTAMP), CAST(from_unixtime(TRY_CAST({value} AS DOUBLE)) AS TIMESTAMP))"+ return f"with_timezone({timestamp}, {self.visit(node.args[1])})" if len(node.args) == 2 else timestampif len(node.args) == 2:return f"with_timezone(CAST({self.visit(value_expr)} AS TIMESTAMP), {self.visit(node.args[1])})"if name == "totimezone":@@ -335,6 +844,8 @@ class TrinoPrinter(PostgresPrinter):return f"at_timezone(with_timezone(CAST({binary_args.left} AS TIMESTAMP), 'UTC'), {binary_args.right})"if name == "parsedatetime":return self._visit_parse_datetime(node)+ if name == "parsedatetimebesteffort":+ return self._visit_parse_datetime_best_effort(node)if name == "tolastdayofweek":return self._visit_to_last_day_of_week(node)if name == "todatetime64":@@ -346,8 +857,8 @@ class TrinoPrinter(PostgresPrinter):"concat does not support DISTINCT or ORDER BY in Trino mode.",node,)- rendered = [f"CAST({self.visit(arg)} AS VARCHAR)" for arg in node.args]- return f"concat({', '.join(rendered)})"+ rendered_args = [f"CAST({self.visit(arg)} AS VARCHAR)" for arg in node.args]+ return f"concat({', '.join(rendered_args)})"if name == "repeat":binary_args = self._visit_binary_args(node)return (@@ -373,12 +884,36 @@ class TrinoPrinter(PostgresPrinter):return self._visit_json_metadata(node)if name == "jsonextractkeysandvalues":return self._visit_json_metadata(node)+ if name == "jsontype":+ return self._visit_json_type(node)if name == "tojsonstring":return self._visit_to_json_string(node)if name == "arraymap":return self._visit_lambda_array_call(node, "transform")if name == "arrayfilter":return self._visit_lambda_array_call(node, "filter")+ if name == "arrayfold":+ if len(node.args) != 3 or not isinstance(node.args[0], ast.Lambda) or len(node.args[0].args) != 2:+ self._invalid_function_arguments(+ node, "arrayFold expects a two-argument lambda, array, and initial state."+ )+ state = self._print_identifier("__hogql_array_fold_state")+ return (+ f"reduce({self.visit(node.args[1])}, {self.visit(node.args[2])}, {self.visit(node.args[0])}, "+ f"{state} -> {state})"+ )+ if name == "arraycount":+ return f"cardinality({self._visit_lambda_array_call(node, 'filter')})"+ if name == "countequal":+ binary_args = self._visit_binary_args(node)+ return (+ f"element_at(transform(ARRAY[ROW({binary_args.left}, {binary_args.right})], __hogql_args -> "+ "cardinality(filter(__hogql_args[1], __hogql_item -> "+ "__hogql_item IS NOT DISTINCT FROM __hogql_args[2]))), 1)"+ )+ if name == "multisearchanycaseinsensitive":+ binary_args = self._visit_binary_args(node)+ return f"any_match({binary_args.right}, __hogql_needle -> strpos(lower({binary_args.left}), lower(__hogql_needle)) > 0)"if name == "arrayelement":return self._visit_binary_function(node, "element_at")if name == "arraydistinct":@@ -388,17 +923,36 @@ class TrinoPrinter(PostgresPrinter):self._invalid_function_arguments(node, "extractAll expects exactly 2 arguments in Trino mode.")return f"regexp_extract_all({self.visit(node.args[0])}, {self.visit(node.args[1])}, 1)"if name == "arraysort":+ if len(node.args) == 2 and isinstance(node.args[0], ast.Lambda):+ return self._visit_array_sort_key(node)return self._visit_unary_function(node, "array_sort")+ if name == "arrayreversesort":+ if len(node.args) == 2 and isinstance(node.args[0], ast.Lambda):+ return f"reverse({self._visit_array_sort_key(node)})"+ return f"reverse({self._visit_unary_function(node, 'array_sort')})"if name == "arrayflatten":return self._visit_unary_function(node, "flatten")if name == "arraymin":return self._visit_unary_function(node, "array_min")- if name == "arrayfirst":+ if name in {"arrayfirst", "arraylast"}:return self._visit_array_first(node)+ if name == "arraylastindex":+ return self._visit_array_last_index(node)+ if name == "arrayresize" and len(node.args) == 2:+ array_type = self._resolve_type(node.args[0])+ if not isinstance(array_type, ast.ArrayType):+ self._invalid_function_arguments(node, "arrayResize requires a resolved array item type in Trino mode.")+ args = [self.visit(arg) for arg in node.args]+ default = self._default_value(array_type.item_type, node)+ if default == "NULL":+ default = f"element_at({args[0]}, cardinality({args[0]}) + 1)"+ args.append(default)+ return TRINO_FUNCTION_HANDLERS_LOWER[name](args)if name == "arrayconcat":return self._visit_variadic_function(node, "concat", minimum=2)if name == "arraysum":- return self._visit_unary_function(node, "array_sum")+ value = self._visit_unary_arg(node)+ return f"reduce({value}, CAST(0 AS DOUBLE), (s, x) -> s + coalesce(CAST(x AS DOUBLE), 0), s -> s)"if name == "has":return self._visit_binary_function(node, "contains")if name == "hasany":@@ -414,9 +968,9 @@ class TrinoPrinter(PostgresPrinter):if name in {"argmaxif", "argminif"}:if len(node.args) != 3:self._invalid_function_arguments(node, f"{node.name} expects exactly 3 arguments in Trino mode.")- values = [self.visit(arg) for arg in node.args]+ rendered_args = [self.visit(arg) for arg in node.args]target = "max_by" if name == "argmaxif" else "min_by"- return f"{target}({values[0]}, {values[1]}) FILTER (WHERE {values[2]})"+ return f"{target}({rendered_args[0]}, {rendered_args[1]}) FILTER (WHERE {rendered_args[2]})"if name == "groupuniqarray":if len(node.args) != 1:self._invalid_function_arguments(node, "groupUniqArray expects exactly 1 argument in Trino mode.")@@ -431,6 +985,10 @@ class TrinoPrinter(PostgresPrinter):return f"array_agg(DISTINCT {self.visit(node.args[0])}) FILTER (WHERE {self.visit(node.args[1])})"if name == "countdistinct":return self._visit_count_distinct(node)+ if name == "first_value":+ if len(node.args) != 1:+ self._invalid_function_arguments(node, "first_value expects exactly 1 argument in Trino mode.")+ return f"arbitrary({self.visit(node.args[0])})"if name == "todecimal":return self._visit_to_decimal(node)if name == "tuple":@@ -440,6 +998,10 @@ class TrinoPrinter(PostgresPrinter):if name == "match":return self._visit_binary_function(node, "regexp_like")if name in {"splitbychar", "splitbystring"}:+ if len(node.args) == 3:+ separator, value, maximum = (self.visit(arg) for arg in node.args)+ split = f"split({value}, {separator})"+ return f"CASE WHEN {maximum} = 0 THEN {split} ELSE slice({split}, 1, {maximum}) END"binary_args = self._visit_binary_args(node)return f"split({binary_args.right}, {binary_args.left})"if name == "md5":@@ -462,7 +1024,30 @@ class TrinoPrinter(PostgresPrinter):if name in {"datetrunc", "date_trunc"} and len(node.args) == 3:unit, value, timezone = (self.visit(arg) for arg in node.args)zoned_value = f"at_timezone(with_timezone(CAST({value} AS TIMESTAMP), 'UTC'), {timezone})"- return f"date_trunc({unit}, {zoned_value})"+ truncated = f"date_trunc({unit}, {zoned_value})"+ if isinstance(node.args[0], ast.Constant) and str(node.args[0].value).lower() in {+ "year",+ "quarter",+ "month",+ "week",+ }:+ return f"CAST({truncated} AS DATE)"+ return truncated+ if name in {"datetrunc", "date_trunc"} and len(node.args) == 2:+ unit, value = (self.visit(arg) for arg in node.args)+ truncated = f"date_trunc({unit}, {value})"+ if isinstance(node.args[0], ast.Constant) and str(node.args[0].value).lower() in {+ "year",+ "quarter",+ "month",+ "week",+ }:+ return f"CAST({truncated} AS DATE)"+ return truncated+ if name == "tostartofday" and len(node.args) == 2:+ value, timezone = (self.visit(arg) for arg in node.args)+ zoned_value = f"at_timezone(with_timezone(CAST({value} AS TIMESTAMP), 'UTC'), {timezone})"+ return f"date_trunc('day', {zoned_value})"if name == "date_part":return self._visit_date_part(node)if name == "json_value":@@ -496,15 +1081,77 @@ class TrinoPrinter(PostgresPrinter):self._unsupported("TRINO_WITH_FILL_UNSUPPORTED", "WITH FILL is not supported in Trino mode.", node)return super().visit_order_expr(node)+ def _visit_predicate(self, node: ast.Expr) -> str:+ rendered = self.visit(node)+ return f"CAST({rendered} AS BOOLEAN)" if self._is_numeric(node) or self._is_dynamic_property(node) else rendered++ def visit_and(self, node: ast.And) -> str:+ return "(" + " AND ".join(f"({self._visit_predicate(expr)})" for expr in node.exprs) + ")"++ def visit_or(self, node: ast.Or) -> str:+ return "(" + " OR ".join(f"({self._visit_predicate(expr)})" for expr in node.exprs) + ")"++ def visit_not(self, node: ast.Not) -> str:+ return f"(NOT {self._visit_predicate(node.expr)})"+def visit_compare_operation(self, node: ast.CompareOperation) -> str:- if node.op in (ast.CompareOperationOp.In, ast.CompareOperationOp.NotIn):+ if node.op in (ast.CompareOperationOp.GlobalIn, ast.CompareOperationOp.GlobalNotIn):+ return self._visit_membership(node.left, node.right, negated=node.op == ast.CompareOperationOp.GlobalNotIn)+ if node.op in (ast.CompareOperationOp.In, ast.CompareOperationOp.NotIn) and not isinstance(+ node.right, (ast.SelectQuery, ast.SelectSetQuery, ast.Tuple)+ ):return self._visit_membership(node.left, node.right, negated=node.op == ast.CompareOperationOp.NotIn)+ if (+ isinstance(self._resolve_type(node.left), ast.ArrayType)+ and isinstance(node.right, ast.Constant)+ and node.right.value == "[]"+ and node.op in (ast.CompareOperationOp.Eq, ast.CompareOperationOp.NotEq)+ ):+ return self._get_compare_op(node.op, f"cardinality({self.visit(node.left)})", "0")left_type = self._resolve_type(node.left)right_type = self._resolve_type(node.right)+ if node.op in (ast.CompareOperationOp.In, ast.CompareOperationOp.NotIn) and isinstance(+ node.right, (ast.SelectQuery, ast.SelectSetQuery)+ ):+ right_scalar_type = self._subquery_scalar_type(node.right)+ if self._is_dynamic_property(node.left) and isinstance(+ right_scalar_type, (ast.IntegerType, ast.FloatType, ast.DecimalType)+ ):+ target = "BIGINT" if isinstance(right_scalar_type, ast.IntegerType) else "DOUBLE"+ return self._get_compare_op(+ node.op, f"TRY_CAST({self.visit(node.left)} AS {target})", self.visit(node.right)+ )+ if isinstance(left_type, ast.StringType) and isinstance(+ right_scalar_type, (ast.IntegerType, ast.FloatType, ast.DecimalType)+ ):+ target = "BIGINT" if isinstance(right_scalar_type, ast.IntegerType) else "DOUBLE"+ return self._get_compare_op(+ node.op, f"TRY_CAST({self.visit(node.left)} AS {target})", self.visit(node.right)+ )+ if self._is_numeric(node.left) and isinstance(right_scalar_type, ast.StringType):+ return self._get_compare_op(+ node.op,+ f"CAST({self.visit(node.left)} AS VARCHAR)",+ self.visit(node.right),+ )+ if (+ node.op in (ast.CompareOperationOp.In, ast.CompareOperationOp.NotIn)+ and isinstance(node.right, ast.Tuple)+ and isinstance(left_type, (ast.DateType, ast.DateTimeType))+ ):+ target = "DATE" if isinstance(left_type, ast.DateType) else "TIMESTAMP"+ values = ", ".join(f"CAST({self.visit(value)} AS {target})" for value in node.right.exprs)+ return self._get_compare_op(node.op, self.visit(node.left), f"({values})")+ if node.op in (ast.CompareOperationOp.In, ast.CompareOperationOp.NotIn):+ return self._visit_membership(node.left, node.right, negated=node.op == ast.CompareOperationOp.NotIn)left_cast: str | None = Noneright_cast: str | None = None- if isinstance(left_type, ast.DateTimeType) and isinstance(right_type, ast.StringType):+ if isinstance(left_type, ast.UUIDType) and isinstance(right_type, ast.StringType):+ left_cast = "VARCHAR"+ elif isinstance(right_type, ast.UUIDType) and isinstance(left_type, ast.StringType):+ right_cast = "VARCHAR"+ elif isinstance(left_type, ast.DateTimeType) and isinstance(right_type, ast.StringType):right_cast = "TIMESTAMP"elif isinstance(right_type, ast.DateTimeType) and isinstance(left_type, ast.StringType):left_cast = "TIMESTAMP"@@ -512,10 +1159,32 @@ class TrinoPrinter(PostgresPrinter):right_cast = "DATE"elif isinstance(right_type, ast.DateType) and isinstance(left_type, ast.StringType):left_cast = "DATE"+ elif isinstance(left_type, ast.DateTimeType) and isinstance(+ right_type, (ast.IntegerType, ast.FloatType, ast.DecimalType)+ ):+ right = f"from_unixtime(CAST({self.visit(node.right)} AS DOUBLE))"+ return self._get_compare_op(node.op, self.visit(node.left), right)+ elif isinstance(right_type, ast.DateTimeType) and isinstance(+ left_type, (ast.IntegerType, ast.FloatType, ast.DecimalType)+ ):+ left = f"from_unixtime(CAST({self.visit(node.left)} AS DOUBLE))"+ return self._get_compare_op(node.op, left, self.visit(node.right))elif self._is_dynamic_property(node.left) and isinstance(right_type, ast.BooleanType):left_cast = "BOOLEAN"elif self._is_dynamic_property(node.right) and isinstance(left_type, ast.BooleanType):right_cast = "BOOLEAN"+ elif isinstance(left_type, ast.StringType) and isinstance(right_type, ast.BooleanType):+ left_cast = "BOOLEAN"+ elif isinstance(right_type, ast.StringType) and isinstance(left_type, ast.BooleanType):+ right_cast = "BOOLEAN"+ elif isinstance(left_type, ast.BooleanType) and isinstance(right_type, ast.IntegerType):+ left_cast = "INTEGER"+ elif isinstance(right_type, ast.BooleanType) and isinstance(left_type, ast.IntegerType):+ right_cast = "INTEGER"+ elif self._is_numeric(node.left) and isinstance(right_type, ast.StringType):+ right_cast = "BIGINT" if isinstance(left_type, ast.IntegerType) else "DOUBLE"+ elif self._is_numeric(node.right) and isinstance(left_type, ast.StringType):+ left_cast = "BIGINT" if isinstance(right_type, ast.IntegerType) else "DOUBLE"else:return super().visit_compare_operation(node)@@ -530,11 +1199,18 @@ class TrinoPrinter(PostgresPrinter):def _visit_membership(self, left: ast.Expr, right: ast.Expr, *, negated: bool) -> str:if isinstance(right, ast.Array) and not right.exprs:return "TRUE" if negated else "FALSE"+ if not isinstance(right, (ast.Array, ast.Tuple, ast.SelectQuery, ast.SelectSetQuery)) and isinstance(+ self._resolve_type(right), ast.ArrayType+ ):+ result = f"contains({self.visit(right)}, {self.visit(left)})"+ return f"NOT ({result})" if negated else resultreturn f"({self.visit(left)} {'NOT IN' if negated else 'IN'} {self._visit_in_values(right)})"def _visit_in_values(self, node: ast.Expr) -> str:if isinstance(node, ast.Array):return f"({', '.join(self.visit(value) for value in node.exprs)})"+ if isinstance(node, ast.Call) and node.name.lower() == "tuple":+ return f"({', '.join(self.visit(value) for value in node.args)})"return super()._visit_in_values(node)def visit_arithmetic_operation(self, node: ast.ArithmeticOperation) -> str:@@ -542,7 +1218,28 @@ class TrinoPrinter(PostgresPrinter):right = self.visit(node.right)if node.op == ast.ArithmeticOperationOp.Div:return f"(CAST({left} AS DOUBLE) / CAST({right} AS DOUBLE))"+ if (+ node.op in (ast.ArithmeticOperationOp.Add, ast.ArithmeticOperationOp.Sub)+ and self._is_numeric(node.right)+ and isinstance(self._resolve_type(node.left), (ast.DateType, ast.DateTimeType))+ ):+ unit = "day" if isinstance(self._resolve_type(node.left), ast.DateType) else "second"+ amount = f"-({right})" if node.op == ast.ArithmeticOperationOp.Sub else right+ return f"date_add('{unit}', CAST({amount} AS BIGINT), {left})"lowered = False+ if isinstance(self._resolve_type(node.left), ast.BooleanType):+ left = f"CAST({left} AS INTEGER)"+ lowered = True+ if isinstance(self._resolve_type(node.right), ast.BooleanType):+ right = f"CAST({right} AS INTEGER)"+ lowered = True+ if (+ isinstance(node.right, ast.Call)+ and node.right.name.lower().startswith("tointerval")+ and isinstance(self._resolve_type(node.left), ast.StringType)+ ):+ left = f"CAST({left} AS TIMESTAMP)"+ lowered = Trueif self._is_dynamic_property(node.left) and self._is_numeric(node.right):left = f"CAST({left} AS DOUBLE)"lowered = True@@ -561,7 +1258,57 @@ class TrinoPrinter(PostgresPrinter):return super().visit_arithmetic_operation(node)def _resolve_type(self, node: ast.Expr) -> ast.ConstantType | None:- return node.type.resolve_constant_type(self.context) if node.type is not None else None+ if isinstance(node, ast.Call) and node.name.lower() in TRINO_TUPLE_OPERATORS:+ if node.name.lower() == "tuplehammingdistance":+ return ast.IntegerType()+ return self._tuple_arithmetic_type(node)+ if isinstance(node, ast.Call) and node.name.lower() in {"jsonhas", "multisearchanycaseinsensitive"}:+ return ast.BooleanType()+ if isinstance(node, ast.Call) and node.name.lower() in {"coalesce", "ifnull", "nullif"}:+ if any(isinstance(self._resolve_type(arg), ast.BooleanType) for arg in node.args) and any(+ self._is_numeric(arg) for arg in node.args+ ):+ return ast.IntegerType()+ if any(isinstance(self._resolve_type(arg), ast.BooleanType) for arg in node.args) and any(+ self._is_dynamic_property(arg) for arg in node.args+ ):+ return ast.BooleanType()+ value_type = node.type+ seen: set[int] = set()+ while value_type is not None and id(value_type) not in seen:+ seen.add(id(value_type))+ if isinstance(value_type, ast.FieldAliasType):+ value_type = value_type.type+ continue+ if isinstance(value_type, ast.FieldType):+ table_type = value_type.table_type+ if isinstance(table_type, ast.CTETableAliasType):+ table_type = table_type.cte_table_type+ if isinstance(table_type, ast.CTETableType) and isinstance(+ table_type.select_query_type, ast.SelectQueryType+ ):+ column_type = table_type.select_query_type.columns.get(value_type.name)+ if column_type is not None:+ value_type = column_type+ continue+ break+ if isinstance(value_type, ast.CallType) and value_type.name.lower() == "jsonextractarrayraw":+ return ast.ArrayType(item_type=ast.StringType())+ resolved = value_type.resolve_constant_type(self.context) if value_type is not None else None+ if isinstance(resolved, ast.StringArrayType):+ return ast.ArrayType(item_type=ast.StringType(), nullable=resolved.nullable)+ return resolved++ def _subquery_scalar_type(self, node: ast.SelectQuery | ast.SelectSetQuery) -> ast.ConstantType | None:+ query = node+ while isinstance(query, ast.SelectSetQuery):+ query = query.initial_select_query+ if not query.select:+ return None+ expression = query.select[0]+ while isinstance(expression, ast.Alias):+ expression = expression.expr+ return self._resolve_type(expression)def _is_dynamic_property(self, node: ast.Expr) -> bool:while isinstance(node, ast.Alias):@@ -571,19 +1318,322 @@ class TrinoPrinter(PostgresPrinter):def _is_numeric(self, node: ast.Expr) -> bool:return isinstance(self._resolve_type(node), (ast.IntegerType, ast.FloatType, ast.DecimalType))+ def _visit_internal_integer_cast(self, node: ast.Call) -> str:+ if len(node.args) != 1:+ self._invalid_function_arguments(node, f"{node.name} expects exactly 1 argument in Trino mode.")+ casts = {+ "_toint8": ("TINYINT", -(2**7), 2**7 - 1),+ "_toint16": ("SMALLINT", -(2**15), 2**15 - 1),+ "_toint32": ("INTEGER", -(2**31), 2**31 - 1),+ "_toint64": ("BIGINT", -(2**63), 2**63 - 1),+ }+ target, minimum, maximum = casts[node.name.lower()]+ value = node.args[0]+ if isinstance(value, ast.Constant) and isinstance(value.value, int) and not minimum <= value.value <= maximum:+ self._unsupported(+ "TRINO_FUNCTION_UNSUPPORTED",+ f"{node.name} constant is outside the Trino {target} range.",+ node,+ )+ return f"CAST({self.visit(value)} AS {target})"++ def _visit_accurate_cast(self, node: ast.Call, *, nullable: bool) -> str:+ if len(node.args) != 2:+ self._invalid_function_arguments(node, f"{node.name} expects a value and target type in Trino mode.")+ target = node.args[1]+ if not isinstance(target, ast.Constant) or not isinstance(target.value, str):+ self._unsupported(+ "TRINO_CAST_TARGET_UNSUPPORTED",+ f"{node.name} requires a constant target type in Trino mode.",+ node,+ )+ type_name = target.value+ while type_name.lower().startswith("nullable(") and type_name.endswith(")"):+ type_name = type_name[9:-1]+ simple_types = {+ "bool": "BOOLEAN",+ "boolean": "BOOLEAN",+ "date": "DATE",+ "datetime": "TIMESTAMP",+ "float32": "REAL",+ "float64": "DOUBLE",+ "int8": "TINYINT",+ "int16": "SMALLINT",+ "int32": "INTEGER",+ "int64": "BIGINT",+ "string": "VARCHAR",+ "uint8": "SMALLINT",+ "uint16": "INTEGER",+ "uint32": "BIGINT",+ "uint64": "DECIMAL(20, 0)",+ "uuid": "UUID",+ }+ trino_type = simple_types.get(type_name.lower())+ decimal_match = re.fullmatch(r"decimal(?:32|64|128|256)\((\d+)\)", type_name, re.IGNORECASE)+ if decimal_match is not None:+ scale = int(decimal_match.group(1))+ if scale <= 38:+ trino_type = f"DECIMAL(38, {scale})"+ if trino_type is None:+ self._unsupported(+ "TRINO_CAST_TARGET_UNSUPPORTED",+ f"accurateCastOrNull target type '{target.value}' is not supported in Trino mode.",+ node,+ )+ value = "__hogql_accurate_cast_value"+ source_type = self._resolve_type(node.args[0])+ normalized_type = type_name.lower()+ integer_bounds = {+ "int8": (-(2**7), 2**7 - 1),+ "int16": (-(2**15), 2**15 - 1),+ "int32": (-(2**31), 2**31 - 1),+ "int64": (-(2**63), 2**63 - 1),+ "uint8": (0, 2**8 - 1),+ "uint16": (0, 2**16 - 1),+ "uint32": (0, 2**32 - 1),+ "uint64": (0, 2**64 - 1),+ }+ if normalized_type in integer_bounds:+ minimum, maximum = integer_bounds[normalized_type]+ decimal_value = f"TRY_CAST({value} AS DECIMAL(38, 18))"+ valid = (+ f"{decimal_value} BETWEEN DECIMAL '{minimum}' AND DECIMAL '{maximum}' "+ f"AND {decimal_value} = truncate({decimal_value})"+ )+ if isinstance(source_type, ast.StringType):+ valid = f"{value} = trim({value}) AND {valid}"+ converted = f"CAST({decimal_value} AS {trino_type})"+ elif normalized_type in {"bool", "boolean"} and isinstance(+ source_type, (ast.IntegerType, ast.FloatType, ast.DecimalType)+ ):+ valid = "TRUE"+ converted = f"({value} <> 0)"+ else:+ converted = f"TRY_CAST({value} AS {trino_type})"+ valid = f"{converted} IS NOT NULL"+ if normalized_type in {"bool", "boolean"} and isinstance(source_type, ast.StringType):+ valid = f"{value} = trim({value}) AND regexp_like({value}, '(?i)^(?:true|false|0|1)$')"+ fallback = "NULL" if nullable else f"fail('Value cannot be safely converted to {type_name}')"+ result = f"IF({value} IS NULL, CAST(NULL AS {trino_type}), IF({valid}, {converted}, {fallback}))"+ return f"element_at(transform(ARRAY[{self.visit(node.args[0])}], {value} -> {result}), 1)"++ def _visit_format(self, node: ast.Call) -> str:+ if len(node.args) < 2:+ self._invalid_function_arguments(node, "format expects a template and at least one value in Trino mode.")+ template = node.args[0]+ if not isinstance(template, ast.Constant) or not isinstance(template.value, str):+ self._unsupported(+ "TRINO_FORMAT_TEMPLATE_UNSUPPORTED",+ "format requires a constant template in Trino mode.",+ node,+ )+ parts: list[str] = []+ argument_index = 1+ try:+ parsed = Formatter().parse(template.value)+ for literal, field_name, format_spec, conversion in parsed:+ if literal:+ parts.append(self.visit(ast.Constant(value=literal)))+ if field_name is None:+ continue+ if field_name or format_spec or conversion:+ self._unsupported(+ "TRINO_FORMAT_TEMPLATE_UNSUPPORTED",+ "format supports only empty placeholders and escaped braces in Trino mode.",+ node,+ )+ if argument_index >= len(node.args):+ self._invalid_function_arguments(node, "format has more placeholders than values in Trino mode.")+ argument = node.args[argument_index]+ argument_type = self._resolve_type(argument)+ if not isinstance(+ argument_type,+ (ast.BooleanType, ast.DateType, ast.DateTimeType, ast.IntegerType, ast.StringType, ast.UUIDType),+ ):+ self._unsupported(+ "TRINO_FORMAT_VALUE_TYPE_UNSUPPORTED",+ "format supports Boolean, Date, DateTime, Integer, String, and UUID values in Trino mode.",+ argument,+ )+ parts.append(f"CAST({self.visit(argument)} AS VARCHAR)")+ argument_index += 1+ except ValueError:+ self._unsupported(+ "TRINO_FORMAT_TEMPLATE_UNSUPPORTED",+ "format received an invalid brace sequence in Trino mode.",+ node,+ )+ if not parts:+ return self.visit(ast.Constant(value=""))+ return parts[0] if len(parts) == 1 else f"concat({', '.join(parts)})"++ @staticmethod+ def _known_decimal_scale(node: ast.Expr) -> int | None:+ if isinstance(node, ast.Constant):+ if isinstance(node.value, bool):+ return None+ if isinstance(node.value, int):+ return 0+ if isinstance(node.value, float):+ return max(0, len(str(node.value).partition(".")[2]))+ if isinstance(node, ast.Call):+ if node.name.lower() == "todecimal" and len(node.args) == 2:+ scale = node.args[1]+ if (+ isinstance(scale, ast.Constant)+ and isinstance(scale.value, int)+ and not isinstance(scale.value, bool)+ ):+ return scale.value+ if node.name.lower() == "accuratecastornull" and len(node.args) == 2:+ target = node.args[1]+ if isinstance(target, ast.Constant) and isinstance(target.value, str):+ match = re.fullmatch(+ r"(?:nullable\()?decimal(?:32|64|128|256)\((\d+)\)\)?", target.value, re.IGNORECASE+ )+ if match is not None:+ return int(match.group(1))+ return None++ def _visit_multiply_decimal(self, node: ast.Call) -> str:+ if len(node.args) not in {2, 3}:+ self._invalid_function_arguments(node, "multiplyDecimal expects two values and an optional scale.")+ scale_expr = node.args[2] if len(node.args) == 3 else None+ if scale_expr is None:+ operand_scales = [self._known_decimal_scale(arg) for arg in node.args]+ if any(scale is None for scale in operand_scales):+ self._unsupported(+ "TRINO_DECIMAL_SCALE_UNSUPPORTED",+ "multiplyDecimal requires a result scale when operand scales cannot be inferred in Trino mode.",+ node,+ )+ scale = max(scale for scale in operand_scales if scale is not None)+ elif (+ isinstance(scale_expr, ast.Constant)+ and isinstance(scale_expr.value, int)+ and not isinstance(scale_expr.value, bool)+ ):+ scale = scale_expr.value+ else:+ self._unsupported(+ "TRINO_DECIMAL_SCALE_UNSUPPORTED",+ "multiplyDecimal requires a constant result scale in Trino mode.",+ node,+ )+ if not 0 <= scale <= 38:+ self._unsupported(+ "TRINO_DECIMAL_SCALE_UNSUPPORTED",+ "multiplyDecimal requires a result scale between 0 and 38 in Trino mode.",+ node,+ )+ return f"CAST(({self.visit(node.args[0])} * {self.visit(node.args[1])}) AS DECIMAL(38, {scale}))"++ def _visit_convert_currency(self, node: ast.Call) -> str:+ if len(node.args) not in {3, 4}:+ self._invalid_function_arguments(+ node, "convertCurrency expects source currency, target currency, amount, and an optional date."+ )+ locator = self.context.trino_table_locators.get("exchange_rate")+ if locator is None:+ self._unsupported(+ "TRINO_EXCHANGE_RATE_TABLE_REQUIRED",+ "convertCurrency requires an exchange_rate table locator in Trino mode.",+ node,+ )+ table = ".".join(self._print_identifier(part) for part in locator)+ from_currency, to_currency, amount = (self.visit(arg) for arg in node.args[:3])+ date = f"CAST({self.visit(node.args[3])} AS DATE)" if len(node.args) == 4 else "CURRENT_DATE"+ scale = EXCHANGE_RATE_DECIMAL_PRECISION+ zero = f"CAST(0 AS DECIMAL(38, {scale}))"++ def rate(currency: str, alias: str) -> str:+ return (+ f"coalesce((SELECT max_by(CAST({alias}.rate AS DECIMAL(38, {scale})), {alias}.date) "+ f"FROM {table} AS {alias} WHERE {alias}.currency = {currency} AND {alias}.date <= {date}), {zero})"+ )++ from_rate = rate(from_currency, "__hogql_from_rate")+ to_rate = rate(to_currency, "__hogql_to_rate")+ decimal_amount = f"CAST({amount} AS DECIMAL(38, {scale}))"+ return (+ f"CASE WHEN {from_currency} = {to_currency} THEN {decimal_amount} "+ f"WHEN {from_rate} = {zero} THEN {zero} "+ f"ELSE CAST(({decimal_amount} / NULLIF({from_rate}, {zero})) * {to_rate} AS DECIMAL(38, {scale})) END"+ )++ def _visit_divide_decimal_with_scale(self, node: ast.Call) -> str:+ scale = node.args[2]+ if (+ not isinstance(scale, ast.Constant)+ or isinstance(scale.value, bool)+ or not isinstance(scale.value, int)+ or not 0 <= scale.value <= 38+ ):+ self._unsupported(+ "TRINO_DECIMAL_SCALE_UNSUPPORTED",+ "divideDecimal requires a constant result scale between 0 and 38 in Trino mode.",+ node,+ )+ return f"CAST(({self.visit(node.args[0])} / {self.visit(node.args[1])}) AS DECIMAL(38, {scale.value}))"++ def _json_default(self, node: ast.Call, expression: str, default: str) -> str:+ result = f"coalesce(TRY({expression}), {default})"+ source_type = self._resolve_type(node.args[0])+ if source_type is not None and source_type.nullable:+ return f"IF({self.visit(node.args[0])} IS NULL, NULL, {result})"+ return result++ @staticmethod+ def _json_type_default(target: str) -> str:+ if target.startswith("ARRAY"):+ return f"CAST(ARRAY[] AS {target})"+ if target.startswith("MAP"):+ return f"CAST(map(ARRAY[], ARRAY[]) AS {target})"+ if target == "VARCHAR":+ return "''"+ if target == "BOOLEAN":+ return "false"+ return f"CAST(0 AS {target})"+def _visit_json_extract(self, node: ast.Call) -> str:name = node.name.lower()+ path: str | Noneif name == "jsonextractarrayraw" and len(node.args) == 1:source = self.visit(node.args[0])value = self._print_identifier("__hogql_json_value")- return (+ extracted = (f"transform(CAST(json_parse(CAST({source} AS VARCHAR)) AS ARRAY(JSON)), "f"{value} -> json_format({value}))")- if len(node.args) < 2:+ return self._json_default(node, extracted, "CAST(ARRAY[] AS ARRAY(VARCHAR))")+ if not node.args or (name == "jsonextract" and len(node.args) < 2):self._invalid_function_arguments(node, f"{node.name} expects a JSON expression and key path in Trino mode.")if name == "jsonextract":return self._visit_typed_json_extract(node)+ if any(not isinstance(key, ast.Constant) for key in node.args[1:]):+ if any(self._is_json_array_index(key) for key in node.args[1:]):+ extracted = self._visit_json_path(self.visit(node.args[0]), node.args[1:])+ else:+ extracted = self.visit(node.args[0])+ for key in node.args[1:]:+ if isinstance(key, ast.Constant) and isinstance(key.value, (str, int)):+ path = self._json_path([key.value])+ else:+ path = self._dynamic_json_key_path(key)+ extracted = f"json_extract({extracted}, {path})"+ if name == "jsonextractraw":+ return self._json_default(node, f"json_format({extracted})", "''")+ scalar = f"json_extract_scalar({extracted}, '$')"+ casts = {+ "jsonextractint": "BIGINT",+ "jsonextractuint": "DECIMAL(20, 0)",+ "jsonextractfloat": "DOUBLE",+ "jsonextractbool": "BOOLEAN",+ }+ target_type = casts.get(name)+ if target_type is None:+ return self._json_default(node, scalar, "''")+ return self._json_default(node, f"CAST({scalar} AS {target_type})", self._json_type_default(target_type))path_members: list[str | int] = []for key in node.args[1:]:if not isinstance(key, ast.Constant) or not isinstance(key.value, (str, int)):@@ -593,12 +1643,21 @@ class TrinoPrinter(PostgresPrinter):node,)path_members.append(key.value)- path = self._json_path(path_members)source = self.visit(node.args[0])- extracted = f"json_extract({source}, {path})"- if name in {"jsonextractraw", "jsonextractarrayraw"}:- return f"json_format({extracted})"- scalar = f"json_extract_scalar({source}, {path})"+ has_array_index = any(self._is_json_array_index(key) for key in node.args[1:])+ path = None if has_array_index else self._json_path(path_members)+ extracted = (+ self._visit_json_path(source, node.args[1:]) if has_array_index else f"json_extract({source}, {path})"+ )+ if name == "jsonextractarrayraw":+ value = self._print_identifier("__hogql_json_value")+ converted = f"transform(CAST({extracted} AS ARRAY(JSON)), {value} -> json_format({value}))"+ return self._json_default(node, converted, "CAST(ARRAY[] AS ARRAY(VARCHAR))")+ if name == "jsonextractraw":+ return self._json_default(node, f"json_format({extracted})", "''")+ scalar = (+ f"json_extract_scalar({extracted}, '$')" if has_array_index else f"json_extract_scalar({source}, {path})"+ )casts = {"jsonextractint": "BIGINT","jsonextractuint": "DECIMAL(20, 0)",@@ -606,7 +1665,9 @@ class TrinoPrinter(PostgresPrinter):"jsonextractbool": "BOOLEAN",}target_type = casts.get(name)- return scalar if target_type is None else f"CAST({scalar} AS {target_type})"+ if target_type is None:+ return self._json_default(node, scalar, "''")+ return self._json_default(node, f"CAST({scalar} AS {target_type})", self._json_type_default(target_type))def _visit_typed_json_extract(self, node: ast.Call) -> str:type_arg = node.args[-1]@@ -627,9 +1688,39 @@ class TrinoPrinter(PostgresPrinter):)path_members.append(key.value)source = self.visit(node.args[0])- path = self._json_path(path_members)+ has_array_index = any(self._is_json_array_index(key) for key in node.args[1:-1])+ path = None if has_array_index else self._json_path(path_members)+ extracted = self._visit_json_path(source, node.args[1:-1]) if has_array_index else None+ if target.startswith("MAP(VARCHAR, "):+ value_type = target[len("MAP(VARCHAR, ") : -1]+ if value_type in {+ "VARCHAR",+ "BOOLEAN",+ "REAL",+ "DOUBLE",+ "TINYINT",+ "SMALLINT",+ "INTEGER",+ "BIGINT",+ "DECIMAL(20, 0)",+ }:+ raw = (+ f"CAST({extracted} AS MAP(VARCHAR, JSON))"+ if extracted+ else f"CAST(json_extract({source}, {path}) AS MAP(VARCHAR, JSON))"+ )+ converted = self._convert_json_scalar("__hogql_json_value", value_type)+ if "nullable(" not in type_arg.value.lower():+ default = "''" if value_type == "VARCHAR" else "false" if value_type == "BOOLEAN" else "0"+ converted = f"coalesce({converted}, CAST({default} AS {value_type}))"+ result = f"transform_values({raw}, (__hogql_json_key, __hogql_json_value) -> {converted})"+ return self._json_default(node, result, self._json_type_default(target))+ if extracted:+ value = extracted if target.startswith(("ARRAY", "MAP")) else f"json_extract_scalar({extracted}, '$')"+ return self._json_default(node, f"CAST({value} AS {target})", self._json_type_default(target))extractor = "json_extract" if target.startswith(("ARRAY", "MAP")) else "json_extract_scalar"- return f"CAST({extractor}({source}, {path}) AS {target})"+ converted = f"CAST({extractor}({source}, {path}) AS {target})"+ return self._json_default(node, converted, self._json_type_default(target))def _trino_json_type(self, type_name: str, node: ast.Call) -> str:normalized = " ".join(type_name.strip().lower().split())@@ -666,21 +1757,44 @@ class TrinoPrinter(PostgresPrinter):def _visit_json_metadata(self, node: ast.Call) -> str:name = node.name.lower()+ extracted: str | None+ path: str | Noneif name == "jsonextractkeysandvaluesraw":- if len(node.args) != 1:- self._invalid_function_arguments(- node, "JSONExtractKeysAndValuesRaw expects exactly 1 argument in Trino mode."- )+ if not node.args:+ self._invalid_function_arguments(node, "JSONExtractKeysAndValuesRaw expects a JSON expression.")source = self.visit(node.args[0])+ path_args = node.args[1:]+ for key in path_args:+ if not isinstance(key, ast.Constant) or not isinstance(key.value, (str, int)):+ self._unsupported(+ "TRINO_JSON_DYNAMIC_PATH_UNSUPPORTED",+ "JSONExtractKeysAndValuesRaw requires a constant key path in Trino mode.",+ node,+ )+ if path_args:+ extracted = self._visit_json_path(source, path_args)+ raw = f"CAST({extracted} AS MAP(VARCHAR, JSON))"+ else:+ raw = f"CAST(json_parse(CAST({source} AS VARCHAR)) AS MAP(VARCHAR, JSON))"entry = self._print_identifier("__hogql_json_entry")- return (- f"transform(map_entries(CAST(json_parse(CAST({source} AS VARCHAR)) AS MAP(VARCHAR, JSON))), "- f"{entry} -> ROW({entry}[1], json_format({entry}[2])))"- )+ result = f"transform(map_entries({raw}), {entry} -> ROW({entry}[1], json_format({entry}[2])))"+ return self._json_default(node, result, "CAST(ARRAY[] AS ARRAY(ROW(VARCHAR, VARCHAR)))")if not node.args:self._invalid_function_arguments(node, f"{node.name} expects a JSON expression in Trino mode.")source = self.visit(node.args[0])path_args = node.args[1:]+ if name == "jsonhas" and any(not isinstance(key, ast.Constant) for key in path_args):+ if any(self._is_json_array_index(key) for key in path_args):+ extracted = self._visit_json_path(source, path_args)+ else:+ extracted = source+ for key in path_args:+ if isinstance(key, ast.Constant) and isinstance(key.value, (str, int)):+ path = self._json_path([key.value])+ else:+ path = self._dynamic_json_key_path(key)+ extracted = f"json_extract({extracted}, {path})"+ return f"({extracted} IS NOT NULL)"target_type: str | None = Noneif name == "jsonextractkeysandvalues":if not path_args or not isinstance(path_args[-1], ast.Constant) or not isinstance(path_args[-1].value, str):@@ -711,20 +1825,83 @@ class TrinoPrinter(PostgresPrinter):node,)path_members.append(key.value)- path = self._json_path(path_members)+ extracted = (+ self._visit_json_path(source, path_args)+ if any(self._is_json_array_index(key) for key in path_args)+ else None+ )+ path = None if extracted else self._json_path(path_members)if name == "jsonhas":+ if extracted:+ return f"({extracted} IS NOT NULL)"return f"(json_extract({source}, {path}) IS NOT NULL)"if name == "jsonlength":- return f"json_size({source}, {path})"+ if extracted:+ return self._json_default(node, f"json_size({extracted}, '$')", "0")+ return self._json_default(node, f"json_size({source}, {path})", "0")if name == "jsonextractkeysandvalues":- return f"map_entries(CAST(json_extract({source}, {path}) AS MAP(VARCHAR, {target_type})))"- return f"map_keys(CAST(json_extract({source}, {path}) AS MAP(VARCHAR, JSON)))"+ raw = (+ f"CAST({extracted} AS MAP(VARCHAR, JSON))"+ if extracted+ else f"CAST(json_extract({source}, {path}) AS MAP(VARCHAR, JSON))"+ )+ value = "__hogql_json_value"+ assert target_type is not None+ converted = self._convert_json_scalar(value, target_type)+ result = (+ f"filter(map_entries(transform_values({raw}, (__hogql_json_key, {value}) -> {converted})), "+ "__hogql_entry -> __hogql_entry[2] IS NOT NULL)"+ )+ default = f"CAST(ARRAY[] AS ARRAY(ROW(VARCHAR, {target_type})))"+ return self._json_default(node, result, default)+ raw = (+ f"CAST({extracted} AS MAP(VARCHAR, JSON))"+ if extracted+ else f"CAST(json_extract({source}, {path}) AS MAP(VARCHAR, JSON))"+ )+ return self._json_default(node, f"map_keys({raw})", "CAST(ARRAY[] AS ARRAY(VARCHAR))")++ def _visit_json_type(self, node: ast.Call) -> str:+ if not 1 <= len(node.args) <= 6:+ self._invalid_function_arguments(node, "JSONType expects a JSON expression and up to five path items.")+ source = self.visit(node.args[0])+ extracted = (+ f"json_parse(CAST({source} AS VARCHAR))"+ if len(node.args) == 1+ else self._visit_json_path(source, node.args[1:])+ )+ raw = f"coalesce(json_format({extracted}), 'null')"+ result = (+ "CASE WHEN __hogql_json_type = 'null' THEN 'Null' "+ "WHEN __hogql_json_type IN ('true', 'false') THEN 'Bool' "+ "WHEN starts_with(__hogql_json_type, '\"') THEN 'String' "+ "WHEN starts_with(__hogql_json_type, '[') THEN 'Array' "+ "WHEN starts_with(__hogql_json_type, '{') THEN 'Object' "+ "WHEN regexp_like(__hogql_json_type, '^-?[0-9]+$') THEN "+ "IF(starts_with(__hogql_json_type, '-') OR TRY_CAST(__hogql_json_type AS BIGINT) IS NOT NULL, "+ "'Int64', 'UInt64') ELSE 'Double' END"+ )+ return f"IF({source} IS NULL, NULL, element_at(transform(ARRAY[{raw}], __hogql_json_type -> {result}), 1))"++ def _convert_json_scalar(self, value: str, target_type: str) -> str:+ if target_type == "VARCHAR":+ converted = f"coalesce(TRY_CAST({value} AS VARCHAR), json_format({value}))"+ return f"IF(json_format({value}) = 'null', NULL, {converted})"+ converted = f"TRY_CAST({value} AS {target_type})"+ if target_type != "BOOLEAN":+ return (+ f"CASE json_format({value}) WHEN 'true' THEN CAST(1 AS {target_type}) "+ f"WHEN 'false' THEN CAST(0 AS {target_type}) ELSE {converted} END"+ )+ return converteddef _visit_to_datetime64(self, node: ast.Call) -> str:- if len(node.args) not in {1, 2}:- self._invalid_function_arguments(node, "toDateTime64 expects a value and optional precision in Trino mode.")+ if len(node.args) not in {1, 2, 3}:+ self._invalid_function_arguments(+ node, "toDateTime64 expects a value, optional precision, and optional timezone in Trino mode."+ )precision = 3- if len(node.args) == 2:+ if len(node.args) >= 2:precision_arg = node.args[1]if (not isinstance(precision_arg, ast.Constant)@@ -738,9 +1915,24 @@ class TrinoPrinter(PostgresPrinter):node,)precision = precision_arg.value- return f"CAST({self.visit(node.args[0])} AS TIMESTAMP({precision}))"+ timestamp = f"CAST({self.visit(node.args[0])} AS TIMESTAMP({precision}))"+ return f"with_timezone({timestamp}, {self.visit(node.args[2])})" if len(node.args) == 3 else timestamp- def _visit_parse_datetime(self, node: ast.Call) -> str:+ def _visit_parse_datetime_best_effort(self, node: ast.Call) -> str:+ if len(node.args) not in {1, 2}:+ self._invalid_function_arguments(node, "parseDateTimeBestEffort expects a string and optional timezone.")+ value = self.visit(node.args[0])+ timezone = self.visit(node.args[1]) if len(node.args) == 2 else self.context.add_value(self._get_timezone())+ day_month_year = self.context.add_value("%e-%b-%y")+ parsed = (+ f"coalesce(IF(regexp_like({value}, '(Z|[+-][0-9]{{2}}:[0-9]{{2}})$'), TRY(from_iso8601_timestamp({value}))), "+ f"IF(regexp_like({value}, '^[0-9]{{9,10}}$'), from_unixtime(TRY_CAST({value} AS DOUBLE))), "+ f"with_timezone(TRY(date_parse({value}, {day_month_year})), {timezone}), "+ f"with_timezone(CAST({value} AS TIMESTAMP), {timezone}))"+ )+ return f"CAST(at_timezone({parsed}, {timezone}) AS TIMESTAMP)"++ def _visit_parse_datetime(self, node: ast.Call) -> str:if len(node.args) not in {2, 3}:self._invalid_function_arguments(node, "parseDateTime expects a value, format, and optional timezone in Trino mode."@@ -830,6 +2022,32 @@ class TrinoPrinter(PostgresPrinter):node,)+ def _dynamic_json_key_path(self, key: ast.Expr) -> str:+ return f"concat('$[', json_format(CAST(CAST({self.visit(key)} AS VARCHAR) AS JSON)), ']')"++ def _is_json_array_index(self, key: ast.Expr) -> bool:+ return (isinstance(key, ast.Constant) and isinstance(key.value, int) and not isinstance(key.value, bool)) or (+ not isinstance(key, ast.Constant) and self._is_numeric(key)+ )++ def _visit_json_path(self, source: str, keys: Iterable[ast.Expr]) -> str:+ extracted = source+ is_json = False+ for key in keys:+ if self._is_json_array_index(key):+ index = str(key.value) if isinstance(key, ast.Constant) else f"CAST({self.visit(key)} AS INTEGER)"+ value = extracted if is_json else f"json_parse(CAST({extracted} AS VARCHAR))"+ extracted = f"TRY(element_at(CAST({value} AS ARRAY(JSON)), {index}))"+ else:+ path = (+ self._json_path([key.value])+ if isinstance(key, ast.Constant) and isinstance(key.value, str)+ else self._dynamic_json_key_path(key)+ )+ extracted = f"json_extract({extracted}, {path})"+ is_json = True+ return extracted+def _json_path(self, members: Iterable[str | int]) -> str:path = "$"for member in members:@@ -841,10 +2059,197 @@ class TrinoPrinter(PostgresPrinter):return self.context.add_value(path)def _visit_lambda_array_call(self, node: ast.Call, target: str) -> str:+ if (+ node.name.lower() == "arraymap"+ and len(node.args) == 3+ and isinstance(node.args[0], ast.Lambda)+ and len(node.args[0].args) == 2+ ):+ left = self.visit(node.args[1])+ right = self.visit(node.args[2])+ mapped = f"zip_with({left}, {right}, {self.visit(node.args[0])})"+ return (+ f"IF(cardinality({left}) = cardinality({right}), {mapped}, "+ "fail('arrayMap requires equal-length arrays'))"+ )if len(node.args) != 2 or not isinstance(node.args[0], ast.Lambda):self._invalid_function_arguments(node, f"{node.name} expects a lambda and array in Trino mode.")return f"{target}({self.visit(node.args[1])}, {self.visit(node.args[0])})"+ def _visit_array_sort_key(self, node: ast.Call) -> str:+ key = node.args[0]+ if not isinstance(key, ast.Lambda) or len(key.args) != 1:+ self._invalid_function_arguments(node, "arraySort expects a single-argument key lambda and array.")+ arg = self._print_identifier(key.args[0])+ keyed = f"transform({self.visit(node.args[1])}, {arg} -> ROW({self.visit(key.expr)}, {arg}))"+ return (+ f"transform(array_sort({keyed}, (__hogql_left, __hogql_right) -> "+ "CASE WHEN __hogql_left[1] IS NULL AND __hogql_right[1] IS NULL THEN 0 "+ "WHEN __hogql_left[1] IS NULL THEN 1 WHEN __hogql_right[1] IS NULL THEN -1 "+ "WHEN __hogql_left[1] < __hogql_right[1] THEN -1 "+ "WHEN __hogql_left[1] > __hogql_right[1] THEN 1 ELSE 0 END), __hogql_pair -> __hogql_pair[2])"+ )++ def _visit_array_auc(self, node: ast.Call) -> str:+ if len(node.args) != 2:+ self._invalid_function_arguments(node, "arrayAUC expects score and label arrays in Trino mode.")+ score_type = self._resolve_type(node.args[0])+ label_type = self._resolve_type(node.args[1])+ if (+ not isinstance(score_type, ast.ArrayType)+ or not isinstance(score_type.item_type, (ast.IntegerType, ast.FloatType))+ or score_type.item_type.nullable+ or not isinstance(label_type, ast.ArrayType)+ or not isinstance(label_type.item_type, (ast.IntegerType, ast.FloatType))+ or label_type.item_type.nullable+ ):+ self._invalid_function_arguments(node, "arrayAUC requires non-null numeric score and label items.")+ scores = self.visit(node.args[0])+ labels = self.visit(node.args[1])+ pairs = (+ "zip(transform(__hogql_auc_arrays[1], __hogql_score -> CAST(__hogql_score AS DOUBLE)), "+ "transform(__hogql_auc_arrays[2], __hogql_label -> __hogql_label <> 0))"+ )+ ordered = (+ f"array_sort({pairs}, (__hogql_left, __hogql_right) -> CASE "+ "WHEN is_nan(__hogql_left[1]) AND is_nan(__hogql_right[1]) THEN 0 "+ "WHEN is_nan(__hogql_left[1]) THEN 1 WHEN is_nan(__hogql_right[1]) THEN -1 "+ "WHEN __hogql_left[1] < __hogql_right[1] THEN -1 "+ "WHEN __hogql_left[1] > __hogql_right[1] THEN 1 ELSE 0 END)"+ )+ state_type = (+ "ROW(seen BOOLEAN, score DOUBLE, group_positive BIGINT, group_negative BIGINT, "+ "negative_before BIGINT, positive_total BIGINT, negative_total BIGINT, favorable DOUBLE)"+ )+ positive = "IF(__hogql_pair[2], BIGINT '1', BIGINT '0')"+ negative = "IF(__hogql_pair[2], BIGINT '0', BIGINT '1')"+ same_score = "(is_nan(__hogql_state[2]) AND is_nan(__hogql_pair[1])) OR __hogql_state[2] = __hogql_pair[1]"+ initial = f"CAST(ROW(false, 0e0, 0, 0, 0, 0, 0, 0e0) AS {state_type})"+ first = (+ f"CAST(ROW(true, __hogql_pair[1], {positive}, {negative}, 0, {positive}, {negative}, 0e0) AS {state_type})"+ )+ tied = (+ f"CAST(ROW(true, __hogql_state[2], __hogql_state[3] + {positive}, "+ f"__hogql_state[4] + {negative}, __hogql_state[5], __hogql_state[6] + {positive}, "+ f"__hogql_state[7] + {negative}, __hogql_state[8]) AS {state_type})"+ )+ next_score = (+ f"CAST(ROW(true, __hogql_pair[1], {positive}, {negative}, "+ f"__hogql_state[5] + __hogql_state[4], __hogql_state[6] + {positive}, "+ f"__hogql_state[7] + {negative}, __hogql_state[8] + __hogql_state[3] * "+ f"(__hogql_state[5] + __hogql_state[4] / 2e0)) AS {state_type})"+ )+ scan = (+ f"reduce({ordered}, {initial}, (__hogql_state, __hogql_pair) -> "+ f"IF(NOT __hogql_state[1], {first}, IF({same_score}, {tied}, {next_score})), "+ "__hogql_state -> __hogql_state)"+ )+ favorable = "__hogql_state[8] + __hogql_state[3] * (__hogql_state[5] + __hogql_state[4] / 2e0)"+ result = (+ "IF(__hogql_state[6] = 0 OR __hogql_state[7] = 0, nan(), "+ f"({favorable}) / (__hogql_state[6] * __hogql_state[7]))"+ )+ result = f"element_at(transform(ARRAY[{scan}], __hogql_state -> {result}), 1)"+ result = (+ "IF(cardinality(__hogql_auc_arrays[1]) = cardinality(__hogql_auc_arrays[2]), "+ f"{result}, fail('arrayAUC requires equal-length arrays'))"+ )+ return (+ f"element_at(transform(ARRAY[ROW({scores}, {labels})], __hogql_auc_arrays -> "+ f"IF(__hogql_auc_arrays[1] IS NULL OR __hogql_auc_arrays[2] IS NULL, NULL, {result})), 1)"+ )++ def _visit_start_of_interval(self, node: ast.Call) -> str:+ if len(node.args) not in {2, 3} or not isinstance(node.args[1], ast.Call):+ self._invalid_function_arguments(node, "toStartOfInterval expects a timestamp and constant interval.")+ interval = node.args[1]+ fixed_units = {+ "tointervalsecond": 1,+ "tointervalminute": 60,+ "tointervalhour": 60 * 60,+ "tointervalday": 24 * 60 * 60,+ "tointervalweek": 7 * 24 * 60 * 60,+ }+ calendar_units = {"tointervalmonth": 1, "tointervalquarter": 3, "tointervalyear": 12}+ normalized_unit = interval.name.lower()+ unit = fixed_units.get(normalized_unit) or calendar_units.get(normalized_unit)+ if (+ unit is None+ or len(interval.args) != 1+ or not isinstance(interval.args[0], ast.Constant)+ or not isinstance(interval.args[0].value, int)+ or interval.args[0].value <= 0+ ):+ self._unsupported(+ "TRINO_INTERVAL_BUCKET_UNSUPPORTED",+ "toStartOfInterval requires a positive constant whole-unit interval in Trino mode.",+ node,+ )+ width = unit * interval.args[0].value+ value = self.visit(node.args[0])+ if len(node.args) == 3:+ origin = self.visit(node.args[2])+ elif normalized_unit == "tointervalhour":+ origin = f"date_trunc('day', {value})"+ else:+ origins = {+ "tointervalsecond": "TIMESTAMP '1970-01-01 00:00:00'",+ "tointervalminute": "TIMESTAMP '1970-01-01 00:00:00'",+ "tointervalday": "TIMESTAMP '1970-01-01 00:00:00'",+ "tointervalweek": "TIMESTAMP '1970-01-05 00:00:00'",+ "tointervalmonth": "TIMESTAMP '1900-01-01 00:00:00'",+ "tointervalquarter": "TIMESTAMP '1900-01-01 00:00:00'",+ "tointervalyear": "TIMESTAMP '0000-01-01 00:00:00'",+ }+ origin = origins[normalized_unit]+ if normalized_unit in calendar_units:+ bucket = (+ f"date_add('month', CAST(floor(date_diff('month', {origin}, {value}) / {width}e0) AS BIGINT) * "+ f"{width}, {origin})"+ )+ return f"CAST({bucket} AS DATE)"+ return (+ f"date_add('second', CAST(floor(date_diff('second', {origin}, {value}) / {width}e0) AS BIGINT) * "+ f"{width}, {origin})"+ )++ def _visit_date_bin(self, node: ast.Call) -> str:+ if len(node.args) != 3 or not isinstance(node.args[0], ast.Call):+ self._invalid_function_arguments(node, "date_bin expects a constant interval, timestamp, and origin.")+ interval = node.args[0]+ fixed_units = {+ "tointervalsecond": 1,+ "tointervalminute": 60,+ "tointervalhour": 60 * 60,+ "tointervalday": 24 * 60 * 60,+ "tointervalweek": 7 * 24 * 60 * 60,+ }+ calendar_units = {"tointervalmonth": 1, "tointervalquarter": 3, "tointervalyear": 12}+ normalized_unit = interval.name.lower()+ unit = fixed_units.get(normalized_unit) or calendar_units.get(normalized_unit)+ if (+ unit is None+ or len(interval.args) != 1+ or not isinstance(interval.args[0], ast.Constant)+ or not isinstance(interval.args[0].value, int)+ or interval.args[0].value <= 0+ ):+ self._unsupported(+ "TRINO_INTERVAL_BUCKET_UNSUPPORTED",+ "date_bin requires a positive constant whole-unit interval in Trino mode.",+ node,+ )+ width = unit * interval.args[0].value+ source = self.visit(node.args[1])+ origin = self.visit(node.args[2])+ date_part = "month" if normalized_unit in calendar_units else "second"+ bucket = f"date_add('{date_part}', CAST(floor(date_diff('{date_part}', __hogql_date_bin[2], __hogql_date_bin[1]) / {width}e0) AS BIGINT) * {width}, __hogql_date_bin[2])"+ bucket = (+ "IF(__hogql_date_bin[1] < __hogql_date_bin[2], "+ f"fail('date_bin origin must not be after timestamp'), {bucket})"+ )+ return f"element_at(transform(ARRAY[ROW({source}, {origin})], __hogql_date_bin -> {bucket}), 1)"+def _visit_unary_function(self, node: ast.Call, target: str) -> str:return f"{target}({self._visit_unary_arg(node)})"@@ -877,33 +2282,448 @@ class TrinoPrinter(PostgresPrinter):else:self._invalid_function_arguments(node, "range expects one or two arguments in Trino mode.")value = self._print_identifier("__hogql_range_value")- return f"filter(sequence({start}, greatest(({end}) - 1, {start})), {value} -> ({value} < {end}))"+ if all(isinstance(arg, ast.Constant) for arg in node.args):+ return f"filter(sequence({start}, greatest(({end}) - 1, {start})), {value} -> ({value} < {end}))"+ return (+ f"element_at(transform(ARRAY[ROW({start}, {end})], __hogql_range -> "+ "filter(sequence(__hogql_range[1], greatest(__hogql_range[2] - 1, __hogql_range[1])), "+ f"{value} -> ({value} < __hogql_range[2]))), 1)"+ )def _visit_map_from_arrays(self, node: ast.Call) -> str:if len(node.args) != 2:self._invalid_function_arguments(node, "mapFromArrays expects key and value arrays in Trino mode.")- keys = node.args[0]- if not isinstance(keys, ast.Array) or any(- not isinstance(key, ast.Constant) or key.value is None for key in keys.exprs+ key_expression = node.args[0]+ if isinstance(key_expression, ast.Array) and all(+ isinstance(key, ast.Constant) and key.value is not None for key in key_expression.exprs):- self._unsupported(- "TRINO_MAP_KEYS_UNPROVEN",- "mapFromArrays requires constant non-null keys so Trino map semantics can be verified.",- node,+ key_values = [key.value for key in key_expression.exprs if isinstance(key, ast.Constant)]+ if any(value in key_values[:index] for index, value in enumerate(key_values)):+ self._unsupported(+ "TRINO_MAP_DUPLICATE_KEYS_UNSUPPORTED",+ "ClickHouse maps with duplicate keys cannot be represented safely in Trino.",+ node,+ )+ return self._visit_binary_function(node, "map")+ keys = self.visit(node.args[0])+ values = self.visit(node.args[1])+ return (+ f"element_at(transform(ARRAY[ROW({keys}, {values})], __hogql_args -> "+ "IF(cardinality(__hogql_args[1]) = cardinality(__hogql_args[2]) "+ "AND all_match(__hogql_args[1], __hogql_key -> __hogql_key IS NOT NULL) "+ "AND cardinality(array_distinct(__hogql_args[1])) = cardinality(__hogql_args[1]), "+ "map(__hogql_args[1], __hogql_args[2]), "+ "fail('mapFromArrays requires equal-length arrays with unique, non-null keys'))), 1)"+ )++ def _visit_map_populate_series(self, node: ast.Call) -> str:+ if len(node.args) not in {1, 2}:+ self._invalid_function_arguments(node, "mapPopulateSeries supports a map and optional maximum key.")+ map_type = self._resolve_type(node.args[0])+ if not isinstance(map_type, ast.MapType) or not isinstance(map_type.key_type, ast.IntegerType):+ self._invalid_function_arguments(node, "mapPopulateSeries requires a resolved integer-keyed map type.")+ source = self.visit(node.args[0])+ upper = self.visit(node.args[1]) if len(node.args) == 2 else "array_max(map_keys(__hogql_series_map))"+ default = self._default_value(map_type.value_type, node)+ keys = (+ f"filter(sequence(array_min(map_keys(__hogql_series_map)), "+ f"greatest(array_min(map_keys(__hogql_series_map)), {upper})), __hogql_key -> __hogql_key <= {upper})"+ )+ entries = (+ f"transform({keys}, __hogql_key -> ROW(__hogql_key, "+ f"IF(contains(map_keys(__hogql_series_map), __hogql_key), "+ f"element_at(__hogql_series_map, __hogql_key), {default})))"+ )+ result = f"IF(cardinality(__hogql_series_map) = 0, __hogql_series_map, map_from_entries({entries}))"+ return f"element_at(transform(ARRAY[{source}], __hogql_series_map -> {result}), 1)"++ def _tuple_arithmetic_type(self, node: ast.Call) -> ast.TupleType:+ name = node.name.lower()+ if len(node.args) != (1 if name == "tuplenegate" else 2):+ self._invalid_function_arguments(node, f"{node.name} has an unsupported argument count in Trino mode.")+ left_type = self._resolve_type(node.args[0])+ if not isinstance(left_type, ast.TupleType) or left_type.repeat or not left_type.item_types:+ self._invalid_function_arguments(node, f"{node.name} requires a tuple with known items in Trino mode.")+ right_type = self._resolve_type(node.args[1]) if len(node.args) == 2 else None+ right_items: list[ast.ConstantType | None]+ if name.endswith("bynumber"):+ right_items = [right_type] * len(left_type.item_types)+ elif name == "tuplenegate":+ right_items = list(left_type.item_types)+ else:+ if (+ not isinstance(right_type, ast.TupleType)+ or right_type.repeat+ or len(left_type.item_types) != len(right_type.item_types)+ ):+ self._invalid_function_arguments(node, f"{node.name} requires equal tuple sizes in Trino mode.")+ right_items = list(right_type.item_types)+ result_types: list[ast.ConstantType] = []+ for left_item, right_item in zip(left_type.item_types, right_items):+ if name != "tuplehammingdistance" and not all(+ isinstance(item, (ast.IntegerType, ast.FloatType)) for item in (left_item, right_item)+ ):+ self._invalid_function_arguments(node, f"{node.name} requires integer or float items in Trino mode.")+ nullable = left_item.nullable or (right_item is not None and right_item.nullable)+ result_types.append(+ ast.FloatType(nullable=nullable)+ if "divide" in name or any(isinstance(item, ast.FloatType) for item in (left_item, right_item))+ else ast.IntegerType(nullable=nullable))- key_values = [key.value for key in keys.exprs if isinstance(key, ast.Constant)]- if any(value in key_values[:index] for index, value in enumerate(key_values)):+ return ast.TupleType(item_types=result_types)++ def _visit_tuple_arithmetic(self, node: ast.Call) -> str:+ name = node.name.lower()+ result_type = self._tuple_arithmetic_type(node)+ operator = TRINO_TUPLE_OPERATORS[name]+ items = []+ for index in range(1, len(result_type.item_types) + 1):+ left = f"__hogql_tuple_args[1][{index}]"+ right = f"__hogql_tuple_args[2][{index}]"+ if name.endswith("bynumber"):+ right = "__hogql_tuple_args[2]"+ if name == "tuplenegate":+ items.append(f"(-{left})")+ elif name == "tuplehammingdistance":+ items.append(f"CAST({left} != {right} AS BIGINT)")+ else:+ if operator == "/":+ left = f"CAST({left} AS DOUBLE)"+ items.append(f"({left} {operator} {right})")+ result = f"({' + '.join(items)})" if name == "tuplehammingdistance" else f"ROW({', '.join(items)})"+ args = ", ".join(self.visit(arg) for arg in node.args)+ return f"element_at(transform(ARRAY[ROW({args})], __hogql_tuple_args -> {result}), 1)"++ def _default_value(self, value_type: ast.ConstantType | None, node: ast.Call) -> str:+ if isinstance(value_type, ast.UnknownType):self._unsupported(- "TRINO_MAP_DUPLICATE_KEYS_UNSUPPORTED",- "ClickHouse maps with duplicate keys cannot be represented safely in Trino.",- node,+ "TRINO_DEFAULT_VALUE_TYPE_UNSUPPORTED", f"{node.name} requires a known result type in Trino mode.", node)- return self._visit_binary_function(node, "map")+ if value_type is not None and value_type.nullable:+ return "NULL"+ if isinstance(value_type, ast.StringType):+ return "''"+ if isinstance(value_type, (ast.IntegerType, ast.DecimalType)):+ return "0"+ if isinstance(value_type, ast.FloatType):+ return "DOUBLE '0'"+ if isinstance(value_type, ast.BooleanType):+ return "FALSE"+ if isinstance(value_type, ast.DateType):+ return "DATE '1970-01-01'"+ if isinstance(value_type, ast.DateTimeType):+ return "TIMESTAMP '1970-01-01 00:00:00'"+ if isinstance(value_type, ast.ArrayType):+ return "ARRAY[]"+ if isinstance(value_type, ast.TupleType):+ return f"ROW({', '.join(self._default_value(item, node) for item in value_type.item_types)})"+ self._unsupported(+ "TRINO_DEFAULT_VALUE_TYPE_UNSUPPORTED", f"{node.name} requires a supported result type in Trino mode.", node+ )++ def _visit_vector_rewrite(self, node: ast.Call) -> str:+ name = node.name.lower()+ normalized = name.endswith("normalize")+ distance = name == "lpdistance"+ parameterized = name.startswith("lp")+ expected_args = 1 + int(distance) + int(parameterized)+ if len(node.args) != expected_args:+ self._invalid_function_arguments(node, f"{node.name} has an unsupported argument count in Trino mode.")+ vectors = []+ first_type = self._resolve_type(node.args[0])+ for source in node.args[: 2 if distance else 1]:+ value_type = self._resolve_type(source)+ if isinstance(value_type, ast.ArrayType) and not normalized:+ item_types = [value_type.item_type]+ vector = f"transform({self.visit(source)}, __hogql_item -> CAST(__hogql_item AS DOUBLE))"+ elif isinstance(value_type, ast.TupleType) and value_type.item_types and not value_type.repeat:+ item_types = value_type.item_types+ items = ", ".join(f"CAST(__hogql_tuple[{index}] AS DOUBLE)" for index in range(1, len(item_types) + 1))+ vector = f"element_at(transform(ARRAY[{self.visit(source)}], __hogql_tuple -> ARRAY[{items}]), 1)"+ else:+ self._invalid_function_arguments(+ node, f"{node.name} requires a supported numeric vector in Trino mode."+ )+ if any(not isinstance(item, (ast.IntegerType, ast.FloatType)) or item.nullable for item in item_types):+ self._invalid_function_arguments(+ node, f"{node.name} requires non-null integer or float items in Trino mode."+ )+ vectors.append(vector)+ if distance and type(first_type) is not type(self._resolve_type(node.args[1])):+ self._invalid_function_arguments(node, "LpDistance requires two arrays or two tuples in Trino mode.")+ parameter = self.visit(node.args[-1]) if parameterized else ("2" if name == "l2normalize" else "1")+ values = "__hogql_vectors[1]"+ if distance:+ values = "zip_with(__hogql_vectors[1], __hogql_vectors[2], (__hogql_left, __hogql_right) -> __hogql_left - __hogql_right)"+ exponent = f"CAST(__hogql_vectors[{len(vectors) + 1}] AS DOUBLE)"+ if name == "linfnormalize":+ norm = f"coalesce(array_max(transform({values}, __hogql_item -> abs(__hogql_item))), DOUBLE '0')"+ else:+ norm = f"power(reduce({values}, DOUBLE '0', (__hogql_total, __hogql_item) -> __hogql_total + power(abs(__hogql_item), {exponent}), __hogql_total -> __hogql_total), 1e0 / {exponent})"+ result = norm+ if normalized:+ assert isinstance(first_type, ast.TupleType)+ items = ", ".join(+ f"element_at(__hogql_vectors[1], {index}) / __hogql_norm"+ for index in range(1, len(first_type.item_types) + 1)+ )+ result = f"element_at(transform(ARRAY[{norm}], __hogql_norm -> ROW({items})), 1)"+ if parameterized:+ result = f"IF(is_nan({exponent}) OR ({exponent} >= 1 AND NOT is_infinite({exponent})), {result}, fail('Lp exponent must be at least one and not infinite'))"+ if distance:+ result = f"IF(cardinality(__hogql_vectors[1]) = cardinality(__hogql_vectors[2]), {result}, fail('LpDistance requires equal vector lengths'))"+ return f"element_at(transform(ARRAY[ROW({', '.join([*vectors, parameter])})], __hogql_vectors -> {result}), 1)"++ def _visit_array_reduce(self, node: ast.Call) -> str:+ if len(node.args) < 2 or not isinstance(node.args[0], ast.Constant) or not isinstance(node.args[0].value, str):+ self._invalid_function_arguments(node, "arrayReduce requires a constant aggregate name in Trino mode.")+ aggregate_name = node.args[0].value+ aggregates = {+ f"{base}{suffix}": (base, suffix)+ for base in ("sum", "avg", "min", "max", "count")+ for suffix in ("", "Map")+ }+ if aggregate_name not in aggregates or len(node.args) != 2:+ self._invalid_function_arguments(node, "arrayReduce does not support this aggregate form in Trino mode.")+ array_type = self._resolve_type(node.args[1])+ if not isinstance(array_type, ast.ArrayType):+ self._invalid_function_arguments(node, "arrayReduce requires a resolved array type in Trino mode.")+ values = self.visit(node.args[1])+ base, mode = aggregates[aggregate_name]+ if mode:+ return self._container_aggregate(node, base, mode, values, array_type.item_type)+ return self._array_aggregate(node, base, values, array_type.item_type)++ def _visit_array_scan(self, node: ast.Call) -> str:+ name = node.name.lower()+ fill = name in {"arrayfill", "arrayreversefill"}+ split = name in {"arraysplit", "arrayreversesplit"}+ has_lambda = bool(node.args) and isinstance(node.args[0], ast.Lambda)+ if len(node.args) != (2 if has_lambda else 1) or ((fill or split) and not has_lambda):+ self._invalid_function_arguments(+ node, f"{node.name} requires one array and an optional single-argument lambda in Trino mode."+ )+ array = node.args[-1]+ array_type = self._resolve_type(array)+ if not isinstance(array_type, ast.ArrayType):+ self._invalid_function_arguments(node, f"{node.name} requires a resolved array type in Trino mode.")+ if has_lambda:+ predicate = node.args[0]+ assert isinstance(predicate, ast.Lambda)+ if len(predicate.args) != 1 or not isinstance(predicate.expr, ast.Expr):+ self._invalid_function_arguments(node, f"{node.name} requires a single-argument lambda in Trino mode.")+ mapped = f"transform(__hogql_scan_array, {self.visit(predicate)})"+ item_type = self._resolve_type(predicate.expr)+ else:+ mapped = "__hogql_scan_array"+ item_type = array_type.item_type+ if split:+ size = "cardinality(__hogql_scan_array)"+ condition_index = "__hogql_position - 1" if name == "arrayreversesplit" else "__hogql_position"+ positions = f"filter(sequence(1, {size}), __hogql_position -> IF(__hogql_position > 1, CAST(element_at(__hogql_flags, {condition_index}) AS BOOLEAN), FALSE))"+ boundaries = f"concat(ARRAY[1], {positions}, ARRAY[{size} + 1])"+ result = (+ f"element_at(transform(ARRAY[{boundaries}], __hogql_boundaries -> "+ "transform(sequence(1, cardinality(__hogql_boundaries) - 1), __hogql_segment -> "+ "slice(__hogql_scan_array, __hogql_boundaries[__hogql_segment], "+ "__hogql_boundaries[__hogql_segment + 1] - __hogql_boundaries[__hogql_segment]))), 1)"+ )+ result = f"IF({size} = 0, ARRAY[], element_at(transform(ARRAY[{mapped}], __hogql_flags -> {result}), 1))"+ elif fill:+ pairs = f"zip(__hogql_scan_array, {mapped})"+ if name == "arrayreversefill":+ pairs = f"reverse({pairs})"+ item = "IF(cardinality(__hogql_filled) = 0 OR CAST(__hogql_pair[2] AS BOOLEAN), __hogql_pair[1], element_at(__hogql_filled, -1))"+ result = f"reduce({pairs}, slice(__hogql_scan_array, 1, 0), (__hogql_filled, __hogql_pair) -> concat(__hogql_filled, ARRAY[{item}], slice(__hogql_scan_array, 1, 0)), __hogql_filled -> __hogql_filled)"+ if name == "arrayreversefill":+ result = f"reverse({result})"+ else:+ if not isinstance(item_type, (ast.IntegerType, ast.FloatType)) or item_type.nullable:+ self._invalid_function_arguments(+ node, f"{node.name} requires non-null integer or float items in Trino mode."+ )+ numeric_type = "DOUBLE" if isinstance(item_type, ast.FloatType) else "BIGINT"+ total = "__hogql_scan_state[1] + __hogql_item"+ if name == "arraycumsumnonnegative":+ total = f"greatest({total}, 0)"+ initial = f"CAST(ROW(0, ARRAY[]) AS ROW(total {numeric_type}, items ARRAY({numeric_type})))"+ result = f"reduce({mapped}, {initial}, (__hogql_scan_state, __hogql_item) -> ROW({total}, concat(__hogql_scan_state[2], ARRAY[{total}])), __hogql_scan_state -> __hogql_scan_state[2])"+ return f"element_at(transform(ARRAY[{self.visit(array)}], __hogql_scan_array -> {result}), 1)"++ def _argument_aggregate(+ self,+ node: ast.Call,+ base: str,+ mode: str,+ empty: str,+ args: list[ast.Expr],+ aggregate_filter: str,+ window_predicate: str,+ ) -> str:+ if len(args) != 2 and not (base == "count" and len(args) == 1):+ self._invalid_function_arguments(node, f"{node.name} requires a value and a selection key in Trino mode.")+ key_type = self._resolve_type(args[-1])+ if not isinstance(+ key_type,+ (ast.IntegerType, ast.FloatType, ast.StringType, ast.DateType, ast.DateTimeType, ast.BooleanType),+ ):+ self._invalid_function_arguments(+ node, f"{node.name} requires a supported scalar selection key in Trino mode."+ )+ value_type = self._resolve_type(args[0]) if len(args) == 2 else ast.IntegerType()+ if value_type is None:+ self._invalid_function_arguments(node, f"{node.name} requires a resolved value type in Trino mode.")+ item_type = replace(value_type, nullable=value_type.nullable or key_type.nullable)+ value = self.visit(args[0]) if len(args) == 2 else "1"+ row = f"ROW({value}, {self.visit(args[-1])})"+ if window_predicate:+ row = f"IF({window_predicate}, {row}, NULL)"+ rows = f"coalesce(array_agg({row}){aggregate_filter}, ARRAY[])"+ valid_rows = "filter(__hogql_arg_rows, __hogql_arg_row -> __hogql_arg_row[2] IS NOT NULL)"+ values = "filter(__hogql_key_rows, __hogql_arg_row -> __hogql_arg_row[1] IS NOT NULL)"+ direction = "min" if mode == "ArgMin" else "max"+ extreme = f"array_{direction}(transform(__hogql_value_rows, __hogql_arg_row -> __hogql_arg_row[2]))"+ selected = "transform(filter(__hogql_value_rows, __hogql_arg_row -> __hogql_arg_row[2] = __hogql_extreme), __hogql_arg_row -> __hogql_arg_row[1])"+ result = self._array_aggregate(node, base, selected, item_type)+ if empty:+ default = (+ "NULL"+ if empty == "OrNull"+ else ("0" if base in {"count", "countDistinct"} else self._default_value(item_type, node))+ )+ result = f"IF(cardinality(__hogql_value_rows) = 0, {default}, {result})"+ result = f"element_at(transform(ARRAY[{extreme}], __hogql_extreme -> {result}), 1)"+ result = f"element_at(transform(ARRAY[{values}], __hogql_value_rows -> {result}), 1)"+ result = f"element_at(transform(ARRAY[{valid_rows}], __hogql_key_rows -> {result}), 1)"+ if isinstance(key_type, ast.FloatType):+ result = f"IF(any_match(__hogql_arg_rows, __hogql_arg_row -> coalesce(is_nan(__hogql_arg_row[2]), false)), fail('NaN selection keys are not supported'), {result})"+ if base in {"min", "max"} and isinstance(value_type, ast.FloatType):+ result = f"IF(any_match(__hogql_arg_rows, __hogql_arg_row -> coalesce(is_nan(__hogql_arg_row[1]), false)), fail('NaN argument-selection values are not supported'), {result})"+ return f"element_at(transform(ARRAY[{rows}], __hogql_arg_rows -> {result}), 1)"++ def _visit_aggregate_combinator(self, node: ast.Call, *, over: str = "") -> str:+ base, array, empty, conditional = TRINO_AGGREGATE_COMBINATORS[node.name.lower()]+ if node.params or node.distinct or node.order_by or node.within_group:+ self._invalid_function_arguments(+ node, f"{node.name} does not support these aggregate modifiers in Trino mode."+ )+ args = node.args[:-1] if conditional else node.args+ predicates = []+ if conditional:+ predicates.append(self._visit_predicate(node.args[-1]))+ if node.filter_expr is not None:+ predicates.append(self._visit_predicate(node.filter_expr))+ predicate_sql = " AND ".join(f"({predicate})" for predicate in predicates)+ window_predicate = predicate_sql if over else ""+ aggregate_filter = f" FILTER (WHERE {predicate_sql})" if predicates and not over else ""+ aggregate_filter += over+ if array in {"ArgMin", "ArgMax"}:+ return self._argument_aggregate(node, base, array, empty, args, aggregate_filter, window_predicate)+ if len(args) != 1 and not (base == "count" and not array and not args):+ self._invalid_function_arguments(node, f"{node.name} requires one value argument in Trino mode.")+ value = self.visit(args[0]) if args else "*"+ value_type = self._resolve_type(args[0]) if args else ast.IntegerType()+ if value_type is None:+ self._invalid_function_arguments(node, f"{node.name} requires a resolved value type in Trino mode.")+ if window_predicate:+ value = f"IF({window_predicate}, {value if args else '1'}, NULL)"+ count = f"count({value}){aggregate_filter}"+ if not array:+ if base == "median":+ rows = f"coalesce(array_agg({value}){aggregate_filter}, ARRAY[])"+ result = self._array_aggregate(node, base, rows, value_type)+ if empty == "OrNull":+ return f"IF({count} = 0, NULL, {result})"+ default = self._default_value(value_type, node)+ return f"IF({count} = 0, {default}, {result})"+ target = "count" if base == "countDistinct" else base+ distinct = "DISTINCT " if base == "countDistinct" else ""+ aggregate = f"{target}({distinct}{value}){aggregate_filter}"+ if empty == "OrNull":+ return f"IF({count} = 0, NULL, {aggregate})"+ if base in {"count", "countDistinct"}:+ return aggregate+ default = self._default_value(value_type, node)+ return f"coalesce({aggregate}, {default})"+ rows = f"coalesce(array_agg({value}){aggregate_filter}, ARRAY[])"+ if window_predicate:+ rows = f"filter({rows}, __hogql_array -> __hogql_array IS NOT NULL)"+ if array in {"ForEach", "Map"}:+ return self._container_aggregate(node, base, array, rows, value_type)+ if not isinstance(value_type, ast.ArrayType):+ self._invalid_function_arguments(node, f"{node.name} requires a resolved array type in Trino mode.")+ item_type = value_type.item_type+ values = f"flatten({rows})"+ result = self._array_aggregate(node, base, values, item_type)+ nullable_array_aggregate = not over and node.name.lower() in {"avgarray", "medianarray"}+ if empty or nullable_array_aggregate:+ default = "0" if base in {"count", "countDistinct"} else self._default_value(item_type, node)+ empty_value = "NULL" if empty == "OrNull" or nullable_array_aggregate else default+ result = f"IF({count} = 0, {empty_value}, {result})"+ return result++ def _container_aggregate(+ self, node: ast.Call, base: str, mode: str, rows: str, value_type: ast.ConstantType | None+ ) -> str:+ if mode == "ForEach":+ if not isinstance(value_type, ast.ArrayType):+ self._invalid_function_arguments(node, f"{node.name} requires a resolved array type in Trino mode.")+ maximum = "coalesce(array_max(transform(__hogql_rows, __hogql_row -> cardinality(__hogql_row))), 0)"+ positions = (+ f"filter(sequence(1, greatest({maximum}, 1)), __hogql_position -> __hogql_position <= {maximum})"+ )+ values = "transform(filter(__hogql_rows, __hogql_row -> cardinality(__hogql_row) >= __hogql_position), __hogql_row -> element_at(__hogql_row, __hogql_position))"+ aggregate = self._array_aggregate(node, base, values, value_type.item_type)+ result = f"transform({positions}, __hogql_position -> {aggregate})"+ else:+ if not isinstance(value_type, ast.MapType):+ self._invalid_function_arguments(node, f"{node.name} requires a resolved map type in Trino mode.")+ keys = "array_sort(array_distinct(flatten(transform(__hogql_rows, __hogql_row -> map_keys(__hogql_row)))))"+ values = "transform(filter(__hogql_rows, __hogql_row -> contains(map_keys(__hogql_row), __hogql_key)), __hogql_row -> element_at(__hogql_row, __hogql_key))"+ aggregate = self._array_aggregate(node, base, values, value_type.value_type)+ result = f"map_from_entries(transform({keys}, __hogql_key -> ROW(__hogql_key, {aggregate})))"+ return f"element_at(transform(ARRAY[{rows}], __hogql_rows -> {result}), 1)"++ def _array_aggregate(self, node: ast.Call, base: str, values: str, item_type: ast.ConstantType) -> str:+ values = f"filter({values}, __hogql_item -> __hogql_item IS NOT NULL)"+ default = "0" if base in {"count", "countDistinct"} else self._default_value(item_type, node)+ if base in {"sum", "avg"}:+ if not isinstance(item_type, (ast.IntegerType, ast.FloatType)):+ self._invalid_function_arguments(+ node, f"{node.name} requires integer or float array items in Trino mode."+ )+ numeric_type = "DOUBLE" if base == "avg" or isinstance(item_type, ast.FloatType) else "BIGINT"+ total = f"reduce(__hogql_values, CAST(0 AS {numeric_type}), (__hogql_sum, __hogql_item) -> __hogql_sum + __hogql_item, __hogql_sum -> __hogql_sum)"+ no_values = "NULL" if item_type.nullable else ("nan()" if base == "avg" else "0")+ result = f"{total} / cardinality(__hogql_values)" if base == "avg" else total+ result = f"IF(cardinality(__hogql_values) = 0, {no_values}, {result})"+ elif base in {"min", "max"}:+ result = f"coalesce(array_{base}(__hogql_values), {default})"+ elif base == "median":+ if not isinstance(item_type, (ast.IntegerType, ast.FloatType)):+ self._invalid_function_arguments(node, f"{node.name} requires integer or float values in Trino mode.")+ median_values = "__hogql_values"+ if isinstance(item_type, ast.FloatType):+ median_values = "filter(__hogql_values, __hogql_value -> NOT is_nan(__hogql_value))"+ ordered = f"array_sort(transform({median_values}, __hogql_value -> CAST(__hogql_value AS DOUBLE)))"+ lower = "CAST(floor((cardinality(__hogql_median) - 1) / 2e0) AS BIGINT) + 1"+ upper = "CAST(ceil((cardinality(__hogql_median) - 1) / 2e0) AS BIGINT) + 1"+ result = (+ f"element_at(transform(ARRAY[{ordered}], __hogql_median -> "+ "IF(cardinality(__hogql_median) = 0, nan(), "+ f"(element_at(__hogql_median, {lower}) + element_at(__hogql_median, {upper})) / 2e0)), 1)"+ )+ elif base == "countDistinct":+ result = "cardinality(array_distinct(__hogql_values))"+ else:+ result = "cardinality(__hogql_values)"+ return f"element_at(transform(ARRAY[{values}], __hogql_values -> {result}), 1)"def _visit_array_first(self, node: ast.Call) -> str:if len(node.args) != 2 or not isinstance(node.args[0], ast.Lambda):- self._invalid_function_arguments(node, "arrayFirst expects a lambda and array in Trino mode.")- filtered = f"element_at(filter({self.visit(node.args[1])}, {self.visit(node.args[0])}), 1)"+ self._invalid_function_arguments(node, f"{node.name} expects a lambda and array in Trino mode.")+ index = -1 if node.name.lower() == "arraylast" else 1+ filtered = f"element_at(filter({self.visit(node.args[1])}, {self.visit(node.args[0])}), {index})"array_type = node.args[1].type.resolve_constant_type(self.context) if node.args[1].type is not None else Noneif not isinstance(array_type, ast.ArrayType):self._unsupported(@@ -911,21 +2731,26 @@ class TrinoPrinter(PostgresPrinter):"arrayFirst requires a resolved array type in Trino mode.",node,)- defaults: list[tuple[type[ast.ConstantType], object]] = [- (ast.IntegerType, 0),- (ast.FloatType, 0.0),- (ast.DecimalType, 0),- (ast.StringType, ""),- (ast.BooleanType, False),- ]- default = next((value for type_class, value in defaults if isinstance(array_type.item_type, type_class)), None)- if default is None:- self._unsupported(- "TRINO_ARRAY_FIRST_ITEM_TYPE_UNSUPPORTED",- "arrayFirst does not support this array item type in Trino mode.",- node,+ return f"coalesce({filtered}, {self._default_value(array_type.item_type, node)})"++ def _visit_array_last_index(self, node: ast.Call) -> str:+ if len(node.args) != 2 or not isinstance(node.args[0], ast.Lambda) or len(node.args[0].args) != 1:+ self._invalid_function_arguments(+ node, "arrayLastIndex expects a one-argument lambda and array in Trino mode.")- return f"coalesce({filtered}, {self.visit(ast.Constant(value=default))})"+ predicate = node.args[0]+ if not isinstance(predicate.expr, ast.Expr):+ self._invalid_function_arguments(node, "arrayLastIndex requires an expression lambda in Trino mode.")+ argument = self._print_identifier(predicate.args[0])+ matches = f"transform({self.visit(node.args[1])}, {argument} -> {self._visit_predicate(predicate.expr)})"+ state = "__hogql_last_index_state"+ matched = "__hogql_last_index_match"+ return (+ f"reduce({matches}, ROW(BIGINT '0', BIGINT '0'), "+ f"({state}, {matched}) -> ROW({state}[1] + 1, "+ f"IF(COALESCE({matched}, FALSE), {state}[1] + 1, {state}[2])), "+ f"{state} -> {state}[2])"+ )def _visit_count_distinct(self, node: ast.Call) -> str:if not node.args:@@ -934,6 +2759,27 @@ class TrinoPrinter(PostgresPrinter):value = arguments[0] if len(arguments) == 1 else f"ROW({', '.join(arguments)})"return f"count(DISTINCT {value})"+ def _visit_top_k(self, node: ast.Call) -> str:+ if (+ node.params is None+ or len(node.params) != 1+ or not isinstance(node.params[0], ast.Constant)+ or isinstance(node.params[0].value, bool)+ or not isinstance(node.params[0].value, int)+ or node.params[0].value <= 0+ or len(node.args) != 1+ ):+ self._invalid_function_arguments(node, "topK expects one positive integer parameter and one value.")+ count = node.params[0].value+ value = self.visit(node.args[0])+ entries = f"map_entries(histogram({value}))"+ ordered = (+ f"array_sort({entries}, (__hogql_left, __hogql_right) -> "+ "CASE WHEN __hogql_left[2] > __hogql_right[2] THEN -1 "+ "WHEN __hogql_left[2] < __hogql_right[2] THEN 1 ELSE 0 END)"+ )+ return f"transform(slice({ordered}, 1, {count}), __hogql_entry -> __hogql_entry[1])"+def _visit_to_decimal(self, node: ast.Call) -> str:if len(node.args) != 2:self._invalid_function_arguments(node, "toDecimal expects a value and scale in Trino mode.")@@ -952,6 +2798,87 @@ class TrinoPrinter(PostgresPrinter):)return f"CAST({self.visit(node.args[0])} AS DECIMAL(38, {scale.value}))"+ def _visit_to_nullable_string(self, node: ast.Call) -> str:+ if len(node.args) != 1:+ self._invalid_function_arguments(node, "toNullableString expects one argument in Trino mode.")+ value_type = self._resolve_type(node.args[0])+ if isinstance(node.args[0], ast.Constant) and node.args[0].value is None:+ return "CAST(NULL AS VARCHAR)"+ if not isinstance(value_type, (ast.StringType, ast.IntegerType, ast.BooleanType, ast.DateType)):+ self._invalid_function_arguments(+ node, "toNullableString supports string, integer, boolean, and date values in Trino mode."+ )+ value = self.visit(node.args[0])+ if isinstance(value_type, ast.StringType):+ return value+ if isinstance(value_type, ast.BooleanType):+ return f"IF({value} IS NULL, NULL, IF({value}, '1', '0'))"+ return f"CAST({value} AS VARCHAR)"++ def _visit_to_timestamp(self, node: ast.Call) -> str:+ if len(node.args) != 1 or not isinstance(self._resolve_type(node.args[0]), ast.IntegerType):+ self._invalid_function_arguments(node, "to_timestamp requires one integer Unix timestamp in Trino mode.")+ return f"CAST(from_unixtime(CAST({self.visit(node.args[0])} AS DOUBLE)) AS TIMESTAMP)"++ def _visit_default_value_of_type_name(self, node: ast.Call) -> str:+ if len(node.args) != 1 or not isinstance(node.args[0], ast.Constant) or not isinstance(node.args[0].value, str):+ self._invalid_function_arguments(+ node, "defaultValueOfTypeName requires one constant type name in Trino mode."+ )+ type_name = "".join(node.args[0].value.split())+ normalized = type_name.lower()+ if normalized.startswith("nullable(") and normalized.endswith(")"):+ target = self._trino_json_type(type_name[9:-1], node)+ return f"CAST(NULL AS {target})"+ if normalized.startswith("array(") or normalized.startswith("map("):+ target = self._trino_json_type(type_name, node)+ empty = "ARRAY[]" if normalized.startswith("array(") else "map(ARRAY[], ARRAY[])"+ return f"CAST({empty} AS {target})"+ defaults = {+ "bool": ("false", "BOOLEAN"),+ "date": ("DATE '1970-01-01'", "DATE"),+ "datetime": ("TIMESTAMP '1970-01-01 00:00:00'", "TIMESTAMP"),+ "float32": ("REAL '0'", "REAL"),+ "float64": ("DOUBLE '0'", "DOUBLE"),+ "int8": ("0", "TINYINT"),+ "int16": ("0", "SMALLINT"),+ "int32": ("0", "INTEGER"),+ "int64": ("0", "BIGINT"),+ "string": ("''", "VARCHAR"),+ "uint8": ("0", "SMALLINT"),+ "uint16": ("0", "INTEGER"),+ "uint32": ("0", "BIGINT"),+ "uint64": ("0", "DECIMAL(20, 0)"),+ "uuid": ("UUID '00000000-0000-0000-0000-000000000000'", "UUID"),+ }+ if normalized not in defaults:+ self._invalid_function_arguments(+ node, f"defaultValueOfTypeName does not support type '{type_name}' in Trino mode."+ )+ value, target = defaults[normalized]+ return f"CAST({value} AS {target})"++ def _visit_date_name(self, node: ast.Call) -> str:+ if len(node.args) != 2 or not isinstance(node.args[0], ast.Constant) or not isinstance(node.args[0].value, str):+ self._invalid_function_arguments(node, "dateName requires a constant date part in Trino mode.")+ unit = node.args[0].value.lower()+ value = self.visit(node.args[1])+ formats = {"month": "%M", "weekday": "%W"}+ if unit in formats:+ return f"date_format(CAST({value} AS TIMESTAMP), '{formats[unit]}')"+ extract_units = {+ "year": "year",+ "quarter": "quarter",+ "week": "week",+ "day": "day",+ "hour": "hour",+ "minute": "minute",+ "second": "second",+ }+ if unit not in extract_units:+ self._invalid_function_arguments(node, f"dateName does not support date part '{unit}' in Trino mode.")+ return f"CAST({extract_units[unit]}(CAST({value} AS TIMESTAMP)) AS VARCHAR)"+def _visit_tuple_element(self, node: ast.Call) -> str:if len(node.args) != 2:self._invalid_function_arguments(node, "tupleElement expects a tuple and index in Trino mode.")@@ -979,6 +2906,146 @@ class TrinoPrinter(PostgresPrinter):return self.visit(source.args[index.value - 1])return f"({self.visit(source)})[{index.value}]"+ def _visit_tuple_to_name_value_pairs(self, node: ast.Call) -> str:+ if len(node.args) != 1:+ self._invalid_function_arguments(node, "tupleToNameValuePairs expects one tuple in Trino mode.")+ tuple_type = self._resolve_type(node.args[0])+ if not isinstance(tuple_type, ast.TupleType) or not tuple_type.item_types:+ self._invalid_function_arguments(node, "tupleToNameValuePairs requires a resolved non-empty tuple type.")+ names = tuple_type.field_names+ entries = [+ f"ROW({self.context.add_value(names[index] if index < len(names) and names[index] else str(index + 1))}, "+ f"__hogql_named_tuple[{index + 1}])"+ for index in range(len(tuple_type.item_types))+ ]+ return (+ f"element_at(transform(ARRAY[{self.visit(node.args[0])}], __hogql_named_tuple -> "+ f"ARRAY[{', '.join(entries)}]), 1)"+ )++ def _visit_round_bankers(self, node: ast.Call) -> str:+ if len(node.args) not in {1, 2}:+ self._invalid_function_arguments(node, "roundBankers expects a value and optional constant precision.")+ precision = node.args[1] if len(node.args) == 2 else ast.Constant(value=0)+ if (+ not isinstance(precision, ast.Constant)+ or type(precision.value) is not int+ or not -18 <= precision.value <= 18+ ):+ self._unsupported(+ "TRINO_ROUND_BANKERS_PRECISION_UNSUPPORTED",+ "roundBankers requires a constant precision between -18 and 18.",+ node,+ )+ digits = precision.value+ step = "0." + "0" * (digits - 1) + "1" if digits > 0 else "1" + "0" * -digits+ half = "0." + "0" * digits + "5" if digits >= 0 else "5" + "0" * (-digits - 1)+ source = self.visit(node.args[0])+ value = "__hogql_round_value"+ rounded = f"round({value}, {digits})"+ return (+ f"element_at(transform(ARRAY[{source}], {value} -> "+ f"CASE WHEN abs({value} - {rounded}) = DECIMAL '{half}' "+ f"AND mod({rounded}, DECIMAL '{step}' * 2) <> 0 "+ f"THEN {rounded} - sign({value}) * DECIMAL '{step}' ELSE {rounded} END), 1)"+ )++ def _visit_constant_regex(self, node: ast.Call) -> str:+ name = node.name.lower()+ replacing = name == "replaceregexpone"+ indexed = name == "regexpextract"+ expected_counts = {2, 3} if indexed else {3} if replacing else {2}+ if len(node.args) not in expected_counts:+ self._invalid_function_arguments(node, f"{node.name} has an invalid argument count.")+ pattern = node.args[1]+ if not isinstance(pattern, ast.Constant) or not isinstance(pattern.value, str):+ self._unsupported("TRINO_REGEX_CONSTANT_REQUIRED", f"{node.name} requires a constant pattern.", node)+ if "(?P" in pattern.value:+ self._unsupported(+ "TRINO_REGEX_PATTERN_UNSUPPORTED", "Named Python regex groups are not supported in Trino mode.", node+ )+ try:+ groups = re.compile(pattern.value).groups+ except re.error:+ self._unsupported(+ "TRINO_REGEX_PATTERN_UNSUPPORTED", "The regular expression cannot be analyzed statically.", node+ )+ value = self.visit(node.args[0])+ if not replacing:+ regex = self.context.add_value("(?s)" + pattern.value)+ if indexed:+ default_group = 1 if groups else 0+ group_index_node = node.args[2] if len(node.args) == 3 else ast.Constant(value=default_group)+ if (+ not isinstance(group_index_node, ast.Constant)+ or isinstance(group_index_node.value, bool)+ or not isinstance(group_index_node.value, int)+ or group_index_node.value < 0+ or group_index_node.value > groups+ ):+ self._invalid_function_arguments(+ node, "regexpExtract requires a valid constant capture-group index."+ )+ extracted = f"regexp_extract({value}, {regex}, {group_index_node.value})"+ result = f"coalesce({extracted}, '')"+ value_type = self._resolve_type(node.args[0])+ return f"IF({value} IS NULL, NULL, {result})" if value_type and value_type.nullable else result+ if groups < 1 or groups > 20:+ self._unsupported(+ "TRINO_REGEX_GROUPS_UNSUPPORTED",+ f"{node.name} requires between 1 and 20 capture groups.",+ node,+ )+ columns = [f"regexp_extract_all({value}, {regex}, {i})" for i in range(1, groups + 1)]+ if name == "extractgroups":+ match = f"regexp_extract({value}, {regex}, 0)"+ entries = ", ".join(+ f"coalesce(regexp_extract({value}, {regex}, {index}), '')" for index in range(1, groups + 1)+ )+ return f"IF({match} IS NULL, ARRAY[], ARRAY[{entries}])"+ if name == "extractallgroupshorizontal":+ entries = ", ".join(+ f"transform({column}, __hogql_group -> coalesce(__hogql_group, ''))" for column in columns+ )+ return f"ARRAY[{entries}]"+ matches = f"regexp_extract_all({value}, {regex}, 0)"+ indexes = (+ f"filter(sequence(1, greatest(cardinality({matches}), 1)), "+ f"__hogql_index -> __hogql_index <= cardinality({matches}))"+ )+ entries = ", ".join(f"coalesce(element_at({column}, __hogql_index), '')" for column in columns)+ return f"transform({indexes}, __hogql_index -> ARRAY[{entries}])"+ replacement = node.args[2]+ if not isinstance(replacement, ast.Constant) or not isinstance(replacement.value, str):+ self._unsupported(+ "TRINO_REGEX_CONSTANT_REQUIRED", "replaceRegexpOne requires a constant replacement.", node+ )+ if re.search(r"\\[1-9]", pattern.value):+ self._unsupported(+ "TRINO_REGEX_PATTERN_UNSUPPORTED",+ "replaceRegexpOne requires a pattern without backreferences.",+ node,+ )+ parts = ["__hogql_match[1]"]+ index = 0+ while index < len(replacement.value):+ char = replacement.value[index]+ if char == "\\" and index + 1 < len(replacement.value):+ index += 1+ char = replacement.value[index]+ if char in "0123456789":+ if int(char) > groups:+ self._invalid_function_arguments(node, "Replacement refers to a missing capture group.")+ parts.append(f"coalesce(__hogql_match[{int(char) + 2}], '')")+ index += 1+ continue+ parts.append(self.context.add_value(char))+ index += 1+ parts.append(f"__hogql_match[{groups + 3}]")+ regex = self.context.add_value(r"(?s)\A(.*?)(" + pattern.value + r")(.*)\z")+ substitute = " || ".join(parts)+ return f"regexp_replace({value}, {regex}, __hogql_match -> {substitute})"+def _visit_extract(self, node: ast.Call) -> str:if len(node.args) != 2:self._invalid_function_arguments(node, "extract expects exactly 2 arguments in Trino mode.")@@ -1022,6 +3089,710 @@ class TrinoPrinter(PostgresPrinter):aggregate += f" FILTER (WHERE {self.visit(node.args[1])})"return aggregate+ def _visit_quantiles(self, node: ast.Call, *, over: str = "") -> str:+ filtered = node.name.lower().endswith("if")+ if (+ len(node.args) != (2 if filtered else 1)+ or not node.params+ or node.distinct+ or node.order_by+ or node.within_group+ ):+ self._invalid_function_arguments(node, f"{node.name} has unsupported arguments in Trino mode.")+ percentile_values: list[int | float] = []+ for percentile in node.params:+ if (+ not isinstance(percentile, ast.Constant)+ or isinstance(percentile.value, bool)+ or not isinstance(percentile.value, (int, float))+ or not 0 <= percentile.value <= 1+ ):+ self._invalid_function_arguments(+ node, f"{node.name} requires constant percentiles between zero and one."+ )+ assert isinstance(percentile.value, (int, float))+ percentile_values.append(percentile.value)+ value_type = self._resolve_type(node.args[0])+ if not isinstance(value_type, (ast.IntegerType, ast.FloatType)):+ self._invalid_function_arguments(node, f"{node.name} requires an integer or float value in Trino mode.")+ source = f"CAST({self.visit(node.args[0])} AS DOUBLE)"+ value = f"element_at(transform(ARRAY[{source}], __hogql_quantile -> IF(is_nan(__hogql_quantile), NULL, __hogql_quantile)), 1)"+ predicates = [self._visit_predicate(node.args[1])] if filtered else []+ if node.filter_expr is not None:+ predicates.append(self._visit_predicate(node.filter_expr))+ predicate_sql = " AND ".join(f"({predicate})" for predicate in predicates)+ aggregate_filter = f" FILTER (WHERE {predicate_sql})" if predicates and not over else ""+ if predicates and over:+ value = f"IF({predicate_sql}, {value}, NULL)"+ percentiles = ", ".join(f"DOUBLE '{percentile}'" for percentile in percentile_values)+ default = f"repeat(nan(), {len(node.params)})"+ return f"coalesce(approx_percentile({value}, ARRAY[{percentiles}]){aggregate_filter}{over}, {default})"++ def _visit_weighted_average(self, node: ast.Call, *, over: str = "") -> str:+ filtered = node.name.lower().endswith("if")+ if (+ len(node.args) != (3 if filtered else 2)+ or node.params+ or node.distinct+ or node.order_by+ or node.within_group+ ):+ self._invalid_function_arguments(node, f"{node.name} requires a value and a weight in Trino mode.")+ value_type = self._resolve_type(node.args[0])+ weight_type = self._resolve_type(node.args[1])+ if not isinstance(value_type, (ast.IntegerType, ast.FloatType)) or not isinstance(+ weight_type, (ast.IntegerType, ast.FloatType)+ ):+ self._invalid_function_arguments(node, f"{node.name} requires integer or float arguments in Trino mode.")+ predicates = [self._visit_predicate(node.args[2])] if filtered else []+ if node.filter_expr is not None:+ predicates.append(self._visit_predicate(node.filter_expr))+ predicate_sql = " AND ".join(f"({predicate})" for predicate in predicates)+ aggregate_filter = f" FILTER (WHERE {predicate_sql})" if predicates and not over else ""+ row = f"ROW({self.visit(node.args[0])}, {self.visit(node.args[1])})"+ if predicates and over:+ row = f"IF({predicate_sql}, {row}, NULL)"+ rows = f"array_agg({row}){aggregate_filter}{over}"+ rows = f"filter(coalesce({rows}, ARRAY[]), __hogql_pair -> __hogql_pair[1] IS NOT NULL AND __hogql_pair[2] IS NOT NULL)"+ floating = isinstance(weight_type, ast.FloatType)+ number_type = "DOUBLE" if floating else "BIGINT"+ value = "__hogql_pair[1]"+ if not floating and isinstance(value_type, ast.FloatType):+ value = f"truncate({value})"+ value = f"CAST({value} AS {number_type})"+ weight = f"CAST(__hogql_pair[2] AS {number_type})"+ state_type = f"ROW(numerator {number_type}, denominator {number_type})"+ result = (+ f"reduce(__hogql_weighted_rows, CAST(ROW(0, 0) AS {state_type}), "+ f"(__hogql_fraction, __hogql_pair) -> CAST(ROW(__hogql_fraction[1] + {value} * {weight}, "+ f"__hogql_fraction[2] + {weight}) AS {state_type}), "+ "__hogql_fraction -> CAST(__hogql_fraction[1] AS DOUBLE) / CAST(__hogql_fraction[2] AS DOUBLE))"+ )+ if not floating:+ valid = "__hogql_pair[1] >= 0 AND __hogql_pair[2] >= 0"+ if isinstance(value_type, ast.FloatType):+ valid += " AND is_finite(__hogql_pair[1])"+ result = f"IF(all_match(__hogql_weighted_rows, __hogql_pair -> {valid}), {result}, fail('Integer weights require non-negative finite values and non-negative weights'))"+ if value_type.nullable or weight_type.nullable:+ result = f"IF(cardinality(__hogql_weighted_rows) = 0, NULL, {result})"+ return f"element_at(transform(ARRAY[{rows}], __hogql_weighted_rows -> {result}), 1)"++ def _visit_percentile_within_group(self, node: ast.Call, *, continuous: bool) -> str:+ if (+ len(node.params or []) != 1+ or node.args+ or len(node.within_group or []) != 1+ or node.distinct+ or node.order_by+ ):+ self._invalid_function_arguments(node, f"{node.name} requires one percentile and one ordering expression.")+ percentile = (node.params or [])[0]+ if (+ not isinstance(percentile, ast.Constant)+ or isinstance(percentile.value, bool)+ or not isinstance(percentile.value, (int, float))+ or not 0 <= percentile.value <= 1+ ):+ self._invalid_function_arguments(node, f"{node.name} requires a constant percentile between zero and one.")+ ordering = (node.within_group or [])[0]+ value = self.visit(ordering.expr)+ aggregate_filter = (+ f" FILTER (WHERE {self._visit_predicate(node.filter_expr)})" if node.filter_expr is not None else ""+ )+ item = f"CAST({value} AS DOUBLE)" if continuous else value+ values = f"filter(array_agg({item}){aggregate_filter}, __hogql_percentile_value -> __hogql_percentile_value IS NOT NULL)"+ values = f"array_sort({values})"+ if ordering.order == "DESC":+ values = f"reverse({values})"+ count = "cardinality(__hogql_percentile_values)"+ if continuous:+ position = f"DOUBLE '{percentile.value}' * ({count} - 1) + 1"+ lower = f"element_at(__hogql_percentile_values, CAST(floor({position}) AS BIGINT))"+ upper = f"element_at(__hogql_percentile_values, CAST(ceil({position}) AS BIGINT))"+ result = f"{lower} + ({position} - floor({position})) * ({upper} - {lower})"+ else:+ index = f"greatest(CAST(ceil(DOUBLE '{percentile.value}' * {count}) AS BIGINT), 1)"+ result = f"element_at(__hogql_percentile_values, {index})"+ return (+ f"element_at(transform(ARRAY[{values}], __hogql_percentile_values -> IF({count} = 0, NULL, {result})), 1)"+ )++ def _visit_sample_statistic(self, node: ast.Call) -> str:+ name = node.name.lower()+ filtered = name.endswith("if")+ base_name = name[:-2] if filtered else name+ targets = {+ "stddevsamp": "stddev_samp",+ "varsamp": "var_samp",+ "covarsamp": "covar_samp",+ "corr": "corr",+ }+ argument_count = 2 if base_name in {"covarsamp", "corr"} else 1+ if len(node.args) != argument_count + int(filtered) or node.params or node.distinct or node.order_by:+ self._invalid_function_arguments(node, f"{node.name} has unsupported arguments in Trino mode.")+ value_nodes = node.args[:argument_count]+ value_types = [self._resolve_type(argument) for argument in value_nodes]+ if any(not isinstance(value_type, (ast.IntegerType, ast.FloatType)) for value_type in value_types):+ self._invalid_function_arguments(node, f"{node.name} requires numeric arguments in Trino mode.")+ values = [self.visit(argument) for argument in value_nodes]+ predicates = [self._visit_predicate(node.args[-1])] if filtered else []+ if node.filter_expr is not None:+ predicates.append(self._visit_predicate(node.filter_expr))+ filter_sql = (+ f" FILTER (WHERE {' AND '.join(f'({predicate})' for predicate in predicates)})" if predicates else ""+ )+ result = f"{targets[base_name]}({', '.join(values)}){filter_sql}"+ result = f"coalesce({result}, CAST('NaN' AS DOUBLE))"+ if any(value_type.nullable for value_type in value_types if value_type is not None):+ present = " AND ".join(f"{value} IS NOT NULL" for value in values)+ if predicates:+ present += " AND " + " AND ".join(f"({predicate})" for predicate in predicates)+ result = f"IF(count_if({present}) = 0, NULL, {result})"+ return result++ def _visit_statistical_aggregate(self, node: ast.Call, *, over: str = "") -> str:+ name = node.name.lower()+ filtered = name.endswith("if")+ regression = name.startswith("simplelinearregression")+ argument_count = 2 if regression else 1+ expected_count = argument_count + int(filtered)+ if len(node.args) != expected_count or node.params or node.distinct or node.order_by or node.within_group:+ self._invalid_function_arguments(node, f"{node.name} has unsupported arguments in Trino mode.")+ argument_types = [self._resolve_type(argument) for argument in node.args[:argument_count]]+ if any(not isinstance(argument_type, (ast.IntegerType, ast.FloatType)) for argument_type in argument_types):+ self._invalid_function_arguments(node, f"{node.name} requires integer or float arguments in Trino mode.")+ predicates = [self._visit_predicate(node.args[-1])] if filtered else []+ if node.filter_expr is not None:+ predicates.append(self._visit_predicate(node.filter_expr))+ predicate_sql = " AND ".join(f"({predicate})" for predicate in predicates)+ values = [f"CAST({self.visit(argument)} AS DOUBLE)" for argument in node.args[:argument_count]]+ value = f"ROW({', '.join(values)})" if regression else values[0]+ aggregate_filter = f" FILTER (WHERE {predicate_sql})" if predicates and not over else ""+ if predicates and over:+ value = f"IF({predicate_sql}, {value}, NULL)"+ rows = f"coalesce(array_agg({value}){aggregate_filter}{over}, ARRAY[])"+ if regression:+ rows = f"filter({rows}, __hogql_value -> __hogql_value[1] IS NOT NULL AND __hogql_value[2] IS NOT NULL)"+ result = self._linear_regression_from_array()+ else:+ rows = f"filter({rows}, __hogql_value -> __hogql_value IS NOT NULL)"+ result = self._moment_statistic_from_array(name)+ nullable_result = any(+ argument_type.nullable for argument_type in argument_types if argument_type is not None+ ) and not (regression and filtered)+ if nullable_result:+ result = f"IF(cardinality(__hogql_stat_rows) = 0, NULL, {result})"+ return f"element_at(transform(ARRAY[{rows}], __hogql_stat_rows -> {result}), 1)"++ def _visit_unique_array_aggregate(self, node: ast.Call, *, over: str = "") -> str:+ filtered = node.name.lower().endswith("if")+ if len(node.args) != (2 if filtered else 1) or node.distinct or node.order_by or node.within_group:+ self._invalid_function_arguments(node, f"{node.name} has unsupported arguments in Trino mode.")+ if node.params:+ if (+ len(node.params) != 1+ or not isinstance(node.params[0], ast.Constant)+ or isinstance(node.params[0].value, bool)+ or not isinstance(node.params[0].value, int)+ or node.params[0].value <= 0+ ):+ self._invalid_function_arguments(node, f"{node.name} requires one positive integer parameter.")+ limit = node.params[0].value+ else:+ limit = None+ value_type = self._resolve_type(node.args[0])+ if not isinstance(value_type, ast.ArrayType):+ self._invalid_function_arguments(node, f"{node.name} requires an array in Trino mode.")+ predicates = [self._visit_predicate(node.args[1])] if filtered else []+ if node.filter_expr is not None:+ predicates.append(self._visit_predicate(node.filter_expr))+ predicate_sql = " AND ".join(f"({predicate})" for predicate in predicates)+ value = self.visit(node.args[0])+ aggregate_filter = f" FILTER (WHERE {predicate_sql})" if predicates and not over else ""+ if predicates and over:+ value = f"IF({predicate_sql}, {value}, NULL)"+ arrays = f"filter(coalesce(array_agg({value}){aggregate_filter}{over}, ARRAY[]), __hogql_array -> __hogql_array IS NOT NULL)"+ result = "array_distinct(filter(flatten(__hogql_arrays), __hogql_value -> __hogql_value IS NOT NULL))"+ if limit is not None:+ result = f"slice({result}, 1, {limit})"+ return f"element_at(transform(ARRAY[{arrays}], __hogql_arrays -> {result}), 1)"++ def _visit_moving_array_aggregate(self, node: ast.Call, *, over: str = "") -> str:+ name = node.name.lower()+ filtered = name.endswith("if")+ average = "avg" in name+ if (+ len(node.args) != (2 if filtered else 1)+ or node.params+ or node.distinct+ or node.order_by+ or node.within_group+ ):+ self._invalid_function_arguments(node, f"{node.name} has unsupported arguments in Trino mode.")+ value_type = self._resolve_type(node.args[0])+ if not isinstance(value_type, (ast.IntegerType, ast.FloatType)):+ self._invalid_function_arguments(node, f"{node.name} requires an integer or float value in Trino mode.")+ predicates = [self._visit_predicate(node.args[1])] if filtered else []+ if node.filter_expr is not None:+ predicates.append(self._visit_predicate(node.filter_expr))+ predicate_sql = " AND ".join(f"({predicate})" for predicate in predicates)+ number_type = "DOUBLE" if average or isinstance(value_type, ast.FloatType) else "BIGINT"+ value = f"CAST({self.visit(node.args[0])} AS {number_type})"+ aggregate_filter = f" FILTER (WHERE {predicate_sql})" if predicates and not over else ""+ if predicates and over:+ value = f"IF({predicate_sql}, {value}, NULL)"+ values = f"filter(coalesce(array_agg({value}){aggregate_filter}{over}, ARRAY[]), __hogql_value -> __hogql_value IS NOT NULL)"+ state_type = f"ROW(total {number_type}, items ARRAY({number_type}))"+ state = (+ f"reduce(__hogql_moving_values, CAST(ROW(0, ARRAY[]) AS {state_type}), "+ "(__hogql_state, __hogql_value) -> CAST(ROW("+ "__hogql_state[1] + __hogql_value, "+ "concat(__hogql_state[2], ARRAY[__hogql_state[1] + __hogql_value])"+ f") AS {state_type}), __hogql_state -> __hogql_state[2])"+ )+ if average:+ state = f"transform({state}, __hogql_total -> __hogql_total / cardinality(__hogql_moving_values))"+ return f"element_at(transform(ARRAY[{values}], __hogql_moving_values -> {state}), 1)"++ def _visit_delta_sum(self, node: ast.Call, *, over: str = "") -> str:+ filtered = node.name.lower().endswith("if")+ if (+ len(node.args) != (2 if filtered else 1)+ or node.params+ or node.distinct+ or node.order_by+ or node.within_group+ ):+ self._invalid_function_arguments(node, f"{node.name} has unsupported arguments in Trino mode.")+ value_type = self._resolve_type(node.args[0])+ if not isinstance(value_type, (ast.IntegerType, ast.FloatType)):+ self._invalid_function_arguments(node, f"{node.name} requires an integer or float value in Trino mode.")+ predicates = [self._visit_predicate(node.args[1])] if filtered else []+ if node.filter_expr is not None:+ predicates.append(self._visit_predicate(node.filter_expr))+ predicate_sql = " AND ".join(f"({predicate})" for predicate in predicates)+ number_type = "DOUBLE" if isinstance(value_type, ast.FloatType) else "BIGINT"+ value = f"CAST({self.visit(node.args[0])} AS {number_type})"+ aggregate_filter = f" FILTER (WHERE {predicate_sql})" if predicates and not over else ""+ if predicates and over:+ value = f"IF({predicate_sql}, {value}, NULL)"+ values = f"filter(coalesce(array_agg({value}){aggregate_filter}{over}, ARRAY[]), __hogql_value -> __hogql_value IS NOT NULL)"+ state_type = f"ROW(seen BOOLEAN, previous {number_type}, total {number_type})"+ zero = "DOUBLE '0'" if number_type == "DOUBLE" else "BIGINT '0'"+ result = (+ f"reduce(__hogql_delta_values, CAST(ROW(false, {zero}, {zero}) AS {state_type}), "+ "(__hogql_state, __hogql_value) -> CAST(ROW(true, __hogql_value, "+ "__hogql_state[3] + IF(__hogql_state[1] AND __hogql_state[2] < __hogql_value, "+ "__hogql_value - __hogql_state[2], 0)"+ f") AS {state_type}), __hogql_state -> __hogql_state[3])"+ )+ return f"element_at(transform(ARRAY[{values}], __hogql_delta_values -> {result}), 1)"++ def _visit_max_intersections(self, node: ast.Call, *, over: str = "") -> str:+ name = node.name.lower()+ filtered = name.endswith("if")+ position_result = "position" in name+ if (+ len(node.args) != (3 if filtered else 2)+ or node.params+ or node.distinct+ or node.order_by+ or node.within_group+ ):+ self._invalid_function_arguments(node, f"{node.name} has unsupported arguments in Trino mode.")+ value_types = [self._resolve_type(argument) for argument in node.args[:2]]+ if any(not isinstance(value_type, (ast.IntegerType, ast.FloatType)) for value_type in value_types):+ self._invalid_function_arguments(node, f"{node.name} requires integer or float interval bounds.")+ numeric_type = (+ "DOUBLE" if any(isinstance(value_type, ast.FloatType) for value_type in value_types) else "BIGINT"+ )+ predicates = [self._visit_predicate(node.args[2])] if filtered else []+ if node.filter_expr is not None:+ predicates.append(self._visit_predicate(node.filter_expr))+ predicate_sql = " AND ".join(f"({predicate})" for predicate in predicates)+ row = f"ROW(CAST({self.visit(node.args[0])} AS {numeric_type}), CAST({self.visit(node.args[1])} AS {numeric_type}))"+ aggregate_filter = f" FILTER (WHERE {predicate_sql})" if predicates and not over else ""+ if predicates and over:+ row = f"IF({predicate_sql}, {row}, NULL)"+ rows = f"filter(coalesce(array_agg({row}){aggregate_filter}{over}, ARRAY[]), __hogql_row -> __hogql_row IS NOT NULL)"+ valid_rows = (+ "filter(__hogql_intersection_rows, __hogql_row -> "+ "__hogql_row[1] IS NOT NULL AND __hogql_row[2] IS NOT NULL AND __hogql_row[1] < __hogql_row[2])"+ )+ events = (+ "flatten(transform(__hogql_valid_intervals, __hogql_row -> "+ "ARRAY[ROW(__hogql_row[1], BIGINT '1'), ROW(__hogql_row[2], BIGINT '-1')]))"+ )+ ordered = (+ f"array_sort({events}, (__hogql_left, __hogql_right) -> CASE "+ "WHEN __hogql_left[1] < __hogql_right[1] THEN -1 "+ "WHEN __hogql_left[1] > __hogql_right[1] THEN 1 "+ "WHEN __hogql_left[2] < __hogql_right[2] THEN -1 "+ "WHEN __hogql_left[2] > __hogql_right[2] THEN 1 ELSE 0 END)"+ )+ state_type = f"ROW(current_count BIGINT, maximum_count BIGINT, first_position {numeric_type})"+ current = "__hogql_state[1] + __hogql_event[2]"+ scan = (+ f"reduce({ordered}, CAST(ROW(0, 0, 0) AS {state_type}), (__hogql_state, __hogql_event) -> "+ f"CAST(ROW({current}, greatest(__hogql_state[2], {current}), "+ f"IF({current} > __hogql_state[2], __hogql_event[1], __hogql_state[3])) AS {state_type}), "+ "__hogql_state -> __hogql_state)"+ )+ result = f"__hogql_intersection_state[{3 if position_result else 2}]"+ result = f"element_at(transform(ARRAY[{scan}], __hogql_intersection_state -> {result}), 1)"+ if any(value_type.nullable for value_type in value_types if value_type is not None):+ has_null = (+ "any_match(__hogql_intersection_rows, __hogql_row -> __hogql_row[1] IS NULL OR __hogql_row[2] IS NULL)"+ )+ result = f"IF(cardinality(__hogql_valid_intervals) = 0 AND {has_null}, NULL, {result})"+ result = f"element_at(transform(ARRAY[{valid_rows}], __hogql_valid_intervals -> {result}), 1)"+ return f"element_at(transform(ARRAY[{rows}], __hogql_intersection_rows -> {result}), 1)"++ def _visit_group_array_insert_at(self, node: ast.Call, *, over: str = "") -> str:+ filtered = node.name.lower().endswith("if")+ if (+ len(node.args) != (3 if filtered else 2)+ or node.params+ or node.distinct+ or node.order_by+ or node.within_group+ ):+ self._invalid_function_arguments(node, f"{node.name} has unsupported arguments in Trino mode.")+ value_type = self._resolve_type(node.args[0])+ position_type = self._resolve_type(node.args[1])+ if value_type is None or not isinstance(position_type, ast.IntegerType):+ self._invalid_function_arguments(+ node, f"{node.name} requires a resolved value and an integer position in Trino mode."+ )+ predicates = [self._visit_predicate(node.args[2])] if filtered else []+ if node.filter_expr is not None:+ predicates.append(self._visit_predicate(node.filter_expr))+ predicate_sql = " AND ".join(f"({predicate})" for predicate in predicates)+ value = self.visit(node.args[0])+ position = f"CAST({self.visit(node.args[1])} AS BIGINT)"+ row = f"ROW({value}, {position})"+ aggregate_filter = f" FILTER (WHERE {predicate_sql})" if predicates and not over else ""+ if predicates and over:+ row = f"IF({predicate_sql}, {row}, NULL)"+ rows = f"coalesce(array_agg({row}){aggregate_filter}{over}, ARRAY[])"+ rows = f"filter({rows}, __hogql_row -> __hogql_row[1] IS NOT NULL AND __hogql_row[2] IS NOT NULL)"+ maximum = "coalesce(array_max(transform(__hogql_insert_rows, __hogql_row -> __hogql_row[2])), -1)"+ positions = f"filter(sequence(0, greatest(__hogql_maximum, 0)), __hogql_position -> __hogql_position <= __hogql_maximum)"+ selected = (+ "element_at(transform(filter(__hogql_insert_rows, __hogql_row -> "+ "__hogql_row[2] = __hogql_position), __hogql_row -> __hogql_row[1]), 1)"+ )+ default = self._default_value(replace(value_type, nullable=False), node)+ result = f"transform({positions}, __hogql_position -> coalesce({selected}, {default}))"+ result = (+ f"IF(__hogql_maximum <= 2147483647, {result}, "+ "fail('groupArrayInsertAt position exceeds the Trino array limit'))"+ )+ result = f"element_at(transform(ARRAY[{maximum}], __hogql_maximum -> {result}), 1)"+ return f"element_at(transform(ARRAY[{rows}], __hogql_insert_rows -> {result}), 1)"++ @staticmethod+ def _linear_regression_from_array() -> str:+ state_type = "ROW(n DOUBLE, sx DOUBLE, sy DOUBLE, sxx DOUBLE, sxy DOUBLE)"+ state = (+ f"reduce(__hogql_stat_rows, CAST(ROW(0e0, 0e0, 0e0, 0e0, 0e0) AS {state_type}), "+ "(__hogql_state, __hogql_value) -> CAST(ROW("+ "__hogql_state[1] + 1e0, "+ "__hogql_state[2] + __hogql_value[1], "+ "__hogql_state[3] + __hogql_value[2], "+ "__hogql_state[4] + __hogql_value[1] * __hogql_value[1], "+ "__hogql_state[5] + __hogql_value[1] * __hogql_value[2]"+ f") AS {state_type}), __hogql_state -> __hogql_state)"+ )+ divisor = "__hogql_state[4] * __hogql_state[1] - __hogql_state[2] * __hogql_state[2]"+ slope = (+ f"IF({divisor} = 0, nan(), "+ "(__hogql_state[5] * __hogql_state[1] - __hogql_state[2] * __hogql_state[3]) / "+ f"({divisor}))"+ )+ intercept = (+ f"IF(__hogql_state[1] = 0, nan(), (__hogql_state[3] - __hogql_slope * __hogql_state[2]) / __hogql_state[1])"+ )+ return (+ f"element_at(transform(ARRAY[{state}], __hogql_state -> "+ f"element_at(transform(ARRAY[{slope}], __hogql_slope -> ROW(__hogql_slope, {intercept})), 1)), 1)"+ )++ @staticmethod+ def _moment_statistic_from_array(name: str) -> str:+ state_type = "ROW(n DOUBLE, s1 DOUBLE, s2 DOUBLE, s3 DOUBLE, s4 DOUBLE)"+ state = (+ f"reduce(__hogql_stat_rows, CAST(ROW(0e0, 0e0, 0e0, 0e0, 0e0) AS {state_type}), "+ "(__hogql_state, __hogql_value) -> CAST(ROW("+ "__hogql_state[1] + 1e0, "+ "__hogql_state[2] + __hogql_value, "+ "__hogql_state[3] + power(__hogql_value, 2), "+ "__hogql_state[4] + power(__hogql_value, 3), "+ "__hogql_state[5] + power(__hogql_value, 4)"+ f") AS {state_type}), __hogql_state -> __hogql_state)"+ )+ population = name.startswith("skewpop") or name.startswith("kurtpop")+ variance_denominator = "__hogql_state[1]" if population else "__hogql_state[1] - 1e0"+ variance = (+ "greatest(0e0, (__hogql_state[3] - __hogql_state[2] * __hogql_state[2] / "+ f"__hogql_state[1]) / ({variance_denominator}))"+ )+ moment3 = (+ "(__hogql_state[4] - (3e0 * __hogql_state[3] - "+ "2e0 * __hogql_state[2] * __hogql_state[2] / __hogql_state[1]) * "+ "__hogql_state[2] / __hogql_state[1]) / __hogql_state[1]"+ )+ moment4 = (+ "(__hogql_state[5] - (4e0 * __hogql_state[4] - "+ "(6e0 * __hogql_state[3] - 3e0 * __hogql_state[2] * __hogql_state[2] / "+ "__hogql_state[1]) * __hogql_state[2] / __hogql_state[1]) * "+ "__hogql_state[2] / __hogql_state[1]) / __hogql_state[1]"+ )+ moment = moment3 if name.startswith("skew") else moment4+ exponent = "1.5" if name.startswith("skew") else "2e0"+ statistic = f"IF(__hogql_variance > 0, ({moment}) / power(__hogql_variance, {exponent}), nan())"+ minimum_count = 0 if population else 1+ return (+ f"element_at(transform(ARRAY[{state}], __hogql_state -> "+ f"IF(__hogql_state[1] <= {minimum_count}, nan(), "+ f"element_at(transform(ARRAY[{variance}], __hogql_variance -> {statistic}), 1))), 1)"+ )++ def _visit_exact_quantile(self, node: ast.Call, *, filtered: bool, over: str = "") -> str:+ expected_arguments = 2 if filtered else 1+ median = node.name.lower().startswith("median")+ if node.distinct or node.order_by or node.within_group:+ self._invalid_function_arguments(+ node, f"{node.name} does not support these aggregate modifiers in Trino mode."+ )+ if len(node.args) != expected_arguments or (+ bool(node.params) if median else node.params is None or len(node.params) != 1+ ):+ self._invalid_function_arguments(node, f"{node.name} expects one percentile parameter in Trino mode.")+ percentile = ast.Constant(value=0.5) if median else (node.params or [])[0]+ if (+ not isinstance(percentile, ast.Constant)+ or isinstance(percentile.value, bool)+ or not isinstance(percentile.value, (int, float))+ or not 0 <= percentile.value <= 1+ ):+ self._unsupported(+ "TRINO_EXACT_QUANTILE_PERCENTILE_UNSUPPORTED",+ f"{node.name} requires a constant percentile between 0 and 1 in Trino mode.",+ node,+ )+ value = self.visit(node.args[0])+ predicates = []+ if filtered:+ predicates.append(self._visit_predicate(node.args[1]))+ if node.filter_expr is not None:+ predicates.append(self._visit_predicate(node.filter_expr))+ if predicates:+ value = f"IF({' AND '.join(f'({predicate})' for predicate in predicates)}, {value}, NULL)"+ return self._exact_quantile_from_array(f"array_agg({value}){over}", str(percentile.value), node)++ def _visit_exact_weighted_median(self, node: ast.Call, *, over: str = "") -> str:+ filtered = node.name.lower().endswith("if")+ if (+ len(node.args) != (3 if filtered else 2)+ or node.params+ or node.distinct+ or node.order_by+ or node.within_group+ ):+ self._invalid_function_arguments(node, f"{node.name} has unsupported arguments in Trino mode.")+ value_type = self._resolve_type(node.args[0])+ weight_type = self._resolve_type(node.args[1])+ if not isinstance(+ value_type, (ast.IntegerType, ast.FloatType, ast.DateType, ast.DateTimeType)+ ) or not isinstance(weight_type, ast.IntegerType):+ self._invalid_function_arguments(+ node, f"{node.name} requires a numeric or date value and an integer weight in Trino mode."+ )+ predicates = [self._visit_predicate(node.args[2])] if filtered else []+ if node.filter_expr is not None:+ predicates.append(self._visit_predicate(node.filter_expr))+ predicate_sql = " AND ".join(f"({predicate})" for predicate in predicates)+ row = f"ROW({self.visit(node.args[0])}, CAST({self.visit(node.args[1])} AS BIGINT))"+ aggregate_filter = f" FILTER (WHERE {predicate_sql})" if predicates and not over else ""+ if predicates and over:+ row = f"IF({predicate_sql}, {row}, NULL)"+ rows = f"coalesce(array_agg({row}){aggregate_filter}{over}, ARRAY[])"+ rows = f"filter({rows}, __hogql_row -> __hogql_row[1] IS NOT NULL AND __hogql_row[2] IS NOT NULL)"+ if isinstance(value_type, ast.FloatType):+ rows = f"filter({rows}, __hogql_row -> NOT is_nan(__hogql_row[1]))"+ ordered = (+ "array_sort(__hogql_weighted_rows, (__hogql_left, __hogql_right) -> "+ "CASE WHEN __hogql_left[1] < __hogql_right[1] THEN -1 "+ "WHEN __hogql_left[1] > __hogql_right[1] THEN 1 ELSE 0 END)"+ )+ weight_state = "ROW(total BIGINT, cumulative ARRAY(BIGINT))"+ cumulative = (+ f"reduce(__hogql_ordered, CAST(ROW(0, ARRAY[]) AS {weight_state}), "+ "(__hogql_state, __hogql_row) -> CAST(ROW("+ "__hogql_state[1] + __hogql_row[2], "+ "concat(__hogql_state[2], ARRAY[__hogql_state[1] + __hogql_row[2]])"+ f") AS {weight_state}), __hogql_state -> __hogql_state)"+ )+ position = (+ "array_position(transform(__hogql_weights[2], __hogql_weight -> "+ "CAST(__hogql_weight AS DOUBLE) >= CAST(__hogql_weights[1] AS DOUBLE) / 2e0), true)"+ )+ selected = f"element_at(__hogql_ordered, {position})[1]"+ default = "nan()" if isinstance(value_type, ast.FloatType) else self._default_value(value_type, node)+ empty = "NULL" if value_type.nullable else default+ result = (+ f"IF(cardinality(__hogql_ordered) = 0, {empty}, "+ f"element_at(transform(ARRAY[{cumulative}], __hogql_weights -> {selected}), 1))"+ )+ result = f"element_at(transform(ARRAY[{ordered}], __hogql_ordered -> {result}), 1)"+ result = (+ "IF(any_match(__hogql_weighted_rows, __hogql_row -> __hogql_row[2] < 0), "+ f"fail('medianExactWeighted requires non-negative weights'), {result})"+ )+ return f"element_at(transform(ARRAY[{rows}], __hogql_weighted_rows -> {result}), 1)"++ def _exact_quantile_from_array(self, values: str, percentile: str, node: ast.Call) -> str:+ value_type = self._resolve_type(node.args[0])+ if not isinstance(value_type, (ast.IntegerType, ast.FloatType, ast.DateType, ast.DateTimeType)):+ self._invalid_function_arguments(node, f"{node.name} requires a numeric or date value in Trino mode.")+ nonnull_values = (+ f"filter(coalesce({values}, ARRAY[]), __hogql_quantile_value -> __hogql_quantile_value IS NOT NULL)"+ )+ sorted_values = "__hogql_quantile_input"+ if isinstance(value_type, ast.FloatType):+ sorted_values = f"filter({sorted_values}, __hogql_quantile_value -> NOT is_nan(__hogql_quantile_value))"+ sorted_values = f"array_sort({sorted_values})"+ default = "nan()" if isinstance(value_type, ast.FloatType) else self._default_value(value_type, node)+ position = (+ "CAST(ceil(0.5 * cardinality(__hogql_quantile_values)) AS BIGINT)"+ if node.name.lower().startswith("medianexactlow")+ else f"least(CAST(floor({percentile} * cardinality(__hogql_quantile_values)) AS BIGINT) + 1, cardinality(__hogql_quantile_values))"+ )+ result = (+ f"element_at(transform(ARRAY[{sorted_values}], __hogql_quantile_values -> "+ f"IF(cardinality(__hogql_quantile_values) = 0, {default}, "+ f"element_at(__hogql_quantile_values, {position}))), 1)"+ )+ if value_type.nullable:+ result = f"IF(cardinality(__hogql_quantile_input) = 0, NULL, {result})"+ return f"element_at(transform(ARRAY[{nonnull_values}], __hogql_quantile_input -> {result}), 1)"++ def _visit_ngram(self, node: ast.Call, *, utf8: bool, case_insensitive: bool, search: bool) -> str:+ binary_args = self._visit_binary_args(node)+ gram_size = 3 if utf8 else 4+ map_key_type = "VARCHAR" if utf8 else "VARBINARY"++ def grams(value: str, label: str) -> str:+ size = f"length({value})"+ count = f"{size} - {gram_size - 1}"+ indexes = f"filter(sequence(1, greatest({count}, 1)), {label}_index -> {label}_index <= {count})"+ return f"transform({indexes}, {label}_index -> substr({value}, {label}_index, {gram_size}))"++ def frequencies(values: str, label: str) -> str:+ return (+ f"reduce({values}, CAST(map(ARRAY[], ARRAY[]) AS MAP({map_key_type}, BIGINT)), "+ f"({label}_counts, {label}_gram) -> map_concat({label}_counts, map(ARRAY[{label}_gram], "+ f"ARRAY[coalesce(element_at({label}_counts, {label}_gram), BIGINT '0') + 1])), {label}_counts -> {label}_counts)"+ )++ left_value = f"CAST({binary_args.left} AS VARCHAR)"+ right_value = f"CAST({binary_args.right} AS VARCHAR)"+ if case_insensitive:+ uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"+ lowercase = "abcdefghijklmnopqrstuvwxyz"+ left_value = f"translate({left_value}, '{uppercase}', '{lowercase}')"+ right_value = f"translate({right_value}, '{uppercase}', '{lowercase}')"+ left = left_value if utf8 else f"to_utf8({left_value})"+ right = right_value if utf8 else f"to_utf8({right_value})"+ left_counts = frequencies(grams("__hogql_ngram_args[1]", "__hogql_left"), "__hogql_left")+ right_counts = frequencies(grams("__hogql_ngram_args[2]", "__hogql_right"), "__hogql_right")+ keys = "array_distinct(concat(map_keys(__hogql_ngram_maps[1]), map_keys(__hogql_ngram_maps[2])))"+ left_count = "coalesce(element_at(__hogql_ngram_maps[1], __hogql_ngram_key), BIGINT '0')"+ right_count = "coalesce(element_at(__hogql_ngram_maps[2], __hogql_ngram_key), BIGINT '0')"+ difference = (+ f"reduce({keys}, DOUBLE '0', (__hogql_distance, __hogql_ngram_key) -> "+ f"__hogql_distance + abs({left_count} - {right_count}), __hogql_distance -> __hogql_distance)"+ )+ total = (+ f"reduce({keys}, DOUBLE '0', (__hogql_total, __hogql_ngram_key) -> "+ f"__hogql_total + {left_count} + {right_count}, __hogql_total -> __hogql_total)"+ )+ if search:+ intersection = (+ f"reduce({keys}, DOUBLE '0', (__hogql_overlap, __hogql_ngram_key) -> "+ f"__hogql_overlap + least({left_count}, {right_count}), __hogql_overlap -> __hogql_overlap)"+ )+ right_total = (+ f"reduce(map_values(__hogql_ngram_maps[2]), DOUBLE '0', "+ "(__hogql_total, __hogql_count) -> __hogql_total + __hogql_count, __hogql_total -> __hogql_total)"+ )+ result = f"IF({right_total} = 0, DOUBLE '1', {intersection} / {right_total})"+ else:+ result = f"IF({total} = 0, DOUBLE '0', {difference} / {total})"+ return (+ f"IF({binary_args.left} IS NULL OR {binary_args.right} IS NULL, NULL, "+ f"element_at(transform(ARRAY[ROW({left}, {right})], __hogql_ngram_args -> "+ f"element_at(transform(ARRAY[ROW({left_counts}, {right_counts})], __hogql_ngram_maps -> {result}), 1)), 1))"+ )++ def _visit_format_readable_time_delta(self, node: ast.Call) -> str:+ if len(node.args) not in {1, 2}:+ self._invalid_function_arguments(+ node, "formatReadableTimeDelta expects seconds and an optional maximum unit."+ )+ maximum_unit = "year"+ if len(node.args) == 2:+ unit = node.args[1]+ if not isinstance(unit, ast.Constant) or not isinstance(unit.value, str):+ self._unsupported(+ "TRINO_TIME_DELTA_UNIT_UNSUPPORTED",+ "formatReadableTimeDelta requires a constant maximum unit in Trino mode.",+ node,+ )+ maximum_unit = unit.value.lower().removesuffix("s")+ units = [+ ("year", 365 * 24 * 60 * 60),+ ("month", 30 * 24 * 60 * 60),+ ("day", 24 * 60 * 60),+ ("hour", 60 * 60),+ ("minute", 60),+ ("second", 1),+ ]+ unit_names = [name for name, _ in units]+ if maximum_unit not in unit_names:+ self._unsupported(+ "TRINO_TIME_DELTA_UNIT_UNSUPPORTED",+ f"formatReadableTimeDelta maximum unit '{maximum_unit}' is not supported in Trino mode.",+ node,+ )+ selected = units[unit_names.index(maximum_unit) :]+ components: list[str] = []+ previous_size: int | None = None+ for unit_name, unit_size in selected:+ amount = (+ f"CAST(floor(__hogql_delta / {unit_size}) AS BIGINT)"+ if previous_size is None+ else f"CAST(floor(mod(__hogql_delta, {previous_size}) / {unit_size}) AS BIGINT)"+ )+ components.append(+ f"IF({amount} = 0, NULL, CAST({amount} AS VARCHAR) || ' ' || "+ f"IF({amount} = 1, '{unit_name}', '{unit_name}s'))"+ )+ previous_size = unit_size+ values = f"filter(ARRAY[{', '.join(components)}], __hogql_delta_part -> __hogql_delta_part IS NOT NULL)"+ formatted = (+ "IF(cardinality(__hogql_delta_parts) = 0, '0 seconds', "+ "IF(cardinality(__hogql_delta_parts) = 1, __hogql_delta_parts[1], "+ "array_join(slice(__hogql_delta_parts, 1, cardinality(__hogql_delta_parts) - 1), ', ') || "+ "' and ' || element_at(__hogql_delta_parts, -1)))"+ )+ seconds = self.visit(node.args[0])+ return (+ f"IF({seconds} IS NULL, NULL, element_at(transform(ARRAY[greatest(CAST(floor({seconds}) AS BIGINT), 0)], "+ f"__hogql_delta -> element_at(transform(ARRAY[{values}], __hogql_delta_parts -> {formatted}), 1)), 1))"+ )+def _visit_json_value(self, node: ast.Call) -> str:if len(node.args) != 2:self._invalid_function_arguments(node, "JSON_VALUE expects a JSON expression and path in Trino mode.")@@ -1040,7 +3811,8 @@ class TrinoPrinter(PostgresPrinter):)path_value = path.value if path.value.lstrip().startswith(("lax ", "strict ")) else f"lax {path.value}"path_literal = "'" + path_value.replace("'", "''") + "'"- return f"json_value({self.visit(node.args[0])}, {path_literal})"+ result = f"json_value({self.visit(node.args[0])}, {path_literal})"+ return self._json_default(node, result, "''")def _print_table_sql(self, table: "Table") -> str:return self._print_table(table)@@ -1070,6 +3842,31 @@ class TrinoPrinter(PostgresPrinter):def visit_array(self, node: ast.Array) -> str:return f"ARRAY[{', '.join(self.visit(expr) for expr in node.exprs)}]"+ def visit_array_access(self, node: ast.ArrayAccess) -> str:+ root: ast.Expr = node.array+ while isinstance(root, ast.ArrayAccess):+ root = root.array+ if isinstance(self._resolve_type(root), ast.StringType) and isinstance(+ self._resolve_type(node.property), ast.StringType+ ):+ parent = self.stack[-2] if len(self.stack) > 1 else None+ function = (+ "json_extract"+ if isinstance(parent, ast.ArrayAccess) and parent.array is node+ else "json_extract_scalar"+ )+ return f"{function}({self.visit(node.array)}, {self._json_path([self._constant_string(node.property)])})"+ return f"element_at({self.visit(node.array)}, {self.visit(node.property)})"++ def _constant_string(self, node: ast.Expr) -> str:+ if isinstance(node, ast.Constant) and isinstance(node.value, str):+ return node.value+ self._unsupported(+ "TRINO_JSON_DYNAMIC_PATH_UNSUPPORTED",+ "String-backed bracket access requires a constant key in Trino mode.",+ node,+ )+def visit_tuple_access(self, node: ast.TupleAccess) -> str:source = self.visit(node.tuple)return f"({source})[{node.index}]"@@ -1087,20 +3884,97 @@ class TrinoPrinter(PostgresPrinter):name = node.name.lower()if name == "countdistinct":return self._visit_window_count_distinct(node)- if node.args:+ if name in {"laginframe", "leadinframe"}:+ return self._visit_offset_in_frame_function(node)+ if (+ name in TRINO_EXACT_QUANTILES+ or name in TRINO_EXACT_WEIGHTED_MEDIANS+ or name in TRINO_ARRAY_INSERT_AGGREGATES+ or name in TRINO_DELTA_AGGREGATES+ or name in TRINO_AGGREGATE_COMBINATORS+ or name in TRINO_STATISTICAL_AGGREGATES+ or name in TRINO_UNIQUE_ARRAY_AGGREGATES+ or name in TRINO_MOVING_ARRAY_AGGREGATES+ or name in TRINO_INTERSECTION_AGGREGATES+ or name in TRINO_QUANTILES+ or name in {"avgweighted", "avgweightedif"}+ ):+ parametric = name in {"quantileexact", "quantileexactif", "quantiles", "quantilesif"}+ if not parametric and node.args is not None:+ self._unsupported(+ "TRINO_WINDOW_FUNCTION_PARAMETERS_UNSUPPORTED", f"{node.name} does not accept parameters.", node+ )+ if node.over_expr:+ over = f"({self.visit(node.over_expr)})"+ elif node.over_identifier:+ over = self._print_identifier(node.over_identifier)+ else:+ over = "()"+ aggregate_call = ast.Call(+ name=node.name,+ args=(node.args if parametric else node.exprs) or [],+ params=node.exprs if parametric else None,+ )+ if name in TRINO_AGGREGATE_COMBINATORS:+ return self._visit_aggregate_combinator(aggregate_call, over=f" OVER {over}")+ if name in {"avgweighted", "avgweightedif"}:+ return self._visit_weighted_average(aggregate_call, over=f" OVER {over}")+ if name in TRINO_STATISTICAL_AGGREGATES:+ return self._visit_statistical_aggregate(aggregate_call, over=f" OVER {over}")+ if name in TRINO_UNIQUE_ARRAY_AGGREGATES:+ return self._visit_unique_array_aggregate(aggregate_call, over=f" OVER {over}")+ if name in TRINO_MOVING_ARRAY_AGGREGATES:+ return self._visit_moving_array_aggregate(aggregate_call, over=f" OVER {over}")+ if name in TRINO_INTERSECTION_AGGREGATES:+ return self._visit_max_intersections(aggregate_call, over=f" OVER {over}")+ if name in TRINO_DELTA_AGGREGATES:+ return self._visit_delta_sum(aggregate_call, over=f" OVER {over}")+ if name in TRINO_ARRAY_INSERT_AGGREGATES:+ return self._visit_group_array_insert_at(aggregate_call, over=f" OVER {over}")+ if name in TRINO_EXACT_WEIGHTED_MEDIANS:+ return self._visit_exact_weighted_median(aggregate_call, over=f" OVER {over}")+ if name in TRINO_QUANTILES:+ return self._visit_quantiles(aggregate_call, over=f" OVER {over}")+ return self._visit_exact_quantile(+ aggregate_call,+ filtered=name.endswith("if"),+ over=f" OVER {over}",+ )+ exprs = [self.visit(expr) for expr in node.exprs or []]+ if name in {"quantile", "quantileif"}:+ filtered = name.endswith("if")+ expected_args = 2 if filtered else 1+ if node.args is None or len(node.args) != expected_args or node.exprs is None or len(node.exprs) != 1:+ self._unsupported(+ "TRINO_WINDOW_FUNCTION_ARGUMENTS_UNSUPPORTED",+ f"Window function '{node.name}' has unsupported arguments in Trino mode.",+ node,+ )+ call = f"approx_percentile({self.visit(node.args[0])}, {self.visit(node.exprs[0])})"+ if filtered:+ call += f" FILTER (WHERE {self.visit(node.args[1])})"+ elif node.args:self._unsupported("TRINO_WINDOW_FUNCTION_PARAMETERS_UNSUPPORTED",f"Parametric window function '{node.name}' is not supported in Trino mode.",node,)- if name == "laginframe":- self._unsupported(- "TRINO_LAG_IN_FRAME_UNSUPPORTED",- "lagInFrame has no semantics-safe native Trino equivalent.",- node,- )- exprs = [self.visit(expr) for expr in node.exprs or []]- if name in _TRINO_CONDITIONAL_WINDOW_FUNCTIONS:+ if name in {"quantile", "quantileif"}:+ pass+ elif name in {"uniq", "uniqexact", "uniqif", "uniqexactif"}:+ filtered = name.endswith("if")+ values = exprs[:-1] if filtered else exprs+ if not values or (filtered and len(exprs) < 2):+ self._unsupported(+ "TRINO_WINDOW_FUNCTION_ARGUMENTS_UNSUPPORTED",+ f"Window function '{node.name}' requires values{' and a condition' if filtered else ''}.",+ node,+ )+ value = values[0] if len(values) == 1 else f"ROW({', '.join(values)})"+ if filtered:+ value = f"IF({self._visit_predicate((node.exprs or [])[-1])}, {value}, NULL)"+ call = f"count(DISTINCT {value})"+ elif name in _TRINO_CONDITIONAL_WINDOW_FUNCTIONS:if not exprs:self._unsupported("TRINO_WINDOW_FUNCTION_ARGUMENTS_UNSUPPORTED",@@ -1156,6 +4030,93 @@ class TrinoPrinter(PostgresPrinter):return f"filter({windowed_call}, {value} -> {value} IS NOT NULL)"return windowed_call+ @staticmethod+ def _window_frame_boundary_offset(boundary: ast.WindowFrameExpr) -> float | int | None:+ if boundary.frame_type == "CURRENT ROW":+ return 0+ if boundary.frame_value is None:+ if boundary.frame_type == "PRECEDING":+ return float("-inf")+ if boundary.frame_type == "FOLLOWING":+ return float("inf")+ return None+ value = boundary.frame_value+ if isinstance(value, ast.Constant):+ value = value.value+ if isinstance(value, bool) or not isinstance(value, int) or value < 0:+ return None+ if boundary.frame_type == "PRECEDING":+ return -value+ if boundary.frame_type == "FOLLOWING":+ return value+ return None++ def _visit_offset_in_frame_function(self, node: ast.WindowFunction) -> str:+ window_expr = self._window_expression(node)+ if window_expr is None:+ self._unsupported(+ "TRINO_OFFSET_IN_FRAME_UNSUPPORTED",+ f"{node.name} requires a constant offset included by its ROWS frame for Trino lowering.",+ node,+ )+ exprs = node.exprs or []+ offset_expr = exprs[1] if len(exprs) >= 2 else ast.Constant(value=1)+ offset = offset_expr.value if isinstance(offset_expr, ast.Constant) else None+ target_offset = -offset if node.name.lower() == "laginframe" and isinstance(offset, int) else offset+ frame_start = (+ self._window_frame_boundary_offset(window_expr.frame_start) if window_expr.frame_start is not None else None+ )+ frame_end = (+ self._window_frame_boundary_offset(window_expr.frame_end) if window_expr.frame_end is not None else None+ )+ default_lag_frame = (+ window_expr.frame_method is None+ and node.name.lower() == "laginframe"+ and isinstance(offset, int)+ and not isinstance(offset, bool)+ and offset >= 0+ )+ if not default_lag_frame and (+ window_expr.frame_method != "ROWS"+ or isinstance(offset, bool)+ or not isinstance(offset, int)+ or offset < 0+ or frame_start is None+ or frame_end is None+ or target_offset is None+ or not frame_start <= target_offset <= frame_end+ ):+ self._unsupported(+ "TRINO_OFFSET_IN_FRAME_UNSUPPORTED",+ f"{node.name} requires a constant offset included by its ROWS frame for Trino lowering.",+ node,+ )+ if not window_expr.order_by:+ self._unsupported(+ "TRINO_WINDOW_ORDER_REQUIRED",+ f"Window function '{node.name}' requires ORDER BY in Trino mode.",+ node,+ )+ if node.args:+ self._unsupported(+ "TRINO_WINDOW_FUNCTION_PARAMETERS_UNSUPPORTED",+ f"Parametric window function '{node.name}' is not supported in Trino mode.",+ node,+ )+ rendered_exprs = [self.visit(expr) for expr in exprs]+ if not 1 <= len(rendered_exprs) <= 3:+ self._unsupported(+ "TRINO_WINDOW_FUNCTION_ARGUMENTS_UNSUPPORTED",+ f"Window function '{node.name}' expects one to three arguments in Trino mode.",+ node,+ )+ target = "lag" if node.name.lower() == "laginframe" else "lead"+ lowered_window = clone_expr(window_expr)+ lowered_window.frame_method = None+ lowered_window.frame_start = None+ lowered_window.frame_end = None+ return f"{target}({', '.join(rendered_exprs)}) OVER ({self.visit(lowered_window)})"+def _window_expression(self, node: ast.WindowFunction) -> ast.WindowExpr | None:if node.over_expr is not None:return node.over_expr@@ -1205,15 +4166,17 @@ class TrinoPrinter(PostgresPrinter):return rendereddef _render_start_of(self, unit: str, arg: str, week_mode: int = 3) -> str:- if unit == "week" and week_mode == 0:+ if unit == "week" and week_mode in {0, 2, 4, 6, 8}:return f"date_add('day', -1, date_trunc('week', date_add('day', 1, {arg})))"- if unit == "week" and week_mode not in {1, 3}:+ if unit == "week" and week_mode not in {1, 3, 5, 7, 9}:self._unsupported("TRINO_START_OF_WEEK_MODE_UNSUPPORTED",f"Unsupported toStartOfWeek mode `{week_mode}` in Trino mode.",)if unit == "isoyear":- self._unsupported("TRINO_START_OF_ISO_YEAR_UNSUPPORTED", "toStartOfISOYear is not supported in Trino mode.")+ date = f"CAST({arg} AS DATE)"+ january_fourth = f"CAST(format('%04d-01-04', year_of_week({date})) AS DATE)"+ return f"date_add('day', 1 - day_of_week({january_fourth}), {january_fourth})"return f"date_trunc('{unit}', {arg})"def _render_minute_bucket(self, arg: str, bucket_size: int) -> str:@@ -1312,10 +4275,14 @@ class TrinoPrinter(PostgresPrinter):self._unsupported("TRINO_WITH_TIES_NOT_LOWERED", "WITH TIES must be lowered before Trino printing.")def visit_cte(self, node: ast.CTE) -> str:- if node.materialized is not None or node.using_key is not None:+ if node.using_key is not None:self._unsupported("TRINO_CTE_MODIFIER_UNSUPPORTED",- "CTE materialization hints and USING KEY are not supported in Trino mode.",+ "CTE USING KEY is not supported in Trino mode.",node,)- return super().visit_cte(node)+ if node.materialized is None:+ return super().visit_cte(node)+ lowered = clone_expr(node, clear_types=False)+ lowered.materialized = None+ return super().visit_cte(lowered)diff --git a/posthog/hogql/printer/trino_functions.py b/posthog/hogql/printer/trino_functions.pyindex 315a93dfbd6e..f3bc9da42995 100644--- a/posthog/hogql/printer/trino_functions.py+++ b/posthog/hogql/printer/trino_functions.py@@ -1,7 +1,54 @@from collections.abc import Callable+from math import factorialfrom posthog.hogql.transforms.trino.errors import TrinoLoweringError+from posthog.dataclasses import frozen++TRINO_AGGREGATE_COMBINATORS = {+ f"{base}{array}{empty}{condition}".lower(): (base, array, empty, bool(condition))+ for base in ("avg", "sum", "min", "max", "count", "countDistinct", "median")+ for array in ("", "Array", "ForEach", "Map", "ArgMin", "ArgMax")+ for empty in ("", "OrDefault", "OrNull")+ for condition in ("", "If")+ if array or empty+}+TRINO_EXACT_QUANTILES = frozenset(+ f"{base}{condition}"+ for base in ("quantileexact", "medianexact", "medianexactlow", "medianexacthigh")+ for condition in ("", "if")+)+TRINO_EXACT_WEIGHTED_MEDIANS = frozenset({"medianexactweighted", "medianexactweightedif"})+TRINO_QUANTILES = frozenset({"quantiles", "quantilesif"})+TRINO_STATISTICAL_AGGREGATES = frozenset(+ f"{base}{condition}"+ for base in ("skewpop", "skewsamp", "kurtpop", "kurtsamp", "simplelinearregression")+ for condition in ("", "if")+)+TRINO_UNIQUE_ARRAY_AGGREGATES = frozenset({"groupuniqarrayarray", "groupuniqarrayarrayif"})+TRINO_MOVING_ARRAY_AGGREGATES = frozenset(+ {"grouparraymovingsum", "grouparraymovingsumif", "grouparraymovingavg", "grouparraymovingavgif"}+)+TRINO_DELTA_AGGREGATES = frozenset({"deltasum", "deltasumif"})+TRINO_ARRAY_INSERT_AGGREGATES = frozenset({"grouparrayinsertat", "grouparrayinsertatif"})+TRINO_INTERSECTION_AGGREGATES = frozenset(+ {"maxintersections", "maxintersectionsif", "maxintersectionsposition", "maxintersectionspositionif"}+)+TRINO_WINDOW_ONLY_FUNCTIONS = frozenset({"laginframe", "leadinframe"})+TRINO_TUPLE_OPERATORS = {+ "tupleplus": "+",+ "tupleminus": "-",+ "tuplemultiply": "*",+ "tupledivide": "/",+ "tuplenegate": "-",+ "tuplemultiplybynumber": "*",+ "tupledividebynumber": "/",+ "tuplehammingdistance": "!=",+}+TRINO_VECTOR_REWRITES = frozenset(+ {"lpnorm", "lpdistance", "l1normalize", "l2normalize", "linfnormalize", "lpnormalize"}+)+TRINO_FUNCTION_RENAMES: dict[str, str] = {"any": "arbitrary","anyLast": "arbitrary",@@ -13,18 +60,58 @@ TRINO_FUNCTION_RENAMES: dict[str, str] = {"fromUnixTimestamp": "from_unixtime","replaceAll": "replace","replaceRegexpAll": "regexp_replace",- "arrayStringConcat": "array_join",- "JSONLength": "json_array_length",- "toTypeName": "typeof","now": "now","startsWith": "starts_with",- "endsWith": "ends_with","rand": "random","dateTrunc": "date_trunc","substringUTF8": "substring",+ "lowerUTF8": "lower",+ "upperUTF8": "upper",+ "encodeURLComponent": "url_encode",+ "encodeURLFormComponent": "url_encode",+ "lengthUTF8": "length","toLastDayOfMonth": "last_day_of_month","mapFromArrays": "map","mapUpdate": "map_concat",+ "log": "ln",+ "decodeURLComponent": "url_decode",+ "decodeURLFormComponent": "url_decode",+ "trimLeft": "ltrim",+ "trimRight": "rtrim",+ "leftPad": "lpad",+ "indexOf": "array_position",+ "TRUNC": "truncate",+ "JSONArrayLength": "json_array_length",+ "age": "date_diff",+ "arrayReverse": "reverse",+ "cosineDistance": "cosine_distance",+ "dotProduct": "dot_product",+ "L2Distance": "euclidean_distance",+ "bitAnd": "bitwise_and",+ "bitOr": "bitwise_or",+ "bitXor": "bitwise_xor",+ "corr": "corr",+ "isFinite": "is_finite",+ "isInfinite": "is_infinite",+ "isNaN": "is_nan",+ "mapKeys": "map_keys",+ "mapValues": "map_values",+ "reverseUTF8": "reverse",+ "split_part": "split_part",+ "stddevPop": "stddev_pop",+ "stddevSamp": "stddev_samp",+ "translate": "translate",+ "translateUTF8": "translate",+ "btrim": "trim",+ "varPop": "var_pop",+ "varSamp": "var_samp",+ "covarPop": "covar_pop",+ "covarSamp": "covar_samp",+ "width_bucket": "width_bucket",+ "hasSubstr": "contains_sequence",+ "groupBitAnd": "bitwise_and_agg",+ "groupBitOr": "bitwise_or_agg",+ "groupBitXor": "bitwise_xor_agg",}@@ -79,6 +166,15 @@ def _multi_if(args: list[str]) -> str:return " ".join(parts)+def _case_with_expression(args: list[str]) -> str:+ if len(args) < 4 or len(args) % 2 != 0:+ raise _invalid_arguments("caseWithExpression", "CASE expects a value, match/result pairs, and a default.")+ parts = [f"CASE {args[0]}"]+ parts.extend(f"WHEN {args[index]} THEN {args[index + 1]}" for index in range(1, len(args) - 1, 2))+ parts.append(f"ELSE {args[-1]} END")+ return " ".join(parts)++def _count_if(args: list[str]) -> str:if len(args) == 1:return f"count(*) FILTER (WHERE {args[0]})"@@ -96,6 +192,53 @@ def _aggregate_if(function: str) -> Callable[[list[str]], str]:return handler+def _has_token(name: str, case_insensitive: bool, null_on_invalid: bool) -> Callable[[list[str]], str]:+ def handler(args: list[str]) -> str:+ _require_args(name, args, 2)+ raw_haystack = "__hogql_token_args[1]"+ raw_needle = "__hogql_token_args[2]"+ haystack = raw_haystack+ needle = raw_needle+ if case_insensitive:+ alphabet = "'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'"+ haystack = f"translate({haystack}, {alphabet})"+ needle = f"translate({needle}, {alphabet})"+ escaped = f"regexp_replace({needle}, '([\\\\|()^$.\\-\\[\\]?*+{{:\\x00])', '\\\\$1')"+ token_character = r"A-Za-z0-9\P{ASCII}"+ valid = f"{needle} = '' OR regexp_like({needle}, '^[{token_character}]+$')"+ pattern = f"concat('(?:^|[^{token_character}])', {escaped}, '(?:$|[^{token_character}])')"+ result = f"IF({needle} = '', false, regexp_like({haystack}, {pattern}))"+ invalid = "NULL" if null_on_invalid else f"fail('{name} requires one token as its second argument')"+ result = f"IF({valid}, {result}, {invalid})"+ result = f"IF({raw_haystack} IS NULL OR {raw_needle} IS NULL, NULL, {result})"+ return f"element_at(transform(ARRAY[ROW({args[0]}, {args[1]})], __hogql_token_args -> {result}), 1)"++ return handler+++def _format_readable(name: str, base: int, units: tuple[str, ...]) -> Callable[[list[str]], str]:+ def handler(args: list[str]) -> str:+ _require_args(name, args, 1)+ value = "__hogql_readable"+ unit_index = (+ f"IF(is_nan({value}), BIGINT '0', IF(is_infinite({value}), BIGINT '{len(units) - 1}', "+ f"IF(abs({value}) < {base}, BIGINT '0', "+ f"least(CAST(floor(ln(abs({value})) / ln({base}e0)) AS BIGINT), {len(units) - 1}))))"+ )+ unit = f"element_at(ARRAY[{', '.join(repr(unit) for unit in units)}], __hogql_unit_index + 1)"+ suffix = f"IF({unit} = '', '', concat(' ', {unit}))"+ finite = f"concat(format('%.2f', {value} / power({base}e0, __hogql_unit_index)), {suffix})"+ nan = "'nan'" if units[0] == "" else f"'nan {units[0]}'"+ infinity = f"concat(IF({value} < 0, '-inf', 'inf'), IF('{units[-1]}' = '', '', ' {units[-1]}'))"+ result = f"IF(is_nan({value}), {nan}, IF(is_infinite({value}), {infinity}, {finite}))"+ return (+ f"element_at(transform(ARRAY[CAST({args[0]} AS DOUBLE)], {value} -> "+ f"element_at(transform(ARRAY[{unit_index}], __hogql_unit_index -> {result}), 1)), 1)"+ )++ return handler++def _uniq(args: list[str]) -> str:if not args:raise _invalid_arguments("uniq", "uniq expects at least one argument in Trino mode.")@@ -128,7 +271,7 @@ def _date_add(unit: str, sign: int = 1) -> Callable[[list[str]], str]:def _interval(unit: str) -> Callable[[list[str]], str]:def handler(args: list[str]) -> str:_require_args("interval", args, 1)- return f"parse_duration(CAST({args[0]} AS VARCHAR) || ' {unit}')"+ return f"(CAST({args[0]} AS BIGINT) * INTERVAL '1' {unit.rstrip('s').upper()})"return handler@@ -161,6 +304,11 @@ def _divide(args: list[str]) -> str:return f"(CAST({args[0]} AS DOUBLE) / CAST({args[1]} AS DOUBLE))"+def _divide_decimal(args: list[str]) -> str:+ _require_args("divideDecimal", args, 2)+ return f"({args[0]} / {args[1]})"++def _not(args: list[str]) -> str:_require_args("not", args, 1)return f"(NOT {args[0]})"@@ -191,9 +339,76 @@ def _identity(name: str) -> Callable[[list[str]], str]:return handler+def _constant(name: str, value: str) -> Callable[[list[str]], str]:+ def handler(args: list[str]) -> str:+ _require_args(name, args, 1)+ return value++ return handler+++def _array_string_concat(args: list[str]) -> str:+ if len(args) not in {1, 2}:+ raise _invalid_arguments("arrayStringConcat", "arrayStringConcat expects an array and optional separator.")+ separator = args[1] if len(args) == 2 else "''"+ return f"array_join({args[0]}, {separator})"+++def _ends_with(args: list[str]) -> str:+ _require_args("endsWith", args, 2)+ return f"({args[1]} = '' OR substr({args[0]}, -length({args[1]})) = {args[1]})"++def _format_date_time(args: list[str]) -> str:- _require_args("formatDateTime", args, 2)- return f"date_format({args[0]}, {args[1]})"+ if len(args) == 2:+ return f"date_format({args[0]}, {args[1]})"+ if len(args) == 3:+ return f"date_format(at_timezone(with_timezone(CAST({args[0]} AS TIMESTAMP), 'UTC'), {args[2]}), {args[1]})"+ raise _invalid_arguments("formatDateTime", "formatDateTime expects a value, format, and optional timezone.")+++def _from_unix_timestamp64_milli(args: list[str]) -> str:+ _require_args("fromUnixTimestamp64Milli", args, 1)+ return f"from_unixtime((CAST({args[0]} AS DOUBLE) / 1000e0))"+++def _time_slot(args: list[str]) -> str:+ _require_args("timeSlot", args, 1)+ return f"date_add('minute', -mod(minute({args[0]}), 30), date_trunc('minute', {args[0]}))"+++def _to_time(args: list[str]) -> str:+ _require_args("toTime", args, 1)+ seconds = f"hour({args[0]}) * 3600 + minute({args[0]}) * 60 + second({args[0]})"+ return f"date_add('second', {seconds}, TIMESTAMP '1970-01-02 00:00:00')"+++def _time_slots(args: list[str]) -> str:+ if len(args) not in {2, 3}:+ raise _invalid_arguments("timeSlots", "timeSlots expects a start, duration, and optional slot size.")+ size = f"CAST({args[2]} AS BIGINT)" if len(args) == 3 else "BIGINT '1800'"+ start = f"CAST(floor(to_unixtime({args[0]})) AS BIGINT)"+ duration = f"CAST({args[1]} AS BIGINT)"+ first = f"{start} - mod({start}, {size})"+ last = f"{start} + {duration} - mod({start} + {duration}, {size})"+ values = f"transform(sequence({first}, {last}, {size}), __hogql_epoch -> CAST(from_unixtime(__hogql_epoch) AS TIMESTAMP))"+ return f"IF({size} > 0 AND {duration} >= 0, {values}, fail('timeSlots requires a positive size and non-negative duration'))"+++def _right(args: list[str]) -> str:+ _require_args("right", args, 2)+ return (+ f"IF({args[1]} = 0, '', IF({args[1]} > 0, substr({args[0]}, -({args[1]})), "+ f"substr({args[0]}, greatest(1, -({args[1]}) + 1))))"+ )+++def _left(args: list[str]) -> str:+ _require_args("left", args, 2)+ return (+ f"IF({args[1]} >= 0, substr({args[0]}, 1, {args[1]}), "+ f"substr({args[0]}, 1, greatest(length({args[0]}) + {args[1]}, 0)))"+ )def _position(args: list[str]) -> str:@@ -201,6 +416,93 @@ def _position(args: list[str]) -> str:return f"strpos({args[0]}, {args[1]})"+def _position_case_insensitive(args: list[str]) -> str:+ if len(args) == 2:+ return f"strpos(lower({args[0]}), lower({args[1]}))"+ if len(args) == 3:+ match = f"strpos(lower(substr({args[0]}, {args[2]})), lower({args[1]}))"+ return f"CASE WHEN {match} = 0 THEN 0 ELSE {match} + {args[2]} - 1 END"+ raise _invalid_arguments(+ "positionCaseInsensitive", "positionCaseInsensitive expects two or three arguments in Trino mode."+ )+++def _replace_one(args: list[str]) -> str:+ _require_args("replaceOne", args, 3)+ source, pattern, replacement = args+ position = f"strpos({source}, {pattern})"+ return (+ f"CASE WHEN length({pattern}) = 0 OR {position} = 0 THEN {source} ELSE "+ f"concat(substr({source}, 1, {position} - 1), {replacement}, "+ f"substr({source}, {position} + length({pattern}))) END"+ )+++def _float_or_null(args: list[str]) -> str:+ _require_args("toFloat64OrNull", args, 1)+ return f"TRY_CAST({args[0]} AS DOUBLE)"+++def _array_slice(args: list[str]) -> str:+ if len(args) not in {2, 3}:+ raise _invalid_arguments("arraySlice", "arraySlice expects an array, offset, and optional length.")+ array, offset, requested_length = "__hogql_slice[1]", "__hogql_slice[2]", "__hogql_slice[3]"+ size = f"cardinality({array})"+ start = f"IF({offset} < 0, {size} + {offset} + 1, {offset})"+ end = (+ size+ if len(args) == 2+ else f"IF({requested_length} < 0, {size} + {requested_length}, {start} + {requested_length} - 1)"+ )+ clipped_start = f"greatest(1, {start})"+ length = f"IF({offset} = 0, 0, greatest(0, {end} - {clipped_start} + 1))"+ return (+ f"element_at(transform(ARRAY[ROW({', '.join(args)})], "+ f"__hogql_slice -> slice({array}, {clipped_start}, {length})), 1)"+ )+++def _array_intersect(args: list[str]) -> str:+ if not args:+ raise _invalid_arguments("arrayIntersect", "arrayIntersect expects at least one argument in Trino mode.")+ result = f"array_distinct({args[0]})"+ for arg in args[1:]:+ result = f"array_intersect({result}, {arg})"+ return result+++def _cut_fragment(args: list[str]) -> str:+ _require_args("cutFragment", args, 1)+ return f"regexp_replace({args[0]}, '#.*$', '')"+++def _cut_query_string(args: list[str]) -> str:+ _require_args("cutQueryString", args, 1)+ return f"regexp_replace({args[0]}, '\\?.*$', '')"+++def _cut_query_string_and_fragment(args: list[str]) -> str:+ _require_args("cutQueryStringAndFragment", args, 1)+ return f"regexp_replace({args[0]}, '[?#].*$', '')"+++def _map(args: list[str]) -> str:+ if not args or len(args) % 2 != 0:+ raise _invalid_arguments("map", "map expects one or more key/value pairs in Trino mode.")+ return f"map(ARRAY[{', '.join(args[::2])}], ARRAY[{', '.join(args[1::2])}])"+++def _transform(args: list[str]) -> str:+ if len(args) not in {3, 4}:+ raise _invalid_arguments("transform", "transform expects three or four arguments in Trino mode.")+ value, source, target = args[:3]+ fallback = args[3] if len(args) == 4 else value+ return (+ f"CASE WHEN contains({source}, {value}) "+ f"THEN element_at({target}, array_position({source}, {value})) ELSE {fallback} END"+ )++def _to_monday(args: list[str]) -> str:_require_args("toMonday", args, 1)return f"CAST(date_trunc('week', {args[0]}) AS DATE)"@@ -245,17 +547,1201 @@ def _current_timestamp(args: list[str]) -> str:return "CURRENT_TIMESTAMP"+def _unary_expression(name: str, template: str) -> Callable[[list[str]], str]:+ def handler(args: list[str]) -> str:+ _require_args(name, args, 1)+ return template.format(value=args[0])++ return handler+++def _binary_expression(name: str, template: str) -> Callable[[list[str]], str]:+ def handler(args: list[str]) -> str:+ _require_args(name, args, 2)+ return template.format(left=args[0], right=args[1])++ return handler+++def _array(args: list[str]) -> str:+ return f"ARRAY[{', '.join(args)}]"+++def _array_pop_front(args: list[str]) -> str:+ _require_args("arrayPopFront", args, 1)+ return f"slice({args[0]}, 2, greatest(cardinality({args[0]}) - 1, 0))"+++def _array_pop_back(args: list[str]) -> str:+ _require_args("arrayPopBack", args, 1)+ return f"slice({args[0]}, 1, greatest(cardinality({args[0]}) - 1, 0))"+++def _array_push_front(args: list[str]) -> str:+ _require_args("arrayPushFront", args, 2)+ return f"concat(ARRAY[{args[1]}], {args[0]})"+++def _array_push_back(args: list[str]) -> str:+ _require_args("arrayPushBack", args, 2)+ return f"concat({args[0]}, ARRAY[{args[1]}])"+++def _array_resize(args: list[str]) -> str:+ if len(args) != 3:+ raise _invalid_arguments(+ "arrayResize",+ "The two-argument form needs a type-dependent default value. Trino mode requires an explicit value.",+ )+ array, size, value = args+ return (+ f"IF({size} >= 0, concat(slice({array}, 1, CAST({size} AS BIGINT)), "+ f"repeat({value}, greatest(CAST({size} AS BIGINT) - cardinality({array}), 0)), slice({array}, 1, 0)), "+ f"concat(repeat({value}, greatest(-(CAST({size} AS BIGINT)) - cardinality({array}), 0)), "+ f"slice({array}, greatest(cardinality({array}) + CAST({size} AS BIGINT) + 1, 1), "+ f"least(-(CAST({size} AS BIGINT)), cardinality({array}))), slice({array}, 1, 0)))"+ )+++def _array_difference(args: list[str]) -> str:+ _require_args("arrayDifference", args, 1)+ value = args[0]+ return (+ f"IF(cardinality({value}) = 0, ARRAY[], "+ f"transform(sequence(1, cardinality({value})), __hogql_index -> "+ f"IF(__hogql_index = 1, 0, {value}[__hogql_index] - {value}[__hogql_index - 1])))"+ )+++def _array_product(args: list[str]) -> str:+ _require_args("arrayProduct", args, 1)+ return (+ f"IF(cardinality({args[0]}) = 0, DOUBLE '0', "+ f"reduce({args[0]}, DOUBLE '1', (__hogql_total, __hogql_value) -> "+ f"__hogql_total * __hogql_value, __hogql_total -> __hogql_total))"+ )+++def _array_uniq(args: list[str]) -> str:+ if not args:+ raise _invalid_arguments("arrayUniq", "arrayUniq expects at least one array.")+ value = args[0] if len(args) == 1 else f"zip({', '.join(args)})"+ return f"cardinality(array_distinct({value}))"+++def _array_with_constant(args: list[str]) -> str:+ _require_args("arrayWithConstant", args, 2)+ return f"repeat({args[1]}, CAST({args[0]} AS BIGINT))"+++def _base64_encode(args: list[str]) -> str:+ _require_args("base64Encode", args, 1)+ return f"to_base64(to_utf8({args[0]}))"+++def _base58_encode(args: list[str]) -> str:+ _require_args("base58Encode", args, 1)+ value = "__hogql_base58_value"+ binary = f"to_utf8({value})"+ byte_count = f"length({binary})"+ positions = f"IF({byte_count} = 0, CAST(ARRAY[] AS ARRAY(BIGINT)), sequence(BIGINT '1', {byte_count}))"+ bytes_array = (+ f"transform({positions}, __hogql_base58_position -> "+ f"from_base(substr(to_hex({binary}), __hogql_base58_position * 2 - 1, 2), 16))"+ )+ state = "__hogql_base58_state"+ byte = "__hogql_base58_byte"+ carry_state = "__hogql_base58_carry_state"+ digit = "__hogql_base58_digit"+ converted = "__hogql_base58_converted"+ multiplied = (+ f"reduce({state}[1], ROW({byte}, CAST(ARRAY[] AS ARRAY(BIGINT))), "+ f"({carry_state}, {digit}) -> ROW(({carry_state}[1] + {digit} * 256) / 58, "+ f"concat({carry_state}[2], ARRAY[mod({carry_state}[1] + {digit} * 256, 58)])), "+ f"{carry_state} -> {carry_state})"+ )+ remaining_digits = (+ f"IF({converted}[1] = 0, CAST(ARRAY[] AS ARRAY(BIGINT)), "+ f"IF({converted}[1] < 58, ARRAY[{converted}[1]], "+ f"ARRAY[mod({converted}[1], 58), {converted}[1] / 58]))"+ )+ update = (+ f"IF(NOT {state}[3] AND {byte} = 0, ROW({state}[1], {state}[2] + 1, false), "+ f"element_at(transform(ARRAY[{multiplied}], {converted} -> "+ f"ROW(concat({converted}[2], {remaining_digits}), {state}[2], true)), 1))"+ )+ reduced = (+ f"reduce({bytes_array}, ROW(CAST(ARRAY[] AS ARRAY(BIGINT)), BIGINT '0', false), "+ f"({state}, {byte}) -> {update}, {state} -> {state})"+ )+ alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"+ encoded = (+ f"array_join(repeat('1', CAST({state}[2] AS INTEGER)), '') || "+ f"array_join(transform(reverse({state}[1]), {digit} -> substr('{alphabet}', {digit} + 1, 1)), '')"+ )+ result = f"element_at(transform(ARRAY[{reduced}], {state} -> {encoded}), 1)"+ return f"element_at(transform(ARRAY[{args[0]}], {value} -> IF({value} IS NULL, NULL, {result})), 1)"+++def _base64_decode(args: list[str]) -> str:+ _require_args("base64Decode", args, 1)+ return f"from_utf8(from_base64({args[0]}))"+++def _try_base64_decode(args: list[str]) -> str:+ _require_args("tryBase64Decode", args, 1)+ valid = (+ f"mod(length({args[0]}), 4) = 0 AND "+ f"regexp_like({args[0]}, '^(?:[A-Za-z0-9+/]{{4}})*(?:[A-Za-z0-9+/]{{2}}==|[A-Za-z0-9+/]{{3}}=)?$')"+ )+ return f"IF({valid}, coalesce(TRY(from_utf8(from_base64({args[0]}))), ''), '')"+++def _ascii(args: list[str]) -> str:+ _require_args("ascii", args, 1)+ return f"IF({args[0]} = '', 0, from_base(to_hex(substr(to_utf8({args[0]}), 1, 1)), 16))"+++def _concat_with_separator(args: list[str]) -> str:+ if len(args) < 2:+ raise _invalid_arguments("concatWithSeparator", "concatWithSeparator expects a separator and values.")+ null_check = " OR ".join(f"{arg} IS NULL" for arg in args)+ return f"IF({null_check}, NULL, array_join(ARRAY[{', '.join(args[1:])}], {args[0]}))"+++def _split_by_whitespace(args: list[str]) -> str:+ _require_args("splitByWhitespace", args, 1)+ return f"IF(trim({args[0]}) = '', ARRAY[], regexp_split(trim({args[0]}), '\\s+'))"+++def _map_contains(args: list[str]) -> str:+ _require_args("mapContains", args, 2)+ return f"contains(map_keys({args[0]}), {args[1]})"+++def _map_lambda(name: str, target: str) -> Callable[[list[str]], str]:+ def handler(args: list[str]) -> str:+ _require_args(name, args, 2)+ return f"{target}({args[1]}, {args[0]})"++ return handler+++def _map_apply(args: list[str]) -> str:+ _require_args("mapApply", args, 2)+ transformed = f"transform_values({args[1]}, {args[0]})"+ return (+ f"map_from_entries(transform(map_entries({transformed}), "+ "__hogql_entry -> ROW(__hogql_entry[2][1], __hogql_entry[2][2])))"+ )+++def _json_agg(args: list[str]) -> str:+ _require_args("json_agg", args, 1)+ return f"json_format(CAST(array_agg({args[0]}) AS JSON))"+++def _string_agg(args: list[str]) -> str:+ _require_args("string_agg", args, 2)+ return f"array_join(array_agg({args[0]}), {args[1]})"+++def _date_arithmetic(name: str, operator: str) -> Callable[[list[str]], str]:+ def handler(args: list[str]) -> str:+ _require_args(name, args, 2)+ return f"({args[0]} {operator} {args[1]})"++ return handler+++def _make_date(args: list[str]) -> str:+ _require_args("make_date", args, 3)+ value = f"TRY_CAST(format('%04d-%02d-%02d', {args[0]}, {args[1]}, {args[2]}) AS DATE)"+ return f"IF({value} BETWEEN DATE '1970-01-01' AND DATE '2149-06-06', {value}, DATE '1970-01-01')"+++def _timezone(args: list[str]) -> str:+ _require_args("timezone", args, 2)+ return f"at_timezone(with_timezone(CAST({args[1]} AS TIMESTAMP), 'UTC'), {args[0]})"+++def _timezone_offset(args: list[str]) -> str:+ _require_args("timeZoneOffset", args, 1)+ return f"(timezone_hour({args[0]}) * 3600 + timezone_minute({args[0]}) * 60)"+++def _week_anchor(january_first: str, weekday: int, rule: str) -> str:+ if rule == "first":+ distance = f"mod({weekday} - day_of_week({january_first}) + 7, 7)"+ return f"date_add('day', {distance}, {january_first})"+ if rule == "four":+ january_fourth = f"date_add('day', 3, {january_first})"+ distance = f"mod(day_of_week({january_fourth}) - {weekday} + 7, 7)"+ return f"date_add('day', -{distance}, {january_fourth})"+ distance = f"mod(day_of_week({january_first}) - {weekday} + 7, 7)"+ return f"date_add('day', -{distance}, {january_first})"+++def _week_value(date: str, january_first: str, weekday: int, rule: str, range_starts_at_one: bool) -> str:+ anchor = _week_anchor(january_first, weekday, rule)+ if not range_starts_at_one:+ return f"IF({date} < {anchor}, BIGINT '0', date_diff('day', {anchor}, {date}) / 7 + 1)"++ previous_january_first = f"date_add('year', -1, {january_first})"+ next_january_first = f"date_add('year', 1, {january_first})"+ previous_anchor = _week_anchor(previous_january_first, weekday, rule)+ next_anchor = _week_anchor(next_january_first, weekday, rule)+ return (+ f"CASE WHEN {date} < {anchor} THEN date_diff('day', {previous_anchor}, {date}) / 7 + 1 "+ f"WHEN {date} >= {next_anchor} THEN date_diff('day', {next_anchor}, {date}) / 7 + 1 "+ f"ELSE date_diff('day', {anchor}, {date}) / 7 + 1 END"+ )+++def _year_week_value(date: str, january_first: str, weekday: int, rule: str) -> str:+ anchor = _week_anchor(january_first, weekday, rule)+ previous_january_first = f"date_add('year', -1, {january_first})"+ next_january_first = f"date_add('year', 1, {january_first})"+ previous_anchor = _week_anchor(previous_january_first, weekday, rule)+ next_anchor = _week_anchor(next_january_first, weekday, rule)+ year = f"year({date})"+ return (+ f"CASE WHEN {date} < {anchor} THEN ({year} - 1) * 100 + date_diff('day', {previous_anchor}, {date}) / 7 + 1 "+ f"WHEN {date} >= {next_anchor} THEN ({year} + 1) * 100 + date_diff('day', {next_anchor}, {date}) / 7 + 1 "+ f"ELSE {year} * 100 + date_diff('day', {anchor}, {date}) / 7 + 1 END"+ )+++def _to_week(name: str, include_year: bool) -> Callable[[list[str]], str]:+ modes = {+ 0: (7, "first", False),+ 1: (1, "four", False),+ 2: (7, "first", True),+ 3: (1, "four", True),+ 4: (7, "four", False),+ 5: (1, "first", False),+ 6: (7, "four", True),+ 7: (1, "first", True),+ 8: (7, "contains", True),+ 9: (1, "contains", True),+ }++ def handler(args: list[str]) -> str:+ if len(args) not in {1, 2, 3}:+ raise _invalid_arguments(name, f"{name} expects a date, optional mode, and optional timezone.")+ date = f"CAST({args[0]} AS DATE)"+ if len(args) == 3:+ date = f"CAST(at_timezone(with_timezone(CAST({args[0]} AS TIMESTAMP), 'UTC'), {args[2]}) AS DATE)"+ mode = f"CAST({args[1]} AS INTEGER)" if len(args) >= 2 else "0"+ week = "__hogql_week[1]"+ january_first = f"date_trunc('year', {week})"+ branches = []+ for mode_number, (weekday, rule, range_starts_at_one) in modes.items():+ value = (+ _year_week_value(week, january_first, weekday, rule)+ if include_year+ else _week_value(week, january_first, weekday, rule, range_starts_at_one)+ )+ branches.append(f"WHEN {mode_number} THEN {value}")+ result = " ".join(branches)+ return (+ f"element_at(transform(ARRAY[ROW({date}, {mode})], __hogql_week -> "+ f"CASE __hogql_week[2] {result} ELSE fail('{name} mode must be between 0 and 9') END), 1)"+ )++ return handler+++def _json_is_valid(args: list[str]) -> str:+ _require_args("isValidJSON", args, 1)+ return f"(TRY(json_parse(CAST({args[0]} AS VARCHAR))) IS NOT NULL)"+++def _positive_modulo(args: list[str]) -> str:+ _require_args("positiveModulo", args, 2)+ return f"mod(mod({args[0]}, {args[1]}) + {args[1]}, {args[1]})"+++def _or_zero(name: str, operator: str) -> Callable[[list[str]], str]:+ def handler(args: list[str]) -> str:+ _require_args(name, args, 2)+ return f"IF({args[1]} = 0, 0, {operator.format(left=args[0], right=args[1])})"++ return handler+++def _every(args: list[str]) -> str:+ _require_args("every", args, 1)+ return f"bool_and(CAST({args[0]} AS BOOLEAN))"+++def _pad(name: str, target: str) -> Callable[[list[str]], str]:+ def handler(args: list[str]) -> str:+ if len(args) not in {2, 3}:+ raise _invalid_arguments(name, f"{name} expects a string, length, and optional padding string.")+ padding = args[2] if len(args) == 3 else "' '"+ return f"{target}({args[0]}, {args[1]}, {padding})"++ return handler+++def _array_avg(args: list[str]) -> str:+ if len(args) == 1:+ values = args[0]+ elif len(args) == 2:+ values = f"transform({args[1]}, {args[0]})"+ else:+ raise _invalid_arguments("arrayAvg", "arrayAvg expects an array or a lambda and an array.")+ return (+ f"IF(cardinality({values}) = 0, DOUBLE '0', "+ f"reduce({values}, DOUBLE '0', (__hogql_total, __hogql_value) -> "+ f"__hogql_total + __hogql_value, __hogql_total -> __hogql_total) / cardinality({values}))"+ )+++def _array_compact(args: list[str]) -> str:+ _require_args("arrayCompact", args, 1)+ value = args[0]+ empty = f"slice({value}, 1, 0)"+ return (+ f"reduce({value}, {empty}, (__hogql_result, __hogql_value) -> "+ f"IF(cardinality(__hogql_result) = 0 OR element_at(__hogql_result, -1) IS DISTINCT FROM __hogql_value, "+ f"concat(__hogql_result, ARRAY[__hogql_value]), __hogql_result), __hogql_result -> __hogql_result)"+ )+++def _array_enumerate_dense(args: list[str]) -> str:+ _require_args("arrayEnumerateDense", args, 1)+ value = args[0]+ return (+ f"IF(cardinality({value}) = 0, ARRAY[], "+ f"transform(sequence(1, cardinality({value})), __hogql_index -> "+ f"array_position(transform(array_distinct(slice({value}, 1, __hogql_index)), "+ f"__hogql_candidate -> __hogql_candidate IS NOT DISTINCT FROM {value}[__hogql_index]), TRUE)))"+ )+++def _array_enumerate_uniq(args: list[str]) -> str:+ if not args:+ raise _invalid_arguments("arrayEnumerateUniq", "arrayEnumerateUniq expects at least one array.")+ value = args[0] if len(args) == 1 else f"zip({', '.join(args)})"+ return (+ f"IF(cardinality({value}) = 0, ARRAY[], "+ f"transform(sequence(1, cardinality({value})), __hogql_index -> "+ f"cardinality(filter(slice({value}, 1, __hogql_index), __hogql_value -> "+ f"__hogql_value IS NOT DISTINCT FROM {value}[__hogql_index]))))"+ )+++def _array_index(name: str, target: str) -> Callable[[list[str]], str]:+ def handler(args: list[str]) -> str:+ _require_args(name, args, 2)+ matches = f"transform({args[1]}, {args[0]})"+ if target == "first":+ return f"coalesce(array_position({matches}, TRUE), 0)"+ position = f"array_position(reverse({matches}), TRUE)"+ return f"IF({position} = 0, 0, cardinality({args[1]}) - {position} + 1)"++ return handler+++def _array_rotate(name: str, direction: int) -> Callable[[list[str]], str]:+ def handler(args: list[str]) -> str:+ _require_args(name, args, 2)+ value = args[0]+ amount = args[1] if direction > 0 else f"-({args[1]})"+ size = f"cardinality({value})"+ offset = f"mod(mod({amount}, {size}) + {size}, {size})"+ return (+ f"IF({size} = 0, {value}, concat(slice({value}, {offset} + 1, {size} - {offset}), "+ f"slice({value}, 1, {offset})))"+ )++ return handler+++def _count_matches(name: str, case_insensitive: bool = False) -> Callable[[list[str]], str]:+ def handler(args: list[str]) -> str:+ _require_args(name, args, 2)+ pattern = f"concat('(?i)', {args[1]})" if case_insensitive else args[1]+ return f"IF(length({args[1]}) = 0, 0, cardinality(regexp_extract_all({args[0]}, {pattern})))"++ return handler+++def _count_substrings(name: str, case_insensitive: bool = False, utf8: bool = False) -> Callable[[list[str]], str]:+ def handler(args: list[str]) -> str:+ if len(args) not in {2, 3}:+ raise _invalid_arguments(name, f"{name} expects a string, substring, and optional start position.")+ value = "__hogql_substrings[1]"+ needle = "__hogql_substrings[2]"+ if case_insensitive:+ if utf8:+ value, needle = f"lower({value})", f"lower({needle})"+ else:+ alphabet = "'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'"+ value, needle = f"translate({value}, {alphabet})", f"translate({needle}, {alphabet})"+ if len(args) == 3:+ value = f"substr({value}, greatest(CAST(__hogql_substrings[3] AS BIGINT), 1))"+ result = (+ f"IF(length({needle}) = 0, 0, "+ f"(length({value}) - length(replace({value}, {needle}, ''))) / length({needle}))"+ )+ if len(args) == 3 and not utf8:+ ascii_only = (+ "length(to_utf8(__hogql_substrings[1])) = length(__hogql_substrings[1]) AND "+ "length(to_utf8(__hogql_substrings[2])) = length(__hogql_substrings[2])"+ )+ result = f"IF({ascii_only}, {result}, fail('A byte start position requires ASCII strings'))"+ if case_insensitive and utf8:+ stable_case = (+ "all_match(regexp_extract_all(concat(__hogql_substrings[1], __hogql_substrings[2]), '(?s).'), "+ "__hogql_character -> length(to_utf8(__hogql_character)) = "+ "length(to_utf8(lower(__hogql_character))))"+ )+ result = (+ f"IF({stable_case}, {result}, "+ "fail('UTF-8 case conversion with a different byte length is not supported'))"+ )+ return f"element_at(transform(ARRAY[ROW({', '.join(args)})], __hogql_substrings -> {result}), 1)"++ return handler+++def _locate(args: list[str]) -> str:+ if len(args) not in {2, 3}:+ raise _invalid_arguments("locate", "locate expects a substring, string, and optional start position.")+ needle = "to_hex(to_utf8(__hogql_locate[1]))"+ value = "to_hex(to_utf8(__hogql_locate[2]))"+ start = "greatest(CAST(__hogql_locate[3] AS BIGINT), 1)" if len(args) == 3 else "BIGINT '1'"+ offset_value = f"substr({value}, 2 * {start} - 1)"+ position = f"strpos({offset_value}, {needle})"+ result = (+ f"IF({start} > length({value}) / 2 + 1 OR {position} = 0, 0, {start} + CAST(({position} - 1) / 2 AS BIGINT))"+ )+ return f"element_at(transform(ARRAY[ROW({', '.join(args)})], __hogql_locate -> {result}), 1)"+++def _has_subsequence(name: str, case_insensitive: bool, utf8: bool) -> Callable[[list[str]], str]:+ def handler(args: list[str]) -> str:+ _require_args(name, args, 2)+ haystack = "__hogql_subsequence[1]"+ needle = "__hogql_subsequence[2]"+ if case_insensitive:+ if utf8:+ haystack, needle = f"lower({haystack})", f"lower({needle})"+ else:+ alphabet = "'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'"+ haystack, needle = f"translate({haystack}, {alphabet})", f"translate({needle}, {alphabet})"++ def characters(value: str) -> str:+ if utf8:+ return f"regexp_extract_all({value}, '(?s).')"+ encoded = f"to_hex(to_utf8({value}))"+ count = f"length({encoded}) / 2"+ indexes = f"filter(sequence(1, greatest({count}, 1)), __hogql_index -> __hogql_index <= {count})"+ return f"transform({indexes}, __hogql_index -> substr({encoded}, 2 * __hogql_index - 1, 2))"++ haystack_characters = characters(haystack)+ needle_characters = characters(needle)+ relative_position = (+ "array_position(slice(__hogql_haystack, __hogql_position + 1, "+ "cardinality(__hogql_haystack)), __hogql_character)"+ )+ next_position = (+ f"element_at(transform(ARRAY[{relative_position}], __hogql_relative -> "+ "IF(__hogql_relative = 0, BIGINT '-1', __hogql_position + __hogql_relative)), 1)"+ )+ result = (+ f"reduce({needle_characters}, BIGINT '0', "+ "(__hogql_position, __hogql_character) -> "+ f"IF(__hogql_position < 0, BIGINT '-1', {next_position}), "+ "__hogql_position -> __hogql_position >= 0)"+ )+ result = f"element_at(transform(ARRAY[{haystack_characters}], __hogql_haystack -> {result}), 1)"+ if case_insensitive and utf8:+ stable_case = (+ "all_match(regexp_extract_all(concat(__hogql_subsequence[1], __hogql_subsequence[2]), '(?s).'), "+ "__hogql_character -> length(to_utf8(__hogql_character)) = "+ "length(to_utf8(lower(__hogql_character))))"+ )+ result = (+ f"IF({stable_case}, {result}, "+ "fail('UTF-8 case conversion with a different byte length is not supported'))"+ )+ return f"element_at(transform(ARRAY[ROW({args[0]}, {args[1]})], __hogql_subsequence -> {result}), 1)"++ return handler+++def _extract_tokens(name: str, alpha_only: bool) -> Callable[[list[str]], str]:+ def handler(args: list[str]) -> str:+ if len(args) not in ({1, 2} if name != "tokens" else {1}):+ raise _invalid_arguments(name, f"{name} expects a string and optional maximum token count.")+ pattern = "'[A-Za-z]+'" if alpha_only else "'[\\p{L}\\p{N}]+'"+ tokens = f"regexp_extract_all({args[0]}, {pattern})"+ if len(args) == 2:+ tokens = f"IF({args[1]} = 0, {tokens}, slice({tokens}, 1, {args[1]}))"+ return tokens++ return handler+++def _logical_xor(args: list[str]) -> str:+ if len(args) < 2:+ raise _invalid_arguments("xor", "xor expects at least two arguments.")+ values = ", ".join(f"CAST({arg} AS BOOLEAN)" for arg in args)+ return (+ f"reduce(ARRAY[{values}], false, (__hogql_xor, __hogql_value) -> "+ "IF(__hogql_value IS NULL, NULL, __hogql_xor <> __hogql_value), "+ "__hogql_xor -> __hogql_xor)"+ )+++def _throw_if(args: list[str]) -> str:+ _require_args("throwIf", args, 2)+ return f"IF({args[0]} IS NULL, NULL, IF(CAST({args[0]} AS BOOLEAN), fail({args[1]}), 0))"+++def _is_valid_utf8(args: list[str]) -> str:+ _require_args("isValidUTF8", args, 1)+ return f"IF({args[0]} IS NULL, NULL, true)"+++def _regexp_quote_meta(args: list[str]) -> str:+ _require_args("regexpQuoteMeta", args, 1)+ return f"regexp_replace({args[0]}, '([\\\\|()^$.\\-\\[\\]?*+{{:\\x00])', '\\\\$1')"+++def _initcap(args: list[str]) -> str:+ _require_args("initcap", args, 1)+ characters = f"regexp_extract_all({args[0]}, '(?s).')"+ state_type = "ROW(at_word_start BOOLEAN, value VARCHAR)"+ character = "__hogql_character"+ alphanumeric = f"regexp_like({character}, '[A-Za-z0-9]')"+ converted = f"IF(__hogql_state[1], upper({character}), lower({character}))"+ return (+ f"reduce({characters}, CAST(ROW(true, '') AS {state_type}), "+ f"(__hogql_state, {character}) -> IF({alphanumeric}, "+ f"CAST(ROW(false, concat(__hogql_state[2], {converted})) AS {state_type}), "+ f"CAST(ROW(true, concat(__hogql_state[2], {character})) AS {state_type})), "+ "__hogql_state -> __hogql_state[2])"+ )+++@frozen+class _IPv4StringParts:+ valid: str+ number: str+++def _ipv4_string_parts(value: str) -> _IPv4StringParts:+ strict = r"'^[0-9]{1,3}(?:\.[0-9]{1,3}){3}$'"+ octets = f"transform(split({value}, '.'), __hogql_octet -> TRY_CAST(__hogql_octet AS BIGINT))"+ valid = f"regexp_like({value}, {strict}) AND all_match({octets}, __hogql_octet -> __hogql_octet <= 255)"+ number = f"reduce({octets}, BIGINT '0', (__hogql_total, __hogql_octet) -> __hogql_total * 256 + __hogql_octet, __hogql_total -> __hogql_total)"+ return _IPv4StringParts(valid=valid, number=number)+++def _is_ipv4_string(args: list[str]) -> str:+ _require_args("isIPv4String", args, 1)+ value = "__hogql_ip"+ parts = _ipv4_string_parts(value)+ return f"element_at(transform(ARRAY[{args[0]}], {value} -> IF({value} IS NULL, NULL, {parts.valid})), 1)"+++def _is_ipv6_string(args: list[str]) -> str:+ _require_args("isIPv6String", args, 1)+ value = "__hogql_ip"+ valid = f"strpos({value}, ':') > 0 AND strpos({value}, '%') = 0 AND TRY_CAST({value} AS IPADDRESS) IS NOT NULL"+ return f"element_at(transform(ARRAY[{args[0]}], {value} -> IF({value} IS NULL, NULL, {valid})), 1)"+++def _is_ip_address_in_range(args: list[str]) -> str:+ _require_args("isIPAddressInRange", args, 2)+ same_family = f"(strpos({args[0]}, ':') > 0) = (strpos({args[1]}, ':') > 0)"+ contains = f"contains({args[1]}, CAST({args[0]} AS IPADDRESS))"+ return f"IF({args[0]} IS NULL OR {args[1]} IS NULL, NULL, IF({contains}, {same_family}, false))"+++def _ipv4_string_to_num(name: str, fallback: str) -> Callable[[list[str]], str]:+ def handler(args: list[str]) -> str:+ _require_args(name, args, 1)+ value = "__hogql_ip"+ parts = _ipv4_string_parts(value)+ result = parts.number if not fallback else f"IF({parts.valid}, {parts.number}, {fallback})"+ if not fallback:+ result = f"IF({parts.valid}, {parts.number}, fail('Invalid IPv4 address'))"+ return f"element_at(transform(ARRAY[{args[0]}], {value} -> IF({value} IS NULL, NULL, {result})), 1)"++ return handler+++def _ipv4_number_to_string(value: str) -> str:+ octets = (+ f"transform(ARRAY[24, 16, 8, 0], __hogql_shift -> "+ f"CAST(bitwise_and(bitwise_right_shift_arithmetic({value}, __hogql_shift), 255) AS VARCHAR))"+ )+ return f"array_join({octets}, '.')"+++def _ipv4_num_to_string(args: list[str]) -> str:+ _require_args("IPv4NumToString", args, 1)+ value = "__hogql_ip"+ result = _ipv4_number_to_string(value)+ result = f"IF({value} BETWEEN 0 AND 4294967295, {result}, fail('IPv4 number is out of range'))"+ return f"element_at(transform(ARRAY[CAST({args[0]} AS BIGINT)], {value} -> IF({value} IS NULL, NULL, {result})), 1)"+++def _to_ipv4(name: str, fallback: str | None) -> Callable[[list[str]], str]:+ def handler(args: list[str]) -> str:+ if len(args) not in ({1, 2} if name == "toIPv4OrDefault" else {1}):+ raise _invalid_arguments(name, f"{name} received an invalid number of arguments.")+ value = "__hogql_ipv4"+ parts = _ipv4_string_parts(value)+ if name == "toIPv4OrDefault":+ default = f"CAST({args[1]} AS IPADDRESS)" if len(args) == 2 else "CAST('0.0.0.0' AS IPADDRESS)"+ elif fallback is None:+ default = "fail('Invalid IPv4 address')"+ elif fallback == "NULL":+ default = "CAST(NULL AS IPADDRESS)"+ else:+ default = "CAST('0.0.0.0' AS IPADDRESS)"+ result = f"IF({parts.valid}, CAST({_ipv4_number_to_string(parts.number)} AS IPADDRESS), {default})"+ return f"element_at(transform(ARRAY[CAST({args[0]} AS VARCHAR)], {value} -> IF({value} IS NULL, NULL, {result})), 1)"++ return handler+++def _ipv4_cidr_to_range(args: list[str]) -> str:+ _require_args("IPv4CIDRToRange", args, 2)+ value = "__hogql_ipv4_cidr[1]"+ prefix = "__hogql_ipv4_cidr[2]"+ parts = _ipv4_string_parts(value)+ host_mask = f"bitwise_left_shift(BIGINT '1', CAST(32 - {prefix} AS INTEGER)) - 1"+ lower = f"({parts.number} - bitwise_and({parts.number}, {host_mask}))"+ upper = f"({lower} + {host_mask})"+ result = (+ f"ROW(CAST({_ipv4_number_to_string(lower)} AS IPADDRESS), CAST({_ipv4_number_to_string(upper)} AS IPADDRESS))"+ )+ checked = (+ f"IF(NOT ({parts.valid}), fail('Invalid IPv4 address'), "+ f"IF({prefix} BETWEEN 0 AND 32, {result}, fail('IPv4 CIDR prefix must be between 0 and 32')))"+ )+ return (+ f"element_at(transform(ARRAY[ROW(CAST({args[0]} AS VARCHAR), CAST({args[1]} AS BIGINT))], "+ f"__hogql_ipv4_cidr -> IF({value} IS NULL OR {prefix} IS NULL, "+ f"CAST(NULL AS ROW(IPADDRESS, IPADDRESS)), {checked})), 1)"+ )+++def _query_string_and_fragment(args: list[str]) -> str:+ _require_args("queryStringAndFragment", args, 1)+ query = _raw_url_query("__hogql_url")+ fragment = _raw_url_fragment("__hogql_url")+ result = f"IF({fragment} = '', {query}, concat({query}, '#', {fragment}))"+ return f"element_at(transform(ARRAY[{args[0]}], __hogql_url -> {result}), 1)"+++def _netloc(args: list[str]) -> str:+ _require_args("netloc", args, 1)+ return f"regexp_extract({args[0]}, '^(?:(?:[A-Za-z][A-Za-z0-9+.-]*:)?//)?([^/?#]*)', 1)"+++def _url_hierarchy(name: str, path_only: bool) -> Callable[[list[str]], str]:+ def handler(args: list[str]) -> str:+ _require_args(name, args, 1)+ value = "__hogql_hierarchy_url"+ absolute = f"regexp_like({value}, '^[A-Za-z][A-Za-z0-9+.-]*://')"+ authority = f"regexp_extract({value}, '^[A-Za-z][A-Za-z0-9+.-]*://[^/?#]*')"+ authority_length = "length(__hogql_authority)"+ question = f"strpos({value}, '?')"+ fragment = f"strpos({value}, '#')"+ path_end = (+ f"least(IF({question} = 0, length({value}) + 1, {question}), "+ f"IF({fragment} = 0, length({value}) + 1, {fragment}))"+ )+ after_authority = f"__hogql_position > {authority_length}"+ if path_only:+ after_authority = f"__hogql_position > {authority_length} + 1"+ slash_boundary = (+ f"({after_authority} AND substr({value}, __hogql_position, 1) = '/' AND __hogql_position < {path_end})"+ )+ marker_boundary = f"({after_authority} AND __hogql_position IN ({question}, {fragment}))"+ terminal_boundary = (+ f"({after_authority} AND __hogql_position = length({value}))"+ if path_only+ else f"__hogql_position = length({value})"+ )+ boundary = f"{slash_boundary} OR {marker_boundary} OR {terminal_boundary}"+ positions = (+ f"filter(sequence(1, greatest(length({value}), 1)), "+ f"__hogql_position -> __hogql_position <= length({value}) AND ({boundary}))"+ )+ prefix = (+ f"substr({value}, {authority_length} + 1, __hogql_position - {authority_length})"+ if path_only+ else f"substr({value}, 1, __hogql_position)"+ )+ hierarchy = f"transform({positions}, __hogql_position -> {prefix})"+ if path_only:+ hierarchy = f"IF({absolute}, {hierarchy}, ARRAY[])"+ else:+ hierarchy = f"IF({absolute}, {hierarchy}, IF({value} = '', ARRAY[], ARRAY[{value}]))"+ return (+ f"element_at(transform(ARRAY[{args[0]}], {value} -> IF({value} IS NULL, NULL, "+ f"element_at(transform(ARRAY[{authority}], __hogql_authority -> {hierarchy}), 1))), 1)"+ )++ return handler+++def _cut_url_parameter(args: list[str]) -> str:+ _require_args("cutURLParameter", args, 2)+ url = "__hogql_cut_url_args[1]"+ name = "__hogql_cut_url_args[2]"+ hash_position = f"strpos({url}, '#')"+ before = f"IF({hash_position} = 0, {url}, substr({url}, 1, {hash_position} - 1))"+ fragment = f"IF({hash_position} = 0, '', substr({url}, {hash_position}))"+ query_position = "strpos(__hogql_cut_url[1], '?')"+ parameters = f"split(substr(__hogql_cut_url[1], {query_position} + 1), '&')"+ matches = (+ f"transform(__hogql_parameters, __hogql_parameter -> "+ f"strpos(__hogql_parameter, '=') > 0 AND split_part(__hogql_parameter, '=', 1) = {name})"+ )+ match_position = f"array_position({matches}, true)"+ remaining = (+ "transform(filter(sequence(1, cardinality(__hogql_parameters)), "+ "__hogql_position -> __hogql_position <> __hogql_match_position), "+ "__hogql_position -> element_at(__hogql_parameters, __hogql_position))"+ )+ result = (+ f"IF({query_position} = 0 OR __hogql_match_position = 0, {url}, "+ f"concat(substr(__hogql_cut_url[1], 1, {query_position}), array_join({remaining}, '&'), "+ "__hogql_cut_url[2]))"+ )+ return (+ f"element_at(transform(ARRAY[ROW({args[0]}, {args[1]})], __hogql_cut_url_args -> "+ f"IF({url} IS NULL OR {name} IS NULL, NULL, "+ f"element_at(transform(ARRAY[ROW({before}, {fragment})], __hogql_cut_url -> "+ f"element_at(transform(ARRAY[{parameters}], __hogql_parameters -> "+ f"element_at(transform(ARRAY[{match_position}], __hogql_match_position -> {result}), 1)), 1)), 1))), 1)"+ )+++def _encode_xml_component(args: list[str]) -> str:+ _require_args("encodeXMLComponent", args, 1)+ result = args[0]+ for source, target in (+ ("'&'", "'&'"),+ ("'<'", "'<'"),+ ("'>'", "'>'"),+ ("'\"'", "'"'"),+ ("''''", "'''"),+ ):+ result = f"replace({result}, {source}, {target})"+ return result+++def _decode_xml_component(args: list[str]) -> str:+ _require_args("decodeXMLComponent", args, 1)+ groups = "__hogql_xml_entity"+ codepoint = f"IF({groups}[1] IS NOT NULL, from_base({groups}[1], 16), CAST({groups}[2] AS BIGINT))"+ result = f"regexp_replace({args[0]}, '&#(?:[xX]([0-9A-Fa-f]+)|([0-9]+));', {groups} -> chr({codepoint}))"+ for source, target in (+ ("'<'", "'<'"),+ ("'>'", "'>'"),+ ("'"'", "'\"'"),+ ("'''", "''''"),+ ("'&'", "'&'"),+ ):+ result = f"replace({result}, {source}, {target})"+ return result+++def _uuid_v7_to_datetime(args: list[str]) -> str:+ _require_args("UUIDv7ToDateTime", args, 1)+ milliseconds = f"from_base(substr(replace(CAST({args[0]} AS VARCHAR), '-', ''), 1, 12), 16)"+ return f"CAST(from_unixtime(({milliseconds}) / 1000e0) AS TIMESTAMP)"+++def _make_timestamp(name: str, with_timezone_result: bool) -> Callable[[list[str]], str]:+ def handler(args: list[str]) -> str:+ expected = 7 if with_timezone_result else 6+ _require_args(name, args, expected)+ parts = ", ".join(f"CAST({argument} AS BIGINT)" for argument in args[:5])+ seconds = f"CAST(truncate({args[5]}) AS BIGINT)"+ value = f"TRY_CAST(format('%04d-%02d-%02d %02d:%02d:%02d', {parts}, {seconds}) AS TIMESTAMP)"+ timestamp = (+ f"IF({value} BETWEEN TIMESTAMP '1970-01-01 00:00:00' AND TIMESTAMP '2106-02-07 06:28:15', "+ f"{value}, TIMESTAMP '1970-01-01 00:00:00')"+ )+ return f"with_timezone({timestamp}, {args[6]})" if with_timezone_result else timestamp++ return handler+++def _sortable_semver(args: list[str]) -> str:+ _require_args("sortablesemver", args, 1)+ pattern = r"'^\s*v?((?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*))(?:[-+][^\s]*)?\s*$'"+ matched = f"regexp_extract(coalesce({args[0]}, ''), {pattern}, 1)"+ return (+ f"element_at(transform(ARRAY[{matched}], __hogql_semver -> "+ "IF(__hogql_semver IS NULL, ARRAY[CAST(NULL AS BIGINT)], "+ "transform(split(__hogql_semver, '.'), __hogql_semver_part -> CAST(__hogql_semver_part AS BIGINT)))), 1)"+ )+++def _point_in_ellipses(args: list[str]) -> str:+ if len(args) < 6 or (len(args) - 2) % 4 != 0:+ raise _invalid_arguments(+ "pointInEllipses", "pointInEllipses expects a point and one or more four-value ellipses."+ )+ tests = []+ for index in range(2, len(args), 4):+ center_x = index + 1+ center_y = index + 2+ radius_x = index + 3+ radius_y = index + 4+ tests.append(+ f"power((__hogql_ellipse[1] - __hogql_ellipse[{center_x}]) / __hogql_ellipse[{radius_x}], 2) + "+ f"power((__hogql_ellipse[2] - __hogql_ellipse[{center_y}]) / __hogql_ellipse[{radius_y}], 2) <= 1e0"+ )+ values = ", ".join(f"CAST({argument} AS DOUBLE)" for argument in args)+ nulls = " OR ".join(f"__hogql_ellipse[{index}] IS NULL" for index in range(1, len(args) + 1))+ return (+ f"element_at(transform(ARRAY[ROW({values})], __hogql_ellipse -> IF({nulls}, NULL, ({' OR '.join(tests)}))), 1)"+ )+++def _if_not_finite(args: list[str]) -> str:+ _require_args("ifNotFinite", args, 2)+ return f"IF(is_finite(CAST({args[0]} AS DOUBLE)), {args[0]}, {args[1]})"+++def _bar(args: list[str]) -> str:+ _require_args("bar", args, 4)+ value = "__hogql_bar[1]"+ minimum = "__hogql_bar[2]"+ maximum = "__hogql_bar[3]"+ width = "__hogql_bar[4]"+ ratio = f"greatest(0e0, least({width}, ({value} - {minimum}) / ({maximum} - {minimum}) * {width}))"+ eighths = f"CAST(floor({ratio} * 8) AS BIGINT)"+ full_blocks = f"{eighths} / 8"+ partial = f"CAST(mod({eighths}, 8) AS INTEGER)"+ result = (+ f"array_join(repeat('█', CAST({full_blocks} AS INTEGER)), '') || "+ f"IF({partial} = 0, '', substr('▏▎▍▌▋▊▉', {partial}, 1))"+ )+ return (+ f"element_at(transform(ARRAY[ROW(CAST({args[0]} AS DOUBLE), CAST({args[1]} AS DOUBLE), "+ f"CAST({args[2]} AS DOUBLE), CAST({args[3]} AS DOUBLE))], __hogql_bar -> "+ f"IF({value} IS NULL OR {minimum} IS NULL OR {maximum} IS NULL OR {width} IS NULL, NULL, {result})), 1)"+ )+++def _ngrams(args: list[str]) -> str:+ _require_args("ngrams", args, 2)+ value = "__hogql_ngram_args[1]"+ size = "CAST(__hogql_ngram_args[2] AS BIGINT)"+ positions = (+ f"filter(sequence(1, greatest(length({value}) - {size} + 1, 1)), "+ f"__hogql_position -> __hogql_position <= length({value}) - {size} + 1)"+ )+ result = f"transform({positions}, __hogql_position -> substr({value}, __hogql_position, {size}))"+ return (+ f"element_at(transform(ARRAY[ROW({args[0]}, {args[1]})], __hogql_ngram_args -> "+ f"IF({value} IS NULL OR {size} IS NULL, NULL, IF({size} < 1, fail('ngrams requires a positive size'), "+ f"{result}))), 1)"+ )+++def _has_tokens(name: str, require_all: bool) -> Callable[[list[str]], str]:+ def handler(args: list[str]) -> str:+ _require_args(name, args, 2)+ haystack = "__hogql_token_array_args[1]"+ tokens = "__hogql_token_array_args[2]"+ token = "__hogql_token"+ escaped = f"regexp_replace({token}, '([\\\\|()^$.\\-\\[\\]?*+{{:\\x00])', '\\\\$1')"+ token_character = r"A-Za-z0-9\P{ASCII}"+ valid = f"{token} <> '' AND regexp_like({token}, '^[{token_character}]+$')"+ pattern = f"concat('(?:^|[^{token_character}])', {escaped}, '(?:$|[^{token_character}])')"+ match = f"{valid} AND regexp_like({haystack}, {pattern})"+ operation = "all_match" if require_all else "any_match"+ result = f"cardinality({tokens}) > 0 AND {operation}({tokens}, {token} -> {match})"+ return (+ f"element_at(transform(ARRAY[ROW({args[0]}, {args[1]})], __hogql_token_array_args -> "+ f"IF({haystack} IS NULL OR {tokens} IS NULL, NULL, {result})), 1)"+ )++ return handler+++def _extract_ipv4_substrings(args: list[str]) -> str:+ _require_args("extractIPv4Substrings", args, 1)+ octet = r"(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]?|0)"+ first_octet = rf"(?:(?<![0-9]){octet}|(?<=[0-9])[0-9])"+ return f"regexp_extract_all({args[0]}, '{first_octet}(?:\\.{octet}){{3}}')"+++def _path_full(args: list[str]) -> str:+ _require_args("pathFull", args, 1)+ without_suffix = "regexp_replace(__hogql_url, '[?#].*$', '')"+ path = f"regexp_replace({without_suffix}, '^(?:[A-Za-z][A-Za-z0-9+.-]*:)?//[^/]*', '')"+ query = _raw_url_query("__hogql_url")+ fragment = _raw_url_fragment("__hogql_url")+ has_query = "strpos(split_part(__hogql_url, '#', 1), '?') > 0"+ result = (+ f"concat({path}, IF({has_query}, concat('?', {query}), ''), IF({fragment} = '', '', concat('#', {fragment})))"+ )+ return f"element_at(transform(ARRAY[{args[0]}], __hogql_url -> IF(strpos(__hogql_url, '/') = 0, '', {result})), 1)"+++def _extract_url_parameters(name: str, names_only: bool) -> Callable[[list[str]], str]:+ def handler(args: list[str]) -> str:+ _require_args(name, args, 1)+ query = _raw_url_query("__hogql_url")+ parameters = f"IF({query} = '', ARRAY[], split({query}, '&'))"+ if names_only:+ parameters = f"transform({parameters}, __hogql_parameter -> split_part(__hogql_parameter, '=', 1))"+ result = f"IF(__hogql_url IS NULL, NULL, {parameters})"+ return f"element_at(transform(ARRAY[{args[0]}], __hogql_url -> {result}), 1)"++ return handler+++def _raw_url_query(value: str) -> str:+ return f"coalesce(regexp_extract(split_part({value}, '#', 1), '\\?(.*)$', 1), '')"+++def _raw_url_fragment(value: str) -> str:+ return f"coalesce(regexp_extract({value}, '#(.*)$', 1), '')"+++def _url_query_part(name: str, fragment: bool) -> Callable[[list[str]], str]:+ def handler(args: list[str]) -> str:+ _require_args(name, args, 1)+ value = "__hogql_url"+ result = _raw_url_fragment(value) if fragment else _raw_url_query(value)+ return f"element_at(transform(ARRAY[{args[0]}], {value} -> IF({value} IS NULL, NULL, {result})), 1)"++ return handler+++def _split_by_regexp(args: list[str]) -> str:+ if len(args) not in {2, 3}:+ raise _invalid_arguments("splitByRegexp", "splitByRegexp expects a pattern, string, and optional limit.")+ split = (+ f"IF({args[0]} = '', IF({args[1]} = '', ARRAY[], transform(sequence(1, length({args[1]})), "+ f"__hogql_index -> substr({args[1]}, __hogql_index, 1))), regexp_split({args[1]}, {args[0]}))"+ )+ return split if len(args) == 2 else f"slice({split}, 1, {args[2]})"+++def _append_trailing_character(args: list[str]) -> str:+ _require_args("appendTrailingCharIfAbsent", args, 2)+ return (+ f"IF(length({args[1]}) <> 1, fail('appendTrailingCharIfAbsent expects one character'), "+ f"IF({args[0]} = '' OR {_ends_with(args)}, {args[0]}, concat({args[0]}, {args[1]})))"+ )+++def _path(args: list[str]) -> str:+ _require_args("path", args, 1)+ return f"IF(strpos({args[0]}, '/') = 0, '', coalesce(url_extract_path({args[0]}), ''))"+++def _map_key_like(name: str, extract: bool) -> Callable[[list[str]], str]:+ def handler(args: list[str]) -> str:+ _require_args(name, args, 2)+ filtered = f"map_filter({args[0]}, (__hogql_key, __hogql_value) -> __hogql_key LIKE {args[1]})"+ return filtered if extract else f"cardinality({filtered}) > 0"++ return handler+++def _bit_test(name: str, mode: str) -> Callable[[list[str]], str]:+ def handler(args: list[str]) -> str:+ if len(args) < 2:+ raise _invalid_arguments(name, f"{name} expects a value and bit positions.")+ tests = [f"bitwise_and({args[0]}, bitwise_left_shift(BIGINT '1', {position})) <> 0" for position in args[1:]]+ operator = " AND " if mode == "all" else " OR "+ return f"({operator.join(tests)})"++ return handler+++def _bit_count(args: list[str]) -> str:+ _require_args("bitCount", args, 1)+ return f"bit_count({args[0]}, 64)"+++def _bit_shift(name: str, target: str) -> Callable[[list[str]], str]:+ def handler(args: list[str]) -> str:+ _require_args(name, args, 2)+ return f"{target}({args[0]}, {args[1]})"++ return handler+++def _domain_without_www(args: list[str]) -> str:+ _require_args("domainWithoutWWW", args, 1)+ return f"regexp_replace(coalesce(url_extract_host({args[0]}), ''), '^www\\.', '')"+++def _url_string(name: str, target: str) -> Callable[[list[str]], str]:+ def handler(args: list[str]) -> str:+ _require_args(name, args, 1)+ return f"coalesce({target}({args[0]}), '')"++ return handler+++def _port(args: list[str]) -> str:+ if len(args) not in {1, 2}:+ raise _invalid_arguments("port", "port expects a URL and an optional default port.")+ default = args[1] if len(args) == 2 else "0"+ return f"coalesce(url_extract_port({args[0]}), {default})"+++def _bit_hamming_distance(args: list[str]) -> str:+ _require_args("bitHammingDistance", args, 2)+ return f"bit_count(bitwise_xor({args[0]}, {args[1]}), 64)"+++def _cut_www(args: list[str]) -> str:+ _require_args("cutWWW", args, 1)+ return f"regexp_replace({args[0]}, '^(https?://)?www\\.', '$1')"+++def _top_level_domain(args: list[str]) -> str:+ _require_args("topLevelDomain", args, 1)+ host = f"coalesce(url_extract_host({args[0]}), '')"+ return f"coalesce(element_at(split({host}, '.'), -1), '')"+++def _l1_distance(args: list[str]) -> str:+ _require_args("L1Distance", args, 2)+ return f"reduce(zip_with({args[0]}, {args[1]}, (x, y) -> abs(x - y)), DOUBLE '0', (s, x) -> s + x, s -> s)"+++def _linf_distance(args: list[str]) -> str:+ _require_args("LinfDistance", args, 2)+ return (+ f"IF(cardinality({args[0]}) = 0, DOUBLE '0', array_max(zip_with({args[0]}, {args[1]}, (x, y) -> abs(x - y))))"+ )+++def _vector_norm(name: str, kind: str) -> Callable[[list[str]], str]:+ def handler(args: list[str]) -> str:+ _require_args(name, args, 1)+ if kind == "l1":+ return f"reduce(transform({args[0]}, x -> abs(x)), DOUBLE '0', (s, x) -> s + x, s -> s)"+ if kind == "l2":+ return f"sqrt(dot_product({args[0]}, {args[0]}))"+ return f"IF(cardinality({args[0]}) = 0, DOUBLE '0', array_max(transform({args[0]}, x -> abs(x))))"++ return handler+++def _multi_search(name: str) -> Callable[[list[str]], str]:+ def handler(args: list[str]) -> str:+ _require_args(name, args, 2)+ haystack = "__hogql_search[1]"+ needle = "__hogql_needle"+ if "CaseInsensitive" in name:+ if "UTF8" in name:+ haystack, needle = f"lower({haystack})", f"lower({needle})"+ else:+ alphabet = "'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'"+ haystack, needle = f"translate({haystack}, {alphabet})", f"translate({needle}, {alphabet})"+ position = f"strpos({haystack}, {needle})"+ if "UTF8" not in name:+ position = f"IF({position} = 0, 0, length(to_utf8(substr({haystack}, 1, {position} - 1))) + 1)"+ positions = f"transform(__hogql_search[2], __hogql_needle -> IF(__hogql_search[1] = '', 0, {position}))"+ if "AllPositions" in name:+ result = positions+ elif "FirstPosition" in name:+ result = f"coalesce(array_min(filter({positions}, __hogql_position -> __hogql_position > 0)), 0)"+ elif "FirstIndex" in name:+ result = f"array_position(transform({positions}, __hogql_position -> __hogql_position > 0), TRUE)"+ else:+ result = f"CAST(any_match({positions}, __hogql_position -> __hogql_position > 0) AS BIGINT)"+ if "CaseInsensitiveUTF8" in name:+ stable_case = (+ "all_match(regexp_extract_all(concat(__hogql_search[1], array_join(__hogql_search[2], '')), '(?s).'), "+ "__hogql_character -> length(to_utf8(__hogql_character)) = length(to_utf8(lower(__hogql_character))))"+ )+ result = f"IF({stable_case}, {result}, fail('UTF-8 case conversion with a different byte length is not supported'))"+ return f"element_at(transform(ARRAY[ROW({args[0]}, {args[1]})], __hogql_search -> {result}), 1)"++ return handler+++def _round_down(args: list[str]) -> str:+ _require_args("roundDown", args, 2)+ return (+ f"element_at(transform(ARRAY[ROW({args[0]}, {args[1]})], __hogql_round -> "+ "IF(__hogql_round[1] IS NULL, NULL, IF(cardinality(__hogql_round[2]) = 0, fail('roundDown requires a non-empty boundary array'), "+ "IF(is_nan(CAST(__hogql_round[1] AS DOUBLE)), __hogql_round[1], "+ "coalesce(array_max(filter(__hogql_round[2], __hogql_boundary -> __hogql_boundary <= __hogql_round[1])), "+ "array_min(__hogql_round[2])))))), 1)"+ )+++def _round_age(args: list[str]) -> str:+ _require_args("roundAge", args, 1)+ cases = " ".join(+ f"WHEN __hogql_age < {threshold} THEN {result}"+ for threshold, result in [(1, 0), (18, 17), (25, 18), (35, 25), (45, 35), (55, 45)]+ )+ return f"element_at(transform(ARRAY[{args[0]}], __hogql_age -> IF(__hogql_age IS NULL, NULL, CASE {cases} ELSE 55 END)), 1)"+++def _round_duration(args: list[str]) -> str:+ _require_args("roundDuration", args, 1)+ buckets = [0, 1, 10, 30, 60, 120, 180, 240, 300, 600, 1200, 1800, 3600, 7200, 18000, 36000]+ cases = " ".join(+ f"WHEN __hogql_duration < {threshold} THEN {result}" for result, threshold in zip(buckets, buckets[1:])+ )+ return f"element_at(transform(ARRAY[{args[0]}], __hogql_duration -> IF(__hogql_duration IS NULL, NULL, CASE {cases} ELSE 36000 END)), 1)"+++def _factorial(args: list[str]) -> str:+ _require_args("factorial", args, 1)+ values = ", ".join(str(factorial(value)) for value in range(21))+ return (+ f"element_at(transform(ARRAY[{args[0]}], __hogql_factorial -> "+ f"IF(__hogql_factorial > 20, fail('factorial requires an integer no greater than 20'), "+ f"element_at(ARRAY[{values}], CAST(greatest(__hogql_factorial, 0) + 1 AS BIGINT)))), 1)"+ )+++def _modified_julian_day(name: str, reverse: bool) -> Callable[[list[str]], str]:+ def handler(args: list[str]) -> str:+ _require_args(name, args, 1)+ if reverse:+ return f"date_add('day', CAST({args[0]} AS BIGINT), DATE '1858-11-17')"+ return f"date_diff('day', DATE '1858-11-17', CAST({args[0]} AS DATE))"++ return handler++TRINO_FUNCTION_HANDLERS: dict[str, Callable[[list[str]], str]] = {+ "DATE": _cast("DATE", "DATE"),"toDate": _cast("toDate", "DATE"),"_toDate": _cast("_toDate", "DATE"),"toDateTime": _cast("toDateTime", "TIMESTAMP"),"toString": _cast("toString", "VARCHAR"),"toInt": _cast("toInt", "BIGINT"),+ "_toUInt64": _cast("_toUInt64", "BIGINT"),"toIntOrZero": _cast_or_default("toIntOrZero", "BIGINT", "0"),"toIntOrDefault": _cast_or_default("toIntOrDefault", "BIGINT", "0"),"toFloat": _cast("toFloat", "DOUBLE"),"toFloatOrZero": _cast_or_default("toFloatOrZero", "DOUBLE", "0e0"),"toFloatOrDefault": _cast_or_default("toFloatOrDefault", "DOUBLE", "0e0"),+ "toFloatOrNull": _float_or_null,+ "toFloat64OrNull": _float_or_null,"toBool": _cast("toBool", "BOOLEAN"),"toUUID": _cast("toUUID", "UUID"),"toYear": _extract("toYear", "YEAR"),@@ -273,8 +1759,15 @@ TRINO_FUNCTION_HANDLERS: dict[str, Callable[[list[str]], str]] = {"toYYYYMMDD": _formatted_date_number("toYYYYMMDD", "%Y%m%d", "INTEGER"),"toYYYYMMDDhhmmss": _formatted_date_number("toYYYYMMDDhhmmss", "%Y%m%d%H%i%s", "BIGINT"),"toUnixTimestamp": _to_unix_timestamp,+ "fromUnixTimestamp64Milli": _from_unix_timestamp64_milli,+ "timeSlot": _time_slot,+ "timeSlots": _time_slots,+ "toTime": _to_time,+ "timeStampAdd": _date_arithmetic("timeStampAdd", "+"),+ "timeStampSub": _date_arithmetic("timeStampSub", "-"),"if": _if,"multiIf": _multi_if,+ "_caseWithExpression": _case_with_expression,"countIf": _count_if,"sumIf": _aggregate_if("sum"),"minIf": _aggregate_if("min"),@@ -285,6 +1778,7 @@ TRINO_FUNCTION_HANDLERS: dict[str, Callable[[list[str]], str]] = {"uniqExact": _uniq,"uniqIf": _uniq_if,"uniqExactIf": _uniq_if,+ "countDistinctIf": _uniq_if,"dateDiff": _date_diff,"date_diff": _date_diff,"addSeconds": _date_add("second"),@@ -322,6 +1816,7 @@ TRINO_FUNCTION_HANDLERS: dict[str, Callable[[list[str]], str]] = {"minus": _binary("minus", "-"),"multiply": _binary("multiply", "*"),"divide": _divide,+ "divideDecimal": _divide_decimal,"modulo": _binary("modulo", "%"),"and": _logical("and", "AND"),"or": _logical("or", "OR"),@@ -331,14 +1826,256 @@ TRINO_FUNCTION_HANDLERS: dict[str, Callable[[list[str]], str]] = {"assumeNotNull": _identity("assumeNotNull"),"toNullable": _identity("toNullable"),"formatDateTime": _format_date_time,+ "to_char": _format_date_time,"position": _position,+ "positionCaseInsensitive": _position_case_insensitive,+ "right": _right,+ "replaceOne": _replace_one,+ "arraySlice": _array_slice,+ "arrayIntersect": _array_intersect,+ "cutFragment": _cut_fragment,+ "cutQueryString": _cut_query_string,+ "cutQueryStringAndFragment": _cut_query_string_and_fragment,+ "_toInt8": _cast("_toInt8", "TINYINT"),+ "_toInt16": _cast("_toInt16", "SMALLINT"),+ "_toInt32": _cast("_toInt32", "INTEGER"),+ "_toInt64": _cast("_toInt64", "BIGINT"),+ "to_date": _cast("to_date", "DATE"),+ "map": _map,+ "transform": _transform,"toMonday": _to_monday,"toIntervalMonth": _to_interval_month,"e": _e,"current_timestamp": _current_timestamp,+ "current_date": _today,+ "array": _array,+ "arrayPopFront": _array_pop_front,+ "arrayPopBack": _array_pop_back,+ "arrayPushFront": _array_push_front,+ "arrayPushBack": _array_push_back,+ "arrayResize": _array_resize,+ "arrayStringConcat": _array_string_concat,+ "arrayDifference": _array_difference,+ "arrayProduct": _array_product,+ "arrayUniq": _array_uniq,+ "arrayWithConstant": _array_with_constant,+ "base64Encode": _base64_encode,+ "base58Encode": _base58_encode,+ "base64Decode": _base64_decode,+ "tryBase64Decode": _try_base64_decode,+ "endsWith": _ends_with,+ "ascii": _ascii,+ "concatWithSeparator": _concat_with_separator,+ "left": _left,+ "leftPadUTF8": _pad("leftPadUTF8", "lpad"),+ "leftPad": _pad("leftPad", "lpad"),+ "rightPad": _pad("rightPad", "rpad"),+ "rightPadUTF8": _pad("rightPadUTF8", "rpad"),+ "positionUTF8": _position,+ "positionCaseInsensitiveUTF8": _position_case_insensitive,+ "splitByWhitespace": _split_by_whitespace,+ "splitByRegexp": _split_by_regexp,+ "appendTrailingCharIfAbsent": _append_trailing_character,+ "countMatches": _count_matches("countMatches"),+ "countMatchesCaseInsensitive": _count_matches("countMatchesCaseInsensitive", True),+ "countSubstrings": _count_substrings("countSubstrings"),+ "countSubstringsCaseInsensitive": _count_substrings("countSubstringsCaseInsensitive", True),+ "countSubstringsCaseInsensitiveUTF8": _count_substrings("countSubstringsCaseInsensitiveUTF8", True, True),+ "locate": _locate,+ "hasSubsequence": _has_subsequence("hasSubsequence", False, False),+ "hasSubsequenceCaseInsensitive": _has_subsequence("hasSubsequenceCaseInsensitive", True, False),+ "hasSubsequenceUTF8": _has_subsequence("hasSubsequenceUTF8", False, True),+ "hasSubsequenceCaseInsensitiveUTF8": _has_subsequence("hasSubsequenceCaseInsensitiveUTF8", True, True),+ "splitByNonAlpha": _extract_tokens("splitByNonAlpha", False),+ "alphaTokens": _extract_tokens("alphaTokens", True),+ "tokens": _extract_tokens("tokens", False),+ "xor": _logical_xor,+ "throwIf": _throw_if,+ "isValidUTF8": _is_valid_utf8,+ "regexpQuoteMeta": _regexp_quote_meta,+ "encodeXMLComponent": _encode_xml_component,+ "decodeXMLComponent": _decode_xml_component,+ "UUIDv7ToDateTime": _uuid_v7_to_datetime,+ "make_timestamp": _make_timestamp("make_timestamp", False),+ "make_timestamptz": _make_timestamp("make_timestamptz", True),+ "sortablesemver": _sortable_semver,+ "pointInEllipses": _point_in_ellipses,+ "ifNotFinite": _if_not_finite,+ "bar": _bar,+ "ngrams": _ngrams,+ "hasAllTokens": _has_tokens("hasAllTokens", True),+ "hasAnyTokens": _has_tokens("hasAnyTokens", False),+ "extractIPv4Substrings": _extract_ipv4_substrings,+ "hasToken": _has_token("hasToken", False, False),+ "hasTokenOrNull": _has_token("hasTokenOrNull", False, True),+ "hasTokenCaseInsensitive": _has_token("hasTokenCaseInsensitive", True, False),+ "hasTokenCaseInsensitiveOrNull": _has_token("hasTokenCaseInsensitiveOrNull", True, True),+ "initcap": _initcap,+ "isIPv4String": _is_ipv4_string,+ "isIPv6String": _is_ipv6_string,+ "isIPAddressInRange": _is_ip_address_in_range,+ "IPv4StringToNum": _ipv4_string_to_num("IPv4StringToNum", ""),+ "IPv4StringToNumOrDefault": _ipv4_string_to_num("IPv4StringToNumOrDefault", "0"),+ "IPv4StringToNumOrNull": _ipv4_string_to_num("IPv4StringToNumOrNull", "NULL"),+ "IPv4NumToString": _ipv4_num_to_string,+ "toIPv4": _to_ipv4("toIPv4", None),+ "toIPv4OrDefault": _to_ipv4("toIPv4OrDefault", "default"),+ "toIPv4OrNull": _to_ipv4("toIPv4OrNull", "NULL"),+ "toIPv4OrZero": _to_ipv4("toIPv4OrZero", "zero"),+ "IPv4CIDRToRange": _ipv4_cidr_to_range,+ "toValidUTF8": _identity("toValidUTF8"),+ "mapContains": _map_contains,+ "mapApply": _map_apply,+ "mapFilter": _map_lambda("mapFilter", "map_filter"),+ "mapContainsKeyLike": _map_key_like("mapContainsKeyLike", False),+ "mapExtractKeyLike": _map_key_like("mapExtractKeyLike", True),+ "json_agg": _json_agg,+ "string_agg": _string_agg,+ "every": _every,+ "stddevPopIf": _aggregate_if("stddev_pop"),+ "stddevSampIf": _aggregate_if("stddev_samp"),+ "varPopIf": _aggregate_if("var_pop"),+ "varSampIf": _aggregate_if("var_samp"),+ "covarPopIf": _aggregate_if("covar_pop"),+ "covarSampIf": _aggregate_if("covar_samp"),+ "groupBitAndIf": _aggregate_if("bitwise_and_agg"),+ "groupBitOrIf": _aggregate_if("bitwise_or_agg"),+ "groupBitXorIf": _aggregate_if("bitwise_xor_agg"),+ "date_add": _date_arithmetic("date_add", "+"),+ "date_subtract": _date_arithmetic("date_subtract", "-"),+ "make_date": _make_date,+ "monthName": _unary_expression("monthName", "date_format({value}, '%M')"),+ "timeZoneOf": _unary_expression("timeZoneOf", "timezone({value})"),+ "toUnixTimestamp64Milli": _unary_expression(+ "toUnixTimestamp64Milli", "CAST(to_unixtime({value}) * 1000 AS BIGINT)"+ ),+ "timezone": _timezone,+ "timeZoneOffset": _timezone_offset,+ "toWeek": _to_week("toWeek", False),+ "toYearWeek": _to_week("toYearWeek", True),+ "isValidJSON": _json_is_valid,+ "max2": _binary_expression("max2", "greatest({left}, {right})"),+ "min2": _binary_expression("min2", "least({left}, {right})"),+ "negate": _unary_expression("negate", "-({value})"),+ "positiveModulo": _positive_modulo,+ "intDivOrZero": _or_zero("intDivOrZero", "CAST({left} AS BIGINT) / CAST({right} AS BIGINT)"),+ "moduloOrZero": _or_zero("moduloOrZero", "mod({left}, {right})"),+ "acosh": _unary_expression("acosh", "ln({value} + sqrt({value} * {value} - 1))"),+ "asinh": _unary_expression("asinh", "ln({value} + sqrt({value} * {value} + 1))"),+ "atanh": _unary_expression("atanh", "0.5 * ln((1 + {value}) / (1 - {value}))"),+ "cosh": _unary_expression("cosh", "(exp({value}) + exp(-({value}))) / 2"),+ "exp10": _unary_expression("exp10", "power(10, {value})"),+ "exp2": _unary_expression("exp2", "power(2, {value})"),+ "hypot": _binary_expression("hypot", "sqrt({left} * {left} + {right} * {right})"),+ "intExp10": _unary_expression("intExp10", "CAST(power(10, {value}) AS BIGINT)"),+ "intExp2": _unary_expression("intExp2", "CAST(power(2, {value}) AS BIGINT)"),+ "log1p": _unary_expression("log1p", "ln(1 + {value})"),+ "sinh": _unary_expression("sinh", "(exp({value}) - exp(-({value}))) / 2"),+ "tanh": _unary_expression("tanh", "(exp({value}) - exp(-({value}))) / (exp({value}) + exp(-({value})))"),+ "_toUInt8": _cast("_toUInt8", "SMALLINT"),+ "arrayAvg": _array_avg,+ "arrayCompact": _array_compact,+ "arrayEnumerateDense": _array_enumerate_dense,+ "arrayEnumerateUniq": _array_enumerate_uniq,+ "arrayFirstIndex": _array_index("arrayFirstIndex", "first"),+ "arrayLastIndex": _array_index("arrayLastIndex", "last"),+ "arrayRotateLeft": _array_rotate("arrayRotateLeft", 1),+ "arrayRotateRight": _array_rotate("arrayRotateRight", -1),+ "bitTest": _bit_test("bitTest", "any"),+ "bitTestAll": _bit_test("bitTestAll", "all"),+ "bitTestAny": _bit_test("bitTestAny", "any"),+ "bitCount": _bit_count,+ "bitHammingDistance": _bit_hamming_distance,+ "bitShiftLeft": _bit_shift("bitShiftLeft", "bitwise_left_shift"),+ "bitShiftRight": _bit_shift("bitShiftRight", "bitwise_right_shift_arithmetic"),+ "domain": _url_string("domain", "url_extract_host"),+ "domainWithoutWWW": _domain_without_www,+ "protocol": _url_string("protocol", "url_extract_protocol"),+ "queryString": _url_query_part("queryString", False),+ "fragment": _url_query_part("fragment", True),+ "queryStringAndFragment": _query_string_and_fragment,+ "URLHierarchy": _url_hierarchy("URLHierarchy", False),+ "URLPathHierarchy": _url_hierarchy("URLPathHierarchy", True),+ "netloc": _netloc,+ "cutURLParameter": _cut_url_parameter,+ "pathFull": _path_full,+ "path": _path,+ "extractURLParameters": _extract_url_parameters("extractURLParameters", False),+ "extractURLParameterNames": _extract_url_parameters("extractURLParameterNames", True),+ "port": _port,+ "cutWWW": _cut_www,+ "topLevelDomain": _top_level_domain,+ "L1Distance": _l1_distance,+ "LinfDistance": _linf_distance,+ "L1Norm": _vector_norm("L1Norm", "l1"),+ "L2Norm": _vector_norm("L2Norm", "l2"),+ "LinfNorm": _vector_norm("LinfNorm", "linf"),+ "toModifiedJulianDay": _modified_julian_day("toModifiedJulianDay", False),+ "fromModifiedJulianDay": _modified_julian_day("fromModifiedJulianDay", True),}TRINO_FUNCTION_RENAMES_LOWER = {name.lower(): target for name, target in TRINO_FUNCTION_RENAMES.items()}+TRINO_FUNCTION_HANDLERS.update(+ {+ name: _multi_search(name)+ for operation in ("AllPositions", "FirstPosition", "FirstIndex", "Any")+ for suffix in ("", "UTF8", "CaseInsensitive", "CaseInsensitiveUTF8")+ if (name := f"multiSearch{operation}{suffix}") != "multiSearchAnyCaseInsensitive"+ }+)+TRINO_FUNCTION_HANDLERS.update(+ {+ "roundDown": _round_down,+ "roundAge": _round_age,+ "roundDuration": _round_duration,+ "roundToExp2": _identity("roundToExp2"),+ "gcd": _identity("gcd"),+ "lcm": _identity("lcm"),+ "JSONType": _identity("JSONType"),+ "date_bin": _identity("date_bin"),+ "arrayAUC": _identity("arrayAUC"),+ "tupleToNameValuePairs": _identity("tupleToNameValuePairs"),+ "mapPopulateSeries": _identity("mapPopulateSeries"),+ "toTypeName": _identity("toTypeName"),+ "bitNot": _identity("bitNot"),+ "indexHint": _constant("indexHint", "1"),+ "factorial": _factorial,+ "formatReadableSize": _format_readable(+ "formatReadableSize", 1024, ("B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB")+ ),+ "formatReadableDecimalSize": _format_readable(+ "formatReadableDecimalSize", 1000, ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB")+ ),+ "formatReadableQuantity": _format_readable(+ "formatReadableQuantity",+ 1000,+ (+ "",+ "thousand",+ "million",+ "billion",+ "trillion",+ "quadrillion",+ "quintillion",+ "sextillion",+ "septillion",+ "octillion",+ "nonillion",+ "decillion",+ "undecillion",+ "duodecillion",+ "tredecillion",+ "quattuordecillion",+ "quindecillion",+ "sexdecillion",+ "septendecillion",+ "octodecillion",+ "novemdecillion",+ "vigintillion",+ ),+ ),+ }+)TRINO_FUNCTION_HANDLERS_LOWER = {name.lower(): handler for name, handler in TRINO_FUNCTION_HANDLERS.items()}TRINO_PASSTHROUGH_FUNCTIONS = frozenset(@@ -366,6 +2103,7 @@ TRINO_PASSTHROUGH_FUNCTIONS = frozenset("json_value","lag","lead",+ "last_value","least","length","ln",@@ -377,6 +2115,7 @@ TRINO_PASSTHROUGH_FUNCTIONS = frozenset("max","min","nullif",+ "nth_value","pow","power","pi",diff --git a/posthog/hogql/printer/trino_hogql.py b/posthog/hogql/printer/trino_hogql.pynew file mode 100644index 000000000000..c64f5d07d886--- /dev/null+++ b/posthog/hogql/printer/trino_hogql.py@@ -0,0 +1,22 @@+from posthog.hogql import ast+from posthog.hogql.printer.hogql import HogQLPrinter+++class TrinoHogQLPrinter(HogQLPrinter):+ def visit_call(self, node: ast.Call) -> str:+ # Diagnostics and inferred names must accept Trino syntax; the Trino compiler validates the calls.+ params = f"({', '.join(self.visit(param) for param in node.params)})" if node.params is not None else ""+ order_by = f" ORDER BY {', '.join(self.visit(expr) for expr in node.order_by)}" if node.order_by else ""+ args_body = f"{'DISTINCT ' if node.distinct else ''}{', '.join(self.visit(arg) for arg in node.args)}{order_by}"+ args = (+ ""+ if node.within_group is not None and not node.args and not node.distinct and not node.order_by+ else f"({args_body})"+ )+ within_group = (+ f" WITHIN GROUP (ORDER BY {', '.join(self.visit(expr) for expr in node.within_group)})"+ if node.within_group+ else ""+ )+ filter_part = f" FILTER (WHERE {self.visit(node.filter_expr)})" if node.filter_expr else ""+ return f"{node.name}{params}{args}{within_group}{filter_part}"diff --git a/posthog/hogql/resolver.py b/posthog/hogql/resolver.pyindex cd7a1d0dbb0f..58a97d612819 100644--- a/posthog/hogql/resolver.py+++ b/posthog/hogql/resolver.py@@ -59,6 +59,7 @@ from posthog.hogql.transforms.trino.persons import (resolve_internal_trino_logical_table,resolve_trino_table_reference,)+from posthog.hogql.transforms.trino.pivot import TrinoPivotLowererfrom posthog.hogql.type_system import (infer_array_access_constant_type,infer_array_constant_type,@@ -272,6 +273,7 @@ def _unify_select_set_columns(select_types: list[ast.SelectQueryType | ast.SelectSetQueryType],dialect: HogQLDialect,context: HogQLContext,+ select_queries: list[ast.SelectQuery | ast.SelectSetQuery] | None = None,) -> dict[str, ast.Type]:if not select_types:return {}@@ -280,8 +282,23 @@ def _unify_select_set_columns(first_columns = branch_columns_per_select[0]columns: dict[str, ast.Type] = {}for index, (column_name, _) in enumerate(first_columns):+ projection_index = index+ if dialect == "trino" and select_queries and isinstance(select_queries[0], ast.SelectQuery):+ for candidate_index, projection in enumerate(select_queries[0].select):+ if (isinstance(projection, ast.Alias) and projection.alias == column_name) or (+ isinstance(projection, ast.Field) and projection.chain[-1] == column_name+ ):+ projection_index = candidate_index+ breakbranch_types: list[ast.ConstantType] = []- for branch_columns in branch_columns_per_select:+ for branch_index, branch_columns in enumerate(branch_columns_per_select):+ query = select_queries[branch_index] if select_queries else None+ if dialect == "trino" and isinstance(query, ast.SelectQuery) and projection_index < len(query.select):+ projection_type = query.select[projection_index].type+ branch_types.append(+ projection_type.resolve_constant_type(context) if projection_type is not None else ast.UnknownType()+ )+ continueif index >= len(branch_columns):branch_types.append(ast.UnknownType())continue@@ -307,7 +324,7 @@ def _by_name_column_mismatch_error(canonical: list[str], names: list[str]) -> Qu)-def _remap_positional_ordinals(leaf: ast.SelectQuery, new_index_by_old: dict[int, int]) -> None:+def _remap_positional_ordinals(leaf: ast.SelectQuery, new_index_by_old: dict[int, int], dialect: HogQLDialect) -> None:# ClickHouse resolves bare integer literals in these clauses positionally (enable_positional_arguments# defaults to on), so a reordered select list must carry the ordinals along or `ORDER BY 2` silently# comes to mean a different column.@@ -316,19 +333,25 @@ def _remap_positional_ordinals(leaf: ast.SelectQuery, new_index_by_old: dict[intif leaf.limit_by:referencing.extend(leaf.limit_by.exprs)for expr in referencing:- if isinstance(expr, ast.Constant) and isinstance(expr.value, int) and not isinstance(expr.value, bool):+ if dialect == "trino" and isinstance(expr, ast.PositionalRef):+ new_index = new_index_by_old.get(expr.index - 1)+ if new_index is not None:+ expr.index = new_index + 1+ elif isinstance(expr, ast.Constant) and isinstance(expr.value, int) and not isinstance(expr.value, bool):new_index = new_index_by_old.get(expr.value - 1)if new_index is not None:expr.value = new_index + 1-def _permute_set_operand(branch: ast.SelectQuery | ast.SelectSetQuery, permutation: list[int]) -> None:+def _permute_set_operand(+ branch: ast.SelectQuery | ast.SelectSetQuery, permutation: list[int], dialect: HogQLDialect+) -> None:"""Apply one positional permutation (new position -> old position) to every SELECT leaf of a setoperand. Each leaf is validated on the way down, so a nested branch whose select list does not lineup with the operand's columns raises instead of being silently truncated."""if isinstance(branch, ast.SelectSetQuery):for sub in branch.select_queries():- _permute_set_operand(sub, permutation)+ _permute_set_operand(sub, permutation, dialect)branch_type = branch.typeif isinstance(branch_type, ast.SelectSetQueryType) and branch_type.columns:names = list(branch_type.columns.keys())@@ -342,7 +365,7 @@ def _permute_set_operand(branch: ast.SelectQuery | ast.SelectSetQuery, permutatileaf_type = branch.typeif not isinstance(leaf_type, ast.SelectQueryType) or len(leaf_type.columns) != len(branch.select):raise QueryError("BY NAME requires uniquely named columns in every branch of the set operation")- _remap_positional_ordinals(branch, {old: new for new, old in enumerate(permutation)})+ _remap_positional_ordinals(branch, {old: new for new, old in enumerate(permutation)}, dialect)branch.select = [branch.select[old] for old in permutation]names = list(leaf_type.columns.keys())leaf_type.columns = {names[old]: leaf_type.columns[names[old]] for old in permutation}@@ -444,7 +467,7 @@ class Resolver(CloningVisitor):]result.type = ast.SelectSetQueryType(types=select_types, # type: ignore[arg-type]- columns=_unify_select_set_columns(select_types, self.dialect, self.context), # type: ignore[arg-type]+ columns=_unify_select_set_columns(select_types, self.dialect, self.context, result.select_queries()), # type: ignore[arg-type])self.ctes = parent_ctes@@ -452,21 +475,26 @@ class Resolver(CloningVisitor):return resultdef _lower_by_name_operators(self, node: ast.SelectSetQuery) -> None:- """ClickHouse has no `UNION ... BY NAME` syntax, so the operator cannot be printed there. Lower- it instead: reorder each BY NAME operand's select lists to the first branch's column order and- emit the plain operator. Dialects with native support (DuckDB behind the postgres printer) keep- the operator untouched. Differing column sets raise here, where DuckDB's native BY NAME would- null-fill — the error tells the user how to close the gap.-- Only UNION variants are lowered. INTERSECT/EXCEPT BY NAME bind tighter than UNION, so their- real set partner is the preceding operand rather than the first branch; aligning to the first- branch would silently misalign them. No engine we target supports them either, so they are- refused rather than lowered."""- if self.dialect != "clickhouse":+ """Align named set operands before positional type unification.++ ClickHouse accepts UNION rewrites. Trino also accepts chains from one+ INTERSECT or EXCEPT family. Mixed-precedence chains keep an explicit error.+ Other dialects retain their native syntax. Every input must have the same+ unique column names; the compiler does not invent missing columns.+ """+ if self.dialect not in {"clickhouse", "trino"}:return+ families = {sub.set_operator.split()[0] for sub in node.subsequent_select_queries}+ if (+ self.dialect == "trino"+ and len(families) > 1+ and any(sub.set_operator.endswith(_BY_NAME_SUFFIX) for sub in node.subsequent_select_queries)+ ):+ raise QueryError("Mixed set operators with BY NAME require explicit subqueries in the 'trino' dialect")for sub in node.subsequent_select_queries:if sub.set_operator.endswith(_BY_NAME_SUFFIX) and not sub.set_operator.startswith("UNION "):- raise QueryError(f"{sub.set_operator} is not supported in the '{self.dialect}' dialect")+ if self.dialect != "trino" or len(families) != 1:+ raise QueryError(f"{sub.set_operator} is not supported in the '{self.dialect}' dialect")if not any(sub.set_operator.endswith(_BY_NAME_SUFFIX) for sub in node.subsequent_select_queries):returninitial = node.initial_select_query@@ -490,7 +518,7 @@ class Resolver(CloningVisitor):if set(names) != set(index_by_name):raise _by_name_column_mismatch_error(canonical, names)branch_index_by_name = {name: index for index, name in enumerate(names)}- _permute_set_operand(branch, [branch_index_by_name[name] for name in canonical])+ _permute_set_operand(branch, [branch_index_by_name[name] for name in canonical], self.dialect)sub.set_operator = cast(ast.SetOperator, sub.set_operator[: -len(_BY_NAME_SUFFIX)])def visit_values_query(self, node: ast.ValuesQuery):@@ -519,7 +547,7 @@ class Resolver(CloningVisitor):return resultdef visit_unpivot_expr(self, node: ast.UnpivotExpr):- if self.dialect not in _PIVOT_DIALECTS:+ if self.dialect not in _PIVOT_DIALECTS and self.dialect != "trino":raise QueryError(f"UNPIVOT is not allowed in {self.dialect} dialect")node = cast(ast.UnpivotExpr, clone_expr(node))@@ -706,7 +734,7 @@ class Resolver(CloningVisitor):self.scopes.pop()def visit_pivot_expr(self, node: ast.PivotExpr):- if self.dialect not in _PIVOT_DIALECTS:+ if self.dialect not in _PIVOT_DIALECTS and self.dialect != "trino":raise QueryError(f"PIVOT is not allowed in {self.dialect} dialect")node = cast(ast.PivotExpr, clone_expr(node))@@ -774,6 +802,13 @@ class Resolver(CloningVisitor):for expr in node.group_by:ensure_pivot_column_valid(expr)+ if self.dialect == "trino":+ source_columns = (+ list(base_type.resolve_database_table(self.context).get_asterisk())+ if isinstance(base_type, ast.BaseTableType)+ else list(columns)+ )+ return self.visit(clone_expr(TrinoPivotLowerer().lower(node, source_columns), clear_types=True))node.type = ast.SelectQueryType(columns=columns)return nodefinally:@@ -922,7 +957,7 @@ class Resolver(CloningVisitor):# Visit the FROM clauses first. This resolves all table aliases onto self.scopes[-1]new_node.select_from = self.visit(node.select_from)- if node.limit_percent and self.dialect not in _POSTGRES_FAMILY:+ if node.limit_percent and self.dialect not in _POSTGRES_FAMILY and self.dialect != "trino":if self.dialect == "clickhouse":if not (isinstance(node.limit, ast.Constant) and isinstance(node.limit.value, (int, float))):raise QueryError("LIMIT percent with expressions is not supported in clickhouse dialect")@@ -1012,7 +1047,14 @@ class Resolver(CloningVisitor):elif isinstance(new_expr.type, ast.CallType):from posthog.hogql.printer import print_prepared_ast- alias = safe_identifier(print_prepared_ast(node=new_expr, context=self.context, dialect="hogql"))+ if self.dialect == "trino":+ from posthog.hogql.printer.trino_hogql import ( # noqa: PLC0415 -- breaks printer/resolver import cycle+ TrinoHogQLPrinter,+ )++ alias = safe_identifier(TrinoHogQLPrinter(context=self.context).visit(new_expr))+ else:+ alias = safe_identifier(print_prepared_ast(node=new_expr, context=self.context, dialect="hogql"))else:alias = None@@ -1578,6 +1620,11 @@ class Resolver(CloningVisitor):node.type = ast.SelectViewType(alias=node.alias,view_name=node.table.view_name,+ table=(+ self.database.get_table(node.table.view_name)+ if self.dialect == "trino" and self.database is not None+ else None+ ),select_query_type=cast(ast.SelectQueryType, node.table.type),)scope.tables[node.alias] = node.type@@ -1745,6 +1792,21 @@ class Resolver(CloningVisitor):return self._desugar_using_constraint(node, using_column_names)return self.visit_join_constraint(node.constraint)+ def _qualify_using_field(self, expr: ast.Expr) -> None:+ while isinstance(expr, ast.Alias):+ expr = expr.expr+ if not isinstance(expr, ast.Field):+ return+ field_type = expr.type+ while isinstance(field_type, ast.FieldAliasType):+ field_type = field_type.type+ if not isinstance(field_type, ast.FieldType):+ return+ for alias, table_type in self._get_scope().tables.items():+ if table_type is field_type.table_type:+ expr.chain = [alias, expr.chain[-1]]+ return+def _desugar_using_constraint(self, node: ast.JoinExpr, using_column_names: Optional[list[str]]) -> ast.JoinConstraint:@@ -1760,15 +1822,21 @@ class Resolver(CloningVisitor):left_exprs = constraint.expr.exprs if isinstance(constraint.expr, ast.Tuple) else [constraint.expr]if using_column_names is None or len(using_column_names) != len(left_exprs):raise ImpossibleASTError("USING constraint columns are out of sync with its resolved expressions")- compare_exprs: list[ast.Expr] = [- ast.CompareOperation(- op=ast.CompareOperationOp.Eq,- left=left_expr,- right=self._resolve_using_column_on_joined_table(node, column_name),- type=ast.BooleanType(nullable=False),+ compare_exprs: list[ast.Expr] = []+ for left_expr, column_name in zip(left_exprs, using_column_names):+ right_expr = self._resolve_using_column_on_joined_table(node, column_name)+ if self.dialect == "trino":+ # Trino clears resolved types before a second pass, so both ON fields need source qualifiers.+ self._qualify_using_field(left_expr)+ self._qualify_using_field(right_expr)+ compare_exprs.append(+ ast.CompareOperation(+ op=ast.CompareOperationOp.Eq,+ left=left_expr,+ right=right_expr,+ type=ast.BooleanType(nullable=False),+ ))- for left_expr, column_name in zip(left_exprs, using_column_names)- ]expr: ast.Expr = (compare_exprs[0]if len(compare_exprs) == 1@@ -1825,7 +1893,9 @@ class Resolver(CloningVisitor):left_type = node.left.type.resolve_constant_type(self.context)right_type = node.right.type.resolve_constant_type(self.context)- if isinstance(left_type, ast.IntegerType) and isinstance(right_type, ast.IntegerType):+ if self.dialect == "trino" and node.op == ast.ArithmeticOperationOp.Div:+ node.type = ast.FloatType()+ elif isinstance(left_type, ast.IntegerType) and isinstance(right_type, ast.IntegerType):node.type = ast.IntegerType()elif isinstance(left_type, ast.FloatType) and isinstance(right_type, ast.FloatType):node.type = ast.FloatType()@@ -1892,6 +1962,10 @@ class Resolver(CloningVisitor):def visit_call(self, node: ast.Call):"""Visit function calls."""+ if self.dialect == "trino" and node.name.lower() == "date":+ node = clone_expr(node, clear_types=False)+ node.name = "toDate"+# Expand *COLUMNS(...) in function argumentsexpanded_args: list[ast.Expr] = []has_spread = False@@ -2038,10 +2112,13 @@ class Resolver(CloningVisitor):)return node- @staticmethod- def _is_higher_order_array_call(node: ast.Call) -> bool:+ def _is_higher_order_array_call(self, node: ast.Call) -> bool:return (- node.name.lower() in _HIGHER_ORDER_ARRAY_FUNCTIONS+ (+ node.name.lower() in _HIGHER_ORDER_ARRAY_FUNCTIONS+ or self.dialect == "trino"+ and node.name.lower() in {"arraycumsum", "arraycumsumnonnegative"}+ )and bool(node.args)and isinstance(node.args[0], ast.Lambda))diff --git a/posthog/hogql/test/test_mapping.py b/posthog/hogql/test/test_mapping.pyindex 99cb1aa3a3aa..24c72d105064 100644--- a/posthog/hogql/test/test_mapping.py+++ b/posthog/hogql/test/test_mapping.py@@ -4,6 +4,7 @@ from typing import Any, Optionalimport pytestimport time_machinefrom posthog.test.base import BaseTest, ClickhouseTestMixin+from unittest import mockfrom posthog.hogql import astfrom posthog.hogql.ast import DateType, FloatType, IntegerType, StringLiteralType, StringType@@ -103,26 +104,28 @@ class TestMappings(ClickhouseTestMixin, BaseTest):assert res is Truedef test_unknown_type_mapping(self):- HOGQL_CLICKHOUSE_FUNCTIONS["overloadedFunction"] = HogQLFunctionMeta(- "overloadFailure",- 1,- 1,- overloads=[((DateType,), "overloadSuccess")],- )-- HOGQL_CLICKHOUSE_FUNCTIONS["dateEmittingFunction"] = HogQLFunctionMeta(- "dateEmittingFunction",- 1,- 1,- signatures=[- ((UnknownType(),), DateType()),- ],- )- sql, _ = prepare_and_print_ast(- parse_expr("overloadedFunction(dateEmittingFunction('123123'))"),- HogQLContext(self.team.pk, enable_select_queries=True),- "clickhouse",- )+ with mock.patch.dict(+ HOGQL_CLICKHOUSE_FUNCTIONS,+ {+ "overloadedFunction": HogQLFunctionMeta(+ "overloadFailure",+ 1,+ 1,+ overloads=[((DateType,), "overloadSuccess")],+ ),+ "dateEmittingFunction": HogQLFunctionMeta(+ "dateEmittingFunction",+ 1,+ 1,+ signatures=[((UnknownType(),), DateType())],+ ),+ },+ ):+ sql, _ = prepare_and_print_ast(+ parse_expr("overloadedFunction(dateEmittingFunction('123123'))"),+ HogQLContext(self.team.pk, enable_select_queries=True),+ "clickhouse",+ )assert "overloadSuccess" in sql@time_machine.travel("2023-01-01T12:00:00Z", tick=False)diff --git a/posthog/hogql/test/test_type_system.py b/posthog/hogql/test/test_type_system.pyindex ea35f0d9b203..37c73558616a 100644--- a/posthog/hogql/test/test_type_system.py+++ b/posthog/hogql/test/test_type_system.py@@ -8,7 +8,7 @@ from posthog.hogql.constants import HogQLDialectfrom posthog.hogql.context import HogQLContextfrom posthog.hogql.database.database import Databasefrom posthog.hogql.database.models import FloatArrayDatabaseField-from posthog.hogql.errors import QueryError+from posthog.hogql.errors import QueryError, ResolutionErrorfrom posthog.hogql.functions.mapping import find_hogql_functionfrom posthog.hogql.parser import parse_selectfrom posthog.hogql.printer import print_prepared_ast@@ -941,16 +941,29 @@ class TestHogQLTypeSystem:),)- def test_select_set_query_unifies_output_column_types(self) -> None:- node = cast(- ast.SelectSetQuery,- resolve_types(- self._select("SELECT 1 AS value UNION ALL SELECT 2.0 AS value"), self.context, dialect="clickhouse"- ),- )-+ @pytest.mark.parametrize(+ "query, dialect, expected",+ [+ ("SELECT 1 AS value UNION ALL SELECT 2.0 AS value", "clickhouse", ast.FloatType(nullable=False)),+ ("SELECT 0, 1 AS value UNION ALL SELECT 2.5 AS other, 3", "trino", ast.IntegerType(nullable=False)),+ ],+ )+ def test_select_set_query_unifies_output_column_types(+ self, query: str, dialect: HogQLDialect, expected: ast.ConstantType+ ) -> None:+ node = cast(ast.SelectSetQuery, resolve_types(self._select(query), self.context, dialect=dialect))assert isinstance(node.type, ast.SelectSetQueryType)- assert node.type.resolve_column_constant_type("value", self.context) == ast.FloatType(nullable=False)+ assert node.type.resolve_column_constant_type("value", self.context) == expected++ def test_clickhouse_view_metadata_remains_lazy(self) -> None:+ query = self._select("SELECT 1 FROM (SELECT 2 AS value) AS saved")+ assert query.select_from is not None and isinstance(query.select_from.table, ast.SelectQuery)+ query.select_from.table.view_name = "unavailable_view"+ context = HogQLContext(database=None, enable_select_queries=True)+ resolved = resolve_types(query, context, dialect="clickhouse")+ assert resolved.select_from is not None and isinstance(resolved.select_from.type, ast.SelectViewType)+ with pytest.raises(ResolutionError, match="Database must be set for queries with views"):+ resolved.select_from.type.resolve_database_table(context)def test_type_diagnostics_reports_unknown_function_boundary(self) -> None:diagnostics = resolve_with_type_diagnostics(diff --git a/posthog/hogql/transforms/trino/any_join.py b/posthog/hogql/transforms/trino/any_join.pyindex c0b6dca2a2ed..641f52516c20 100644--- a/posthog/hogql/transforms/trino/any_join.py+++ b/posthog/hogql/transforms/trino/any_join.py@@ -1,7 +1,7 @@from posthog.hogql import astfrom posthog.hogql.database.models import DatabaseFieldfrom posthog.hogql.transforms.trino.errors import TrinoLoweringError-from posthog.hogql.visitor import CloningVisitor+from posthog.hogql.visitor import CloningVisitor, TraversingVisitor, clone_expr_SUPPORTED_ANY_JOIN_TYPES = {"ANY INNER JOIN": "INNER JOIN",@@ -14,6 +14,127 @@ class TrinoAnyJoinLowerer(CloningVisitor):super().__init__(clear_types=False)self.join_index = 0+ def visit_select_query(self, node: ast.SelectQuery) -> ast.SelectQuery:+ first = node.select_from+ second = first.next_join if first is not None else None+ right_modes = {+ "RIGHT ANY JOIN": "LEFT ANY JOIN",+ "RIGHT SEMI JOIN": "LEFT SEMI JOIN",+ "RIGHT ANTI JOIN": "LEFT ANTI JOIN",+ }+ later_join = second.next_join if second is not None else None+ while later_join is not None:+ if later_join.join_type in right_modes:+ raise TrinoLoweringError(+ "TRINO_RIGHT_JOIN_CHAIN_UNSUPPORTED", "RIGHT ANY, SEMI, or ANTI in a join chain", later_join+ )+ later_join = later_join.next_join+ if first is not None and second is not None and second.join_type in right_modes:+ if second.next_join is not None:+ raise TrinoLoweringError(+ "TRINO_RIGHT_JOIN_CHAIN_UNSUPPORTED", "RIGHT ANY, SEMI, or ANTI in a join chain", second+ )+ node = clone_expr(node, clear_types=False)+ first = node.select_from+ assert first is not None and first.next_join is not None+ second = first.next_join+ assert second.join_type is not None+ first.join_type = right_modes[second.join_type]+ first.constraint = second.constraint+ first.next_join = None+ second.join_type = None+ second.constraint = None+ second.next_join = first+ node.select_from = second+ lowered = super().visit_select_query(node)+ join = lowered.select_from+ while join is not None:+ if join.join_type in {"LEFT SEMI JOIN", "SEMI JOIN", "LEFT ANTI JOIN", "ANTI JOIN"}:+ self._lower_filter_join(lowered, join)+ join = join.next_join+ return lowered++ def _lower_filter_join(self, query: ast.SelectQuery, join: ast.JoinExpr) -> None:+ if join.column_aliases:+ raise TrinoLoweringError(+ "TRINO_FILTER_JOIN_COLUMN_ALIASES_UNSUPPORTED", "SEMI or ANTI column aliases", join+ )+ alias = join.alias+ if alias is None and isinstance(join.table, ast.Field) and isinstance(join.table.chain[-1], str):+ alias = join.table.chain[-1]+ if alias is None or join.constraint is None or join.constraint.constraint_type != "ON":+ raise TrinoLoweringError("TRINO_FILTER_JOIN_ON_REQUIRED", "SEMI or ANTI JOIN without an alias and ON", join)+ table_type = join.type+ while isinstance(table_type, (ast.TableAliasType, ast.ColumnAliasedTableType)):+ table_type = table_type.table_type+ if not isinstance(table_type, (ast.BaseTableType, ast.SelectQueryAliasType)):+ raise TrinoLoweringError(+ "TRINO_FILTER_JOIN_TABLE_UNRESOLVED", "SEMI or ANTI JOIN without a table type", join+ )+ keys = self._right_key_expressions(join.constraint.expr, alias, table_type)+ names = [self._right_field_name(key, alias, table_type) for key in keys]+ if not names or any(name is None for name in names):+ raise TrinoLoweringError(+ "TRINO_FILTER_JOIN_FIELD_KEYS_REQUIRED", "SEMI or ANTI JOIN with a computed right key", join+ )+ outer = self+ right_alias: str = alias+ right_type: ast.TableOrSelectType = table_type++ class RightReferenceValidator(TraversingVisitor):+ def visit_field(self, field: ast.Field) -> None:+ if outer._right_field_name(field, right_alias, right_type) is not None:+ raise TrinoLoweringError(+ "TRINO_FILTER_JOIN_RIGHT_OUTPUT_UNSUPPORTED", "SEMI or ANTI JOIN right-side output", field+ )++ validator = RightReferenceValidator()+ for expression in [+ *query.select,+ query.where,+ query.prewhere,+ query.having,+ query.qualify,+ query.limit_by,+ *(query.group_by or []),+ *(query.order_by or []),+ *(query.array_join_list or []),+ *(query.window_exprs or {}).values(),+ ]:+ if expression is not None:+ validator.visit(expression)+ following = join.next_join+ while following is not None:+ if following.constraint is not None:+ validator.visit(following.constraint)+ if following.table is not None:+ validator.visit(following.table)+ for argument in following.table_args or []:+ validator.visit(argument)+ following = following.next_join+ source = clone_expr(join, clear_types=False)+ source.join_type = None+ source.constraint = None+ source.next_join = None+ join.table = ast.SelectQuery(+ select=[+ ast.Alias(alias=name, expr=ast.Field(chain=[alias, name])) for name in dict.fromkeys(names) if name+ ],+ select_from=source,+ distinct=True,+ )+ join.alias = alias+ join.table_args = None+ join.column_aliases = None+ join.table_final = None+ join.sample = None+ if "ANTI" in (join.join_type or "").split():+ predicate = ast.Call(name="isNull", args=[ast.Field(chain=[alias, str(names[0])])])+ query.where = ast.And(exprs=[query.where, predicate]) if query.where is not None else predicate+ join.join_type = "LEFT JOIN"+ else:+ join.join_type = "INNER JOIN"+def visit_join_expr(self, node: ast.JoinExpr) -> ast.JoinExpr:lowered = super().visit_join_expr(node)join_type = lowered.join_type or ""@@ -23,7 +144,9 @@ class TrinoAnyJoinLowerer(CloningVisitor):if target_join_type is None:raise TrinoLoweringError("TRINO_ANY_JOIN_MODE_UNSUPPORTED", join_type, lowered)if lowered.alias is None:- raise TrinoLoweringError("TRINO_ANY_JOIN_ALIAS_REQUIRED", f"{join_type} without a right alias", lowered)+ if not isinstance(lowered.table, ast.Field) or not isinstance(lowered.table.chain[-1], str):+ raise TrinoLoweringError("TRINO_ANY_JOIN_ALIAS_REQUIRED", f"{join_type} without a right alias", lowered)+ lowered.alias = lowered.table.chain[-1]if lowered.column_aliases:raise TrinoLoweringError("TRINO_ANY_JOIN_COLUMN_ALIASES_UNSUPPORTED", f"{join_type} with column aliases", lowered@@ -32,25 +155,47 @@ class TrinoAnyJoinLowerer(CloningVisitor):raise TrinoLoweringError("TRINO_ANY_JOIN_ON_REQUIRED", f"{join_type} without an ON constraint", lowered)table_type = lowered.type- while isinstance(table_type, (ast.TableAliasType, ast.ColumnAliasedTableType)):+ while isinstance(table_type, (ast.TableAliasType, ast.ColumnAliasedTableType, ast.CTETableAliasType)):+ if isinstance(table_type, ast.CTETableAliasType):+ table_type = table_type.cte_table_type+ continuetable_type = table_type.table_type- if not isinstance(table_type, ast.TableType) or not getattr(table_type.table, "has_complete_columns", False):+ key_expressions = self._right_key_expressions(lowered.constraint.expr, lowered.alias, table_type)+ key_names = [+ name+ for expr in key_expressions+ if (name := self._right_field_name(expr, lowered.alias, table_type)) is not None+ ]+ if isinstance(table_type, ast.LazyTableType) and table_type.table.name == "persons" and key_names == ["id"]:+ lowered.join_type = target_join_type+ return lowered+ if isinstance(table_type, ast.CTETableType):+ column_names = list(table_type.select_query_type.columns)+ elif isinstance(table_type, ast.SelectQueryAliasType):+ column_names = list(table_type.select_query_type.columns)+ elif isinstance(lowered.table, (ast.SelectQuery, ast.SelectSetQuery)) and isinstance(+ lowered.table.type, (ast.SelectQueryType, ast.SelectSetQueryType)+ ):+ column_names = list(lowered.table.type.columns)+ elif isinstance(table_type, ast.LazyTableType):+ column_names = [+ field.name+ for field in table_type.table.fields.values()+ if isinstance(field, DatabaseField)+ and not (table_type.table.name == "persons" and field.name == "last_seen_at")+ ]+ elif not isinstance(table_type, ast.TableType):raise TrinoLoweringError("TRINO_ANY_JOIN_COMPLETE_TABLE_REQUIRED",- f"{join_type} against a relation without a complete physical column list",+ f"{join_type} against a relation without a physical column list",lowered,)- if any(not isinstance(field, DatabaseField) for field in table_type.table.fields.values()):- raise TrinoLoweringError(- "TRINO_ANY_JOIN_PHYSICAL_COLUMNS_REQUIRED",- f"{join_type} against a relation with logical or nested fields",- lowered,- )-- column_names = [field.name for field in table_type.table.fields.values() if isinstance(field, DatabaseField)]+ else:+ column_names = [+ field.name for field in table_type.table.fields.values() if isinstance(field, DatabaseField)+ ]if not column_names:raise TrinoLoweringError("TRINO_ANY_JOIN_EMPTY_TABLE_UNSUPPORTED", f"{join_type} without columns", lowered)- key_names = self._right_key_names(lowered.constraint.expr, lowered.alias)index = self.join_indexself.join_index += 1@@ -69,7 +214,10 @@ class TrinoAnyJoinLowerer(CloningVisitor):name="row_number",exprs=[],over_expr=ast.WindowExpr(- partition_by=[ast.Field(chain=[source_alias, name]) for name in key_names]+ partition_by=[+ self._qualify_right_expression(expr, lowered.alias, table_type, source_alias)+ for expr in key_expressions+ ]),),)@@ -96,9 +244,11 @@ class TrinoAnyJoinLowerer(CloningVisitor):lowered.column_aliases = Nonereturn lowered- def _right_key_names(self, constraint: ast.Expr, alias: str) -> list[str]:+ def _right_key_expressions(+ self, constraint: ast.Expr, alias: str, right_table_type: ast.TableOrSelectType+ ) -> list[ast.Expr]:terms = constraint.exprs if isinstance(constraint, ast.And) else [constraint]- key_names: list[str] = []+ key_expressions: list[ast.Expr] = []for term in terms:if not isinstance(term, ast.CompareOperation) or term.op != ast.CompareOperationOp.Eq:raise TrinoLoweringError(@@ -106,18 +256,64 @@ class TrinoAnyJoinLowerer(CloningVisitor):"ANY JOIN with a non-equality ON term",term,)- left_name = self._right_field_name(term.left, alias)- right_name = self._right_field_name(term.right, alias)- if (left_name is None) == (right_name is None):+ left_is_right = self._expression_uses_only_right_fields(term.left, alias, right_table_type)+ right_is_right = self._expression_uses_only_right_fields(term.right, alias, right_table_type)+ if left_is_right == right_is_right:raise TrinoLoweringError("TRINO_ANY_JOIN_EQUI_KEYS_REQUIRED","ANY JOIN equality without exactly one right-side field",term,)- key_names.append(left_name or right_name or "")- return list(dict.fromkeys(key_names))+ key_expressions.append(term.left if left_is_right else term.right)+ return key_expressions++ def _expression_uses_only_right_fields(+ self, expression: ast.Expr, alias: str, right_table_type: ast.TableOrSelectType+ ) -> bool:+ outer = self++ class RightFieldFinder(CloningVisitor):+ def __init__(self) -> None:+ super().__init__(clear_types=False)+ self.found = False+ self.invalid = False- def _right_field_name(self, expression: ast.Expr, alias: str) -> str | None:+ def visit_field(self, node: ast.Field) -> ast.Field:+ if outer._right_field_name(node, alias, right_table_type) is None:+ self.invalid = True+ else:+ self.found = True+ return node++ finder = RightFieldFinder()+ finder.visit(expression)+ return finder.found and not finder.invalid++ def _qualify_right_expression(+ self,+ expression: ast.Expr,+ alias: str,+ right_table_type: ast.TableOrSelectType,+ source_alias: str,+ ) -> ast.Expr:+ outer = self++ class RightFieldQualifier(CloningVisitor):+ def visit_field(self, node: ast.Field) -> ast.Field:+ name = outer._right_field_name(node, alias, right_table_type)+ if name is None:+ raise TrinoLoweringError(+ "TRINO_ANY_JOIN_EQUI_KEYS_REQUIRED",+ "ANY JOIN right key expression includes a left-side field",+ node,+ )+ return ast.Field(chain=[source_alias, name], start=node.start, end=node.end)++ return RightFieldQualifier(clear_types=False).visit(expression)++ def _right_field_name(+ self, expression: ast.Expr, alias: str, right_table_type: ast.TableOrSelectType+ ) -> str | None:while isinstance(expression, ast.Alias):expression = expression.exprif not isinstance(expression, ast.Field):@@ -132,6 +328,22 @@ class TrinoAnyJoinLowerer(CloningVisitor):table_type = table_type.table_typeif isinstance(table_type, ast.TableAliasType) and table_type.alias == alias:return field_type.name+ if isinstance(table_type, ast.CTETableAliasType) and table_type.alias == alias:+ return field_type.name+ if isinstance(table_type, ast.SelectQueryAliasType) and table_type.alias == alias:+ return field_type.name+ if (+ isinstance(table_type, ast.TableType)+ and isinstance(right_table_type, ast.TableType)+ and table_type.table is right_table_type.table+ ):+ return field_type.name+ if (+ isinstance(table_type, ast.LazyTableType)+ and isinstance(right_table_type, ast.LazyTableType)+ and table_type.table is right_table_type.table+ ):+ return field_type.namereturn Nonediff --git a/posthog/hogql/transforms/trino/asof_join.py b/posthog/hogql/transforms/trino/asof_join.pynew file mode 100644index 000000000000..28102cf66e23--- /dev/null+++ b/posthog/hogql/transforms/trino/asof_join.py@@ -0,0 +1,190 @@+from typing import Literal++from posthog.hogql import ast+from posthog.hogql.transforms.trino.any_join import TrinoAnyJoinLowerer+from posthog.hogql.transforms.trino.errors import TrinoLoweringError+from posthog.hogql.visitor import CloningVisitor, clone_expr+++class TrinoAsOfJoinLowerer(CloningVisitor):+ def __init__(self) -> None:+ super().__init__(clear_types=False)+ self.index = 0++ def _columns(self, join: ast.JoinExpr) -> list[str]:+ if join.column_aliases:+ raise TrinoLoweringError("TRINO_ASOF_COLUMN_ALIASES_UNSUPPORTED", "ASOF column aliases", join)+ relation = join.type+ while isinstance(relation, (ast.TableAliasType, ast.CTETableAliasType)):+ relation = relation.cte_table_type if isinstance(relation, ast.CTETableAliasType) else relation.table_type+ if isinstance(relation, ast.SelectQueryAliasType):+ relation = relation.select_query_type+ if isinstance(relation, ast.CTETableType):+ relation = relation.select_query_type+ if isinstance(relation, (ast.SelectQueryType, ast.SelectSetQueryType)):+ return list(relation.columns)+ if isinstance(relation, ast.TableType) and getattr(relation.table, "has_complete_columns", False):+ return list(relation.table.get_asterisk())+ raise TrinoLoweringError("TRINO_ASOF_COMPLETE_TABLE_REQUIRED", "ASOF without complete input columns", join)++ def _alias(self, join: ast.JoinExpr) -> str:+ if join.alias is not None:+ return join.alias+ if isinstance(join.table, ast.Field) and isinstance(join.table.chain[-1], str):+ return join.table.chain[-1]+ raise TrinoLoweringError("TRINO_ASOF_ALIAS_REQUIRED", "ASOF without an input alias", join)++ def visit_select_query(self, node: ast.SelectQuery) -> ast.SelectQuery:+ lowered = super().visit_select_query(node)+ left = lowered.select_from+ right = left.next_join if left is not None else None+ if right is None or "ASOF" not in (right.join_type or "").split():+ return lowered+ if right.next_join is not None or right.join_type not in {+ "ASOF INNER JOIN",+ "LEFT ASOF JOIN",+ "ASOF LEFT JOIN",+ }:+ raise TrinoLoweringError(+ "TRINO_ASOF_JOIN_SHAPE_UNSUPPORTED", "ASOF outside a two-table INNER or LEFT join", right+ )+ assert left is not None+ if right.constraint is None or right.constraint.constraint_type != "ON":+ raise TrinoLoweringError("TRINO_ASOF_ON_REQUIRED", "ASOF without an ON constraint", right)+ left_alias, right_alias = self._alias(left), self._alias(right)+ left_columns, right_columns = self._columns(left), self._columns(right)+ left_type, right_type = left.type, right.type+ if left_type is None or right_type is None:+ raise TrinoLoweringError("TRINO_ASOF_COMPLETE_TABLE_REQUIRED", "ASOF without input types", right)+ bindings = TrinoAnyJoinLowerer()+ predicate = right.constraint.expr+ terms = predicate.exprs if isinstance(predicate, ast.And) else [predicate]+ equality_terms: list[ast.Expr] = []+ nearest: ast.Expr | None = None+ direction: Literal["ASC", "DESC"] = "DESC"+ for term in terms:+ if not isinstance(term, ast.CompareOperation):+ raise TrinoLoweringError("TRINO_ASOF_CONSTRAINT_UNSUPPORTED", "ASOF with a non-comparison term", term)+ if term.op == ast.CompareOperationOp.Eq:+ equality_terms.append(term)+ continue+ if nearest is not None or term.op not in {+ ast.CompareOperationOp.Lt,+ ast.CompareOperationOp.LtEq,+ ast.CompareOperationOp.Gt,+ ast.CompareOperationOp.GtEq,+ }:+ raise TrinoLoweringError(+ "TRINO_ASOF_CONSTRAINT_UNSUPPORTED", "ASOF without exactly one inequality", term+ )+ right_on_right = bindings._right_field_name(term.right, right_alias, right_type) is not None+ right_on_left = bindings._right_field_name(term.left, right_alias, right_type) is not None+ if right_on_left == right_on_right:+ raise TrinoLoweringError(+ "TRINO_ASOF_CONSTRAINT_UNSUPPORTED", "ASOF inequality without one right field", term+ )+ nearest = term.right if right_on_right else term.left+ left_time = term.left if right_on_right else term.right+ if bindings._right_field_name(left_time, left_alias, left_type) is None:+ raise TrinoLoweringError(+ "TRINO_ASOF_CONSTRAINT_UNSUPPORTED", "ASOF inequality without one left field", term+ )+ ascending = term.op in {ast.CompareOperationOp.Lt, ast.CompareOperationOp.LtEq}+ direction = "ASC" if ascending == right_on_right else "DESC"+ if nearest is None or not equality_terms:+ raise TrinoLoweringError(+ "TRINO_ASOF_CONSTRAINT_UNSUPPORTED", "ASOF needs equality keys and one inequality", right+ )+ bindings._right_key_expressions(ast.And(exprs=equality_terms), right_alias, right_type)+ prefix = f"__hogql_asof_{self.index}"+ self.index += 1+ while prefix in {left_alias, right_alias}:+ prefix += "_"+ row_name = f"{prefix}_left_row"+ while row_name in left_columns:+ row_name += "_"+ rank_name = f"{prefix}_rank"+ mappings = [+ (alias, name, f"{side}_{index}")+ for side, alias, columns in [("left", left_alias, left_columns), ("right", right_alias, right_columns)]+ for index, name in enumerate(columns)+ ]+ source = clone_expr(left, clear_types=False)+ source.next_join = None+ numbered = ast.SelectQuery(+ select=[ast.Field(chain=[left_alias, name]) for name in left_columns]+ + [+ ast.Alias(+ alias=row_name, expr=ast.WindowFunction(name="row_number", exprs=[], over_expr=ast.WindowExpr())+ )+ ],+ select_from=source,+ )+ right.join_type = "LEFT JOIN" if "LEFT" in (right.join_type or "").split() else "INNER JOIN"+ projections: list[ast.Expr] = [+ ast.Alias(alias=output, expr=ast.Field(chain=[alias, name])) for alias, name, output in mappings+ ]+ projections.append(+ ast.Alias(+ alias=rank_name,+ expr=ast.WindowFunction(+ name="row_number",+ exprs=[],+ over_expr=ast.WindowExpr(+ partition_by=[ast.Field(chain=[left_alias, row_name])],+ order_by=[ast.OrderExpr(expr=nearest, order=direction)],+ ),+ ),+ )+ )+ ranked = ast.SelectQuery(+ select=projections,+ select_from=ast.JoinExpr(table=numbered, alias=left_alias, next_join=right),+ )+ matched = ast.SelectQuery(+ select=[ast.Field(chain=[prefix, output]) for _, _, output in mappings],+ select_from=ast.JoinExpr(table=ranked, alias=prefix),+ where=ast.CompareOperation(+ left=ast.Field(chain=[prefix, rank_name]), op=ast.CompareOperationOp.Eq, right=ast.Constant(value=1)+ ),+ )+ by_left = {name: output for alias, name, output in mappings if alias == left_alias}+ by_right = {name: output for alias, name, output in mappings if alias == right_alias}++ class OutputRewriter(CloningVisitor):+ def visit_select_query(self, query: ast.SelectQuery) -> ast.SelectQuery:+ raise TrinoLoweringError(+ "TRINO_ASOF_SUBQUERY_UNSUPPORTED", "ASOF with a subquery outside its inputs", query+ )++ def visit_field(self, field: ast.Field) -> ast.Field:+ name = bindings._right_field_name(field, left_alias, left_type)+ if name is not None and name in by_left:+ return ast.Field(chain=[prefix, by_left[name]])+ name = bindings._right_field_name(field, right_alias, right_type)+ if name is not None and name in by_right:+ return ast.Field(chain=[prefix, by_right[name]])+ if isinstance(field.type, ast.FieldAliasType) and len(field.chain) == 1:+ return field+ raise TrinoLoweringError(+ "TRINO_ASOF_OUTPUT_UNSUPPORTED", "ASOF output without a direct input field", field+ )++ rewriter = OutputRewriter(clear_types=False)+ lowered.select = [rewriter.visit(expr) for expr in lowered.select]+ for clause in ["where", "prewhere", "having", "qualify", "limit_by"]:+ expression = getattr(lowered, clause)+ if expression is not None:+ setattr(lowered, clause, rewriter.visit(expression))+ lowered.group_by = [rewriter.visit(expr) for expr in lowered.group_by] if lowered.group_by is not None else None+ lowered.order_by = [rewriter.visit(expr) for expr in lowered.order_by] if lowered.order_by is not None else None+ lowered.array_join_list = (+ [rewriter.visit(expr) for expr in lowered.array_join_list] if lowered.array_join_list else None+ )+ lowered.window_exprs = (+ {name: rewriter.visit(expr) for name, expr in lowered.window_exprs.items()}+ if lowered.window_exprs+ else None+ )+ lowered.select_from = ast.JoinExpr(table=matched, alias=prefix)+ return lowereddiff --git a/posthog/hogql/transforms/trino/expressions.py b/posthog/hogql/transforms/trino/expressions.pyindex f4b3860c3070..bef8b8fc851a 100644--- a/posthog/hogql/transforms/trino/expressions.py+++ b/posthog/hogql/transforms/trino/expressions.py@@ -38,3 +38,24 @@ def positional_index(node: ast.Expr) -> int | None:if isinstance(node, ast.Constant) and isinstance(node.value, int) and not isinstance(node.value, bool):return node.valuereturn None+++def constant_integer(node: ast.Expr | None) -> int | None:+ if isinstance(node, ast.Constant) and isinstance(node.value, int) and not isinstance(node.value, bool):+ return node.value+ if not isinstance(node, ast.ArithmeticOperation):+ return None+ left = constant_integer(node.left)+ right = constant_integer(node.right)+ if left is None or right is None or not (-(2**63) <= left < 2**63 and -(2**63) <= right < 2**63):+ return None+ match node.op:+ case ast.ArithmeticOperationOp.Add:+ result = left + right+ case ast.ArithmeticOperationOp.Sub:+ result = left - right+ case ast.ArithmeticOperationOp.Mult:+ result = left * right+ case _:+ return None+ return result if -(2**63) <= result < 2**63 else Nonediff --git a/posthog/hogql/transforms/trino/limits.py b/posthog/hogql/transforms/trino/limits.pynew file mode 100644index 000000000000..c3887069eba6--- /dev/null+++ b/posthog/hogql/transforms/trino/limits.py@@ -0,0 +1,25 @@+from posthog.hogql import ast+from posthog.hogql.transforms.trino.errors import TrinoLoweringError+from posthog.hogql.visitor import TraversingVisitor++MAX_TRINO_SQL_LENGTH = 1_000_000+++class TrinoCompilationBudget(TraversingVisitor):+ def __init__(self) -> None:+ self.remaining_nodes = 10_000++ def consume_node(self, node: ast.AST | None) -> None:+ if node is None:+ return+ self.remaining_nodes -= 1+ if self.remaining_nodes < 0:+ raise TrinoLoweringError(+ "TRINO_AST_EXPANSION_LIMIT",+ "expressions that expand beyond the compilation limit; simplify the query",+ node if isinstance(node, ast.Expr) else None,+ )++ def visit(self, node: ast.AST | None) -> None:+ self.consume_node(node)+ super().visit(node)diff --git a/posthog/hogql/transforms/trino/manifest.py b/posthog/hogql/transforms/trino/manifest.pyindex 7ee2df08b2bc..514b5a75c840 100644--- a/posthog/hogql/transforms/trino/manifest.py+++ b/posthog/hogql/transforms/trino/manifest.py@@ -1,6 +1,7 @@from __future__ import annotationsfrom collections.abc import Mapping+from copy import deepcopyfrom dataclasses import fieldfrom types import MappingProxyTypefrom typing import Any@@ -32,7 +33,9 @@ from posthog.hogql.database.models import (from posthog.hogql.database.trino_locator import TrinoTableLocatorfrom posthog.hogql.parser import parse_expr, parse_selectfrom posthog.hogql.placeholders import find_placeholders-from posthog.hogql.printer.utils import prepare_and_print_ast, print_prepared_ast+from posthog.hogql.printer.trino_hogql import TrinoHogQLPrinter+from posthog.hogql.printer.utils import prepare_and_print_ast+from posthog.hogql.resolver import resolve_typesfrom posthog.hogql.resolver_utils import extract_select_queriesfrom posthog.hogql.transforms.trino.errors import TrinoLoweringErrorfrom posthog.hogql.visitor import TraversingVisitor, clone_expr@@ -54,6 +57,7 @@ class TrinoManifestTable:logical_name: strlocator: TrinoTableLocatorcolumns: tuple[TrinoManifestColumn, ...] = ()+ field_overrides: Mapping[str, DatabaseField] = field(default_factory=dict)@frozen@@ -221,7 +225,7 @@ def build_trino_manifest_database(manifest: TrinoCatalogManifest) -> tuple[Datablocators[table.logical_name] = table.locatorif table.logical_name in _CORE_TABLES:- if table.columns:+ if table.columns or table.field_overrides:raise TrinoLoweringError("TRINO_PURE_INVALID_MANIFEST","core table manifest",@@ -237,6 +241,7 @@ def build_trino_manifest_database(manifest: TrinoCatalogManifest) -> tuple[Datab"manifest columns",detail=f"Manifest table `{table.logical_name}` must declare unique columns.",)+ columns.update(deepcopy(dict(table.field_overrides)))direct_table = DirectTrinoTable(name=chain[-1],fields=columns,@@ -415,7 +420,8 @@ def transpile_hogql_to_trino_with_database(print_columns: list[str] = []if include_hogql:hogql_context = create_context()- hogql, prepared_hogql = prepare_and_print_ast(clone_expr(node), hogql_context, dialect="hogql")+ prepared_hogql = resolve_types(clone_expr(node), hogql_context, dialect="trino")+ hogql = TrinoHogQLPrinter(context=hogql_context).visit(prepared_hogql)if isinstance(prepared_hogql, ast.SelectQuery | ast.SelectSetQuery):columns_query = (next(extract_select_queries(prepared_hogql))@@ -426,10 +432,8 @@ def transpile_hogql_to_trino_with_database(if isinstance(select_node, ast.Alias):print_columns.append(select_node.alias)else:- stack = [prepared_hogql] if isinstance(prepared_hogql, ast.SelectQuery) else None- print_columns.append(- print_prepared_ast(node=select_node, context=hogql_context, dialect="hogql", stack=stack)- )+ stack: list[ast.AST] = [prepared_hogql] if isinstance(prepared_hogql, ast.SelectQuery) else []+ print_columns.append(TrinoHogQLPrinter(context=hogql_context, stack=stack).visit(select_node))sql, _ = prepare_and_print_ast(node, context, dialect="trino", pretty=pretty)return TrinoManifestTranspilerResult(sql=sql, values=dict(context.values), hogql=hogql, print_columns=tuple(print_columns)diff --git a/posthog/hogql/transforms/trino/normalize.py b/posthog/hogql/transforms/trino/normalize.pyindex 0d8e1b4ae67c..bd1ce1fe3da2 100644--- a/posthog/hogql/transforms/trino/normalize.py+++ b/posthog/hogql/transforms/trino/normalize.py@@ -1,14 +1,21 @@+from typing import TypeVar+from posthog.hogql import astfrom posthog.hogql.context import HogQLContext+from posthog.hogql.database.models import DatabaseFieldfrom posthog.hogql.database.schema.numbers import NumbersTablefrom posthog.hogql.database.trino_unnest_table import TRINO_UNNEST_TABLE_NAMEfrom posthog.hogql.transforms.trino.any_join import lower_trino_any_joins+from posthog.hogql.transforms.trino.asof_join import TrinoAsOfJoinLowererfrom posthog.hogql.transforms.trino.errors import TrinoLoweringErrorfrom posthog.hogql.transforms.trino.expressions import expression_key, positional_index+from posthog.hogql.transforms.trino.limits import TrinoCompilationBudgetfrom posthog.hogql.transforms.trino.query_wrappers import lower_trino_query_wrappers-from posthog.hogql.visitor import CloningVisitor, TraversingVisitor+from posthog.hogql.visitor import CloningVisitor, TraversingVisitor, clone_expr++_T_AST = TypeVar("_T_AST", bound=ast.AST | None)-_MAX_NUMBERS_ROWS = 10_000_000+_MAX_NUMBERS_ROWS = 10_000_EVENT_PROPERTY_BACKED_FIELDS = frozenset({"$session_id", "$window_id", "$group_0", "$group_1", "$group_2", "$group_3", "$group_4"})@@ -38,15 +45,116 @@ def _wrap_unnest_elements(array_expr: ast.Expr, lambda_name: str) -> ast.Call:)+class TrinoUnpivotLowerer(CloningVisitor):+ def __init__(self, context: HogQLContext) -> None:+ super().__init__(clear_types=False)+ self.context = context+ self.index = 0++ def visit_unpivot_expr(self, node: ast.UnpivotExpr) -> ast.SelectQuery:+ lowered = super().visit_unpivot_expr(node)+ if len(lowered.columns) != 1 or not isinstance(lowered.type, ast.SelectQueryType):+ raise TrinoLoweringError(+ "TRINO_UNPIVOT_SHAPE_UNSUPPORTED", "UNPIVOT without a resolved single column group", node+ )+ column = lowered.columns[0]+ if not isinstance(column.value_columns, ast.Field) or not isinstance(column.name_columns, ast.Field):+ raise TrinoLoweringError("TRINO_UNPIVOT_SHAPE_UNSUPPORTED", "UNPIVOT tuple outputs", node)+ value_name = str(column.value_columns.chain[-1])+ label_name = str(column.name_columns.chain[-1])+ if value_name == label_name or not column.unpivot_values:+ raise TrinoLoweringError(+ "TRINO_UNPIVOT_SHAPE_UNSUPPORTED", "UNPIVOT without distinct output names or inputs", node+ )+ rows: list[ast.Expr] = []+ value_types: set[type[ast.ConstantType]] = set()+ for value in column.unpivot_values:+ if not isinstance(value, ast.Field):+ raise TrinoLoweringError("TRINO_UNPIVOT_SHAPE_UNSUPPORTED", "UNPIVOT input that is not a field", value)+ value_type = value.type.resolve_constant_type(self.context) if value.type else ast.UnknownType()+ if not isinstance(value_type, ast.UnknownType):+ value_types.add(type(value_type))+ binding = value.type+ while isinstance(binding, ast.FieldAliasType):+ binding = binding.type+ label = binding.name if isinstance(binding, ast.FieldType) else str(value.chain[-1])+ rows.append(ast.Call(name="tuple", args=[value, ast.Constant(value=label)]))+ if len(value_types) > 1 and not value_types <= {ast.IntegerType, ast.FloatType}:+ raise TrinoLoweringError("TRINO_UNPIVOT_TYPE_UNSUPPORTED", "UNPIVOT with incompatible value types", node)+ if isinstance(lowered.table, ast.JoinExpr):+ source = lowered.table+ elif isinstance(+ lowered.table,+ (ast.Field, ast.SelectQuery, ast.SelectSetQuery, ast.ValuesQuery, ast.UnpivotExpr, ast.PivotExpr),+ ):+ source = ast.JoinExpr(table=lowered.table)+ else:+ raise TrinoLoweringError("TRINO_UNPIVOT_SOURCE_UNSUPPORTED", "UNPIVOT without a table source", node)+ alias = f"__hogql_unpivot_{self.index}"+ self.index += 1+ aliases: set[str] = set()+ relation: ast.JoinExpr | None = source+ while relation is not None:+ if relation.alias is not None:+ aliases.add(relation.alias)+ elif isinstance(relation.table, ast.Field) and isinstance(relation.table.chain[-1], str):+ aliases.add(relation.table.chain[-1])+ relation = relation.next_join+ while alias in aliases:+ alias += "_"+ final_join = source+ while final_join.next_join is not None:+ final_join = final_join.next_join+ final_join.next_join = ast.JoinExpr(+ join_type="CROSS JOIN",+ table=ast.Field(chain=[TRINO_UNNEST_TABLE_NAME]),+ table_args=[ast.Array(exprs=rows)],+ alias=alias,+ column_aliases=[value_name, label_name],+ )+ return ast.SelectQuery(+ type=lowered.type,+ select=[+ ast.Field(chain=[alias, name]) if name in {value_name, label_name} else ast.Field(chain=[name])+ for name in lowered.type.columns+ ],+ select_from=source,+ where=(+ None+ if lowered.include_nulls+ else ast.Call(name="isNotNull", args=[ast.Field(chain=[alias, value_name])])+ ),+ )++class TrinoPhysicalFieldLowerer(CloningVisitor):- def __init__(self) -> None:+ def __init__(self, context: HogQLContext) -> None:super().__init__(clear_types=False)+ self.context = context+ self.scopes: list[ast.SelectQueryType] = []++ def visit_select_query(self, node: ast.SelectQuery) -> ast.SelectQuery:+ if not isinstance(node.type, ast.SelectQueryType):+ return super().visit_select_query(node)+ self.scopes.append(node.type)+ try:+ return super().visit_select_query(node)+ finally:+ self.scopes.pop()++ def _source_alias(self, table_type: ast.TableOrSelectType) -> str | None:+ for scope in reversed(self.scopes):+ for alias, source_type in scope.tables.items():+ if source_type is table_type:+ return alias+ return Nonedef visit_field(self, node: ast.Field) -> ast.Expr:field_type = node.typewhile isinstance(field_type, ast.FieldAliasType):field_type = field_type.type- table_type = field_type.table_type if isinstance(field_type, ast.FieldType) else None+ source_type = field_type.table_type if isinstance(field_type, ast.FieldType) else None+ table_type = source_typewhile isinstance(table_type, (ast.TableAliasType, ast.ColumnAliasedTableType)):table_type = table_type.table_typeis_events_field = (@@ -81,6 +189,17 @@ class TrinoPhysicalFieldLowerer(CloningVisitor):name="arrayDistinct",args=[ast.Call(name="extractAll", args=[source, ast.Constant(value=pattern)])],)+ if isinstance(field_type, ast.FieldType) and isinstance(table_type, ast.TableType):+ database_field = field_type.resolve_database_field(self.context)+ if isinstance(database_field, DatabaseField) and database_field.name != field_type.name:+ lowered = super().visit_field(node)+ lowered.chain[-1] = database_field.name+ if len(lowered.chain) == 1 and source_type is not None:+ # The second resolver pass cannot recover the source of a renamed bare field.+ source_alias = self._source_alias(source_type)+ if source_alias is not None:+ lowered.chain.insert(0, source_alias)+ return loweredreturn super().visit_field(node)@@ -102,15 +221,59 @@ class TrinoSemanticCallLowerer(CloningVisitor):)+class TrinoScalarCTELowerer(CloningVisitor):+ def __init__(self, budget: TrinoCompilationBudget) -> None:+ super().__init__(clear_types=False)+ self.scalar_ctes: dict[str, ast.Expr] = {}+ self.expansion_budget = budget++ def visit_select_query(self, node: ast.SelectQuery) -> ast.SelectQuery:+ outer_scalar_ctes = self.scalar_ctes+ self.scalar_ctes = dict(outer_scalar_ctes)+ try:+ for name, cte in (node.ctes or {}).items():+ if cte.cte_type == "column":+ self.scalar_ctes[name] = self.visit(cte.expr)+ lowered = super().visit_select_query(node)+ if lowered.ctes:+ lowered.ctes = {name: cte for name, cte in lowered.ctes.items() if cte.cte_type == "subquery"}+ if not lowered.ctes:+ lowered.ctes = None+ return lowered+ finally:+ self.scalar_ctes = outer_scalar_ctes++ def visit_field(self, node: ast.Field) -> ast.Expr:+ if (+ isinstance(node.type, ast.FieldAliasType)+ and len(node.chain) == 1+ and isinstance(node.chain[0], str)+ and node.chain[0] in self.scalar_ctes+ ):+ self.expansion_budget.visit(self.scalar_ctes[node.chain[0]])+ return clone_expr(self.scalar_ctes[node.chain[0]], clear_types=False)+ return super().visit_field(node)++class TrinoSelectAliasLowerer(CloningVisitor):- def __init__(self) -> None:+ def __init__(self, budget: TrinoCompilationBudget) -> None:super().__init__(clear_types=False)self.aliases: dict[str, ast.Expr] = {}+ self.alias_positions: dict[str, int] = {}self.expanding: set[str] = set()+ self.expansion_budget = budget++ def visit(self, node: _T_AST) -> _T_AST:+ self.expansion_budget.consume_node(node)+ return super().visit(node)def visit_select_query(self, node: ast.SelectQuery) -> ast.SelectQuery:outer_aliases = self.aliases+ outer_alias_positions = self.alias_positionsself.aliases = {expr.alias: expr.expr for expr in node.select if isinstance(expr, ast.Alias)}+ self.alias_positions = {+ expr.alias: index for index, expr in enumerate(node.select, start=1) if isinstance(expr, ast.Alias)+ }lowered = super().visit_select_query(node)if node.group_by is not None and lowered.group_by is not None and lowered.group_by_mode is None:projections = [expression_key(expr) for expr in lowered.select]@@ -137,7 +300,52 @@ class TrinoSelectAliasLowerer(CloningVisitor):and (position := alias_positions.get(expr.chain[0])) is not None):order.expr = ast.PositionalRef(index=position)+ for order in lowered.order_by or []:+ order_expression = order.expr+ while isinstance(order_expression, ast.Alias) and order_expression.hidden:+ order_expression = order_expression.expr+ if (+ isinstance(order_expression, ast.Field)+ and len(order_expression.chain) > 1+ and isinstance(order_expression.chain[0], str)+ and order_expression.chain[0] in self.aliases+ and isinstance(order_expression.chain[-1], str)+ and order_expression.chain[-1] in self.aliases+ ):+ order.expr = ast.PositionalRef(index=self.alias_positions[order_expression.chain[-1]])self.aliases = outer_aliases+ self.alias_positions = outer_alias_positions+ return lowered++ def visit_alias(self, node: ast.Alias) -> ast.Alias:+ if node.hidden:+ self.expansion_budget.visit(node)+ return clone_expr(node, clear_types=False)+ already_expanding = node.alias in self.expanding+ self.expanding.add(node.alias)+ try:+ return super().visit_alias(node)+ finally:+ if not already_expanding:+ self.expanding.remove(node.alias)++ def visit_join_expr(self, node: ast.JoinExpr) -> ast.JoinExpr:+ outer_aliases = self.aliases+ next_join = node.next_join+ node.next_join = None+ self.aliases = {}+ try:+ lowered = super().visit_join_expr(node)+ finally:+ self.aliases = outer_aliases+ node.next_join = next_join+ if node.table_args is not None:+ lowered.table_args = []+ for argument in node.table_args:+ while isinstance(argument, ast.Alias) and argument.hidden:+ argument = argument.expr+ lowered.table_args.append(self.visit(argument))+ lowered.next_join = self.visit(next_join) if next_join is not None else Nonereturn lowereddef visit_field(self, node: ast.Field) -> ast.Expr:@@ -157,6 +365,33 @@ class TrinoSelectAliasLowerer(CloningVisitor):return super().visit_field(node)+class TrinoPhysicalProjectionAliasLowerer(CloningVisitor):+ def __init__(self, context: HogQLContext) -> None:+ super().__init__(clear_types=False)+ self.context = context++ def visit_select_query(self, node: ast.SelectQuery) -> ast.SelectQuery:+ lowered = super().visit_select_query(node)+ for projection in lowered.select:+ if not isinstance(projection, ast.Alias) or not projection.hidden:+ continue+ expression = projection.expr+ while isinstance(expression, ast.Alias) and expression.hidden:+ expression = expression.expr+ if not isinstance(expression, ast.Field):+ projection.hidden = False+ continue+ field_type = projection.expr.type+ while isinstance(field_type, ast.FieldAliasType):+ field_type = field_type.type+ if not isinstance(field_type, ast.FieldType):+ continue+ database_field = field_type.resolve_database_field(self.context)+ if isinstance(database_field, DatabaseField) and database_field.name != projection.alias:+ projection.hidden = False+ return lowered++class TrinoArrayJoinFunctionLowerer(CloningVisitor):def __init__(self, context: HogQLContext) -> None:super().__init__(clear_types=False)@@ -215,33 +450,82 @@ class TrinoNormalizer(TraversingVisitor):def _lower_array_join(self, node: ast.SelectQuery) -> None:if node.array_join_op is None and not node.array_join_list:return- if node.array_join_op not in {"ARRAY JOIN", "INNER ARRAY JOIN"}:+ if node.array_join_op not in {"ARRAY JOIN", "INNER ARRAY JOIN", "LEFT ARRAY JOIN"}:raise TrinoLoweringError("TRINO_ARRAY_JOIN_MODE_UNSUPPORTED", node.array_join_op or "ARRAY JOIN without an operation", node)- if node.array_join_list is None or len(node.array_join_list) != 1:- raise TrinoLoweringError("TRINO_ARRAY_JOIN_MULTIPLE_ARRAYS_UNSUPPORTED", "multiple-array ARRAY JOIN", node)- array_expr = node.array_join_list[0]- if not isinstance(array_expr, ast.Alias):+ if not node.array_join_list or not all(+ isinstance(array_expr, ast.Alias) for array_expr in node.array_join_list+ ):raise TrinoLoweringError("TRINO_ARRAY_JOIN_ALIAS_REQUIRED", "ARRAY JOIN without an output alias", node)- if node.select_from is None:- raise TrinoLoweringError("TRINO_ARRAY_JOIN_RELATION_REQUIRED", "ARRAY JOIN without a FROM relation", node)+ array_exprs = [array_expr for array_expr in node.array_join_list if isinstance(array_expr, ast.Alias)]table_name = f"__trino_unnest_{self.unnest_index}"self.unnest_index += 1- final_join = node.select_from- while final_join.next_join is not None:- final_join = final_join.next_join- final_join.next_join = ast.JoinExpr(- join_type="CROSS JOIN",+ elements: ast.Expr = (+ _wrap_unnest_elements(array_exprs[0].expr, f"{table_name}_value")+ if len(array_exprs) == 1+ else ast.Call(name="arrayZip", args=[array_expr.expr for array_expr in array_exprs])+ )+ if node.array_join_op == "LEFT ARRAY JOIN":+ defaults = []+ for array_expr in array_exprs:+ array_type = array_expr.expr.type.resolve_constant_type(self.context) if array_expr.expr.type else None+ if not isinstance(array_type, ast.ArrayType):+ raise TrinoLoweringError(+ "TRINO_ARRAY_JOIN_DEFAULT_TYPE_REQUIRED",+ "LEFT ARRAY JOIN without an array item type",+ array_expr,+ )+ defaults.append(self._array_default(array_type.item_type))+ elements = ast.Call(+ name="if",+ args=[+ ast.Call(name="empty", args=[elements]),+ ast.Array(exprs=[ast.Call(name="tuple", args=defaults)]),+ elements,+ ],+ )+ unnest = ast.JoinExpr(table=ast.Field(chain=[TRINO_UNNEST_TABLE_NAME]),- table_args=[_wrap_unnest_elements(array_expr.expr, f"{table_name}_value")],+ table_args=[elements],alias=table_name,- column_aliases=[array_expr.alias],+ column_aliases=[array_expr.alias for array_expr in array_exprs],)+ final_join = node.select_from+ if final_join is None:+ node.select_from = unnest+ else:+ while final_join.next_join is not None:+ final_join = final_join.next_join+ unnest.join_type = "CROSS JOIN"+ final_join.next_join = unnestnode.array_join_op = Nonenode.array_join_list = None+ def _array_default(self, item_type: ast.ConstantType) -> ast.Expr:+ if isinstance(item_type, ast.UnknownType) and item_type.unanalyzable:+ raise TrinoLoweringError(+ "TRINO_ARRAY_JOIN_DEFAULT_TYPE_REQUIRED", "LEFT ARRAY JOIN with an unknown item type"+ )+ if item_type.nullable:+ return ast.Constant(value=None)+ if isinstance(item_type, ast.StringType):+ return ast.Constant(value="")+ if isinstance(item_type, ast.IntegerType):+ return ast.Constant(value=0)+ if isinstance(item_type, ast.FloatType):+ return ast.Constant(value=0.0)+ if isinstance(item_type, ast.BooleanType):+ return ast.Constant(value=False)+ if isinstance(item_type, ast.ArrayType):+ return ast.Array(exprs=[])+ if isinstance(item_type, ast.TupleType):+ return ast.Call(name="tuple", args=[self._array_default(nested) for nested in item_type.item_types])+ raise TrinoLoweringError("TRINO_ARRAY_JOIN_DEFAULT_TYPE_UNSUPPORTED", item_type.print_type())+def visit_join_expr(self, node: ast.JoinExpr) -> None:+ if node.join_type is not None and node.join_type.startswith("GLOBAL "):+ node.join_type = node.join_type.removeprefix("GLOBAL ")if node.join_type in _ALL_JOIN_TYPES:node.join_type = _ALL_JOIN_TYPES[node.join_type]table_type = node.type@@ -262,29 +546,53 @@ class TrinoNormalizer(TraversingVisitor):def _lower_numbers_args(self, args: list[ast.Expr] | None) -> ast.Call:if args is None or len(args) not in {1, 2}:raise TrinoLoweringError("TRINO_NUMBERS_ARGUMENT_COUNT", "numbers with other than one or two arguments")- values: list[int] = []- for arg in args:- if not isinstance(arg, ast.Constant) or isinstance(arg.value, bool) or not isinstance(arg.value, int):+ if all(+ isinstance(arg, ast.Constant) and not isinstance(arg.value, bool) and isinstance(arg.value, int)+ for arg in args+ ):+ values = [arg.value for arg in args if isinstance(arg, ast.Constant) and isinstance(arg.value, int)]+ constant_start, constant_count = (0, values[0]) if len(values) == 1 else values+ if constant_count < 0:+ raise TrinoLoweringError("TRINO_NUMBERS_NEGATIVE_ROW_COUNT", "numbers with a negative row count")+ if constant_count > _MAX_NUMBERS_ROWS:raise TrinoLoweringError(- "TRINO_NUMBERS_NON_CONSTANT_ARGUMENT", "numbers requires constant integer arguments", arg+ "TRINO_NUMBERS_ROW_LIMIT_EXCEEDED", f"numbers above the {_MAX_NUMBERS_ROWS:,}-row limit")- values.append(arg.value)- start, count = (0, values[0]) if len(values) == 1 else values- if count < 0:- raise TrinoLoweringError("TRINO_NUMBERS_NEGATIVE_ROW_COUNT", "numbers with a negative row count")- if count > _MAX_NUMBERS_ROWS:- raise TrinoLoweringError(- "TRINO_NUMBERS_ROW_LIMIT_EXCEEDED", f"numbers above the {_MAX_NUMBERS_ROWS:,}-row limit"+ return ast.Call(+ name="range",+ args=[ast.Constant(value=constant_start), ast.Constant(value=constant_start + constant_count)],)- return ast.Call(name="range", args=[ast.Constant(value=start), ast.Constant(value=start + count)])++ start_expr = ast.Constant(value=0) if len(args) == 1 else args[0]+ count_expr = args[-1]+ bounded_count = ast.Call(+ name="least",+ args=[+ ast.Call(name="greatest", args=[ast.Call(name="toInt", args=[count_expr]), ast.Constant(value=0)]),+ ast.Constant(value=_MAX_NUMBERS_ROWS),+ ],+ )+ return ast.Call(+ name="range",+ args=[+ start_expr,+ ast.ArithmeticOperation(op=ast.ArithmeticOperationOp.Add, left=start_expr, right=bounded_count),+ ],+ )def normalize_trino_ast(node: ast.AST, context: HogQLContext) -> ast.AST:- lowered = TrinoArrayJoinFunctionLowerer(context).visit(node)- lowered = TrinoPhysicalFieldLowerer().visit(lowered)+ budget = TrinoCompilationBudget()+ budget.visit(node)+ lowered = TrinoScalarCTELowerer(budget).visit(node)+ lowered = TrinoUnpivotLowerer(context).visit(lowered)+ lowered = TrinoArrayJoinFunctionLowerer(context).visit(lowered)+ lowered = TrinoPhysicalFieldLowerer(context).visit(lowered)lowered = TrinoSemanticCallLowerer().visit(lowered)+ lowered = TrinoAsOfJoinLowerer().visit(lowered)lowered = lower_trino_any_joins(lowered)lowered = lower_trino_query_wrappers(lowered)- lowered = TrinoSelectAliasLowerer().visit(lowered)+ lowered = TrinoSelectAliasLowerer(budget).visit(lowered)+ lowered = TrinoPhysicalProjectionAliasLowerer(context).visit(lowered)TrinoNormalizer(context).visit(lowered)return lowereddiff --git a/posthog/hogql/transforms/trino/pivot.py b/posthog/hogql/transforms/trino/pivot.pynew file mode 100644index 000000000000..201a3967644d--- /dev/null+++ b/posthog/hogql/transforms/trino/pivot.py@@ -0,0 +1,79 @@+from posthog.hogql import ast+from posthog.hogql.transforms.trino.errors import TrinoLoweringError+from posthog.hogql.visitor import TraversingVisitor, clone_expr+++class TrinoPivotLowerer:+ def lower(self, node: ast.PivotExpr, source_columns: list[str]) -> ast.SelectQuery:+ if len(node.columns) != 1 or len(node.aggregates) != 1:+ raise TrinoLoweringError("TRINO_PIVOT_SHAPE_UNSUPPORTED", "PIVOT with multiple keys or aggregates", node)+ column = node.columns[0]+ key = column.column+ while isinstance(key, ast.Alias) and key.hidden:+ key = key.expr+ aggregate = node.aggregates[0]+ suffix = ""+ if isinstance(aggregate, ast.Alias):+ suffix = f"_{aggregate.alias}"+ aggregate = aggregate.expr+ if not isinstance(aggregate, ast.Call) or aggregate.name.lower() not in {"count", "sum", "avg", "min", "max"}:+ raise TrinoLoweringError("TRINO_PIVOT_AGGREGATE_UNSUPPORTED", "PIVOT without a standard aggregate", node)+ if not isinstance(key, ast.Field) or not column.values:+ raise TrinoLoweringError(+ "TRINO_PIVOT_SHAPE_UNSUPPORTED", "PIVOT without a field key and static values", node+ )+ consumed: set[str] = set()++ class ConsumedFields(TraversingVisitor):+ def visit_field(self, field: ast.Field) -> None:+ consumed.add(str(field.chain[-1]))++ finder = ConsumedFields()+ finder.visit(key)+ finder.visit(aggregate)+ groups: list[ast.Expr] = (+ list(node.group_by)+ if node.group_by is not None+ else [ast.Field(chain=[name]) for name in source_columns if name not in consumed]+ )+ for index, group in enumerate(groups):+ while isinstance(group, ast.Alias) and group.hidden:+ group = group.expr+ groups[index] = group+ if not all(isinstance(group, ast.Field) for group in groups):+ raise TrinoLoweringError("TRINO_PIVOT_GROUP_UNSUPPORTED", "PIVOT with a computed grouping key", node)+ names = {str(group.chain[-1]).casefold() for group in groups if isinstance(group, ast.Field)}+ projections = list(groups)+ for value in column.values:+ name = None+ if isinstance(value, ast.Alias):+ name = value.alias+ value = value.expr+ if (+ not isinstance(value, ast.Constant)+ or not isinstance(value.value, (str, int))+ or isinstance(value.value, bool)+ ):+ raise TrinoLoweringError(+ "TRINO_PIVOT_VALUE_UNSUPPORTED", "PIVOT with a non-string or non-integer value", value+ )+ name = f"{name if name is not None else value.value}{suffix}"+ if name.casefold() in names:+ raise TrinoLoweringError("TRINO_PIVOT_OUTPUT_COLLISION", "PIVOT with duplicate output names", node)+ names.add(name.casefold())+ filtered = clone_expr(aggregate, clear_types=False)+ predicate = ast.CompareOperation(left=key, op=ast.CompareOperationOp.Eq, right=value)+ filtered.filter_expr = (+ ast.And(exprs=[filtered.filter_expr, predicate]) if filtered.filter_expr is not None else predicate+ )+ projections.append(ast.Alias(alias=name, expr=filtered))+ if isinstance(node.table, ast.JoinExpr):+ source = node.table+ elif isinstance(+ node.table,+ (ast.Field, ast.SelectQuery, ast.SelectSetQuery, ast.ValuesQuery, ast.UnpivotExpr, ast.PivotExpr),+ ):+ source = ast.JoinExpr(table=node.table)+ else:+ raise TrinoLoweringError("TRINO_PIVOT_SOURCE_UNSUPPORTED", "PIVOT without a table source", node)+ return ast.SelectQuery(select=projections, select_from=source, group_by=groups or None)diff --git a/posthog/hogql/transforms/trino/query_wrappers.py b/posthog/hogql/transforms/trino/query_wrappers.pyindex 44dd7ded2e18..fa7e7716e1b2 100644--- a/posthog/hogql/transforms/trino/query_wrappers.py+++ b/posthog/hogql/transforms/trino/query_wrappers.py@@ -1,7 +1,7 @@from posthog.hogql import astfrom posthog.hogql.functions.mapping import find_hogql_aggregationfrom posthog.hogql.transforms.trino.errors import TrinoLoweringError-from posthog.hogql.transforms.trino.expressions import expression_key, positional_index+from posthog.hogql.transforms.trino.expressions import constant_integer, expression_key, positional_indexfrom posthog.hogql.visitor import CloningVisitor, TraversingVisitor@@ -33,40 +33,175 @@ class TrinoQueryWrapperLowerer(CloningVisitor):def visit_select_query(self, node: ast.SelectQuery) -> ast.SelectQuery:lowered = super().visit_select_query(node)- if lowered.qualify is not None and lowered.limit_by is not None:- raise TrinoLoweringError("TRINO_QUALIFY_LIMIT_BY_UNSUPPORTED", "combined QUALIFY and LIMIT BY", node)+ if lowered.limit_by is not None:+ finder = _WindowFunctionFinder()+ for expr in lowered.limit_by.exprs:+ finder.visit(self._input_expression(expr, lowered.select))+ for order in lowered.order_by or []:+ finder.visit(self._input_expression(order.expr, lowered.select))+ if lowered.qualify is not None or finder.found:+ lowered = self._stage_limit_by(lowered)if lowered.qualify is not None:lowered = self._lower_qualify(lowered)if lowered.limit_by is not None:lowered = self._lower_limit_by(lowered)+ if lowered.limit_percent:+ lowered = self._lower_limit_percent(lowered)return lowered+ def _lower_limit_percent(self, node: ast.SelectQuery) -> ast.SelectQuery:+ if (+ not isinstance(node.limit, ast.Constant)+ or isinstance(node.limit.value, bool)+ or not isinstance(node.limit.value, (int, float))+ or not 0 <= node.limit.value <= 100+ or node.limit_with_ties+ ):+ raise TrinoLoweringError(+ "TRINO_LIMIT_PERCENT_UNSUPPORTED", "LIMIT PERCENT without a constant percentage, or with ties", node+ )+ percentage = node.limit.value / 100+ offset = self._non_negative_integer(node.offset, "percentage offset", default=0)+ node.limit = None+ node.offset = None+ node.limit_percent = False+ staged = self._wrap(node, ast.Constant(value=True))+ window_order = [+ ast.OrderExpr(expr=self._input_expression(order.expr, staged.select), order=order.order)+ for order in staged.order_by or []+ ]+ row_number = ast.WindowFunction(+ name="row_number", exprs=[], over_expr=ast.WindowExpr(order_by=window_order or None)+ )+ count = ast.WindowFunction(name="count", exprs=[], over_expr=ast.WindowExpr())+ upper_bound = ast.ArithmeticOperation(+ left=ast.Constant(value=offset),+ op=ast.ArithmeticOperationOp.Add,+ right=ast.Call(+ name="ceil",+ args=[+ ast.ArithmeticOperation(+ left=count, op=ast.ArithmeticOperationOp.Mult, right=ast.Constant(value=percentage)+ )+ ],+ ),+ )+ predicate: ast.Expr = ast.CompareOperation(left=row_number, op=ast.CompareOperationOp.LtEq, right=upper_bound)+ if offset:+ predicate = ast.And(+ exprs=[+ ast.CompareOperation(+ left=row_number, op=ast.CompareOperationOp.Gt, right=ast.Constant(value=offset)+ ),+ predicate,+ ]+ )+ helper_name = self._helper_name(staged, f"__hogql_percent_{self.wrapper_index}")+ staged.select.append(ast.Alias(alias=helper_name, expr=predicate))+ return self._wrap(staged, ast.Field(chain=[helper_name]), helper_name=helper_name)++ def _stage_limit_by(self, node: ast.SelectQuery) -> ast.SelectQuery:+ assert node.limit_by is not None+ if any(order.with_fill is not None for order in node.order_by or []):+ raise TrinoLoweringError("TRINO_WITH_FILL_UNSUPPORTED", "WITH FILL in a staged LIMIT BY query", node)+ output_names = self._output_names(node)+ visible_count = len(output_names)+ limit_by = node.limit_by+ node.limit_by = None+ columns = dict(node.type.columns) if node.type is not None else {}+ node.type = ast.SelectQueryType(columns=columns)++ def project(expr: ast.Expr) -> str:+ expression = self._input_expression(expr, node.select[:visible_count])+ key = expression_key(expression)+ for name, projection in zip(columns, node.select, strict=True):+ if expression_key(self._input_expression(projection, node.select)) == key:+ return name+ if node.distinct:+ raise TrinoLoweringError(+ "TRINO_LIMIT_BY_DISTINCT_PARTITION_NOT_PROJECTED",+ "DISTINCT LIMIT BY stage with an unprojected expression",+ expr,+ )+ name = self._helper_name(node, f"__hogql_stage_{len(columns)}")+ node.select.append(ast.Alias(alias=name, expr=expression))+ columns[name] = expression.type or ast.UnknownType()+ return name++ partition_names = [project(expr) for expr in limit_by.exprs]+ ordering = [(project(order.expr), order.order) for order in node.order_by or []]+ node.order_by = None+ staged = self._lower_qualify(node) if node.qualify is not None else self._wrap(node, ast.Constant(value=True))+ assert staged.select_from is not None+ source_alias = staged.select_from.alias+ assert source_alias is not None+ staged.limit_by = ast.LimitByExpr(+ n=limit_by.n,+ offset_value=limit_by.offset_value,+ exprs=[ast.Field(chain=[source_alias, name]) for name in partition_names],+ )+ staged.order_by = [+ ast.OrderExpr(expr=ast.Field(chain=[source_alias, name]), order=order) for name, order in ordering+ ] or None+ result = self._lower_limit_by(staged)+ result.select = result.select[:visible_count]+ result.type = ast.SelectQueryType(columns={name: columns[name] for name in output_names})+ return result+def _lower_qualify(self, node: ast.SelectQuery) -> ast.SelectQuery:assert node.qualify is not Nonefinder = _WindowFunctionFinder()finder.visit(node.qualify)- if finder.found:- raise TrinoLoweringError(- "TRINO_QUALIFY_WINDOW_NOT_PROJECTED",- "QUALIFY window expression without a projected alias",- node.qualify,- )predicate = node.qualifynode.qualify = None- return self._wrap(node, predicate)+ output_names = self._output_names(node)+ projection_keys = [expression_key(self._input_expression(expr, node.select)) for expr in node.select]++ class ProjectedPredicate(CloningVisitor):+ def visit_field(self, field: ast.Field) -> ast.Field:+ if (+ isinstance(field.type, ast.FieldAliasType)+ and len(field.chain) == 1+ and field.chain[0] in output_names+ ):+ return ast.Field(chain=list(field.chain))+ key = expression_key(field)+ if key in projection_keys:+ return ast.Field(chain=[output_names[projection_keys.index(key)]])+ raise TrinoLoweringError("TRINO_QUALIFY_HELPER_REQUIRED", "QUALIFY with an unprojected field", field)++ projected_predicate = predicate+ try:+ projected_predicate = ProjectedPredicate(clear_types=False).visit(predicate)+ needs_helper = finder.found+ except TrinoLoweringError:+ needs_helper = True+ if not needs_helper:+ return self._wrap(node, projected_predicate)+ if node.distinct:+ self._outer_order_by(node, output_names, "")+ helper_name = self._helper_name(node, f"__hogql_qualify_{self.wrapper_index}")+ node.select.append(ast.Alias(alias=helper_name, expr=predicate))+ distinct = node.distinct+ node.distinct = False+ result = self._wrap(node, ast.Field(chain=[helper_name]), helper_name=helper_name)+ result.distinct = distinct+ return resultdef _lower_limit_by(self, node: ast.SelectQuery) -> ast.SelectQuery:assert node.limit_by is not Noneif node.distinct:- raise TrinoLoweringError("TRINO_LIMIT_BY_DISTINCT_UNSUPPORTED", "LIMIT BY with DISTINCT", node)- n = self._non_negative_integer(node.limit_by.n, "LIMIT BY count")- offset = self._non_negative_integer(node.limit_by.offset_value, "LIMIT BY offset", default=0)+ node = self._wrap_distinct_limit_by_input(node)+ limit_by = node.limit_by+ assert limit_by is not None+ n = self._non_negative_integer(limit_by.n, "LIMIT BY count")+ offset = self._non_negative_integer(limit_by.offset_value, "LIMIT BY offset", default=0)helper_name = self._helper_name(node, f"__hogql_limit_by_row_{self.wrapper_index}")row_number = ast.WindowFunction(name="row_number",exprs=[],over_expr=ast.WindowExpr(- partition_by=[self._input_expression(expr, node.select) for expr in node.limit_by.exprs],+ partition_by=[self._input_expression(expr, node.select) for expr in limit_by.exprs],order_by=([ast.OrderExpr(expr=self._input_expression(order.expr, node.select), order=order.order)@@ -105,6 +240,60 @@ class TrinoQueryWrapperLowerer(CloningVisitor):)return self._wrap(node, predicate, helper_name=helper_name)+ def _wrap_distinct_limit_by_input(self, node: ast.SelectQuery) -> ast.SelectQuery:+ assert node.limit_by is not None+ output_names = self._output_names(node)+ selected_expressions = [self._input_expression(expr, node.select) for expr in node.select]+ projection_keys = [expression_key(expr) for expr in selected_expressions]+ source_alias = f"__hogql_trino_distinct_{self.wrapper_index}"+ self.wrapper_index += 1++ partition_by: list[ast.Expr] = []+ for expr in node.limit_by.exprs:+ key = expression_key(self._input_expression(expr, node.select))+ if key not in projection_keys:+ raise TrinoLoweringError(+ "TRINO_LIMIT_BY_DISTINCT_PARTITION_NOT_PROJECTED",+ "DISTINCT LIMIT BY expression not present in SELECT",+ expr,+ )+ partition_by.append(ast.Field(chain=[source_alias, output_names[projection_keys.index(key)]]))++ node.select = [+ expr+ if isinstance(expr, ast.Alias) and expr.alias == name and not expr.hidden+ else ast.Alias(alias=name, expr=expr)+ for expr, name in zip(node.select, output_names, strict=True)+ ]+ outer_order = self._outer_order_by(node, output_names, source_alias)+ outer_ctes = node.ctes+ outer_limit = node.limit+ outer_offset = node.offset+ outer_limit_with_ties = node.limit_with_ties+ outer_limit_percent = node.limit_percent+ limit_by = node.limit_by+ node.ctes = None+ node.order_by = None+ node.limit = None+ node.offset = None+ node.limit_by = None+ node.limit_with_ties = False+ node.limit_percent = False++ return ast.SelectQuery(+ type=node.type,+ ctes=outer_ctes,+ select=[ast.Field(chain=[source_alias, name]) for name in output_names],+ select_from=ast.JoinExpr(table=node, alias=source_alias),+ order_by=outer_order,+ limit=outer_limit,+ offset=outer_offset,+ limit_by=ast.LimitByExpr(n=limit_by.n, exprs=partition_by, offset_value=limit_by.offset_value),+ limit_with_ties=outer_limit_with_ties,+ limit_percent=outer_limit_percent,+ view_name=node.view_name,+ )+def _wrap(self, node: ast.SelectQuery, predicate: ast.Expr, helper_name: str | None = None) -> ast.SelectQuery:source_alias = f"__hogql_trino_source_{self.wrapper_index}"self.wrapper_index += 1@@ -136,6 +325,7 @@ class TrinoQueryWrapperLowerer(CloningVisitor):return ast.SelectQuery(ctes=outer_ctes,+ type=ast.SelectQueryType(columns=dict(node.type.columns)) if node.type is not None else None,select=[ast.Field(chain=[source_alias, name]) for name in output_names],select_from=ast.JoinExpr(table=node, alias=source_alias),where=self._qualify_wrapper_fields(@@ -259,11 +449,12 @@ class TrinoQueryWrapperLowerer(CloningVisitor):def _non_negative_integer(self, node: ast.Expr | None, label: str, default: int | None = None) -> int:if node is None and default is not None:return default- if not isinstance(node, ast.Constant) or isinstance(node.value, bool) or not isinstance(node.value, int):+ value = constant_integer(node)+ if value is None:raise TrinoLoweringError("TRINO_LIMIT_BY_NON_CONSTANT_LIMIT", f"non-constant {label}", node)- if node.value < 0:+ if value < 0:raise TrinoLoweringError("TRINO_LIMIT_BY_NEGATIVE_LIMIT", f"negative {label}", node)- return node.value+ return valuedef lower_trino_query_wrappers(node: ast.AST) -> ast.AST:diff --git a/posthog/hogql/transforms/trino/test/__snapshots__/test_manifest.ambr b/posthog/hogql/transforms/trino/test/__snapshots__/test_manifest.ambrindex 75bc4f806970..f2501520982a 100644--- a/posthog/hogql/transforms/trino/test/__snapshots__/test_manifest.ambr+++ b/posthog/hogql/transforms/trino/test/__snapshots__/test_manifest.ambr@@ -1,7 +1,7 @@# serializer version: 1# name: test_transpiles_core_table_with_values_without_django_queries[SELECT event FROM events WHERE event = {event} ORDER BY timestamp DESC LIMIT 1 BY event]tuple(- 'SELECT "__hogql_trino_source_0"."event" FROM (SELECT "org_catalog"."posthog"."events_production"."event" AS "event", row_number() OVER (PARTITION BY "org_catalog"."posthog"."events_production"."event" ORDER BY "org_catalog"."posthog"."events_production"."timestamp" DESC) AS "__hogql_limit_by_row_0", "org_catalog"."posthog"."events_production"."timestamp" AS "__hogql_order_0" FROM "org_catalog"."posthog"."events_production" WHERE ("org_catalog"."posthog"."events_production"."event" = %(hogql_val_0)s)) AS "__hogql_trino_source_0" WHERE ("__hogql_trino_source_0"."__hogql_limit_by_row_0" <= 1) ORDER BY "__hogql_trino_source_0"."__hogql_order_0" DESC LIMIT 50000',+ 'SELECT "__hogql_trino_source_0"."event" FROM (SELECT "org_catalog"."posthog"."events_production"."event" AS "event", row_number() OVER (PARTITION BY "org_catalog"."posthog"."events_production"."event" ORDER BY "org_catalog"."posthog"."events_production"."timestamp" DESC) AS "__hogql_limit_by_row_0", "org_catalog"."posthog"."events_production"."timestamp" AS "__hogql_order_0" FROM "org_catalog"."posthog"."events_production" WHERE ("event" = %(hogql_val_0)s)) AS "__hogql_trino_source_0" WHERE ("__hogql_trino_source_0"."__hogql_limit_by_row_0" <= 1) ORDER BY "__hogql_trino_source_0"."__hogql_order_0" DESC LIMIT 50000',dict({'hogql_val_0': 'signup',}),diff --git a/posthog/hogql/transforms/trino/test/test_manifest.py b/posthog/hogql/transforms/trino/test/test_manifest.pyindex c20dc9bdd343..0b9fe080d221 100644--- a/posthog/hogql/transforms/trino/test/test_manifest.py+++ b/posthog/hogql/transforms/trino/test/test_manifest.py@@ -7,7 +7,10 @@ from syrupy.assertion import SnapshotAssertionfrom posthog.schema import DateRange, HogQLFilters, HogQLQueryModifiers, HogQLVariable+from posthog.hogql import ast+from posthog.hogql.database.models import ExpressionField, StringDatabaseFieldfrom posthog.hogql.errors import QueryError+from posthog.hogql.parser import parse_exprfrom posthog.hogql.transforms.trino.errors import TrinoLoweringErrorfrom posthog.hogql.transforms.trino.manifest import (TrinoCatalogManifest,@@ -57,6 +60,52 @@ def test_transpiles_core_table_with_values_without_django_queries(assert (result.sql, result.values, result.hogql) == snapshot+ "expression",+ [+ "date('2026-01-01')",+ "Date('2026-01-01')",+ "ifNotFinite(1, 2)",+ "ifnotfinite(1, 2)",+ "IFNOTFINITE(1, 2)",+ "cardinality([1, 2])",+ "CARDINALITY([1, 2])",+ "json_value('{\"a\": 1}', '$.a')",+ "medianExactWeighted(3, 2)",+ "medianexactweighted(3, 2)",+ "medianExactWeightedIf(3, 2, true)",+ "medianexactweightedif(3, 2, true)",+ "quantiles(0.25, 0.75)(3)",+ "quantilesIf(0.25, 0.75)(3, true)",+ "sum(DISTINCT 3) FILTER (WHERE true)",+ "array_agg(3 ORDER BY 3 DESC)",+ "percentile_cont(0.5) WITHIN GROUP (ORDER BY 3 ASC)",+ ],+)[email protected]("alias", ["", " AS result"])+def test_hogql_diagnostics_accept_trino_signatures(expression: str, alias: str) -> None:+ query = f"SELECT {expression}{alias}"+ result = transpile_hogql_to_trino(query, manifest=_manifest(), include_hogql=True)+ without_hogql = transpile_hogql_to_trino(query, manifest=_manifest())++ assert (result.sql, result.values) == (without_hogql.sql, without_hogql.values)+ assert result.hogql is not None+ expected_expression = "toDate" + expression[4:] if expression[:4].lower() == "date" else expression+ assert result.print_columns == (("result" if alias else expected_expression),)+ round_trip = transpile_hogql_to_trino(result.hogql, manifest=_manifest())+ assert (round_trip.sql, round_trip.values) == (result.sql, result.values)++[email protected]("include_hogql", [False, True])+ ("expression", "error"),+ [("quantiles(0.5)(1, 2)", "quantiles"), ("unknownFunction(1)", "(?i)unknownfunction")],+)+def test_hogql_diagnostics_preserve_trino_validation(expression: str, error: str, include_hogql: bool) -> None:+ with pytest.raises(QueryError, match=error):+ transpile_hogql_to_trino(f"SELECT {expression}", manifest=_manifest(), include_hogql=include_hogql)++def test_transpiles_manifest_table_without_django_queries(django_assert_num_queries: Any) -> None:orders = TrinoManifestTable(logical_name="stripe.orders",@@ -173,3 +222,94 @@ def test_accepts_content_free_filters_and_null_modifiers() -> None:def test_rejects_tables_absent_from_manifest() -> None:with pytest.raises(QueryError, match="Unknown table `saved_query`"):transpile_hogql_to_trino("SELECT * FROM saved_query", manifest=_manifest(_events()))+++def test_manifest_preserves_curated_physical_names_and_computed_fields() -> None:+ created_at_field = ExpressionField(name="created_at", expr=parse_expr("toDateTime(created)"), isolate_scope=True)+ fields = {+ "customer_id": StringDatabaseField(name="customer"),+ "created_at": created_at_field,+ }+ table = TrinoManifestTable(+ logical_name="billing.subscriptions",+ locator=("catalog", "imports", "subscriptions"),+ columns=(+ TrinoManifestColumn(name="customer", type=DatabaseSerializedFieldType.STRING),+ TrinoManifestColumn(name="created", type=DatabaseSerializedFieldType.INTEGER),+ ),+ field_overrides=fields,+ )+ result = transpile_hogql_to_trino(+ "SELECT customer_id AS customer_id, created_at AS created_at FROM billing.subscriptions",+ manifest=_manifest(table),+ )++ assert '"billing__subscriptions"."customer" AS "customer_id"' in result.sql+ assert 'from_unixtime(CAST("billing__subscriptions"."created" AS DOUBLE))' in result.sql+ assert isinstance(created_at_field.expr, ast.Call)+++def test_manifest_qualifies_renamed_physical_field_across_join() -> None:+ subscriptions = TrinoManifestTable(+ logical_name="billing.subscriptions",+ locator=("catalog", "imports", "subscriptions"),+ columns=(+ TrinoManifestColumn(name="id", type=DatabaseSerializedFieldType.STRING),+ TrinoManifestColumn(name="customer", type=DatabaseSerializedFieldType.STRING),+ ),+ field_overrides={"customer_id": StringDatabaseField(name="customer")},+ )+ payments = TrinoManifestTable(+ logical_name="billing.payments",+ locator=("catalog", "imports", "payments"),+ columns=(+ TrinoManifestColumn(name="id", type=DatabaseSerializedFieldType.STRING),+ TrinoManifestColumn(name="customer", type=DatabaseSerializedFieldType.STRING),+ ),+ )+ result = transpile_hogql_to_trino(+ "SELECT customer_id FROM billing.subscriptions AS s JOIN billing.payments AS p ON s.id = p.id",+ manifest=_manifest(subscriptions, payments),+ )++ assert 'SELECT "s"."customer" AS "customer_id"' in result.sql+++ ("query", "expected_fields"),+ [+ (+ "SELECT l.id FROM left_table AS l JOIN right_table AS r USING (id)",+ ('"l"."id" = "r"."id"',),+ ),+ (+ "WITH l AS (SELECT id FROM left_table), r AS (SELECT id FROM right_table) "+ "SELECT l.id FROM l JOIN r USING (id)",+ ('"l"."id" = "r"."id"',),+ ),+ (+ "SELECT 1 FROM (SELECT id, value FROM left_table) "+ "JOIN (SELECT id, value FROM right_table) USING (id, value)",+ (+ '"__using_join_1"."id" = "__using_join_2"."id"',+ '"__using_join_1"."value" = "__using_join_2"."value"',+ ),+ ),+ ],+)+def test_manifest_preserves_using_join_sources_through_trino_lowering(+ query: str, expected_fields: tuple[str, ...]+) -> None:+ columns = (+ TrinoManifestColumn(name="id", type=DatabaseSerializedFieldType.STRING),+ TrinoManifestColumn(name="value", type=DatabaseSerializedFieldType.STRING),+ )+ manifest = _manifest(+ TrinoManifestTable(logical_name="left_table", locator=("catalog", "imports", "left_table"), columns=columns),+ TrinoManifestTable(logical_name="right_table", locator=("catalog", "imports", "right_table"), columns=columns),+ )++ result = transpile_hogql_to_trino(query, manifest=manifest)++ assert " USING " not in result.sql+ assert all(field_comparison in result.sql for field_comparison in expected_fields)diff --git a/posthog/hogql/transforms/trino/test/test_type_inference.py b/posthog/hogql/transforms/trino/test/test_type_inference.pynew file mode 100644index 000000000000..bc9691873e0d--- /dev/null+++ b/posthog/hogql/transforms/trino/test/test_type_inference.py@@ -0,0 +1,242 @@+import pytest++from posthog.hogql import ast+from posthog.hogql.constants import HogQLDialect+from posthog.hogql.type_system import infer_function_return_type+++ "name,arg_types,expected",+ [+ ("medianExact", [ast.IntegerType(nullable=False)], ast.IntegerType(nullable=False)),+ ("medianExactLow", [ast.DateType(nullable=True)], ast.DateType(nullable=True)),+ (+ "medianExactWeightedIf",+ [+ ast.IntegerType(nullable=True),+ ast.IntegerType(nullable=False),+ ast.BooleanType(nullable=False),+ ],+ ast.IntegerType(nullable=True),+ ),+ ("quantileExact", [ast.FloatType(nullable=False)], ast.FloatType(nullable=False)),+ (+ "medianExactHighIf",+ [ast.IntegerType(nullable=False), ast.BooleanType(nullable=True)],+ ast.IntegerType(nullable=False),+ ),+ (+ "avgWeightedIf",+ [ast.IntegerType(nullable=False), ast.FloatType(nullable=True), ast.BooleanType(nullable=False)],+ ast.FloatType(nullable=True),+ ),+ ("skewPop", [ast.IntegerType(nullable=False)], ast.FloatType(nullable=False)),+ (+ "kurtSampIf",+ [ast.FloatType(nullable=True), ast.BooleanType(nullable=False)],+ ast.FloatType(nullable=True),+ ),+ (+ "simpleLinearRegressionIf",+ [+ ast.IntegerType(nullable=False),+ ast.FloatType(nullable=True),+ ast.BooleanType(nullable=False),+ ],+ ast.TupleType(+ nullable=False,+ item_types=[ast.FloatType(nullable=False), ast.FloatType(nullable=False)],+ field_names=["k", "b"],+ ),+ ),+ (+ "maxIntersectionsPositionIf",+ [+ ast.IntegerType(nullable=False),+ ast.IntegerType(nullable=True),+ ast.BooleanType(nullable=False),+ ],+ ast.IntegerType(nullable=True),+ ),+ (+ "groupUniqArrayArrayIf",+ [+ ast.ArrayType(nullable=False, item_type=ast.IntegerType(nullable=True)),+ ast.BooleanType(nullable=False),+ ],+ ast.ArrayType(nullable=False, item_type=ast.IntegerType(nullable=False)),+ ),+ (+ "groupArrayMovingSumIf",+ [ast.FloatType(nullable=True), ast.BooleanType(nullable=False)],+ ast.ArrayType(nullable=False, item_type=ast.FloatType(nullable=False)),+ ),+ (+ "groupArrayMovingAvg",+ [ast.IntegerType(nullable=False)],+ ast.ArrayType(nullable=False, item_type=ast.FloatType(nullable=False)),+ ),+ (+ "deltaSumIf",+ [ast.IntegerType(nullable=True), ast.BooleanType(nullable=False)],+ ast.IntegerType(nullable=False),+ ),+ (+ "groupArrayInsertAtIf",+ [+ ast.StringType(nullable=True),+ ast.IntegerType(nullable=False),+ ast.BooleanType(nullable=False),+ ],+ ast.ArrayType(nullable=False, item_type=ast.StringType(nullable=False)),+ ),+ ("roundToExp2", [ast.IntegerType(nullable=True)], ast.IntegerType(nullable=True)),+ (+ "gcd",+ [ast.IntegerType(nullable=False), ast.IntegerType(nullable=True)],+ ast.IntegerType(nullable=True),+ ),+ (+ "arrayAUC",+ [+ ast.ArrayType(nullable=False, item_type=ast.FloatType(nullable=False)),+ ast.ArrayType(nullable=True, item_type=ast.IntegerType(nullable=False)),+ ],+ ast.FloatType(nullable=True),+ ),+ ("UUIDv7ToDateTime", [ast.UUIDType(nullable=True)], ast.DateTimeType(nullable=True)),+ (+ "tupleToNameValuePairs",+ [+ ast.TupleType(+ nullable=False,+ item_types=[ast.IntegerType(nullable=False), ast.FloatType(nullable=True)],+ )+ ],+ ast.ArrayType(+ nullable=False,+ item_type=ast.TupleType(+ nullable=False,+ item_types=[ast.StringType(nullable=False), ast.FloatType(nullable=True)],+ ),+ ),+ ),+ (+ "pointInEllipses",+ [ast.FloatType(nullable=False), ast.FloatType(nullable=True)],+ ast.BooleanType(nullable=True),+ ),+ (+ "ifNotFinite",+ [ast.FloatType(nullable=True), ast.IntegerType(nullable=False)],+ ast.FloatType(nullable=True),+ ),+ (+ "mapPopulateSeries",+ [+ ast.MapType(+ nullable=True,+ key_type=ast.IntegerType(nullable=False),+ value_type=ast.StringType(nullable=False),+ )+ ],+ ast.MapType(+ nullable=True,+ key_type=ast.IntegerType(nullable=False),+ value_type=ast.StringType(nullable=False),+ ),+ ),+ ],+)+def test_trino_function_types(name: str, arg_types: list[ast.ConstantType], expected: ast.ConstantType) -> None:+ assert infer_function_return_type(name, arg_types, dialect="trino").return_type == expected+++ "name",+ [+ "medianMap",+ "medianMapIf",+ "medianMapOrDefault",+ "medianMapOrDefaultIf",+ "medianMapOrNull",+ "medianMapOrNullIf",+ ],+)+def test_resolver_infers_median_map_combinator_types(name: str) -> None:+ arg_types: list[ast.ConstantType] = [+ ast.MapType(+ nullable=False,+ key_type=ast.StringType(nullable=False),+ value_type=ast.IntegerType(nullable=True),+ )+ ]+ if name.endswith("If"):+ arg_types.append(ast.BooleanType(nullable=False))++ assert infer_function_return_type(name, arg_types, dialect="trino").return_type == ast.MapType(+ nullable=False,+ key_type=ast.StringType(nullable=False),+ value_type=ast.FloatType(nullable=False),+ )+++ "name",+ [+ "medianForEach",+ "medianForEachIf",+ "medianForEachOrDefault",+ "medianForEachOrDefaultIf",+ "medianForEachOrNull",+ "medianForEachOrNullIf",+ ],+)+def test_resolver_infers_median_for_each_combinator_types(name: str) -> None:+ arg_types: list[ast.ConstantType] = [ast.ArrayType(nullable=False, item_type=ast.IntegerType(nullable=True))]+ if name.endswith("If"):+ arg_types.append(ast.BooleanType(nullable=False))++ assert infer_function_return_type(name, arg_types, dialect="trino").return_type == ast.ArrayType(+ nullable=False,+ item_type=ast.FloatType(nullable=False),+ )++[email protected]("dialect", ["clickhouse", "hogql", "postgres", "duckdb", "mysql", "snowflake", "redshift"])+ "name,arg_types,expected",+ [+ ("medianExact", [ast.IntegerType(nullable=False)], ast.FloatType(nullable=False)),+ (+ "medianForEach",+ [ast.ArrayType(nullable=False, item_type=ast.IntegerType(nullable=False))],+ ast.ArrayType(nullable=False, item_type=ast.FloatType(nullable=False)),+ ),+ (+ "L2Normalize",+ [ast.ArrayType(nullable=False, item_type=ast.IntegerType(nullable=False))],+ ast.ArrayType(nullable=False, item_type=ast.IntegerType(nullable=False)),+ ),+ ("IPv4StringToNum", [ast.StringType(nullable=False)], ast.UnknownType(unanalyzable=True)),+ ("gcd", [ast.IntegerType(nullable=False), ast.IntegerType(nullable=False)], ast.UnknownType(unanalyzable=True)),+ ],+)+def test_trino_inference_does_not_change_other_dialects(+ name: str, arg_types: list[ast.ConstantType], expected: ast.ConstantType, dialect: HogQLDialect+) -> None:+ assert infer_function_return_type(name, arg_types, dialect=dialect).return_type == expected+++ "name,arg_types,expected",+ [+ ("isIPv4String", [ast.StringType(nullable=False)], ast.BooleanType(nullable=False)),+ ("isIPv6String", [ast.StringType(nullable=True)], ast.BooleanType(nullable=True)),+ ("IPv4NumToString", [ast.IntegerType(nullable=False)], ast.StringType(nullable=False)),+ ("IPv4StringToNum", [ast.StringType(nullable=False)], ast.IntegerType(nullable=False)),+ ("IPv4StringToNumOrNull", [ast.StringType(nullable=False)], ast.IntegerType(nullable=True)),+ ],+)+def test_trino_network_function_types(name: str, arg_types: list[ast.ConstantType], expected: ast.ConstantType) -> None:+ assert infer_function_return_type(name, arg_types, dialect="trino").return_type == expecteddiff --git a/posthog/hogql/transforms/trino/validate.py b/posthog/hogql/transforms/trino/validate.pyindex 816753f7cbe8..007173b937ae 100644--- a/posthog/hogql/transforms/trino/validate.py+++ b/posthog/hogql/transforms/trino/validate.py@@ -5,9 +5,22 @@ from posthog.hogql.context import HogQLContextfrom posthog.hogql.database.schema.numbers import NumbersTablefrom posthog.hogql.database.trino_locator import resolve_trino_table_locatorfrom posthog.hogql.printer.trino_functions import (+ TRINO_AGGREGATE_COMBINATORS,+ TRINO_ARRAY_INSERT_AGGREGATES,+ TRINO_DELTA_AGGREGATES,+ TRINO_EXACT_QUANTILES,+ TRINO_EXACT_WEIGHTED_MEDIANS,TRINO_FUNCTION_HANDLERS_LOWER,TRINO_FUNCTION_RENAMES_LOWER,+ TRINO_INTERSECTION_AGGREGATES,+ TRINO_MOVING_ARRAY_AGGREGATES,TRINO_PASSTHROUGH_FUNCTIONS,+ TRINO_QUANTILES,+ TRINO_STATISTICAL_AGGREGATES,+ TRINO_TUPLE_OPERATORS,+ TRINO_UNIQUE_ARRAY_AGGREGATES,+ TRINO_VECTOR_REWRITES,+ TRINO_WINDOW_ONLY_FUNCTIONS,)from posthog.hogql.transforms.trino.errors import TrinoLoweringErrorfrom posthog.hogql.transforms.trino.persons import is_internal_trino_logical_table@@ -17,6 +30,61 @@ from posthog.schema_enums import PersonsOnEventsMode_SPECIAL_CALLS = frozenset({+ *TRINO_AGGREGATE_COMBINATORS,+ *TRINO_ARRAY_INSERT_AGGREGATES,+ *TRINO_EXACT_QUANTILES,+ *TRINO_EXACT_WEIGHTED_MEDIANS,+ *TRINO_DELTA_AGGREGATES,+ *TRINO_INTERSECTION_AGGREGATES,+ *TRINO_MOVING_ARRAY_AGGREGATES,+ *TRINO_QUANTILES,+ *TRINO_STATISTICAL_AGGREGATES,+ *TRINO_UNIQUE_ARRAY_AGGREGATES,+ *TRINO_WINDOW_ONLY_FUNCTIONS,+ *TRINO_TUPLE_OPERATORS,+ *TRINO_VECTOR_REWRITES,+ "arraylast",+ "arrayreduce",+ "arraycumsum",+ "arraycumsumnonnegative",+ "arrayfill",+ "arrayreversefill",+ "arraysplit",+ "arrayreversesplit",+ "tonullablestring",+ "to_timestamp",+ "defaultvalueoftypename",+ "datename",+ "accuratecast",+ "accuratecastornull",+ "format",+ "domain",+ "intdiv",+ "multiplydecimal",+ "convertcurrency",+ "formatreadabletimedelta",+ "roundbankers",+ "extracturlparameter",+ "arrayzip",+ "arrayfold",+ "arrayreversesort",+ "extractallgroups",+ "extractallgroupshorizontal",+ "extractallgroupsvertical",+ "extractgroups",+ "regexpextract",+ "replaceregexpone",+ "median",+ "medianif",+ "topk",+ "arraymax",+ "arrayenumerate",+ "arrayall",+ "arrayexists",+ "arraycount",+ "countequal",+ "multisearchanycaseinsensitive",+ "tostartofinterval","percentile_cont","percentile_disc","argmax",@@ -29,13 +97,16 @@ _SPECIAL_CALLS = frozenset("arrayfilter","arrayfirst","arrayflatten",+ "arraylastindex","arraymap","arraymin",+ "arrayslice","arraysort","arraysum","empty","extract","extractall",+ "first_value","grouparrayif","groupuniqarrayif","groupuniqarray",@@ -44,6 +115,7 @@ _SPECIAL_CALLS = frozenset("hasany","in","countdistinct",+ "countdistinctif","date_part","dateadd","datesub",@@ -65,8 +137,23 @@ _SPECIAL_CALLS = frozenset("notempty","notin","parsedatetime",+ "parsedatetimebesteffort","quantile","quantileif",+ "avgweighted",+ "avgweightedif",+ "aggregate_funnel_trends",+ "cityhash64",+ "cuttofirstsignificantsubdomain",+ "ngramdistance",+ "ngramdistancecaseinsensitive",+ "ngramdistanceutf8",+ "ngramsearch",+ "ngramsearchcaseinsensitive",+ "ngramsearchutf8",+ "hex",+ "touuidordefault",+ "reinterpretasuuid","range","repeat","splitbychar",@@ -90,6 +177,10 @@ _SPECIAL_CALLS = frozenset("tostartofyear","tolastdayofweek","totimezone",+ "like",+ "ilike",+ "notlike",+ "notilike",})_SEMANTIC_CALLS = frozenset({"cohort", "matchesaction", "savedquery"})@@ -129,11 +220,18 @@ class TrinoSourceValidator(TraversingVisitor):raise TrinoLoweringError("TRINO_SETTINGS_UNSUPPORTED", "SETTINGS", node)super().visit_select_query(node)- def visit_pivot_expr(self, node: ast.PivotExpr) -> None:- raise TrinoLoweringError("TRINO_PIVOT_UNSUPPORTED", "PIVOT", node)-def visit_unpivot_expr(self, node: ast.UnpivotExpr) -> None:- raise TrinoLoweringError("TRINO_UNPIVOT_UNSUPPORTED", "UNPIVOT", node)+ if len(node.columns) != 1 or not all(+ isinstance(expr, ast.Field)+ for column in node.columns+ for expr in [column.value_columns, column.name_columns, *column.unpivot_values]+ ):+ raise TrinoLoweringError(+ "TRINO_UNPIVOT_SHAPE_UNSUPPORTED",+ "UNPIVOT with tuple outputs, aliases, or multiple column groups",+ node,+ )+ super().visit_unpivot_expr(node)class TrinoReadyValidator(TraversingVisitor):@@ -194,8 +292,8 @@ class TrinoReadyValidator(TraversingVisitor):def visit_cte(self, node: ast.CTE) -> None:if node.cte_type != "subquery":self._fail("TRINO_SCALAR_CTE_UNSUPPORTED", "scalar CTE", node)- if node.materialized is not None or node.using_key is not None:- self._fail("TRINO_CTE_MODIFIER_UNSUPPORTED", "CTE modifier", node)+ if node.using_key is not None:+ self._fail("TRINO_CTE_MODIFIER_UNSUPPORTED", "CTE USING KEY", node)super().visit_cte(node)def visit_pivot_expr(self, node: ast.PivotExpr) -> None:diff --git a/posthog/hogql/type_system.py b/posthog/hogql/type_system.pyindex 5ec09864792d..bee8cb102bfc 100644--- a/posthog/hogql/type_system.py+++ b/posthog/hogql/type_system.py@@ -1022,6 +1022,82 @@ def infer_tuple_name_access_constant_type(tuple_type: ast.ConstantType, field_nareturn dataclasses.replace(item_type, nullable=tuple_type.nullable or item_type.nullable)+def _infer_trino_function_type(+ normalized_name: str,+ arg_types: list[ast.ConstantType],+ args: Optional[list[ast.Expr]],+) -> ast.ConstantType | None:+ if normalized_name == "roundtoexp2" and arg_types and isinstance(arg_types[0], (ast.IntegerType, ast.FloatType)):+ return dataclasses.replace(arg_types[0])++ if (+ normalized_name in {"gcd", "lcm"}+ and len(arg_types) == 2+ and all(isinstance(arg_type, ast.IntegerType) for arg_type in arg_types)+ ):+ return ast.IntegerType(nullable=any(arg_type.nullable for arg_type in arg_types))++ if normalized_name == "arrayauc" and len(arg_types) == 2:+ return ast.FloatType(nullable=any(arg_type.nullable for arg_type in arg_types))++ if normalized_name == "uuidv7todatetime" and arg_types:+ return ast.DateTimeType(nullable=any(arg_type.nullable for arg_type in arg_types))++ if normalized_name == "tupletonamevaluepairs" and arg_types and isinstance(arg_types[0], ast.TupleType):+ tuple_type = arg_types[0]+ value_type = least_common_supertype(tuple_type.item_types, dialect="trino")+ return ast.ArrayType(+ nullable=tuple_type.nullable,+ item_type=ast.TupleType(+ nullable=False,+ item_types=[ast.StringType(nullable=False), value_type],+ ),+ )++ if normalized_name == "pointinellipses":+ return ast.BooleanType(nullable=any(arg_type.nullable for arg_type in arg_types))++ if normalized_name == "ifnotfinite" and len(arg_types) == 2:+ return least_common_supertype(arg_types, dialect="trino")++ if normalized_name == "mappopulateseries" and arg_types and isinstance(arg_types[0], ast.MapType):+ return dataclasses.replace(arg_types[0])++ if normalized_name == "ipv4numtostring":+ return ast.StringType(nullable=any(arg_type.nullable for arg_type in arg_types))++ if normalized_name == "extractipv4substrings":+ return ast.ArrayType(+ nullable=any(arg_type.nullable for arg_type in arg_types), item_type=ast.StringType(nullable=False)+ )++ if normalized_name in {"isipv4string", "isipv6string", "isipaddressinrange"}:+ return ast.BooleanType(nullable=any(arg_type.nullable for arg_type in arg_types))++ if normalized_name == "ipv4stringtonumornull":+ return ast.IntegerType(nullable=True)++ if normalized_name in {"ipv4stringtonum", "ipv4stringtonumordefault"}:+ return ast.IntegerType(nullable=any(arg_type.nullable for arg_type in arg_types))++ if normalized_name == "totime":+ return ast.DateTimeType(nullable=any(arg_type.nullable for arg_type in arg_types))++ if normalized_name in _VECTOR_ARRAY_RESULT_FUNCTIONS and arg_types:+ if isinstance(arg_types[0], ast.TupleType):+ return dataclasses.replace(+ arg_types[0], item_types=[ast.FloatType(nullable=item.nullable) for item in arg_types[0].item_types]+ )+ if isinstance(arg_types[0], ast.ArrayType):+ return dataclasses.replace(arg_types[0], item_type=ast.FloatType(nullable=arg_types[0].item_type.nullable))+ return dataclasses.replace(arg_types[0])++ if normalized_name in {"arraycumsum", "arraycumsumnonnegative"} and args and isinstance(args[0], ast.Lambda):+ return _infer_higher_order_array_type(arg_types, args=args, dialect="trino", use_lambda_return=True)++ return None++def _infer_generic_function_type(normalized_name: str,arg_types: list[ast.ConstantType],@@ -1029,6 +1105,11 @@ def _infer_generic_function_type(dialect: HogQLDialect,meta: Optional[HogQLFunctionMeta] = None,) -> ast.ConstantType | None:+ if dialect == "trino":+ trino_type = _infer_trino_function_type(normalized_name, arg_types, args)+ if trino_type is not None:+ return trino_type+if normalized_name in {"equals","notequals",@@ -1350,7 +1431,7 @@ def _infer_generic_function_type(return item_typeif normalized_name == "arrayreduce":- return _infer_array_reduce_type(arg_types=arg_types, args=args)+ return _infer_array_reduce_type(arg_types=arg_types, args=args, dialect=dialect)if (normalized_name@@ -1417,7 +1498,7 @@ def _infer_generic_function_type(return infer_tuple_name_access_constant_type(arg_types[0], field_name)return ast.UnknownType()- aggregate_type = _infer_aggregate_function_type(normalized_name, arg_types)+ aggregate_type = _infer_aggregate_function_type(normalized_name, arg_types, dialect)if aggregate_type is not None:return aggregate_type@@ -1578,7 +1659,9 @@ def _array_element_type(array_type: ast.ConstantType) -> ast.ConstantType:return ast.UnknownType()-def _infer_array_reduce_type(arg_types: list[ast.ConstantType], args: Optional[list[ast.Expr]]) -> ast.ConstantType:+def _infer_array_reduce_type(+ arg_types: list[ast.ConstantType], args: Optional[list[ast.Expr]], dialect: HogQLDialect+) -> ast.ConstantType:if not args or len(args) < 2:return ast.UnknownType()@@ -1591,24 +1674,122 @@ def _infer_array_reduce_type(arg_types: list[ast.ConstantType], args: Optional[lreturn ast.UnknownType()normalized_aggregate = _normalize_array_reduce_aggregate_name(aggregate_name)- return _infer_aggregate_function_type(normalized_aggregate, array_item_types) or ast.UnknownType()+ return _infer_aggregate_function_type(normalized_aggregate, array_item_types, dialect) or ast.UnknownType()def _normalize_array_reduce_aggregate_name(aggregate_name: str) -> str:return aggregate_name.split("(", 1)[0].strip().lower()-def _infer_aggregate_function_type(normalized_name: str, arg_types: list[ast.ConstantType]) -> ast.ConstantType | None:+def _infer_trino_aggregate_function_type(+ normalized_name: str, arg_types: list[ast.ConstantType]+) -> ast.ConstantType | None:+ if normalized_name == "simplelinearregressionif":+ return ast.TupleType(+ nullable=False,+ item_types=[ast.FloatType(nullable=False), ast.FloatType(nullable=False)],+ field_names=["k", "b"],+ )++ if normalized_name in {"maxintersections", "maxintersectionsif"}:+ value_types = arg_types[:2]+ return ast.IntegerType(nullable=any(value_type.nullable for value_type in value_types))++ if normalized_name in {"maxintersectionsposition", "maxintersectionspositionif"} and arg_types:+ value_types = arg_types[:2]+ return dataclasses.replace(arg_types[0], nullable=any(value_type.nullable for value_type in value_types))++ median_container_suffixes = {"", "if", "ordefault", "ordefaultif", "ornull", "ornullif"}++ if (+ normalized_name.startswith("medianmap")+ and normalized_name.removeprefix("medianmap") in median_container_suffixes+ and arg_types+ and isinstance(arg_types[0], ast.MapType)+ ):+ return ast.MapType(+ nullable=False,+ key_type=dataclasses.replace(arg_types[0].key_type),+ value_type=ast.FloatType(nullable=False),+ )++ if (+ normalized_name.startswith("medianforeach")+ and normalized_name.removeprefix("medianforeach") in median_container_suffixes+ and arg_types+ and isinstance(arg_types[0], ast.ArrayType)+ ):+ return ast.ArrayType(nullable=False, item_type=ast.FloatType(nullable=False))++ if normalized_name in {"groupuniqarrayarray", "groupuniqarrayarrayif"} and arg_types:+ source_type = arg_types[0]+ if isinstance(source_type, ast.ArrayType):+ return ast.ArrayType(+ nullable=False,+ item_type=dataclasses.replace(source_type.item_type, nullable=False),+ )++ if (+ normalized_name+ in {+ "quantileexact",+ "medianexact",+ "medianexactlow",+ "medianexacthigh",+ "medianexactweighted",+ }+ and arg_types+ ):+ return dataclasses.replace(arg_types[0])++ if normalized_name == "simplelinearregression":+ return ast.TupleType(+ nullable=any(arg_type.nullable for arg_type in arg_types),+ item_types=[ast.FloatType(nullable=False), ast.FloatType(nullable=False)],+ field_names=["k", "b"],+ )++ if normalized_name == "deltasum" and arg_types:+ return dataclasses.replace(arg_types[0], nullable=False)++ if normalized_name == "grouparrayinsertat" and arg_types:+ return ast.ArrayType(+ nullable=False,+ item_type=dataclasses.replace(arg_types[0], nullable=False),+ )++ if normalized_name in {"grouparraymovingavg", "grouparraymovingsum"} and arg_types:+ item_type = (+ ast.FloatType(nullable=False)+ if normalized_name.endswith("avg") or isinstance(arg_types[0], ast.FloatType)+ else ast.IntegerType(nullable=False)+ )+ return ast.ArrayType(nullable=False, item_type=item_type)++ if normalized_name in {"avgweighted", "skewpop", "skewsamp", "kurtpop", "kurtsamp"}:+ return ast.FloatType(nullable=any(arg_type.nullable for arg_type in arg_types))++ return None+++def _infer_aggregate_function_type(+ normalized_name: str, arg_types: list[ast.ConstantType], dialect: HogQLDialect+) -> ast.ConstantType | None:# A ClickHouse aggregate is a base aggregate plus zero or more stackable combinator suffixes# (-If, -Array, -ForEach, -OrNull, -OrDefault, -Distinct, -State, -Merge). Peel known combinators# first so the base return type is computed once and each suffix transforms it, instead of# enumerating every base×combinator permutation. This must run before the base checks below so a# greedy `startswith` match (e.g. "quantiles") can't swallow a combinator such as -ForEach.- combinator_type = _infer_aggregate_combinator_type(normalized_name, arg_types)+ if dialect == "trino":+ trino_type = _infer_trino_aggregate_function_type(normalized_name, arg_types)+ if trino_type is not None:+ return trino_type++ combinator_type = _infer_aggregate_combinator_type(normalized_name, arg_types, dialect)if combinator_type is not None:return combinator_type- state_or_merge_type = _infer_aggregate_state_or_merge_type(normalized_name, arg_types)+ state_or_merge_type = _infer_aggregate_state_or_merge_type(normalized_name, arg_types, dialect)if state_or_merge_type is not None:return state_or_merge_type@@ -1654,7 +1835,7 @@ _AGGREGATE_COMBINATOR_SUFFIXES: tuple[str, ...] = ("ordefault", "ornull", "distidef _infer_aggregate_combinator_type(- normalized_name: str, arg_types: list[ast.ConstantType]+ normalized_name: str, arg_types: list[ast.ConstantType], dialect: HogQLDialect) -> ast.ConstantType | None:for suffix in _AGGREGATE_COMBINATOR_SUFFIXES:if not normalized_name.endswith(suffix) or len(normalized_name) <= len(suffix):@@ -1664,7 +1845,7 @@ def _infer_aggregate_combinator_type(# Only accept the peel if what remains is itself a known aggregate (possibly with further# combinators). Otherwise the suffix was a coincidence — try the next, then fall through to# Unknown. This keeps the rule conservative: a wrong type is worse than no type.- base_type = _infer_aggregate_function_type(base_name, base_arg_types)+ base_type = _infer_aggregate_function_type(base_name, base_arg_types, dialect)if base_type is None:continuereturn _apply_aggregate_combinator(suffix, base_type)@@ -1697,12 +1878,12 @@ def _is_aggregate_state_or_merge(normalized_name: str) -> bool:def _infer_aggregate_state_or_merge_type(- normalized_name: str, arg_types: list[ast.ConstantType]+ normalized_name: str, arg_types: list[ast.ConstantType], dialect: HogQLDialect) -> ast.ConstantType | None:state_base_name = _strip_aggregate_suffix(normalized_name, ("stateif", "state"))if state_base_name is not None:state_arg_types = arg_types[:-1] if normalized_name.endswith("stateif") else arg_types- wrapped_type = _infer_aggregate_function_type(state_base_name, state_arg_types)+ wrapped_type = _infer_aggregate_function_type(state_base_name, state_arg_types, dialect)if wrapped_type is None:return Nonereturn ast.AggregateStateType(nullable=False, wrapped_type=wrapped_type)