Skip to content

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

feat(hogql): add an explicitly invoked trino compiler (#91719)

Bill Guowei Yangac8d14ca2a50
diff --git a/docs/internal/hogql-trino-compiler.md b/docs/internal/hogql-trino-compiler.md
new file mode 100644
index 000000000000..0f0a4bb0d42c
--- /dev/null
+++ b/docs/internal/hogql-trino-compiler.md
@@ -0,0 +1,44 @@
+# HogQL to Trino compilation
+
+The Trino backend compiles a resolved HogQL query into SQL and bound values. It does not connect to Trino or enable HogQL on an existing Query Editor connection.
+
+## Release boundary
+
+Call `prepare_and_print_ast(node, context, "trino")` explicitly to use the backend. Normal query routing and the raw-only Trino adapter remain unchanged. The compiler and lowering modules load only when a caller selects the Trino dialect.
+
+The returned SQL uses named placeholders, with values stored in `context.values`. `convert_pyformat_placeholders` converts these into positional placeholders and values for a Trino client; calling this helper does not execute SQL.
+
+Query Editor capability changes, case-insensitive connection lookup, and parameter submission belong to a separate connection-integration change. They are not prerequisites for compilation.
+
+For supported string, array, and map arguments, `empty(x)` returns true when the value is NULL or has zero length. `notEmpty(x)` requires a non-NULL value with nonzero length. String predicates use an empty-string comparison; arrays and maps use `cardinality`.
+
+## Why some shared integration is necessary
+
+The 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:
+
+| Shared surface | Reason | Effect on other dialects |
+| ------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- |
+| Dialect and runtime-type declarations | Identify Trino throughout resolution and printing. | Existing dialect membership and behavior stay unchanged. |
+| `HogQLContext.trino_table_locators` | Carry explicit physical destinations through context copies and semantic expansion. | An empty default is unused outside Trino compilation. |
+| `printer/utils.py` | Run Trino lowering before and after shared lazy-table, property, and cohort expansion; resolve introduced nodes again. | Trino-specific passes and imports require the Trino dialect. |
+| Resolver allowances | Accept `TRY_CAST`, positional references, and array slices before the printer sees them. | Existing dialect checks retain their previous outcomes. |
+| `BasePrinter` rendering hooks | Support Trino's limit/offset order, `FETCH FIRST ... WITH TIES`, and `GROUP BY AUTO`. | Default hook implementations preserve the existing rendering. |
+| Lazy-table visitor annotations | The Trino validator visits `LazyTableType`; the common visitor signature must describe that actual node type. | The workload visitor drops an impossible `FunctionCallTable` check; valid lazy-table behavior stays unchanged. |
+
+A standalone printer cannot repair a query rejected earlier by the resolver or introduce relation-shape rewrites after semantic resolution is finished. A separate compiler pipeline could avoid these hooks, but would duplicate the PostHog semantic expansion sequence. The small hooks keep that sequence shared. Overriding complete base-printer methods would likewise duplicate unrelated SELECT and set-operation rendering.
+
+Trino table rendering stays in Trino-specific modules. Neither the built-in numbers table nor the shared direct-Trino table class needs a new rendering method.
+
+## Explicit compilation from Django
+
+After deployment, Django shell can call the same compilation API. Construct the context with the intended team, user, effective modifiers, and `Database.create_for(...)`, then supply explicit Trino locators. No new HTTP endpoint or scheduled job is required.
+
+Source metadata describes what HogQL means. Target mappings describe where the corresponding Trino data exists. Missing mappings and unsupported constructs fail compilation; the compiler must not invent physical relations or assume a ClickHouse materialized view exists in Trino.
+
+`test_trino_semantics.py` exercises action expansion, cohort expansion, and lazy person joins through the compilation API without using the execution adapter. A batch export script is a separate operational tool, not part of this release.
+
+## Validation
+
+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.
diff --git a/posthog/hogql/constants.py b/posthog/hogql/constants.py
index 4cefec5fe637..e6eb4a09abc0 100644
--- a/posthog/hogql/constants.py
+++ b/posthog/hogql/constants.py
@@ -66,14 +66,14 @@ EXCEPTION_STRING_ARRAY_PROPERTIES = frozenset(
}
)
-type HogQLDialect = Literal["hogql", "clickhouse", "postgres", "duckdb", "mysql", "snowflake", "redshift"]
+type HogQLDialect = Literal["hogql", "clickhouse", "postgres", "duckdb", "mysql", "snowflake", "redshift", "trino"]
# All dialects that compile to an external SQL database queried directly (as opposed to
# ClickHouse / HogQL). MySQL shares the standard-SQL keyword surface (CURRENT_DATE & co.)
# but not Postgres-specific features like PIVOT/UNPIVOT, TRY_CAST, or positional references.
# Redshift is a Postgres fork: it reuses the Postgres-family lazy-table resolution and
# property lowering, then its printer blocks the constructs the Redshift engine can't run.
-SQL_TARGET_DIALECTS: frozenset[HogQLDialect] = frozenset({"postgres", "duckdb", "mysql", "redshift"})
+SQL_TARGET_DIALECTS: frozenset[HogQLDialect] = frozenset({"postgres", "duckdb", "mysql", "redshift", "trino"})
type HogQLParserBackend = Literal["cpp-json", "rust-json", "rust-py"]
diff --git a/posthog/hogql/context.py b/posthog/hogql/context.py
index 8257c6ceed7a..51614a05534f 100644
--- a/posthog/hogql/context.py
+++ b/posthog/hogql/context.py
@@ -64,6 +64,8 @@ class HogQLContext:
database: Optional["Database"] = None
# Metadata discovered for a direct Postgres connection, if one is selected
direct_postgres_connection_metadata: dict[str, Any] | None = None
+ # Query-scoped mappings preserve resolved logical tables through Trino lowering.
+ trino_table_locators: dict[str, tuple[str, str, str]] = field(default_factory=dict)
# Set when the query executes against an external direct-SQL connection instead of PostHog's own cluster
is_direct_query: bool = False
# If set, will save string constants to this dict. Inlines strings into the query if None.
diff --git a/posthog/hogql/database/database.py b/posthog/hogql/database/database.py
index 05a90b5ddb1b..8dc0a8ff3534 100644
--- a/posthog/hogql/database/database.py
+++ b/posthog/hogql/database/database.py
@@ -1031,7 +1031,6 @@ class Database(BaseModel):
include_hidden_posthog_tables: bool = False,
include_fields: bool = True,
) -> dict[str, DatabaseSchemaTable]:
-
from posthog.schema import ( # noqa: PLC0415
DatabaseSchemaDataWarehouseTable,
DatabaseSchemaEndpointTable,
@@ -2402,7 +2401,6 @@ class Database(BaseModel):
def get_data_warehouse_table_name(source: ExternalDataSource | None, table_name: str):
-
if source is None:
return table_name
@@ -2767,7 +2765,6 @@ def _strip_external_source_prefix(source: ExternalDataSource, table_name: str) -
def _get_warehouse_table_keys(warehouse_table: DataWarehouseTable, *, direct_query: bool) -> list[str]:
-
source = warehouse_table.external_data_source
if source is not None and source.access_method == ExternalDataSourceAccessMethod.DIRECT and direct_query:
return [warehouse_table.name]
@@ -2780,7 +2777,6 @@ def _should_include_connection_table(
*,
connection_id: str,
) -> bool:
-
source = warehouse_table.external_data_source
if source is None or source.access_method != ExternalDataSourceAccessMethod.DIRECT:
return False
diff --git a/posthog/hogql/database/trino_locator.py b/posthog/hogql/database/trino_locator.py
new file mode 100644
index 000000000000..e572c2ca22b2
--- /dev/null
+++ b/posthog/hogql/database/trino_locator.py
@@ -0,0 +1,24 @@
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+from posthog.hogql.database.direct_trino_table import DirectTrinoTable
+from posthog.hogql.errors import QueryError
+
+if TYPE_CHECKING:
+ from posthog.hogql.context import HogQLContext
+ from posthog.hogql.database.models import Table
+
+
+TrinoTableLocator = tuple[str, str, str]
+
+
+def resolve_trino_table_locator(table: Table, context: HogQLContext) -> TrinoTableLocator | None:
+ if isinstance(table, DirectTrinoTable):
+ locator = (table.trino_catalog, table.trino_schema, table.trino_table_name)
+ for label, value in zip(("catalog name", "schema name", "table name"), locator):
+ if not value.strip():
+ raise QueryError(f"Direct Trino tables require a {label}.")
+ return locator
+ logical_name = table.name or table.to_printed_hogql()
+ return context.trino_table_locators.get(logical_name)
diff --git a/posthog/hogql/database/trino_unnest_table.py b/posthog/hogql/database/trino_unnest_table.py
new file mode 100644
index 000000000000..f2d9ef10ec53
--- /dev/null
+++ b/posthog/hogql/database/trino_unnest_table.py
@@ -0,0 +1,24 @@
+from typing import TYPE_CHECKING
+
+from posthog.hogql.database.models import (
+ DANGEROUS_NoTeamIdCheckTable,
+ FieldOrTable,
+ FunctionCallTable,
+ UnknownDatabaseField,
+)
+
+if TYPE_CHECKING:
+ from posthog.hogql.context import HogQLContext
+
+
+class TrinoUnnestTable(FunctionCallTable, DANGEROUS_NoTeamIdCheckTable):
+ name: str
+ fields: dict[str, FieldOrTable] = {"value": UnknownDatabaseField(name="value")}
+ min_args: int = 1
+ max_args: int = 1
+
+ def to_printed_hogql(self) -> str:
+ return self.name
+
+ def to_printed_trino(self, context: "HogQLContext") -> str:
+ return "UNNEST"
diff --git a/posthog/hogql/direct_sql/test/test_registry_and_capability.py b/posthog/hogql/direct_sql/test/test_registry_and_capability.py
index 0b21cb14ab7c..cb3532ec5658 100644
--- a/posthog/hogql/direct_sql/test/test_registry_and_capability.py
+++ b/posthog/hogql/direct_sql/test/test_registry_and_capability.py
@@ -39,6 +39,11 @@ class TestDirectSQLRegistry(SimpleTestCase):
# dialect is non-None, so direct_supports_hogql is True (not raw-only).
self.assertEqual(adapter.dialect, "clickhouse")
+ def test_trino_adapter_remains_raw_only(self):
+ adapter = get_adapter("trino")
+ assert adapter is not None
+ self.assertIsNone(adapter.dialect)
+
def test_register_adapter_round_trips(self):
class FakeAdapter:
engine = "fake"
diff --git a/posthog/hogql/escape_sql.py b/posthog/hogql/escape_sql.py
index bf24f81dc3e7..a33508bdb16d 100644
--- a/posthog/hogql/escape_sql.py
+++ b/posthog/hogql/escape_sql.py
@@ -271,6 +271,13 @@ def escape_duckdb_identifier(v: str) -> str:
return _quote_postgres_wire_identifier(v, extra_reserved_keywords=DUCKDB_EXTRA_RESERVED_KEYWORDS)
+def escape_trino_identifier(v: str) -> str:
+ for character, label in (("%", "%"), ("?", "?"), ("\0", "NUL")):
+ if character in v:
+ raise QueryError(f'The Trino identifier "{v}" is not permitted as it contains the "{label}" character')
+ return '"' + v.replace('"', '""') + '"'
+
+
def escape_snowflake_identifier(v: str) -> str:
# Always double-quote: Snowflake folds unquoted identifiers to uppercase, so quoting
# preserves the column's stored case. ``%`` is rejected for parity with the other
diff --git a/posthog/hogql/printer/base.py b/posthog/hogql/printer/base.py
index 6a8883de7b1e..7970b5caa6c7 100644
--- a/posthog/hogql/printer/base.py
+++ b/posthog/hogql/printer/base.py
@@ -204,6 +204,38 @@ class BasePrinter(Visitor[str]):
raise QueryError(f"LIMIT percent is not allowed in {self.DIALECT_NAME} dialect")
return f"LIMIT {self.visit(limit)}"
+ def _append_select_limit_and_offset(
+ self, clauses: list[str | None], node: ast.SelectQuery, limit: ast.Expr | None
+ ) -> None:
+ if limit is not None:
+ if node.limit_with_ties:
+ self._assert_with_ties_supported()
+ clauses.append(self._render_select_query_limit_clause(limit, bool(node.limit_percent)))
+ if node.limit_with_ties:
+ clauses.append("WITH TIES")
+
+ if node.offset is not None:
+ clauses.append(f"OFFSET {self.visit(node.offset)}")
+
+ def _append_set_limit_and_offset(self, sql: str, node: ast.SelectSetQuery) -> str:
+ if node.limit is not None:
+ limit_str = self.visit(node.limit)
+ if node.limit_percent:
+ limit_str = self._render_set_query_limit_percent(node.limit, limit_str)
+ if node.limit_with_ties:
+ limit_str += " WITH TIES"
+ if self.pretty:
+ sql = sql.rstrip() + f"\n{self.indent(1)}LIMIT {limit_str}"
+ else:
+ sql += f" LIMIT {limit_str}"
+ if node.offset is not None:
+ offset_str = self.visit(node.offset)
+ if self.pretty:
+ sql = sql.rstrip() + f"\n{self.indent(1)}OFFSET {offset_str}"
+ else:
+ sql += f" OFFSET {offset_str}"
+ return sql
+
def _validate_within_group_for_aggregation(self, node: "ast.Call", func_meta) -> None:
"""Validate that this dialect accepts the WITHIN GROUP clause for `node`.
@@ -280,23 +312,7 @@ class BasePrinter(Visitor[str]):
ret += f" {expr.set_operator} "
ret += query
self._indent += 1
- if node.limit is not None:
- limit_str = self.visit(node.limit)
- if node.limit_percent:
- limit_str = self._render_set_query_limit_percent(node.limit, limit_str)
-
- if node.limit_with_ties:
- limit_str += " WITH TIES"
- if self.pretty:
- ret = ret.rstrip() + f"\n{self.indent(1)}LIMIT {limit_str}"
- else:
- ret += f" LIMIT {limit_str}"
- if node.offset is not None:
- offset_str = self.visit(node.offset)
- if self.pretty:
- ret = ret.rstrip() + f"\n{self.indent(1)}OFFSET {offset_str}"
- else:
- ret += f" OFFSET {offset_str}"
+ ret = self._append_set_limit_and_offset(ret, node)
if len(self.stack) > 1:
return f"({ret.strip()})"
return ret
@@ -311,6 +327,9 @@ class BasePrinter(Visitor[str]):
def _print_select_columns(self, columns: Iterable[ast.Expr]) -> list[str]:
return [self.visit(column) for column in columns]
+ def _render_group_by_all_clause(self) -> str:
+ return "GROUP BY ALL"
+
def visit_select_query(self, node: ast.SelectQuery):
# if we are the first parsed node in the tree, or a child of a SelectSetQuery, mark us as a top level query
part_of_select_union = len(self.stack) >= 2 and isinstance(self.stack[-2], ast.SelectSetQuery)
@@ -405,7 +424,7 @@ class BasePrinter(Visitor[str]):
f"PREWHERE{space}" + prewhere if prewhere else None,
f"WHERE{space}" + where if where else None,
(
- f"GROUP BY ALL"
+ self._render_group_by_all_clause()
if node.group_by_mode == "all"
else f"GROUP BY{space}GROUPING SETS ({comma.join(group_by or [])})"
if node.group_by_mode == "grouping_sets"
@@ -450,16 +469,7 @@ class BasePrinter(Visitor[str]):
f"LIMIT {self.visit(node.limit_by.n)} {f'OFFSET {self.visit(node.limit_by.offset_value)}' if node.limit_by.offset_value else ''} BY {', '.join([self.visit(expr) for expr in node.limit_by.exprs])}"
)
- if limit is not None:
- if node.limit_with_ties:
- self._assert_with_ties_supported()
- limit_str = self._render_select_query_limit_clause(limit, bool(node.limit_percent))
- clauses.append(limit_str)
- if node.limit_with_ties:
- clauses.append("WITH TIES")
-
- if node.offset is not None:
- clauses.append(f"OFFSET {self.visit(node.offset)}")
+ self._append_select_limit_and_offset(clauses, node, limit)
clauses.extend(
self._get_extra_select_clauses(
diff --git a/posthog/hogql/printer/test/test_printer.py b/posthog/hogql/printer/test/test_printer.py
index 8814ff99b930..f78a510c4e17 100644
--- a/posthog/hogql/printer/test/test_printer.py
+++ b/posthog/hogql/printer/test/test_printer.py
@@ -8519,6 +8519,7 @@ class TestDialectConstantBinding(BaseTest):
("snowflake", "snowflake"),
("redshift", "redshift"),
("duckdb", "duckdb"),
+ ("trino", "trino"),
]
def _constant(self, value: Any, dialect: HogQLDialect) -> tuple[str, dict[str, Any]]:
diff --git a/posthog/hogql/printer/test/test_trino_printer.py b/posthog/hogql/printer/test/test_trino_printer.py
new file mode 100644
index 000000000000..39b6d868fd23
--- /dev/null
+++ b/posthog/hogql/printer/test/test_trino_printer.py
@@ -0,0 +1,900 @@
+import sqlite3
+from contextlib import closing
+
+import pytest
+
+from posthog.hogql import ast
+from posthog.hogql.constants import HogQLQuerySettings
+from posthog.hogql.context import HogQLContext
+from posthog.hogql.database.database import Database
+from posthog.hogql.database.direct_trino_table import DirectTrinoTable
+from posthog.hogql.database.models import DateTimeDatabaseField, StringDatabaseField, StringJSONDatabaseField, TableNode
+from posthog.hogql.errors import QueryError
+from posthog.hogql.escape_sql import escape_trino_identifier
+from posthog.hogql.parser import parse_select
+from posthog.hogql.printer import prepare_and_print_ast, print_prepared_ast
+from posthog.hogql.transforms.trino.errors import TrinoLoweringError
+from posthog.hogql.trino_parameters import convert_pyformat_placeholders
+
+
+def _context_with_trino_table() -> HogQLContext:
+ database = Database(include_posthog_tables=False)
+ database.tables.add_child(
+ TableNode(
+ name="users",
+ table=DirectTrinoTable(
+ name="users",
+ fields={
+ "user_id": StringDatabaseField(name="user_id", nullable=False),
+ "created_at": DateTimeDatabaseField(name="created_at", nullable=False),
+ "properties": StringJSONDatabaseField(name="properties", nullable=False),
+ },
+ external_data_source_id="source-id",
+ trino_catalog="ducklake",
+ trino_schema="analytics",
+ trino_table_name="users",
+ has_complete_columns=True,
+ ),
+ )
+ )
+ return HogQLContext(
+ database=database,
+ enable_select_queries=True,
+ limit_top_select=False,
+ restricted_properties=set(),
+ )
+
+
+def test_prints_resolved_query_with_explicit_trino_locator_and_bound_value() -> None:
+ context = _context_with_trino_table()
+
+ sql, _ = prepare_and_print_ast(
+ parse_select("SELECT user_id, toDate(created_at) FROM users WHERE user_id = 'person-1'"),
+ context,
+ "trino",
+ )
+
+ assert sql == (
+ 'SELECT "users"."user_id", CAST("users"."created_at" AS DATE) '
+ 'FROM "ducklake"."analytics"."users" AS "users" WHERE ("users"."user_id" = %(hogql_val_0)s)'
+ )
+ assert context.values == {"hogql_val_0": "person-1"}
+
+
+def test_prints_trino_lambda_syntax() -> None:
+ context = HogQLContext()
+ node = ast.Lambda(args=["value"], expr=ast.Field(chain=["value"], type=ast.LambdaArgumentType(name="value")))
+
+ assert print_prepared_ast(node, context, "trino") == '"value" -> "value"'
+
+
+def test_uses_trino_arbitrary_value_aggregate_for_any_variants() -> None:
+ context = HogQLContext()
+
+ assert print_prepared_ast(ast.Call(name="any", args=[ast.Constant(value=1)]), context, "trino") == "arbitrary(1)"
+ assert (
+ print_prepared_ast(ast.Call(name="anyLast", args=[ast.Constant(value=1)]), context, "trino") == "arbitrary(1)"
+ )
+
+
+def test_rejects_table_without_trino_locator() -> None:
+ context = HogQLContext(
+ database=Database(include_posthog_tables=True),
+ enable_select_queries=True,
+ limit_top_select=False,
+ restricted_properties=set(),
+ use_new_events_schema=False,
+ apply_events_retention_floor=False,
+ )
+
+ with pytest.raises(QueryError, match="TRINO_TABLE_LOCATOR_MISSING"):
+ prepare_and_print_ast(parse_select("SELECT event FROM events"), context, "trino")
+
+
+def test_normalizes_prewhere_before_validation() -> None:
+ context = _context_with_trino_table()
+
+ sql, _ = prepare_and_print_ast(
+ parse_select("SELECT user_id FROM users PREWHERE user_id != 'blocked' WHERE user_id != 'deleted'"),
+ context,
+ "trino",
+ )
+
+ assert "PREWHERE" not in sql
+ 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",
+ )
+
+ assert error.value.feature_code == "TRINO_LIMIT_BY_DISTINCT_UNSUPPORTED"
+
+
+ ("expression", "expected"),
+ [
+ ("arrayMap(value -> value + 1, [1, 2])", 'transform(ARRAY[1, 2], "value" -> ("value" + 1))'),
+ ("arrayFilter(value -> value > 1, [1, 2])", 'filter(ARRAY[1, 2], "value" -> ("value" > 1))'),
+ ("arrayElement([1, 2], 1)", "element_at(ARRAY[1, 2], 1)"),
+ ("hasAny([1, 2], [2, 3])", "(cardinality(array_intersect(ARRAY[1, 2], ARRAY[2, 3])) > 0)"),
+ (
+ "range(2, 5)",
+ 'filter(sequence(2, greatest((5) - 1, 2)), "__hogql_range_value" -> ("__hogql_range_value" < 5))',
+ ),
+ ("tuple(1, 2).1", "(ROW(1, 2))[1]"),
+ ("extract(user_id, 'id-(.*)')", 'regexp_extract("users"."user_id", %(hogql_val_0)s, 1)'),
+ ("JSON_VALUE(user_id, '$.key')", 'json_value("users"."user_id", \'lax $.key\')'),
+ (
+ "quantileIf(0.9)(length(user_id), user_id != '')",
+ 'approx_percentile(length("users"."user_id"), 0.9) FILTER',
+ ),
+ ("argMax(user_id, created_at)", 'max_by("users"."user_id", "users"."created_at")'),
+ ("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)'),
+ ],
+)
+def test_prints_core_trino_expression_mappings(expression: str, expected: str) -> None:
+ context = _context_with_trino_table()
+
+ sql, _ = prepare_and_print_ast(parse_select(f"SELECT {expression} FROM users"), context, "trino")
+
+ assert expected in sql
+
+
+def test_coerces_strict_trino_types_after_property_lowering() -> None:
+ context = _context_with_trino_table()
+
+ sql, _ = prepare_and_print_ast(
+ parse_select(
+ "SELECT properties.duration / 1000, sum(properties.amount), properties.failed = true, "
+ "created_at >= '2026-04-01' FROM users"
+ ),
+ context,
+ "trino",
+ )
+
+ assert 'CAST(json_extract_scalar("users"."properties", %(hogql_val_0)s) AS DOUBLE) / CAST(1000 AS DOUBLE)' in sql
+ assert 'sum(CAST(json_extract_scalar("users"."properties", %(hogql_val_1)s) AS DOUBLE))' in sql
+ assert 'CAST(json_extract_scalar("users"."properties", %(hogql_val_2)s) AS BOOLEAN) = true' in sql
+ assert '"users"."created_at" >= CAST(%(hogql_val_3)s AS TIMESTAMP)' in sql
+
+
+def test_prints_iso_datetime_and_heterogeneous_concat_for_trino() -> None:
+ context = _context_with_trino_table()
+
+ sql, _ = prepare_and_print_ast(
+ parse_select("SELECT toDateTime('2025-06-03T12:00:34.000Z'), concat('ticket-', length(user_id)) FROM users"),
+ context,
+ "trino",
+ )
+
+ assert "CAST(from_iso8601_timestamp(%(hogql_val_0)s) AS TIMESTAMP)" in sql
+ assert 'concat(CAST(%(hogql_val_1)s AS VARCHAR), CAST(length("users"."user_id") AS VARCHAR))' in sql
+
+
+def test_preserves_date_return_type_for_trino_date_truncation() -> None:
+ sql, _ = prepare_and_print_ast(
+ parse_select("SELECT toStartOfMonth(created_at), toStartOfDay(created_at) FROM users"),
+ _context_with_trino_table(),
+ "trino",
+ )
+
+ assert 'CAST(date_trunc(\'month\', "users"."created_at") AS DATE)' in sql
+ assert 'date_trunc(\'day\', "users"."created_at")' in sql
+ assert 'CAST(date_trunc(\'day\', "users"."created_at") AS DATE)' not in sql
+
+
+def test_uses_trino_array_cardinality_and_lax_json_paths() -> None:
+ context = _context_with_trino_table()
+
+ sql, _ = prepare_and_print_ast(
+ parse_select(
+ "SELECT length(arrayDistinct([1, 1])), JSON_VALUE(properties, '$.items'), "
+ "JSON_VALUE(properties, 'strict $.items') FROM users"
+ ),
+ context,
+ "trino",
+ )
+
+ assert "cardinality(array_distinct(ARRAY[1, 1]))" in sql
+ assert 'json_value("users"."properties", \'lax $.items\')' in sql
+ assert 'json_value("users"."properties", \'strict $.items\')' in sql
+
+
+def test_prints_json_paths_as_bound_values() -> None:
+ context = _context_with_trino_table()
+
+ sql, _ = prepare_and_print_ast(
+ parse_select("SELECT JSONExtractString(user_id, 'key.with.dot', 2) 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]'}
+
+
+def test_lowers_event_property_backed_fields_to_the_physical_json_column() -> None:
+ context = HogQLContext(
+ database=Database(include_posthog_tables=True),
+ enable_select_queries=True,
+ trino_table_locators={"events": ("tenant", "posthog", "events")},
+ )
+
+ sql, _ = prepare_and_print_ast(
+ parse_select("SELECT events.`$session_id`, events.`$window_id`, events.`$group_0` FROM events"),
+ context,
+ "trino",
+ )
+
+ assert 'json_extract_scalar("tenant"."posthog"."events"."properties", %(hogql_val_0)s)' in sql
+ assert 'json_extract_scalar("tenant"."posthog"."events"."properties", %(hogql_val_1)s)' in sql
+ assert 'json_extract_scalar("tenant"."posthog"."events"."properties", %(hogql_val_2)s)' in sql
+ assert context.values == {
+ "hogql_val_0": '$["$session_id"]',
+ "hogql_val_1": '$["$window_id"]',
+ "hogql_val_2": '$["$group_0"]',
+ }
+
+
+def test_lowers_event_element_materializations_to_the_physical_chain() -> None:
+ context = HogQLContext(
+ database=Database(include_posthog_tables=True),
+ enable_select_queries=True,
+ trino_table_locators={"events": ("tenant", "posthog", "events")},
+ )
+
+ sql, _ = prepare_and_print_ast(
+ parse_select("SELECT elements_chain_href, elements_chain_ids FROM events"),
+ context,
+ "trino",
+ )
+
+ assert 'regexp_extract("tenant"."posthog"."events"."elements_chain", %(hogql_val_0)s, 1)' in sql
+ assert 'array_distinct(regexp_extract_all("tenant"."posthog"."events"."elements_chain"' in sql
+
+
+def test_lowers_clickhouse_select_alias_references_to_expressions() -> None:
+ context = _context_with_trino_table()
+
+ sql, _ = prepare_and_print_ast(
+ parse_select(
+ "SELECT user_id AS account_id, count() AS total FROM users "
+ "GROUP BY account_id HAVING total > 0 ORDER BY total"
+ ),
+ context,
+ "trino",
+ )
+
+ assert "GROUP BY 1" in sql
+ assert "HAVING (count(*) > 0)" in sql
+ assert "ORDER BY count(*) ASC" in sql
+
+
+ "expression, expected",
+ [
+ (
+ "''",
+ "(%(hogql_val_0)s IS NULL OR %(hogql_val_0)s = ''), "
+ "(%(hogql_val_1)s IS NOT NULL AND %(hogql_val_1)s <> '')",
+ ),
+ ("[]", "(ARRAY[] IS NULL OR cardinality(ARRAY[]) = 0), (ARRAY[] IS NOT NULL AND cardinality(ARRAY[]) > 0)"),
+ (
+ "[1]",
+ "(ARRAY[1] IS NULL OR cardinality(ARRAY[1]) = 0), (ARRAY[1] IS NOT NULL AND cardinality(ARRAY[1]) > 0)",
+ ),
+ (
+ "mapFromArrays([], [])",
+ "(map(ARRAY[], ARRAY[]) IS NULL OR cardinality(map(ARRAY[], ARRAY[])) = 0), "
+ "(map(ARRAY[], ARRAY[]) IS NOT NULL AND cardinality(map(ARRAY[], ARRAY[])) > 0)",
+ ),
+ (
+ "mapFromArrays([1], [2])",
+ "(map(ARRAY[1], ARRAY[2]) IS NULL OR cardinality(map(ARRAY[1], ARRAY[2])) = 0), "
+ "(map(ARRAY[1], ARRAY[2]) IS NOT NULL AND cardinality(map(ARRAY[1], ARRAY[2])) > 0)",
+ ),
+ ],
+)
+def test_prints_empty_according_to_resolved_argument_type(expression: str, expected: str) -> None:
+ context = _context_with_trino_table()
+
+ sql, _ = prepare_and_print_ast(
+ parse_select(f"SELECT empty({expression}), notEmpty({expression})"), context, "trino"
+ )
+
+ assert sql == f"SELECT {expected}"
+
+
[email protected]("value, expected_empty", [("", True), ("hello", False), (None, True)])
+def test_empty_string_predicates_return_expected_results(value: str | None, expected_empty: bool) -> None:
+ context = HogQLContext()
+ argument = ast.Constant(value=value, type=ast.StringType(nullable=True))
+ empty_sql = print_prepared_ast(ast.Call(name="empty", args=[argument]), context, "trino")
+ not_empty_sql = print_prepared_ast(ast.Call(name="notEmpty", args=[argument]), context, "trino")
+ sql, values = convert_pyformat_placeholders(f"SELECT {empty_sql}, {not_empty_sql}", context.values)
+
+ with closing(sqlite3.connect(":memory:")) as connection:
+ assert connection.execute(sql, values).fetchone() == (expected_empty, not expected_empty)
+
+
+def test_rejects_empty_for_unsupported_types_with_stable_error() -> None:
+ context = _context_with_trino_table()
+
+ with pytest.raises(TrinoLoweringError) as error:
+ prepare_and_print_ast(parse_select("SELECT notEmpty(1)"), context, "trino")
+
+ assert error.value.feature_code == "TRINO_EMPTY_ARGUMENT_TYPE_UNSUPPORTED"
+
+
+def test_prints_empty_for_lowered_json_property_after_second_resolution() -> None:
+ context = _context_with_trino_table()
+
+ sql, _ = prepare_and_print_ast(
+ parse_select("SELECT notEmpty(properties.task_run_id) FROM users"),
+ context,
+ "trino",
+ )
+
+ assert 'json_extract_scalar("users"."properties", %(hogql_val_0)s) <> \'\'' in sql
+ assert context.values == {"hogql_val_0": '$["task_run_id"]'}
+
+
+def test_rejects_function_argument_shapes_with_stable_error() -> None:
+ context = _context_with_trino_table()
+
+ with pytest.raises(TrinoLoweringError) as error:
+ prepare_and_print_ast(parse_select("SELECT JSONExtractKeysAndValuesRaw('{}', 'extra')"), context, "trino")
+
+ assert error.value.feature_code == "TRINO_FUNCTION_ARGUMENTS_UNSUPPORTED"
+
+
+ ("source", "expected"),
+ [
+ ("numbers(3)", "sequence(0, greatest((3) - 1, 0))"),
+ ("numbers(4, 2)", "sequence(4, greatest((6) - 1, 4))"),
+ ("numbers(0)", "sequence(0, greatest((0) - 1, 0))"),
+ ],
+)
+def test_lowers_numbers_to_bounded_unnest(source: str, expected: str) -> None:
+ context = HogQLContext(
+ database=Database(include_posthog_tables=True),
+ enable_select_queries=True,
+ limit_top_select=False,
+ restricted_properties=set(),
+ )
+
+ sql, _ = prepare_and_print_ast(parse_select(f"SELECT number FROM {source}"), context, "trino")
+
+ assert f"FROM UNNEST(filter({expected}" in sql
+ assert 'AS "numbers" ("number")' in sql
+
+
+def test_rejects_unbounded_numbers_input() -> None:
+ context = HogQLContext(
+ database=Database(include_posthog_tables=True),
+ enable_select_queries=True,
+ limit_top_select=False,
+ 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")
+
+ assert error.value.feature_code == "TRINO_NUMBERS_NON_CONSTANT_ARGUMENT"
+
+
+def test_lowers_single_array_join_to_cross_join_unnest() -> None:
+ context = _context_with_trino_table()
+
+ sql, _ = prepare_and_print_ast(
+ parse_select("SELECT item FROM users ARRAY JOIN [1, 2] AS item"),
+ context,
+ "trino",
+ )
+
+ assert (
+ 'CROSS JOIN UNNEST(transform(ARRAY[1, 2], "__trino_unnest_0_value" -> ROW("__trino_unnest_0_value"))) '
+ 'AS "__trino_unnest_0" ("item")'
+ in sql
+ and 'SELECT "__trino_unnest_0"."item"' in sql
+ )
+
+
+def test_rejects_multi_array_join_with_different_cardinality_semantics() -> 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",
+ )
+
+ assert error.value.feature_code == "TRINO_ARRAY_JOIN_MULTIPLE_ARRAYS_UNSUPPORTED"
+
+
+def test_lowers_array_join_function_to_cross_join_unnest() -> None:
+ context = _context_with_trino_table()
+
+ sql, _ = prepare_and_print_ast(
+ parse_select("SELECT arrayJoin([1, 2]) AS item FROM users"),
+ context,
+ "trino",
+ )
+
+ assert 'SELECT "__trino_array_function_0"."value_0" AS "item"' in sql
+ assert (
+ 'CROSS JOIN UNNEST(transform(ARRAY[1, 2], "__trino_array_function_0_value" -> '
+ 'ROW("__trino_array_function_0_value"))) AS "__trino_array_function_0" ("value_0")' in sql
+ )
+
+
+def test_lowers_limit_by_to_row_number_wrapper() -> None:
+ context = _context_with_trino_table()
+
+ sql, _ = prepare_and_print_ast(
+ parse_select("SELECT user_id, created_at FROM users ORDER BY created_at DESC LIMIT 2 BY user_id LIMIT 5"),
+ context,
+ "trino",
+ )
+
+ assert 'row_number() OVER (PARTITION BY "users"."user_id" ORDER BY "users"."created_at" DESC)' in sql
+ assert 'WHERE ("__hogql_trino_source_0"."__hogql_limit_by_row_0" <= 2)' in sql
+ assert 'ORDER BY "__hogql_trino_source_0"."created_at" DESC LIMIT 5' in sql
+ assert "LIMIT 2 BY" not in sql
+
+
+def test_lowers_qualify_alias_to_outer_filter() -> None:
+ context = _context_with_trino_table()
+
+ sql, _ = prepare_and_print_ast(
+ parse_select(
+ "SELECT user_id, row_number() OVER (PARTITION BY user_id ORDER BY created_at DESC) AS position "
+ "FROM users QUALIFY position = 1"
+ ),
+ context,
+ "trino",
+ )
+
+ assert 'AS "position" FROM "ducklake"."analytics"."users"' in sql
+ assert 'WHERE ("__hogql_trino_source_0"."position" = 1)' in sql
+ assert "QUALIFY" not in sql
+
+
+def test_lowers_window_count_distinct_without_unsupported_distinct_window_aggregate() -> None:
+ context = _context_with_trino_table()
+
+ sql, _ = prepare_and_print_ast(
+ parse_select("SELECT countDistinct(user_id) OVER (PARTITION BY created_at) FROM users"),
+ context,
+ "trino",
+ )
+
+ assert "cardinality(array_distinct(filter(array_agg(" in sql
+ assert 'OVER (PARTITION BY "users"."created_at")' in sql
+ assert "count(DISTINCT" not in sql
+
+
+ ("type_name", "expected"),
+ [
+ ("Array(String)", "ARRAY(VARCHAR)"),
+ ("Nullable(Array(UInt64))", "ARRAY(DECIMAL(20, 0))"),
+ ("Decimal(18, 2)", "DECIMAL(18,2)"),
+ ("DateTime64(6)", "TIMESTAMP(6)"),
+ ("FixedString(8)", "CHAR(8)"),
+ ("timestamp with time zone", "TIMESTAMP WITH TIME ZONE"),
+ ],
+)
+def test_renders_allowlisted_trino_cast_types(type_name: str, expected: str) -> None:
+ query = parse_select("SELECT user_id FROM users")
+ assert isinstance(query, ast.SelectQuery)
+ query.select[0] = ast.TypeCast(expr=query.select[0], type_name=type_name)
+
+ sql, _ = prepare_and_print_ast(query, _context_with_trino_table(), "trino")
+
+ assert f" AS {expected})" in sql
+
+
+ "type_name",
+ [
+ "varchar); DROP TABLE users; --",
+ "decimal(39,0)",
+ "decimal(2,3)",
+ "timestamp(13)",
+ "char(1,2)",
+ ],
+)
+def test_rejects_invalid_trino_cast_types(type_name: str) -> None:
+ query = parse_select("SELECT user_id FROM users")
+ assert isinstance(query, ast.SelectQuery)
+ query.select[0] = ast.TypeCast(expr=query.select[0], type_name=type_name)
+
+ with pytest.raises(TrinoLoweringError) as error:
+ prepare_and_print_ast(query, _context_with_trino_table(), "trino")
+
+ assert error.value.feature_code == "TRINO_CAST_TYPE_UNSUPPORTED"
+
+
+ ("query", "expected_suffix"),
+ [
+ ("SELECT user_id FROM users LIMIT 10 OFFSET 4", "OFFSET 4 ROWS LIMIT 10"),
+ (
+ "SELECT user_id FROM users ORDER BY user_id LIMIT 10 WITH TIES",
+ "FETCH FIRST 10 ROWS WITH TIES",
+ ),
+ ],
+)
+def test_prints_trino_limit_syntax(query: str, expected_suffix: str) -> None:
+ sql, _ = prepare_and_print_ast(parse_select(query), _context_with_trino_table(), "trino")
+
+ assert sql.endswith(expected_suffix)
+
+
+def test_prints_trino_limit_syntax_after_set_operation() -> None:
+ query = parse_select("SELECT user_id FROM users UNION ALL SELECT user_id FROM users")
+ assert isinstance(query, ast.SelectSetQuery)
+ query.limit = ast.Constant(value=10)
+ query.offset = ast.Constant(value=4)
+
+ sql, _ = prepare_and_print_ast(query, _context_with_trino_table(), "trino")
+
+ assert sql.endswith("OFFSET 4 ROWS LIMIT 10")
+
+
+def test_rejects_non_literal_trino_limit() -> None:
+ query = parse_select("SELECT user_id FROM users")
+ assert isinstance(query, ast.SelectQuery)
+ query.limit = ast.Call(name="least", args=[ast.Constant(value=10), ast.Constant(value=20)])
+
+ with pytest.raises(TrinoLoweringError) as error:
+ prepare_and_print_ast(query, _context_with_trino_table(), "trino")
+
+ assert error.value.feature_code == "TRINO_ROW_COUNT_NON_LITERAL"
+
+
+def test_rejects_with_fill_before_printing_invalid_trino_sql() -> None:
+ with pytest.raises(TrinoLoweringError) as error:
+ prepare_and_print_ast(
+ parse_select("SELECT user_id FROM users ORDER BY user_id WITH FILL"),
+ _context_with_trino_table(),
+ "trino",
+ )
+
+ assert error.value.feature_code == "TRINO_WITH_FILL_UNSUPPORTED"
+
+
+ ("expression", "expected"),
+ [
+ ("user_id ILIKE 'person-%'", 'lower("users"."user_id") LIKE lower(%(hogql_val_0)s)'),
+ (
+ "uniq(user_id, created_at)",
+ 'count(DISTINCT ROW("users"."user_id", "users"."created_at"))',
+ ),
+ ("toDateTime64(created_at, 6)", 'CAST("users"."created_at" AS TIMESTAMP(6))'),
+ (
+ "dateAdd(toDate('2026-01-01'), toIntervalMonth(1))",
+ "(CAST(%(hogql_val_0)s AS DATE) + (CAST(1 AS BIGINT) * INTERVAL '1' MONTH))",
+ ),
+ ("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)))',
+ ),
+ ("['a', 'b'][2:]", "slice(ARRAY[%(hogql_val_0)s, %(hogql_val_1)s], 2, 2147483647)"),
+ ],
+)
+def test_prints_additional_semantics_safe_trino_expressions(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"),
+ [
+ ("endsWith(user_id, '1')", 'ends_with("users"."user_id", %(hogql_val_0)s)'),
+ ("mapFromArrays(['a'], [1])", "map(ARRAY[%(hogql_val_0)s], ARRAY[1])"),
+ (
+ "mapUpdate(mapFromArrays(['a'], [1]), mapFromArrays(['a'], [2]))",
+ "map_concat(map(ARRAY[%(hogql_val_0)s], ARRAY[1]), map(ARRAY[%(hogql_val_1)s], ARRAY[2]))",
+ ),
+ ("in(user_id, ('a', 'b'))", '"users"."user_id" IN (%(hogql_val_0)s, %(hogql_val_1)s)'),
+ ("notIn(user_id, ('a', 'b'))", '"users"."user_id" NOT IN (%(hogql_val_0)s, %(hogql_val_1)s)'),
+ ("toDateTime(created_at, 'UTC')", 'with_timezone(CAST("users"."created_at" AS TIMESTAMP),'),
+ ("toTimeZone(created_at, 'America/Toronto')", "at_timezone(with_timezone(CAST("),
+ ("parseDateTime(user_id, '%Y-%m-%d')", 'TRY(date_parse("users"."user_id",'),
+ ("dateAdd('day', 2, created_at)", 'date_add(%(hogql_val_0)s, 2, "users"."created_at")'),
+ ("dateSub('day', 2, created_at)", 'date_add(%(hogql_val_0)s, -(2), "users"."created_at")'),
+ ("date_diff('day', created_at, created_at)", 'date_diff(%(hogql_val_0)s, "users"."created_at"'),
+ ("dateTrunc('month', created_at, 'UTC')", "date_trunc(%(hogql_val_0)s, at_timezone("),
+ ("toISOWeek(created_at)", 'EXTRACT(WEEK FROM "users"."created_at")'),
+ ("toISOYear(created_at)", 'EXTRACT(YEAR_OF_WEEK FROM "users"."created_at")'),
+ ("toYYYYMM(created_at)", 'CAST(date_format("users"."created_at", \'%Y%m\') AS INTEGER)'),
+ ("toYYYYMMDD(created_at)", 'CAST(date_format("users"."created_at", \'%Y%m%d\') AS INTEGER)'),
+ (
+ "toYYYYMMDDhhmmss(created_at)",
+ 'CAST(date_format("users"."created_at", \'%Y%m%d%H%i%s\') AS BIGINT)',
+ ),
+ ("toLastDayOfWeek(created_at)", "CAST(date_add('day', 5, date_trunc('week',"),
+ ("toLastDayOfWeek(created_at, 1)", "CAST(date_add('day', 6, date_trunc('week',"),
+ ("toIntervalQuarter(2)", "CAST(2 AS BIGINT) * INTERVAL '3' MONTH"),
+ ("toIntervalYear(2)", "CAST(2 AS BIGINT) * INTERVAL '12' MONTH"),
+ ("toIntervalWeek(2)", "CAST(2 AS BIGINT) * INTERVAL '7' DAY"),
+ ("toIntOrDefault(user_id, 7)", 'COALESCE(TRY_CAST("users"."user_id" AS BIGINT), CAST(7 AS BIGINT))'),
+ ("toNullable(user_id)", '"users"."user_id"'),
+ ("_toDate(user_id)", 'CAST("users"."user_id" AS DATE)'),
+ ("anyIf(user_id, user_id != '')", 'arbitrary("users"."user_id") FILTER (WHERE'),
+ ("countIf(user_id, user_id != '')", 'count("users"."user_id") FILTER (WHERE'),
+ ("repeat(user_id, 2)", 'ELSE array_join(repeat("users"."user_id", 2), \'\') END'),
+ ("5 / 2", "(CAST(5 AS DOUBLE) / CAST(2 AS DOUBLE))"),
+ ("divide(5, 2)", "(CAST(5 AS DOUBLE) / CAST(2 AS DOUBLE))"),
+ ("not(user_id = '')", '(NOT ("users"."user_id" = %(hogql_val_0)s))'),
+ ("toMonday(created_at)", 'CAST(date_trunc(\'week\', "users"."created_at") AS DATE)'),
+ ("yesterday()", "date_add('day', -1, CURRENT_DATE)"),
+ ("md5(user_id)", 'to_hex(md5(to_utf8(CAST("users"."user_id" AS VARCHAR))))'),
+ ("power(2, 3)", "power(2, 3)"),
+ ("ln(2)", "ln(2)"),
+ ("log2(2)", "log2(2)"),
+ ("cbrt(8)", "cbrt(8)"),
+ ("degrees(1)", "degrees(1)"),
+ ("radians(1)", "radians(1)"),
+ ("pi()", "pi()"),
+ ("sign(-1)", "sign(-1)"),
+ ("sin(1)", "sin(1)"),
+ ("cos(1)", "cos(1)"),
+ ("tan(1)", "tan(1)"),
+ ("asin(1)", "asin(1)"),
+ ("acos(1)", "acos(1)"),
+ ("atan(1)", "atan(1)"),
+ ("atan2(1, 2)", "atan2(1, 2)"),
+ ("trim(' x ', ' ')", "trim(%(hogql_val_0)s, %(hogql_val_1)s)"),
+ ("ltrim(' x ', ' ')", "ltrim(%(hogql_val_0)s, %(hogql_val_1)s)"),
+ ("rtrim(' x ', ' ')", "rtrim(%(hogql_val_0)s, %(hogql_val_1)s)"),
+ ("reverse(user_id)", 'reverse("users"."user_id")'),
+ ("replace(user_id, 'a', 'b')", 'replace("users"."user_id",'),
+ ("lpad(user_id, 3, '0')", 'lpad("users"."user_id", 3,'),
+ ("rpad(user_id, 3, '0')", 'rpad("users"."user_id", 3,'),
+ ("e()", "e()"),
+ ],
+)
+def test_prints_safe_pr_91053_function_mappings(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_prints_typed_json_map_and_trino_try_cast() -> None:
+ query = parse_select("SELECT JSONExtract(properties, 'Map(String, Float64)') FROM users")
+ assert isinstance(query, ast.SelectQuery)
+ query.select.append(ast.TryCast(expr=ast.Field(chain=["users", "user_id"]), type_name="BIGINT"))
+
+ sql, _ = prepare_and_print_ast(query, _context_with_trino_table(), "trino")
+
+ assert "AS MAP(VARCHAR, DOUBLE))" in sql
+ assert 'TRY_CAST("users"."user_id" AS BIGINT)' in sql
+
+
+def test_rejects_parse_datetime_format_without_matching_trino_semantics() -> None:
+ with pytest.raises(TrinoLoweringError) as error:
+ prepare_and_print_ast(
+ parse_select("SELECT parseDateTime(user_id, '%Q') FROM users"),
+ _context_with_trino_table(),
+ "trino",
+ )
+
+ assert error.value.feature_code == "TRINO_DATETIME_FORMAT_UNSUPPORTED"
+
+
+def test_rejects_map_from_arrays_with_duplicate_keys() -> None:
+ with pytest.raises(TrinoLoweringError) as error:
+ prepare_and_print_ast(
+ parse_select("SELECT mapFromArrays(['a', 'a'], [1, 2])"),
+ _context_with_trino_table(),
+ "trino",
+ )
+
+ assert error.value.feature_code == "TRINO_MAP_DUPLICATE_KEYS_UNSUPPORTED"
+
+
+ "expression",
+ [
+ "formatReadableTimeDelta(1)",
+ "intDiv(5, 2)",
+ "medianIf(1, true)",
+ "multiplyDecimal(1, 2)",
+ "_toInt16(40000)",
+ ],
+)
+def test_rejects_pr_91053_shortcuts_without_matching_trino_semantics(expression: str) -> None:
+ with pytest.raises(TrinoLoweringError) as error:
+ prepare_and_print_ast(
+ parse_select(f"SELECT {expression}"),
+ _context_with_trino_table(),
+ "trino",
+ )
+
+ assert error.value.feature_code == "TRINO_FUNCTION_UNSUPPORTED"
+
+
[email protected]("identifier", ["parameter?", "parameter%", "nul\0identifier"])
+def test_rejects_trino_identifiers_that_can_collide_with_parameter_binding(identifier: str) -> None:
+ with pytest.raises(QueryError):
+ escape_trino_identifier(identifier)
+
+
+ ("expression", "expected"),
+ [
+ ("any(user_id) OVER ()", 'arbitrary("users"."user_id") OVER ()'),
+ ("groupArray(user_id) OVER ()", 'array_agg("users"."user_id") OVER ()'),
+ (
+ "countIf(user_id != '') OVER ()",
+ 'count_if(("users"."user_id" != %(hogql_val_0)s)) OVER ()',
+ ),
+ ],
+)
+def test_prints_semantics_safe_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", "feature_code"),
+ [
+ ("lag(user_id) OVER ()", "TRINO_WINDOW_ORDER_REQUIRED"),
+ (
+ "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:
+ 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
+
+
[email protected]("modifier", ["distinct", "filter"])
+def test_rejects_aggregate_modifiers_on_scalar_trino_calls(modifier: str) -> None:
+ query = parse_select("SELECT toDecimal(user_id, 2) FROM users")
+ assert isinstance(query, ast.SelectQuery)
+ call = query.select[0]
+ assert isinstance(call, ast.Call)
+ if modifier == "distinct":
+ call.distinct = True
+ else:
+ call.filter_expr = ast.Constant(value=True)
+
+ with pytest.raises(TrinoLoweringError) as error:
+ prepare_and_print_ast(query, _context_with_trino_table(), "trino")
+
+ assert error.value.feature_code == "TRINO_SCALAR_FUNCTION_MODIFIER_UNSUPPORTED"
+
+
+def test_lowers_left_any_join_by_deduplicating_the_right_relation() -> 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 = 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 'WHERE ("__hogql_any_ranked_0"."__hogql_any_row_0" = 1)' in sql
+ assert ') AS "other" ON ("users"."user_id" = "other"."user_id")' in sql
+
+
+ ("join", "constraint", "feature_code"),
+ [
+ ("RIGHT 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"),
+ ],
+)
+def test_rejects_unsafe_any_join_shapes(join: str, constraint: str, feature_code: str) -> None:
+ with pytest.raises(TrinoLoweringError) as error:
+ prepare_and_print_ast(
+ parse_select(f"SELECT users.user_id FROM users {join} users AS other ON {constraint}"),
+ _context_with_trino_table(),
+ "trino",
+ )
+
+ assert error.value.feature_code == feature_code
+
+
+ ("join", "expected"),
+ [
+ ("ALL INNER JOIN", "INNER JOIN"),
+ ("LEFT ALL JOIN", "LEFT JOIN"),
+ ("RIGHT ALL JOIN", "RIGHT JOIN"),
+ ("FULL ALL JOIN", "FULL JOIN"),
+ ],
+)
+def test_lowers_clickhouse_all_join_to_standard_trino_join(join: str, expected: 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 f" {expected} " in sql
+ assert f" {join} " not in sql
+
+
+def test_removes_noop_sample_one_for_trino() -> None:
+ sql, _ = prepare_and_print_ast(
+ parse_select("SELECT user_id FROM users SAMPLE 1"),
+ _context_with_trino_table(),
+ "trino",
+ )
+
+ assert "SAMPLE" not in sql
+
+
+ ("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 UNPIVOT(value FOR key IN (user_id))",
+ "TRINO_UNPIVOT_UNSUPPORTED",
+ ),
+ ],
+)
+def test_rejects_clickhouse_query_clauses_without_safe_trino_semantics(query: str, feature_code: str) -> None:
+ with pytest.raises(TrinoLoweringError) as error:
+ prepare_and_print_ast(parse_select(query), _context_with_trino_table(), "trino")
+
+ assert error.value.feature_code == feature_code
+
+
+def test_rejects_source_ast_with_clickhouse_settings() -> None:
+ query = parse_select("SELECT user_id FROM users")
+ assert isinstance(query, ast.SelectQuery)
+ query.settings = HogQLQuerySettings(optimize_aggregation_in_order=True)
+
+ with pytest.raises(TrinoLoweringError) as error:
+ prepare_and_print_ast(query, _context_with_trino_table(), "trino")
+
+ assert error.value.feature_code == "TRINO_SETTINGS_UNSUPPORTED"
diff --git a/posthog/hogql/printer/trino.py b/posthog/hogql/printer/trino.py
new file mode 100644
index 000000000000..ac642d661084
--- /dev/null
+++ b/posthog/hogql/printer/trino.py
@@ -0,0 +1,1280 @@
+import re
+from collections.abc import Callable, Iterable
+from typing import TYPE_CHECKING, ClassVar, NoReturn
+
+from posthog.hogql import ast
+from posthog.hogql.constants import HogQLDialect
+from posthog.hogql.database.schema.numbers import NumbersTable
+from posthog.hogql.database.trino_locator import resolve_trino_table_locator
+from posthog.hogql.database.trino_unnest_table import TrinoUnnestTable
+from posthog.hogql.escape_sql import escape_trino_identifier
+from posthog.hogql.functions import find_hogql_aggregation
+from posthog.hogql.printer.postgres import PostgresPrinter
+from posthog.hogql.printer.trino_functions import (
+ TRINO_FUNCTION_HANDLERS_LOWER,
+ TRINO_FUNCTION_RENAMES_LOWER,
+ TRINO_PASSTHROUGH_FUNCTIONS,
+)
+from posthog.hogql.printer.types import JoinExprResponse
+from posthog.hogql.transforms.trino.errors import TrinoLoweringError
+from posthog.hogql.visitor import clone_expr
+
+from posthog.dataclasses import frozen
+
+if TYPE_CHECKING:
+ from posthog.hogql.database.models import Table
+
+_TRINO_SIMPLE_TYPES = {
+ "bigint": "BIGINT",
+ "bool": "BOOLEAN",
+ "boolean": "BOOLEAN",
+ "date": "DATE",
+ "datetime": "TIMESTAMP",
+ "double": "DOUBLE",
+ "double precision": "DOUBLE",
+ "float": "DOUBLE",
+ "float32": "REAL",
+ "float64": "DOUBLE",
+ "int": "BIGINT",
+ "int8": "TINYINT",
+ "int16": "SMALLINT",
+ "int32": "INTEGER",
+ "int64": "BIGINT",
+ "integer": "INTEGER",
+ "json": "JSON",
+ "real": "REAL",
+ "smallint": "SMALLINT",
+ "string": "VARCHAR",
+ "text": "VARCHAR",
+ "timestamp": "TIMESTAMP",
+ "timestamp with local time zone": "TIMESTAMP WITH TIME ZONE",
+ "timestamp with time zone": "TIMESTAMP WITH TIME ZONE",
+ "timestamptz": "TIMESTAMP WITH TIME ZONE",
+ "tinyint": "TINYINT",
+ "uint8": "SMALLINT",
+ "uint16": "INTEGER",
+ "uint32": "BIGINT",
+ "uint64": "DECIMAL(20, 0)",
+ "uuid": "UUID",
+ "varbinary": "VARBINARY",
+ "varchar": "VARCHAR",
+}
+_TRINO_PARAMETERIZED_TYPE_RE = re.compile(
+ r"^(decimal|numeric|varchar|char|fixedstring|datetime64|timestamp)\s*\((\d+(?:\s*,\s*\d+)?)\)$",
+ re.IGNORECASE,
+)
+_TRINO_JOIN_TYPES = frozenset(
+ {
+ "JOIN",
+ "INNER JOIN",
+ "LEFT JOIN",
+ "LEFT OUTER JOIN",
+ "RIGHT JOIN",
+ "RIGHT OUTER JOIN",
+ "FULL JOIN",
+ "FULL OUTER JOIN",
+ "CROSS JOIN",
+ }
+)
+_TRINO_SET_OPERATORS = frozenset(
+ {
+ "UNION DISTINCT",
+ "UNION ALL",
+ "INTERSECT DISTINCT",
+ "INTERSECT ALL",
+ "INTERSECT",
+ "EXCEPT DISTINCT",
+ "EXCEPT ALL",
+ "EXCEPT",
+ }
+)
+_TRINO_WINDOW_FUNCTIONS = frozenset(
+ {
+ "arbitrary",
+ "array_agg",
+ "avg",
+ "count",
+ "cume_dist",
+ "dense_rank",
+ "first_value",
+ "lag",
+ "last_value",
+ "lead",
+ "max",
+ "max_by",
+ "min",
+ "min_by",
+ "nth_value",
+ "ntile",
+ "percent_rank",
+ "rank",
+ "row_number",
+ "sum",
+ }
+)
+_TRINO_WINDOW_FUNCTION_RENAMES = {
+ "any": "arbitrary",
+ "anylast": "arbitrary",
+ "argmax": "max_by",
+ "argmin": "min_by",
+ "grouparray": "array_agg",
+}
+_TRINO_CONDITIONAL_WINDOW_FUNCTIONS = {
+ "anyif": "arbitrary",
+ "avgif": "avg",
+ "countif": "count",
+ "grouparrayif": "array_agg",
+ "maxif": "max",
+ "minif": "min",
+ "sumif": "sum",
+}
+_TRINO_NO_FRAME_WINDOW_FUNCTIONS = frozenset(
+ {"cume_dist", "dense_rank", "lag", "lead", "ntile", "percent_rank", "rank", "row_number"}
+)
+_TRINO_EXTRACT_FIELDS = frozenset(
+ {
+ "day",
+ "day_of_week",
+ "day_of_year",
+ "dow",
+ "doy",
+ "hour",
+ "minute",
+ "month",
+ "quarter",
+ "second",
+ "timezone_hour",
+ "timezone_minute",
+ "week",
+ "year",
+ "year_of_week",
+ "yow",
+ }
+)
+_TRINO_DATE_PARSE_SPECIFIERS = frozenset(
+ {"%%", "%Y", "%y", "%m", "%c", "%d", "%e", "%H", "%k", "%h", "%I", "%l", "%i", "%s", "%S", "%f", "%p", "%T", "%r"}
+)
+
+
+@frozen
+class _BinaryArguments:
+ left: str
+ right: str
+
+
+class TrinoPrinter(PostgresPrinter):
+ DIALECT_NAME: ClassVar[HogQLDialect] = "trino"
+ DIALECT_LABEL: ClassVar[str] = "Trino"
+
+ def _print_identifier(self, name: str) -> str:
+ return escape_trino_identifier(name)
+
+ def _get_function_renames(self) -> dict[str, str]:
+ return TRINO_FUNCTION_RENAMES_LOWER
+
+ def _get_function_handlers(self) -> dict[str, Callable[[list[str]], str]]:
+ return TRINO_FUNCTION_HANDLERS_LOWER
+
+ def _get_passthrough_functions(self) -> frozenset[str]:
+ return TRINO_PASSTHROUGH_FUNCTIONS
+
+ def _get_connection_supported_functions(self) -> set[str]:
+ return set()
+
+ def _render_group_by_all_clause(self) -> str:
+ return "GROUP BY AUTO"
+
+ def _assert_set_operator_supported(self, set_operator: str) -> None:
+ if set_operator not in _TRINO_SET_OPERATORS:
+ self._unsupported(
+ "TRINO_SET_OPERATOR_UNSUPPORTED",
+ f"Set operator '{set_operator}' is not supported in Trino mode.",
+ )
+
+ @staticmethod
+ def _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
+ ):
+ raise TrinoLoweringError(
+ "TRINO_ROW_COUNT_NON_LITERAL",
+ clause,
+ value,
+ detail=f"{clause} must be a non-negative integer literal in Trino mode.",
+ )
+ return value.value
+
+ def _append_select_limit_and_offset(
+ self, clauses: list[str | None], node: ast.SelectQuery, limit: ast.Expr | None
+ ) -> None:
+ if node.offset is not None:
+ clauses.append(f"OFFSET {self._validate_row_count(node.offset, 'OFFSET')} ROWS")
+ if limit is None:
+ return
+ count = self._validate_row_count(limit, "LIMIT")
+ if node.limit_percent:
+ self._unsupported("TRINO_LIMIT_PERCENT_UNSUPPORTED", "LIMIT PERCENT is not supported in Trino mode.")
+ if node.limit_with_ties:
+ if not node.order_by:
+ self._unsupported(
+ "TRINO_WITH_TIES_ORDER_REQUIRED",
+ "LIMIT WITH TIES requires ORDER BY in Trino mode.",
+ node,
+ )
+ clauses.append(f"FETCH FIRST {count} ROWS WITH TIES")
+ else:
+ clauses.append(f"LIMIT {count}")
+
+ def _append_set_limit_and_offset(self, sql: str, node: ast.SelectSetQuery) -> str:
+ suffixes: list[str] = []
+ if node.offset is not None:
+ suffixes.append(f"OFFSET {self._validate_row_count(node.offset, 'OFFSET')} ROWS")
+ if node.limit is not None:
+ count = self._validate_row_count(node.limit, "LIMIT")
+ if node.limit_percent:
+ self._unsupported("TRINO_LIMIT_PERCENT_UNSUPPORTED", "LIMIT PERCENT is not supported in Trino mode.")
+ if node.limit_with_ties:
+ self._unsupported(
+ "TRINO_SET_WITH_TIES_UNSUPPORTED",
+ "WITH TIES is not supported on Trino set queries.",
+ node,
+ )
+ suffixes.append(f"LIMIT {count}")
+ if not suffixes:
+ return sql
+ separator = f"\n{self.indent(1)}" if self.pretty else " "
+ return sql.rstrip() + separator + separator.join(suffixes)
+
+ def _unsupported(self, feature_code: str, detail: str, node: ast.Expr | None = None) -> NoReturn:
+ construct = node.name if isinstance(node, ast.Call) else node.__class__.__name__ if node else detail
+ raise TrinoLoweringError(feature_code, construct, node, detail=detail)
+
+ def _invalid_function_arguments(self, node: ast.Call, detail: str) -> NoReturn:
+ self._unsupported("TRINO_FUNCTION_ARGUMENTS_UNSUPPORTED", detail, node)
+
+ def visit_call(self, node: ast.Call) -> str:
+ name = node.name.lower()
+ 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
+ ):
+ self._unsupported(
+ "TRINO_SCALAR_FUNCTION_MODIFIER_UNSUPPORTED",
+ f"Scalar function '{node.name}' does not accept aggregate modifiers in Trino mode.",
+ node,
+ )
+ if name in {"empty", "notempty"}:
+ return self._visit_empty(node, negated=name == "notempty")
+ if name in {"in", "notin"}:
+ binary_args = self._visit_binary_args(node)
+ return f"({binary_args.left} {'NOT IN' if name == 'notin' else 'IN'} {binary_args.right})"
+ if name == "mapfromarrays":
+ return self._visit_map_from_arrays(node)
+ 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:
+ arg = node.args[0]
+ arg_type = arg.type.resolve_constant_type(self.context) if arg.type is not None else None
+ rendered = self.visit(arg)
+ if isinstance(arg_type, ast.DateType):
+ return f"date_diff('day', DATE '1970-01-01', {rendered})"
+ if isinstance(arg_type, ast.DateTimeType):
+ 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 == "todatetime" and node.args:
+ value_expr = node.args[0]
+ if (
+ isinstance(value_expr, ast.Constant)
+ and isinstance(value_expr.value, str)
+ and re.search(r"T.*(?:Z|[+-]\d\d:\d\d)$", value_expr.value)
+ ):
+ timestamp = f"from_iso8601_timestamp({self.visit(value_expr)})"
+ if len(node.args) == 1:
+ return f"CAST({timestamp} AS TIMESTAMP)"
+ if len(node.args) == 2:
+ return f"at_timezone({timestamp}, {self.visit(node.args[1])})"
+ self._invalid_function_arguments(
+ node, "toDateTime expects a value and optional timezone in Trino mode."
+ )
+ if len(node.args) == 2:
+ return f"with_timezone(CAST({self.visit(value_expr)} AS TIMESTAMP), {self.visit(node.args[1])})"
+ if name == "totimezone":
+ binary_args = self._visit_binary_args(node)
+ 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 == "tolastdayofweek":
+ return self._visit_to_last_day_of_week(node)
+ if name == "todatetime64":
+ return self._visit_to_datetime64(node)
+ if name == "concat":
+ if node.distinct or node.order_by:
+ self._unsupported(
+ "TRINO_CONCAT_MODIFIER_UNSUPPORTED",
+ "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)})"
+ if name == "repeat":
+ binary_args = self._visit_binary_args(node)
+ return (
+ f"CASE WHEN {binary_args.left} IS NULL OR {binary_args.right} IS NULL THEN NULL "
+ f"ELSE array_join(repeat({binary_args.left}, {binary_args.right}), '') END"
+ )
+ if name == "sum" and len(node.args) == 1 and self._is_dynamic_property(node.args[0]):
+ lowered = clone_expr(node)
+ lowered.args = [ast.Call(name="toFloat", args=[lowered.args[0]])]
+ return super().visit_call(lowered)
+ if name in {
+ "jsonextract",
+ "jsonextractstring",
+ "jsonextractraw",
+ "jsonextractarrayraw",
+ "jsonextractint",
+ "jsonextractuint",
+ "jsonextractfloat",
+ "jsonextractbool",
+ }:
+ return self._visit_json_extract(node)
+ if name in {"jsonextractkeys", "jsonextractkeysandvaluesraw", "jsonhas", "jsonlength"}:
+ return self._visit_json_metadata(node)
+ if name == "jsonextractkeysandvalues":
+ return self._visit_json_metadata(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 == "arrayelement":
+ return self._visit_binary_function(node, "element_at")
+ if name == "arraydistinct":
+ return self._visit_unary_function(node, "array_distinct")
+ if name == "extractall":
+ if len(node.args) != 2:
+ 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":
+ return 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":
+ return self._visit_array_first(node)
+ if name == "arrayconcat":
+ return self._visit_variadic_function(node, "concat", minimum=2)
+ if name == "arraysum":
+ return self._visit_unary_function(node, "array_sum")
+ if name == "has":
+ return self._visit_binary_function(node, "contains")
+ if name == "hasany":
+ binary_args = self._visit_binary_args(node)
+ return f"(cardinality(array_intersect({binary_args.left}, {binary_args.right})) > 0)"
+ if name == "hasall":
+ binary_args = self._visit_binary_args(node)
+ return f"(cardinality(array_except({binary_args.right}, {binary_args.left})) = 0)"
+ if name == "range":
+ return self._visit_range(node)
+ if name in {"argmax", "argmin"}:
+ return self._visit_binary_function(node, "max_by" if name == "argmax" else "min_by")
+ 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]
+ target = "max_by" if name == "argmaxif" else "min_by"
+ return f"{target}({values[0]}, {values[1]}) FILTER (WHERE {values[2]})"
+ if name == "groupuniqarray":
+ if len(node.args) != 1:
+ self._invalid_function_arguments(node, "groupUniqArray expects exactly 1 argument in Trino mode.")
+ return f"array_agg(DISTINCT {self.visit(node.args[0])})"
+ if name == "grouparrayif":
+ if len(node.args) != 2:
+ self._invalid_function_arguments(node, "groupArrayIf expects exactly 2 arguments in Trino mode.")
+ return f"array_agg({self.visit(node.args[0])}) FILTER (WHERE {self.visit(node.args[1])})"
+ if name == "groupuniqarrayif":
+ if len(node.args) != 2:
+ self._invalid_function_arguments(node, "groupUniqArrayIf expects exactly 2 arguments in Trino mode.")
+ 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 == "todecimal":
+ return self._visit_to_decimal(node)
+ if name == "tuple":
+ return f"ROW({', '.join(self.visit(arg) for arg in node.args)})"
+ if name == "tupleelement":
+ return self._visit_tuple_element(node)
+ if name == "match":
+ return self._visit_binary_function(node, "regexp_like")
+ if name in {"splitbychar", "splitbystring"}:
+ binary_args = self._visit_binary_args(node)
+ return f"split({binary_args.right}, {binary_args.left})"
+ if name == "md5":
+ rendered_value = self._visit_unary_arg(node)
+ return f"to_hex(md5(to_utf8(CAST({rendered_value} AS VARCHAR))))"
+ if name == "extract":
+ return self._visit_extract(node)
+ if name in {"quantile", "quantileif"}:
+ return self._visit_quantile(node, filtered=name == "quantileif")
+ if name in {"dateadd", "datesub"}:
+ if len(node.args) == 2:
+ binary_args = self._visit_binary_args(node)
+ return f"({binary_args.left} {'+' if name == 'dateadd' else '-'} {binary_args.right})"
+ if len(node.args) == 3:
+ unit, amount, value = (self.visit(arg) for arg in node.args)
+ if name == "datesub":
+ amount = f"-({amount})"
+ return f"date_add({unit}, {amount}, {value})"
+ self._invalid_function_arguments(node, f"{node.name} expects two or three arguments in Trino mode.")
+ 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})"
+ if name == "date_part":
+ return self._visit_date_part(node)
+ if name == "json_value":
+ return self._visit_json_value(node)
+ return super().visit_call(node)
+
+ def visit_join_expr(self, node: ast.JoinExpr) -> JoinExprResponse:
+ if node.join_type is not None and node.join_type not in _TRINO_JOIN_TYPES:
+ self._unsupported(
+ "TRINO_JOIN_TYPE_UNSUPPORTED",
+ f"Join type '{node.join_type}' is not supported in Trino mode.",
+ node,
+ )
+ if node.constraint is not None and node.join_type in {None, "CROSS JOIN"}:
+ self._unsupported(
+ "TRINO_JOIN_CONSTRAINT_UNSUPPORTED",
+ f"{node.join_type or 'FROM'} does not accept a join constraint in Trino mode.",
+ node,
+ )
+ return super().visit_join_expr(node)
+
+ def visit_named_argument(self, node: ast.NamedArgument) -> NoReturn:
+ self._unsupported(
+ "TRINO_NAMED_ARGUMENT_UNSUPPORTED",
+ "Named arguments are not supported in Trino mode.",
+ node,
+ )
+
+ def visit_order_expr(self, node: ast.OrderExpr) -> str:
+ if node.with_fill is not None:
+ self._unsupported("TRINO_WITH_FILL_UNSUPPORTED", "WITH FILL is not supported in Trino mode.", node)
+ return super().visit_order_expr(node)
+
+ def visit_compare_operation(self, node: ast.CompareOperation) -> str:
+ left_type = self._resolve_type(node.left)
+ right_type = self._resolve_type(node.right)
+ left_cast: str | None = None
+ right_cast: str | None = None
+
+ if 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"
+ elif isinstance(left_type, ast.DateType) and isinstance(right_type, ast.StringType):
+ right_cast = "DATE"
+ elif isinstance(right_type, ast.DateType) and isinstance(left_type, ast.StringType):
+ left_cast = "DATE"
+ 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"
+ else:
+ return super().visit_compare_operation(node)
+
+ left = self.visit(node.left)
+ right = self.visit(node.right)
+ if left_cast is not None:
+ left = f"CAST({left} AS {left_cast})"
+ if right_cast is not None:
+ right = f"CAST({right} AS {right_cast})"
+ return self._get_compare_op(node.op, left, right)
+
+ def visit_arithmetic_operation(self, node: ast.ArithmeticOperation) -> str:
+ left = self.visit(node.left)
+ right = self.visit(node.right)
+ if node.op == ast.ArithmeticOperationOp.Div:
+ return f"(CAST({left} AS DOUBLE) / CAST({right} AS DOUBLE))"
+ lowered = False
+ if self._is_dynamic_property(node.left) and self._is_numeric(node.right):
+ left = f"CAST({left} AS DOUBLE)"
+ lowered = True
+ if self._is_dynamic_property(node.right) and self._is_numeric(node.left):
+ right = f"CAST({right} AS DOUBLE)"
+ lowered = True
+ operators = {
+ ast.ArithmeticOperationOp.Add: "+",
+ ast.ArithmeticOperationOp.Sub: "-",
+ ast.ArithmeticOperationOp.Mult: "*",
+ ast.ArithmeticOperationOp.Mod: "%",
+ }
+ operator = operators.get(node.op)
+ if operator is not None and lowered:
+ return f"({left} {operator} {right})"
+ 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
+
+ def _is_dynamic_property(self, node: ast.Expr) -> bool:
+ while isinstance(node, ast.Alias):
+ node = node.expr
+ return isinstance(node, ast.PropertyAccess)
+
+ def _is_numeric(self, node: ast.Expr) -> bool:
+ return isinstance(self._resolve_type(node), (ast.IntegerType, ast.FloatType, ast.DecimalType))
+
+ def _visit_json_extract(self, node: ast.Call) -> str:
+ name = node.name.lower()
+ if name == "jsonextractarrayraw" and len(node.args) == 1:
+ source = self.visit(node.args[0])
+ value = self._print_identifier("__hogql_json_value")
+ return (
+ f"transform(CAST(json_parse(CAST({source} AS VARCHAR)) AS ARRAY(JSON)), "
+ f"{value} -> json_format({value}))"
+ )
+ if 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)
+ path_members: list[str | int] = []
+ for key in node.args[1:]:
+ if not isinstance(key, ast.Constant) or not isinstance(key.value, (str, int)):
+ self._unsupported(
+ "TRINO_JSON_DYNAMIC_PATH_UNSUPPORTED",
+ f"{node.name} requires a constant key path in Trino mode.",
+ 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})"
+ casts = {
+ "jsonextractint": "BIGINT",
+ "jsonextractuint": "DECIMAL(20, 0)",
+ "jsonextractfloat": "DOUBLE",
+ "jsonextractbool": "BOOLEAN",
+ }
+ target_type = casts.get(name)
+ return scalar if target_type is None else f"CAST({scalar} AS {target_type})"
+
+ def _visit_typed_json_extract(self, node: ast.Call) -> str:
+ type_arg = node.args[-1]
+ if not isinstance(type_arg, ast.Constant) or not isinstance(type_arg.value, str):
+ self._unsupported(
+ "TRINO_JSON_DYNAMIC_TARGET_TYPE_UNSUPPORTED",
+ "JSONExtract requires a constant target type in Trino mode.",
+ node,
+ )
+ target = self._trino_json_type(type_arg.value, node)
+ path_members: list[str | int] = []
+ for key in node.args[1:-1]:
+ if not isinstance(key, ast.Constant) or not isinstance(key.value, (str, int)):
+ self._unsupported(
+ "TRINO_JSON_DYNAMIC_PATH_UNSUPPORTED",
+ "JSONExtract requires a constant key path in Trino mode.",
+ node,
+ )
+ path_members.append(key.value)
+ source = self.visit(node.args[0])
+ path = self._json_path(path_members)
+ extractor = "json_extract" if target.startswith(("ARRAY", "MAP")) else "json_extract_scalar"
+ return f"CAST({extractor}({source}, {path}) AS {target})"
+
+ def _trino_json_type(self, type_name: str, node: ast.Call) -> str:
+ normalized = " ".join(type_name.strip().lower().split())
+ scalar_types = {
+ "bool": "BOOLEAN",
+ "float32": "REAL",
+ "float64": "DOUBLE",
+ "int8": "TINYINT",
+ "int16": "SMALLINT",
+ "int32": "INTEGER",
+ "int64": "BIGINT",
+ "string": "VARCHAR",
+ "uint8": "SMALLINT",
+ "uint16": "INTEGER",
+ "uint32": "BIGINT",
+ "uint64": "DECIMAL(20, 0)",
+ }
+ target = scalar_types.get(normalized)
+ if target is not None:
+ return target
+ if normalized.startswith("nullable(") and normalized.endswith(")"):
+ return self._trino_json_type(normalized[9:-1], node)
+ if normalized.startswith("array(") and normalized.endswith(")"):
+ return f"ARRAY({self._trino_json_type(normalized[6:-1], node)})"
+ if normalized.startswith("map(") and normalized.endswith(")"):
+ arguments = self._split_type_arguments(normalized[4:-1])
+ if len(arguments) == 2 and arguments[0] == "string":
+ return f"MAP(VARCHAR, {self._trino_json_type(arguments[1], node)})"
+ self._unsupported(
+ "TRINO_JSON_TARGET_TYPE_UNSUPPORTED",
+ f"JSONExtract target type '{type_name}' is not supported in Trino mode.",
+ node,
+ )
+
+ def _visit_json_metadata(self, node: ast.Call) -> str:
+ name = node.name.lower()
+ if name == "jsonextractkeysandvaluesraw":
+ if len(node.args) != 1:
+ self._invalid_function_arguments(
+ node, "JSONExtractKeysAndValuesRaw expects exactly 1 argument in Trino mode."
+ )
+ source = self.visit(node.args[0])
+ 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])))"
+ )
+ 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:]
+ target_type: str | None = None
+ if name == "jsonextractkeysandvalues":
+ if not path_args or not isinstance(path_args[-1], ast.Constant) or not isinstance(path_args[-1].value, str):
+ self._invalid_function_arguments(
+ node, "JSONExtractKeysAndValues requires a constant target type in Trino mode."
+ )
+ target_types = {
+ "bool": "BOOLEAN",
+ "float64": "DOUBLE",
+ "int64": "BIGINT",
+ "string": "VARCHAR",
+ "uint64": "DECIMAL(20, 0)",
+ }
+ target_type = target_types.get(path_args[-1].value.lower())
+ if target_type is None:
+ self._unsupported(
+ "TRINO_JSON_TARGET_TYPE_UNSUPPORTED",
+ f"JSONExtractKeysAndValues target type '{path_args[-1].value}' is not supported in Trino mode.",
+ node,
+ )
+ path_args = path_args[:-1]
+ path_members: list[str | int] = []
+ 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",
+ f"{node.name} requires a constant key path in Trino mode.",
+ node,
+ )
+ path_members.append(key.value)
+ path = self._json_path(path_members)
+ if name == "jsonhas":
+ return f"(json_extract({source}, {path}) IS NOT NULL)"
+ if name == "jsonlength":
+ return f"json_size({source}, {path})"
+ 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)))"
+
+ def _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.")
+ precision = 3
+ if len(node.args) == 2:
+ precision_arg = node.args[1]
+ if (
+ not isinstance(precision_arg, ast.Constant)
+ or isinstance(precision_arg.value, bool)
+ or not isinstance(precision_arg.value, int)
+ or not 0 <= precision_arg.value <= 12
+ ):
+ self._unsupported(
+ "TRINO_DATETIME_PRECISION_UNSUPPORTED",
+ "toDateTime64 requires an integer precision from 0 to 12 in Trino mode.",
+ node,
+ )
+ precision = precision_arg.value
+ return f"CAST({self.visit(node.args[0])} AS TIMESTAMP({precision}))"
+
+ 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."
+ )
+ format_arg = node.args[1]
+ if not isinstance(format_arg, ast.Constant) or not isinstance(format_arg.value, str):
+ self._unsupported(
+ "TRINO_DATETIME_FORMAT_NON_CONSTANT",
+ "parseDateTime requires a constant format in Trino mode.",
+ node,
+ )
+ directives = re.findall(r"%.", format_arg.value)
+ if any(directive not in _TRINO_DATE_PARSE_SPECIFIERS for directive in directives):
+ self._unsupported(
+ "TRINO_DATETIME_FORMAT_UNSUPPORTED",
+ "parseDateTime uses a format directive that does not have matching Trino semantics.",
+ node,
+ )
+ parsed = f"TRY(date_parse({self.visit(node.args[0])}, {self.visit(format_arg)}))"
+ if len(node.args) == 3:
+ return f"with_timezone({parsed}, {self.visit(node.args[2])})"
+ return parsed
+
+ def _visit_to_last_day_of_week(self, node: ast.Call) -> str:
+ if len(node.args) not in {1, 2}:
+ self._invalid_function_arguments(node, "toLastDayOfWeek expects a value and optional mode in Trino mode.")
+ mode = 0
+ if len(node.args) == 2:
+ mode_arg = node.args[1]
+ if (
+ not isinstance(mode_arg, ast.Constant)
+ or isinstance(mode_arg.value, bool)
+ or not isinstance(mode_arg.value, int)
+ or not 0 <= mode_arg.value <= 9
+ ):
+ self._unsupported(
+ "TRINO_WEEK_MODE_UNSUPPORTED",
+ "toLastDayOfWeek requires a constant ClickHouse week mode from 0 to 9 in Trino mode.",
+ node,
+ )
+ mode = mode_arg.value
+ day_offset = 5 if mode % 2 == 0 else 6
+ value = self.visit(node.args[0])
+ return f"CAST(date_add('day', {day_offset}, date_trunc('week', {value})) AS DATE)"
+
+ def _visit_date_part(self, node: ast.Call) -> str:
+ if len(node.args) != 2:
+ self._invalid_function_arguments(node, "date_part expects a unit and value in Trino mode.")
+ unit = node.args[0]
+ if (
+ not isinstance(unit, ast.Constant)
+ or not isinstance(unit.value, str)
+ or unit.value.lower() not in _TRINO_EXTRACT_FIELDS
+ ):
+ self._unsupported(
+ "TRINO_DATE_PART_UNIT_UNSUPPORTED",
+ "date_part requires a supported constant unit in Trino mode.",
+ node,
+ )
+ return f"EXTRACT({unit.value.upper()} FROM {self.visit(node.args[1])})"
+
+ def _visit_to_json_string(self, node: ast.Call) -> str:
+ value = self._visit_unary_arg(node)
+ return f"json_format(CAST({value} AS JSON))"
+
+ def _visit_empty(self, node: ast.Call, *, negated: bool) -> str:
+ if len(node.args) != 1:
+ self._invalid_function_arguments(node, f"{node.name} expects exactly 1 argument in Trino mode.")
+ arg = node.args[0]
+ rendered = self.visit(arg)
+ value_expr = arg
+ while isinstance(value_expr, ast.Alias):
+ value_expr = value_expr.expr
+ arg_type = self._resolve_type(value_expr)
+ if isinstance(value_expr, ast.PropertyAccess):
+ arg_type = ast.StringType(nullable=True)
+ conjunction = "AND" if negated else "OR"
+ if isinstance(arg_type, (ast.ArrayType, ast.MapType)):
+ comparison = "> 0" if negated else "= 0"
+ return f"({rendered} IS {'NOT ' if negated else ''}NULL {conjunction} cardinality({rendered}) {comparison})"
+ if isinstance(arg_type, ast.StringType):
+ comparison = "<> ''" if negated else "= ''"
+ return f"({rendered} IS {'NOT ' if negated else ''}NULL {conjunction} {rendered} {comparison})"
+ self._unsupported(
+ "TRINO_EMPTY_ARGUMENT_TYPE_UNSUPPORTED",
+ f"{node.name} requires a string, array, or map argument in Trino mode.",
+ node,
+ )
+
+ def _json_path(self, members: Iterable[str | int]) -> str:
+ path = "$"
+ for member in members:
+ if isinstance(member, int):
+ path += f"[{member}]"
+ else:
+ escaped = str(member).replace("\\", "\\\\").replace('"', '\\"')
+ path += f'["{escaped}"]'
+ return self.context.add_value(path)
+
+ def _visit_lambda_array_call(self, node: ast.Call, target: str) -> str:
+ 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_unary_function(self, node: ast.Call, target: str) -> str:
+ return f"{target}({self._visit_unary_arg(node)})"
+
+ def _visit_unary_arg(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.")
+ return self.visit(node.args[0])
+
+ def _visit_binary_args(self, node: ast.Call) -> _BinaryArguments:
+ if len(node.args) != 2:
+ self._invalid_function_arguments(node, f"{node.name} expects exactly 2 arguments in Trino mode.")
+ return _BinaryArguments(left=self.visit(node.args[0]), right=self.visit(node.args[1]))
+
+ def _visit_binary_function(self, node: ast.Call, target: str) -> str:
+ binary_args = self._visit_binary_args(node)
+ return f"{target}({binary_args.left}, {binary_args.right})"
+
+ def _visit_variadic_function(self, node: ast.Call, target: str, minimum: int) -> str:
+ if len(node.args) < minimum:
+ self._invalid_function_arguments(node, f"{node.name} expects at least {minimum} arguments in Trino mode.")
+ return f"{target}({', '.join(self.visit(arg) for arg in node.args)})"
+
+ def _visit_range(self, node: ast.Call) -> str:
+ if len(node.args) == 1:
+ start = "0"
+ end = self.visit(node.args[0])
+ elif len(node.args) == 2:
+ start = self.visit(node.args[0])
+ end = self.visit(node.args[1])
+ 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}))"
+
+ 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
+ ):
+ 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 keys.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")
+
+ 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)"
+ array_type = node.args[1].type.resolve_constant_type(self.context) if node.args[1].type is not None else None
+ if not isinstance(array_type, ast.ArrayType):
+ self._unsupported(
+ "TRINO_ARRAY_FIRST_TYPE_UNRESOLVED",
+ "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.visit(ast.Constant(value=default))})"
+
+ def _visit_count_distinct(self, node: ast.Call) -> str:
+ if not node.args:
+ self._invalid_function_arguments(node, "countDistinct expects at least one argument in Trino mode.")
+ arguments = [self.visit(arg) for arg in node.args]
+ value = arguments[0] if len(arguments) == 1 else f"ROW({', '.join(arguments)})"
+ return f"count(DISTINCT {value})"
+
+ 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.")
+ scale = node.args[1]
+ if not isinstance(scale, ast.Constant) or isinstance(scale.value, bool) or not isinstance(scale.value, int):
+ self._unsupported(
+ "TRINO_DECIMAL_NON_CONSTANT_SCALE",
+ "toDecimal requires a constant integer scale in Trino mode.",
+ node,
+ )
+ if scale.value < 0 or scale.value > 38:
+ self._unsupported(
+ "TRINO_DECIMAL_SCALE_OUT_OF_RANGE",
+ "toDecimal scale must be between 0 and 38 in Trino mode.",
+ node,
+ )
+ return f"CAST({self.visit(node.args[0])} AS DECIMAL(38, {scale.value}))"
+
+ 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.")
+ index = node.args[1]
+ if not isinstance(index, ast.Constant) or isinstance(index.value, bool) or not isinstance(index.value, int):
+ self._unsupported(
+ "TRINO_TUPLE_ELEMENT_NON_CONSTANT_INDEX",
+ "tupleElement requires a constant integer index in Trino mode.",
+ node,
+ )
+ if index.value < 1:
+ self._unsupported(
+ "TRINO_TUPLE_ELEMENT_INDEX_OUT_OF_RANGE",
+ "tupleElement index must be positive in Trino mode.",
+ node,
+ )
+ source = node.args[0]
+ if isinstance(source, ast.Call) and source.name.lower() == "tuple":
+ if index.value > len(source.args):
+ self._unsupported(
+ "TRINO_TUPLE_ELEMENT_INDEX_OUT_OF_RANGE",
+ "tupleElement index is out of range in Trino mode.",
+ node,
+ )
+ return self.visit(source.args[index.value - 1])
+ return f"({self.visit(source)})[{index.value}]"
+
+ 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.")
+ pattern = node.args[1]
+ if not isinstance(pattern, ast.Constant) or not isinstance(pattern.value, str):
+ self._unsupported(
+ "TRINO_EXTRACT_DYNAMIC_PATTERN_UNSUPPORTED",
+ "extract requires a constant regular expression in Trino mode.",
+ node,
+ )
+ group = self._first_regex_capture_group(pattern.value)
+ extracted = f"regexp_extract({self.visit(node.args[0])}, {self.visit(pattern)}, {group})"
+ return f"coalesce({extracted}, {self.visit(ast.Constant(value=''))})"
+
+ def _first_regex_capture_group(self, pattern: str) -> int:
+ escaped = False
+ in_character_class = False
+ for index, character in enumerate(pattern):
+ if escaped:
+ escaped = False
+ continue
+ if character == "\\":
+ escaped = True
+ continue
+ if character == "[":
+ in_character_class = True
+ continue
+ if character == "]":
+ in_character_class = False
+ continue
+ if character == "(" and not in_character_class and pattern[index + 1 : index + 2] != "?":
+ return 1
+ return 0
+
+ def _visit_quantile(self, node: ast.Call, *, filtered: bool) -> str:
+ expected_arguments = 2 if filtered else 1
+ if len(node.args) != expected_arguments or node.params is None or len(node.params) != 1:
+ self._invalid_function_arguments(node, f"{node.name} expects one percentile parameter in Trino mode.")
+ aggregate = f"approx_percentile({self.visit(node.args[0])}, {self.visit(node.params[0])})"
+ if filtered:
+ aggregate += f" FILTER (WHERE {self.visit(node.args[1])})"
+ return aggregate
+
+ 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.")
+ path = node.args[1]
+ if not isinstance(path, ast.Constant) or not isinstance(path.value, str):
+ self._unsupported(
+ "TRINO_JSON_DYNAMIC_PATH_UNSUPPORTED",
+ "JSON_VALUE requires a constant path in Trino mode.",
+ node,
+ )
+ if "\0" in path.value:
+ self._unsupported(
+ "TRINO_JSON_PATH_INVALID",
+ "JSON_VALUE path contains an invalid NUL character.",
+ node,
+ )
+ 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})"
+
+ def _print_table_sql(self, table: "Table") -> str:
+ return self._print_table(table)
+
+ def _print_table(self, table: "Table") -> str:
+ if isinstance(table, NumbersTable):
+ return "UNNEST"
+ if isinstance(table, TrinoUnnestTable):
+ return table.to_printed_trino(self.context)
+ locator = resolve_trino_table_locator(table, self.context)
+ if locator is not None:
+ return ".".join(escape_trino_identifier(part) for part in locator)
+ self._unsupported(
+ "TRINO_TABLE_LOCATOR_MISSING",
+ f"Table '{table.name or table.__class__.__name__}' has no Trino physical locator.",
+ )
+
+ def visit_lambda(self, node: ast.Lambda) -> str:
+ identifiers = [self._print_identifier(arg) for arg in node.args]
+ if not identifiers:
+ self._unsupported(
+ "TRINO_LAMBDA_ARGUMENT_REQUIRED", "Lambdas require at least one argument in Trino mode.", node
+ )
+ arguments = identifiers[0] if len(identifiers) == 1 else f"({', '.join(identifiers)})"
+ return f"{arguments} -> {self.visit(node.expr)}"
+
+ def visit_array(self, node: ast.Array) -> str:
+ return f"ARRAY[{', '.join(self.visit(expr) for expr in node.exprs)}]"
+
+ def visit_tuple_access(self, node: ast.TupleAccess) -> str:
+ source = self.visit(node.tuple)
+ return f"({source})[{node.index}]"
+
+ def visit_positional_ref(self, node: ast.PositionalRef) -> str:
+ if not isinstance(node.index, int) or node.index < 1:
+ self._unsupported(
+ "TRINO_POSITIONAL_REFERENCE_INVALID",
+ f"Positional reference must be a positive integer, got {node.index}.",
+ node,
+ )
+ return str(node.index)
+
+ def visit_window_function(self, node: ast.WindowFunction) -> str:
+ name = node.name.lower()
+ if name == "countdistinct":
+ return self._visit_window_count_distinct(node)
+ if 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 not exprs:
+ self._unsupported(
+ "TRINO_WINDOW_FUNCTION_ARGUMENTS_UNSUPPORTED",
+ f"Window function '{node.name}' requires a condition in Trino mode.",
+ node,
+ )
+ target = _TRINO_CONDITIONAL_WINDOW_FUNCTIONS[name]
+ arguments = exprs[:-1]
+ if target == "count" and not arguments:
+ call = f"count_if({exprs[-1]})"
+ else:
+ if len(arguments) != 1:
+ self._unsupported(
+ "TRINO_WINDOW_FUNCTION_ARGUMENTS_UNSUPPORTED",
+ f"Window function '{node.name}' requires one value and one condition in Trino mode.",
+ node,
+ )
+ call = f"{target}(IF({exprs[-1]}, {arguments[0]}, NULL))"
+ else:
+ target = _TRINO_WINDOW_FUNCTION_RENAMES.get(name, name)
+ if target not in _TRINO_WINDOW_FUNCTIONS:
+ self._unsupported(
+ "TRINO_WINDOW_FUNCTION_UNSUPPORTED",
+ f"Window function '{node.name}' is not supported in Trino mode.",
+ node,
+ )
+ rendered_arguments = "*" if target == "count" and not exprs else ", ".join(exprs)
+ call = f"{target}({rendered_arguments})"
+
+ window_expr = self._window_expression(node)
+ target = _TRINO_WINDOW_FUNCTION_RENAMES.get(name, name)
+ if target in _TRINO_NO_FRAME_WINDOW_FUNCTIONS and window_expr is not None and window_expr.frame_method:
+ self._unsupported(
+ "TRINO_WINDOW_FRAME_UNSUPPORTED",
+ f"Window function '{node.name}' does not allow an explicit frame in Trino mode.",
+ node,
+ )
+ if target in {"lag", "lead"} and (window_expr is None or 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.over_expr:
+ over = f"({self.visit(node.over_expr)})"
+ elif node.over_identifier:
+ over = self._print_identifier(node.over_identifier)
+ else:
+ over = "()"
+ windowed_call = f"{call} OVER {over}"
+ if name == "grouparrayif":
+ value = self._print_identifier("__hogql_group_array_value")
+ return f"filter({windowed_call}, {value} -> {value} IS NOT NULL)"
+ return windowed_call
+
+ def _window_expression(self, node: ast.WindowFunction) -> ast.WindowExpr | None:
+ if node.over_expr is not None:
+ return node.over_expr
+ if node.over_identifier is None:
+ return None
+ select = self._last_select()
+ if select is None or select.window_exprs is None:
+ return None
+ return select.window_exprs.get(node.over_identifier)
+
+ def _visit_window_count_distinct(self, node: ast.WindowFunction) -> str:
+ if node.exprs is None or len(node.exprs) != 1 or node.args:
+ self._unsupported(
+ "TRINO_WINDOW_FUNCTION_ARGUMENTS_UNSUPPORTED",
+ "countDistinct window function expects exactly one argument in Trino mode.",
+ 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 = "()"
+ value = self._print_identifier("__hogql_count_distinct_value")
+ values = f"array_agg({self.visit(node.exprs[0])}) OVER {over}"
+ return f"cardinality(array_distinct(filter({values}, {value} -> {value} IS NOT NULL)))"
+
+ def _get_compare_op(self, op: ast.CompareOperationOp, left: str, right: str) -> str:
+ if op == ast.CompareOperationOp.ILike:
+ return f"(lower({left}) LIKE lower({right}))"
+ if op == ast.CompareOperationOp.NotILike:
+ return f"(lower({left}) NOT LIKE lower({right}))"
+ if op == ast.CompareOperationOp.Regex:
+ return f"regexp_like({left}, {right})"
+ if op == ast.CompareOperationOp.IRegex:
+ return f"regexp_like({left}, '(?i)' || {right})"
+ if op == ast.CompareOperationOp.NotRegex:
+ return f"(NOT regexp_like({left}, {right}))"
+ if op == ast.CompareOperationOp.NotIRegex:
+ return f"(NOT regexp_like({left}, '(?i)' || {right}))"
+ return super()._get_compare_op(op, left, right)
+
+ def _visit_to_start_of_call(self, node: ast.Call) -> str:
+ rendered = super()._visit_to_start_of_call(node)
+ if isinstance(self._resolve_type(node), ast.DateType):
+ return f"CAST({rendered} AS DATE)"
+ return rendered
+
+ def _render_start_of(self, unit: str, arg: str, week_mode: int = 3) -> str:
+ if unit == "week" and week_mode == 0:
+ return f"date_add('day', -1, date_trunc('week', date_add('day', 1, {arg})))"
+ if unit == "week" and week_mode not in {1, 3}:
+ 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.")
+ return f"date_trunc('{unit}', {arg})"
+
+ def _render_minute_bucket(self, arg: str, bucket_size: int) -> str:
+ return (
+ f"date_add('minute', CAST(floor(minute({arg}) / {bucket_size}) AS BIGINT) * {bucket_size}, "
+ f"date_trunc('hour', {arg}))"
+ )
+
+ def visit_array_slice(self, node: ast.ArraySlice) -> str:
+ start = self.visit(node.start_expr) if node.start_expr is not None else "1"
+ if node.end_expr is None:
+ length = "2147483647"
+ else:
+ end = self.visit(node.end_expr)
+ length = f"greatest(0, ({end}) - ({start}) + 1)"
+ return f"slice({self.visit(node.array)}, {start}, {length})"
+
+ def visit_type_cast(self, node: ast.TypeCast) -> str:
+ return f"CAST({self.visit(node.expr)} AS {self._trino_type(node.type_name)})"
+
+ def visit_try_cast(self, node: ast.TryCast) -> str:
+ return f"TRY_CAST({self.visit(node.expr)} AS {self._trino_type(node.type_name)})"
+
+ def _trino_type(self, type_name: str) -> str:
+ normalized = " ".join(type_name.strip().lower().split())
+ target = _TRINO_SIMPLE_TYPES.get(normalized)
+ if target is not None:
+ return target
+ if normalized.startswith("array(") and normalized.endswith(")"):
+ return f"ARRAY({self._trino_type(normalized[6:-1])})"
+ if normalized.startswith("map(") and normalized.endswith(")"):
+ arguments = self._split_type_arguments(normalized[4:-1])
+ if len(arguments) == 2:
+ return f"MAP({self._trino_type(arguments[0])}, {self._trino_type(arguments[1])})"
+ if normalized.startswith("nullable(") and normalized.endswith(")"):
+ return self._trino_type(normalized[9:-1])
+ match = _TRINO_PARAMETERIZED_TYPE_RE.fullmatch(normalized)
+ if match is not None:
+ base, parameters = match.groups()
+ values = [int(parameter.strip()) for parameter in parameters.split(",")]
+ normalized_base = base.lower()
+ if normalized_base in {"decimal", "numeric"}:
+ precision = values[0]
+ scale = values[1] if len(values) == 2 else 0
+ if len(values) > 2 or not 1 <= precision <= 38 or not 0 <= scale <= precision:
+ self._unsupported(
+ "TRINO_CAST_TYPE_UNSUPPORTED", f"Type '{type_name}' is not supported in Trino mode."
+ )
+ rendered_parameters = str(precision) if len(values) == 1 else f"{precision},{scale}"
+ return f"DECIMAL({rendered_parameters})"
+ if normalized_base in {"datetime64", "timestamp"}:
+ if len(values) != 1 or not 0 <= values[0] <= 12:
+ self._unsupported(
+ "TRINO_CAST_TYPE_UNSUPPORTED", f"Type '{type_name}' is not supported in Trino mode."
+ )
+ return f"TIMESTAMP({values[0]})"
+ if len(values) != 1 or values[0] < 1:
+ self._unsupported("TRINO_CAST_TYPE_UNSUPPORTED", f"Type '{type_name}' is not supported in Trino mode.")
+ rendered_base = "CHAR" if normalized_base == "fixedstring" else normalized_base.upper()
+ return f"{rendered_base}({values[0]})"
+ self._unsupported("TRINO_CAST_TYPE_UNSUPPORTED", f"Type '{type_name}' is not supported in Trino mode.")
+
+ @staticmethod
+ def _split_type_arguments(arguments: str) -> list[str]:
+ parts: list[str] = []
+ depth = 0
+ start = 0
+ for index, character in enumerate(arguments):
+ if character == "(":
+ depth += 1
+ elif character == ")":
+ depth -= 1
+ elif character == "," and depth == 0:
+ parts.append(arguments[start:index].strip())
+ start = index + 1
+ parts.append(arguments[start:].strip())
+ return parts
+
+ def _unsafe_json_extract_trim_quotes(self, unsafe_field: str, unsafe_args: list[str]) -> str:
+ if not unsafe_args:
+ return unsafe_field
+ if len(unsafe_args) != 1:
+ self._unsupported(
+ "TRINO_JSON_PROPERTY_NOT_LOWERED",
+ "Nested JSON property access must be lowered before Trino printing.",
+ )
+ return f"json_extract_scalar({unsafe_field}, {unsafe_args[0]})"
+
+ def _json_property_args(self, chain: Iterable[str | int]) -> list[str]:
+ return [self._json_path(chain)]
+
+ def _assert_qualify_supported(self) -> None:
+ self._unsupported("TRINO_QUALIFY_NOT_LOWERED", "QUALIFY must be lowered before Trino printing.")
+
+ def _assert_with_ties_supported(self) -> None:
+ 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:
+ self._unsupported(
+ "TRINO_CTE_MODIFIER_UNSUPPORTED",
+ "CTE materialization hints and USING KEY are not supported in Trino mode.",
+ node,
+ )
+ return super().visit_cte(node)
diff --git a/posthog/hogql/printer/trino_functions.py b/posthog/hogql/printer/trino_functions.py
new file mode 100644
index 000000000000..315a93dfbd6e
--- /dev/null
+++ b/posthog/hogql/printer/trino_functions.py
@@ -0,0 +1,400 @@
+from collections.abc import Callable
+
+from posthog.hogql.transforms.trino.errors import TrinoLoweringError
+
+TRINO_FUNCTION_RENAMES: dict[str, str] = {
+ "any": "arbitrary",
+ "anyLast": "arbitrary",
+ "ifNull": "coalesce",
+ "groupArray": "array_agg",
+ "JSONExtractString": "json_extract_scalar",
+ "JSONExtractRaw": "json_extract",
+ "JSONExtractArrayRaw": "json_extract",
+ "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",
+ "toLastDayOfMonth": "last_day_of_month",
+ "mapFromArrays": "map",
+ "mapUpdate": "map_concat",
+}
+
+
+def _require_args(name: str, args: list[str], count: int) -> None:
+ if len(args) != count:
+ raise _invalid_arguments(name, f"{name} expects exactly {count} arguments in Trino mode.")
+
+
+def _invalid_arguments(name: str, detail: str) -> TrinoLoweringError:
+ return TrinoLoweringError("TRINO_FUNCTION_ARGUMENTS_UNSUPPORTED", name, detail=detail)
+
+
+def _cast(name: str, trino_type: str) -> Callable[[list[str]], str]:
+ def handler(args: list[str]) -> str:
+ _require_args(name, args, 1)
+ return f"CAST({args[0]} AS {trino_type})"
+
+ return handler
+
+
+def _cast_or_default(name: str, trino_type: str, default: str) -> Callable[[list[str]], str]:
+ def handler(args: list[str]) -> str:
+ if len(args) not in {1, 2}:
+ raise _invalid_arguments(name, f"{name} expects one or two arguments in Trino mode.")
+ fallback = args[1] if len(args) == 2 else default
+ fallback = f"CAST({fallback} AS {trino_type})"
+ return f"COALESCE(TRY_CAST({args[0]} AS {trino_type}), {fallback})"
+
+ return handler
+
+
+def _extract(name: str, unit: str) -> Callable[[list[str]], str]:
+ def handler(args: list[str]) -> str:
+ _require_args(name, args, 1)
+ return f"EXTRACT({unit} FROM {args[0]})"
+
+ return handler
+
+
+def _if(args: list[str]) -> str:
+ _require_args("if", args, 3)
+ return f"CASE WHEN {args[0]} THEN {args[1]} ELSE {args[2]} END"
+
+
+def _multi_if(args: list[str]) -> str:
+ if len(args) < 3 or len(args) % 2 == 0:
+ raise _invalid_arguments("multiIf", "multiIf expects condition/value pairs and a default in Trino mode.")
+ parts = ["CASE"]
+ for index in range(0, len(args) - 1, 2):
+ parts.append(f"WHEN {args[index]} THEN {args[index + 1]}")
+ 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]})"
+ if len(args) == 2:
+ return f"count({args[0]}) FILTER (WHERE {args[1]})"
+ raise _invalid_arguments("countIf", "countIf expects one or two arguments in Trino mode.")
+
+
+def _aggregate_if(function: str) -> Callable[[list[str]], str]:
+ def handler(args: list[str]) -> str:
+ if len(args) < 2:
+ raise _invalid_arguments(f"{function}If", f"{function}If expects a value and condition in Trino mode.")
+ return f"{function}({', '.join(args[:-1])}) FILTER (WHERE {args[-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.")
+ value = args[0] if len(args) == 1 else f"ROW({', '.join(args)})"
+ return f"count(DISTINCT {value})"
+
+
+def _uniq_if(args: list[str]) -> str:
+ if len(args) < 2:
+ raise _invalid_arguments("uniqIf", "uniqIf expects a value and condition in Trino mode.")
+ values = args[:-1]
+ value = values[0] if len(values) == 1 else f"ROW({', '.join(values)})"
+ return f"count(DISTINCT {value}) FILTER (WHERE {args[-1]})"
+
+
+def _date_diff(args: list[str]) -> str:
+ _require_args("dateDiff", args, 3)
+ return f"date_diff({args[0]}, {args[1]}, {args[2]})"
+
+
+def _date_add(unit: str, sign: int = 1) -> Callable[[list[str]], str]:
+ def handler(args: list[str]) -> str:
+ _require_args("date arithmetic", args, 2)
+ amount = args[1] if sign == 1 else f"-({args[1]})"
+ return f"date_add('{unit}', {amount}, {args[0]})"
+
+ return handler
+
+
+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 handler
+
+
+def _today(args: list[str]) -> str:
+ _require_args("today", args, 0)
+ return "CURRENT_DATE"
+
+
+def _yesterday(args: list[str]) -> str:
+ _require_args("yesterday", args, 0)
+ return "date_add('day', -1, CURRENT_DATE)"
+
+
+def _to_unix_timestamp(args: list[str]) -> str:
+ _require_args("toUnixTimestamp", args, 1)
+ return f"CAST(to_unixtime({args[0]}) AS BIGINT)"
+
+
+def _binary(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 _divide(args: list[str]) -> str:
+ _require_args("divide", args, 2)
+ return f"(CAST({args[0]} AS DOUBLE) / CAST({args[1]} AS DOUBLE))"
+
+
+def _not(args: list[str]) -> str:
+ _require_args("not", args, 1)
+ return f"(NOT {args[0]})"
+
+
+def _logical(name: str, operator: str) -> Callable[[list[str]], str]:
+ def handler(args: list[str]) -> str:
+ if len(args) < 2:
+ raise _invalid_arguments(name, f"{name} expects at least two arguments in Trino mode.")
+ return f"({f' {operator} '.join(args)})"
+
+ return handler
+
+
+def _null_check(name: str, negated: bool) -> Callable[[list[str]], str]:
+ def handler(args: list[str]) -> str:
+ _require_args(name, args, 1)
+ return f"({args[0]} IS {'NOT ' if negated else ''}NULL)"
+
+ return handler
+
+
+def _identity(name: str) -> Callable[[list[str]], str]:
+ def handler(args: list[str]) -> str:
+ _require_args(name, args, 1)
+ return args[0]
+
+ return handler
+
+
+def _format_date_time(args: list[str]) -> str:
+ _require_args("formatDateTime", args, 2)
+ return f"date_format({args[0]}, {args[1]})"
+
+
+def _position(args: list[str]) -> str:
+ _require_args("position", args, 2)
+ return f"strpos({args[0]}, {args[1]})"
+
+
+def _to_monday(args: list[str]) -> str:
+ _require_args("toMonday", args, 1)
+ return f"CAST(date_trunc('week', {args[0]}) AS DATE)"
+
+
+def _to_interval_month(args: list[str]) -> str:
+ _require_args("toIntervalMonth", args, 1)
+ return f"(CAST({args[0]} AS BIGINT) * INTERVAL '1' MONTH)"
+
+
+def _scaled_month_interval(name: str, months: int) -> Callable[[list[str]], str]:
+ def handler(args: list[str]) -> str:
+ _require_args(name, args, 1)
+ return f"(CAST({args[0]} AS BIGINT) * INTERVAL '{months}' MONTH)"
+
+ return handler
+
+
+def _scaled_day_interval(name: str, days: int) -> Callable[[list[str]], str]:
+ def handler(args: list[str]) -> str:
+ _require_args(name, args, 1)
+ return f"(CAST({args[0]} AS BIGINT) * INTERVAL '{days}' DAY)"
+
+ return handler
+
+
+def _formatted_date_number(name: str, pattern: str, trino_type: str) -> Callable[[list[str]], str]:
+ def handler(args: list[str]) -> str:
+ _require_args(name, args, 1)
+ return f"CAST(date_format({args[0]}, '{pattern}') AS {trino_type})"
+
+ return handler
+
+
+def _e(args: list[str]) -> str:
+ _require_args("e", args, 0)
+ return "e()"
+
+
+def _current_timestamp(args: list[str]) -> str:
+ _require_args("current_timestamp", args, 0)
+ return "CURRENT_TIMESTAMP"
+
+
+TRINO_FUNCTION_HANDLERS: dict[str, Callable[[list[str]], str]] = {
+ "toDate": _cast("toDate", "DATE"),
+ "_toDate": _cast("_toDate", "DATE"),
+ "toDateTime": _cast("toDateTime", "TIMESTAMP"),
+ "toString": _cast("toString", "VARCHAR"),
+ "toInt": _cast("toInt", "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"),
+ "toBool": _cast("toBool", "BOOLEAN"),
+ "toUUID": _cast("toUUID", "UUID"),
+ "toYear": _extract("toYear", "YEAR"),
+ "toQuarter": _extract("toQuarter", "QUARTER"),
+ "toMonth": _extract("toMonth", "MONTH"),
+ "toDayOfMonth": _extract("toDayOfMonth", "DAY"),
+ "toDayOfWeek": _extract("toDayOfWeek", "DAY_OF_WEEK"),
+ "toDayOfYear": _extract("toDayOfYear", "DAY_OF_YEAR"),
+ "toHour": _extract("toHour", "HOUR"),
+ "toMinute": _extract("toMinute", "MINUTE"),
+ "toSecond": _extract("toSecond", "SECOND"),
+ "toISOWeek": _extract("toISOWeek", "WEEK"),
+ "toISOYear": _extract("toISOYear", "YEAR_OF_WEEK"),
+ "toYYYYMM": _formatted_date_number("toYYYYMM", "%Y%m", "INTEGER"),
+ "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,
+ "if": _if,
+ "multiIf": _multi_if,
+ "countIf": _count_if,
+ "sumIf": _aggregate_if("sum"),
+ "minIf": _aggregate_if("min"),
+ "maxIf": _aggregate_if("max"),
+ "avgIf": _aggregate_if("avg"),
+ "anyIf": _aggregate_if("arbitrary"),
+ "uniq": _uniq,
+ "uniqExact": _uniq,
+ "uniqIf": _uniq_if,
+ "uniqExactIf": _uniq_if,
+ "dateDiff": _date_diff,
+ "date_diff": _date_diff,
+ "addSeconds": _date_add("second"),
+ "addMinutes": _date_add("minute"),
+ "addHours": _date_add("hour"),
+ "addDays": _date_add("day"),
+ "addWeeks": _date_add("week"),
+ "addMonths": _date_add("month"),
+ "addQuarters": _date_add("quarter"),
+ "addYears": _date_add("year"),
+ "subtractSeconds": _date_add("second", -1),
+ "subtractMinutes": _date_add("minute", -1),
+ "subtractHours": _date_add("hour", -1),
+ "subtractDays": _date_add("day", -1),
+ "subtractWeeks": _date_add("week", -1),
+ "subtractMonths": _date_add("month", -1),
+ "subtractQuarters": _date_add("quarter", -1),
+ "subtractYears": _date_add("year", -1),
+ "toIntervalSecond": _interval("seconds"),
+ "toIntervalMinute": _interval("minutes"),
+ "toIntervalHour": _interval("hours"),
+ "toIntervalDay": _interval("days"),
+ "toIntervalWeek": _scaled_day_interval("toIntervalWeek", 7),
+ "toIntervalQuarter": _scaled_month_interval("toIntervalQuarter", 3),
+ "toIntervalYear": _scaled_month_interval("toIntervalYear", 12),
+ "today": _today,
+ "yesterday": _yesterday,
+ "equals": _binary("equals", "="),
+ "notEquals": _binary("notEquals", "<>"),
+ "greater": _binary("greater", ">"),
+ "greaterOrEquals": _binary("greaterOrEquals", ">="),
+ "less": _binary("less", "<"),
+ "lessOrEquals": _binary("lessOrEquals", "<="),
+ "plus": _binary("plus", "+"),
+ "minus": _binary("minus", "-"),
+ "multiply": _binary("multiply", "*"),
+ "divide": _divide,
+ "modulo": _binary("modulo", "%"),
+ "and": _logical("and", "AND"),
+ "or": _logical("or", "OR"),
+ "not": _not,
+ "isNull": _null_check("isNull", False),
+ "isNotNull": _null_check("isNotNull", True),
+ "assumeNotNull": _identity("assumeNotNull"),
+ "toNullable": _identity("toNullable"),
+ "formatDateTime": _format_date_time,
+ "position": _position,
+ "toMonday": _to_monday,
+ "toIntervalMonth": _to_interval_month,
+ "e": _e,
+ "current_timestamp": _current_timestamp,
+}
+
+TRINO_FUNCTION_RENAMES_LOWER = {name.lower(): target for name, target in TRINO_FUNCTION_RENAMES.items()}
+TRINO_FUNCTION_HANDLERS_LOWER = {name.lower(): handler for name, handler in TRINO_FUNCTION_HANDLERS.items()}
+
+TRINO_PASSTHROUGH_FUNCTIONS = frozenset(
+ {
+ "abs",
+ "acos",
+ "array_agg",
+ "asin",
+ "atan",
+ "atan2",
+ "avg",
+ "cardinality",
+ "cbrt",
+ "ceil",
+ "coalesce",
+ "concat",
+ "cos",
+ "count",
+ "date_trunc",
+ "degrees",
+ "dense_rank",
+ "exp",
+ "floor",
+ "greatest",
+ "json_value",
+ "lag",
+ "lead",
+ "least",
+ "length",
+ "ln",
+ "log10",
+ "log2",
+ "lower",
+ "lpad",
+ "ltrim",
+ "max",
+ "min",
+ "nullif",
+ "pow",
+ "power",
+ "pi",
+ "radians",
+ "rank",
+ "replace",
+ "reverse",
+ "round",
+ "row_number",
+ "rpad",
+ "rtrim",
+ "sign",
+ "sin",
+ "sqrt",
+ "sum",
+ "substring",
+ "tan",
+ "trim",
+ "upper",
+ }
+)
diff --git a/posthog/hogql/printer/utils.py b/posthog/hogql/printer/utils.py
index 61d9571c54e9..75bb8cbe7f42 100644
--- a/posthog/hogql/printer/utils.py
+++ b/posthog/hogql/printer/utils.py
@@ -155,6 +155,17 @@ def prepare_ast_for_printing(
context.modifiers = set_default_in_cohort_via(context.modifiers)
+ if dialect == "trino":
+ from posthog.hogql.transforms.trino.normalize import ( # noqa: PLC0415 -- load the optional backend only for Trino compilation
+ normalize_trino_ast,
+ )
+ from posthog.hogql.transforms.trino.validate import ( # noqa: PLC0415 — breaks validator → printer package cycle
+ validate_trino_source_ast,
+ )
+
+ with context.timings.measure("validate_trino_source_ast"):
+ validate_trino_source_ast(node)
+
# Load property-level access control restrictions onto the context. They are enforced only on the ClickHouse path —
# the printer wraps the JSON blob in JSONDropKeys, and property resolution declines backing columns (and reads a
# restricted property as NULL). The warehouse (Postgres / DuckDB) dialects only compile external data-warehouse
@@ -235,6 +246,19 @@ def prepare_ast_for_printing(
# wrongly pruned column fails loudly at compile time instead of emitting broken SQL.
context.cte_database_table_cache.clear()
+ if dialect == "trino":
+ with context.timings.measure("trino_structural_lowering"):
+ node = cast(_T_AST, normalize_trino_ast(node, context))
+ with context.timings.measure("resolve_types_after_trino_structural_lowering"):
+ node = clone_expr(node, clear_types=True)
+ node = resolve_types(
+ node,
+ context,
+ dialect=dialect,
+ scopes=[scope.type for scope in stack if scope.type is not None] if stack else None,
+ resolver_factory=resolver_factory,
+ )
+
if dialect in SQL_TARGET_DIALECTS:
with context.timings.measure("resolve_lazy_tables"):
resolve_lazy_tables(node, dialect, stack, context, resolver_factory=resolver_factory)
@@ -341,6 +365,18 @@ def prepare_ast_for_printing(
with context.timings.measure("resolve_in_cohorts"):
resolve_in_cohorts(node, dialect, stack, context, resolver_factory=resolver_factory)
+ if dialect == "trino":
+ from posthog.hogql.transforms.trino.validate import ( # noqa: PLC0415 — breaks validator → printer package cycle
+ validate_trino_ready_ast,
+ )
+
+ with context.timings.measure("finalize_trino_lowering"):
+ node = cast(_T_AST, normalize_trino_ast(node, context))
+ with context.timings.measure("finalize_trino_property_access"):
+ node = lower_property_access(node, context)
+ with context.timings.measure("validate_trino_ready_ast"):
+ validate_trino_ready_ast(node, context)
+
# Drop argmax_select's tuple()/tupleElement() wrap for non-nullable columns; runs last so resolved nullability is final. ClickHouse-only.
if dialect == "clickhouse":
with context.timings.measure("simplify_argmax_over_non_nullable"):
@@ -361,7 +397,14 @@ def print_prepared_ast(
with context.timings.measure("printer"):
printer_stack = cast(list[ast.AST], stack or [])
- printer_class = PRINTER_CLASSES.get(dialect)
+ if dialect == "trino":
+ from posthog.hogql.printer.trino import ( # noqa: PLC0415 -- other dialects do not need the Trino backend
+ TrinoPrinter,
+ )
+
+ printer_class: type[BasePrinter] | None = TrinoPrinter
+ else:
+ printer_class = PRINTER_CLASSES.get(dialect)
if printer_class is None:
raise InternalHogQLError(f"Invalid SQL dialect: {dialect}")
diff --git a/posthog/hogql/resolver.py b/posthog/hogql/resolver.py
index 6083db38a84b..de3282c00ce0 100644
--- a/posthog/hogql/resolver.py
+++ b/posthog/hogql/resolver.py
@@ -2139,7 +2139,7 @@ class Resolver(CloningVisitor):
return node
def visit_try_cast(self, node: ast.TryCast):
- if self.dialect not in _POSTGRES_FAMILY:
+ if self.dialect not in _POSTGRES_FAMILY and self.dialect != "trino":
raise QueryError(f"TRY_CAST is not allowed in {self.dialect} dialect")
node = cast(ast.TryCast, clone_expr(node))
node.expr = self.visit(node.expr)
@@ -2154,14 +2154,14 @@ class Resolver(CloningVisitor):
return node
def visit_positional_ref(self, node: ast.PositionalRef):
- if self.dialect not in _POSTGRES_FAMILY:
+ if self.dialect not in _POSTGRES_FAMILY and self.dialect != "trino":
raise QueryError(f"Positional references are not allowed in {self.dialect} dialect")
node = cast(ast.PositionalRef, clone_expr(node))
node.type = ast.UnknownType()
return node
def visit_array_slice(self, node: ast.ArraySlice):
- if self.dialect not in _POSTGRES_FAMILY and self.dialect != "clickhouse":
+ if self.dialect not in _POSTGRES_FAMILY and self.dialect not in {"clickhouse", "trino"}:
raise QueryError(f"Array slices are not allowed in {self.dialect} dialect")
node = cast(ast.ArraySlice, clone_expr(node))
node.array = self.visit(node.array)
diff --git a/posthog/hogql/test/test_trino_corpus.py b/posthog/hogql/test/test_trino_corpus.py
new file mode 100644
index 000000000000..251fb6650c95
--- /dev/null
+++ b/posthog/hogql/test/test_trino_corpus.py
@@ -0,0 +1,104 @@
+from typing import cast
+
+import pytest
+
+from posthog.hogql.trino_corpus import (
+ CorpusCaseResult,
+ build_corpus_manifest,
+ build_corpus_report,
+ create_corpus_run_directory,
+ write_generated_sql,
+)
+
+
+def test_manifest_tracks_all_fences_features_and_duplicates_without_sql() -> None:
+ markdown = """# Queries
+
+```sql
+SELECT number FROM numbers(3)
+```
+
+```SQL title=duplicate
+SELECT number FROM numbers(3)
+```
+
+```sql
+SELECT value FROM events ARRAY JOIN properties.items AS value LIMIT 1 BY value
+```
+"""
+
+ manifest = build_corpus_manifest(markdown)
+ queries = cast(list[dict[str, object]], manifest["queries"])
+ source = cast(dict[str, object], manifest["source"])
+
+ assert isinstance(queries, list)
+ assert [query["id"] for query in queries] == ["q0001", "q0002", "q0003"]
+ assert queries[1]["duplicateOf"] == "q0001"
+ assert queries[2]["features"] == ["array_join", "limit_by", "property_access"]
+ assert source["sqlFenceCount"] == 3
+ assert source["uniqueQueryCount"] == 2
+ assert "sql" not in queries[0]
+
+
+def test_manifest_ignores_feature_words_inside_literals_and_comments() -> None:
+ manifest = build_corpus_manifest(
+ """```sql
+SELECT 'ARRAY JOIN', 1 -- LIMIT 2 BY key
+/* numbers(3) */
+```
+"""
+ )
+
+ assert manifest["featureCounts"] == {}
+
+
+def test_report_requires_one_terminal_result_for_every_manifest_query() -> None:
+ manifest = build_corpus_manifest("""```sql
+SELECT 1
+```
+""")
+
+ with pytest.raises(ValueError, match="q0001"):
+ build_corpus_report(manifest, {})
+
+ result: CorpusCaseResult = {
+ "category": "PASS_PARSE",
+ "runtimeMs": 1.5,
+ "featureCode": None,
+ "generatedSqlSha256": "generated-hash",
+ "generatedSqlBytes": 8,
+ }
+ report = build_corpus_report(manifest, {"q0001": result})
+ report_queries = cast(list[dict[str, object]], report["queries"])
+
+ assert report["categoryCounts"] == {"PASS_PARSE": 1}
+ assert report_queries[0]["generatedSqlSha256"] == "generated-hash"
+
+
+def test_report_rejects_results_for_unknown_queries() -> None:
+ manifest = build_corpus_manifest("""```sql
+SELECT 1
+```
+""")
+ result: CorpusCaseResult = {
+ "category": "PASS_PARSE",
+ "runtimeMs": 1.5,
+ "featureCode": None,
+ "generatedSqlSha256": None,
+ "generatedSqlBytes": None,
+ }
+
+ with pytest.raises(ValueError, match="q0002"):
+ build_corpus_report(manifest, {"q0001": result, "q0002": result})
+
+
+def test_each_corpus_run_uses_a_fresh_sql_directory(tmp_path) -> None:
+ first_run = create_corpus_run_directory(tmp_path, "a" * 64)
+ write_generated_sql(first_run, "q0001", "SELECT 1")
+ second_run = create_corpus_run_directory(tmp_path, "a" * 64)
+
+ assert first_run != second_run
+ assert not list(second_run.glob("*.sql"))
+
+ with pytest.raises(ValueError, match="Invalid corpus query identifier"):
+ write_generated_sql(second_run, "../private", "SELECT 1")
diff --git a/posthog/hogql/test/test_trino_parameters.py b/posthog/hogql/test/test_trino_parameters.py
new file mode 100644
index 000000000000..e3977a89917f
--- /dev/null
+++ b/posthog/hogql/test/test_trino_parameters.py
@@ -0,0 +1,29 @@
+import pytest
+
+from posthog.hogql.errors import ExposedHogQLError
+from posthog.hogql.trino_parameters import convert_pyformat_placeholders
+
+
+def test_convert_pyformat_placeholders_preserves_occurrence_order() -> None:
+ sql, values = convert_pyformat_placeholders(
+ "SELECT %(second)s, %(first)s, %(second)s",
+ {"first": "a", "second": "b"},
+ )
+
+ assert sql == "SELECT ?, ?, ?"
+ assert values == ["b", "a", "b"]
+
+
+def test_convert_pyformat_placeholders_rejects_missing_values() -> None:
+ with pytest.raises(ExposedHogQLError, match="Missing bound value"):
+ convert_pyformat_placeholders("SELECT %(missing)s", {})
+
+
+def test_convert_pyformat_placeholders_ignores_quoted_placeholder_shapes() -> None:
+ sql, values = convert_pyformat_placeholders(
+ "SELECT '%(literal)s', \"%(identifier)s\", %(bound)s, 'it''s %(still_literal)s'",
+ {"bound": "value"},
+ )
+
+ assert sql == "SELECT '%(literal)s', \"%(identifier)s\", ?, 'it''s %(still_literal)s'"
+ assert values == ["value"]
diff --git a/posthog/hogql/test/test_trino_semantics.py b/posthog/hogql/test/test_trino_semantics.py
new file mode 100644
index 000000000000..f6a8f0d162a2
--- /dev/null
+++ b/posthog/hogql/test/test_trino_semantics.py
@@ -0,0 +1,95 @@
+from posthog.test.base import APIBaseTest
+
+from posthog.schema import HogQLQueryModifiers
+
+from posthog.hogql.context import HogQLContext
+from posthog.hogql.database.database import Database
+from posthog.hogql.parser import parse_select
+from posthog.hogql.printer import prepare_and_print_ast
+
+from posthog.schema_enums import InCohortVia, InlineCohortCalculation, PersonsOnEventsMode
+
+from products.actions.backend.models.action import Action
+from products.cohorts.backend.models.cohort import Cohort
+
+
+class TestTrinoSemantics(APIBaseTest):
+ def _semantic_context(
+ self,
+ table_names: list[str],
+ modifiers: HogQLQueryModifiers | None = None,
+ ) -> HogQLContext:
+ modifiers = modifiers or HogQLQueryModifiers()
+ return HogQLContext(
+ team_id=self.team.pk,
+ team=self.team,
+ user=self.user,
+ database=Database.create_for(
+ self.team.pk,
+ team=self.team,
+ user=self.user,
+ modifiers=modifiers,
+ ),
+ modifiers=modifiers,
+ enable_select_queries=True,
+ limit_top_select=False,
+ restricted_properties=set(),
+ use_new_events_schema=False,
+ apply_events_retention_floor=False,
+ trino_table_locators={name: ("ducklake", "analytics", name) for name in table_names},
+ )
+
+ def test_action_semantics_expand_before_trino_printing(self) -> None:
+ action = Action.objects.create(
+ team=self.team,
+ name="completed checkout",
+ steps_json=[{"event": "checkout completed"}],
+ )
+ context = self._semantic_context(["events"])
+
+ sql, _ = prepare_and_print_ast(
+ parse_select(f"SELECT event FROM events WHERE matchesAction({action.pk})"),
+ context,
+ "trino",
+ )
+
+ self.assertNotIn("matchesAction", sql)
+ self.assertIn('"ducklake"."analytics"."events"', sql)
+ self.assertIn("checkout completed", context.values.values())
+
+ def test_cohort_semantics_expand_before_trino_printing(self) -> None:
+ cohort = Cohort.objects.create(team=self.team, name="active accounts")
+ modifiers = HogQLQueryModifiers(
+ inCohortVia=InCohortVia.SUBQUERY,
+ inlineCohortCalculation=InlineCohortCalculation.OFF,
+ )
+ context = self._semantic_context(
+ ["events", "raw_cohort_people", "raw_person_distinct_id_overrides"],
+ modifiers,
+ )
+
+ sql, _ = prepare_and_print_ast(
+ parse_select(f"SELECT person_id FROM events WHERE person_id IN COHORT {cohort.pk}"),
+ context,
+ "trino",
+ )
+
+ self.assertNotIn("COHORT", sql)
+ self.assertIn('"ducklake"."analytics"."raw_cohort_people"', sql)
+
+ def test_lazy_person_join_expands_before_trino_printing(self) -> None:
+ modifiers = HogQLQueryModifiers(personsOnEventsMode=PersonsOnEventsMode.DISABLED)
+ context = self._semantic_context(
+ ["events", "raw_persons", "raw_person_distinct_ids", "raw_person_distinct_id_overrides"],
+ modifiers,
+ )
+
+ sql, _ = prepare_and_print_ast(
+ parse_select("SELECT person.properties.email FROM events"),
+ context,
+ "trino",
+ )
+
+ self.assertNotIn("person.properties.email", sql)
+ self.assertIn('"ducklake"."analytics"."raw_persons"', sql)
+ self.assertIn(" JOIN ", sql)
diff --git a/posthog/hogql/transforms/lazy_tables.py b/posthog/hogql/transforms/lazy_tables.py
index ccbae2c5b0dd..2b099e6d9125 100644
--- a/posthog/hogql/transforms/lazy_tables.py
+++ b/posthog/hogql/transforms/lazy_tables.py
@@ -160,7 +160,7 @@ class LazyFinder(TraversingVisitor):
def visit_lazy_join_type(self, node: ast.LazyJoinType):
self.found_lazy = True
- def visit_lazy_table_type(self, node: ast.TableType):
+ def visit_lazy_table_type(self, node: ast.LazyTableType):
self.found_lazy = True
def visit_field_type(self, node: ast.FieldType):
diff --git a/posthog/hogql/transforms/trino/any_join.py b/posthog/hogql/transforms/trino/any_join.py
new file mode 100644
index 000000000000..c0b6dca2a2ed
--- /dev/null
+++ b/posthog/hogql/transforms/trino/any_join.py
@@ -0,0 +1,139 @@
+from posthog.hogql import ast
+from posthog.hogql.database.models import DatabaseField
+from posthog.hogql.transforms.trino.errors import TrinoLoweringError
+from posthog.hogql.visitor import CloningVisitor
+
+_SUPPORTED_ANY_JOIN_TYPES = {
+ "ANY INNER JOIN": "INNER JOIN",
+ "LEFT ANY JOIN": "LEFT JOIN",
+}
+
+
+class TrinoAnyJoinLowerer(CloningVisitor):
+ def __init__(self) -> None:
+ super().__init__(clear_types=False)
+ self.join_index = 0
+
+ def visit_join_expr(self, node: ast.JoinExpr) -> ast.JoinExpr:
+ lowered = super().visit_join_expr(node)
+ join_type = lowered.join_type or ""
+ if "ANY" not in join_type.split():
+ return lowered
+ target_join_type = _SUPPORTED_ANY_JOIN_TYPES.get(join_type)
+ 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 lowered.column_aliases:
+ raise TrinoLoweringError(
+ "TRINO_ANY_JOIN_COLUMN_ALIASES_UNSUPPORTED", f"{join_type} with column aliases", lowered
+ )
+ if lowered.constraint is None or lowered.constraint.constraint_type != "ON":
+ 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)):
+ table_type = table_type.table_type
+ if not isinstance(table_type, ast.TableType) or not getattr(table_type.table, "has_complete_columns", False):
+ raise TrinoLoweringError(
+ "TRINO_ANY_JOIN_COMPLETE_TABLE_REQUIRED",
+ f"{join_type} against a relation without a complete 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)]
+ 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_index
+ self.join_index += 1
+ source_alias = f"__hogql_any_source_{index}"
+ ranked_alias = f"__hogql_any_ranked_{index}"
+ row_name = f"__hogql_any_row_{index}"
+ while row_name in column_names:
+ row_name += "_"
+
+ ranked = ast.SelectQuery(
+ select=[ast.Field(chain=[source_alias, name]) for name in column_names]
+ + [
+ ast.Alias(
+ alias=row_name,
+ expr=ast.WindowFunction(
+ name="row_number",
+ exprs=[],
+ over_expr=ast.WindowExpr(
+ partition_by=[ast.Field(chain=[source_alias, name]) for name in key_names]
+ ),
+ ),
+ )
+ ],
+ select_from=ast.JoinExpr(
+ table=lowered.table,
+ table_args=lowered.table_args,
+ alias=source_alias,
+ ),
+ )
+ deduplicated = ast.SelectQuery(
+ select=[ast.Field(chain=[ranked_alias, name]) for name in column_names],
+ select_from=ast.JoinExpr(table=ranked, alias=ranked_alias),
+ where=ast.CompareOperation(
+ left=ast.Field(chain=[ranked_alias, row_name]),
+ right=ast.Constant(value=1),
+ op=ast.CompareOperationOp.Eq,
+ ),
+ )
+
+ lowered.join_type = target_join_type
+ lowered.table = deduplicated
+ lowered.table_args = None
+ lowered.column_aliases = None
+ return lowered
+
+ def _right_key_names(self, constraint: ast.Expr, alias: str) -> list[str]:
+ terms = constraint.exprs if isinstance(constraint, ast.And) else [constraint]
+ key_names: list[str] = []
+ for term in terms:
+ if not isinstance(term, ast.CompareOperation) or term.op != ast.CompareOperationOp.Eq:
+ raise TrinoLoweringError(
+ "TRINO_ANY_JOIN_EQUI_KEYS_REQUIRED",
+ "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):
+ 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))
+
+ def _right_field_name(self, expression: ast.Expr, alias: str) -> str | None:
+ while isinstance(expression, ast.Alias):
+ expression = expression.expr
+ if not isinstance(expression, ast.Field):
+ return None
+ field_type = expression.type
+ while isinstance(field_type, ast.FieldAliasType):
+ field_type = field_type.type
+ if not isinstance(field_type, ast.FieldType):
+ return None
+ table_type = field_type.table_type
+ while isinstance(table_type, ast.ColumnAliasedTableType):
+ table_type = table_type.table_type
+ if isinstance(table_type, ast.TableAliasType) and table_type.alias == alias:
+ return field_type.name
+ return None
+
+
+def lower_trino_any_joins(node: ast.AST) -> ast.AST:
+ return TrinoAnyJoinLowerer().visit(node)
diff --git a/posthog/hogql/transforms/trino/errors.py b/posthog/hogql/transforms/trino/errors.py
new file mode 100644
index 000000000000..2ef56c9a0756
--- /dev/null
+++ b/posthog/hogql/transforms/trino/errors.py
@@ -0,0 +1,20 @@
+from posthog.hogql import ast
+from posthog.hogql.errors import QueryError
+
+
+class TrinoLoweringError(QueryError):
+ code_name = "hogql_trino_unsupported"
+
+ def __init__(
+ self,
+ feature_code: str,
+ construct: str,
+ node: ast.Expr | None = None,
+ *,
+ detail: str | None = None,
+ ) -> None:
+ super().__init__(
+ f"[{feature_code}] {detail or f'{construct} is not supported by the Trino backend.'}", node=node
+ )
+ self.feature_code = feature_code
+ self.construct = construct
diff --git a/posthog/hogql/transforms/trino/normalize.py b/posthog/hogql/transforms/trino/normalize.py
new file mode 100644
index 000000000000..969b2532f098
--- /dev/null
+++ b/posthog/hogql/transforms/trino/normalize.py
@@ -0,0 +1,298 @@
+from posthog.hogql import ast
+from posthog.hogql.context import HogQLContext
+from posthog.hogql.database.models import TableNode
+from posthog.hogql.database.schema.numbers import NumbersTable
+from posthog.hogql.database.trino_unnest_table import TrinoUnnestTable
+from posthog.hogql.transforms.trino.any_join import lower_trino_any_joins
+from posthog.hogql.transforms.trino.errors import TrinoLoweringError
+from posthog.hogql.transforms.trino.query_wrappers import lower_trino_query_wrappers
+from posthog.hogql.visitor import CloningVisitor, TraversingVisitor
+
+_MAX_NUMBERS_ROWS = 10_000_000
+_EVENT_PROPERTY_BACKED_FIELDS = frozenset(
+ {"$session_id", "$window_id", "$group_0", "$group_1", "$group_2", "$group_3", "$group_4"}
+)
+_EVENT_ELEMENTS_CHAIN_PATTERNS = {
+ "elements_chain_texts": r'(?::|")text="(.*?)"',
+ "elements_chain_ids": r'(?::|")attr_id="(.*?)"',
+ "elements_chain_elements": r"(?:^|;)(a|button|form|input|select|textarea|label)(?:\.|$|:)",
+}
+_ALL_JOIN_TYPES = {
+ "ALL INNER JOIN": "INNER JOIN",
+ "LEFT ALL JOIN": "LEFT JOIN",
+ "RIGHT ALL JOIN": "RIGHT JOIN",
+ "FULL ALL JOIN": "FULL JOIN",
+}
+
+
+def _wrap_unnest_elements(array_expr: ast.Expr, lambda_name: str) -> ast.Call:
+ return ast.Call(
+ name="arrayMap",
+ args=[
+ ast.Lambda(
+ args=[lambda_name],
+ expr=ast.Tuple(exprs=[ast.Field(chain=[lambda_name])]),
+ ),
+ array_expr,
+ ],
+ )
+
+
+class TrinoPhysicalFieldLowerer(CloningVisitor):
+ def __init__(self) -> None:
+ super().__init__(clear_types=False)
+
+ def visit_field(self, node: ast.Field) -> ast.Expr:
+ field_type = node.type
+ while isinstance(field_type, ast.FieldAliasType):
+ field_type = field_type.type
+ table_type = field_type.table_type if isinstance(field_type, ast.FieldType) else None
+ while isinstance(table_type, (ast.TableAliasType, ast.ColumnAliasedTableType)):
+ table_type = table_type.table_type
+ is_events_field = (
+ isinstance(table_type, ast.TableType)
+ and (table_type.table.name or table_type.table.to_printed_hogql()) == "events"
+ )
+ if (
+ isinstance(field_type, ast.FieldType)
+ and field_type.name in _EVENT_PROPERTY_BACKED_FIELDS
+ and is_events_field
+ ):
+ return ast.PropertyAccess(
+ start=node.start,
+ end=node.end,
+ expr=ast.Field(chain=[*node.chain[:-1], "properties"]),
+ keys=[field_type.name],
+ type=ast.StringType(nullable=True),
+ )
+ if isinstance(field_type, ast.FieldType) and is_events_field:
+ source = ast.Field(chain=[*node.chain[:-1], "elements_chain"])
+ if field_type.name == "elements_chain_href":
+ return ast.Call(
+ name="ifNull",
+ args=[
+ ast.Call(name="extract", args=[source, ast.Constant(value=r'(?::|")href="(.*?)"')]),
+ ast.Constant(value=""),
+ ],
+ )
+ pattern = _EVENT_ELEMENTS_CHAIN_PATTERNS.get(field_type.name)
+ if pattern is not None:
+ return ast.Call(
+ name="arrayDistinct",
+ args=[ast.Call(name="extractAll", args=[source, ast.Constant(value=pattern)])],
+ )
+ return super().visit_field(node)
+
+
+class TrinoSemanticCallLowerer(CloningVisitor):
+ def __init__(self) -> None:
+ super().__init__(clear_types=False)
+
+ def visit_call(self, node: ast.Call) -> ast.Expr:
+ lowered = super().visit_call(node)
+ if lowered.name.lower() != "not":
+ return lowered
+ if len(lowered.args) != 1:
+ raise TrinoLoweringError("TRINO_NOT_ARGUMENT_COUNT", "not with other than one argument", node)
+ return ast.Not(
+ start=lowered.start,
+ end=lowered.end,
+ expr=lowered.args[0],
+ type=lowered.type,
+ )
+
+
+class TrinoSelectAliasLowerer(CloningVisitor):
+ def __init__(self) -> None:
+ super().__init__(clear_types=False)
+ self.aliases: dict[str, ast.Expr] = {}
+ self.alias_positions: dict[str, int] = {}
+ self.expanding: set[str] = set()
+ self.in_group_by = False
+
+ def visit_select_query(self, node: ast.SelectQuery) -> ast.SelectQuery:
+ outer_aliases = self.aliases
+ outer_alias_positions = self.alias_positions
+ self.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:
+ outer_in_group_by = self.in_group_by
+ self.in_group_by = True
+ try:
+ lowered.group_by = [self.visit(expr) for expr in node.group_by]
+ finally:
+ self.in_group_by = outer_in_group_by
+ self.aliases = outer_aliases
+ self.alias_positions = outer_alias_positions
+ return lowered
+
+ def visit_field(self, node: ast.Field) -> ast.Expr:
+ if (
+ len(node.chain) == 1
+ and isinstance(node.type, ast.FieldAliasType)
+ and isinstance(node.chain[0], str)
+ and node.chain[0] in self.aliases
+ and node.chain[0] not in self.expanding
+ ):
+ alias = node.chain[0]
+ if self.in_group_by:
+ return ast.PositionalRef(index=self.alias_positions[alias])
+ self.expanding.add(alias)
+ try:
+ return self.visit(self.aliases[alias])
+ finally:
+ self.expanding.remove(alias)
+ return super().visit_field(node)
+
+
+class TrinoArrayJoinFunctionLowerer(CloningVisitor):
+ def __init__(self, context: HogQLContext) -> None:
+ super().__init__(clear_types=False)
+ self.context = context
+ self.pending_unnests: list[tuple[str, str, ast.Expr]] = []
+ self.unnest_index = 0
+
+ def visit_select_query(self, node: ast.SelectQuery) -> ast.SelectQuery:
+ outer_pending = self.pending_unnests
+ self.pending_unnests = []
+ lowered = super().visit_select_query(node)
+ pending = self.pending_unnests
+ self.pending_unnests = outer_pending
+ for table_name, output_name, array_expr in pending:
+ join = ast.JoinExpr(
+ join_type="CROSS JOIN" if lowered.select_from is not None else None,
+ table=ast.Field(chain=[table_name]),
+ table_args=[_wrap_unnest_elements(array_expr, f"{table_name}_value")],
+ alias=table_name,
+ column_aliases=[output_name],
+ )
+ if lowered.select_from is None:
+ lowered.select_from = join
+ else:
+ final_join = lowered.select_from
+ while final_join.next_join is not None:
+ final_join = final_join.next_join
+ final_join.next_join = join
+ return lowered
+
+ def visit_call(self, node: ast.Call) -> ast.Expr:
+ if node.name.lower() != "arrayjoin":
+ return super().visit_call(node)
+ if len(node.args) != 1:
+ raise TrinoLoweringError("TRINO_ARRAY_JOIN_ARGUMENT_COUNT", "arrayJoin with other than one argument", node)
+ if self.context.database is None:
+ raise TrinoLoweringError(
+ "TRINO_ARRAY_JOIN_DATABASE_REQUIRED", "arrayJoin without a resolved database", node
+ )
+ table_name = f"__trino_array_function_{self.unnest_index}"
+ output_name = f"value_{self.unnest_index}"
+ self.unnest_index += 1
+ self.context.database.tables.add_child(
+ TableNode(name=table_name, table=TrinoUnnestTable(name=table_name)),
+ table_conflict_mode="override",
+ )
+ self.pending_unnests.append((table_name, output_name, self.visit(node.args[0])))
+ return ast.Field(chain=[output_name], start=node.start, end=node.end)
+
+
+class TrinoNormalizer(TraversingVisitor):
+ def __init__(self, context: HogQLContext) -> None:
+ self.context = context
+ self.unnest_index = 0
+
+ def visit_select_query(self, node: ast.SelectQuery) -> None:
+ if node.prewhere is not None:
+ node.where = ast.And(exprs=[node.prewhere, node.where]) if node.where is not None else node.prewhere
+ node.prewhere = None
+ node.settings = None
+ self._lower_array_join(node)
+ super().visit_select_query(node)
+
+ 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"}:
+ 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):
+ 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)
+ if self.context.database is None:
+ raise TrinoLoweringError(
+ "TRINO_ARRAY_JOIN_DATABASE_REQUIRED", "ARRAY JOIN without a resolved database", node
+ )
+
+ table_name = f"__trino_unnest_{self.unnest_index}"
+ self.unnest_index += 1
+ self.context.database.tables.add_child(
+ TableNode(name=table_name, table=TrinoUnnestTable(name=table_name)),
+ table_conflict_mode="override",
+ )
+ 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",
+ table=ast.Field(chain=[table_name]),
+ table_args=[_wrap_unnest_elements(array_expr.expr, f"{table_name}_value")],
+ alias=table_name,
+ column_aliases=[array_expr.alias],
+ )
+ node.array_join_op = None
+ node.array_join_list = None
+
+ def visit_join_expr(self, node: ast.JoinExpr) -> None:
+ if node.join_type in _ALL_JOIN_TYPES:
+ node.join_type = _ALL_JOIN_TYPES[node.join_type]
+ table_type = node.type
+ while isinstance(table_type, (ast.TableAliasType, ast.ColumnAliasedTableType)):
+ table_type = table_type.table_type
+ if isinstance(table_type, ast.TableType) and isinstance(table_type.table, NumbersTable):
+ if not (
+ node.table_args is not None
+ and len(node.table_args) == 1
+ and isinstance(node.table_args[0], ast.Call)
+ and node.table_args[0].name.lower() == "range"
+ ):
+ node.table_args = [self._lower_numbers_args(node.table_args)]
+ if node.column_aliases is None:
+ node.column_aliases = ["number"]
+ super().visit_join_expr(node)
+
+ 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):
+ raise TrinoLoweringError(
+ "TRINO_NUMBERS_NON_CONSTANT_ARGUMENT", "numbers requires constant integer arguments", arg
+ )
+ 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=start), ast.Constant(value=start + count)])
+
+
+def normalize_trino_ast(node: ast.AST, context: HogQLContext) -> ast.AST:
+ lowered = TrinoArrayJoinFunctionLowerer(context).visit(node)
+ lowered = TrinoPhysicalFieldLowerer().visit(lowered)
+ lowered = TrinoSemanticCallLowerer().visit(lowered)
+ lowered = lower_trino_any_joins(lowered)
+ lowered = lower_trino_query_wrappers(lowered)
+ lowered = TrinoSelectAliasLowerer().visit(lowered)
+ TrinoNormalizer(context).visit(lowered)
+ return lowered
diff --git a/posthog/hogql/transforms/trino/query_wrappers.py b/posthog/hogql/transforms/trino/query_wrappers.py
new file mode 100644
index 000000000000..5627334f53e9
--- /dev/null
+++ b/posthog/hogql/transforms/trino/query_wrappers.py
@@ -0,0 +1,199 @@
+from posthog.hogql import ast
+from posthog.hogql.transforms.trino.errors import TrinoLoweringError
+from posthog.hogql.visitor import CloningVisitor, TraversingVisitor
+
+
+class _WindowFunctionFinder(TraversingVisitor):
+ found: bool = False
+
+ def visit_window_function(self, node: ast.WindowFunction) -> None:
+ self.found = True
+ super().visit_window_function(node)
+
+
+class TrinoQueryWrapperLowerer(CloningVisitor):
+ def __init__(self) -> None:
+ super().__init__(clear_types=False)
+ self.wrapper_index = 0
+
+ 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.qualify is not None:
+ lowered = self._lower_qualify(lowered)
+ if lowered.limit_by is not None:
+ lowered = self._lower_limit_by(lowered)
+ return lowered
+
+ def _lower_qualify(self, node: ast.SelectQuery) -> ast.SelectQuery:
+ assert node.qualify is not None
+ finder = _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.qualify
+ node.qualify = None
+ return self._wrap(node, predicate)
+
+ def _lower_limit_by(self, node: ast.SelectQuery) -> ast.SelectQuery:
+ assert node.limit_by is not None
+ if 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)
+ helper_name = f"__hogql_limit_by_row_{self.wrapper_index}"
+ row_number = ast.WindowFunction(
+ name="row_number",
+ exprs=[],
+ over_expr=ast.WindowExpr(
+ partition_by=[self._unwrap_hidden_alias(expr) for expr in node.limit_by.exprs],
+ order_by=(
+ [
+ ast.OrderExpr(expr=self._unwrap_hidden_alias(order.expr), order=order.order)
+ for order in node.order_by
+ ]
+ if node.order_by
+ else None
+ ),
+ ),
+ )
+ node.select.append(ast.Alias(alias=helper_name, expr=row_number))
+ node.limit_by = None
+ predicate: ast.Expr = ast.CompareOperation(
+ left=ast.Field(chain=[helper_name]),
+ right=ast.Constant(value=offset + n),
+ op=ast.CompareOperationOp.LtEq,
+ )
+ if offset:
+ predicate = ast.And(
+ exprs=[
+ ast.CompareOperation(
+ left=ast.Field(chain=[helper_name]),
+ right=ast.Constant(value=offset),
+ op=ast.CompareOperationOp.Gt,
+ ),
+ predicate,
+ ]
+ )
+ return self._wrap(node, predicate, helper_name=helper_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
+ output_names = self._output_names(node)
+ visible_select = node.select[:-1] if helper_name is not None else node.select
+ if len(output_names) != len(visible_select):
+ raise TrinoLoweringError(
+ "TRINO_WRAPPER_OUTPUT_NAME_UNSAFE", "wrapper query without stable output names", node
+ )
+ node.select = [
+ expr if isinstance(expr, ast.Alias) and expr.alias == name else ast.Alias(alias=name, expr=expr)
+ for expr, name in zip(visible_select, output_names, strict=True)
+ ] + ([node.select[-1]] if helper_name is not None else [])
+
+ outer_order = self._outer_order_by(node.order_by, output_names, source_alias)
+ outer_limit = node.limit
+ outer_offset = node.offset
+ outer_limit_with_ties = node.limit_with_ties
+ outer_limit_percent = node.limit_percent
+ outer_ctes = node.ctes
+ node.ctes = None
+ node.order_by = None
+ node.limit = None
+ node.offset = None
+ node.limit_with_ties = False
+ node.limit_percent = False
+
+ return ast.SelectQuery(
+ ctes=outer_ctes,
+ 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(
+ predicate,
+ source_alias,
+ {*output_names, *({helper_name} if helper_name else set())},
+ ),
+ order_by=outer_order,
+ limit=outer_limit,
+ offset=outer_offset,
+ limit_with_ties=outer_limit_with_ties,
+ limit_percent=outer_limit_percent,
+ view_name=node.view_name,
+ )
+
+ def _output_names(self, node: ast.SelectQuery) -> list[str]:
+ if not isinstance(node.type, ast.SelectQueryType):
+ raise TrinoLoweringError(
+ "TRINO_WRAPPER_OUTPUT_TYPE_UNRESOLVED", "wrapper query with unresolved output types", node
+ )
+ return list(node.type.columns)
+
+ def _outer_order_by(
+ self,
+ order_by: list[ast.OrderExpr] | None,
+ output_names: list[str],
+ source_alias: str,
+ ) -> list[ast.OrderExpr] | None:
+ if order_by is None:
+ return None
+ output_set = set(output_names)
+ outer: list[ast.OrderExpr] = []
+ for order in order_by:
+ if order.with_fill is not None:
+ raise TrinoLoweringError("TRINO_ORDER_BY_WITH_FILL_UNSUPPORTED", "ORDER BY WITH FILL", order.expr)
+ if isinstance(order.expr, ast.PositionalRef):
+ expr: ast.Expr = ast.PositionalRef(index=order.expr.index)
+ else:
+ unwrapped = self._unwrap_hidden_alias(order.expr)
+ if not isinstance(unwrapped, ast.Field) or not isinstance(unwrapped.chain[-1], str):
+ raise TrinoLoweringError(
+ "TRINO_WRAPPER_ORDER_NOT_PROJECTED",
+ "LIMIT BY or QUALIFY ORDER BY expression not present in SELECT",
+ order.expr,
+ )
+ name = unwrapped.chain[-1]
+ if name not in output_set:
+ raise TrinoLoweringError(
+ "TRINO_WRAPPER_ORDER_NOT_PROJECTED",
+ "LIMIT BY or QUALIFY ORDER BY expression not present in SELECT",
+ order.expr,
+ )
+ expr = ast.Field(chain=[source_alias, name])
+ outer.append(ast.OrderExpr(expr=expr, order=order.order))
+ return outer
+
+ def _unwrap_hidden_alias(self, expr: ast.Expr) -> ast.Expr:
+ while isinstance(expr, ast.Alias) and expr.hidden:
+ expr = expr.expr
+ return expr
+
+ def _qualify_wrapper_fields(self, node: ast.Expr, source_alias: str, output_names: set[str]) -> ast.Expr:
+ class FieldQualifier(CloningVisitor):
+ def visit_field(self, field: ast.Field) -> ast.Field:
+ if not field.chain or not isinstance(field.chain[-1], str) or field.chain[-1] not in output_names:
+ raise TrinoLoweringError(
+ "TRINO_WRAPPER_PREDICATE_NOT_PROJECTED",
+ "wrapper predicate that does not reference a projected output alias",
+ field,
+ )
+ return ast.Field(chain=[source_alias, field.chain[-1]], start=field.start, end=field.end)
+
+ return FieldQualifier(clear_types=False).visit(node)
+
+ 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):
+ raise TrinoLoweringError("TRINO_LIMIT_BY_NON_CONSTANT_LIMIT", f"non-constant {label}", node)
+ if node.value < 0:
+ raise TrinoLoweringError("TRINO_LIMIT_BY_NEGATIVE_LIMIT", f"negative {label}", node)
+ return node.value
+
+
+def lower_trino_query_wrappers(node: ast.AST) -> ast.AST:
+ return TrinoQueryWrapperLowerer().visit(node)
diff --git a/posthog/hogql/transforms/trino/validate.py b/posthog/hogql/transforms/trino/validate.py
new file mode 100644
index 000000000000..9aee7b4b1208
--- /dev/null
+++ b/posthog/hogql/transforms/trino/validate.py
@@ -0,0 +1,235 @@
+from typing import NoReturn
+
+from posthog.hogql import ast
+from posthog.hogql.context import HogQLContext
+from posthog.hogql.database.schema.numbers import NumbersTable
+from posthog.hogql.database.trino_locator import resolve_trino_table_locator
+from posthog.hogql.printer.trino_functions import (
+ TRINO_FUNCTION_HANDLERS_LOWER,
+ TRINO_FUNCTION_RENAMES_LOWER,
+ TRINO_PASSTHROUGH_FUNCTIONS,
+)
+from posthog.hogql.transforms.trino.errors import TrinoLoweringError
+from posthog.hogql.visitor import TraversingVisitor
+
+_SPECIAL_CALLS = frozenset(
+ {
+ "percentile_cont",
+ "percentile_disc",
+ "argmax",
+ "argmaxif",
+ "argmin",
+ "argminif",
+ "arrayconcat",
+ "arraydistinct",
+ "arrayelement",
+ "arrayfilter",
+ "arrayfirst",
+ "arrayflatten",
+ "arraymap",
+ "arraymin",
+ "arraysort",
+ "arraysum",
+ "empty",
+ "extract",
+ "extractall",
+ "grouparrayif",
+ "groupuniqarrayif",
+ "groupuniqarray",
+ "has",
+ "hasall",
+ "hasany",
+ "in",
+ "countdistinct",
+ "date_part",
+ "dateadd",
+ "datesub",
+ "jsonextract",
+ "jsonextractarrayraw",
+ "jsonextractbool",
+ "jsonextractfloat",
+ "jsonextractint",
+ "jsonextractkeys",
+ "jsonextractkeysandvalues",
+ "jsonextractkeysandvaluesraw",
+ "jsonextractraw",
+ "jsonextractstring",
+ "jsonextractuint",
+ "jsonhas",
+ "jsonlength",
+ "match",
+ "md5",
+ "notempty",
+ "notin",
+ "parsedatetime",
+ "quantile",
+ "quantileif",
+ "range",
+ "repeat",
+ "splitbychar",
+ "splitbystring",
+ "todecimal",
+ "todatetime64",
+ "tojsonstring",
+ "tuple",
+ "tupleelement",
+ "tostartofday",
+ "tostartoffifteenminutes",
+ "tostartoffiveminutes",
+ "tostartofhour",
+ "tostartofisoyear",
+ "tostartofminute",
+ "tostartofmonth",
+ "tostartofquarter",
+ "tostartofsecond",
+ "tostartoftenminutes",
+ "tostartofweek",
+ "tostartofyear",
+ "tolastdayofweek",
+ "totimezone",
+ }
+)
+_SEMANTIC_CALLS = frozenset({"cohort", "matchesaction", "savedquery"})
+_SUPPORTED_CALLS = frozenset(
+ {
+ *TRINO_FUNCTION_HANDLERS_LOWER,
+ *TRINO_FUNCTION_RENAMES_LOWER,
+ *TRINO_PASSTHROUGH_FUNCTIONS,
+ *_SPECIAL_CALLS,
+ }
+)
+
+
+class TrinoSourceValidator(TraversingVisitor):
+ def visit_select_query(self, node: ast.SelectQuery) -> None:
+ if node.settings is not None:
+ 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)
+
+
+class TrinoReadyValidator(TraversingVisitor):
+ def __init__(self, context: HogQLContext) -> None:
+ super().__init__()
+ self.context = context
+
+ def _fail(self, feature_code: str, construct: str, node: ast.Expr | None = None) -> NoReturn:
+ raise TrinoLoweringError(feature_code, construct, node)
+
+ def visit_select_query(self, node: ast.SelectQuery) -> None:
+ if node.array_join_op is not None or node.array_join_list:
+ self._fail("TRINO_ARRAY_JOIN_NOT_LOWERED", "ARRAY JOIN", node)
+ if node.limit_by is not None:
+ self._fail("TRINO_LIMIT_BY_NOT_LOWERED", "LIMIT BY", node)
+ if node.qualify is not None:
+ self._fail("TRINO_QUALIFY_NOT_LOWERED", "QUALIFY", node)
+ if node.prewhere is not None:
+ self._fail("TRINO_PREWHERE_NOT_LOWERED", "PREWHERE", node)
+ if node.interpolate is not None:
+ self._fail("TRINO_INTERPOLATE_UNSUPPORTED", "INTERPOLATE", node)
+ if node.limit_percent:
+ self._fail("TRINO_LIMIT_PERCENT_UNSUPPORTED", "LIMIT PERCENT", node)
+ if node.limit_with_ties and (node.limit is None or not node.order_by):
+ self._fail("TRINO_WITH_TIES_ORDER_REQUIRED", "WITH TIES without ORDER BY and LIMIT", node)
+ if node.settings is not None:
+ self._fail("TRINO_SETTINGS_UNSUPPORTED", "SETTINGS", node)
+ super().visit_select_query(node)
+
+ def visit_select_set_query(self, node: ast.SelectSetQuery) -> None:
+ if node.limit_with_ties:
+ self._fail("TRINO_SET_WITH_TIES_UNSUPPORTED", "WITH TIES on a set query", node)
+ super().visit_select_set_query(node)
+
+ def visit_join_expr(self, node: ast.JoinExpr) -> None:
+ join_type = node.join_type or ""
+ if "ANY" in join_type.split():
+ self._fail("TRINO_ANY_JOIN_NOT_LOWERED", join_type, node)
+ if "ASOF" in join_type.split():
+ self._fail("TRINO_ASOF_JOIN_UNSUPPORTED", join_type, node)
+ if join_type.startswith("GLOBAL "):
+ self._fail("TRINO_GLOBAL_JOIN_UNSUPPORTED", join_type, node)
+ if node.table_final:
+ self._fail("TRINO_FINAL_UNSUPPORTED", "FINAL", node)
+ if node.sample is not None and not (
+ node.sample.sample_value.left.value == 1
+ and node.sample.sample_value.right is None
+ and node.sample.offset_value is None
+ ):
+ self._fail("TRINO_SAMPLE_UNSUPPORTED", "SAMPLE", node)
+ super().visit_join_expr(node)
+
+ def visit_order_expr(self, node: ast.OrderExpr) -> None:
+ if node.with_fill is not None:
+ self._fail("TRINO_WITH_FILL_UNSUPPORTED", "WITH FILL", node)
+ super().visit_order_expr(node)
+
+ 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)
+ super().visit_cte(node)
+
+ def visit_pivot_expr(self, node: ast.PivotExpr) -> None:
+ self._fail("TRINO_PIVOT_UNSUPPORTED", "PIVOT", node)
+
+ def visit_unpivot_expr(self, node: ast.UnpivotExpr) -> None:
+ self._fail("TRINO_UNPIVOT_UNSUPPORTED", "UNPIVOT", node)
+
+ def visit_named_argument(self, node: ast.NamedArgument) -> None:
+ self._fail("TRINO_NAMED_ARGUMENT_UNSUPPORTED", "named function argument", node)
+
+ def visit_call(self, node: ast.Call) -> None:
+ name = node.name.lower()
+ if name in _SEMANTIC_CALLS:
+ self._fail("TRINO_SEMANTIC_CALL_NOT_RESOLVED", node.name, node)
+ if name == "arrayjoin":
+ self._fail("TRINO_ARRAY_JOIN_FUNCTION_NOT_LOWERED", node.name, node)
+ if name not in _SUPPORTED_CALLS:
+ self._fail("TRINO_FUNCTION_UNSUPPORTED", node.name, node)
+ super().visit_call(node)
+
+ def visit_lazy_table_type(self, node: ast.LazyTableType) -> None:
+ self._fail("TRINO_LAZY_TABLE_NOT_RESOLVED", node.table.name or node.table.__class__.__name__)
+
+ def visit_lazy_join_type(self, node: ast.LazyJoinType) -> None:
+ self._fail("TRINO_LAZY_JOIN_NOT_RESOLVED", f"lazy join {node.field}")
+
+ def visit_virtual_table_type(self, node: ast.VirtualTableType) -> None:
+ self._fail("TRINO_VIRTUAL_TABLE_NOT_RESOLVED", "virtual relationship")
+
+ def visit_field(self, node: ast.Field) -> None:
+ if (
+ isinstance(node.type, ast.PropertyType)
+ and node.type.joined_subquery is None
+ and node.type.joined_subquery_field_name is None
+ ):
+ self._fail("TRINO_PROPERTY_NOT_LOWERED", "logical property access", node)
+ super().visit_field(node)
+
+ def visit_map_property_type(self, node: ast.PropertyType) -> None:
+ self._fail("TRINO_PROPERTY_NOT_LOWERED", "logical map property access")
+
+ def visit_table_type(self, node: ast.TableType) -> None:
+ if (
+ not isinstance(node.table, NumbersTable)
+ and not hasattr(node.table, "to_printed_trino")
+ and resolve_trino_table_locator(node.table, self.context) is None
+ ):
+ self._fail(
+ "TRINO_TABLE_LOCATOR_MISSING",
+ f"table {node.table.name or node.table.__class__.__name__}",
+ )
+
+
+def validate_trino_ready_ast(node: ast.AST, context: HogQLContext) -> None:
+ TrinoReadyValidator(context).visit(node)
+
+
+def validate_trino_source_ast(node: ast.AST) -> None:
+ TrinoSourceValidator().visit(node)
diff --git a/posthog/hogql/trino_corpus.py b/posthog/hogql/trino_corpus.py
new file mode 100644
index 000000000000..7845da375c25
--- /dev/null
+++ b/posthog/hogql/trino_corpus.py
@@ -0,0 +1,192 @@
+import re
+import json
+import hashlib
+import argparse
+import tempfile
+from collections import Counter
+from collections.abc import Mapping
+from pathlib import Path
+from typing import Literal, TypedDict
+
+CorpusTerminalCategory = Literal[
+ "PASS_PARSE",
+ "PASS_ANALYZE",
+ "PASS_EXECUTE",
+ "FAIL_HOGQL_RESOLUTION",
+ "FAIL_TRINO_LOWERING",
+ "FAIL_TRINO_PRINTING",
+ "FAIL_TRINO_SYNTAX",
+ "FAIL_TABLE_NOT_FOUND",
+ "FAIL_COLUMN_NOT_FOUND",
+ "FAIL_TYPE_MISMATCH",
+ "FAIL_UNSUPPORTED_SAFE_EQUIVALENT",
+ "FAIL_EXECUTION",
+ "FAIL_RESULT_MISMATCH",
+]
+
+
+class CorpusCaseResult(TypedDict):
+ category: CorpusTerminalCategory
+ runtimeMs: float
+ featureCode: str | None
+ generatedSqlSha256: str | None
+ generatedSqlBytes: int | None
+
+
+_SQL_FENCE = re.compile(r"^```sql[^\n]*\n(.*?)^```[ \t]*$", re.IGNORECASE | re.MULTILINE | re.DOTALL)
+_FEATURE_PATTERNS = {
+ "any_join": re.compile(r"\b(?:LEFT\s+)?ANY\s+(?:INNER\s+)?JOIN\b", re.IGNORECASE),
+ "array_join": re.compile(r"\b(?:LEFT\s+|INNER\s+)?ARRAY\s+JOIN\b", re.IGNORECASE),
+ "lambda": re.compile(r"->"),
+ "limit_by": re.compile(r"\bLIMIT\s+.+?\s+BY\b", re.IGNORECASE | re.DOTALL),
+ "numbers": re.compile(r"\bnumbers\s*\(", re.IGNORECASE),
+ "prewhere": re.compile(r"\bPREWHERE\b", re.IGNORECASE),
+ "property_access": re.compile(r"\bproperties\s*(?:\.|\[)", re.IGNORECASE),
+ "qualify": re.compile(r"\bQUALIFY\b", re.IGNORECASE),
+ "window": re.compile(r"\bOVER\s*\(", re.IGNORECASE),
+}
+
+
+def _sha256(value: str) -> str:
+ return hashlib.sha256(value.encode()).hexdigest()
+
+
+def _sanitize_sql(sql: str) -> str:
+ output: list[str] = []
+ index = 0
+ state = "normal"
+ while index < len(sql):
+ char = sql[index]
+ next_char = sql[index + 1] if index + 1 < len(sql) else ""
+ if state == "normal":
+ if char == "'":
+ state = "single"
+ output.append(" ")
+ elif char == "-" and next_char == "-":
+ state = "line_comment"
+ output.extend((" ", " "))
+ index += 1
+ elif char == "/" and next_char == "*":
+ state = "block_comment"
+ output.extend((" ", " "))
+ index += 1
+ else:
+ output.append(char)
+ elif state == "single":
+ if char == "'" and next_char == "'":
+ output.extend((" ", " "))
+ index += 1
+ elif char == "'":
+ state = "normal"
+ output.append(" ")
+ else:
+ output.append("\n" if char == "\n" else " ")
+ elif state == "line_comment":
+ if char == "\n":
+ state = "normal"
+ output.append("\n")
+ else:
+ output.append(" ")
+ elif char == "*" and next_char == "/":
+ state = "normal"
+ output.extend((" ", " "))
+ index += 1
+ else:
+ output.append("\n" if char == "\n" else " ")
+ index += 1
+ return "".join(output)
+
+
+def build_corpus_manifest(markdown: str) -> dict[str, object]:
+ queries: list[dict[str, object]] = []
+ first_id_by_hash: dict[str, str] = {}
+ feature_counts: Counter[str] = Counter()
+ for index, block in enumerate(_SQL_FENCE.findall(markdown), start=1):
+ query_id = f"q{index:04d}"
+ sql = block.rstrip() + "\n"
+ digest = _sha256(sql)
+ sanitized = _sanitize_sql(sql)
+ features = sorted(name for name, pattern in _FEATURE_PATTERNS.items() if pattern.search(sanitized))
+ feature_counts.update(features)
+ record: dict[str, object] = {
+ "bytes": len(sql.encode()),
+ "characters": len(sql),
+ "features": features,
+ "id": query_id,
+ "lines": len(sql.splitlines()),
+ "sha256": digest,
+ }
+ duplicate_of = first_id_by_hash.get(digest)
+ if duplicate_of is None:
+ first_id_by_hash[digest] = query_id
+ else:
+ record["duplicateOf"] = duplicate_of
+ queries.append(record)
+
+ return {
+ "featureCounts": dict(sorted(feature_counts.items())),
+ "queries": queries,
+ "source": {
+ "bytes": len(markdown.encode()),
+ "characters": len(markdown),
+ "sha256": _sha256(markdown),
+ "sqlFenceCount": len(queries),
+ "uniqueQueryCount": len(first_id_by_hash),
+ },
+ }
+
+
+def create_corpus_run_directory(root: Path, source_sha256: str) -> Path:
+ root.mkdir(parents=True, exist_ok=True)
+ return Path(tempfile.mkdtemp(prefix=f"{source_sha256[:12]}-", dir=root))
+
+
+def write_generated_sql(run_directory: Path, query_id: str, sql: str) -> Path:
+ if not re.fullmatch(r"q[0-9]{4}", query_id):
+ raise ValueError(f"Invalid corpus query identifier: {query_id}")
+ output = run_directory / f"{query_id}.sql"
+ output.write_text(sql)
+ return output
+
+
+def build_corpus_report(manifest: Mapping[str, object], results: Mapping[str, CorpusCaseResult]) -> dict[str, object]:
+ manifest_queries = manifest.get("queries")
+ if not isinstance(manifest_queries, list):
+ raise ValueError("Corpus manifest must contain a query list")
+
+ query_ids: list[str] = []
+ reported_queries: list[dict[str, object]] = []
+ category_counts: Counter[str] = Counter()
+ for query in manifest_queries:
+ if not isinstance(query, dict) or not isinstance(query.get("id"), str):
+ raise ValueError("Corpus manifest contains a query without an identifier")
+ query_id = query["id"]
+ query_ids.append(query_id)
+ result = results.get(query_id)
+ if result is None:
+ raise ValueError(f"Corpus query has no terminal result: {query_id}")
+ category_counts[result["category"]] += 1
+ reported_queries.append({**query, **result})
+
+ unknown_ids = sorted(set(results).difference(query_ids))
+ if unknown_ids:
+ raise ValueError(f"Corpus results contain unknown query identifiers: {', '.join(unknown_ids)}")
+
+ return {
+ "categoryCounts": dict(sorted(category_counts.items())),
+ "queries": reported_queries,
+ "source": manifest.get("source"),
+ }
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--source", type=Path, required=True)
+ parser.add_argument("--output", type=Path, required=True)
+ args = parser.parse_args()
+ manifest = build_corpus_manifest(args.source.read_text())
+ args.output.write_text(json.dumps(manifest, indent=2, sort_keys=True) + "\n")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/posthog/hogql/trino_parameters.py b/posthog/hogql/trino_parameters.py
new file mode 100644
index 000000000000..3011ecd85818
--- /dev/null
+++ b/posthog/hogql/trino_parameters.py
@@ -0,0 +1,43 @@
+import re
+
+from posthog.hogql.errors import ExposedHogQLError
+
+_PYFORMAT_PLACEHOLDER_RE = re.compile(r"%\((?P<name>[A-Za-z0-9_]+)\)s")
+
+
+def convert_pyformat_placeholders(sql: str, values: dict[str, object] | None) -> tuple[str, list[object]]:
+ bound_values: list[object] = []
+ converted: list[str] = []
+ index = 0
+ quote: str | None = None
+ while index < len(sql):
+ character = sql[index]
+ if quote is not None:
+ converted.append(character)
+ if character == quote:
+ if index + 1 < len(sql) and sql[index + 1] == quote:
+ converted.append(sql[index + 1])
+ index += 2
+ continue
+ quote = None
+ index += 1
+ continue
+ if character in {"'", '"'}:
+ quote = character
+ converted.append(character)
+ index += 1
+ continue
+ match = _PYFORMAT_PLACEHOLDER_RE.match(sql, index)
+ if match is None:
+ converted.append(character)
+ index += 1
+ continue
+ name = match.group("name")
+ if values is None or name not in values:
+ raise ExposedHogQLError(f"Missing bound value for Trino parameter '{name}'.")
+ bound_values.append(values[name])
+ converted.append("?")
+ index = match.end()
+ if values and not bound_values:
+ raise ExposedHogQLError("Trino query has bound values but no parameter placeholders.")
+ return "".join(converted), bound_values
diff --git a/posthog/hogql/type_system.py b/posthog/hogql/type_system.py
index 76327c099897..5ec09864792d 100644
--- a/posthog/hogql/type_system.py
+++ b/posthog/hogql/type_system.py
@@ -36,7 +36,7 @@ type RuntimeTypeFamily = Literal[
"enum",
"aggregate_state",
]
-type RuntimeTypeDialect = Literal["common", "clickhouse", "postgres", "duckdb", "mysql"]
+type RuntimeTypeDialect = Literal["common", "clickhouse", "postgres", "duckdb", "mysql", "trino"]
class ComparisonCompatibility(StrEnum):
diff --git a/posthog/hogql/visitor.py b/posthog/hogql/visitor.py
index c90da48f44ef..bf6e9dd4abed 100644
--- a/posthog/hogql/visitor.py
+++ b/posthog/hogql/visitor.py
@@ -296,7 +296,7 @@ class TraversingVisitor(Visitor[None]):
def visit_table_type(self, node: ast.TableType):
pass
- def visit_lazy_table_type(self, node: ast.TableType):
+ def visit_lazy_table_type(self, node: ast.LazyTableType):
pass
def visit_field_traverser_type(self, node: ast.LazyJoinType):
diff --git a/posthog/hogql/workload.py b/posthog/hogql/workload.py
index 9d3a95abaeb6..34ba82f61e66 100644
--- a/posthog/hogql/workload.py
+++ b/posthog/hogql/workload.py
@@ -19,10 +19,7 @@ class WorkloadCollector(TraversingVisitor):
self.workloads.add(node.table.workload or self.default_workload)
- def visit_lazy_table_type(self, node: ast.TableType):
- if isinstance(node.table, FunctionCallTable):
- return
-
+ def visit_lazy_table_type(self, node: ast.LazyTableType):
if hasattr(node.table, "workload"):
self.workloads.add(node.table.workload or self.default_workload)