: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
feat(data-warehouse): type warehouse UUID columns as UUID in HogQL (#72528)
Thomas Obermüller717e0f89bad6
diff --git a/posthog/hogql/resolver.py b/posthog/hogql/resolver.pyindex 20f703707792..54f25eea5f1d 100644--- a/posthog/hogql/resolver.py+++ b/posthog/hogql/resolver.py@@ -2301,9 +2301,13 @@ class Resolver(CloningVisitor):return nodedef _raise_on_invalid_uuid_literal(self, node: ast.CompareOperation) -> None:- """A malformed string literal compared against a UUID column (events.uuid, person ids)- would fail the whole query at execution time with ClickHouse's CANNOT_PARSE_UUID —- reject it here instead, naming the bad value."""+ """A malformed string literal compared against a UUID column (events.uuid, person ids,+ warehouse UUID columns) would fail the whole query at execution time with ClickHouse's+ CANNOT_PARSE_UUID — reject it here instead, naming the bad value. Only ClickHouse-bound+ queries are guarded: other target dialects (postgres, snowflake, ...) accept UUID text+ forms ClickHouse doesn't, so rejecting the canonical-form mismatch there would be wrong."""+ if self.dialect not in ("clickhouse", "hogql"):+ returnif node.op not in _UUID_GUARDED_COMPARE_OPS:returnfor uuid_side, literal_side in ((node.left, node.right), (node.right, node.left)):diff --git a/posthog/hogql/test/test_resolver.py b/posthog/hogql/test/test_resolver.pyindex 61f2c7109ed5..0bc453a22c47 100644--- a/posthog/hogql/test/test_resolver.py+++ b/posthog/hogql/test/test_resolver.py@@ -2117,3 +2117,9 @@ class TestResolver(BaseTest):def test_uuid_literal_comparison_allows(self, _name, query):expr = self._select(query)resolve_types(expr, self.context, dialect="clickhouse")++ def test_uuid_literal_guard_skipped_for_non_clickhouse_dialects(self):+ # other target dialects accept UUID text forms ClickHouse doesn't (braces, no dashes),+ # so the canonical-form guard must not reject their queries+ expr = self._select("SELECT event FROM events WHERE person_id = 'not-a-uuid'")+ resolve_types(expr, self.context, dialect="postgres")diff --git a/posthog/hogql_queries/insights/funnels/funnel_event_query.py b/posthog/hogql_queries/insights/funnels/funnel_event_query.pyindex 21cf893cc8c8..82b00274d8a0 100644--- a/posthog/hogql_queries/insights/funnels/funnel_event_query.py+++ b/posthog/hogql_queries/insights/funnels/funnel_event_query.py@@ -543,10 +543,11 @@ class FunnelEventQuery(DataWarehouseSchemaMixin):if isinstance(table_entity, FunnelsDataWarehouseNode):if field == "uuid":resolved_field = self.get_warehouse_field(table_entity.table_name, table_entity.id_field)- if isinstance(resolved_field, UUIDDatabaseField):+ # Only non-nullable UUID columns may skip the null guard below+ if isinstance(resolved_field, UUIDDatabaseField) and not resolved_field.is_nullable():return ast.Field(chain=[self.EVENT_TABLE_ALIAS, table_entity.id_field])else:- # Handle non-UUID fields:+ # Handle nullable or non-UUID fields:# 1. Throw if we're encountering a null value.# 2. Try to cast strings to UUID directly.# 3. As a last resort, create a UUID by hashing the value with a table prefix.diff --git a/posthog/hogql_queries/insights/funnels/test/test_funnel_event_query.py b/posthog/hogql_queries/insights/funnels/test/test_funnel_event_query.pyindex 755946c6bf4c..b0ca9f5b14ec 100644--- a/posthog/hogql_queries/insights/funnels/test/test_funnel_event_query.py+++ b/posthog/hogql_queries/insights/funnels/test/test_funnel_event_query.py@@ -93,9 +93,10 @@ class TestFunnelEventQuery(ClickhouseTestMixin, APIBaseTest):timestamp_field: str,extra_columns: dict[str, dict[str, str | bool]] | None = None,timestamp_column: dict[str, str | bool] | None = None,+ id_column: dict[str, str | bool] | None = None,) -> None:columns: dict[str, dict[str, str | bool]] = {- id_field: {"hogql": "StringDatabaseField", "clickhouse": "String", "valid": True},+ id_field: id_column or {"hogql": "StringDatabaseField", "clickhouse": "String", "valid": True},distinct_id_field: {"hogql": "StringDatabaseField", "clickhouse": "String", "valid": True},timestamp_field: timestamp_columnor {"hogql": "DateTimeDatabaseField", "clickhouse": "DateTime64(3, 'UTC')", "valid": True},@@ -364,6 +365,39 @@ class TestFunnelEventQuery(ClickhouseTestMixin, APIBaseTest):self.assertIn("argMin(some_id, e.ts) AS uuid", sql)self.assertIn("GROUP BY some_user_id", sql)+ @parameterized.expand(+ [+ ("nullable_uuid_keeps_null_guard", "Nullable(UUID)", True),+ ("non_nullable_uuid_skips_null_guard", "UUID", False),+ ]+ )+ def test_dwh_uuid_id_field_null_guard(self, _name: str, clickhouse_type: str, nullable: bool) -> None:+ self._create_data_warehouse_table(+ name="payments_uuid",+ id_field="uuid_id",+ distinct_id_field="user_id",+ timestamp_field="created_at",+ id_column={"hogql": "UUIDDatabaseField", "clickhouse": clickhouse_type, "valid": True},+ )+ dwh_node = FunnelsDataWarehouseNode(+ id="payments_uuid",+ table_name="payments_uuid",+ id_field="uuid_id",+ aggregation_target_field="user_id",+ timestamp_field="created_at",+ )+ query = FunnelsQuery(series=[dwh_node, dwh_node])+ context = FunnelQueryContext(query=query, team=self.team)++ sql = raw_query(FunnelEventQuery(context=context, extra_event_fields_and_properties=["uuid"]).to_query())++ if nullable:+ # a null id must fail loudly instead of flowing into the funnel silently+ self.assertIn("throwIf(isNull(e.uuid_id)", sql)+ else:+ self.assertIn("e.uuid_id AS uuid", sql)+ self.assertNotIn("throwIf", sql)+@freeze_time("2025-11-12")def test_dwh_first_time_for_user_two_different_tables(self):query = FunnelsQuery(diff --git a/products/data_modeling/backend/models/datawarehouse_saved_query.py b/products/data_modeling/backend/models/datawarehouse_saved_query.pyindex 3a6488e56be8..6fc0306ed69f 100644--- a/products/data_modeling/backend/models/datawarehouse_saved_query.py+++ b/products/data_modeling/backend/models/datawarehouse_saved_query.py@@ -31,6 +31,7 @@ from posthog.sync import database_sync_to_asyncfrom products.warehouse_sources.backend.facade.hogql import (CLICKHOUSE_HOGQL_MAPPING,+ LEGACY_CLICKHOUSE_HOGQL_MAPPING,STR_TO_HOGQL_MAPPING,clean_type,reconstruct_ordered_columns,@@ -447,7 +448,7 @@ class DataWarehouseSavedQuery(CreatedMetaFields, UUIDTModel, UpdatedMetaFields,# Support for 'old' style columnsif isinstance(type, str):hogql_type_str = clickhouse_type.partition("(")[0]- fields[column] = CLICKHOUSE_HOGQL_MAPPING[hogql_type_str](name=column)+ fields[column] = LEGACY_CLICKHOUSE_HOGQL_MAPPING[hogql_type_str](name=column)elif isinstance(type, dict):fields[column] = STR_TO_HOGQL_MAPPING[type["hogql"]](name=column)else:diff --git a/products/warehouse_sources/backend/facade/hogql.py b/products/warehouse_sources/backend/facade/hogql.pyindex 306d413b6729..061e1ab72dea 100644--- a/products/warehouse_sources/backend/facade/hogql.py+++ b/products/warehouse_sources/backend/facade/hogql.py@@ -29,6 +29,7 @@ from products.warehouse_sources.backend.models.table import (# rather than the contract-returning facade/api.py.from products.warehouse_sources.backend.models.util import (CLICKHOUSE_HOGQL_MAPPING,+ LEGACY_CLICKHOUSE_HOGQL_MAPPING,STR_TO_HOGQL_MAPPING,clean_type,get_view_or_table_by_name,@@ -38,6 +39,7 @@ from products.warehouse_sources.backend.models.util import (__all__ = ["CLICKHOUSE_HOGQL_MAPPING",+ "LEGACY_CLICKHOUSE_HOGQL_MAPPING","SERIALIZED_FIELD_TO_CLICKHOUSE_MAPPING","STR_TO_HOGQL_MAPPING","DataWarehouseCredential",diff --git a/products/warehouse_sources/backend/models/table.py b/products/warehouse_sources/backend/models/table.pyindex 443395e85296..039cea9c4a73 100644--- a/products/warehouse_sources/backend/models/table.py+++ b/products/warehouse_sources/backend/models/table.py@@ -40,6 +40,7 @@ from posthog.sync import database_sync_to_asyncfrom products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchemafrom products.warehouse_sources.backend.models.util import (CLICKHOUSE_HOGQL_MAPPING,+ LEGACY_CLICKHOUSE_HOGQL_MAPPING,STR_TO_HOGQL_MAPPING,clean_type,reconstruct_ordered_columns,@@ -197,7 +198,7 @@ def get_hogql_field_for_column(# Support for 'old' style columnsif isinstance(column_definition, str):hogql_type_str = clickhouse_type.partition("(")[0]- return CLICKHOUSE_HOGQL_MAPPING[hogql_type_str](name=column_name, nullable=is_nullable)+ return LEGACY_CLICKHOUSE_HOGQL_MAPPING[hogql_type_str](name=column_name, nullable=is_nullable)return STR_TO_HOGQL_MAPPING.get(str(column_definition.get("hogql", "UnknownDatabaseField")),diff --git a/products/warehouse_sources/backend/models/util.py b/products/warehouse_sources/backend/models/util.pyindex faf5eb7f70d0..19e9cca52f8a 100644--- a/products/warehouse_sources/backend/models/util.py+++ b/products/warehouse_sources/backend/models/util.py@@ -18,6 +18,7 @@ from posthog.hogql.database.models import (StringJSONDatabaseField,StructDatabaseField,UnknownDatabaseField,+ UUIDDatabaseField,)if TYPE_CHECKING:@@ -181,7 +182,7 @@ def reconstruct_ordered_columns(CLICKHOUSE_HOGQL_MAPPING: dict[str, DatabaseFieldFactory] = {- "UUID": StringDatabaseField,+ "UUID": UUIDDatabaseField,"String": StringDatabaseField,"Nothing": UnknownDatabaseField,"DateTime64": DateTimeDatabaseField,@@ -210,6 +211,15 @@ CLICKHOUSE_HOGQL_MAPPING: dict[str, DatabaseFieldFactory] = {"Enum8": StringDatabaseField,}+# Old-style column metadata stores only the ClickHouse type string and resolves through a+# mapping on every query, so retyping UUID in CLICKHOUSE_HOGQL_MAPPING would flip every+# legacy column at once on deploy. Pin those to their historical String typing — UUID typing+# reaches a table only when a sync or materialization regenerates its column metadata.+LEGACY_CLICKHOUSE_HOGQL_MAPPING: dict[str, DatabaseFieldFactory] = {+ **CLICKHOUSE_HOGQL_MAPPING,+ "UUID": StringDatabaseField,+}+STR_TO_HOGQL_MAPPING: dict[str, DatabaseFieldFactory] = {"BooleanDatabaseField": BooleanDatabaseField,"DateDatabaseField": DateDatabaseField,@@ -220,6 +230,7 @@ STR_TO_HOGQL_MAPPING: dict[str, DatabaseFieldFactory] = {"StringArrayDatabaseField": StringArrayDatabaseField,"StringDatabaseField": StringDatabaseField,"StringJSONDatabaseField": StringJSONDatabaseField,+ "UUIDDatabaseField": UUIDDatabaseField,"StructDatabaseField": StructDatabaseField,"UnknownDatabaseField": UnknownDatabaseField,"boolean": BooleanDatabaseField,diff --git a/products/warehouse_sources/backend/tests/test_table.py b/products/warehouse_sources/backend/tests/test_table.pyindex bbe26cd819f2..0da80a283aa6 100644--- a/products/warehouse_sources/backend/tests/test_table.py+++ b/products/warehouse_sources/backend/tests/test_table.py@@ -1,14 +1,24 @@import subprocess+from typing import Anyimport pytestfrom posthog.test.base import BaseTestfrom unittest.mock import patch+from django.test import SimpleTestCase+from clickhouse_driver.errors import ServerException+from parameterized import parameterized++from posthog.hogql.database.models import DatabaseField, StringDatabaseField, UUIDDatabaseFieldfrom posthog.exceptions import ClickHouseAtCapacity-from products.warehouse_sources.backend.models.table import DataWarehouseTable, run_chdb_query+from products.warehouse_sources.backend.models.table import (+ DataWarehouseTable,+ get_hogql_field_for_column,+ run_chdb_query,+)class TestDataWarehouseTableColumnOrder(BaseTest):@@ -69,3 +79,26 @@ class TestRunChdbQuery:run_chdb_query("DESCRIBE TABLE s3('https://example.com/table/')")assert DataWarehouseTable()._is_suppressed_chdb_error(exc_info.value)+++class TestGetHogqlFieldForColumn(SimpleTestCase):+ @parameterized.expand(+ [+ # Old-style metadata is just the ClickHouse type string, resolved through a mapping+ # on every query — it must keep its historical String typing so a mapping change+ # cannot retype every legacy UUID column at once.+ ("old_style_pinned_to_string", "Nullable(UUID)", StringDatabaseField),+ (+ "new_style_stored_type",+ {"clickhouse": "Nullable(UUID)", "hogql": "UUIDDatabaseField"},+ UUIDDatabaseField,+ ),+ ]+ )+ def test_uuid_column_typing(+ self, _name: str, column_definition: dict[str, Any] | str, expected_type: type[DatabaseField]+ ) -> None:+ field = get_hogql_field_for_column("id", column_definition, "UUID", is_nullable=True)++ assert type(field) is expected_type+ assert field.is_nullable()