Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(hogql): preserve trino grouping and wrapper expressions (#95427)

Bill Guowei Yang7627476b4216
diff --git a/docs/internal/hogql-trino-compiler.md b/docs/internal/hogql-trino-compiler.md
index 1003b70dc6af..fa7d13e08ebf 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 r
For supported string, array, and map arguments, `empty(x)` returns true when the value is NULL or has zero length. `notEmpty(x)` requires a non-NULL value with nonzero length. String predicates use an empty-string comparison; arrays and maps use `cardinality`.
+`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.
+
## Why some shared integration is necessary
The backend owns its function mappings, structural rewrites, validation, and table rendering. These shared extension points let it reuse the existing compiler without duplicating its semantic pipeline:
diff --git a/posthog/hogql/helpers/test_timestamp_visitor.py b/posthog/hogql/helpers/test_timestamp_visitor.py
index da1188a5d8e6..d7dd614a329a 100644
--- a/posthog/hogql/helpers/test_timestamp_visitor.py
+++ b/posthog/hogql/helpers/test_timestamp_visitor.py
@@ -161,8 +161,14 @@ class TestIsTimeOrIntervalConstant(unittest.TestCase):
def test_constant_with_tombstone_returns_false(self) -> None:
self.assertFalse(is_time_or_interval_constant(ast.Constant(value="tombstone"), tombstone_string="tombstone"))
- def test_field_returns_false(self) -> None:
- self.assertFalse(is_time_or_interval_constant(ast.Field(chain=["timestamp"])))
+ @parameterized.expand(
+ [
+ (ast.Field(chain=["timestamp"]),),
+ (ast.PropertyAccess(expr=ast.Field(chain=["properties"]), keys=["cutoff"]),),
+ ]
+ )
+ def test_field_returns_false(self, node: ast.Expr) -> None:
+ self.assertFalse(is_time_or_interval_constant(node))
def test_select_query_returns_false(self) -> None:
self.assertFalse(is_time_or_interval_constant(ast.SelectQuery(select=[ast.Constant(value=1)])))
diff --git a/posthog/hogql/helpers/timestamp_visitor.py b/posthog/hogql/helpers/timestamp_visitor.py
index 694405a9ac85..6b434950a364 100644
--- a/posthog/hogql/helpers/timestamp_visitor.py
+++ b/posthog/hogql/helpers/timestamp_visitor.py
@@ -248,6 +248,9 @@ class IsTimeOrIntervalConstantVisitor(Visitor[bool]):
def visit_field(self, node: ast.Field) -> bool:
return False
+ def visit_property_access(self, node: ast.PropertyAccess) -> bool:
+ return False
+
def visit_and(self, node: ast.And) -> bool:
return False
diff --git a/posthog/hogql/printer/test/__snapshots__/test_trino_printer.ambr b/posthog/hogql/printer/test/__snapshots__/test_trino_printer.ambr
new file mode 100644
index 000000000000..580d5d3377a7
--- /dev/null
+++ b/posthog/hogql/printer/test/__snapshots__/test_trino_printer.ambr
@@ -0,0 +1,216 @@
+# serializer version: 1
+# name: test_grouping_does_not_replace_different_or_nested_expressions[SELECT 2, count() FROM users GROUP BY 2]
+ tuple(
+ 'SELECT 2, count(*) FROM "ducklake"."analytics"."users" AS "users" GROUP BY 2',
+ dict({
+ }),
+ )
+# ---
+# name: test_grouping_does_not_replace_different_or_nested_expressions[SELECT a.user_id FROM users a JOIN users b ON a.user_id = b.user_id GROUP BY b.user_id]
+ tuple(
+ 'SELECT "a"."user_id" FROM "ducklake"."analytics"."users" AS "a" JOIN "ducklake"."analytics"."users" AS "b" ON ("a"."user_id" = "b"."user_id") GROUP BY "b"."user_id"',
+ dict({
+ }),
+ )
+# ---
+# name: test_grouping_does_not_replace_different_or_nested_expressions[SELECT properties.color, count() FROM users GROUP BY properties.shape]
+ tuple(
+ 'SELECT json_extract_scalar("users"."properties", %(hogql_val_0)s), count(*) FROM "ducklake"."analytics"."users" AS "users" GROUP BY json_extract_scalar("users"."properties", %(hogql_val_1)s)',
+ dict({
+ 'hogql_val_0': '$["color"]',
+ 'hogql_val_1': '$["shape"]',
+ }),
+ )
+# ---
+# name: test_grouping_does_not_replace_different_or_nested_expressions[SELECT user_id = toString(1) AS bucket, count() FROM users GROUP BY user_id = toString(true)]
+ tuple(
+ 'SELECT ("users"."user_id" = CAST(1 AS VARCHAR)) AS "bucket", count(*) FROM "ducklake"."analytics"."users" AS "users" GROUP BY ("users"."user_id" = CAST(true AS VARCHAR))',
+ dict({
+ }),
+ )
+# ---
+# name: test_grouping_does_not_replace_different_or_nested_expressions[SELECT user_id AS id FROM users GROUP BY concat(id, 'suffix')]
+ tuple(
+ 'SELECT "users"."user_id" AS "id" FROM "ducklake"."analytics"."users" AS "users" GROUP BY concat(CAST("users"."user_id" AS VARCHAR), CAST(%(hogql_val_0)s AS VARCHAR))',
+ dict({
+ 'hogql_val_0': 'suffix',
+ }),
+ )
+# ---
+# name: test_grouping_does_not_replace_different_or_nested_expressions[SELECT user_id, count() FROM users GROUP BY ROLLUP(user_id)]
+ tuple(
+ 'SELECT "users"."user_id", count(*) FROM "ducklake"."analytics"."users" AS "users" GROUP BY ROLLUP("users"."user_id")',
+ dict({
+ }),
+ )
+# ---
+# name: test_grouping_reuses_projected_expression[concat(user_id, 'suffix')-None]
+ tuple(
+ 'SELECT concat(CAST("users"."user_id" AS VARCHAR), CAST(%(hogql_val_0)s AS VARCHAR)) AS "dimension", count(*) FROM "ducklake"."analytics"."users" AS "users" GROUP BY 1',
+ dict({
+ 'hogql_val_0': 'suffix',
+ }),
+ )
+# ---
+# name: test_grouping_reuses_projected_expression[integer_alias]
+ tuple(
+ 'SELECT 2 AS "dimension", count(*) FROM "ducklake"."analytics"."users" AS "users" GROUP BY 1',
+ dict({
+ }),
+ )
+# ---
+# name: test_grouping_reuses_projected_expression[notEmpty(properties.color)-None]
+ tuple(
+ 'SELECT (json_extract_scalar("users"."properties", %(hogql_val_0)s) IS NOT NULL AND json_extract_scalar("users"."properties", %(hogql_val_0)s) <> \'\') AS "dimension", count(*) FROM "ducklake"."analytics"."users" AS "users" GROUP BY 1',
+ dict({
+ 'hogql_val_0': '$["color"]',
+ }),
+ )
+# ---
+# name: test_grouping_reuses_projected_expression[properties.color-None]
+ tuple(
+ 'SELECT json_extract_scalar("users"."properties", %(hogql_val_0)s) AS "dimension", count(*) FROM "ducklake"."analytics"."users" AS "users" GROUP BY 1',
+ dict({
+ 'hogql_val_0': '$["color"]',
+ }),
+ )
+# ---
+# name: test_grouping_reuses_projected_expression[toStartOfMonth(toTimeZone(created_at, 'UTC'))-None]
+ tuple(
+ 'SELECT CAST(date_trunc(\'month\', at_timezone(with_timezone(CAST("users"."created_at" AS TIMESTAMP), \'UTC\'), %(hogql_val_0)s)) AS DATE) AS "dimension", count(*) FROM "ducklake"."analytics"."users" AS "users" GROUP BY 1',
+ dict({
+ 'hogql_val_0': 'UTC',
+ }),
+ )
+# ---
+# name: test_grouping_reuses_projected_expression[zero_alias]
+ tuple(
+ 'SELECT 0 AS "dimension", count(*) FROM "ducklake"."analytics"."users" AS "users" GROUP BY 1',
+ dict({
+ }),
+ )
+# ---
+# name: test_lowered_property_timestamp_is_not_constant
+ tuple(
+ 'SELECT CAST(json_extract_scalar("users"."properties", %(hogql_val_0)s) AS TIMESTAMP) FROM "ducklake"."analytics"."users" AS "users"',
+ dict({
+ 'hogql_val_0': '$["cutoff"]',
+ }),
+ )
+# ---
+# name: test_prepared_trino_transpiler_does_not_rebuild_the_schema_database[SELECT properties.color, count() FROM users GROUP BY properties.color]
+ tuple(
+ 'SELECT json_extract_scalar("users"."properties", %(hogql_val_0)s), count(*) FROM "ducklake"."analytics"."users" AS "users" GROUP BY 1',
+ dict({
+ 'hogql_val_0': '$["color"]',
+ }),
+ )
+# ---
+# name: test_prepared_trino_transpiler_does_not_rebuild_the_schema_database[SELECT user_id FROM users ORDER BY created_at DESC LIMIT 2 BY user_id]
+ tuple(
+ 'SELECT "__hogql_trino_source_0"."user_id" FROM (SELECT "users"."user_id" AS "user_id", row_number() OVER (PARTITION BY "users"."user_id" ORDER BY "users"."created_at" DESC) AS "__hogql_limit_by_row_0", "users"."created_at" AS "__hogql_order_0" FROM "ducklake"."analytics"."users" AS "users") 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',
+ dict({
+ }),
+ )
+# ---
+# name: test_prepared_trino_transpiler_does_not_rebuild_the_schema_database[SELECT user_id FROM users WHERE user_id = 'person-1']
+ tuple(
+ 'SELECT "users"."user_id" FROM "ducklake"."analytics"."users" AS "users" WHERE ("users"."user_id" = %(hogql_val_0)s)',
+ dict({
+ 'hogql_val_0': 'person-1',
+ }),
+ )
+# ---
+# 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',
+ dict({
+ }),
+ )
+# ---
+# name: test_wrapper_sort_projections_preserve_output[SELECT properties.color FROM users ORDER BY user_id LIMIT 1 BY user_id]
+ tuple(
+ 'SELECT "__hogql_trino_source_0"."color" FROM (SELECT json_extract_scalar("users"."properties", %(hogql_val_0)s) AS "color", row_number() OVER (PARTITION BY "users"."user_id" ORDER BY "users"."user_id" ASC) AS "__hogql_limit_by_row_0", "users"."user_id" AS "__hogql_order_0" FROM "ducklake"."analytics"."users" AS "users") AS "__hogql_trino_source_0" WHERE ("__hogql_trino_source_0"."__hogql_limit_by_row_0" <= 1) ORDER BY "__hogql_trino_source_0"."__hogql_order_0" ASC',
+ dict({
+ 'hogql_val_0': '$["color"]',
+ }),
+ )
+# ---
+# name: test_wrapper_sort_projections_preserve_output[SELECT properties.color, row_number() OVER (ORDER BY user_id) AS rn FROM users QUALIFY rn = 1 ORDER BY user_id]
+ tuple(
+ 'SELECT "__hogql_trino_source_0"."color", "__hogql_trino_source_0"."rn" FROM (SELECT json_extract_scalar("users"."properties", %(hogql_val_0)s) AS "color", row_number() OVER (ORDER BY "users"."user_id" ASC) AS "rn", "users"."user_id" AS "__hogql_order_0" FROM "ducklake"."analytics"."users" AS "users") AS "__hogql_trino_source_0" WHERE ("__hogql_trino_source_0"."rn" = 1) ORDER BY "__hogql_trino_source_0"."__hogql_order_0" ASC',
+ dict({
+ 'hogql_val_0': '$["color"]',
+ }),
+ )
+# ---
+# name: test_wrapper_sort_projections_preserve_output[SELECT user_id AS __hogql_order_0, created_at AS __hogql_limit_by_row_0 FROM users ORDER BY toStartOfDay(created_at) DESC LIMIT 2 BY user_id]
+ tuple(
+ 'SELECT "__hogql_trino_source_0"."__hogql_order_0", "__hogql_trino_source_0"."__hogql_limit_by_row_0" FROM (SELECT "users"."user_id" AS "__hogql_order_0", "users"."created_at" AS "__hogql_limit_by_row_0", row_number() OVER (PARTITION BY "users"."user_id" ORDER BY date_trunc(\'day\', "users"."created_at") DESC) AS "__hogql_limit_by_row_0_1", date_trunc(\'day\', "users"."created_at") AS "__hogql_order_0_1" FROM "ducklake"."analytics"."users" AS "users") AS "__hogql_trino_source_0" WHERE ("__hogql_trino_source_0"."__hogql_limit_by_row_0_1" <= 2) ORDER BY "__hogql_trino_source_0"."__hogql_order_0_1" DESC',
+ dict({
+ }),
+ )
+# ---
+# name: test_wrapper_sort_projections_preserve_output[SELECT user_id AS id FROM users ORDER BY id DESC LIMIT 2 BY id]
+ tuple(
+ 'SELECT "__hogql_trino_source_0"."id" FROM (SELECT "users"."user_id" AS "id", row_number() OVER (PARTITION BY "users"."user_id" ORDER BY "users"."user_id" DESC) AS "__hogql_limit_by_row_0" FROM "ducklake"."analytics"."users" AS "users") AS "__hogql_trino_source_0" WHERE ("__hogql_trino_source_0"."__hogql_limit_by_row_0" <= 2) ORDER BY "__hogql_trino_source_0"."id" DESC',
+ dict({
+ }),
+ )
+# ---
+# name: test_wrapper_sort_projections_preserve_output[SELECT user_id FROM users ORDER BY created_at DESC LIMIT 2 BY user_id LIMIT 5 OFFSET 1]
+ tuple(
+ 'SELECT "__hogql_trino_source_0"."user_id" FROM (SELECT "users"."user_id" AS "user_id", row_number() OVER (PARTITION BY "users"."user_id" ORDER BY "users"."created_at" DESC) AS "__hogql_limit_by_row_0", "users"."created_at" AS "__hogql_order_0" FROM "ducklake"."analytics"."users" AS "users") 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 OFFSET 1 ROWS LIMIT 5',
+ dict({
+ }),
+ )
+# ---
+# name: test_wrapper_sort_projections_preserve_output[SELECT user_id FROM users ORDER BY toStartOfDay(created_at) DESC LIMIT 2 BY user_id]
+ tuple(
+ 'SELECT "__hogql_trino_source_0"."user_id" FROM (SELECT "users"."user_id" AS "user_id", row_number() OVER (PARTITION BY "users"."user_id" ORDER BY date_trunc(\'day\', "users"."created_at") DESC) AS "__hogql_limit_by_row_0", date_trunc(\'day\', "users"."created_at") AS "__hogql_order_0" FROM "ducklake"."analytics"."users" AS "users") 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',
+ dict({
+ }),
+ )
+# ---
+# name: test_wrapper_sort_projections_preserve_output[SELECT user_id, count() AS total FROM users GROUP BY user_id ORDER BY total DESC LIMIT 2 BY user_id]
+ tuple(
+ 'SELECT "__hogql_trino_source_0"."user_id", "__hogql_trino_source_0"."total" FROM (SELECT "users"."user_id" AS "user_id", count(*) AS "total", row_number() OVER (PARTITION BY "users"."user_id" ORDER BY count(*) DESC) AS "__hogql_limit_by_row_0" FROM "ducklake"."analytics"."users" AS "users" GROUP BY 1) AS "__hogql_trino_source_0" WHERE ("__hogql_trino_source_0"."__hogql_limit_by_row_0" <= 2) ORDER BY "__hogql_trino_source_0"."total" DESC',
+ dict({
+ }),
+ )
+# ---
+# name: test_wrapper_sort_projections_preserve_output[SELECT user_id, created_at FROM users ORDER BY 2 DESC LIMIT 2 BY 1]
+ tuple(
+ 'SELECT "__hogql_trino_source_0"."user_id", "__hogql_trino_source_0"."created_at" FROM (SELECT "users"."user_id" AS "user_id", "users"."created_at" AS "created_at", row_number() OVER (PARTITION BY "users"."user_id" ORDER BY "users"."created_at" DESC) AS "__hogql_limit_by_row_0" FROM "ducklake"."analytics"."users" AS "users") AS "__hogql_trino_source_0" WHERE ("__hogql_trino_source_0"."__hogql_limit_by_row_0" <= 2) ORDER BY 2 DESC',
+ dict({
+ }),
+ )
+# ---
+# name: test_wrapper_sort_projections_preserve_output[SELECT user_id, created_at FROM users ORDER BY 2 DESC LIMIT 2 BY user_id]
+ tuple(
+ 'SELECT "__hogql_trino_source_0"."user_id", "__hogql_trino_source_0"."created_at" FROM (SELECT "users"."user_id" AS "user_id", "users"."created_at" AS "created_at", row_number() OVER (PARTITION BY "users"."user_id" ORDER BY "users"."created_at" DESC) AS "__hogql_limit_by_row_0" FROM "ducklake"."analytics"."users" AS "users") AS "__hogql_trino_source_0" WHERE ("__hogql_trino_source_0"."__hogql_limit_by_row_0" <= 2) ORDER BY 2 DESC',
+ dict({
+ }),
+ )
+# ---
+# name: test_wrapper_sort_projections_preserve_output[SELECT user_id, row_number() OVER (ORDER BY created_at) AS position FROM users QUALIFY position = 1 ORDER BY created_at DESC LIMIT 3]
+ tuple(
+ 'SELECT "__hogql_trino_source_0"."user_id", "__hogql_trino_source_0"."position" FROM (SELECT "users"."user_id" AS "user_id", row_number() OVER (ORDER BY "users"."created_at" ASC) AS "position", "users"."created_at" AS "__hogql_order_0" FROM "ducklake"."analytics"."users" AS "users") AS "__hogql_trino_source_0" WHERE ("__hogql_trino_source_0"."position" = 1) ORDER BY "__hogql_trino_source_0"."__hogql_order_0" DESC LIMIT 3',
+ dict({
+ }),
+ )
+# ---
+# name: test_wrapper_sort_projections_preserve_output[SELECT user_id, user_id = toString(1) AS bucket, row_number() OVER (ORDER BY user_id) AS rn FROM users QUALIFY rn > 0 ORDER BY user_id = toString(1.0) DESC LIMIT 1]
+ tuple(
+ 'SELECT "__hogql_trino_source_0"."user_id", "__hogql_trino_source_0"."bucket", "__hogql_trino_source_0"."rn" FROM (SELECT "users"."user_id" AS "user_id", ("users"."user_id" = CAST(1 AS VARCHAR)) AS "bucket", row_number() OVER (ORDER BY "users"."user_id" ASC) AS "rn", ("users"."user_id" = CAST(1.0 AS VARCHAR)) AS "__hogql_order_0" FROM "ducklake"."analytics"."users" AS "users") AS "__hogql_trino_source_0" WHERE ("__hogql_trino_source_0"."rn" > 0) ORDER BY "__hogql_trino_source_0"."__hogql_order_0" DESC LIMIT 1',
+ dict({
+ }),
+ )
+# ---
+# name: test_wrapper_sort_projections_preserve_output[SELECT user_id, user_id = toString(1) AS bucket, row_number() OVER (ORDER BY user_id) AS rn FROM users QUALIFY rn > 0 ORDER BY user_id = toString(true) DESC LIMIT 1]
+ tuple(
+ 'SELECT "__hogql_trino_source_0"."user_id", "__hogql_trino_source_0"."bucket", "__hogql_trino_source_0"."rn" FROM (SELECT "users"."user_id" AS "user_id", ("users"."user_id" = CAST(1 AS VARCHAR)) AS "bucket", row_number() OVER (ORDER BY "users"."user_id" ASC) AS "rn", ("users"."user_id" = CAST(true AS VARCHAR)) AS "__hogql_order_0" FROM "ducklake"."analytics"."users" AS "users") AS "__hogql_trino_source_0" WHERE ("__hogql_trino_source_0"."rn" > 0) ORDER BY "__hogql_trino_source_0"."__hogql_order_0" DESC LIMIT 1',
+ dict({
+ }),
+ )
+# ---
diff --git a/posthog/hogql/printer/test/test_trino_printer.py b/posthog/hogql/printer/test/test_trino_printer.py
index bcb2a4c27e01..dd4b20859e03 100644
--- a/posthog/hogql/printer/test/test_trino_printer.py
+++ b/posthog/hogql/printer/test/test_trino_printer.py
@@ -4,6 +4,8 @@ from contextlib import closing
import pytest
from unittest import mock
+from syrupy.assertion import SnapshotAssertion
+
from posthog.schema import HogQLQueryModifiers
from posthog.hogql import ast
@@ -14,6 +16,7 @@ from posthog.hogql.database.direct_trino_table import DirectTrinoTable
from posthog.hogql.database.models import DateTimeDatabaseField, StringDatabaseField, StringJSONDatabaseField, TableNode
from posthog.hogql.errors import QueryError
from posthog.hogql.escape_sql import escape_trino_identifier
+from posthog.hogql.helpers.timestamp_visitor import is_time_or_interval_constant
from posthog.hogql.parser import parse_select
from posthog.hogql.printer import prepare_and_print_ast, prepare_ast_for_printing, print_prepared_ast
from posthog.hogql.transforms.trino.errors import TrinoLoweringError
@@ -72,11 +75,19 @@ 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:
+ "query",
+ [
+ "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",
+ ],
+)
+def test_prepared_trino_transpiler_does_not_rebuild_the_schema_database(
+ query: str, snapshot: SnapshotAssertion
+) -> 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"
- )
+ prepared = prepare_ast_for_printing(parse_select(query), preparation_context, "trino")
assert prepared is not None
assert preparation_context.database is not None
@@ -98,11 +109,7 @@ def test_prepared_trino_transpiler_does_not_rebuild_the_schema_database() -> Non
):
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"}
+ assert (transpiled.sql, transpiled.values) == snapshot
def test_prints_trino_lambda_syntax() -> None:
@@ -960,3 +967,165 @@ def test_rejects_source_ast_with_clickhouse_settings() -> None:
prepare_and_print_ast(query, _context_with_trino_table(), "trino")
assert error.value.feature_code == "TRINO_SETTINGS_UNSUPPORTED"
+
+
+ "query",
+ [
+ "SELECT user_id FROM users ORDER BY created_at DESC LIMIT 2 BY user_id LIMIT 5 OFFSET 1",
+ "SELECT user_id FROM users ORDER BY toStartOfDay(created_at) DESC LIMIT 2 BY user_id",
+ "SELECT user_id AS id FROM users ORDER BY id DESC LIMIT 2 BY id",
+ "SELECT user_id, created_at FROM users ORDER BY 2 DESC LIMIT 2 BY user_id",
+ "SELECT user_id, created_at FROM users ORDER BY 2 DESC LIMIT 2 BY 1",
+ "SELECT user_id AS __hogql_order_0, created_at AS __hogql_limit_by_row_0 "
+ "FROM users ORDER BY toStartOfDay(created_at) DESC LIMIT 2 BY user_id",
+ "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",
+ "SELECT user_id, row_number() OVER (ORDER BY created_at) AS position "
+ "FROM users QUALIFY position = 1 ORDER BY created_at DESC LIMIT 3",
+ "SELECT user_id, count() AS total FROM users GROUP BY user_id ORDER BY total DESC LIMIT 2 BY user_id",
+ "SELECT user_id, user_id = toString(1) AS bucket, row_number() OVER (ORDER BY user_id) AS rn "
+ "FROM users QUALIFY rn > 0 ORDER BY user_id = toString(true) DESC LIMIT 1",
+ "SELECT user_id, user_id = toString(1) AS bucket, row_number() OVER (ORDER BY user_id) AS rn "
+ "FROM users QUALIFY rn > 0 ORDER BY user_id = toString(1.0) DESC LIMIT 1",
+ "SELECT properties.color FROM users ORDER BY user_id LIMIT 1 BY user_id",
+ "SELECT properties.color, row_number() OVER (ORDER BY user_id) AS rn "
+ "FROM users QUALIFY rn = 1 ORDER BY user_id",
+ ],
+)
+def test_wrapper_sort_projections_preserve_output(query: str, snapshot: SnapshotAssertion) -> None:
+ context = _context_with_trino_table()
+ sql, node = prepare_and_print_ast(parse_select(query), context, "trino")
+
+ assert isinstance(node, ast.SelectQuery)
+ assert node.select_from is not None
+ inner = node.select_from.table
+ assert isinstance(inner, ast.SelectQuery)
+ for expr in node.select:
+ while isinstance(expr, ast.Alias):
+ expr = expr.expr
+ assert isinstance(expr, ast.Field)
+ original = parse_select(query)
+ assert isinstance(original, ast.SelectQuery)
+ assert len(node.select) == len(original.select)
+ assert inner.order_by is None
+ assert inner.limit is None
+ assert inner.limit_by is None
+ assert inner.qualify is None
+ assert (sql, context.values) == snapshot
+
+
+ ("query", "feature_code"),
+ [
+ (
+ "SELECT user_id FROM users GROUP BY user_id ORDER BY created_at LIMIT 1 BY user_id",
+ "TRINO_WRAPPER_ORDER_NOT_PROJECTED",
+ ),
+ (
+ "SELECT user_id, count() AS total FROM users GROUP BY user_id ORDER BY max(created_at) DESC LIMIT 2 BY user_id",
+ "TRINO_WRAPPER_ORDER_NOT_PROJECTED",
+ ),
+ ("SELECT user_id FROM users ORDER BY count() LIMIT 1 BY user_id", "TRINO_WRAPPER_ORDER_NOT_PROJECTED"),
+ (
+ "SELECT user_id FROM users ORDER BY count() + 1 LIMIT 1 BY user_id",
+ "TRINO_WRAPPER_ORDER_NOT_PROJECTED",
+ ),
+ (
+ "SELECT DISTINCT user_id, row_number() OVER (ORDER BY user_id) AS position "
+ "FROM users QUALIFY position = 1 ORDER BY created_at",
+ "TRINO_WRAPPER_ORDER_NOT_PROJECTED",
+ ),
+ ("SELECT user_id FROM users ORDER BY 2 LIMIT 1 BY user_id", "TRINO_POSITIONAL_REFERENCE_INVALID"),
+ ("SELECT user_id FROM users LIMIT 1 BY 2", "TRINO_POSITIONAL_REFERENCE_INVALID"),
+ (
+ "SELECT DISTINCT user_id, user_id = toString(1) AS bucket, row_number() OVER (ORDER BY user_id) AS rn "
+ "FROM users QUALIFY rn > 0 ORDER BY user_id = toString(true)",
+ "TRINO_WRAPPER_ORDER_NOT_PROJECTED",
+ ),
+ (
+ "SELECT user_id FROM users ORDER BY row_number() OVER (ORDER BY created_at) LIMIT 1 BY user_id",
+ "TRINO_LIMIT_BY_WINDOW_UNSUPPORTED",
+ ),
+ (
+ "SELECT user_id, row_number() OVER (ORDER BY created_at) AS rn FROM users ORDER BY 2 LIMIT 1 BY user_id",
+ "TRINO_LIMIT_BY_WINDOW_UNSUPPORTED",
+ ),
+ (
+ "SELECT user_id, row_number() OVER (ORDER BY created_at) AS rn FROM users LIMIT 1 BY rn",
+ "TRINO_LIMIT_BY_WINDOW_UNSUPPORTED",
+ ),
+ ],
+)
+def test_wrapper_rejects_unsafe_sort_or_partition(query: str, feature_code: str) -> None:
+ with pytest.raises(TrinoLoweringError, match=feature_code):
+ prepare_and_print_ast(
+ parse_select(query),
+ _context_with_trino_table(),
+ "trino",
+ )
+
+
+ ("expression", "group_by"),
+ [
+ ("properties.color", None),
+ ("toStartOfMonth(toTimeZone(created_at, 'UTC'))", None),
+ ("notEmpty(properties.color)", None),
+ ("concat(user_id, 'suffix')", None),
+ pytest.param("2", "dimension", id="integer_alias"),
+ pytest.param("0", "dimension", id="zero_alias"),
+ ],
+)
+def test_grouping_reuses_projected_expression(
+ expression: str, group_by: str | None, snapshot: SnapshotAssertion
+) -> None:
+ context = _context_with_trino_table()
+ sql, node = prepare_and_print_ast(
+ parse_select(f"SELECT {expression} AS dimension, count() FROM users GROUP BY {group_by or expression}"),
+ context,
+ "trino",
+ )
+
+ assert isinstance(node, ast.SelectQuery)
+ assert node.group_by is not None
+ assert len(node.group_by) == 1
+ assert isinstance(node.group_by[0], ast.PositionalRef)
+ assert node.group_by[0].index == 1
+ assert (sql, context.values) == snapshot
+
+
+def test_lowered_property_timestamp_is_not_constant(snapshot: SnapshotAssertion) -> None:
+ context = _context_with_trino_table()
+ sql, node = prepare_and_print_ast(parse_select("SELECT toDateTime(properties.cutoff) FROM users"), context, "trino")
+
+ assert isinstance(node, ast.SelectQuery)
+ expr = node.select[0]
+ assert isinstance(expr, ast.Call)
+ argument = expr.args[0]
+ while isinstance(argument, ast.Alias):
+ argument = argument.expr
+ assert isinstance(argument, ast.PropertyAccess)
+ assert not is_time_or_interval_constant(expr)
+ assert (sql, context.values) == snapshot
+
+
+ "query",
+ [
+ "SELECT a.user_id FROM users a JOIN users b ON a.user_id = b.user_id GROUP BY b.user_id",
+ "SELECT user_id AS id FROM users GROUP BY concat(id, 'suffix')",
+ "SELECT properties.color, count() FROM users GROUP BY properties.shape",
+ "SELECT user_id, count() FROM users GROUP BY ROLLUP(user_id)",
+ "SELECT 2, count() FROM users GROUP BY 2",
+ "SELECT user_id = toString(1) AS bucket, count() FROM users GROUP BY user_id = toString(true)",
+ ],
+)
+def test_grouping_does_not_replace_different_or_nested_expressions(query: str, snapshot: SnapshotAssertion) -> None:
+ context = _context_with_trino_table()
+ sql, node = prepare_and_print_ast(parse_select(query), context, "trino")
+
+ assert isinstance(node, ast.SelectQuery)
+ assert node.group_by is not None
+ assert not isinstance(node.group_by[0], ast.PositionalRef)
+ assert (sql, context.values) == snapshot
diff --git a/posthog/hogql/test/test_trino_semantics.py b/posthog/hogql/test/test_trino_semantics.py
index 3011fcbeb87c..437dcda830f0 100644
--- a/posthog/hogql/test/test_trino_semantics.py
+++ b/posthog/hogql/test/test_trino_semantics.py
@@ -4,6 +4,7 @@ from django.test import SimpleTestCase
from posthog.schema import HogQLQueryModifiers
+from posthog.hogql import ast
from posthog.hogql.context import HogQLContext
from posthog.hogql.database.database import Database
from posthog.hogql.errors import QueryError
@@ -58,8 +59,11 @@ class TestTrinoSemantics(APIBaseTest):
)
context = self._semantic_context(["events"])
- sql, _ = prepare_and_print_ast(
- parse_select(f"SELECT event FROM events WHERE matchesAction({action.pk})"),
+ sql, node = prepare_and_print_ast(
+ parse_select(
+ f"SELECT event, count() AS total FROM events WHERE matchesAction({action.pk}) "
+ "GROUP BY event ORDER BY total DESC LIMIT 1 BY event"
+ ),
context,
"trino",
)
@@ -67,6 +71,9 @@ class TestTrinoSemantics(APIBaseTest):
self.assertNotIn("matchesAction", sql)
self.assertIn('"ducklake"."analytics"."events"', sql)
self.assertIn("checkout completed", context.values.values())
+ self.assertIsInstance(node, ast.SelectQuery)
+ self.assertIn("GROUP BY 1", sql)
+ self.assertIn('ORDER BY "__hogql_trino_source_0"."total" DESC', sql)
def test_cohort_semantics_expand_before_trino_printing(self) -> None:
cohort = Cohort.objects.create(team=self.team, name="active accounts")
diff --git a/posthog/hogql/transforms/trino/expressions.py b/posthog/hogql/transforms/trino/expressions.py
new file mode 100644
index 000000000000..f4b3860c3070
--- /dev/null
+++ b/posthog/hogql/transforms/trino/expressions.py
@@ -0,0 +1,40 @@
+from dataclasses import fields
+
+from posthog.hogql import ast
+
+
+def expression_key(value: object) -> tuple[object, ...]:
+ if isinstance(value, ast.Alias):
+ return expression_key(value.expr)
+ if isinstance(value, ast.Field):
+ field_type = value.type
+ while isinstance(field_type, ast.FieldAliasType):
+ field_type = field_type.type
+ if isinstance(field_type, ast.PropertyType):
+ return (ast.Field, id(field_type.field_type.table_type), field_type.field_type.name, *field_type.chain)
+ if isinstance(field_type, ast.FieldType):
+ # A resolved binding distinguishes joined columns even when their names match.
+ return (ast.Field, id(field_type.table_type), field_type.name)
+ if isinstance(value, ast.AST):
+ return (
+ type(value),
+ tuple(
+ (field.name, expression_key(getattr(value, field.name)))
+ for field in fields(value)
+ if field.name not in {"start", "end", "type"}
+ ),
+ )
+ if isinstance(value, (list, tuple)):
+ return (type(value), tuple(expression_key(item) for item in value))
+ if isinstance(value, dict):
+ return (dict, {key: expression_key(item) for key, item in value.items()})
+ # Python considers 1, True, and 1.0 equal, but SQL casts distinguish their literal types.
+ return (type(value), value)
+
+
+def positional_index(node: ast.Expr) -> int | None:
+ if isinstance(node, ast.PositionalRef):
+ return node.index
+ if isinstance(node, ast.Constant) and isinstance(node.value, int) and not isinstance(node.value, bool):
+ return node.value
+ return None
diff --git a/posthog/hogql/transforms/trino/normalize.py b/posthog/hogql/transforms/trino/normalize.py
index 2e7e085e636a..ffe3f603af14 100644
--- a/posthog/hogql/transforms/trino/normalize.py
+++ b/posthog/hogql/transforms/trino/normalize.py
@@ -4,6 +4,7 @@ from posthog.hogql.database.schema.numbers import NumbersTable
from posthog.hogql.database.trino_unnest_table import TRINO_UNNEST_TABLE_NAME
from posthog.hogql.transforms.trino.any_join import lower_trino_any_joins
from posthog.hogql.transforms.trino.errors import TrinoLoweringError
+from posthog.hogql.transforms.trino.expressions import expression_key, positional_index
from posthog.hogql.transforms.trino.query_wrappers import lower_trino_query_wrappers
from posthog.hogql.visitor import CloningVisitor, TraversingVisitor
@@ -105,27 +106,22 @@ class TrinoSelectAliasLowerer(CloningVisitor):
def __init__(self) -> None:
super().__init__(clear_types=False)
self.aliases: dict[str, ast.Expr] = {}
- self.alias_positions: dict[str, int] = {}
self.expanding: set[str] = set()
- self.in_group_by = False
def visit_select_query(self, node: ast.SelectQuery) -> ast.SelectQuery:
outer_aliases = self.aliases
- outer_alias_positions = self.alias_positions
self.aliases = {expr.alias: expr.expr for expr in node.select if isinstance(expr, ast.Alias)}
- self.alias_positions = {
- expr.alias: index for index, expr in enumerate(node.select, start=1) if isinstance(expr, ast.Alias)
- }
lowered = super().visit_select_query(node)
- if node.group_by is not None:
- outer_in_group_by = self.in_group_by
- self.in_group_by = True
- try:
- lowered.group_by = [self.visit(expr) for expr in node.group_by]
- finally:
- self.in_group_by = outer_in_group_by
+ if node.group_by is not None and lowered.group_by is not None and lowered.group_by_mode is None:
+ projections = [expression_key(expr) for expr in lowered.select]
+ # Separate parameter occurrences are not identical grouping expressions in Trino.
+ for index, expr in enumerate(lowered.group_by):
+ if positional_index(node.group_by[index]) is not None:
+ continue
+ key = expression_key(expr)
+ if key in projections:
+ lowered.group_by[index] = ast.PositionalRef(index=projections.index(key) + 1)
self.aliases = outer_aliases
- self.alias_positions = outer_alias_positions
return lowered
def visit_field(self, node: ast.Field) -> ast.Expr:
@@ -137,8 +133,6 @@ class TrinoSelectAliasLowerer(CloningVisitor):
and node.chain[0] not in self.expanding
):
alias = node.chain[0]
- if self.in_group_by:
- return ast.PositionalRef(index=self.alias_positions[alias])
self.expanding.add(alias)
try:
return self.visit(self.aliases[alias])
diff --git a/posthog/hogql/transforms/trino/query_wrappers.py b/posthog/hogql/transforms/trino/query_wrappers.py
index 5627334f53e9..44dd7ded2e18 100644
--- a/posthog/hogql/transforms/trino/query_wrappers.py
+++ b/posthog/hogql/transforms/trino/query_wrappers.py
@@ -1,5 +1,7 @@
from posthog.hogql import ast
+from posthog.hogql.functions.mapping import find_hogql_aggregation
from posthog.hogql.transforms.trino.errors import TrinoLoweringError
+from posthog.hogql.transforms.trino.expressions import expression_key, positional_index
from posthog.hogql.visitor import CloningVisitor, TraversingVisitor
@@ -11,6 +13,19 @@ class _WindowFunctionFinder(TraversingVisitor):
super().visit_window_function(node)
+class _AggregateFunctionFinder(TraversingVisitor):
+ found: bool = False
+
+ def visit_select_query(self, node: ast.SelectQuery) -> None:
+ pass
+
+ def visit_call(self, node: ast.Call) -> None:
+ if find_hogql_aggregation(node.name):
+ self.found = True
+ else:
+ super().visit_call(node)
+
+
class TrinoQueryWrapperLowerer(CloningVisitor):
def __init__(self) -> None:
super().__init__(clear_types=False)
@@ -46,15 +61,15 @@ class TrinoQueryWrapperLowerer(CloningVisitor):
raise TrinoLoweringError("TRINO_LIMIT_BY_DISTINCT_UNSUPPORTED", "LIMIT BY with DISTINCT", node)
n = self._non_negative_integer(node.limit_by.n, "LIMIT BY count")
offset = self._non_negative_integer(node.limit_by.offset_value, "LIMIT BY offset", default=0)
- helper_name = f"__hogql_limit_by_row_{self.wrapper_index}"
+ helper_name = self._helper_name(node, f"__hogql_limit_by_row_{self.wrapper_index}")
row_number = ast.WindowFunction(
name="row_number",
exprs=[],
over_expr=ast.WindowExpr(
- partition_by=[self._unwrap_hidden_alias(expr) for expr in node.limit_by.exprs],
+ partition_by=[self._input_expression(expr, node.select) for expr in node.limit_by.exprs],
order_by=(
[
- ast.OrderExpr(expr=self._unwrap_hidden_alias(order.expr), order=order.order)
+ ast.OrderExpr(expr=self._input_expression(order.expr, node.select), order=order.order)
for order in node.order_by
]
if node.order_by
@@ -62,6 +77,14 @@ class TrinoQueryWrapperLowerer(CloningVisitor):
),
),
)
+ finder = _WindowFunctionFinder()
+ finder.visit(row_number.over_expr)
+ if finder.found:
+ raise TrinoLoweringError(
+ "TRINO_LIMIT_BY_WINDOW_UNSUPPORTED",
+ "LIMIT BY partition or ordering containing a window expression",
+ node,
+ )
node.select.append(ast.Alias(alias=helper_name, expr=row_number))
node.limit_by = None
predicate: ast.Expr = ast.CompareOperation(
@@ -92,11 +115,13 @@ class TrinoQueryWrapperLowerer(CloningVisitor):
"TRINO_WRAPPER_OUTPUT_NAME_UNSAFE", "wrapper query without stable output names", node
)
node.select = [
- expr if isinstance(expr, ast.Alias) and expr.alias == name else ast.Alias(alias=name, expr=expr)
+ expr
+ if isinstance(expr, ast.Alias) and expr.alias == name and not expr.hidden
+ else ast.Alias(alias=name, expr=expr)
for expr, name in zip(visible_select, output_names, strict=True)
] + ([node.select[-1]] if helper_name is not None else [])
- outer_order = self._outer_order_by(node.order_by, output_names, source_alias)
+ outer_order = self._outer_order_by(node, output_names, source_alias)
outer_limit = node.limit
outer_offset = node.offset
outer_limit_with_ties = node.limit_with_ties
@@ -135,38 +160,84 @@ class TrinoQueryWrapperLowerer(CloningVisitor):
def _outer_order_by(
self,
- order_by: list[ast.OrderExpr] | None,
+ node: ast.SelectQuery,
output_names: list[str],
source_alias: str,
) -> list[ast.OrderExpr] | None:
- if order_by is None:
+ if node.order_by is None:
return None
- output_set = set(output_names)
+ projections = [expression_key(expr) for expr in node.select[: len(output_names)]]
outer: list[ast.OrderExpr] = []
- for order in order_by:
+ for order in node.order_by:
if order.with_fill is not None:
raise TrinoLoweringError("TRINO_ORDER_BY_WITH_FILL_UNSUPPORTED", "ORDER BY WITH FILL", order.expr)
- if isinstance(order.expr, ast.PositionalRef):
- expr: ast.Expr = ast.PositionalRef(index=order.expr.index)
- else:
- unwrapped = self._unwrap_hidden_alias(order.expr)
- if not isinstance(unwrapped, ast.Field) or not isinstance(unwrapped.chain[-1], str):
- raise TrinoLoweringError(
- "TRINO_WRAPPER_ORDER_NOT_PROJECTED",
- "LIMIT BY or QUALIFY ORDER BY expression not present in SELECT",
- order.expr,
- )
- name = unwrapped.chain[-1]
- if name not in output_set:
+ position = positional_index(order.expr)
+ if position is not None:
+ if not 1 <= position <= len(output_names):
raise TrinoLoweringError(
- "TRINO_WRAPPER_ORDER_NOT_PROJECTED",
- "LIMIT BY or QUALIFY ORDER BY expression not present in SELECT",
- order.expr,
+ "TRINO_POSITIONAL_REFERENCE_INVALID", "ORDER BY ordinal out of range", order.expr
)
+ expr: ast.Expr = ast.PositionalRef(index=position)
+ else:
+ unwrapped = self._input_expression(order.expr, node.select[: len(output_names)])
+ key = expression_key(unwrapped)
+ if key in projections:
+ name = output_names[projections.index(key)]
+ else:
+ finder = _AggregateFunctionFinder()
+ finder.visit(unwrapped)
+ if node.distinct or node.group_by is not None or finder.found:
+ raise TrinoLoweringError(
+ "TRINO_WRAPPER_ORDER_NOT_PROJECTED",
+ "DISTINCT or grouped wrapper, or aggregate ORDER BY expression not present in SELECT",
+ order.expr,
+ )
+ name = self._helper_name(node, f"__hogql_order_{len(outer)}")
+ node.select.append(ast.Alias(alias=name, expr=unwrapped))
expr = ast.Field(chain=[source_alias, name])
outer.append(ast.OrderExpr(expr=expr, order=order.order))
return outer
+ def _input_expression(self, expr: ast.Expr, select: list[ast.Expr]) -> ast.Expr:
+ expr = self._unwrap_hidden_alias(expr)
+ position = positional_index(expr)
+ if position is not None:
+ if not 1 <= position <= len(select):
+ raise TrinoLoweringError("TRINO_POSITIONAL_REFERENCE_INVALID", "wrapper ordinal out of range", expr)
+ expr = select[position - 1]
+ elif isinstance(expr, ast.Field) and isinstance(expr.type, ast.FieldAliasType) and len(expr.chain) == 1:
+ alias_name = expr.chain[0]
+ expr = next(
+ (
+ projection
+ for projection in select
+ if isinstance(projection, ast.Alias) and projection.alias == alias_name
+ ),
+ expr,
+ )
+ while isinstance(expr, ast.Alias):
+ expr = expr.expr
+ return expr
+
+ def _helper_name(self, node: ast.SelectQuery, prefix: str) -> str:
+ names = set(self._output_names(node))
+
+ class NameFinder(TraversingVisitor):
+ def visit_alias(self, alias: ast.Alias) -> None:
+ names.add(alias.alias)
+ super().visit_alias(alias)
+
+ def visit_field(self, field: ast.Field) -> None:
+ names.update(part for part in field.chain if isinstance(part, str))
+
+ NameFinder().visit(node)
+ name = prefix
+ suffix = 1
+ while name in names:
+ name = f"{prefix}_{suffix}"
+ suffix += 1
+ return name
+
def _unwrap_hidden_alias(self, expr: ast.Expr) -> ast.Expr:
while isinstance(expr, ast.Alias) and expr.hidden:
expr = expr.expr
diff --git a/posthog/hogql/transforms/trino/test/__snapshots__/test_manifest.ambr b/posthog/hogql/transforms/trino/test/__snapshots__/test_manifest.ambr
new file mode 100644
index 000000000000..75bc4f806970
--- /dev/null
+++ b/posthog/hogql/transforms/trino/test/__snapshots__/test_manifest.ambr
@@ -0,0 +1,19 @@
+# serializer version: 1
+# name: test_transpiles_core_table_with_values_without_django_queries[SELECT event FROM events WHERE event = {event} ORDER BY timestamp DESC LIMIT 1 BY event]
+ tuple(
+ 'SELECT "__hogql_trino_source_0"."event" FROM (SELECT "org_catalog"."posthog"."events_production"."event" AS "event", row_number() OVER (PARTITION BY "org_catalog"."posthog"."events_production"."event" ORDER BY "org_catalog"."posthog"."events_production"."timestamp" DESC) AS "__hogql_limit_by_row_0", "org_catalog"."posthog"."events_production"."timestamp" AS "__hogql_order_0" FROM "org_catalog"."posthog"."events_production" WHERE ("org_catalog"."posthog"."events_production"."event" = %(hogql_val_0)s)) AS "__hogql_trino_source_0" WHERE ("__hogql_trino_source_0"."__hogql_limit_by_row_0" <= 1) ORDER BY "__hogql_trino_source_0"."__hogql_order_0" DESC LIMIT 50000',
+ dict({
+ 'hogql_val_0': 'signup',
+ }),
+ "SELECT event FROM events WHERE equals(event, 'signup') ORDER BY timestamp DESC LIMIT 1 BY event LIMIT 50000",
+ )
+# ---
+# name: test_transpiles_core_table_with_values_without_django_queries[SELECT event FROM events WHERE event = {event}]
+ tuple(
+ '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',
+ dict({
+ 'hogql_val_0': 'signup',
+ }),
+ "SELECT event FROM events WHERE equals(event, 'signup') LIMIT 50000",
+ )
+# ---
diff --git a/posthog/hogql/transforms/trino/test/test_manifest.py b/posthog/hogql/transforms/trino/test/test_manifest.py
index 068d55c7660c..c20dc9bdd343 100644
--- a/posthog/hogql/transforms/trino/test/test_manifest.py
+++ b/posthog/hogql/transforms/trino/test/test_manifest.py
@@ -3,6 +3,8 @@ from typing import Any
import pytest
from unittest import mock
+from syrupy.assertion import SnapshotAssertion
+
from posthog.schema import DateRange, HogQLFilters, HogQLQueryModifiers, HogQLVariable
from posthog.hogql.errors import QueryError
@@ -32,24 +34,27 @@ def _events() -> TrinoManifestTable:
)
+ "query",
+ [
+ "SELECT event FROM events WHERE event = {event}",
+ "SELECT event FROM events WHERE event = {event} ORDER BY timestamp DESC LIMIT 1 BY event",
+ ],
+)
def test_transpiles_core_table_with_values_without_django_queries(
django_assert_num_queries: Any,
+ query: str,
+ snapshot: SnapshotAssertion,
) -> None:
with django_assert_num_queries(0):
result = transpile_hogql_to_trino(
- "SELECT event FROM events WHERE event = {event}",
+ query,
manifest=_manifest(_events()),
values={"event": "signup"},
include_hogql=True,
)
- assert result.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 result.values == {"hogql_val_0": "signup"}
- assert result.hogql == "SELECT event FROM events WHERE equals(event, 'signup') LIMIT 50000"
+ assert (result.sql, result.values, result.hogql) == snapshot
def test_transpiles_manifest_table_without_django_queries(django_assert_num_queries: Any) -> None: