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.

refactor(hogql): extract property-metadata bundle and loader from property swapper (#71960)

George Munyoro2474729a58e4
diff --git a/posthog/hogql/context.py b/posthog/hogql/context.py
index 12190bee3951..caadb74213c5 100644
--- a/posthog/hogql/context.py
+++ b/posthog/hogql/context.py
@@ -13,6 +13,7 @@ if TYPE_CHECKING:
from posthog.hogql.database.database import Database
from posthog.hogql.database.models import Table
from posthog.hogql.observability import HogQLTypeObservability
+ from posthog.hogql.property_metadata import PropertyMetadata
from posthog.hogql.transforms.property_types import PropertySwapper
from posthog.clickhouse.client.execute import ClickHouseExternalTable
@@ -116,6 +117,9 @@ class HogQLContext:
# Bounded source/surface label for type-system observability metrics.
observability_source: str = "unknown"
+ # Property-definition metadata for the properties this query touches, loaded from Postgres by
+ # load_property_metadata during property-type resolution (None until build_property_swapper runs).
+ property_metadata: Optional["PropertyMetadata"] = None
property_swapper: Optional["PropertySwapper"] = None
# Workload detected during AST resolution (set by prepare_ast_for_printing)
workload: Optional[Workload] = None
diff --git a/posthog/hogql/property_metadata.py b/posthog/hogql/property_metadata.py
new file mode 100644
index 000000000000..f9bb4ecea3fc
--- /dev/null
+++ b/posthog/hogql/property_metadata.py
@@ -0,0 +1,141 @@
+"""Property-definition metadata for HogQL property-type resolution.
+
+`PropertyMetadata` is the plain data bundle the engine consumes; `load_property_metadata` is its
+Django-side loader. The ORM reads stay behind the function call (the `Database.create_for`
+pattern), so this module imports without booting Django (no settings or app registry).
+"""
+
+from dataclasses import dataclass, field
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+ from posthog.hogql.context import HogQLContext
+
+
+@dataclass(frozen=True)
+class PropertyMetadata:
+ """Property-definition types for the properties a query touches.
+
+ Values are `{"type": <PropertyType value>}` dicts, plus a `"dmat"` key when a READY
+ materialized-column slot backs an event property. Group keys are `"{group_type_index}_{name}"`.
+ """
+
+ event_properties: dict[str, dict[str, str | None]] = field(default_factory=dict)
+ person_properties: dict[str, dict[str, str | None]] = field(default_factory=dict)
+ group_properties: dict[str, dict[str, str | None]] = field(default_factory=dict)
+
+
+def load_property_metadata(
+ context: "HogQLContext",
+ *,
+ event_property_names: set[str],
+ person_property_names: set[str],
+ group_property_names: dict[int, set[str]],
+) -> PropertyMetadata:
+ """Fetch property-definition types for the given property names from Postgres.
+
+ Sets `context.team` when only `team_id` was provided. Callers keep the result on
+ `context.property_metadata` so downstream transforms read it without touching the ORM.
+ """
+ # Deferred: this function is the Django boundary of property-type resolution — keeping the ORM
+ # imports behind the call is what lets the module (and its importers) load without django.setup().
+ from django.db import models # noqa: PLC0415
+ from django.db.models.functions.comparison import Coalesce # noqa: PLC0415
+
+ from posthog.clickhouse.materialized_columns import DMAT_STRING_COLUMN_NAME_PREFIX # noqa: PLC0415
+ from posthog.models import PropertyDefinition, Team # noqa: PLC0415
+ from posthog.models.materialized_column_slots import ( # noqa: PLC0415
+ MaterializedColumnSlot,
+ MaterializedColumnSlotState,
+ )
+
+ team_id = context.team_id
+ if team_id is None:
+ raise ValueError("load_property_metadata requires a context with team_id set")
+
+ if not context.team:
+ context.team = Team.objects.get(id=team_id)
+
+ # Load event property definitions with their materialized slots in a single query
+ event_property_definitions = (
+ PropertyDefinition.objects.alias(
+ effective_project_id=Coalesce("project_id", "team_id", output_field=models.BigIntegerField())
+ )
+ .filter(
+ effective_project_id=context.team.project_id,
+ name__in=event_property_names,
+ type__in=[None, PropertyDefinition.Type.EVENT],
+ )
+ .prefetch_related(
+ models.Prefetch(
+ "materialized_column_slots",
+ queryset=MaterializedColumnSlot.objects.filter(
+ team_id=team_id, state=MaterializedColumnSlotState.READY
+ ),
+ )
+ )
+ if event_property_names
+ else []
+ )
+
+ type_overrides = context.property_type_overrides or {}
+
+ event_properties: dict[str, dict[str, str | None]] = {}
+ for prop_def in event_property_definitions:
+ if not prop_def.property_type:
+ continue
+
+ prop_type = type_overrides.get(prop_def.name, prop_def.property_type)
+ prop_info: dict[str, str | None] = {"type": prop_type}
+ slot = prop_def.materialized_column_slots.first()
+ if slot:
+ prop_info["dmat"] = f"{DMAT_STRING_COLUMN_NAME_PREFIX}{slot.slot_index}"
+
+ event_properties[prop_def.name] = prop_info
+
+ person_property_values = (
+ PropertyDefinition.objects.alias(
+ effective_project_id=Coalesce("project_id", "team_id", output_field=models.BigIntegerField())
+ )
+ .filter(
+ effective_project_id=context.team.project_id,
+ name__in=person_property_names,
+ type=PropertyDefinition.Type.PERSON,
+ )
+ .values_list("name", "property_type")
+ if person_property_names
+ else []
+ )
+ person_properties: dict[str, dict[str, str | None]] = {
+ name: {"type": property_type} for name, property_type in person_property_values if property_type
+ }
+
+ group_properties: dict[str, dict[str, str | None]] = {}
+ for group_id, properties in group_property_names.items():
+ if not properties:
+ continue
+ group_property_values = (
+ PropertyDefinition.objects.alias(
+ effective_project_id=Coalesce("project_id", "team_id", output_field=models.BigIntegerField())
+ )
+ .filter(
+ effective_project_id=context.team.project_id,
+ name__in=properties,
+ type=PropertyDefinition.Type.GROUP,
+ group_type_index=group_id,
+ )
+ .values_list("name", "property_type")
+ )
+ group_properties.update(
+ {
+ f"{group_id}_{name}": {"type": property_type}
+ for name, property_type in group_property_values
+ if property_type
+ }
+ )
+
+ return PropertyMetadata(
+ event_properties=event_properties,
+ person_properties=person_properties,
+ group_properties=group_properties,
+ )
diff --git a/posthog/hogql/test/test_no_django_imports.py b/posthog/hogql/test/test_no_django_imports.py
index c8de0a19cdb4..5d29e04720d8 100644
--- a/posthog/hogql/test/test_no_django_imports.py
+++ b/posthog/hogql/test/test_no_django_imports.py
@@ -31,6 +31,7 @@ DJANGO_FREE_MODULES = [
# providers land (it transitively imports the property transforms).
"posthog.hogql.database.database",
"posthog.hogql.resolver",
+ "posthog.hogql.property_metadata",
]
_CHILD = f"""
diff --git a/posthog/hogql/transforms/property_types.py b/posthog/hogql/transforms/property_types.py
index 92012fe41b87..e81996723ddd 100644
--- a/posthog/hogql/transforms/property_types.py
+++ b/posthog/hogql/transforms/property_types.py
@@ -1,9 +1,6 @@
from datetime import datetime
from typing import Literal, Optional, cast
-from django.db import models
-from django.db.models.functions.comparison import Coalesce
-
from posthog.hogql import ast
from posthog.hogql.constants import EXCEPTION_STRING_ARRAY_PROPERTIES
from posthog.hogql.context import HogQLContext
@@ -20,6 +17,7 @@ from posthog.hogql.database.schema.persons import PersonsTable, RawPersonsTable
from posthog.hogql.errors import QueryError
from posthog.hogql.escape_sql import escape_hogql_identifier
from posthog.hogql.helpers.timestamp_visitor import parse_zoned_datetime_string
+from posthog.hogql.property_metadata import load_property_metadata
from posthog.hogql.property_planner import PropertySourceKind, plan_property_access
from posthog.hogql.restricted_properties import restricted_property_keys_for_table_type
from posthog.hogql.type_system import normalized_runtime_type, parse_sql_runtime_type
@@ -27,13 +25,11 @@ from posthog.hogql.visitor import CloningVisitor, TraversingVisitor
from posthog.clickhouse.events_json import EVENTS_PROPERTIES_JSON_SUBCOLUMNS, PERSON_PROPERTIES_JSON_SUBCOLUMNS
from posthog.clickhouse.materialized_columns import (
- DMAT_STRING_COLUMN_NAME_PREFIX,
MATERIALIZATION_VALID_TABLES,
MaterializedColumn,
TablesWithMaterializedColumns,
get_materialized_column_for_property,
)
-from posthog.models import Team
from posthog.property_columns import PropertyName, TableColumn
_JSON_EXTRACT_SCALAR_CASTS: dict[str, tuple[str, object]] = {
@@ -46,123 +42,44 @@ _JSON_EXTRACT_SCALAR_CASTS: dict[str, tuple[str, object]] = {
def build_property_swapper(node: ast.AST, context: HogQLContext) -> None:
- from posthog.models import PropertyDefinition
- from posthog.models.materialized_column_slots import MaterializedColumnSlot, MaterializedColumnSlotState
-
if not context or not context.team_id:
return
- if not context.team:
- context.team = Team.objects.get(id=context.team_id)
-
- if not context.team:
- return
-
# find all properties
property_finder = PropertyFinder(context)
property_finder.visit(node)
- # Load event property definitions with their materialized slots in a single query
- event_property_definitions = (
- PropertyDefinition.objects.alias(
- effective_project_id=Coalesce("project_id", "team_id", output_field=models.BigIntegerField())
- )
- .filter(
- effective_project_id=context.team.project_id,
- name__in=property_finder.event_properties,
- type__in=[None, PropertyDefinition.Type.EVENT],
- )
- .prefetch_related(
- models.Prefetch(
- "materialized_column_slots",
- queryset=MaterializedColumnSlot.objects.filter(
- team_id=context.team_id, state=MaterializedColumnSlotState.READY
- ),
- )
- )
- if property_finder.event_properties
- else []
- )
-
- type_overrides = context.property_type_overrides or {}
-
- event_properties: dict[str, dict[str, str | None]] = {}
- for prop_def in event_property_definitions:
- if not prop_def.property_type:
- continue
-
- prop_type = type_overrides.get(prop_def.name, prop_def.property_type)
- prop_info: dict[str, str | None] = {"type": prop_type}
- slot = prop_def.materialized_column_slots.first()
- if slot:
- prop_info["dmat"] = f"{DMAT_STRING_COLUMN_NAME_PREFIX}{slot.slot_index}"
-
- event_properties[prop_def.name] = prop_info
-
- person_property_values = (
- PropertyDefinition.objects.alias(
- effective_project_id=Coalesce("project_id", "team_id", output_field=models.BigIntegerField())
- )
- .filter(
- effective_project_id=context.team.project_id,
- name__in=property_finder.person_properties,
- type=PropertyDefinition.Type.PERSON,
- )
- .values_list("name", "property_type")
- if property_finder.person_properties
- else []
+ metadata = load_property_metadata(
+ context,
+ event_property_names=property_finder.event_properties,
+ person_property_names=property_finder.person_properties,
+ group_property_names=property_finder.group_properties,
)
- person_properties: dict[str, dict[str, str | None]] = {
- name: {"type": property_type} for name, property_type in person_property_values if property_type
- }
-
- group_properties: dict[str, dict[str, str | None]] = {}
- for group_id, properties in property_finder.group_properties.items():
- if not properties:
- continue
- group_property_values = (
- PropertyDefinition.objects.alias(
- effective_project_id=Coalesce("project_id", "team_id", output_field=models.BigIntegerField())
- )
- .filter(
- effective_project_id=context.team.project_id,
- name__in=properties,
- type=PropertyDefinition.Type.GROUP,
- group_type_index=group_id,
- )
- .values_list("name", "property_type")
- )
- group_properties.update(
- {
- f"{group_id}_{name}": {"type": property_type}
- for name, property_type in group_property_values
- if property_type
- }
- )
+ context.property_metadata = metadata
if context.type_observability is not None:
context.type_observability.record_property_definition_lookup(
property_source="event",
- known_count=len(event_properties),
+ known_count=len(metadata.event_properties),
total_count=len(property_finder.event_properties),
)
context.type_observability.record_property_definition_lookup(
property_source="person",
- known_count=len(person_properties),
+ known_count=len(metadata.person_properties),
total_count=len(property_finder.person_properties),
)
context.type_observability.record_property_definition_lookup(
property_source="group",
- known_count=len(group_properties),
+ known_count=len(metadata.group_properties),
total_count=sum(len(properties) for properties in property_finder.group_properties.values()),
)
timezone = context.database.get_timezone() if context and context.database else "UTC"
context.property_swapper = PropertySwapper(
timezone=timezone,
- event_properties=event_properties,
- person_properties=person_properties,
- group_properties=group_properties,
+ event_properties=metadata.event_properties,
+ person_properties=metadata.person_properties,
+ group_properties=metadata.group_properties,
context=context,
setTimeZones=True,
)