: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): match clickhouse type coercions in trino printing (#123149)
Jovan Sakovic439b56b4aaf7
diff --git a/posthog/hogql/printer/test/__snapshots__/test_trino_printer.ambr b/posthog/hogql/printer/test/__snapshots__/test_trino_printer.ambrindex 3f45da5fafc7..36d3065e00d1 100644--- a/posthog/hogql/printer/test/__snapshots__/test_trino_printer.ambr+++ b/posthog/hogql/printer/test/__snapshots__/test_trino_printer.ambr@@ -563,14 +563,14 @@# ---# 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", ("user_id" = CAST(1 AS VARCHAR)) AS "bucket", row_number() OVER (ORDER BY "user_id" ASC) AS "rn", ("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',+ '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", ("user_id" = CAST(1 AS VARCHAR)) AS "bucket", row_number() OVER (ORDER BY "user_id" ASC) AS "rn", ("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',+ '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.pyindex 3382df85d423..6b702f45af4d 100644--- a/posthog/hogql/printer/test/test_trino_printer.py+++ b/posthog/hogql/printer/test/test_trino_printer.py@@ -648,6 +648,40 @@ def test_regex_character_classes_keep_clickhouse_meaning(pattern: str, expected:("SELECT toDate(user_id) FROM users", "TRY", 'CAST("users"."user_id" AS DATE)'),# Fractional seconds just before midnight must not round up into the next day.("SELECT toDate(user_id) FROM users", "AS TIMESTAMP(12)", "AS TIMESTAMP)"),+ (+ "SELECT parseDateTimeBestEffort(user_id) FROM users",+ "'(Z|[+-][0-9]{2}:?[0-9]{2})$'",+ "'(Z|[+-][0-9]{2}:[0-9]{2})$'",+ ),+ # A direct Trino table declares its physical types, so a native UUID column keeps pushdown.+ (+ "SELECT 1 FROM users WHERE uuid = toUUID(user_id)",+ '("users"."uuid" = CAST("users"."user_id" AS UUID))',+ "AS VARCHAR",+ ),+ ("SELECT id, NULL AS missing FROM users", 'CAST(NULL AS VARCHAR) AS "missing"', ' NULL AS "missing"'),+ (+ "SELECT NULL AS missing FROM users UNION ALL SELECT NULL AS missing FROM users",+ 'CAST(NULL AS VARCHAR) AS "missing"',+ ' NULL AS "missing"',+ ),+ (+ "SELECT toUnixTimestamp(created_at) + 1 AS created_at, fromUnixTimestamp(created_at) AS later FROM users",+ 'from_unixtime((CAST(to_unixtime("users"."created_at") AS BIGINT) + 1))',+ 'CAST("created_at" AS BIGINT)',+ ),+ (+ "SELECT toFloat(tupleElement(kv, 2)) FROM users ARRAY JOIN JSONExtractKeysAndValuesRaw(user_id) AS kv",+ 'TRY_CAST(("__trino_unnest_0"."kv")[2] AS DOUBLE)',+ 'CAST(("__trino_unnest_0"."kv")[2] AS DOUBLE)',+ ),+ # ClickHouse returns NULL for a fractional float but truncates a decimal.+ (+ "SELECT toInt(id / 3) FROM users",+ "= truncate(TRY_CAST(__hogql_accurate_cast_value AS DECIMAL(38, 18)))",+ "TRY_CAST(truncate(",+ ),+ ("SELECT toInt(toDecimal(id, 2)) FROM users", "TRY_CAST(truncate(CAST(", "__hogql_accurate_cast_value"),],)def test_lowers_clickhouse_semantics_trino_rejects(query: str, required: str, forbidden: str) -> None:@@ -893,6 +927,22 @@ def test_lowers_event_element_materializations_to_the_physical_chain() -> None:assert 'array_distinct(regexp_extract_all("tenant"."posthog"."events"."elements_chain"' in sql+def test_uuid_comparison_on_exported_table_compares_as_varchar() -> None:+ context = HogQLContext(+ database=Database(include_posthog_tables=True),+ modifiers=_trino_modifiers(),+ enable_select_queries=True,+ trino_table_locators={"events": ("tenant", "posthog", "events")},+ )++ sql, _ = prepare_and_print_ast(parse_select("SELECT 1 FROM events WHERE uuid = toUUID(event)"), context, "trino")++ assert (+ '(CAST("tenant"."posthog"."events"."uuid" AS VARCHAR) = '+ 'CAST(CAST("tenant"."posthog"."events"."event" AS UUID) AS VARCHAR))'+ ) in sql++@pytest.mark.parametrize("expression, group_by, order_by, expected_order, expected_values",[@@ -2713,6 +2763,12 @@ def test_removes_noop_sample_one_for_trino() -> None:"SELECT * FROM users UNPIVOT((value1, value2) FOR (key1, key2) IN ((user_id, id)))","TRINO_UNPIVOT_SHAPE_UNSUPPORTED",),+ # Inside a lambda, a qualifier that is also a column name would read that column instead of the table.+ ("SELECT arrayMap(x -> x + id, [1]) AS id FROM users AS properties", "TRINO_LAMBDA_QUALIFIER_AMBIGUOUS"),+ (+ "SELECT arrayMap(x -> concat(x, user_id), ['a']) AS user_id FROM users AS id",+ "TRINO_LAMBDA_QUALIFIER_AMBIGUOUS",+ ),],)def test_rejects_clickhouse_query_clauses_without_safe_trino_semantics(query: str, feature_code: str) -> None:diff --git a/posthog/hogql/printer/trino.py b/posthog/hogql/printer/trino.pyindex 069e850a695c..cd0fd7c30d01 100644--- a/posthog/hogql/printer/trino.py+++ b/posthog/hogql/printer/trino.py@@ -6,6 +6,8 @@ from typing import TYPE_CHECKING, ClassVar, NoReturnfrom posthog.hogql import astfrom posthog.hogql.constants import HogQLDialect+from posthog.hogql.database.direct_trino_table import DirectTrinoTable+from posthog.hogql.database.models import UUIDDatabaseFieldfrom posthog.hogql.database.schema.numbers import NumbersTablefrom posthog.hogql.database.trino_locator import resolve_trino_table_locatorfrom posthog.hogql.database.trino_unnest_table import TrinoUnnestTable@@ -198,6 +200,12 @@ _TRINO_REGEX_PATTERN_ARGUMENTS = {_POSIX_CLASS_PATTERN = re.compile(r"\[:\^?[a-z]+:\]")+def _is_null_constant(expr: ast.Expr) -> bool:+ if isinstance(expr, ast.Alias):+ return _is_null_constant(expr.expr)+ return isinstance(expr, ast.Constant) and expr.value is None++def _escape_regex_class_brackets(pattern: str) -> str:"""Keep RE2 bracket-expression meaning under Trino's Joni engine.@@ -382,10 +390,25 @@ class TrinoPrinter(PostgresPrinter):def _invalid_function_arguments(self, node: ast.Call, detail: str) -> NoReturn:self._unsupported("TRINO_FUNCTION_ARGUMENTS_UNSUPPORTED", detail, node)+ def _print_select_columns(self, columns: Iterable[ast.Expr]) -> list[str]:+ # A bare NULL output column has no Trino type, so CREATE TABLE AS rejects it.+ if len(self.stack) != 1:+ return super()._print_select_columns(columns)+ printed: list[str] = []+ for column in columns:+ if not _is_null_constant(column):+ printed.extend(super()._print_select_columns([column]))+ elif isinstance(column, ast.Alias) and not column.hidden:+ printed.append(f"CAST(NULL AS VARCHAR) AS {self._print_identifier(column.alias)}")+ else:+ printed.append("CAST(NULL AS VARCHAR)")+ return printed+def _align_set_query_types(self, node: ast.SelectSetQuery) -> ast.SelectSetQuery:branches = self._set_query_branches(node)if not branches:return node+ is_top_level = len(self.stack) == 1width = min(len(branch.select) for branch in branches)targets: dict[int, str] = {}for index in range(width):@@ -394,7 +417,9 @@ class TrinoPrinter(PostgresPrinter):for branch in branches]types = [self._resolve_type(expression) for expression in expressions]- if any(isinstance(value_type, ast.StringType) for value_type in types) and any(+ if is_top_level and all(_is_null_constant(expression) for expression in expressions):+ targets[index] = "varchar"+ elif any(isinstance(value_type, ast.StringType) for value_type in types) and any(isinstance(value_type,(ast.IntegerType, ast.FloatType, ast.DecimalType, ast.BooleanType, ast.UUIDType),@@ -947,6 +972,14 @@ class TrinoPrinter(PostgresPrinter):return f"CASE WHEN {self.visit(arg)} THEN 1 ELSE 0 END"if name == "toint" and isinstance(arg_type, ast.StringType):return f"TRY_CAST({self.visit(arg)} AS BIGINT)"+ # HogQL toInt is accurateCastOrNull, which maps a fractional, NaN or out-of-range float to NULL+ # but truncates a decimal. A Trino CAST rounds and raises instead.+ if name == "toint" and isinstance(arg_type, ast.FloatType):+ return self._visit_accurate_cast(+ ast.Call(name="accurateCastOrNull", args=[arg, ast.Constant(value="Int64")]), nullable=True+ )+ if name == "toint" and isinstance(arg_type, ast.DecimalType):+ return f"TRY_CAST(truncate({self.visit(arg)}) AS BIGINT)"if name in {"tofloat", "tofloatorzero", "tofloatordefault"} and node.args:arg = node.args[0]arg_type = self._resolve_type(arg)@@ -955,7 +988,7 @@ class TrinoPrinter(PostgresPrinter):if isinstance(arg_type, ast.DateTimeType):return f"to_unixtime({self.visit(arg)})"# HogQL defines toFloat as accurateCastOrNull, so unparsable input becomes NULL instead of an error.- if name == "tofloat" and len(node.args) == 1 and isinstance(arg_type, ast.StringType):+ if name == "tofloat" and len(node.args) == 1 and isinstance(arg_type, (ast.StringType, ast.UnknownType)):return f"TRY_CAST({self.visit(arg)} AS DOUBLE)"if (name == "todate"@@ -1341,7 +1374,12 @@ class TrinoPrinter(PostgresPrinter):left_cast: str | None = Noneright_cast: str | None = None- if isinstance(left_type, ast.UUIDType) and isinstance(right_type, ast.StringType):+ if isinstance(left_type, ast.UUIDType) and isinstance(right_type, ast.UUIDType):+ # Exported tables can store UUID columns as VARCHAR, while toUUID() yields a real UUID.+ # Keep native types when both sides are known UUIDs, so the connector can still push the predicate down.+ if not (self._is_native_uuid(node.left) and self._is_native_uuid(node.right)):+ left_cast = right_cast = "VARCHAR"+ elif isinstance(left_type, ast.UUIDType) and isinstance(right_type, ast.StringType):left_cast = "VARCHAR"elif isinstance(right_type, ast.UUIDType) and isinstance(left_type, ast.StringType):right_cast = "VARCHAR"@@ -1537,6 +1575,21 @@ class TrinoPrinter(PostgresPrinter):expression = expression.exprreturn self._resolve_type(expression)+ def _is_native_uuid(self, node: ast.Expr) -> bool:+ while isinstance(node, ast.Alias):+ node = node.expr+ if isinstance(node, ast.Call):+ return node.name.lower() == "touuid"+ field_type = node.type+ while isinstance(field_type, ast.FieldAliasType):+ field_type = field_type.type+ if not isinstance(field_type, ast.FieldType) or not isinstance(field_type.table_type, ast.BaseTableType):+ return False+ # Only a direct Trino table declares its physical column types; other tables may store UUIDs as VARCHAR.+ return isinstance(field_type.table_type.resolve_database_table(self.context), DirectTrinoTable) and isinstance(+ field_type.resolve_database_field(self.context), UUIDDatabaseField+ )+def _is_dynamic_property(self, node: ast.Expr) -> bool:while isinstance(node, ast.Alias):node = node.expr@@ -2151,8 +2204,10 @@ class TrinoPrinter(PostgresPrinter):value = self.visit(node.args[0])timezone = self.visit(node.args[1]) if len(node.args) == 2 else self.context.add_value(self._get_timezone())day_month_year = self.context.add_value("%e-%b-%y")+ # ClickHouse accepts offsets without a colon (+0000); normalize them before Trino's ISO-8601 parser.+ iso_value = f"regexp_replace({value}, '([+-][0-9]{{2}})([0-9]{{2}})$', '$1:$2')"parsed = (- f"coalesce(IF(regexp_like({value}, '(Z|[+-][0-9]{{2}}:[0-9]{{2}})$'), TRY(from_iso8601_timestamp({value}))), "+ f"coalesce(IF(regexp_like({value}, '(Z|[+-][0-9]{{2}}:?[0-9]{{2}})$'), TRY(from_iso8601_timestamp({iso_value}))), "f"IF(regexp_like({value}, '^[0-9]{{9,10}}$'), from_unixtime(TRY_CAST({value} AS DOUBLE))), "f"with_timezone(TRY(date_parse({value}, {day_month_year})), {timezone}), "f"with_timezone(CAST({value} AS TIMESTAMP), {timezone}))"diff --git a/posthog/hogql/transforms/trino/normalize.py b/posthog/hogql/transforms/trino/normalize.pyindex b0ab6f125985..fa3e72b38d89 100644--- a/posthog/hogql/transforms/trino/normalize.py+++ b/posthog/hogql/transforms/trino/normalize.py@@ -5,6 +5,8 @@ from posthog.hogql.context import HogQLContextfrom posthog.hogql.database.models import DatabaseFieldfrom posthog.hogql.database.schema.numbers import NumbersTablefrom posthog.hogql.database.trino_unnest_table import TRINO_UNNEST_TABLE_NAME+from posthog.hogql.errors import QueryError+from posthog.hogql.resolver_utils import lookup_field_by_namefrom posthog.hogql.transforms.trino.any_join import lower_trino_any_joinsfrom posthog.hogql.transforms.trino.asof_join import TrinoAsOfJoinLowererfrom posthog.hogql.transforms.trino.errors import TrinoLoweringError@@ -258,8 +260,10 @@ class TrinoScalarCTELowerer(CloningVisitor):class TrinoSelectAliasLowerer(CloningVisitor):- def __init__(self, budget: TrinoCompilationBudget) -> None:+ def __init__(self, context: HogQLContext, budget: TrinoCompilationBudget) -> None:super().__init__(clear_types=False)+ self.context = context+ self.lambda_scopes: list[ast.SelectQueryType | None] = []self.aliases: dict[str, ast.Expr] = {}self.alias_positions: dict[str, int] = {}self.expanding: set[str] = set()@@ -322,7 +326,14 @@ class TrinoSelectAliasLowerer(CloningVisitor):def visit_alias(self, node: ast.Alias) -> ast.Alias:if node.hidden:self.expansion_budget.visit(node)- return clone_expr(node, clear_types=False)+ cloned = clone_expr(node, clear_types=False)+ inner = cloned+ while isinstance(inner.expr, ast.Alias) and inner.expr.hidden:+ inner = inner.expr+ qualified = self._qualified_shadowed_column(inner.expr)+ if qualified is not None:+ inner.expr = qualified+ return clonedalready_expanding = node.alias in self.expandingself.expanding.add(node.alias)try:@@ -331,6 +342,13 @@ class TrinoSelectAliasLowerer(CloningVisitor):if not already_expanding:self.expanding.remove(node.alias)+ def visit_lambda(self, node: ast.Lambda) -> ast.Lambda:+ self.lambda_scopes.append(node.type if isinstance(node.type, ast.SelectQueryType) else None)+ try:+ return super().visit_lambda(node)+ finally:+ self.lambda_scopes.pop()+def visit_join_expr(self, node: ast.JoinExpr) -> ast.JoinExpr:outer_aliases = self.aliasesnext_join = node.next_join@@ -364,8 +382,54 @@ class TrinoSelectAliasLowerer(CloningVisitor):return self.visit(self.aliases[alias])finally:self.expanding.remove(alias)+ qualified = self._qualified_shadowed_column(node)+ if qualified is not None:+ return qualifiedreturn super().visit_field(node)+ def _qualified_shadowed_column(self, node: ast.Expr) -> ast.Field | None:+ # After alias inlining, a later resolver pass would bind a bare column named like a projection alias to the+ # alias. Qualifying it keeps the column the first pass chose.+ if not (+ isinstance(node, ast.Field)+ and len(node.chain) == 1+ and isinstance(node.chain[0], str)+ and node.chain[0] in self.aliases+ and isinstance(node.type, ast.FieldType)+ and isinstance(node.type.table_type, ast.TableAliasType)+ ):+ return None+ qualifier = node.type.table_type.alias+ if self.lambda_scopes and self._lambda_reads_qualifier_as_field(qualifier):+ raise TrinoLoweringError(+ "TRINO_LAMBDA_QUALIFIER_AMBIGUOUS",+ "a lambda reading a column shadowed by a projection alias",+ node,+ detail=(+ f"Inside a lambda, the table alias `{qualifier}` also names a column or alias, "+ "so the Trino query could read the wrong value. Rename the table alias."+ ),+ )+ return ast.Field(+ start=node.start,+ end=node.end,+ chain=[qualifier, node.chain[0]],+ type=node.type,+ from_asterisk=node.from_asterisk,+ )++ def _lambda_reads_qualifier_as_field(self, qualifier: str) -> bool:+ # Inside a lambda the resolver looks up the head of a chain as a field before it tries table aliases, so the+ # second pass would bind `qualifier.column` to a field named like the qualifier. Without a lambda scope to+ # check, assume a collision.+ scope = self.lambda_scopes[-1]+ if scope is None:+ return True+ try:+ return lookup_field_by_name(scope, qualifier, self.context) is not None+ except QueryError:+ return True+class TrinoPhysicalProjectionAliasLowerer(CloningVisitor):def __init__(self, context: HogQLContext) -> None:@@ -607,7 +671,7 @@ def normalize_trino_ast(node: ast.AST, context: HogQLContext, *, physical_names:lowered = TrinoAsOfJoinLowerer().visit(lowered)lowered = lower_trino_any_joins(lowered, physical_names=physical_names)lowered = lower_trino_query_wrappers(lowered)- lowered = TrinoSelectAliasLowerer(budget).visit(lowered)+ lowered = TrinoSelectAliasLowerer(context, budget).visit(lowered)lowered = TrinoPhysicalProjectionAliasLowerer(context).visit(lowered)TrinoNormalizer(context).visit(lowered)return lowered