: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): translate common functions for DuckDB (#77879)
Eric Duong57de1084d7cc
diff --git a/posthog/hogql/printer/duckdb.py b/posthog/hogql/printer/duckdb.pyindex 4cb9d2f2f2a0..5a914cb5d7be 100644--- a/posthog/hogql/printer/duckdb.py+++ b/posthog/hogql/printer/duckdb.py@@ -1,11 +1,12 @@from collections.abc import Callablefrom typing import ClassVar+from posthog.hogql import astfrom posthog.hogql.ast import ASTfrom posthog.hogql.constants import HogQLDialect, HogQLGlobalSettingsfrom posthog.hogql.context import HogQLContextfrom posthog.hogql.escape_sql import escape_duckdb_identifier-from posthog.hogql.printer.duckdb_functions import DUCKDB_FUNCTION_RENAMES_LOWER+from posthog.hogql.printer.duckdb_functions import DUCKDB_FUNCTION_HANDLERS_LOWER, DUCKDB_FUNCTION_RENAMES_LOWERfrom posthog.hogql.printer.postgres import PostgresPrinter@@ -34,13 +35,17 @@ class DuckDBPrinter(PostgresPrinter):parent_renames = super()._get_function_renames()self._duckdb_function_renames: dict[str, str] = {**parent_renames, **DUCKDB_FUNCTION_RENAMES_LOWER}parent_handlers = super()._get_function_handlers()- self._duckdb_function_handlers: dict[str, Callable[[list[str]], str]] = {+ inherited_handlers = {# PG emulates these HogQL names via handler functions; DuckDB prefers the# native renames, so strip the parent handler entries whose names we remap.k: vfor k, v in parent_handlers.items()if k not in DUCKDB_FUNCTION_RENAMES_LOWER}+ self._duckdb_function_handlers: dict[str, Callable[[list[str]], str]] = {+ **inherited_handlers,+ **DUCKDB_FUNCTION_HANDLERS_LOWER,+ }self._jsonpath_placeholders: dict[str, str] = {}def _print_identifier(self, name: str) -> str:@@ -55,6 +60,13 @@ class DuckDBPrinter(PostgresPrinter):def _get_function_handlers(self) -> dict[str, Callable[[list[str]], str]]:return self._duckdb_function_handlers+ def visit_call(self, node: ast.Call) -> str:+ rendered = super().visit_call(node)+ return_type = node.type.return_type if isinstance(node.type, ast.CallType) else node.type+ if node.name.lower() in {"dateadd", "datetrunc", "date_trunc"} and isinstance(return_type, ast.DateType):+ return f"CAST({rendered} AS DATE)"+ return rendered+def _assert_with_ties_supported(self) -> None:# DuckDB supports the ``LIMIT N WITH TIES`` shape this printer emits via the# inherited limit-clause rendering. Override to allow what Postgres rejects.diff --git a/posthog/hogql/printer/duckdb_functions.py b/posthog/hogql/printer/duckdb_functions.pyindex 41dfa0fd1787..8f6a22c219e4 100644--- a/posthog/hogql/printer/duckdb_functions.py+++ b/posthog/hogql/printer/duckdb_functions.py@@ -1,11 +1,12 @@-"""DuckDB-specific function renames that override the Postgres defaults.+"""DuckDB-specific function mappings that override the Postgres defaults.-These mappings are merged on top of ``POSTGRES_FUNCTION_RENAMES_LOWER`` in-``DuckDBPrinter._get_function_renames``. DuckDB is Postgres-wire compatible but-ships a number of native functions that produce cleaner or faster output than-the Postgres equivalents we emit by default.+These mappings are merged on top of the Postgres mappings in ``DuckDBPrinter``.+DuckDB is Postgres-wire compatible but ships a number of native functions that+produce cleaner or faster output than the Postgres equivalents we emit by default."""+from collections.abc import Callable+# HogQL name → DuckDB target name. Overlays POSTGRES_FUNCTION_RENAMES.DUCKDB_FUNCTION_RENAMES: dict[str, str] = {# ClickHouse's ``any`` is "pick any row"; DuckDB has a native ``any_value`` aggregator.@@ -20,6 +21,73 @@ DUCKDB_FUNCTION_RENAMES: dict[str, str] = {# Postgres has a custom handler for endsWith that falls back to a ``RIGHT()`` comparison;# DuckDB ships ``ends_with`` natively."endsWith": "ends_with",+ "argMax": "arg_max",+ "argMin": "arg_min",+ "dateTrunc": "date_trunc",+ "tuple": "row",+ "range": "range",}DUCKDB_FUNCTION_RENAMES_LOWER: dict[str, str] = {k.lower(): v for k, v in DUCKDB_FUNCTION_RENAMES.items()}+++def _handle_arg_max_if(args: list[str]) -> str:+ return f"arg_max({args[0]}, {args[1]}) FILTER (WHERE {args[2]})"+++def _handle_arg_min_if(args: list[str]) -> str:+ return f"arg_min({args[0]}, {args[1]}) FILTER (WHERE {args[2]})"+++def _handle_date_add(args: list[str]) -> str:+ if len(args) == 2:+ return f"date_add({args[0]}, {args[1]})"++ interval = f"CAST((CAST({args[1]} AS VARCHAR) || ' ' || CAST({args[0]} AS VARCHAR)) AS INTERVAL)"+ return f"date_add({args[2]}, {interval})"+++def _handle_group_uniq_array(args: list[str]) -> str:+ return f"list(DISTINCT {args[0]})"+++def _handle_group_uniq_array_if(args: list[str]) -> str:+ return f"list(DISTINCT {args[0]}) FILTER (WHERE {args[1]})"+++def _handle_tuple_element(args: list[str]) -> str:+ return f"struct_extract({args[0]}, {args[1]})"+++def _handle_multiply(args: list[str]) -> str:+ return f"({args[0]} * {args[1]})"+++def _handle_not(args: list[str]) -> str:+ return f"(NOT {args[0]})"+++def _handle_like(args: list[str]) -> str:+ return f"({args[0]} LIKE {args[1]})"+++def _handle_current_timestamp(args: list[str]) -> str:+ return "CURRENT_TIMESTAMP"+++DUCKDB_FUNCTION_HANDLERS: dict[str, Callable[[list[str]], str]] = {+ "argMaxIf": _handle_arg_max_if,+ "argMinIf": _handle_arg_min_if,+ "dateAdd": _handle_date_add,+ "groupUniqArray": _handle_group_uniq_array,+ "groupUniqArrayIf": _handle_group_uniq_array_if,+ "tupleElement": _handle_tuple_element,+ "multiply": _handle_multiply,+ "not": _handle_not,+ "like": _handle_like,+ "current_timestamp": _handle_current_timestamp,+}++DUCKDB_FUNCTION_HANDLERS_LOWER: dict[str, Callable[[list[str]], str]] = {+ k.lower(): v for k, v in DUCKDB_FUNCTION_HANDLERS.items()+}diff --git a/posthog/hogql/printer/test/test_printer.py b/posthog/hogql/printer/test/test_printer.pyindex 9f05c5d6ce8e..9a7051c99ee7 100644--- a/posthog/hogql/printer/test/test_printer.py+++ b/posthog/hogql/printer/test/test_printer.py@@ -22,7 +22,7 @@ from unittest import mockfrom unittest.mock import patchfrom django.conf import settings-from django.test import override_settings+from django.test import SimpleTestCase, override_settingsfrom parameterized import parameterized@@ -7852,7 +7852,7 @@ class TestPostgresPrinter(BaseTest):)-class TestDuckDBPrinter(BaseTest):+class TestDuckDBPrinter(SimpleTestCase):"""DuckDB printer tests — focused on the DuckDB-specific overrides vs Postgres.The DuckDB dialect inherits most of its behavior from PostgresPrinter, so the@@ -7861,6 +7861,7 @@ class TestDuckDBPrinter(BaseTest):"""maxDiff = None+ team_id = 1def _expr(self,@@ -7870,7 +7871,10 @@ class TestDuckDBPrinter(BaseTest):backend: HogQLParserBackend = "cpp-json",) -> str:node = parse_expr(query, backend=backend) if isinstance(query, str) else query- context = context or HogQLContext(team_id=self.team.pk, enable_select_queries=True)+ context = context or HogQLContext(team_id=self.team_id, enable_select_queries=True)+ context.database = context.database or Database()+ if context.restricted_properties is None:+ context.restricted_properties = set()select_query = ast.SelectQuery(select=[node], select_from=ast.JoinExpr(table=ast.Field(chain=["events"])), settings=settings)@@ -7891,9 +7895,13 @@ class TestDuckDBPrinter(BaseTest):context: Optional[HogQLContext] = None,placeholders: Optional[dict[str, ast.Expr]] = None,) -> str:+ context = context or HogQLContext(team_id=self.team_id, enable_select_queries=True)+ context.database = context.database or Database()+ if context.restricted_properties is None:+ context.restricted_properties = set()return prepare_and_print_ast(parse_select(query, placeholders=placeholders, backend="cpp-json"),- context or HogQLContext(team_id=self.team.pk, enable_select_queries=True),+ context,"duckdb",)[0]@@ -7911,9 +7919,70 @@ class TestDuckDBPrinter(BaseTest):"endsWith(event, '_done')","ends_with(events.event, %(hogql_val_0)s)",),+ ("argMax_renames_to_arg_max", "argMax(event, timestamp)", "arg_max(events.event, events.timestamp)"),+ ("argMin_renames_to_arg_min", "argMin(event, timestamp)", "arg_min(events.event, events.timestamp)"),+ (+ "dateTrunc_renames_to_date_trunc",+ "dateTrunc('day', timestamp)",+ "date_trunc(%(hogql_val_0)s, events.timestamp)",+ ),+ ("tuple_renames_to_row", "tuple(event, 1)", "row(events.event, 1)"),+ ("range_is_allowed", "range(3)", "range(3)"),+ ]+ )+ def test_function_renames(self, _name: str, expr: str, expected: str) -> None:+ self.assertEqual(self._expr(expr), expected)++ @parameterized.expand(+ [+ (+ "argMaxIf_uses_filter",+ "argMaxIf(event, timestamp, event = 'x')",+ "arg_max(events.event, events.timestamp) FILTER (WHERE (events.event = %(hogql_val_0)s))",+ ),+ (+ "argMinIf_uses_filter",+ "argMinIf(event, timestamp, event = 'x')",+ "arg_min(events.event, events.timestamp) FILTER (WHERE (events.event = %(hogql_val_0)s))",+ ),+ (+ "dateAdd_builds_interval",+ "dateAdd('day', 2, timestamp)",+ "date_add(events.timestamp, CAST((CAST(2 AS VARCHAR) || ' ' || CAST(%(hogql_val_0)s AS VARCHAR)) AS INTERVAL))",+ ),+ (+ "dateAdd_accepts_interval",+ "dateAdd(timestamp, toIntervalDay(2))",+ "date_add(events.timestamp, (2 * INTERVAL '1 day'))",+ ),+ (+ "dateAdd_preserves_date_type",+ "dateAdd('day', 2, toDate('2026-08-04'))",+ "CAST(date_add(CAST(%(hogql_val_1)s AS DATE), CAST((CAST(2 AS VARCHAR) || ' ' || CAST(%(hogql_val_0)s AS VARCHAR)) AS INTERVAL)) AS DATE)",+ ),+ (+ "dateTrunc_preserves_date_type",+ "dateTrunc('month', toDate('2026-08-04'))",+ "CAST(date_trunc(%(hogql_val_0)s, CAST(%(hogql_val_1)s AS DATE)) AS DATE)",+ ),+ ("groupUniqArray_uses_distinct_list", "groupUniqArray(event)", "list(DISTINCT events.event)"),+ (+ "groupUniqArrayIf_uses_filter",+ "groupUniqArrayIf(event, event = 'x')",+ "list(DISTINCT events.event) FILTER (WHERE (events.event = %(hogql_val_0)s))",+ ),+ (+ "tupleElement_uses_struct_extract",+ "tupleElement(tuple(1, event), 2)",+ "struct_extract(row(1, events.event), 2)",+ ),+ ("multiply_uses_operator", "multiply(2, 3)", "(2 * 3)"),+ ("not_uses_operator", ast.Call(name="NOT", args=[ast.Constant(value=True)]), "(NOT true)"),+ ("like_uses_operator", "like(event, 'x%')", "(events.event LIKE %(hogql_val_0)s)"),+ ("current_timestamp_uses_keyword", "current_timestamp()", "CURRENT_TIMESTAMP"),])- def test_function_renames(self, _name: str, expr: str, expected: str):+ def test_function_handlers(self, _name: str, expr: str, expected: str) -> None:self.assertEqual(self._expr(expr), expected)def test_smoke_basic_select(self):@@ -7931,7 +8000,7 @@ class TestDuckDBPrinter(BaseTest):self.assertGreater(len(long_name), 63)from posthog.hogql.printer.duckdb import DuckDBPrinter- printer = DuckDBPrinter(context=HogQLContext(team_id=self.team.pk))+ printer = DuckDBPrinter(context=HogQLContext(team_id=self.team_id))# Simple alphanumeric identifier — returned verbatim without quoting.self.assertEqual(printer._print_identifier(long_name), long_name)@@ -7960,7 +8029,7 @@ class TestDuckDBPrinter(BaseTest):# DuckDB reserves these even though Postgres doesn't — an unquoted identifier would parse-error.from posthog.hogql.printer.duckdb import DuckDBPrinter- printer = DuckDBPrinter(context=HogQLContext(team_id=self.team.pk))+ printer = DuckDBPrinter(context=HogQLContext(team_id=self.team_id))self.assertEqual(printer._print_identifier(name), f'"{name}"')def test_percent_in_identifier_rejected_postgres_family(self):@@ -7968,7 +8037,7 @@ class TestDuckDBPrinter(BaseTest):from posthog.hogql.printer.duckdb import DuckDBPrinterfrom posthog.hogql.printer.postgres import PostgresPrinter- ctx = HogQLContext(team_id=self.team.pk)+ ctx = HogQLContext(team_id=self.team_id)for printer in (DuckDBPrinter(context=ctx), PostgresPrinter(context=ctx)):with self.assertRaisesMessage(QueryError, 'is not permitted as it contains the "%" character'):printer._print_identifier("bad%name")@@ -7978,14 +8047,14 @@ class TestDuckDBPrinter(BaseTest):# inherited Postgres form `(properties) ->> '$ai_session_id'` fails to bind on duckgres with# "JSON path error near 'ai_session_id'". Every PostHog built-in property is `$`-prefixed, so# DuckDB must emit the key as a quoted JSONPath member instead: `$."$ai_session_id"`.- context = HogQLContext(team_id=self.team.pk, enable_select_queries=True)+ context = HogQLContext(team_id=self.team_id, enable_select_queries=True)printed = self._expr("properties.$ai_session_id", context=context)self.assertEqual(printed, "(events.properties) ->> %(hogql_val_0)s")self.assertEqual(list(context.values.values()), ['$."$ai_session_id"'])def test_nested_property_renders_as_single_jsonpath_member(self):# A nested chain collapses into one JSONPath bound as a single value, not a chain of arrows.- context = HogQLContext(team_id=self.team.pk, enable_select_queries=True)+ context = HogQLContext(team_id=self.team_id, enable_select_queries=True)printed = self._expr("properties.a.b.$browser", context=context)self.assertEqual(printed, "(events.properties) ->> %(hogql_val_0)s")self.assertEqual(list(context.values.values()), ['$."a"."b"."$browser"'])@@ -7993,7 +8062,7 @@ class TestDuckDBPrinter(BaseTest):def test_json_property_key_with_quote_is_escaped_in_jsonpath(self):# A `"` in the key would terminate the quoted JSONPath member early, so it must be backslash# escaped. The whole path is still a bound value, so this is not a SQL-injection vector.- context = HogQLContext(team_id=self.team.pk, enable_select_queries=True)+ context = HogQLContext(team_id=self.team_id, enable_select_queries=True)self._expr("properties['a\"b']", context=context)self.assertEqual(list(context.values.values()), ['$."a\\"b"'])@@ -8002,7 +8071,7 @@ class TestDuckDBPrinter(BaseTest):# in the SELECT than in the GROUP BY — it can't prove the two parameterized expressions are# equal. Repeated identical reads must collapse to a single bound value so the printed# expressions match textually.- context = HogQLContext(team_id=self.team.pk, enable_select_queries=True)+ context = HogQLContext(team_id=self.team_id, enable_select_queries=True)printed = self._select("SELECT properties.$ai_session_id AS s, count() AS n FROM events GROUP BY properties.$ai_session_id",context=context,