: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): correct trino cte and array membership syntax (#97023)
Bill Guowei Yang65ed7f98e785
diff --git a/docs/internal/hogql-trino-compiler.md b/docs/internal/hogql-trino-compiler.mdindex ab3e960630d9..093d0a9ba199 100644--- a/docs/internal/hogql-trino-compiler.md+++ b/docs/internal/hogql-trino-compiler.md@@ -44,6 +44,10 @@ The Django `DuckgresServer` row remains the transitional owner of the existing rFor 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`.+Leading CTEs stay in scope across all operands of a set operation. Trino prints them before the parenthesized operands, preserving each operand's ordering and limit. A branch with its own CTEs uses a derived table to keep that scope local.++`IN` and `NOT IN` with array literals print SQL value lists, including the `in(...)` and `notIn(...)` function forms. Empty literals reduce the entire predicate to `FALSE` for membership and `TRUE` for non-membership, including for a NULL left operand, tuple operands, and predicates inside lambdas. Nonempty lists retain SQL NULL comparison behavior. Array expressions outside membership predicates still use Trino's `ARRAY[...]` constructor. These rewrites run in the shared printer for both pure and Django-expanded compilation.+`LIMIT BY` and `QUALIFY` wrappers preserve ordering by projecting unselected sort expressions inside the wrapper and removing those helper columns from the result. The inner query gives projected expressions explicit output aliases, including property accesses, so the outer query can reference them by name. Helper names avoid existing aliases, and matching uses resolved column bindings so joined columns with the same name remain distinct. Expression matching also distinguishes literal types, including `1`, `true`, and `1.0`. `DISTINCT` and `GROUP BY` wrappers still reject unprojected sort expressions. Unprojected aggregate sort expressions are also rejected; callers must select them explicitly. `LIMIT BY` rejects partition or sort expressions containing window functions, including aliases and ordinals resolving to them, because its ranking would otherwise nest window functions.For ordinary `GROUP BY`, an expression that matches a selected expression uses that output's ordinal. This keeps property paths, date conversions, and other bound expressions identical for Trino's grouping checks. An alias for an integer constant uses the selected expression's position; the constant's value does not become an ordinal. Explicit source ordinals remain unchanged. Alias references inside larger expressions expand to their expressions, not ordinals. Complex grouping modes retain their expressions. These rewrites apply to both pure and Django-expanded compilation.diff --git a/posthog/hogql/printer/test/__snapshots__/test_trino_printer.ambr b/posthog/hogql/printer/test/__snapshots__/test_trino_printer.ambrindex 580d5d3377a7..4e5cbab871ec 100644--- a/posthog/hogql/printer/test/__snapshots__/test_trino_printer.ambr+++ b/posthog/hogql/printer/test/__snapshots__/test_trino_printer.ambr@@ -121,6 +121,22 @@}),)# ---+# name: test_prepared_trino_transpiler_does_not_rebuild_the_schema_database[SELECT user_id FROM users WHERE user_id IN ['violet', 'amber']]+ tuple(+ 'SELECT "users"."user_id" FROM "ducklake"."analytics"."users" AS "users" WHERE ("users"."user_id" IN (%(hogql_val_0)s, %(hogql_val_1)s))',+ dict({+ 'hogql_val_0': 'violet',+ 'hogql_val_1': 'amber',+ }),+ )+# ---+# name: test_prepared_trino_transpiler_does_not_rebuild_the_schema_database[WITH seed AS (SELECT 7 AS n) SELECT n FROM seed UNION ALL SELECT n FROM seed]+ tuple(+ 'WITH "seed" AS (SELECT 7 AS "n") (SELECT "seed"."n" FROM "seed") UNION ALL (SELECT "seed"."n" FROM "seed")',+ dict({+ }),+ )+# ---# name: test_wrapper_sort_projections_preserve_output[SELECT a.created_at FROM users a JOIN users b ON a.user_id = b.user_id ORDER BY b.created_at DESC LIMIT 2 BY a.user_id]tuple('SELECT "__hogql_trino_source_0"."created_at" FROM (SELECT "a"."created_at" AS "created_at", row_number() OVER (PARTITION BY "a"."user_id" ORDER BY "b"."created_at" DESC) AS "__hogql_limit_by_row_0", "b"."created_at" AS "__hogql_order_0" FROM "ducklake"."analytics"."users" AS "a" JOIN "ducklake"."analytics"."users" AS "b" ON ("a"."user_id" = "b"."user_id")) AS "__hogql_trino_source_0" WHERE ("__hogql_trino_source_0"."__hogql_limit_by_row_0" <= 2) ORDER BY "__hogql_trino_source_0"."__hogql_order_0" DESC',diff --git a/posthog/hogql/printer/test/test_trino_printer.py b/posthog/hogql/printer/test/test_trino_printer.pyindex 4e90437bd6c1..41dc03a2aff7 100644--- a/posthog/hogql/printer/test/test_trino_printer.py+++ b/posthog/hogql/printer/test/test_trino_printer.py@@ -81,6 +81,8 @@ def test_prints_resolved_query_with_explicit_trino_locator_and_bound_value() ->"SELECT user_id FROM users WHERE user_id = 'person-1'","SELECT properties.color, count() FROM users GROUP BY properties.color","SELECT user_id FROM users ORDER BY created_at DESC LIMIT 2 BY user_id",+ "WITH seed AS (SELECT 7 AS n) SELECT n FROM seed UNION ALL SELECT n FROM seed",+ "SELECT user_id FROM users WHERE user_id IN ['violet', 'amber']",],)def test_prepared_trino_transpiler_does_not_rebuild_the_schema_database(@@ -648,6 +650,39 @@ def test_prints_trino_limit_syntax_after_set_operation() -> None:assert sql.endswith("OFFSET 4 ROWS LIMIT 10")[email protected]("pretty", [False, True])[email protected]("nested", [False, True])+def test_set_query_ctes_are_visible_to_every_operand(pretty: bool, nested: bool) -> None:+ query = "WITH seed AS (SELECT 7 AS n) SELECT n FROM seed LIMIT 1 UNION ALL SELECT n FROM seed"+ if nested:+ query = f"SELECT n FROM ({query})"++ sql, _ = prepare_and_print_ast(parse_select(query), _context_with_trino_table(), "trino", pretty=pretty)++ compact = " ".join(sql.split())+ assert 'WITH "seed" AS (SELECT 7 AS "n")' in compact+ assert '(SELECT "seed"."n" FROM "seed" LIMIT 1) UNION ALL (SELECT "seed"."n" FROM "seed")' in compact+ assert compact.count('WITH "seed"') == 1+ if not nested:+ assert compact.startswith("WITH ")++[email protected]("branch_is_set", [False, True])[email protected]("branch_first", [False, True])+def test_set_operand_preserves_branch_local_cte_scope(branch_is_set: bool, branch_first: bool) -> None:+ branch = "WITH seed AS (SELECT 11 AS n) SELECT n FROM seed"+ if branch_is_set:+ branch += " UNION ALL SELECT n FROM seed"+ outer = "WITH seed AS (SELECT 7 AS n) SELECT n FROM seed"+ query = f"({branch}) UNION ALL ({outer})" if branch_first else f"{outer} UNION ALL ({branch})"++ sql, _ = prepare_and_print_ast(parse_select(query), _context_with_trino_table(), "trino")++ assert 'WITH "seed" AS (SELECT 7 AS "n") ' in sql+ assert 'WITH "seed" AS (SELECT 11 AS "n") ' in sql+ assert "(SELECT * FROM (WITH " in sql++def test_rejects_non_literal_trino_limit() -> None:query = parse_select("SELECT user_id FROM users")assert isinstance(query, ast.SelectQuery)@@ -712,6 +747,19 @@ def test_prints_additional_semantics_safe_trino_expressions(expression: str, exp),("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)'),+ ("user_id IN ['violet', 'amber']", '"users"."user_id" IN (%(hogql_val_0)s, %(hogql_val_1)s)'),+ ("user_id NOT IN ['violet']", '"users"."user_id" NOT IN (%(hogql_val_0)s)'),+ ("in(user_id, ['violet'])", '"users"."user_id" IN (%(hogql_val_0)s)'),+ ("notIn(user_id, [])", "SELECT TRUE FROM"),+ ("user_id IN []", "SELECT FALSE FROM"),+ ("(1, 2) IN []", "SELECT FALSE FROM"),+ ("notIn((1, 2), [])", "SELECT TRUE FROM"),+ ("NULL IN []", "SELECT FALSE FROM"),+ ("NULL NOT IN []", "SELECT TRUE FROM"),+ ("arrayMap(x -> x IN [], [1, 2])", 'transform(ARRAY[1, 2], "x" -> FALSE)'),+ ("arrayFilter(x -> x NOT IN [], [1, 2])", 'filter(ARRAY[1, 2], "x" -> TRUE)'),+ ("arrayMap(x -> in(x, []), [1, 2])", 'transform(ARRAY[1, 2], "x" -> FALSE)'),+ ("user_id IN ['violet', NULL]", '"users"."user_id" IN (%(hogql_val_0)s, NULL)'),("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",'),diff --git a/posthog/hogql/printer/trino.py b/posthog/hogql/printer/trino.pyindex ac642d661084..741bf1aae1a9 100644--- a/posthog/hogql/printer/trino.py+++ b/posthog/hogql/printer/trino.py@@ -248,6 +248,34 @@ class TrinoPrinter(PostgresPrinter):separator = f"\n{self.indent(1)}" if self.pretty else " "return sql.rstrip() + separator + separator.join(suffixes)+ def visit_select_set_query(self, node: ast.SelectSetQuery) -> str:+ if not isinstance(node.initial_select_query, ast.SelectQuery) or not node.initial_select_query.ctes:+ return super().visit_select_set_query(node)+ ctes = node.initial_select_query.ctes++ # HogQL stores set-wide CTEs on the first operand. Trino's queryPrimary excludes WITH.+ query = clone_expr(node)+ assert isinstance(query.initial_select_query, ast.SelectQuery)+ query.initial_select_query.ctes = None+ recursive = any(cte.recursive for cte in ctes.values())+ if recursive:+ self._assert_recursive_cte_supported()+ prefix = ("WITH RECURSIVE " if recursive else "WITH ") + ", ".join(self.visit(cte) for cte in ctes.values())+ sql = f"{prefix} {super().visit_select_set_query(query)}"+ return f"({sql})" if len(self.stack) > 1 else sql++ def _visit_set_operand(self, node: ast.SelectQuery | ast.SelectSetQuery) -> str:+ if (+ isinstance(node, ast.SelectSetQuery)+ and isinstance(node.initial_select_query, ast.SelectQuery)+ and node.initial_select_query.ctes+ ):+ return f"(SELECT * FROM {self.visit(node)})"+ sql = super()._visit_set_operand(node)+ if isinstance(node, ast.SelectQuery) and node.ctes:+ return f"(SELECT * FROM {sql})"+ return sql+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 detailraise TrinoLoweringError(feature_code, construct, node, detail=detail)@@ -268,8 +296,9 @@ class TrinoPrinter(PostgresPrinter):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 len(node.args) != 2:+ self._invalid_function_arguments(node, f"{node.name} expects exactly 2 arguments in Trino mode.")+ return self._visit_membership(node.args[0], node.args[1], negated=name == "notin")if name == "mapfromarrays":return self._visit_map_from_arrays(node)if name == "length" and node.args and isinstance(self._resolve_type(node.args[0]), ast.ArrayType):@@ -468,6 +497,8 @@ class TrinoPrinter(PostgresPrinter):return super().visit_order_expr(node)def visit_compare_operation(self, node: ast.CompareOperation) -> str:+ if node.op in (ast.CompareOperationOp.In, ast.CompareOperationOp.NotIn):+ return self._visit_membership(node.left, node.right, negated=node.op == ast.CompareOperationOp.NotIn)left_type = self._resolve_type(node.left)right_type = self._resolve_type(node.right)left_cast: str | None = None@@ -496,6 +527,16 @@ class TrinoPrinter(PostgresPrinter):right = f"CAST({right} AS {right_cast})"return self._get_compare_op(node.op, left, right)+ def _visit_membership(self, left: ast.Expr, right: ast.Expr, *, negated: bool) -> str:+ if isinstance(right, ast.Array) and not right.exprs:+ return "TRUE" if negated else "FALSE"+ return f"({self.visit(left)} {'NOT IN' if negated else 'IN'} {self._visit_in_values(right)})"++ def _visit_in_values(self, node: ast.Expr) -> str:+ if isinstance(node, ast.Array):+ return f"({', '.join(self.visit(value) for value in node.exprs)})"+ return super()._visit_in_values(node)+def visit_arithmetic_operation(self, node: ast.ArithmeticOperation) -> str:left = self.visit(node.left)right = self.visit(node.right)