:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(hogql): run HogQL on Trino from Query Editor (#94202)
Bill Guowei Yang9e78c5c6fc90
diff --git a/docs/internal/hogql-trino-compiler.md b/docs/internal/hogql-trino-compiler.mdindex 1df2d1e77018..b92ba3c69cdb 100644--- a/docs/internal/hogql-trino-compiler.md+++ b/docs/internal/hogql-trino-compiler.md@@ -1,12 +1,12 @@# 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.+The Trino backend compiles a resolved HogQL query into SQL and bound values. The compiler itself does not connect to Trino. A separate adapter integration enables HogQL on Query Editor connections.## 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.+Call `prepare_and_print_ast(node, context, "trino")` explicitly for standalone compilation. Query Editor uses the same backend when a selected direct connection advertises the Trino dialect. 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.+The returned SQL uses named placeholders, with values stored in `context.values`. The direct Trino adapter converts them into positional placeholders and submits the ordered values to the Trino client.The final Trino transpiler accepts a prepared AST plus frozen snapshots of bindings, table locators, modifiers, limits, timezone, and week start. It clones the AST and creates a fresh print context without a team, user, or schema database before final lowering, validation, and printing.@@ -14,7 +14,15 @@ The final Trino transpiler accepts a prepared AST plus frozen snapshots of bindiPure transpilation accepts caller-supplied constant values. It rejects unresolved placeholders, action and cohort references, tables absent from the manifest, non-leaf warehouse column types, and invalid or incomplete manifest entries. Callers needing Django-backed semantics must select the explicit expansion mode described below.-Query Editor capability changes, case-insensitive connection lookup, and parameter submission belong to separate integration changes. They are not prerequisites for compilation.+## Query Editor connection integration++The connection integration advertises `TrinoAdapter.dialect = "trino"`. Selecting a Trino connection for a HogQL query calls the same pure transpiler as managed compilation, handing it the connection-scoped database directly. It does not enable Django semantic expansion. Catalog introspection through `system.information_schema` keeps running on the ClickHouse path. Editor validation prints with the same dialect and rejects the same unsupported features, so a query that validates also compiles.++Table and field lookup follow Trino's case-insensitive identifier rules for discovered tables and columns, including table-qualified column references; explicit aliases keep their written case. Printed relations use the connection's catalog, schema, and physical table name. Tables outside the selected connection are absent from the connection-scoped database. Actions, cohorts, saved queries, content-carrying query filters, variables, and Django-only modifiers receive the pure compiler's existing unsupported-feature errors; a content-free filters object and modifiers carried as explicit nulls pass through.++The adapter converts compiler placeholders into positional parameters and never concatenates values into SQL itself. The Trino client submits them through its prepared-statement emulation, which escapes each value into the `EXECUTE` statement text, so values still appear in Trino's query log and UI. Raw SQL requests without bound values still pass through unchanged. Existing source configuration validation, raw read-only checks, timeouts, and row caps remain in place.++The integration does not provision catalogs, alter deployments, or make source-only ClickHouse tables available in Trino.## Managed Trino connectionsdiff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.tsindex 0a2cb3ebdfe2..23312ed40561 100644--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts@@ -2185,36 +2185,58 @@ describe('sqlEditorLogic', () => {expect(String(router.values.hashParams.raw)).toEqual('1')})- it('defaults to raw SQL mode for the managed warehouse connection', async () => {+ it.each([+ {+ label: 'managed warehouse',+ connection: {+ id: 'managed-conn-1',+ prefix: MANAGED_WAREHOUSE_SOURCE_PREFIX,+ engine: 'duckdb',+ source_type: 'Postgres',+ access_method: 'direct',+ supports_hogql: true,+ is_builtin_managed_warehouse: false,+ },+ source: {+ id: 'managed-conn-1',+ source_id: 'src-managed-1',+ prefix: MANAGED_WAREHOUSE_SOURCE_PREFIX,+ source_type: 'Postgres',+ access_method: 'direct',+ engine: 'duckdb',+ } as any,+ query: 'SELECT * FROM managed_warehouse.events',+ },+ {+ label: 'Trino',+ connection: {+ id: 'trino-conn-1',+ prefix: 'trino',+ // The serializer reports no engine for Trino connections in production.+ engine: null,+ source_type: 'Trino',+ access_method: 'direct',+ supports_hogql: true,+ is_builtin_managed_warehouse: false,+ },+ source: {+ id: 'trino-conn-1',+ source_id: 'src-trino-1',+ prefix: 'trino',+ source_type: 'Trino',+ access_method: 'direct',+ engine: 'trino',+ } as any,+ query: 'SELECT * FROM orders',+ },+ ])('defaults to raw SQL mode for $label connections', async ({ connection, source, query }) => {useMocks({get: {- '/api/projects/:team_id/external_data_sources/connections/': [- 200,- [- {- id: 'managed-conn-1',- prefix: MANAGED_WAREHOUSE_SOURCE_PREFIX,- engine: 'duckdb',- source_type: 'Postgres',- access_method: 'direct',- supports_hogql: true,- is_builtin_managed_warehouse: false,- },- ],- ],+ '/api/projects/:team_id/external_data_sources/connections/': [200, [connection]],'/api/environments/:team_id/external_data_sources/': [200,{- results: [- {- id: 'managed-conn-1',- source_id: 'src-managed-1',- prefix: MANAGED_WAREHOUSE_SOURCE_PREFIX,- source_type: 'Postgres',- access_method: 'direct',- engine: 'duckdb',- } as any,- ],+ results: [source],},],},@@ -2226,7 +2248,7 @@ describe('sqlEditorLogic', () => {})logic.mount()- router.actions.push(urls.sqlEditor(), undefined, { q: 'SELECT 1', c: 'managed-conn-1' })+ router.actions.push(urls.sqlEditor(), undefined, { q: 'SELECT 1', c: connection.id })await expectLogic(logic).toDispatchActions(['setSourceQuery', 'createTab', 'updateTab'])await expectLogic(logic).toDispatchActions(['setSendRawQuery'])@@ -2235,12 +2257,10 @@ describe('sqlEditorLogic', () => {expect(logic.values.sourceQuery.source.sendRawQuery).toEqual(true)expect(logic.values.sendRawQueryEnabled).toEqual(true)- // The database sidebar opens a query through this URL without a raw hash param.- // The connection stays the same, so the query-opening path must reapply the default.router.actions.push(urls.sqlEditor({- query: 'SELECT * FROM managed_warehouse.events',- connectionId: 'managed-conn-1',+ query,+ connectionId: connection.id,}))diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsxindex 48f7b4245f66..5bd6cecf56a2 100644--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx@@ -1990,18 +1990,20 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([actions.syncUrlWithQuery()},enforceConnectionRawQueryMode: () => {- // Raw-only connections cannot compile HogQL — force raw SQL mode.- // The managed warehouse (auto-provisioned Duckgres) speaks DuckDB- // natively end-to-end, so raw mode is the better default for it too:- // it skips the HogQL reprint and reaches the engine verbatim.+ // Raw-only connections cannot compile HogQL, so force raw SQL mode.+ // Trino and the managed warehouse default to raw so native SQL reaches the engine unchanged.+ // They still advertise HogQL support, which keeps the mode toggle available.if (values.selectedConnectionId && !values.sourceQuery.source.sendRawQuery) {const option = (values.connectionOptions ?? []).find((option) => option.id === values.selectedConnectionId)const isManagedWarehouseSource =option?.prefix === MANAGED_WAREHOUSE_SOURCE_PREFIX && option?.source_type === 'Postgres'+ // The serializer only sets `engine` for sources that report connection+ // metadata, and Trino does not, so key off the source type instead.+ const defaultsToRawQuery = isManagedWarehouseSource || option?.source_type === 'Trino'- if (!values.selectedConnectionSupportsHogQL || isManagedWarehouseSource) {+ if (!values.selectedConnectionSupportsHogQL || defaultsToRawQuery) {actions.setSendRawQuery(true)}}diff --git a/posthog/hogql/database/database.py b/posthog/hogql/database/database.pyindex e47b3db2d412..412024e2dfa9 100644--- a/posthog/hogql/database/database.py+++ b/posthog/hogql/database/database.py@@ -2068,14 +2068,15 @@ class Database(BaseModel):# For a chain of type a.b.c, we want to create a nested table node# where a is the parent, b is the child of a, and c is the child of b# where a.b.c will contain the table.- # Snowflake stores identifiers uppercase but resolves them- # case-insensitively, so mark its nodes so `from tpch_sf1.nation`- # (any case) resolves to the canonical `TPCH_SF1.NATION`.+ # Direct Snowflake and Trino connections resolve unquoted identifiers+ # case-insensitively. Synced table names are PostHog-generated, so+ # they stay exact-match.warehouse_tables.add_child(TableNode.create_nested_for_chain(table_chain,table_for_key,- case_insensitive=table.external_data_source.is_direct_snowflake,+ case_insensitive=table.external_data_source.is_direct_query+ and table.external_data_source.direct_engine in {"snowflake", "trino"},),table_conflict_mode=table_conflict_mode,)@@ -2123,9 +2124,12 @@ class Database(BaseModel):TableNode.create_nested_for_chain(table_key.split("."),virtual_table,- # Snowflake resolves identifiers case-insensitively; the model's- # is_direct_snowflake prop is False for synced sources, so key off type.- case_insensitive=(virtual_source.source_type == ExternalDataSourceType.SNOWFLAKE),+ # A dual-mode source queried directly follows its engine's+ # case-insensitive identifier rules.+ case_insensitive=(+ virtual_source.source_type+ in {ExternalDataSourceType.SNOWFLAKE, ExternalDataSourceType.TRINO}+ ),),table_conflict_mode="override",)diff --git a/posthog/hogql/database/direct_sql_table.py b/posthog/hogql/database/direct_sql_table.pyindex 94c12ecdf9ae..8216c79e16d8 100644--- a/posthog/hogql/database/direct_sql_table.py+++ b/posthog/hogql/database/direct_sql_table.py@@ -1,3 +1,5 @@+from typing import ClassVar+from posthog.hogql.database.models import FunctionCallTablefrom posthog.hogql.escape_sql import escape_hogql_identifier@@ -10,6 +12,9 @@ class DirectSQLTable(FunctionCallTable):requires_args: bool = Falseexternal_data_source_id: strconnection_metadata: dict[str, object] | None = None+ # True for engines that resolve unquoted identifiers case-insensitively, so the resolver+ # accepts any spelling of a table qualifier while the printer keeps the discovered names.+ case_insensitive_identifiers: ClassVar[bool] = False# True only when these fields are the table's complete physical schema (no column-picker# restriction). Gates the direct `SELECT *` literal-star passthrough: when a restriction is in# effect the fields are a subset, so the star must expand from them rather than let the externaldiff --git a/posthog/hogql/database/direct_trino_table.py b/posthog/hogql/database/direct_trino_table.pyindex 30e44584a082..a82ad2dcd537 100644--- a/posthog/hogql/database/direct_trino_table.py+++ b/posthog/hogql/database/direct_trino_table.py@@ -1,4 +1,7 @@+from typing import ClassVar+from posthog.hogql.database.direct_sql_table import DirectSQLTable+from posthog.hogql.database.models import FieldOrTablefrom posthog.hogql.errors import QueryError@@ -7,8 +10,27 @@ class DirectTrinoTable(DirectSQLTable):trino_schema: strtrino_table_name: str+ case_insensitive_identifiers: ClassVar[bool] = True++ # Trino resolves unquoted identifiers case-insensitively, but the printer quotes canonical+ # names. Resolve the user's field spelling to the discovered column name before printing it.+ def _canonical_field_key(self, name: str | int) -> str | None:+ target = str(name).lower()+ return next((key for key in self.fields if key.lower() == target), None)++ def has_field(self, name: str | int) -> bool:+ return super().has_field(name) or self._canonical_field_key(name) is not None++ def get_field(self, name: str | int) -> FieldOrTable:+ if super().has_field(name):+ return super().get_field(name)+ key = self._canonical_field_key(name)+ if key is not None:+ return self.fields[key]+ return super().get_field(name)+def to_printed_duckdb(self, context) -> str:- raise QueryError("Trino direct connections support raw SQL only")+ raise QueryError("Direct Trino tables cannot be printed into DuckDB SQL")def to_printed_postgres(self, context) -> str:raise QueryError("Direct Trino tables cannot be printed into Postgres SQL")diff --git a/posthog/hogql/direct_sql/test/test_registry_and_capability.py b/posthog/hogql/direct_sql/test/test_registry_and_capability.pyindex cb3532ec5658..e55a89d61249 100644--- a/posthog/hogql/direct_sql/test/test_registry_and_capability.py+++ b/posthog/hogql/direct_sql/test/test_registry_and_capability.py@@ -39,10 +39,10 @@ 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):+ def test_trino_adapter_compiles_hogql(self):adapter = get_adapter("trino")assert adapter is not None- self.assertIsNone(adapter.dialect)+ self.assertEqual(adapter.dialect, "trino")def test_register_adapter_round_trips(self):class FakeAdapter:diff --git a/posthog/hogql/direct_sql/test/test_trino_adapter.py b/posthog/hogql/direct_sql/test/test_trino_adapter.pyindex fb050366e201..371f8be0ccef 100644--- a/posthog/hogql/direct_sql/test/test_trino_adapter.py+++ b/posthog/hogql/direct_sql/test/test_trino_adapter.py@@ -24,10 +24,31 @@ def test_raw_trino_queries_accept_single_select(sql: str) -> None:assert ensure_read_only_raw_trino_statement(sql) == sql-def test_execute_returns_rows_and_types() -> None:+ ("request_sql", "request_values", "expected_execute_args"),+ [+ ("SELECT id, active FROM users", None, ("SELECT id, active FROM users",)),+ (+ "SELECT id, active FROM users -- %(unbound)s",+ None,+ ("SELECT id, active FROM users -- %(unbound)s",),+ ),+ (+ "SELECT id, active FROM users WHERE id = %(id)s AND active = %(active)s",+ {"active": True, "id": 1},+ ("SELECT id, active FROM users WHERE id = ? AND active = ?", [1, True]),+ ),+ ],+)+def test_execute_returns_rows_and_types(+ request_sql: str,+ request_values: dict[str, object] | None,+ expected_execute_args: tuple[object, ...],+) -> None:adapter = TrinoAdapter()request = MagicMock()- request.sql = "SELECT id, active FROM users"+ request.sql = request_sql+ request.values = request_valuesrequest.team.pk = 1request.source.id = "source-id"request.settings.max_execution_time = 30@@ -50,7 +71,7 @@ def test_execute_returns_rows_and_types() -> None:):result = adapter.execute(request)- cursor.execute.assert_called_once_with(request.sql)+ cursor.execute.assert_called_once_with(*expected_execute_args)cursor.fetchmany.assert_called_once_with(1_000_001)assert result.results == [(1, True)]assert result.print_columns == ["id", "active"]diff --git a/posthog/hogql/direct_sql/trino_adapter.py b/posthog/hogql/direct_sql/trino_adapter.pyindex 6d2adb70e457..fe9c8322c4b4 100644--- a/posthog/hogql/direct_sql/trino_adapter.py+++ b/posthog/hogql/direct_sql/trino_adapter.py@@ -13,6 +13,7 @@ from posthog.hogql.direct_sql.adapter import DirectQueryRequest, DirectQueryResufrom posthog.hogql.direct_sql.capability import is_direct_capablefrom posthog.hogql.direct_sql.raw_sql import ensure_single_direct_statementfrom posthog.hogql.errors import ExposedHogQLError+from posthog.hogql.trino_parameters import convert_pyformat_placeholdersif TYPE_CHECKING:from posthog.models.team import Team@@ -72,7 +73,7 @@ class _CancelWatchdog:class TrinoAdapter:engine = "trino"- dialect: HogQLDialect | None = None+ dialect: HogQLDialect | None = "trino"def validate_source_config(self, source: ExternalDataSource, team: Team) -> tuple[TrinoSource, TrinoSourceConfig]:from products.warehouse_sources.backend.facade.source_management import (@@ -113,6 +114,11 @@ class TrinoAdapter:span.set_attribute("team_id", request.team.pk)span.set_attribute("query_type", request.query_type)span.set_attribute("source_id", str(request.source.id))+ sql, values = (+ convert_pyformat_placeholders(request.sql, request.values)+ if request.values is not None+ else (request.sql, [])+ )try:with request.timings.measure("trino_execute"), observe_direct_query("trino"):@@ -120,14 +126,24 @@ class TrinoAdapter:cursor = connection.cursor()with _CancelWatchdog(cursor, timeout_seconds) as watchdog:try:- cursor.execute( # nosemgrep: python.django.security.injection.sql.sql-injection-using-db-cursor-execute.sql-injection-db-cursor-execute -- direct SQL is intentionally user-authored and SELECT-gated- request.sql- )+ if values:+ cursor.execute( # nosemgrep: python.django.security.injection.sql.sql-injection-using-db-cursor-execute.sql-injection-db-cursor-execute -- values are passed as parameters; the trino client escapes them, this code never concatenates them+ sql, values+ )+ else:+ cursor.execute( # nosemgrep: python.django.security.injection.sql.sql-injection-using-db-cursor-execute.sql-injection-db-cursor-execute -- raw SQL is intentionally user-authored and SELECT-gated+ sql+ )results = cursor.fetchmany(DIRECT_TRINO_MAX_ROWS + 1)except Exception as error:if watchdog.fired:raise ExposedHogQLError(DIRECT_TRINO_TIMEOUT_ERROR) from errorraise+ # The parameterized path runs a capability probe and a PREPARE before the+ # main query exists, where cancel() is a no-op. Refuse results that arrive+ # past the deadline so the timeout holds through that window.+ if watchdog.fired:+ raise ExposedHogQLError(DIRECT_TRINO_TIMEOUT_ERROR)description = cursor.description or []except Exception as error:span.set_attribute("error_type", error.__class__.__name__)diff --git a/posthog/hogql/metadata.py b/posthog/hogql/metadata.pyindex aca3c898a496..a9c8a3a0113e 100644--- a/posthog/hogql/metadata.py+++ b/posthog/hogql/metadata.py@@ -45,6 +45,7 @@ from posthog.hogql_queries.query_runner import get_query_runnerfrom posthog.models import Teamfrom posthog.models.user import Userfrom posthog.ph_client import feature_enabled_or_false+from posthog.schema_enums import PersonsOnEventsModelogger = structlog.get_logger(__name__)@@ -135,6 +136,22 @@ def get_hogql_metadata(direct_dialect: HogQLDialect = (direct_adapter.dialect if direct_adapter and direct_adapter.dialect else "postgres")+ if source and direct_dialect == "trino":+ from posthog.hogql.transforms.trino.manifest import ( # noqa: PLC0415 -- load the Trino backend only for Trino connections+ find_unsupported_pure_trino_features,+ )++ # Execution rejects these regardless of Django expansion, so surface the+ # same error at edit time.+ find_unsupported_pure_trino_features(hogql_ast)+ # Direct queries cannot join PostHog person tables, so the team's+ # person-on-events mode has no effect; print with the one mode the Trino+ # dialect accepts. A direct database exposes no event or person properties,+ # so property restrictions cannot apply either.+ context.modifiers = context.modifiers.model_copy(+ update={"personsOnEventsMode": PersonsOnEventsMode.PERSON_ID_OVERRIDE_PROPERTIES_ON_EVENTS}+ )+ context.restricted_properties = set()printed_sql, prepared_ast = prepare_and_print_ast(clone_expr(hogql_ast),context=context,diff --git a/posthog/hogql/query.py b/posthog/hogql/query.pyindex a8a044afce64..1e3647176186 100644--- a/posthog/hogql/query.py+++ b/posthog/hogql/query.py@@ -1,6 +1,6 @@import dataclassesfrom time import sleep-from typing import Any, ClassVar, Literal, Optional, Union, cast+from typing import TYPE_CHECKING, Any, ClassVar, Literal, Optional, Union, castfrom opentelemetry import trace@@ -77,6 +77,9 @@ from posthog.settings import HOGQL_INCREASED_MAX_EXECUTION_TIMEfrom products.access_control.backend.facade.user_access_control import UserAccessControlfrom products.warehouse_sources.backend.facade.types import ManagedWarehouseSQLMode+if TYPE_CHECKING:+ from products.warehouse_sources.backend.facade.models import ExternalDataSource+tracer = trace.get_tracer(__name__)TRANSIENT_S3_ERROR_RETRY_DELAY_SECONDS = 1.0@@ -147,6 +150,8 @@ class HogQLQueryExecutor:self.limit: Optional[int] = Noneself.offset: Optional[int] = Noneself.used_data_warehouse_sources: list[WarehouseSourceUsage] = []+ self._direct_source: Optional[ExternalDataSource] = None+ self._direct_source_resolved = False@tracer.start_as_current_span("HogQLQueryExecutor._parse_query")def _parse_query(self):@@ -235,8 +240,11 @@ class HogQLQueryExecutor:if isinstance(transformed_node, ast.SelectQuery) or isinstance(transformed_node, ast.SelectSetQuery):self.select_query = transformed_node- @tracer.start_as_current_span("HogQLQueryExecutor._generate_hogql")- def _generate_hogql(self):+ @tracer.start_as_current_span("HogQLQueryExecutor._resolve_direct_source")+ def _resolve_direct_source(self) -> Optional["ExternalDataSource"]:+ if self._direct_source_resolved:+ return self._direct_source+source = get_direct_connection_source_none_or_raise(self.team,self.connection_id,@@ -245,6 +253,12 @@ class HogQLQueryExecutor:)self.connection_id = str(source.id) if source else Noneself._direct_source = source+ self._direct_source_resolved = True+ return source++ @tracer.start_as_current_span("HogQLQueryExecutor._generate_hogql")+ def _generate_hogql(self):+ self._resolve_direct_source()database = self.context.databaseif database is None or self.connection_id is not None:@@ -403,7 +417,7 @@ class HogQLQueryExecutor:if self.connection_id != direct_source_id:raise ExposedHogQLError("The query references a different source than the selected connection.")- source = getattr(self, "_direct_source", None)+ source = self._direct_sourceadapter = get_adapter(source.direct_engine) if source is not None else Nonedialect: HogQLDialect = adapter.dialect if adapter is not None and adapter.dialect is not None else "postgres"@@ -444,6 +458,84 @@ class HogQLQueryExecutor:engine="direct_sql",)+ def _references_information_schema(self, context: HogQLContext) -> bool:+ try:+ resolved = Resolver(context=context, dialect="hogql").visit(clone_expr(self.select_query, True))+ query_type = getattr(resolved, "type", None)+ except Exception:+ # The transpiler reports its own resolution errors; only a resolvable+ # introspection query changes the route.+ return False+ if query_type is None:+ return False+ return any(+ isinstance(lazy_table_type.table, InformationSchemaTable)+ for lazy_table_type in extract_lazy_table_types(query_type)+ )++ def _prepare_pure_trino_query(self) -> _PreparedExecution | None:+ source = self._resolve_direct_source()+ if source is None or self.connection_id is None:+ raise InternalHogQLError("Pure Trino compilation requires a selected connection.")++ database = Database.create_for(+ team=self.team,+ user=self.user,+ user_access_control=self.context.user_access_control,+ modifiers=self.query_modifiers,+ timings=self.timings,+ connection_id=self.connection_id,+ bypass_warehouse_access_control=self.context.bypass_warehouse_access_control,+ trigger="executor",+ )++ limit_context = self.limit_context or LimitContext.QUERY+ direct_context = dataclasses.replace(+ self.context,+ is_direct_query=True,+ team_id=self.team.pk,+ team=self.team,+ enable_select_queries=True,+ timings=self.timings,+ modifiers=self.query_modifiers,+ limit_context=limit_context,+ database=database,+ )++ # Catalog introspection describes the connection but reads nothing from it. Route such a+ # query to the ClickHouse path in _prepare_execution, where these tables exist.+ if self._references_information_schema(direct_context):+ return None++ from posthog.hogql.transforms.trino.manifest import ( # noqa: PLC0415 -- load the optional backend only for Trino queries+ transpile_hogql_to_trino_with_database,+ )++ transpiled = transpile_hogql_to_trino_with_database(+ self.select_query,+ database=database,+ filters=self.filters,+ variables=self.variables,+ modifiers=self.modifiers,+ # The team-effective value, so a team-level timezone setting is honored even when the+ # caller sets no modifiers of its own.+ convert_to_project_timezone=self.query_modifiers.convertToProjectTimezone,+ limit_top_select=limit_context not in (LimitContext.COHORT_CALCULATION, LimitContext.SAVED_QUERY),+ limit_context=limit_context,+ default_limit=get_default_limit_for_context(limit_context),+ pretty=self.pretty if self.pretty is not None else True,+ include_hogql=True,+ )++ self.hogql = transpiled.hogql+ self.print_columns = list(transpiled.print_columns)+ self.direct_sql = ensure_single_direct_statement(transpiled.sql)+ self.direct_values = transpiled.values+ self.direct_source_id = str(source.id)+ self.direct_dialect = "trino"+ self.direct_context = dataclasses.replace(direct_context, values=dict(transpiled.values))+ return self._PreparedExecution(sql=self.direct_sql, context=self.direct_context, engine="direct_sql")+def _get_select_query_type(self) -> ast.SelectQueryType | ast.SelectSetQueryType | None:if self.select_query.type is not None:return self.select_query.type@@ -585,6 +677,13 @@ class HogQLQueryExecutor:def _prepare_execution(self) -> _PreparedExecution:self._parse_query()++ source = self._resolve_direct_source()+ if source is not None and source.direct_engine == "trino":+ trino_execution = self._prepare_pure_trino_query()+ if trino_execution is not None:+ return trino_execution+self._process_variables()self._process_placeholders()self._apply_limit()diff --git a/posthog/hogql/resolver_utils.py b/posthog/hogql/resolver_utils.pyindex 4987867e27d8..5b9f0a97a1b8 100644--- a/posthog/hogql/resolver_utils.py+++ b/posthog/hogql/resolver_utils.py@@ -198,9 +198,37 @@ def lookup_table_by_name(if isinstance(cte.type, ast.CTETableType):return cte.type.select_query_type+ # Some external engines resolve unquoted identifiers case-insensitively, so a qualifier may+ # spell such a table differently than the FROM clause did. Accept a unique folded match.+ if len(node.chain) > 1:+ head = str(node.chain[0]).lower()+ folded_matches = [+ table+ for table_alias, table in scope.tables.items()+ if table_alias.lower() == head and _folds_identifier_case(table)+ ]+ if len(folded_matches) == 1:+ return folded_matches[0]+return None+def _folds_identifier_case(table_type: ast.TableOrSelectType) -> bool:+ if isinstance(table_type, ast.TableType):+ return getattr(table_type.table, "case_insensitive_identifiers", False)+ # A table referenced with different casing than discovery registers as an implicit alias.+ # Fold only that re-spelling; an explicit alias keeps the user's exact name.+ if isinstance(table_type, ast.TableAliasType):+ inner = table_type.table_type+ return (+ isinstance(inner, ast.TableType)+ and getattr(inner.table, "case_insensitive_identifiers", False)+ and inner.table.name is not None+ and inner.table.name.lower() == table_type.alias.lower()+ )+ return False++def lookup_cte_by_name(global_scopes: list[ast.SelectQueryType], name: str) -> Optional[ast.CTE]:for scope in global_scopes:if scope and scope.ctes and name in scope.ctes:diff --git a/posthog/hogql/test/test_direct_trino_query.py b/posthog/hogql/test/test_direct_trino_query.pynew file mode 100644index 000000000000..9a7b0e0fcc24--- /dev/null+++ b/posthog/hogql/test/test_direct_trino_query.py@@ -0,0 +1,119 @@+from uuid import uuid4++from posthog.test.base import APIBaseTest+from unittest.mock import MagicMock, patch++from posthog.schema import HogQLQuery++from posthog.hogql.query import HogQLQueryExecutor+from posthog.hogql.transforms.trino.errors import TrinoLoweringError++from posthog.hogql_queries.hogql_query_runner import HogQLQueryRunner++from products.data_warehouse.backend.facade.api import DIRECT_TRINO_URL_PATTERN+from products.data_warehouse.backend.facade.sources import (+ DIRECT_TRINO_CATALOG_OPTION,+ DIRECT_TRINO_SCHEMA_OPTION,+ DIRECT_TRINO_TABLE_OPTION,+)+from products.warehouse_sources.backend.facade.models import DataWarehouseTable, ExternalDataSource+from products.warehouse_sources.backend.facade.types import ExternalDataSourceType+++class TestDirectTrinoQuery(APIBaseTest):+ def _create_source_and_table(self) -> ExternalDataSource:+ source = ExternalDataSource.objects.create(+ team=self.team,+ source_id=str(uuid4()),+ connection_id=str(uuid4()),+ status=ExternalDataSource.Status.COMPLETED,+ source_type=ExternalDataSourceType.TRINO,+ access_method=ExternalDataSource.AccessMethod.DIRECT,+ prefix="analytics",+ job_inputs={+ "host": "trino.example.com",+ "port": 443,+ "catalog": "ducklake",+ "schema": "analytics",+ "auth_type": {"selection": "none", "user": "posthog"},+ "use_ssl": True,+ "verify_ssl": True,+ },+ )+ DataWarehouseTable.objects.create(+ name="orders",+ format=DataWarehouseTable.TableFormat.Parquet,+ team=self.team,+ external_data_source=source,+ url_pattern=DIRECT_TRINO_URL_PATTERN,+ columns={+ "id": {"hogql": "IntegerDatabaseField", "clickhouse": "Int64", "valid": True},+ "status": {"hogql": "StringDatabaseField", "clickhouse": "String", "valid": True},+ },+ options={+ DIRECT_TRINO_CATALOG_OPTION: "ducklake",+ DIRECT_TRINO_SCHEMA_OPTION: "analytics",+ DIRECT_TRINO_TABLE_OPTION: "materialized_orders",+ },+ )+ return source++ def test_query_editor_compiles_to_explicit_trino_relation(self) -> None:+ source = self._create_source_and_table()+ executor = HogQLQueryExecutor(+ query="SELECT ID FROM ORDERS WHERE STATUS = 'paid'",+ team=self.team,+ connection_id=str(source.id),+ )++ sql, context = executor.generate_clickhouse_sql()++ self.assertIn('"ducklake"."analytics"."materialized_orders"', sql)+ self.assertEqual(executor.direct_dialect, "trino")+ self.assertEqual(executor.direct_values, context.values)+ self.assertIn("paid", context.values.values())++ def test_query_editor_uses_pure_compilation(self) -> None:+ source = self._create_source_and_table()+ runner = HogQLQueryRunner(+ team=self.team,+ query=HogQLQuery(+ query="SELECT matchesAction(1) FROM orders",+ connectionId=str(source.id),+ ),+ )++ with self.assertRaises(TrinoLoweringError) as error:+ runner.calculate()++ self.assertEqual(error.exception.feature_code, "TRINO_PURE_ACTION_UNSUPPORTED")++ @patch("posthog.hogql.direct_sql.trino_adapter.TrinoAdapter.validate_source_config")+ @patch("products.warehouse_sources.backend.facade.source_management.connect_trino")+ def test_query_editor_executes_compiled_values_as_driver_parameters(+ self, mock_connect_trino: MagicMock, mock_validate_source_config: MagicMock+ ) -> None:+ source = self._create_source_and_table()+ mock_validate_source_config.return_value = (MagicMock(), MagicMock())+ cursor = MagicMock()+ cursor.fetchmany.return_value = [(7,)]+ cursor.description = [("id", "bigint")]+ connection = MagicMock()+ connection.cursor.return_value = cursor+ mock_connect_trino.return_value.__enter__.return_value = connection+ runner = HogQLQueryRunner(+ team=self.team,+ query=HogQLQuery(+ query="SELECT id FROM orders WHERE status = 'paid' LIMIT 1",+ connectionId=str(source.id),+ ),+ )++ response = runner.calculate()++ submitted_sql, submitted_values = cursor.execute.call_args.args+ self.assertIn('"ducklake"."analytics"."materialized_orders"', submitted_sql)+ self.assertIn("?", submitted_sql)+ self.assertNotIn("paid", submitted_sql)+ self.assertEqual(submitted_values, ["paid"])+ self.assertEqual(response.results, [(7,)])diff --git a/posthog/hogql/transforms/trino/manifest.py b/posthog/hogql/transforms/trino/manifest.pyindex e2c3bb7bc35e..9926756f69c9 100644--- a/posthog/hogql/transforms/trino/manifest.py+++ b/posthog/hogql/transforms/trino/manifest.py@@ -3,7 +3,7 @@ from __future__ import annotationsfrom collections.abc import Mappingfrom typing import Any-from posthog.schema import HogQLQueryModifiers+from posthog.schema import HogQLFilters, HogQLQueryModifiers, HogQLVariablefrom posthog.hogql import astfrom posthog.hogql.constants import LimitContext@@ -30,7 +30,8 @@ from posthog.hogql.database.models import (from posthog.hogql.database.trino_locator import TrinoTableLocatorfrom posthog.hogql.parser import parse_expr, parse_selectfrom posthog.hogql.placeholders import find_placeholders-from posthog.hogql.printer.utils import prepare_and_print_ast+from posthog.hogql.printer.utils import prepare_and_print_ast, print_prepared_ast+from posthog.hogql.resolver_utils import extract_select_queriesfrom posthog.hogql.transforms.trino.errors import TrinoLoweringErrorfrom posthog.hogql.visitor import TraversingVisitor, clone_expr@@ -65,9 +66,11 @@ class TrinoManifestTranspilerResult:sql: strvalues: dict[str, Any]hogql: str | None = None+ print_columns: tuple[str, ...] = ()_CORE_TABLES = frozenset({"events", "persons"})+_SUPPORTED_PURE_MODIFIERS = frozenset({"personsOnEventsMode", "convertToProjectTimezone"})_FIELD_TYPES: dict[DatabaseSerializedFieldType, type[DatabaseField]] = {DatabaseSerializedFieldType.INTEGER: IntegerDatabaseField,DatabaseSerializedFieldType.FLOAT: FloatDatabaseField,@@ -182,6 +185,7 @@ def build_trino_manifest_database(manifest: TrinoCatalogManifest) -> tuple[Datab"core table manifest",detail=f"Core table `{table.logical_name}` uses its fixed schema and cannot declare columns.",)+ database.tables.get_child(chain).case_insensitive = Truecontinuecolumns = {column.name: _manifest_field(column) for column in table.columns}@@ -201,28 +205,124 @@ def build_trino_manifest_database(manifest: TrinoCatalogManifest) -> tuple[Databtrino_table_name=table.locator[2],)database.tables.add_child(- TableNode.create_nested_for_chain(chain, direct_table),+ TableNode.create_nested_for_chain(chain, direct_table, case_insensitive=True),table_conflict_mode="override",)return database, locators+def find_unsupported_pure_trino_features(node: ast.AST) -> None:+ """Raise the pure compiler's error for constructs Trino execution can never compile."""+ _UnsupportedSemanticFeatureFinder().visit(node)+++def _validate_pure_inputs(+ *,+ filters: HogQLFilters | None,+ variables: Mapping[str, HogQLVariable] | None,+ modifiers: HogQLQueryModifiers | None,+) -> None:+ # Dashboards and URL-opened editor tabs send an empty filters object even when no filter is+ # set, so gate on content rather than presence.+ if filters is not None and filters.model_dump(exclude_none=True):+ raise TrinoLoweringError(+ "TRINO_PURE_FILTERS_UNSUPPORTED",+ "query filters",+ detail="Query filters require Django semantic expansion.",+ )+ if variables:+ raise TrinoLoweringError(+ "TRINO_PURE_VARIABLES_UNSUPPORTED",+ "query variables",+ detail="Query variables require Django semantic expansion.",+ )+ if modifiers is None:+ return++ # model_fields_set counts fields a serialize/validate round trip carried as explicit nulls,+ # so gate on values rather than key presence.+ set_modifiers = {key for key in modifiers.model_fields_set if getattr(modifiers, key) is not None}+ unsupported_modifiers = set_modifiers - _SUPPORTED_PURE_MODIFIERS+ if unsupported_modifiers:+ unsupported = ", ".join(sorted(unsupported_modifiers))+ raise TrinoLoweringError(+ "TRINO_PURE_MODIFIER_UNSUPPORTED",+ "query modifier",+ detail=f"Pure Trino transpilation does not support these modifiers: {unsupported}.",+ )+ persons_mode = modifiers.personsOnEventsMode+ if persons_mode is not None and persons_mode != PersonsOnEventsMode.PERSON_ID_OVERRIDE_PROPERTIES_ON_EVENTS:+ raise TrinoLoweringError(+ "TRINO_PERSONS_ON_EVENTS_MODE_UNSUPPORTED",+ f"personsOnEventsMode={persons_mode.value}",+ detail="Trino compilation supports only personsOnEventsMode=person_id_override_properties_on_events.",+ )++def transpile_hogql_to_trino(- query: str,+ query: str | ast.SelectQuery | ast.SelectSetQuery,*,manifest: TrinoCatalogManifest,values: Mapping[str, object] | None = None,+ filters: HogQLFilters | None = None,+ variables: Mapping[str, HogQLVariable] | None = None,+ modifiers: HogQLQueryModifiers | None = None,+ convert_to_project_timezone: bool | None = None,+ limit_top_select: bool = True,+ limit_context: LimitContext | None = None,+ default_limit: int | None = None,+ pretty: bool = False,+ include_hogql: bool = False,+) -> TrinoManifestTranspilerResult:+ database, locators = build_trino_manifest_database(manifest)+ return transpile_hogql_to_trino_with_database(+ query,+ database=database,+ locators=locators,+ values=values,+ filters=filters,+ variables=variables,+ modifiers=modifiers,+ convert_to_project_timezone=convert_to_project_timezone,+ limit_top_select=limit_top_select,+ limit_context=limit_context,+ default_limit=default_limit,+ pretty=pretty,+ include_hogql=include_hogql,+ )+++def transpile_hogql_to_trino_with_database(+ query: str | ast.SelectQuery | ast.SelectSetQuery,+ *,+ database: Database,+ locators: Mapping[str, TrinoTableLocator] | None = None,+ values: Mapping[str, object] | None = None,+ filters: HogQLFilters | None = None,+ variables: Mapping[str, HogQLVariable] | None = None,+ modifiers: HogQLQueryModifiers | None = None,convert_to_project_timezone: bool | None = None,limit_top_select: bool = True,limit_context: LimitContext | None = None,+ default_limit: int | None = None,pretty: bool = False,include_hogql: bool = False,) -> TrinoManifestTranspilerResult:+ """Transpile against an already-built database, such as a connection-scoped one.++ A DirectTrinoTable carries its own physical locator, so ``locators`` is only needed for+ tables that do not, such as the managed core tables.+ """+ _validate_pure_inputs(filters=filters, variables=variables, modifiers=modifiers)placeholders: dict[str, ast.Expr] | None = ({key: ast.Constant(value=value) for key, value in values.items()} if values else None)- node = parse_select(query, placeholders=placeholders)+ node = parse_select(query, placeholders=placeholders) if isinstance(query, str) else clone_expr(query, True)+ if default_limit is not None:+ for select_query in extract_select_queries(node):+ if select_query.limit is None:+ select_query.limit = ast.Constant(value=default_limit)unsupported_placeholders = find_placeholders(node)if (unsupported_placeholders.has_filters@@ -237,7 +337,7 @@ def transpile_hogql_to_trino()_UnsupportedSemanticFeatureFinder().visit(node)- database, locators = build_trino_manifest_database(manifest)+ table_locators = dict(locators) if locators else {}def create_context() -> HogQLContext:return HogQLContext(@@ -250,17 +350,39 @@ def transpile_hogql_to_trino(limit_context=limit_context,modifiers=HogQLQueryModifiers(personsOnEventsMode=PersonsOnEventsMode.PERSON_ID_OVERRIDE_PROPERTIES_ON_EVENTS,- convertToProjectTimezone=convert_to_project_timezone,+ convertToProjectTimezone=(+ modifiers.convertToProjectTimezone+ if modifiers is not None and modifiers.convertToProjectTimezone is not None+ else convert_to_project_timezone+ ),),restricted_properties=set(),- trino_table_locators=locators,- timezone=manifest.timezone,- week_start_day=manifest.week_start_day,+ trino_table_locators=table_locators,+ timezone=database.get_timezone(),+ week_start_day=database.get_week_start_day(),)context = create_context()hogql: str | None = None+ print_columns: list[str] = []if include_hogql:- hogql, _ = prepare_and_print_ast(clone_expr(node), create_context(), dialect="hogql")+ hogql_context = create_context()+ hogql, prepared_hogql = prepare_and_print_ast(clone_expr(node), hogql_context, dialect="hogql")+ if isinstance(prepared_hogql, ast.SelectQuery | ast.SelectSetQuery):+ columns_query = (+ next(extract_select_queries(prepared_hogql))+ if isinstance(prepared_hogql, ast.SelectSetQuery)+ else prepared_hogql+ )+ for select_node in columns_query.select:+ if isinstance(select_node, ast.Alias):+ print_columns.append(select_node.alias)+ else:+ stack = [prepared_hogql] if isinstance(prepared_hogql, ast.SelectQuery) else None+ print_columns.append(+ print_prepared_ast(node=select_node, context=hogql_context, dialect="hogql", stack=stack)+ )sql, _ = prepare_and_print_ast(node, context, dialect="trino", pretty=pretty)- return TrinoManifestTranspilerResult(sql=sql, values=dict(context.values), hogql=hogql)+ return TrinoManifestTranspilerResult(+ sql=sql, values=dict(context.values), hogql=hogql, print_columns=tuple(print_columns)+ )diff --git a/posthog/hogql/transforms/trino/test/test_manifest.py b/posthog/hogql/transforms/trino/test/test_manifest.pyindex 298bde02836e..d91b7e172b74 100644--- a/posthog/hogql/transforms/trino/test/test_manifest.py+++ b/posthog/hogql/transforms/trino/test/test_manifest.py@@ -2,6 +2,8 @@ from typing import Anyimport pytest+from posthog.schema import DateRange, HogQLFilters, HogQLQueryModifiers, HogQLVariable+from posthog.hogql.errors import QueryErrorfrom posthog.hogql.transforms.trino.errors import TrinoLoweringErrorfrom posthog.hogql.transforms.trino.manifest import (@@ -11,7 +13,7 @@ from posthog.hogql.transforms.trino.manifest import (transpile_hogql_to_trino,)-from posthog.schema_enums import DatabaseSerializedFieldType+from posthog.schema_enums import DatabaseSerializedFieldType, PersonsOnEventsModepytestmark = pytest.mark.django_db@@ -71,20 +73,53 @@ def test_transpiles_manifest_table_without_django_queries(django_assert_num_quer@pytest.mark.parametrize(- ("query", "feature_code"),+ ("query", "kwargs", "feature_code"),[- ("SELECT matchesAction(1) FROM events", "TRINO_PURE_ACTION_UNSUPPORTED"),- ("SELECT event FROM events WHERE person_id IN COHORT 1", "TRINO_PURE_COHORT_UNSUPPORTED"),- ("SELECT event FROM events WHERE {filters}", "TRINO_PURE_PLACEHOLDER_UNSUPPORTED"),+ ("SELECT matchesAction(1) FROM events", {}, "TRINO_PURE_ACTION_UNSUPPORTED"),+ ("SELECT event FROM events WHERE person_id IN COHORT 1", {}, "TRINO_PURE_COHORT_UNSUPPORTED"),+ ("SELECT event FROM events WHERE {filters}", {}, "TRINO_PURE_PLACEHOLDER_UNSUPPORTED"),+ (+ "SELECT event FROM events",+ {"filters": HogQLFilters(dateRange=DateRange(date_from="-7d"))},+ "TRINO_PURE_FILTERS_UNSUPPORTED",+ ),+ (+ "SELECT event FROM events",+ {"variables": {"value": HogQLVariable(code_name="value", variableId="1", value="signup")}},+ "TRINO_PURE_VARIABLES_UNSUPPORTED",+ ),+ (+ "SELECT event FROM events",+ {"modifiers": HogQLQueryModifiers(debug=True)},+ "TRINO_PURE_MODIFIER_UNSUPPORTED",+ ),+ (+ "SELECT event FROM events",+ {"modifiers": HogQLQueryModifiers(personsOnEventsMode=PersonsOnEventsMode.DISABLED)},+ "TRINO_PERSONS_ON_EVENTS_MODE_UNSUPPORTED",+ ),],)-def test_rejects_django_backed_semantics(query: str, feature_code: str) -> None:+def test_rejects_django_backed_semantics(query: str, kwargs: dict[str, Any], feature_code: str) -> None:with pytest.raises(TrinoLoweringError) as error:- transpile_hogql_to_trino(query, manifest=_manifest(_events()))+ transpile_hogql_to_trino(query, manifest=_manifest(_events()), **kwargs)assert error.value.feature_code == feature_code+def test_accepts_content_free_filters_and_null_modifiers() -> None:+ # Dashboards send an empty filters object, and a serialize/validate round trip carries every+ # unset modifier as an explicit null. Neither asks for Django semantics.+ result = transpile_hogql_to_trino(+ "SELECT event FROM events",+ manifest=_manifest(_events()),+ filters=HogQLFilters(),+ modifiers=HogQLQueryModifiers.model_validate({"debug": None, "materializationMode": None}),+ )++ assert 'FROM "org_catalog"."posthog"."events_production"' in result.sql++def test_rejects_tables_absent_from_manifest() -> None:with pytest.raises(QueryError, match="Unknown table `saved_query`"):transpile_hogql_to_trino("SELECT * FROM saved_query", manifest=_manifest(_events()))diff --git a/posthog/hogql_queries/hogql_query_runner.py b/posthog/hogql_queries/hogql_query_runner.pyindex 13fde0aa93d2..85ea0d0c7bcf 100644--- a/posthog/hogql_queries/hogql_query_runner.py+++ b/posthog/hogql_queries/hogql_query_runner.py@@ -10,6 +10,7 @@ from posthog.schema import (DateRange,HogQLFilters,HogQLQuery,+ HogQLQueryModifiers,HogQLQueryResponse,QueryStatusResponse,)@@ -56,6 +57,7 @@ class HogQLQueryRunner(AnalyticsQueryRunner[HogQLQueryResponse]):):self.settings = settings or HogQLGlobalSettings()self._direct_connection_validated = False+ self._direct_engine: str | None = Noneself._managed_warehouse_sql_mode: ManagedWarehouseSQLMode | None = Nonesuper().__init__(*args, **kwargs)@@ -69,6 +71,7 @@ class HogQLQueryRunner(AnalyticsQueryRunner[HogQLQueryResponse]):if self._direct_connection_validated and not force:returnmanaged_warehouse_sql_mode: ManagedWarehouseSQLMode | None = None+ direct_engine: str | None = Noneif self.query.connectionId:source = get_direct_connection_source(self.team,@@ -77,11 +80,13 @@ class HogQLQueryRunner(AnalyticsQueryRunner[HogQLQueryResponse]):)if source is None:raise ExposedHogQLError(INVALID_CONNECTION_ID_ERROR)+ direct_engine = source.direct_engineif source.has_managed_warehouse_prefix:managed_warehouse_sql_mode = source.managed_warehouse_sql_modeif managed_warehouse_sql_mode == ManagedWarehouseSQLMode.UNAVAILABLE:raise ExposedHogQLError(INVALID_CONNECTION_ID_ERROR)self._managed_warehouse_sql_mode = managed_warehouse_sql_mode+ self._direct_engine = direct_engineself._direct_connection_validated = Truedef get_cache_payload(self) -> dict:@@ -176,7 +181,7 @@ class HogQLQueryRunner(AnalyticsQueryRunner[HogQLQueryResponse]):except Exception:return set()- def to_query(self) -> ast.SelectQuery | ast.SelectSetQuery:+ def _parse_query(self) -> tuple[ast.SelectQuery | ast.SelectSetQuery, Optional[dict[str, ast.Expr]]]:values: Optional[dict[str, ast.Expr]] = ({key: ast.Constant(value=value) for key, value in self.query.values.items()} if self.query.values else None)@@ -187,6 +192,10 @@ class HogQLQueryRunner(AnalyticsQueryRunner[HogQLQueryResponse]):placeholders=values,cache_origin=CacheOrigin.USER,)+ return parsed_select, values++ def to_query(self) -> ast.SelectQuery | ast.SelectSetQuery:+ parsed_select, values = self._parse_query()finder = find_placeholders(parsed_select)with self.timings.measure("filters"):@@ -247,7 +256,7 @@ class HogQLQueryRunner(AnalyticsQueryRunner[HogQLQueryResponse]):send_raw_query=True,)- query = self.to_query()+ query = self._parse_query()[0] if self._direct_engine == "trino" else self.to_query()if self.is_query_service:validate_user_query(query, team=self.team)@@ -265,14 +274,17 @@ class HogQLQueryRunner(AnalyticsQueryRunner[HogQLQueryResponse]):# With a connection id the executor builds its own connection-scoped database,# so the shared one would be built for nothing.context_kwargs["context"] = self.build_hogql_context()+ # Non-direct queries must print with the same effective modifiers that built the shared database.+ execution_modifiers: Optional[HogQLQueryModifiers] = self.modifiers+ if self._direct_engine == "trino":+ # Pure compilation validates only the modifiers the caller supplied. Team defaults+ # contain Django-only settings and must not make an otherwise pure query fail.+ execution_modifiers = self.query.modifiersresponse = func(query_type="HogQLQuery",query=query,filters=self.query.filters,- # Print with the same modifiers the shared database was built from (self.modifiers).- # The shared database uses self.modifiers, so passing self.query.modifiers here would let- # a caller that sets both build the schema from one modifier set and print SQL for another.- modifiers=self.modifiers,+ modifiers=execution_modifiers,team=self.team,user=self.user,user_access_control=self.user_access_control,diff --git a/products/managed_warehouse/backend/trino_compiler.py b/products/managed_warehouse/backend/trino_compiler.pyindex aa5e5fa6d5fc..3d02dce9de0e 100644--- a/products/managed_warehouse/backend/trino_compiler.py+++ b/products/managed_warehouse/backend/trino_compiler.py@@ -35,11 +35,6 @@ class TrinoTargetUnavailable(RuntimeError):pass-def _reject_pure_compilation(error: Exception, *, feature_code: str) -> None:- TRINO_PURE_REJECTION_TOTAL.labels(feature_code=feature_code).inc()- raise error--def get_ready_trino_catalog_name(organization_id: str) -> str | None:"""Return the control-plane-owned catalog only after its Trino target is ready."""from products.managed_warehouse.backend.presentation.views import _request # noqa: PLC0415@@ -117,66 +112,17 @@ def compile_hogql_to_trino_sql(transpile_hogql_to_trino,)- from posthog.schema_enums import PersonsOnEventsMode # noqa: PLC0415from posthog.week_start_day import WeekStartDay # noqa: PLC0415- if query.filters is not None:- _reject_pure_compilation(- TrinoLoweringError(- "TRINO_PURE_FILTERS_UNSUPPORTED",- "query filters",- detail="Query filters require Django semantic expansion.",- ),- feature_code="TRINO_PURE_FILTERS_UNSUPPORTED",- )- if query.variables:- _reject_pure_compilation(- TrinoLoweringError(- "TRINO_PURE_VARIABLES_UNSUPPORTED",- "query variables",- detail="Query variables require Django semantic expansion.",- ),- feature_code="TRINO_PURE_VARIABLES_UNSUPPORTED",- )-- modifiers = query.modifiers- explicitly_set_modifiers = set(modifiers.model_fields_set) if modifiers is not None else set()- supported_modifiers = {"personsOnEventsMode", "convertToProjectTimezone"}- unsupported_modifiers = explicitly_set_modifiers - supported_modifiers- if unsupported_modifiers:- unsupported = ", ".join(sorted(unsupported_modifiers))- _reject_pure_compilation(- TrinoLoweringError(- "TRINO_PURE_MODIFIER_UNSUPPORTED",- "query modifier",- detail=f"Pure Trino transpilation does not support these modifiers: {unsupported}.",- ),- feature_code="TRINO_PURE_MODIFIER_UNSUPPORTED",- )- persons_mode = modifiers.personsOnEventsMode if modifiers is not None else None- if persons_mode not in (None, PersonsOnEventsMode.PERSON_ID_OVERRIDE_PROPERTIES_ON_EVENTS):- mode_name = persons_mode.value if persons_mode is not None else "unset"- _reject_pure_compilation(- TrinoLoweringError(- "TRINO_PERSONS_ON_EVENTS_MODE_UNSUPPORTED",- f"personsOnEventsMode={mode_name}",- detail=(- "Trino compilation supports only personsOnEventsMode=person_id_override_properties_on_events."- ),- ),- feature_code="TRINO_PERSONS_ON_EVENTS_MODE_UNSUPPORTED",- )-additional_tables = catalog_manifest.tables if catalog_manifest is not None else ()if any(table.logical_name in {"events", "persons"} for table in additional_tables):- _reject_pure_compilation(- TrinoLoweringError(- "TRINO_PURE_CORE_TABLE_OVERRIDE",- "core table manifest",- detail="Managed warehouse compilation owns the events and persons physical mappings.",- ),- feature_code="TRINO_PURE_CORE_TABLE_OVERRIDE",+ error = TrinoLoweringError(+ "TRINO_PURE_CORE_TABLE_OVERRIDE",+ "core table manifest",+ detail="Managed warehouse compilation owns the events and persons physical mappings.",)+ TRINO_PURE_REJECTION_TOTAL.labels(feature_code=error.feature_code).inc()+ raise errorpure_manifest = TrinoCatalogManifest(tables=(TrinoManifestTable(@@ -197,7 +143,9 @@ def compile_hogql_to_trino_sql(query.query,manifest=pure_manifest,values=query.values,- convert_to_project_timezone=(modifiers.convertToProjectTimezone if modifiers is not None else None),+ filters=query.filters,+ variables=query.variables,+ modifiers=query.modifiers,include_hogql=include_hogql,)except TrinoLoweringError as error: