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): bind temporal and UUID constants in non-ClickHouse dialects (#75990)

George Munyoro4a6494e06a7d
diff --git a/posthog/hogql/printer/postgres.py b/posthog/hogql/printer/postgres.py
index 5230b541e9af..c10202bd1e9a 100644
--- a/posthog/hogql/printer/postgres.py
+++ b/posthog/hogql/printer/postgres.py
@@ -1,7 +1,6 @@
import re
import hashlib
from collections.abc import Callable
-from datetime import date, datetime
from typing import ClassVar
from uuid import UUID
@@ -245,16 +244,21 @@ class PostgresPrinter(BasePrinter):
# through the HogQL string escape path would produce ClickHouse-style ``\'`` escape
# sequences that Postgres and DuckDB do not recognize (``standard_conforming_strings``
# defaults to ``on``), allowing statement-terminator SQL injection.
- if (
- node.value is None
- or isinstance(node.value, bool)
- or isinstance(node.value, (int, float, UUID, UUIDT, datetime, date))
- ):
+ if node.value is None or isinstance(node.value, (bool, int, float)):
value = self._print_escaped_string(node.value)
if "%" in value:
# ``%`` would be interpreted as the start of a parameter placeholder by psycopg.
raise QueryError(f"Invalid character '%' in constant: {value}")
return value
+ # Temporal and UUID values have to be bound for the same reason. ``SQLValueEscaper`` only
+ # models the `hogql` and `clickhouse` dialects, so the escape path renders them as
+ # `toDate(...)`, `toDateTime(...)`, and `toUUID(...)`, which do not exist in any engine
+ # below this printer. Binding lets each driver emit its own literal, and matches how the
+ # function translations already handle an explicit `toDate(...)` call.
+ if isinstance(node.value, (UUID, UUIDT)):
+ # Every dialect here models a UUID as a string (see the `toUUID` translations), and the
+ # MySQL and Snowflake drivers will not bind a UUID object.
+ return self.context.add_value(str(node.value))
return self.context.add_value(node.value)
def visit_lambda(self, node: ast.Lambda):
diff --git a/posthog/hogql/printer/test/test_printer.py b/posthog/hogql/printer/test/test_printer.py
index 5190f60c9268..c3572ae6e310 100644
--- a/posthog/hogql/printer/test/test_printer.py
+++ b/posthog/hogql/printer/test/test_printer.py
@@ -1,7 +1,8 @@
import json
from collections.abc import Mapping
-from datetime import datetime
+from datetime import UTC, date, datetime
from typing import Any, Literal, Optional, cast
+from uuid import UUID
import pytest
from posthog.test.base import (
@@ -8477,3 +8478,54 @@ class TestSnowflakePrinter(BaseTest):
def test_snowflake_pivot_rejects_inner_group_by(self):
with self.assertRaises(QueryError):
self._select("SELECT * FROM events PIVOT(count(timestamp) FOR event IN ('a') GROUP BY uuid)")
+
+
+class TestDialectConstantBinding(BaseTest):
+ # Every printer below PostgresPrinter used to escape constants through SQLValueEscaper, which
+ # only models the `hogql` and `clickhouse` dialects. Temporal and UUID values therefore came out
+ # as toDate(...)/toDateTime(...)/toUUID(...), none of which exist in Postgres, MySQL, Snowflake,
+ # Redshift, or DuckDB. Reachable in production from a {filters} date range on a direct-SQL
+ # source, where replace_filters injects a real datetime constant.
+ maxDiff = None
+
+ NON_CLICKHOUSE_DIALECTS: list[tuple[str, HogQLDialect]] = [
+ ("postgres", "postgres"),
+ ("mysql", "mysql"),
+ ("snowflake", "snowflake"),
+ ("redshift", "redshift"),
+ ("duckdb", "duckdb"),
+ ]
+
+ def _constant(self, value: Any, dialect: HogQLDialect) -> tuple[str, dict[str, Any]]:
+ context = HogQLContext(team_id=self.team.pk, enable_select_queries=True)
+ printed = print_prepared_ast(ast.Constant(value=value), context=context, dialect=dialect)
+ return printed, context.values
+
+ @parameterized.expand(NON_CLICKHOUSE_DIALECTS)
+ def test_temporal_and_uuid_constants_are_bound(self, _name: str, dialect: HogQLDialect):
+ cases: list[tuple[Any, Any]] = [
+ (date(2024, 1, 1), date(2024, 1, 1)),
+ (datetime(2024, 1, 1, 12, 0, tzinfo=UTC), datetime(2024, 1, 1, 12, 0, tzinfo=UTC)),
+ # UUIDs bind as strings: these engines model them as text, and the MySQL and Snowflake
+ # drivers will not bind a UUID object.
+ (UUID("019f8904-44e9-0000-4c77-dc6aed04b8ff"), "019f8904-44e9-0000-4c77-dc6aed04b8ff"),
+ ]
+ for value, expected_bound in cases:
+ printed, values = self._constant(value, dialect)
+ self.assertEqual(printed, "%(hogql_val_0)s", f"{dialect} inlined {type(value).__name__}")
+ self.assertEqual(list(values.values()), [expected_bound])
+
+ @parameterized.expand(NON_CLICKHOUSE_DIALECTS)
+ def test_simple_scalar_constants_stay_inline(self, _name: str, dialect: HogQLDialect):
+ # None/bool/int/float have no dialect-specific syntax, so they stay inlined and unbound.
+ # Guards against the fix over-reaching into values that were never broken.
+ for value, expected in [(None, "NULL"), (True, "true"), (42, "42"), (1.5, "1.5")]:
+ printed, values = self._constant(value, dialect)
+ self.assertEqual(printed, expected)
+ self.assertEqual(values, {})
+
+ def test_clickhouse_still_inlines_temporal_constants(self):
+ # ClickHouse is where toDate()/toDateTime64() are correct, so it must keep inlining them.
+ printed, values = self._constant(date(2024, 1, 1), "clickhouse")
+ self.assertEqual(printed, "toDate('2024-01-01')")
+ self.assertEqual(values, {})