: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
fix(hogql): preserve logical fields during trino resolution (#102530)
Eric Duongddfaf8843fca
diff --git a/docs/internal/hogql-trino-compiler.md b/docs/internal/hogql-trino-compiler.mdindex 8d86a25dc61d..b7ef6ede82dd 100644--- a/docs/internal/hogql-trino-compiler.md+++ b/docs/internal/hogql-trino-compiler.md@@ -39,6 +39,9 @@ Warehouse callers can obtain curated definitions from `resolve_external_table_fiusing the source resource name and the columns actually present in the import.Supplying raw column metadata alone omits these semantic mappings.+Structural lowering retains logical field names until the second type-resolution pass finishes.+Physical names are emitted during final lowering, so a curated schema does not need to expose physical columns as additional logical fields.+When a logical field maps to a different physical column, Trino keeps the source qualifier after rewriting the field.This lets a query join tables that share the physical column name while selecting the intended logical field.`JOIN ... USING` becomes an `ON` condition with both sources qualified, including joins between CTEs and subqueries.diff --git a/posthog/hogql/printer/test/test_trino_printer.py b/posthog/hogql/printer/test/test_trino_printer.pyindex 41319f2ef6c1..c4889a2e2938 100644--- a/posthog/hogql/printer/test/test_trino_printer.py+++ b/posthog/hogql/printer/test/test_trino_printer.py@@ -80,7 +80,8 @@ def _context_with_trino_table() -> HogQLContext:)-def test_star_projection_preserves_logical_name_for_physical_column_alias() -> None:[email protected]("expose_physical_names", [True, False])+def test_star_projection_preserves_logical_name_for_physical_column_alias(expose_physical_names: bool) -> None:database = Database(include_posthog_tables=False)database.tables.add_child(TableNode(@@ -88,10 +89,13 @@ def test_star_projection_preserves_logical_name_for_physical_column_alias() -> Ntable=DirectTrinoTable(name="subscriptions",fields={- "customer": StringDatabaseField(name="customer"),+ **({"customer": StringDatabaseField(name="customer")} if expose_physical_names else {}),"customer_id": StringDatabaseField(name="customer"),- "created": IntegerDatabaseField(name="created"),- "created_at": ExpressionField(name="created_at", expr=parse_expr("toDateTime(created)")),+ "__created": IntegerDatabaseField(name="created", hidden=True),+ **({"created": IntegerDatabaseField(name="created")} if expose_physical_names else {}),+ "created_at": ExpressionField(+ name="created_at", expr=parse_expr("toDateTime(__created)"), isolate_scope=True+ ),},external_data_source_id="source-id",trino_catalog="ducklake",@@ -115,7 +119,7 @@ def test_star_projection_preserves_logical_name_for_physical_column_alias() -> N"trino",)- assert sql.startswith('SELECT "customer_id" FROM (SELECT "subscriptions"."customer", ')+ assert sql.startswith('SELECT "customer_id" FROM (SELECT "subscriptions"."customer"')assert '"subscriptions"."customer" AS "customer_id"' in sqlassert 'AS "created_at" FROM "ducklake"."billing"."subscriptions"' in sql@@ -129,6 +133,16 @@ def test_star_projection_preserves_logical_name_for_physical_column_alias() -> N)assert 'PARTITION BY "subscriptions"."customer" ORDER BY "subscriptions"."customer" ASC' in window_sql+ join_sql, _ = prepare_and_print_ast(+ parse_select(+ "SELECT s.customer_id, other.created_at FROM subscriptions AS s "+ "LEFT ANY JOIN subscriptions AS other ON s.customer_id = other.customer_id"+ ),+ context,+ "trino",+ )+ assert '"__hogql_any_source_0"."customer"' in join_sql+def test_prints_resolved_query_with_explicit_trino_locator_and_bound_value() -> None:context = _context_with_trino_table()diff --git a/posthog/hogql/printer/utils.py b/posthog/hogql/printer/utils.pyindex e839a94ba2a3..90f4b4210cb1 100644--- a/posthog/hogql/printer/utils.py+++ b/posthog/hogql/printer/utils.py@@ -308,7 +308,8 @@ def prepare_ast_for_printing(if dialect == "trino":with context.timings.measure("trino_structural_lowering"):- node = cast(_T_AST, normalize_trino_ast(node, context))+ # The next resolver pass looks up logical schema keys, which may differ from physical column names.+ node = cast(_T_AST, normalize_trino_ast(node, context, physical_names=False))with context.timings.measure("resolve_types_after_trino_structural_lowering"):node = clone_expr(node, clear_types=True)node = resolve_types(diff --git a/posthog/hogql/transforms/trino/any_join.py b/posthog/hogql/transforms/trino/any_join.pyindex 641f52516c20..d822d0b63f61 100644--- a/posthog/hogql/transforms/trino/any_join.py+++ b/posthog/hogql/transforms/trino/any_join.py@@ -10,9 +10,10 @@ _SUPPORTED_ANY_JOIN_TYPES = {class TrinoAnyJoinLowerer(CloningVisitor):- def __init__(self) -> None:+ def __init__(self, *, physical_names: bool = True) -> None:super().__init__(clear_types=False)self.join_index = 0+ self.physical_names = physical_namesdef visit_select_query(self, node: ast.SelectQuery) -> ast.SelectQuery:first = node.select_from@@ -179,8 +180,8 @@ class TrinoAnyJoinLowerer(CloningVisitor):column_names = list(lowered.table.type.columns)elif isinstance(table_type, ast.LazyTableType):column_names = [- field.name- for field in table_type.table.fields.values()+ field.name if self.physical_names else name+ for name, field in table_type.table.fields.items()if isinstance(field, DatabaseField)and not (table_type.table.name == "persons" and field.name == "last_seen_at")]@@ -192,7 +193,9 @@ class TrinoAnyJoinLowerer(CloningVisitor):)else:column_names = [- field.name for field in table_type.table.fields.values() if isinstance(field, DatabaseField)+ field.name if self.physical_names else name+ for name, field in table_type.table.fields.items()+ if isinstance(field, DatabaseField)]if not column_names:raise TrinoLoweringError("TRINO_ANY_JOIN_EMPTY_TABLE_UNSUPPORTED", f"{join_type} without columns", lowered)@@ -347,5 +350,5 @@ class TrinoAnyJoinLowerer(CloningVisitor):return None-def lower_trino_any_joins(node: ast.AST) -> ast.AST:- return TrinoAnyJoinLowerer().visit(node)+def lower_trino_any_joins(node: ast.AST, *, physical_names: bool = True) -> ast.AST:+ return TrinoAnyJoinLowerer(physical_names=physical_names).visit(node)diff --git a/posthog/hogql/transforms/trino/normalize.py b/posthog/hogql/transforms/trino/normalize.pyindex bd1ce1fe3da2..9eb947a7d61d 100644--- a/posthog/hogql/transforms/trino/normalize.py+++ b/posthog/hogql/transforms/trino/normalize.py@@ -128,9 +128,10 @@ class TrinoUnpivotLowerer(CloningVisitor):class TrinoPhysicalFieldLowerer(CloningVisitor):- def __init__(self, context: HogQLContext) -> None:+ def __init__(self, context: HogQLContext, *, physical_names: bool) -> None:super().__init__(clear_types=False)self.context = context+ self.physical_names = physical_namesself.scopes: list[ast.SelectQueryType] = []def visit_select_query(self, node: ast.SelectQuery) -> ast.SelectQuery:@@ -193,7 +194,8 @@ class TrinoPhysicalFieldLowerer(CloningVisitor):database_field = field_type.resolve_database_field(self.context)if isinstance(database_field, DatabaseField) and database_field.name != field_type.name:lowered = super().visit_field(node)- lowered.chain[-1] = database_field.name+ if self.physical_names:+ lowered.chain[-1] = database_field.nameif len(lowered.chain) == 1 and source_type is not None:# The second resolver pass cannot recover the source of a renamed bare field.source_alias = self._source_alias(source_type)@@ -581,16 +583,16 @@ class TrinoNormalizer(TraversingVisitor):)-def normalize_trino_ast(node: ast.AST, context: HogQLContext) -> ast.AST:+def normalize_trino_ast(node: ast.AST, context: HogQLContext, *, physical_names: bool = True) -> ast.AST:budget = TrinoCompilationBudget()budget.visit(node)lowered = TrinoScalarCTELowerer(budget).visit(node)lowered = TrinoUnpivotLowerer(context).visit(lowered)lowered = TrinoArrayJoinFunctionLowerer(context).visit(lowered)- lowered = TrinoPhysicalFieldLowerer(context).visit(lowered)+ lowered = TrinoPhysicalFieldLowerer(context, physical_names=physical_names).visit(lowered)lowered = TrinoSemanticCallLowerer().visit(lowered)lowered = TrinoAsOfJoinLowerer().visit(lowered)- lowered = lower_trino_any_joins(lowered)+ lowered = lower_trino_any_joins(lowered, physical_names=physical_names)lowered = lower_trino_query_wrappers(lowered)lowered = TrinoSelectAliasLowerer(budget).visit(lowered)lowered = TrinoPhysicalProjectionAliasLowerer(context).visit(lowered)