:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(hogql): correct trino expression rendering (#103188)
Eric Duong1642630acd26
diff --git a/docs/internal/hogql-trino-compiler.md b/docs/internal/hogql-trino-compiler.mdindex b7ef6ede82dd..50d976cbcf61 100644--- a/docs/internal/hogql-trino-compiler.md+++ b/docs/internal/hogql-trino-compiler.md@@ -96,6 +96,10 @@ The printer checks each rendered expression against a 1,000,000-character SQL li`arraySlice` and dynamic `range` bind their arguments once so nesting does not multiply their generated SQL.Scalar CTE substitution preserves resolved column bindings, including columns that share a CTE name.+Arithmetic operators render each operand once and reuse its SQL after applying Trino's type conversions.+This keeps long arithmetic chains from repeatedly registering unused bind parameters, including JSON extraction paths.+Integer conversions also render their input only in the selected conversion path, so nested casts do not retain discarded parameters.+`numbers()` uses Trino's scalar `sequence`, which supports at most 10,000 entries.Constant counts above this limit fail during compilation; dynamic counts are clamped to the range from zero to 10,000.@@ -196,6 +200,8 @@ expressions and numeric conditions in `if`/`multiIf` use native Trino conditionaAliases inside expressions are omitted from SQL; projection aliases are retained.String inputs to `toInt` use `TRY_CAST`, returning NULL for strings that do notrepresent an integer. Numeric aggregate-filter conditions are cast to BOOLEAN.+This includes conditional argument, array, and quantile aggregates and conditional window functions.+Window quantiles use a conditional NULL input because Trino does not support `FILTER` on window functions.Additional mappings cover common mathematical functions, array transforms,base64 strings, maps, URLs, date arithmetic, vector operations, and statistical@@ -260,6 +266,7 @@ Dynamic arrays receive an equal-length guard instead of Trino's NULL padding.The regex group functions support constant patterns with 1–20 capture groups.They support one-match, vertical, and horizontal result shapes.`regexpExtract` supports a constant pattern and an optional constant group index.+`extractAll` returns the first capture group when present and the entire match otherwise, for both constant and dynamic patterns.`replaceRegexpOne` supports constantpatterns and replacements, including numbered replacement captures. Lookarounds,inline flags, and pattern backreferences remain rejected for first-only replacement.diff --git a/posthog/hogql/printer/test/test_trino_printer.py b/posthog/hogql/printer/test/test_trino_printer.pyindex c4889a2e2938..72510540f3e2 100644--- a/posthog/hogql/printer/test/test_trino_printer.py+++ b/posthog/hogql/printer/test/test_trino_printer.py@@ -708,6 +708,94 @@ def test_preserves_clickhouse_json_array_indexing() -> None:assert context.values == {"hogql_val_0": '$["key.with.dot"]', "hogql_val_1": '$["items"]'}[email protected]("operator", ["+", "-", "*", "/", "%"])+def test_chained_arithmetic_keeps_only_used_parameters(operator: str) -> None:+ context = _context_with_trino_table()+ terms = [f"JSONExtractFloat(user_id, 'metric_{index}')" for index in range(6)]++ 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)}+ rendered_terms = [+ 'coalesce(TRY(CAST(json_extract_scalar("users"."user_id", '+ f"%(hogql_val_{index})s) AS DOUBLE)), CAST(0 AS DOUBLE))"+ for index in range(6)+ ]+ expected = rendered_terms[0]+ for term in rendered_terms[1:]:+ if operator == "/":+ expected = f"(CAST({expected} AS DOUBLE) / CAST({term} AS DOUBLE))"+ elif operator == "%":+ expected = f"MOD({expected}, {term})"+ else:+ expected = f"({expected} {operator} {term})"+ assert sql == f'SELECT {expected} FROM "ducklake"."analytics"."users" AS "users"'++[email protected]("function", ["toInt", "toIntOrDefault", "toIntOrZero", "_toUInt64"])+def test_nested_integer_conversions_keep_only_used_parameters(function: str) -> None:+ context = _context_with_trino_table()+ expression = "'7'"+ for _ in range(6):+ argument = f"toString({expression})" if function == "toIntOrZero" else expression+ expression = f"{function}({argument})"++ sql, _ = prepare_and_print_ast(parse_select(f"SELECT {expression}"), context, "trino")++ assert context.values == {"hogql_val_0": "7"}+ sql, values = convert_pyformat_placeholders(sql, context.values)+ with duckdb.connect(":memory:") as connection:+ assert connection.execute(sql, values).fetchone() == (7,)+++ "expression",+ [+ "argMaxIf(10, 20, 1)",+ "argMinIf(10, 20, 1)",+ "groupArrayIf(10, 1)",+ "groupUniqArrayIf(10, 1)",+ "quantileIf(0.5)(10, 1)",+ "quantileIf(0.5)(10, 1) OVER ()",+ "sumIf(10, 1) OVER ()",+ "countIf(1) OVER ()",+ ],+)+def test_conditional_aggregates_coerce_numeric_predicates(expression: str) -> None:+ sql, _ = prepare_and_print_ast(parse_select(f"SELECT {expression}"), _context_with_trino_table(), "trino")++ assert "CAST(1 AS BOOLEAN)" in sql+ if "OVER" in expression:+ assert "FILTER" not in sql+++ ("pattern", "expected"),+ [+ ("[0-9]+", ["12", "34"]),+ ("([a-z])([0-9]+)", ["a", "b"]),+ ("(?:[a-z])[0-9]+", ["a12", "b34"]),+ ],+)[email protected]("dynamic", [False, True])+def test_extract_all_uses_first_capture_or_entire_match(pattern: str, expected: list[str], dynamic: bool) -> None:+ context = _context_with_trino_table()+ query = (+ "SELECT extractAll('a12 b34', pattern) FROM (SELECT {pattern} AS pattern)"+ if dynamic+ else "SELECT extractAll('a12 b34', {pattern})"+ )+ sql, _ = prepare_and_print_ast(+ parse_select(query, placeholders={"pattern": ast.Constant(value=pattern)}),+ context,+ "trino",+ )++ sql, values = convert_pyformat_placeholders(sql, context.values)+ with duckdb.connect(":memory:") as connection:+ assert connection.execute(sql, values).fetchone() == (expected,)++def test_lowers_event_property_backed_fields_to_the_physical_json_column() -> None:context = HogQLContext(database=Database(include_posthog_tables=True),diff --git a/posthog/hogql/printer/trino.py b/posthog/hogql/printer/trino.pyindex 197f6702d613..bb57323f6bd6 100644--- a/posthog/hogql/printer/trino.py+++ b/posthog/hogql/printer/trino.py@@ -9,6 +9,7 @@ from posthog.hogql.constants import HogQLDialectfrom 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+from posthog.hogql.errors import ImpossibleASTErrorfrom posthog.hogql.escape_sql import escape_trino_identifierfrom posthog.hogql.functions import find_hogql_aggregationfrom posthog.hogql.printer.postgres import PostgresPrinter@@ -777,15 +778,14 @@ class TrinoPrinter(PostgresPrinter):if name in {"toint", "tointorzero", "tointordefault", "_touint64"} and node.args:arg = node.args[0]arg_type = arg.type.resolve_constant_type(self.context) if arg.type is not None else None- rendered = self.visit(arg)if isinstance(arg_type, ast.DateType):- return f"date_diff('day', DATE '1970-01-01', {rendered})"+ return f"date_diff('day', DATE '1970-01-01', {self.visit(arg)})"if isinstance(arg_type, ast.DateTimeType):- return f"CAST(to_unixtime({rendered}) AS BIGINT)"+ return f"CAST(to_unixtime({self.visit(arg)}) AS BIGINT)"if isinstance(arg_type, ast.BooleanType):- return f"CASE WHEN {rendered} THEN 1 ELSE 0 END"+ 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({rendered} AS BIGINT)"+ return f"TRY_CAST({self.visit(arg)} AS BIGINT)"if name in {"tofloat", "tofloatorzero", "tofloatordefault"} and node.args:arg = node.args[0]arg_type = self._resolve_type(arg)@@ -919,9 +919,15 @@ class TrinoPrinter(PostgresPrinter):if name == "arraydistinct":return self._visit_unary_function(node, "array_distinct")if name == "extractall":- if len(node.args) != 2:- self._invalid_function_arguments(node, "extractAll expects exactly 2 arguments in Trino mode.")- return f"regexp_extract_all({self.visit(node.args[0])}, {self.visit(node.args[1])}, 1)"+ binary_args = self._visit_binary_args(node)+ pattern = node.args[1]+ if isinstance(pattern, ast.Constant) and isinstance(pattern.value, str):+ group = self._first_regex_capture_group(pattern.value)+ return f"regexp_extract_all({binary_args.left}, {binary_args.right}, {group})"+ return (+ f"coalesce(TRY(regexp_extract_all({binary_args.left}, {binary_args.right}, 1)), "+ f"regexp_extract_all({binary_args.left}, {binary_args.right}, 0))"+ )if name == "arraysort":if len(node.args) == 2 and isinstance(node.args[0], ast.Lambda):return self._visit_array_sort_key(node)@@ -968,9 +974,11 @@ class TrinoPrinter(PostgresPrinter):if name in {"argmaxif", "argminif"}:if len(node.args) != 3:self._invalid_function_arguments(node, f"{node.name} expects exactly 3 arguments in Trino mode.")- rendered_args = [self.visit(arg) for arg in node.args]+ rendered_args = [self.visit(arg) for arg in node.args[:2]]target = "max_by" if name == "argmaxif" else "min_by"- return f"{target}({rendered_args[0]}, {rendered_args[1]}) FILTER (WHERE {rendered_args[2]})"+ return (+ f"{target}({rendered_args[0]}, {rendered_args[1]}) FILTER (WHERE {self._visit_predicate(node.args[2])})"+ )if name == "groupuniqarray":if len(node.args) != 1:self._invalid_function_arguments(node, "groupUniqArray expects exactly 1 argument in Trino mode.")@@ -978,11 +986,13 @@ class TrinoPrinter(PostgresPrinter):if name == "grouparrayif":if len(node.args) != 2:self._invalid_function_arguments(node, "groupArrayIf expects exactly 2 arguments in Trino mode.")- return f"array_agg({self.visit(node.args[0])}) FILTER (WHERE {self.visit(node.args[1])})"+ return f"array_agg({self.visit(node.args[0])}) FILTER (WHERE {self._visit_predicate(node.args[1])})"if name == "groupuniqarrayif":if len(node.args) != 2:self._invalid_function_arguments(node, "groupUniqArrayIf expects exactly 2 arguments in Trino mode.")- return f"array_agg(DISTINCT {self.visit(node.args[0])}) FILTER (WHERE {self.visit(node.args[1])})"+ return (+ f"array_agg(DISTINCT {self.visit(node.args[0])}) FILTER (WHERE {self._visit_predicate(node.args[1])})"+ )if name == "countdistinct":return self._visit_count_distinct(node)if name == "first_value":@@ -1253,9 +1263,12 @@ class TrinoPrinter(PostgresPrinter):ast.ArithmeticOperationOp.Mod: "%",}operator = operators.get(node.op)- if operator is not None and lowered:+ # Rendering operands again doubles work at each level and retains discarded bind values.+ if operator is not None:+ if node.op == ast.ArithmeticOperationOp.Mod and not lowered:+ return f"MOD({left}, {right})"return f"({left} {operator} {right})"- return super().visit_arithmetic_operation(node)+ raise ImpossibleASTError(f"Unknown ArithmeticOperationOp {node.op}")def _resolve_type(self, node: ast.Expr) -> ast.ConstantType | None:if isinstance(node, ast.Call) and node.name.lower() in TRINO_TUPLE_OPERATORS:@@ -3086,7 +3099,7 @@ class TrinoPrinter(PostgresPrinter):self._invalid_function_arguments(node, f"{node.name} expects one percentile parameter in Trino mode.")aggregate = f"approx_percentile({self.visit(node.args[0])}, {self.visit(node.params[0])})"if filtered:- aggregate += f" FILTER (WHERE {self.visit(node.args[1])})"+ aggregate += f" FILTER (WHERE {self._visit_predicate(node.args[1])})"return aggregatedef _visit_quantiles(self, node: ast.Call, *, over: str = "") -> str:@@ -3940,7 +3953,11 @@ class TrinoPrinter(PostgresPrinter):filtered=name.endswith("if"),over=f" OVER {over}",)- exprs = [self.visit(expr) for expr in node.exprs or []]+ conditional = name in _TRINO_CONDITIONAL_WINDOW_FUNCTIONS or name in {"uniqif", "uniqexactif"}+ exprs = [+ self._visit_predicate(expr) if conditional and index == len(node.exprs or []) - 1 else self.visit(expr)+ for index, expr in enumerate(node.exprs or [])+ ]if name in {"quantile", "quantileif"}:filtered = name.endswith("if")expected_args = 2 if filtered else 1@@ -3950,9 +3967,10 @@ class TrinoPrinter(PostgresPrinter):f"Window function '{node.name}' has unsupported arguments in Trino mode.",node,)- call = f"approx_percentile({self.visit(node.args[0])}, {self.visit(node.exprs[0])})"+ value = self.visit(node.args[0])if filtered:- call += f" FILTER (WHERE {self.visit(node.args[1])})"+ value = f"IF({self._visit_predicate(node.args[1])}, {value}, NULL)"+ call = f"approx_percentile({value}, {exprs[0]})"elif node.args:self._unsupported("TRINO_WINDOW_FUNCTION_PARAMETERS_UNSUPPORTED",@@ -3972,7 +3990,7 @@ class TrinoPrinter(PostgresPrinter):)value = values[0] if len(values) == 1 else f"ROW({', '.join(values)})"if filtered:- value = f"IF({self._visit_predicate((node.exprs or [])[-1])}, {value}, NULL)"+ value = f"IF({exprs[-1]}, {value}, NULL)"call = f"count(DISTINCT {value})"elif name in _TRINO_CONDITIONAL_WINDOW_FUNCTIONS:if not exprs: