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(data-warehouse): compile DuckLake queries with the DuckDB dialect (#66045)

Jovan Sakovice618fcf93fe2
diff --git a/posthog/ducklake/client.py b/posthog/ducklake/client.py
index 6006b2bf303b..2b9556c89cdd 100644
--- a/posthog/ducklake/client.py
+++ b/posthog/ducklake/client.py
@@ -73,7 +73,7 @@ def _set_search_path(conn: psycopg.Connection[Any], extra_schemas: list[str] | N
def compile_hogql_to_ducklake_sql(
team_id: int, query: HogQLQuery, *, team: Team | None = None
) -> tuple[str, dict[str, object], str]:
- """Compile a HogQLQuery to Postgres-dialect SQL for DuckLake.
+ """Compile a HogQLQuery to DuckDB-dialect SQL for DuckLake.
Returns ``(postgres_sql, values, hogql_pretty)``. The ``values`` dict holds
parameter bindings for ``psycopg``'s ``%(name)s`` placeholders embedded in
@@ -91,10 +91,10 @@ def compile_hogql_to_ducklake_sql(
if query.variables:
team = team or Team.objects.get(pk=team_id)
parsed = replace_variables(parsed, list(query.variables.values()), team)
- # Separate context for the Postgres print — the HogQL round-trip below shouldn't
+ # Separate context for the DuckDB print — the HogQL round-trip below shouldn't
# contribute to ``postgres_context.values``.
postgres_context = HogQLContext(team_id=team_id, enable_select_queries=True)
- postgres_sql, _ = prepare_and_print_ast(parsed, postgres_context, dialect="postgres")
+ postgres_sql, _ = prepare_and_print_ast(parsed, postgres_context, dialect="duckdb")
hogql_context = HogQLContext(team_id=team_id, enable_select_queries=True)
hogql_pretty, _ = prepare_and_print_ast(parsed, hogql_context, dialect="hogql")
@@ -113,7 +113,7 @@ def execute_ducklake_query(
"""Execute a query against a team's duckgres server.
Accepts either raw SQL or a HogQLQuery (which gets compiled to
- Postgres-dialect SQL). Exactly one of `sql` or `query` must be provided.
+ DuckDB-dialect SQL). Exactly one of `sql` or `query` must be provided.
Pass organization_id to skip the Team→Organization lookup when org
context is already available from the caller. Pass team to skip the
diff --git a/posthog/hogql/printer/duckdb.py b/posthog/hogql/printer/duckdb.py
index cb2d4da9693d..a74ffdefaa9e 100644
--- a/posthog/hogql/printer/duckdb.py
+++ b/posthog/hogql/printer/duckdb.py
@@ -58,3 +58,21 @@ class DuckDBPrinter(PostgresPrinter):
# DuckDB supports the ``LIMIT N WITH TIES`` shape this printer emits via the
# inherited limit-clause rendering. Override to allow what Postgres rejects.
return
+
+ def _json_property_args(self, chain) -> list[str]:
+ # DuckDB reads a JSON key beginning with `$` as a JSONPath root marker, so PostHog's
+ # `$`-prefixed property keys break the inherited Postgres `->>` arrow form. Bind the whole
+ # chain as one quoted JSONPath member expression (`$."k1"."k2"`) instead, forcing plain-key
+ # semantics for every key. The path is a bound value (not inlined), so this is not an
+ # injection vector; the escaping only keeps the JSONPath itself well-formed.
+ def member(key) -> str:
+ escaped = str(key).replace("\\", "\\\\").replace('"', '\\"')
+ return f'."{escaped}"'
+
+ path = "$" + "".join(member(k) for k in chain)
+ return [self.context.add_value(path)]
+
+ def _unsafe_json_extract_trim_quotes(self, unsafe_field, unsafe_args):
+ if not unsafe_args:
+ return unsafe_field
+ return f"({unsafe_field}) ->> {unsafe_args[0]}"
diff --git a/posthog/hogql/printer/test/test_printer.py b/posthog/hogql/printer/test/test_printer.py
index 4e119594e79a..42f5a9abec24 100644
--- a/posthog/hogql/printer/test/test_printer.py
+++ b/posthog/hogql/printer/test/test_printer.py
@@ -6859,6 +6859,30 @@ class TestDuckDBPrinter(BaseTest):
with self.assertRaisesMessage(QueryError, 'is not permitted as it contains the "%" character'):
printer._print_identifier("bad%name")
+ def test_dollar_prefixed_property_renders_as_jsonpath_member(self):
+ # DuckDB's JSON arrow operator reads a key beginning with `$` as a JSONPath root marker, so the
+ # 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)
+ 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)
+ 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"'])
+
+ 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)
+ self._expr("properties['a\"b']", context=context)
+ self.assertEqual(list(context.values.values()), ['$."a\\"b"'])
+
class TestMySQLPrinter(BaseTest):
maxDiff = None