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): close five more trino lowering gaps (#123152)

Jovan Sakovic6b2b26e6fd70
diff --git a/posthog/hogql/database/database.py b/posthog/hogql/database/database.py
index 5990f20b4531..d65f4a15146e 100644
--- a/posthog/hogql/database/database.py
+++ b/posthog/hogql/database/database.py
@@ -880,7 +880,8 @@ class Database(BaseModel):
except ZoneInfoNotFoundError:
raise ValueError(f"Unknown timezone: '{str(timezone)}'")
- self._week_start_day = week_start_day
+ # The team model stores a plain integer, and printers read the enum's members.
+ self._week_start_day = WeekStartDay(week_start_day) if week_start_day is not None else None
self._warehouse_table_names = []
self._warehouse_self_managed_table_names = []
self._view_table_names = []
diff --git a/posthog/hogql/escape_sql.py b/posthog/hogql/escape_sql.py
index d6305143e426..d46905bbbe6b 100644
--- a/posthog/hogql/escape_sql.py
+++ b/posthog/hogql/escape_sql.py
@@ -284,6 +284,13 @@ def escape_trino_identifier(v: str) -> str:
return '"' + v.replace('"', '""') + '"'
+def escape_trino_string(v: str) -> str:
+ # Trino string literals have no backslash escapes; doubling the quote is the only escape.
+ if "\0" in v:
+ raise QueryError("Trino string literals cannot contain the NUL character")
+ return "'" + v.replace("'", "''") + "'"
+
+
def escape_snowflake_identifier(v: str) -> str:
# Always double-quote: Snowflake folds unquoted identifiers to uppercase, so quoting
# preserves the column's stored case. ``%`` is rejected for parity with the other
diff --git a/posthog/hogql/printer/test/__snapshots__/test_trino_printer.ambr b/posthog/hogql/printer/test/__snapshots__/test_trino_printer.ambr
index 36d3065e00d1..bc0930e7fe28 100644
--- a/posthog/hogql/printer/test/__snapshots__/test_trino_printer.ambr
+++ b/posthog/hogql/printer/test/__snapshots__/test_trino_printer.ambr
@@ -15,10 +15,8 @@
# ---
# 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) AS "color", count(*) FROM "ducklake"."analytics"."users" AS "users" GROUP BY json_extract_scalar("users"."properties", %(hogql_val_1)s)',
+ 'SELECT json_extract_scalar("users"."properties", \'$["color"]\') AS "color", count(*) FROM "ducklake"."analytics"."users" AS "users" GROUP BY json_extract_scalar("users"."properties", \'$["shape"]\')',
dict({
- 'hogql_val_0': '$["color"]',
- 'hogql_val_1': '$["shape"]',
}),
)
# ---
@@ -61,17 +59,15 @@
# ---
# 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',
+ 'SELECT (json_extract_scalar("users"."properties", \'$["color"]\') IS NOT NULL AND json_extract_scalar("users"."properties", \'$["color"]\') <> \'\') 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',
+ 'SELECT json_extract_scalar("users"."properties", \'$["color"]\') AS "dimension", count(*) FROM "ducklake"."analytics"."users" AS "users" GROUP BY 1',
dict({
- 'hogql_val_0': '$["color"]',
}),
)
# ---
@@ -92,17 +88,15 @@
# ---
# name: test_lowered_property_timestamp_is_not_constant
tuple(
- 'SELECT coalesce(TRY_CAST(json_extract_scalar("users"."properties", %(hogql_val_0)s) AS TIMESTAMP), CAST(TRY(from_iso8601_timestamp(json_extract_scalar("users"."properties", %(hogql_val_0)s))) AS TIMESTAMP), CAST(from_unixtime(TRY_CAST(json_extract_scalar("users"."properties", %(hogql_val_0)s) AS DOUBLE)) AS TIMESTAMP)) FROM "ducklake"."analytics"."users" AS "users"',
+ 'SELECT coalesce(TRY_CAST(json_extract_scalar("users"."properties", \'$["cutoff"]\') AS TIMESTAMP), CAST(TRY(from_iso8601_timestamp(json_extract_scalar("users"."properties", \'$["cutoff"]\'))) AS TIMESTAMP), CAST(from_unixtime(TRY_CAST(json_extract_scalar("users"."properties", \'$["cutoff"]\') AS DOUBLE)) 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) AS "color", count(*) FROM "ducklake"."analytics"."users" AS "users" GROUP BY 1',
+ 'SELECT json_extract_scalar("users"."properties", \'$["color"]\') AS "color", count(*) FROM "ducklake"."analytics"."users" AS "users" GROUP BY 1',
dict({
- 'hogql_val_0': '$["color"]',
}),
)
# ---
@@ -491,17 +485,15 @@
# ---
# 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',
+ 'SELECT "__hogql_trino_source_0"."color" FROM (SELECT json_extract_scalar("users"."properties", \'$["color"]\') 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',
+ 'SELECT "__hogql_trino_source_0"."color", "__hogql_trino_source_0"."rn" FROM (SELECT json_extract_scalar("users"."properties", \'$["color"]\') 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"]',
}),
)
# ---
diff --git a/posthog/hogql/printer/test/test_trino_printer.py b/posthog/hogql/printer/test/test_trino_printer.py
index 75e067902bdb..34669a281b7e 100644
--- a/posthog/hogql/printer/test/test_trino_printer.py
+++ b/posthog/hogql/printer/test/test_trino_printer.py
@@ -19,11 +19,13 @@ from posthog.hogql.database.models import (
ExpressionField,
IntegerDatabaseField,
SavedQuery,
+ StringArrayDatabaseField,
StringDatabaseField,
StringJSONDatabaseField,
TableNode,
UUIDDatabaseField,
)
+from posthog.hogql.database.s3_table import DataWarehouseTable
from posthog.hogql.errors import QueryError
from posthog.hogql.escape_sql import escape_trino_identifier
from posthog.hogql.functions.mapping import HOGQL_AGGREGATIONS, HOGQL_CLICKHOUSE_FUNCTIONS, HOGQL_POSTHOG_FUNCTIONS
@@ -226,6 +228,26 @@ def test_prepared_trino_transpiler_does_not_rebuild_the_schema_database(
assert (transpiled.sql, transpiled.values) == snapshot
+ "week_start_day, expected",
+ [
+ (0, "date_add('day', -1, date_trunc('week', date_add('day', 1, "),
+ (1, "CAST(date_trunc('week', "),
+ ],
+)
+def test_to_start_of_week_accepts_the_week_start_day_stored_on_the_team(week_start_day: int, expected: str) -> None:
+ context = _context_with_trino_table()
+ assert context.database is not None
+ users = context.database.tables.children["users"]
+ # The team row stores the week start day as a plain integer, not as the enum.
+ context.database = Database(week_start_day=week_start_day, include_posthog_tables=False) # type: ignore[arg-type]
+ context.database.tables.add_child(users)
+
+ sql, _ = prepare_and_print_ast(parse_select("SELECT toStartOfWeek(created_at) FROM users"), context, "trino")
+
+ assert expected in sql
+
+
def test_prints_trino_lambda_syntax() -> None:
context = HogQLContext()
node = ast.Lambda(args=["value"], expr=ast.Field(chain=["value"], type=ast.LambdaArgumentType(name="value")))
@@ -373,6 +395,7 @@ def test_ignores_clickhouse_cte_materialization_hint() -> None:
("domain(user_id)", "coalesce(TRY(url_extract_host(CAST("),
("multiplyDecimal(1, 2)", "CAST((1 * 2) AS DECIMAL(38, 0))"),
("quantileExact(0.9)(length(user_id))", "filter(coalesce(array_agg(length("),
+ ("quantileExact(0.5)(log10(1 + length(user_id)))", "filter(coalesce(array_agg(log10("),
("ngramDistance(user_id, 'abc')", "MAP(VARBINARY, BIGINT)"),
("formatReadableTimeDelta(3661)", "'hour', 'hours'"),
(
@@ -724,10 +747,10 @@ def test_coerces_strict_trino_types_after_property_lowering() -> None:
"trino",
)
- assert 'CAST(json_extract_scalar("users"."properties", %(hogql_val_0)s) AS DOUBLE) / CAST(1000 AS DOUBLE)' in sql
- assert 'sum(CAST(json_extract_scalar("users"."properties", %(hogql_val_1)s) AS DOUBLE))' in sql
- assert 'CAST(json_extract_scalar("users"."properties", %(hogql_val_2)s) AS BOOLEAN) = true' in sql
- assert '"users"."created_at" >= CAST(%(hogql_val_3)s AS TIMESTAMP)' in sql
+ assert 'CAST(json_extract_scalar("users"."properties", \'$["duration"]\') AS DOUBLE) / CAST(1000 AS DOUBLE)' in sql
+ assert 'sum(CAST(json_extract_scalar("users"."properties", \'$["amount"]\') AS DOUBLE))' in sql
+ assert 'CAST(json_extract_scalar("users"."properties", \'$["failed"]\') AS BOOLEAN) = true' in sql
+ assert '"users"."created_at" >= CAST(%(hogql_val_0)s AS TIMESTAMP)' in sql
def test_prints_iso_datetime_and_heterogeneous_concat_for_trino() -> None:
@@ -792,9 +815,10 @@ def test_preserves_clickhouse_json_array_indexing() -> None:
assert "AS ARRAY(JSON)), 2)" in sql
assert 'AS ARRAY(JSON)), CAST(length("users"."user_id") AS INTEGER))' in sql
assert sql.count("element_at(") == 9
- assert 'CAST(json_extract("users"."properties", %(hogql_val_1)s) AS ARRAY(JSON))' in sql
+ assert 'CAST(json_extract("users"."properties", \'$["items"]\') AS ARRAY(JSON))' in sql
+ assert 'json_extract("users"."user_id", \'$["key.with.dot"]\')' in sql
assert "CAST(TRY(element_at(" in sql
- assert context.values == {"hogql_val_0": '$["key.with.dot"]', "hogql_val_1": '$["items"]'}
+ assert context.values == {}
@pytest.mark.parametrize("operator", ["+", "-", "*", "/", "%"])
@@ -804,10 +828,10 @@ def test_chained_arithmetic_keeps_only_used_parameters(operator: str) -> None:
sql, _ = prepare_and_print_ast(parse_select(f"SELECT {f' {operator} '.join(terms)} FROM users"), context, "trino")
- assert context.values == {f"hogql_val_{index}": f'$["metric_{index}"]' for index in range(6)}
+ assert context.values == {}
rendered_terms = [
'coalesce(TRY(CAST(json_extract_scalar("users"."user_id", '
- f"%(hogql_val_{index})s) AS DOUBLE)), CAST(0 AS DOUBLE))"
+ f"'$[\"metric_{index}\"]') AS DOUBLE)), CAST(0 AS DOUBLE))"
for index in range(6)
]
expected = rendered_terms[0]
@@ -899,14 +923,9 @@ def test_lowers_event_property_backed_fields_to_the_physical_json_column() -> No
"trino",
)
- assert 'json_extract_scalar("tenant"."posthog"."events"."properties", %(hogql_val_0)s)' in sql
- assert 'json_extract_scalar("tenant"."posthog"."events"."properties", %(hogql_val_1)s)' in sql
- assert 'json_extract_scalar("tenant"."posthog"."events"."properties", %(hogql_val_2)s)' in sql
- assert context.values == {
- "hogql_val_0": '$["$session_id"]',
- "hogql_val_1": '$["$window_id"]',
- "hogql_val_2": '$["$group_0"]',
- }
+ for key in ("$session_id", "$window_id", "$group_0"):
+ assert f'json_extract_scalar("tenant"."posthog"."events"."properties", \'$["{key}"]\')' in sql
+ assert context.values == {}
def test_lowers_event_element_materializations_to_the_physical_chain() -> None:
@@ -943,6 +962,35 @@ def test_uuid_comparison_on_exported_table_compares_as_varchar() -> None:
) in sql
+ "key, expected_path",
+ [
+ ("plan", "'$[\"plan\"]'"),
+ ("it's", "'$[\"it''s\"]'"),
+ ("%(hogql_val_0)s", "'$[\"%(hogql_val_0)s\"]'"),
+ ('a"b\\c', '\'$["a\\"b\\\\c"]\''),
+ ],
+)
+def test_grouped_json_property_prints_the_same_path_in_projection_and_group_by(key: str, expected_path: str) -> None:
+ context = _context_with_trino_table()
+ escaped_key = key.replace("\\", "\\\\").replace("'", "\\'")
+
+ sql, _ = prepare_and_print_ast(
+ parse_select(
+ f"SELECT JSONExtractString(properties, '{escaped_key}') = '' AS missing, count() FROM users "
+ f"GROUP BY JSONExtractString(properties, '{escaped_key}')"
+ ),
+ context,
+ "trino",
+ )
+ sql, values = convert_pyformat_placeholders(sql, context.values)
+
+ grouped = f'json_extract_scalar("users"."properties", {expected_path})'
+ assert sql.count(grouped) == 2
+ assert sql.split(" GROUP BY ")[1].count(grouped) == 1
+ assert values == [""]
+
+
@pytest.mark.parametrize(
"expression, group_by, order_by, expected_order, expected_values",
[
@@ -954,7 +1002,7 @@ def test_uuid_comparison_on_exported_table_compares_as_varchar() -> None:
"1 DESC",
["suffix"],
),
- ("properties.color", "account_id", "account_id", "1 ASC", ['$["color"]']),
+ ("properties.color", "account_id", "account_id", "1 ASC", []),
("0", "account_id", "account_id", "1 ASC", []),
("user_id", "account_id", "2", "2 ASC", []),
(
@@ -1176,8 +1224,8 @@ def test_prints_empty_for_lowered_json_property_after_second_resolution() -> Non
"trino",
)
- assert 'json_extract_scalar("users"."properties", %(hogql_val_0)s) <> \'\'' in sql
- assert context.values == {"hogql_val_0": '$["task_run_id"]'}
+ assert 'json_extract_scalar("users"."properties", \'$["task_run_id"]\') <> \'\'' in sql
+ assert context.values == {}
def test_lowers_nested_json_keys_and_values_raw() -> None:
@@ -1185,7 +1233,8 @@ def test_lowers_nested_json_keys_and_values_raw() -> None:
sql, _ = prepare_and_print_ast(parse_select("SELECT JSONExtractKeysAndValuesRaw('{}', 'teams')"), context, "trino")
assert "map_entries(CAST(json_extract(" in sql
- assert context.values == {"hogql_val_0": "{}", "hogql_val_1": '$["teams"]'}
+ assert context.values == {"hogql_val_0": "{}"}
+ assert "'$[\"teams\"]'" in sql
def test_lowers_currency_conversion_with_the_trino_exchange_rate_table() -> None:
@@ -1930,7 +1979,7 @@ def test_rejects_with_fill_before_printing_invalid_trino_sql() -> None:
("date_part('year', created_at)", 'EXTRACT(YEAR FROM "users"."created_at")'),
(
"JSONExtractKeysAndValues(properties, 'Float64')",
- 'map_entries(transform_values(CAST(json_extract("users"."properties", %(hogql_val_0)s) AS MAP(VARCHAR, JSON))',
+ 'map_entries(transform_values(CAST(json_extract("users"."properties", \'$\') AS MAP(VARCHAR, JSON))',
),
("['a', 'b'][2:]", "slice(ARRAY[%(hogql_val_0)s, %(hogql_val_1)s], 2, 2147483647)"),
],
@@ -2109,6 +2158,11 @@ def test_prints_additional_semantics_safe_trino_expressions(expression: str, exp
("arrayCumSum([1, -3, 2])", "ROW(total BIGINT, items ARRAY(BIGINT))"),
("arrayCumSumNonNegative([1, -3, 2])", "greatest(__hogql_scan_state[1] + __hogql_item, 0)"),
("arrayCumSum(value -> value / 2, [1, 2])", "ROW(total DOUBLE, items ARRAY(DOUBLE))"),
+ ("arraySum(value -> value * 2, [1, 2])", 'reduce(transform(ARRAY[1, 2], "value" -> ("value" * 2)), '),
+ ("arrayMax(value -> value * 2, [1, 2])", 'array_max(transform(ARRAY[1, 2], "value" -> ("value" * 2)))'),
+ ("arrayMin(value -> value * 2, [1, 2])", 'array_min(transform(ARRAY[1, 2], "value" -> ("value" * 2)))'),
+ ("arrayMax(value -> toString(value), [1, 2]) = '2'", "))) = %(hogql_val_0)s)"),
+ ("arrayMin(value -> toString(value), [1, 2]) = '2'", "))) = %(hogql_val_0)s)"),
("arrayResize(arrayCumSum(value -> value / 2, [1, 2]), 4)", "repeat(DOUBLE '0',"),
("arrayFill(value -> value > 0, [0, 1, 0])", "element_at(__hogql_filled, -1)"),
("arrayReverseFill(value -> value > 0, [0, 1, 0])", "reverse(reduce(reverse(zip("),
@@ -2653,7 +2707,15 @@ def test_lowers_multi_key_any_join_with_a_right_expression() -> None:
assert '"users"."user_id" = CAST("other"."user_id" AS VARCHAR)' in sql
-def test_lowers_unaliased_left_any_join() -> None:
+ "people_column, error",
+ [
+ ("people.created_at", None),
+ # Property reads through a derived table are not lowered yet, but the hidden column must still resolve.
+ ("people.raw.key", "TRINO_PROPERTY_NOT_LOWERED"),
+ ],
+)
+def test_lowers_unaliased_left_any_join(people_column: str, error: str | None) -> None:
context = _context_with_trino_table()
assert context.database is not None
context.database.tables.add_child(
@@ -2664,6 +2726,8 @@ def test_lowers_unaliased_left_any_join() -> None:
fields={
"user_id": StringDatabaseField(name="user_id", nullable=False),
"created_at": DateTimeDatabaseField(name="created_at", nullable=False),
+ "__sync_id": StringDatabaseField(name="_sync_id", hidden=True),
+ "raw": StringJSONDatabaseField(name="_raw", hidden=True),
},
external_data_source_id="source-id",
trino_catalog="ducklake",
@@ -2673,18 +2737,82 @@ def test_lowers_unaliased_left_any_join() -> None:
),
)
)
- sql, _ = prepare_and_print_ast(
- parse_select(
- "SELECT users.user_id, people.created_at FROM users LEFT ANY JOIN people ON users.user_id = people.user_id"
- ),
- context,
- "trino",
+ query = parse_select(
+ f"SELECT users.user_id, {people_column} FROM users LEFT ANY JOIN people ON users.user_id = people.user_id"
)
+ if error is not None:
+ with pytest.raises(TrinoLoweringError, match=error):
+ prepare_and_print_ast(query, context, "trino")
+ return
+ sql, _ = prepare_and_print_ast(query, context, "trino")
assert "LEFT ANY JOIN" not in sql
+ assert "_sync_id" not in sql
+ assert "_raw" not in sql
assert ') AS "people" ON ("users"."user_id" = "people"."user_id")' in sql
+ "structure, query, expected",
+ [
+ (
+ "`id` String, `tiers` Nullable(String)",
+ "SELECT tiers != '[]' FROM prices",
+ '("prices"."tiers" != %(hogql_val_0)s)',
+ ),
+ (
+ "`id` String, `tiers` Array(String)",
+ "SELECT tiers != '[]' FROM prices",
+ '(cardinality("prices"."tiers") != 0)',
+ ),
+ (
+ "`id` String, `tiers` Nullable(Array(String))",
+ "SELECT tiers != '[]' FROM prices",
+ '(cardinality("prices"."tiers") != 0)',
+ ),
+ (
+ "`id` String, `tiers` Nullable(String)",
+ "SELECT p.tiers != '[]' FROM (SELECT tiers FROM prices) AS p",
+ '("p"."tiers" != %(hogql_val_0)s)',
+ ),
+ (
+ "`id` String, `tiers` Nullable(String)",
+ "SELECT p.tiers != '[]' FROM prices LEFT ANY JOIN prices AS p ON prices.id = p.id",
+ '("p"."tiers" != %(hogql_val_0)s)',
+ ),
+ ],
+)
+def test_curated_array_field_over_a_text_column_compares_as_text(structure: str, query: str, expected: str) -> None:
+ database = Database(include_posthog_tables=False)
+ database.tables.add_child(
+ TableNode(
+ name="prices",
+ table=DataWarehouseTable(
+ name="prices",
+ url="http://example.com/prices",
+ format="Parquet",
+ structure=structure,
+ fields={
+ "id": StringDatabaseField(name="id"),
+ "tiers": StringArrayDatabaseField(name="tiers"),
+ },
+ ),
+ )
+ )
+ context = HogQLContext(
+ database=database,
+ modifiers=_trino_modifiers(),
+ enable_select_queries=True,
+ limit_top_select=False,
+ restricted_properties=set(),
+ trino_table_locators={"prices": ("ducklake", "stripe", "prices")},
+ )
+
+ sql, _ = prepare_and_print_ast(parse_select(query), context, "trino")
+
+ assert expected in sql
+
+
def test_lowers_any_join_to_the_deduplicated_trino_persons_relation() -> None:
context = HogQLContext(
database=Database(include_posthog_tables=True),
diff --git a/posthog/hogql/printer/trino.py b/posthog/hogql/printer/trino.py
index afc8d6c63e33..208deb71e08f 100644
--- a/posthog/hogql/printer/trino.py
+++ b/posthog/hogql/printer/trino.py
@@ -7,12 +7,13 @@ from typing import TYPE_CHECKING, ClassVar, NoReturn
from posthog.hogql import ast
from posthog.hogql.constants import HogQLDialect
from posthog.hogql.database.direct_trino_table import DirectTrinoTable
-from posthog.hogql.database.models import UUIDDatabaseField
+from posthog.hogql.database.models import DatabaseField, UUIDDatabaseField
+from posthog.hogql.database.s3_table import S3Table
from posthog.hogql.database.schema.numbers import NumbersTable
from posthog.hogql.database.trino_locator import resolve_trino_table_locator
from posthog.hogql.database.trino_unnest_table import TrinoUnnestTable
from posthog.hogql.errors import ImpossibleASTError
-from posthog.hogql.escape_sql import escape_trino_identifier
+from posthog.hogql.escape_sql import escape_trino_identifier, escape_trino_string
from posthog.hogql.functions import find_hogql_aggregation
from posthog.hogql.printer.postgres import PostgresPrinter
from posthog.hogql.printer.trino_functions import (
@@ -753,7 +754,7 @@ class TrinoPrinter(PostgresPrinter):
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 == "arraymax":
- return self._visit_unary_function(node, "array_max")
+ return f"array_max({self._visit_mapped_array_arg(node)})"
if name == "arrayenumerate":
value = self._visit_unary_arg(node)
return f"IF(cardinality({value}) = 0, CAST(ARRAY[] AS ARRAY(BIGINT)), sequence(1, cardinality({value})))"
@@ -1165,7 +1166,7 @@ class TrinoPrinter(PostgresPrinter):
if name == "arrayflatten":
return self._visit_unary_function(node, "flatten")
if name == "arraymin":
- return self._visit_unary_function(node, "array_min")
+ return f"array_min({self._visit_mapped_array_arg(node)})"
if name in {"arrayfirst", "arraylast"}:
return self._visit_array_first(node)
if name == "arraylastindex":
@@ -1183,7 +1184,7 @@ class TrinoPrinter(PostgresPrinter):
if name == "arrayconcat":
return self._visit_variadic_function(node, "concat", minimum=2)
if name == "arraysum":
- value = self._visit_unary_arg(node)
+ value = self._visit_mapped_array_arg(node)
return f"reduce({value}, CAST(0 AS DOUBLE), (s, x) -> s + coalesce(CAST(x AS DOUBLE), 0), s -> s)"
if name == "has":
return self._visit_binary_function(node, "contains")
@@ -1548,9 +1549,48 @@ class TrinoPrinter(PostgresPrinter):
return ast.ArrayType(item_type=ast.StringType())
resolved = value_type.resolve_constant_type(self.context) if value_type is not None else None
if isinstance(resolved, ast.StringArrayType):
+ if isinstance(value_type, ast.FieldType) and self._is_text_backed_warehouse_column(value_type):
+ return ast.StringType(nullable=True)
return ast.ArrayType(item_type=ast.StringType(), nullable=resolved.nullable)
return resolved
+ def _is_text_backed_warehouse_column(self, field_type: ast.FieldType) -> bool:
+ # Curated source schemas type some JSON text columns as arrays, but the synced column is text.
+ backing_type = self._backing_field_type(field_type)
+ if backing_type is None or not isinstance(backing_type.table_type, ast.BaseTableType):
+ return False
+ table = backing_type.table_type.resolve_database_table(self.context)
+ if not isinstance(table, S3Table) or not table.structure:
+ return False
+ field = backing_type.resolve_database_field(self.context)
+ if not isinstance(field, DatabaseField):
+ return False
+ match = re.search(rf"(?:^|,)\s*`{re.escape(field.name)}`\s+(\S+)", table.structure)
+ return match is not None and not match.group(1).removeprefix("Nullable(").startswith("Array(")
+
+ def _backing_field_type(self, field_type: ast.FieldType) -> ast.FieldType | None:
+ # Derived tables (explicit subqueries, CTEs, ANY JOIN dedupe wrappers) hide the stored column behind projections.
+ current: ast.Type | None = field_type
+ seen: set[int] = set()
+ while current is not None and id(current) not in seen:
+ seen.add(id(current))
+ if isinstance(current, ast.FieldAliasType):
+ current = current.type
+ continue
+ if not isinstance(current, ast.FieldType):
+ return None
+ table_type = current.table_type
+ if isinstance(table_type, ast.CTETableAliasType):
+ table_type = table_type.cte_table_type
+ if isinstance(table_type, (ast.CTETableType, ast.SelectQueryAliasType)):
+ select_type = table_type.select_query_type
+ current = (
+ select_type.columns.get(current.name) if isinstance(select_type, ast.SelectQueryType) else None
+ )
+ continue
+ return current
+ return None
+
def _unnest_column_type(self, table_type: ast.ColumnAliasedTableType, column: str) -> ast.ConstantType | None:
# UNNEST output columns are untyped in the schema; their type is the matching row field of the unnested array.
if not isinstance(table_type.table_type, ast.TableType) or not isinstance(
@@ -2351,7 +2391,11 @@ class TrinoPrinter(PostgresPrinter):
else:
escaped = str(member).replace("\\", "\\\\").replace('"', '\\"')
path += f'["{escaped}"]'
- return self.context.add_value(path)
+ if "\0" in path:
+ return self.context.add_value(path)
+ # Inlined, because Trino treats every bound `?` as distinct, so a grouped JSON property
+ # would never match the same property in the projection.
+ return escape_trino_string(path)
def _visit_lambda_array_call(self, node: ast.Call, target: str) -> str:
if (
@@ -2548,6 +2592,12 @@ class TrinoPrinter(PostgresPrinter):
def _visit_unary_function(self, node: ast.Call, target: str) -> str:
return f"{target}({self._visit_unary_arg(node)})"
+ def _visit_mapped_array_arg(self, node: ast.Call) -> str:
+ # ClickHouse's `f(lambda, arr)` form is `f(arrayMap(lambda, arr))`.
+ if len(node.args) == 2 and isinstance(node.args[0], ast.Lambda):
+ return self._visit_lambda_array_call(node, "transform")
+ return self._visit_unary_arg(node)
+
def _visit_unary_arg(self, node: ast.Call) -> str:
if len(node.args) != 1:
self._invalid_function_arguments(node, f"{node.name} expects exactly 1 argument in Trino mode.")
diff --git a/posthog/hogql/transforms/trino/any_join.py b/posthog/hogql/transforms/trino/any_join.py
index d822d0b63f61..6ece2fff136f 100644
--- a/posthog/hogql/transforms/trino/any_join.py
+++ b/posthog/hogql/transforms/trino/any_join.py
@@ -14,6 +14,18 @@ class TrinoAnyJoinLowerer(CloningVisitor):
super().__init__(clear_types=False)
self.join_index = 0
self.physical_names = physical_names
+ # Each entry is a query and its lazily collected references, so queries without hidden ANY JOIN
+ # columns are never scanned.
+ self._query_references: list[tuple[ast.SelectQuery, dict[str, set[str]] | None]] = []
+
+ def _referenced_names(self, alias: str) -> set[str]:
+ if not self._query_references:
+ return set()
+ query, references = self._query_references[-1]
+ if references is None:
+ references = _collect_table_references(query)
+ self._query_references[-1] = (query, references)
+ return references.get(alias, set())
def visit_select_query(self, node: ast.SelectQuery) -> ast.SelectQuery:
first = node.select_from
@@ -47,7 +59,11 @@ class TrinoAnyJoinLowerer(CloningVisitor):
second.constraint = None
second.next_join = first
node.select_from = second
- lowered = super().visit_select_query(node)
+ self._query_references.append((node, None))
+ try:
+ lowered = super().visit_select_query(node)
+ finally:
+ self._query_references.pop()
join = lowered.select_from
while join is not None:
if join.join_type in {"LEFT SEMI JOIN", "SEMI JOIN", "LEFT ANTI JOIN", "ANTI JOIN"}:
@@ -192,10 +208,12 @@ class TrinoAnyJoinLowerer(CloningVisitor):
lowered,
)
else:
+ # Hidden sync columns are not in the Trino copy of the table, and `*` never exposes them.
column_names = [
field.name if self.physical_names else name
for name, field in table_type.table.fields.items()
if isinstance(field, DatabaseField)
+ and (not field.hidden or name in key_names or name in self._referenced_names(lowered.alias))
]
if not column_names:
raise TrinoLoweringError("TRINO_ANY_JOIN_EMPTY_TABLE_UNSUPPORTED", f"{join_type} without columns", lowered)
@@ -350,5 +368,29 @@ class TrinoAnyJoinLowerer(CloningVisitor):
return None
+def _collect_table_references(query: ast.SelectQuery) -> dict[str, set[str]]:
+ references: dict[str, set[str]] = {}
+
+ class Collector(TraversingVisitor):
+ def visit_field(self, node: ast.Field) -> None:
+ field_type = node.type
+ while isinstance(field_type, ast.FieldAliasType):
+ field_type = field_type.type
+ if isinstance(field_type, ast.PropertyType):
+ field_type = field_type.field_type
+ if not isinstance(field_type, ast.FieldType):
+ return
+ table_type = field_type.table_type
+ while isinstance(table_type, ast.ColumnAliasedTableType):
+ table_type = table_type.table_type
+ if isinstance(table_type, (ast.TableAliasType, ast.CTETableAliasType, ast.SelectQueryAliasType)):
+ references.setdefault(table_type.alias, set()).add(field_type.name)
+ elif isinstance(table_type, (ast.TableType, ast.LazyTableType)) and table_type.table.name:
+ references.setdefault(table_type.table.name, set()).add(field_type.name)
+
+ Collector().visit(query)
+ return references
+
+
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/test/test_type_inference.py b/posthog/hogql/transforms/trino/test/test_type_inference.py
index bc9691873e0d..f5f1671c4f57 100644
--- a/posthog/hogql/transforms/trino/test/test_type_inference.py
+++ b/posthog/hogql/transforms/trino/test/test_type_inference.py
@@ -20,6 +20,9 @@ from posthog.hogql.type_system import infer_function_return_type
ast.IntegerType(nullable=True),
),
("quantileExact", [ast.FloatType(nullable=False)], ast.FloatType(nullable=False)),
+ ("log10", [ast.IntegerType(nullable=True)], ast.FloatType(nullable=True)),
+ ("sqrt", [ast.FloatType(nullable=False)], ast.FloatType(nullable=False)),
+ ("ln", [ast.StringType(nullable=False)], ast.UnknownType(unanalyzable=True)),
(
"medianExactHighIf",
[ast.IntegerType(nullable=False), ast.BooleanType(nullable=True)],
diff --git a/posthog/hogql/type_system.py b/posthog/hogql/type_system.py
index 1a43816dbc03..a64e46887373 100644
--- a/posthog/hogql/type_system.py
+++ b/posthog/hogql/type_system.py
@@ -1089,11 +1089,41 @@ def infer_tuple_name_access_constant_type(tuple_type: ast.ConstantType, field_na
return dataclasses.replace(item_type, nullable=tuple_type.nullable or item_type.nullable)
+# ClickHouse returns Float64 from these for any numeric input.
+_FLOAT64_MATH_FUNCTIONS = frozenset(
+ {
+ "exp",
+ "log",
+ "ln",
+ "exp2",
+ "log2",
+ "exp10",
+ "log10",
+ "log1p",
+ "sqrt",
+ "cbrt",
+ "sin",
+ "cos",
+ "tan",
+ "asin",
+ "acos",
+ "atan",
+ }
+)
+
+
def _infer_trino_function_type(
normalized_name: str,
arg_types: list[ast.ConstantType],
args: Optional[list[ast.Expr]],
) -> ast.ConstantType | None:
+ if (
+ normalized_name in _FLOAT64_MATH_FUNCTIONS
+ and len(arg_types) == 1
+ and isinstance(arg_types[0], (ast.IntegerType, ast.FloatType, ast.DecimalType))
+ ):
+ return ast.FloatType(nullable=arg_types[0].nullable)
+
if normalized_name == "roundtoexp2" and arg_types and isinstance(arg_types[0], (ast.IntegerType, ast.FloatType)):
return dataclasses.replace(arg_types[0])
@@ -1493,6 +1523,11 @@ def _infer_generic_function_type(
if normalized_name in {"arraysum", "arrayavg", "arraymin", "arraymax"} and arg_types:
item_type = infer_array_access_constant_type(arg_types[-1])
+ if args and isinstance(args[0], ast.Lambda):
+ # `f(lambda, arr)` reduces `arrayMap(lambda, arr)`, so the lambda decides the element type.
+ lambda_type = _lambda_return_constant_type(args[0])
+ if lambda_type is not None and not isinstance(lambda_type, ast.UnknownType):
+ item_type = dataclasses.replace(lambda_type, nullable=item_type.nullable or lambda_type.nullable)
if normalized_name == "arrayavg":
return ast.FloatType(nullable=item_type.nullable)
return item_type