:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
chore(hogql): extract pure trino transpiler (#93632)
Bill Guowei Yang19c118fc285e
diff --git a/docs/internal/hogql-trino-compiler.md b/docs/internal/hogql-trino-compiler.mdindex 3e63c6088970..61a09c0116bb 100644--- a/docs/internal/hogql-trino-compiler.md+++ b/docs/internal/hogql-trino-compiler.md@@ -8,6 +8,10 @@ Call `prepare_and_print_ast(node, context, "trino")` explicitly to use the backeThe 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.+The existing preparation path still owns schema construction, access checks, saved-query expansion, lazy-table resolution, and resolver passes. It then passes the prepared AST and snapshots of bindings, table locators, modifiers, limits, timezone, and week start in a frozen input to the final Trino transpiler. The final transpiler clones the AST and creates a fresh print context without a team, user, or schema database before final lowering, validation, and printing.++This boundary does not add a restricted manifest-backed entry point. Callers still use the Django-backed preparation path described below.+Query Editor capability changes, case-insensitive connection lookup, and parameter submission belong to separate integration changes. They are not prerequisites for compilation.## Managed Trino connections@@ -24,14 +28,14 @@ For supported string, array, and map arguments, `empty(x)` returns true when theThe 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. |+| 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 resolver-dependent Trino lowering before shared expansion, then invoke the detached final transpiler. | 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.diff --git a/posthog/hogql/context.py b/posthog/hogql/context.pyindex a6d2c58dde4c..d44f652e7951 100644--- a/posthog/hogql/context.py+++ b/posthog/hogql/context.py@@ -8,6 +8,7 @@ from posthog.hogql.property_access_types import RestrictedPropertyfrom posthog.hogql.timings import HogQLTimingsfrom posthog.clickhouse.workload import Workload+from posthog.week_start_day import WeekStartDayif TYPE_CHECKING:from posthog.schema import DataWarehouseSyncWarning, HogQLNotice, HogQLQueryModifiers@@ -69,6 +70,9 @@ class HogQLContext: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)+ # Detached printer stages snapshot these values so they do not retain the schema database.+ timezone: Optional[str] = None+ week_start_day: Optional[WeekStartDay] = None# Set when the query executes against an external direct-SQL connection instead of PostHog's own clusteris_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/printer/base.py b/posthog/hogql/printer/base.pyindex edd4816eb729..f755799fdcdd 100644--- a/posthog/hogql/printer/base.py+++ b/posthog/hogql/printer/base.py@@ -1549,9 +1549,13 @@ class BasePrinter(Visitor[str]):def _get_timezone(self) -> str:if self.context.modifiers.convertToProjectTimezone is False:return "UTC"+ if self.context.timezone is not None:+ return self.context.timezonereturn self.context.database.get_timezone() if self.context.database else "UTC"def _get_week_start_day(self) -> WeekStartDay:+ if self.context.week_start_day is not None:+ return self.context.week_start_dayreturn self.context.database.get_week_start_day() if self.context.database else WeekStartDay.SUNDAYdef _is_type_nullable(self, node_type: ast.Type) -> bool | None:diff --git a/posthog/hogql/printer/test/test_trino_printer.py b/posthog/hogql/printer/test/test_trino_printer.pyindex 51e6060a9692..beca963f3cbe 100644--- a/posthog/hogql/printer/test/test_trino_printer.py+++ b/posthog/hogql/printer/test/test_trino_printer.py@@ -2,6 +2,7 @@ import sqlite3from contextlib import closingimport pytest+from unittest import mockfrom posthog.schema import HogQLQueryModifiers@@ -14,8 +15,9 @@ from posthog.hogql.database.models import DateTimeDatabaseField, StringDatabaseFfrom posthog.hogql.errors import QueryErrorfrom posthog.hogql.escape_sql import escape_trino_identifierfrom posthog.hogql.parser import parse_select-from posthog.hogql.printer import prepare_and_print_ast, print_prepared_ast+from posthog.hogql.printer import prepare_and_print_ast, prepare_ast_for_printing, print_prepared_astfrom posthog.hogql.transforms.trino.errors import TrinoLoweringError+from posthog.hogql.transforms.trino.transpiler import TrinoTranspilerInput, transpile_prepared_hogql_to_trinofrom posthog.hogql.trino_parameters import convert_pyformat_placeholdersfrom posthog.schema_enums import PersonsOnEventsMode@@ -70,6 +72,39 @@ def test_prints_resolved_query_with_explicit_trino_locator_and_bound_value() ->assert context.values == {"hogql_val_0": "person-1"}+def test_prepared_trino_transpiler_does_not_rebuild_the_schema_database() -> None:+ preparation_context = _context_with_trino_table()+ prepared = prepare_ast_for_printing(+ parse_select("SELECT user_id FROM users WHERE user_id = 'person-1'"), preparation_context, "trino"+ )+ assert prepared is not None+ assert preparation_context.database is not None++ transpiler_input = TrinoTranspilerInput(+ node=prepared,+ values=tuple(preparation_context.values.items()),+ table_locators=tuple(preparation_context.trino_table_locators.items()),+ persons_on_events_mode=preparation_context.modifiers.personsOnEventsMode,+ convert_to_project_timezone=preparation_context.modifiers.convertToProjectTimezone,+ limit_top_select=preparation_context.limit_top_select,+ limit_context=preparation_context.limit_context,+ timezone=preparation_context.database.get_timezone(),+ week_start_day=preparation_context.database.get_week_start_day(),+ )++ with mock.patch(+ "posthog.hogql.database.database.Database.create_for",+ side_effect=AssertionError("the prepared transpiler must not build a database"),+ ):+ transpiled = transpile_prepared_hogql_to_trino(transpiler_input)++ assert transpiled.sql == (+ 'SELECT "users"."user_id" FROM "ducklake"."analytics"."users" AS "users" '+ 'WHERE ("users"."user_id" = %(hogql_val_0)s)'+ )+ assert transpiled.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")))diff --git a/posthog/hogql/printer/utils.py b/posthog/hogql/printer/utils.pyindex 07d8adaf1dfc..7fc2cfdfaf67 100644--- a/posthog/hogql/printer/utils.py+++ b/posthog/hogql/printer/utils.py@@ -47,6 +47,7 @@ from posthog.hogql.visitor import clone_exprfrom posthog.hogql.workload import WorkloadCollectorfrom posthog.clickhouse.workload import Workload+from posthog.week_start_day import WeekStartDayPRINTER_CLASSES: dict[HogQLDialect, type[BasePrinter]] = {"clickhouse": ClickHousePrinter,@@ -101,24 +102,65 @@ def prepare_and_print_ast()try:prepared_ast = prepare_ast_for_printing(- node=node, context=context, dialect=dialect, stack=stack, settings=settings+ node=node,+ context=context,+ dialect=dialect,+ stack=stack,+ settings=settings,+ _finalize_trino=dialect != "trino",)if prepared_ast is None:if context.type_observability is not None:context.type_observability.result = "empty"return "", None- collect_hogql_type_coverage(prepared_ast, context.type_observability, context)- collect_hogql_sql_shape(prepared_ast, context.type_observability)+ if dialect == "trino":+ from posthog.hogql.transforms.trino.transpiler import ( # noqa: PLC0415 -- load the optional backend only for Trino compilation+ TrinoTranspilerInput,+ transpile_prepared_hogql_to_trino,+ )++ database = context.database+ with context.timings.measure("trino_transpiler"):+ transpiled = transpile_prepared_hogql_to_trino(+ TrinoTranspilerInput(+ node=prepared_ast,+ values=tuple(context.values.items()),+ table_locators=tuple(context.trino_table_locators.items()),+ persons_on_events_mode=context.modifiers.personsOnEventsMode,+ convert_to_project_timezone=context.modifiers.convertToProjectTimezone,+ limit_top_select=context.limit_top_select,+ limit_context=context.limit_context,+ timezone=database.get_timezone() if database is not None else context.timezone or "UTC",+ week_start_day=(+ database.get_week_start_day()+ if database is not None+ else context.week_start_day or WeekStartDay.SUNDAY+ ),+ within_non_hogql_query=context.within_non_hogql_query,+ stack=tuple(stack or []),+ settings=settings,+ pretty=pretty,+ )+ )+ context.values.clear()+ context.values.update(transpiled.values)+ prepared_ast = cast(_T_AST, transpiled.node)+ printed = transpiled.sql+ collect_hogql_type_coverage(transpiled.prepared_node, context.type_observability, context)+ collect_hogql_sql_shape(transpiled.prepared_node, context.type_observability)+ else:+ collect_hogql_type_coverage(prepared_ast, context.type_observability, context)+ collect_hogql_sql_shape(prepared_ast, context.type_observability)+ printed = print_prepared_ast(+ node=prepared_ast,+ context=context,+ dialect=dialect,+ stack=stack,+ settings=settings,+ pretty=pretty,+ )- printed = print_prepared_ast(- node=prepared_ast,- context=context,- dialect=dialect,- stack=stack,- settings=settings,- pretty=pretty,- )return printed, prepared_astexcept Exception:if context.type_observability is not None:@@ -137,6 +179,8 @@ def prepare_ast_for_printing(stack: list[ast.SelectQuery] | None = None,settings: HogQLGlobalSettings | None = None,resolver_factory: ResolverFactory | None = None,+ *,+ _finalize_trino: bool = True,) -> _T_AST | None:if context.database is None:with context.timings.measure("create_hogql_database"): # Legacy name to keep backwards compatibility@@ -379,7 +423,7 @@ 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":+ if dialect == "trino" and _finalize_trino:from posthog.hogql.transforms.trino.validate import ( # noqa: PLC0415 — breaks validator → printer package cyclevalidate_trino_ready_ast,)diff --git a/posthog/hogql/transforms/trino/transpiler.py b/posthog/hogql/transforms/trino/transpiler.pynew file mode 100644index 000000000000..09349534eab7--- /dev/null+++ b/posthog/hogql/transforms/trino/transpiler.py@@ -0,0 +1,77 @@+from __future__ import annotations++from typing import Any++from posthog.schema import HogQLQueryModifiers++from posthog.hogql import ast+from posthog.hogql.constants import HogQLGlobalSettings, LimitContext+from posthog.hogql.context import HogQLContext+from posthog.hogql.database.trino_locator import TrinoTableLocator+from posthog.hogql.printer.trino import TrinoPrinter+from posthog.hogql.transforms.logical_property_lowering import lower_property_access+from posthog.hogql.transforms.trino.normalize import normalize_trino_ast+from posthog.hogql.transforms.trino.validate import validate_trino_ready_ast+from posthog.hogql.visitor import clone_expr++from posthog.dataclasses import frozen+from posthog.schema_enums import PersonsOnEventsMode+from posthog.week_start_day import WeekStartDay+++@frozen+class TrinoTranspilerInput:+ node: ast.AST+ values: tuple[tuple[str, Any], ...]+ table_locators: tuple[tuple[str, TrinoTableLocator], ...]+ persons_on_events_mode: PersonsOnEventsMode | None+ convert_to_project_timezone: bool | None+ limit_top_select: bool+ limit_context: LimitContext | None+ timezone: str+ week_start_day: WeekStartDay+ within_non_hogql_query: bool = False+ stack: tuple[ast.SelectQuery, ...] = ()+ settings: HogQLGlobalSettings | None = None+ pretty: bool = False+++@frozen+class TrinoTranspilerResult:+ sql: str+ values: dict[str, Any]+ prepared_node: ast.AST+ node: ast.AST+++def transpile_prepared_hogql_to_trino(transpiler_input: TrinoTranspilerInput) -> TrinoTranspilerResult:+ context = HogQLContext(+ database=None,+ team_id=None,+ team=None,+ user=None,+ enable_select_queries=True,+ limit_top_select=transpiler_input.limit_top_select,+ limit_context=transpiler_input.limit_context,+ within_non_hogql_query=transpiler_input.within_non_hogql_query,+ modifiers=HogQLQueryModifiers(+ personsOnEventsMode=transpiler_input.persons_on_events_mode,+ convertToProjectTimezone=transpiler_input.convert_to_project_timezone,+ ),+ restricted_properties=set(),+ trino_table_locators=dict(transpiler_input.table_locators),+ values=dict(transpiler_input.values),+ timezone=transpiler_input.timezone,+ week_start_day=transpiler_input.week_start_day,+ )+ node = normalize_trino_ast(clone_expr(transpiler_input.node), context)+ node = lower_property_access(node, context)+ validate_trino_ready_ast(node, context)+ prepared_node = clone_expr(node)+ sql = TrinoPrinter(+ context=context,+ stack=list(transpiler_input.stack),+ settings=transpiler_input.settings,+ pretty=transpiler_input.pretty,+ ).visit(node)+ return TrinoTranspilerResult(sql=sql, values=dict(context.values), prepared_node=prepared_node, node=node)diff --git a/products/managed_warehouse/backend/tests/test_trino_compiler.py b/products/managed_warehouse/backend/tests/test_trino_compiler.pyindex 3d37ab7dc9d4..a75f197e300d 100644--- a/products/managed_warehouse/backend/tests/test_trino_compiler.py+++ b/products/managed_warehouse/backend/tests/test_trino_compiler.py@@ -7,7 +7,10 @@ from rest_framework.response import Responsefrom posthog.schema import HogQLQuery, HogQLQueryModifiers+from posthog.hogql.database.database import Database+from posthog.models import Organization, Team+from posthog.schema_enums import PersonsOnEventsModefrom products.data_modeling.backend.facade.modeling import DataWarehouseModelPathfrom products.data_modeling.backend.facade.models import DataWarehouseSavedQuery@@ -82,6 +85,50 @@ class TestReadyTrinoCatalogName:class TestCompileHogQLToTrinoSQL:+ def test_preserves_sql_bind_values_and_diagnostics_across_the_transpiler_boundary(self) -> None:+ team = _team()+ membership = _membership(team_id=team.pk, organization_id=str(team.organization_id))+ database = Database(include_posthog_tables=True)+ modifiers = HogQLQueryModifiers(personsOnEventsMode=PersonsOnEventsMode.PERSON_ID_OVERRIDE_PROPERTIES_ON_EVENTS)++ with (+ mock.patch(+ "products.managed_warehouse.backend.trino_compiler.get_ready_trino_catalog_name",+ return_value="org_catalog",+ ),+ mock.patch(+ "products.managed_warehouse.backend.trino_compiler.get_org_team_membership",+ return_value=membership,+ ),+ mock.patch("posthog.hogql.database.database.Database.create_for", return_value=database),+ mock.patch(+ "posthog.hogql.modifiers.create_default_modifiers_for_team",+ return_value=modifiers,+ ),+ mock.patch(+ "products.managed_warehouse.backend.trino_compiler.build_trino_table_locators",+ return_value={"events": ("org_catalog", "posthog", "events_production")},+ ),+ mock.patch(+ "products.access_control.backend.property_access_control.get_restricted_properties_with_group_type_index_for_team",+ return_value=set(),+ ),+ ):+ compiled = compile_hogql_to_trino_sql(+ team.pk,+ HogQLQuery(query="SELECT event FROM events WHERE event = {event}", values={"event": "signup"}),+ team=team,+ include_hogql=True,+ )++ assert compiled.sql == (+ 'SELECT "org_catalog"."posthog"."events_production"."event" '+ 'FROM "org_catalog"."posthog"."events_production" '+ 'WHERE ("org_catalog"."posthog"."events_production"."event" = %(hogql_val_0)s) LIMIT 50000'+ )+ assert compiled.values == {"hogql_val_0": "signup"}+ assert compiled.hogql == "SELECT event FROM events WHERE equals(event, 'signup') LIMIT 50000"+@pytest.mark.parametrize(("include_hogql", "expected_hogql", "expected_print_calls"),[(False, None, 1), (True, "SELECT event FROM events", 2)],