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): make built-in lazy joins serializable (2/2) (#62560)

Sandy Spicer09d08787ea3f
diff --git a/docs/published/handbook/engineering/databases/hogql-python.md b/docs/published/handbook/engineering/databases/hogql-python.md
index 28e171a4a2f3..47062ffbbf3d 100644
--- a/docs/published/handbook/engineering/databases/hogql-python.md
+++ b/docs/published/handbook/engineering/databases/hogql-python.md
@@ -105,9 +105,10 @@ class EventsTable(Table):
elements_chain: StringDatabaseField = StringDatabaseField(name="elements_chain")
created_at: DateTimeDatabaseField = DateTimeDatabaseField(name="created_at")
- # lazy table that adds a join to the persons table
- pdi: LazyTable = LazyTable(
- from_field="distinct_id", table=PersonDistinctIdTable(), join_function=join_with_max_person_distinct_id_table
+ # lazy join that joins in the person_distinct_ids table when accessed. The join is described
+ # as plain data: a resolver tag naming a join recipe in `lazy_join_registry.RESOLVERS`.
+ pdi: LazyJoin = LazyJoin(
+ from_field=["distinct_id"], join_table=PersonDistinctIdsTable(), resolver=PERSON_DISTINCT_IDS
)
# person fields on the event itself
poe: EventsPersonSubTable = EventsPersonSubTable()
diff --git a/posthog/hogql/database/database.py b/posthog/hogql/database/database.py
index 405af05e9b48..fdc4a17a5b4a 100644
--- a/posthog/hogql/database/database.py
+++ b/posthog/hogql/database/database.py
@@ -34,6 +34,18 @@ from posthog.schema import (
from posthog.hogql import ast
from posthog.hogql.context import HogQLContext
from posthog.hogql.database.direct_postgres_table import DirectPostgresTable
+from posthog.hogql.database.lazy_join_tags import (
+ DATA_WAREHOUSE,
+ DATA_WAREHOUSE_EXPERIMENTS,
+ ERROR_TRACKING_FINGERPRINT_ISSUE_STATE,
+ ERROR_TRACKING_ISSUE_FINGERPRINT_OVERRIDES,
+ EVENTS_TO_SESSIONS_V2,
+ EVENTS_TO_SESSIONS_V3,
+ PERSON_DISTINCT_ID_OVERRIDES,
+ PERSONS,
+ REPLAY_TO_SESSIONS_V2,
+ REPLAY_TO_SESSIONS_V3,
+)
from posthog.hogql.database.models import (
BooleanDatabaseField,
DatabaseField,
@@ -78,12 +90,10 @@ from posthog.hogql.database.schema.duckdb_table_functions import GenerateSeriesT
from posthog.hogql.database.schema.error_tracking_fingerprint_issue_state import (
ErrorTrackingFingerprintIssueStateTable,
RawErrorTrackingFingerprintIssueStateTable,
- join_with_error_tracking_fingerprint_issue_state_table,
)
from posthog.hogql.database.schema.error_tracking_issue_fingerprint_overrides import (
ErrorTrackingIssueFingerprintOverridesTable,
RawErrorTrackingIssueFingerprintOverridesTable,
- join_with_error_tracking_issue_fingerprint_overrides_table,
)
from posthog.hogql.database.schema.events import EventsTable
from posthog.hogql.database.schema.exchange_rate import ExchangeRateTable
@@ -106,34 +116,20 @@ from posthog.hogql.database.schema.numbers import NumbersTable
from posthog.hogql.database.schema.person_distinct_id_overrides import (
PersonDistinctIdOverridesTable,
RawPersonDistinctIdOverridesTable,
- join_with_person_distinct_id_overrides_table,
)
from posthog.hogql.database.schema.person_distinct_ids import PersonDistinctIdsTable, RawPersonDistinctIdsTable
-from posthog.hogql.database.schema.persons import PersonsTable, RawPersonsTable, join_with_persons_table
+from posthog.hogql.database.schema.persons import PersonsTable, RawPersonsTable
from posthog.hogql.database.schema.persons_revenue_analytics import PersonsRevenueAnalyticsTable
from posthog.hogql.database.schema.pg_embeddings import PgEmbeddingsTable
from posthog.hogql.database.schema.preaggregation_results import PreaggregationResultsTable
from posthog.hogql.database.schema.precalculated_events import PrecalculatedEventsTable
from posthog.hogql.database.schema.precalculated_person_properties import PrecalculatedPersonPropertiesTable
from posthog.hogql.database.schema.query_log_archive import QueryLogArchiveTable, RawQueryLogArchiveTable
-from posthog.hogql.database.schema.session_replay_events import (
- RawSessionReplayEventsTable,
- SessionReplayEventsTable,
- join_replay_table_to_sessions_table_v2,
- join_replay_table_to_sessions_table_v3,
-)
+from posthog.hogql.database.schema.session_replay_events import RawSessionReplayEventsTable, SessionReplayEventsTable
from posthog.hogql.database.schema.session_replay_features import SessionReplayFeaturesTable
from posthog.hogql.database.schema.sessions_v1 import RawSessionsTableV1, SessionsTableV1
-from posthog.hogql.database.schema.sessions_v2 import (
- RawSessionsTableV2,
- SessionsTableV2,
- join_events_table_to_sessions_table_v2,
-)
-from posthog.hogql.database.schema.sessions_v3 import (
- RawSessionsTableV3,
- SessionsTableV3,
- join_events_table_to_sessions_table_v3,
-)
+from posthog.hogql.database.schema.sessions_v2 import RawSessionsTableV2, SessionsTableV2
+from posthog.hogql.database.schema.sessions_v3 import RawSessionsTableV3, SessionsTableV3
from posthog.hogql.database.schema.spans import TraceAttributesTable, TraceSpansTable
from posthog.hogql.database.schema.static_cohort_people import StaticCohortPeople
from posthog.hogql.database.schema.system import SystemTables
@@ -148,6 +144,7 @@ from posthog.hogql.database.schema.web_stats_paths_preaggregated import WebStats
from posthog.hogql.database.schema.web_stats_preaggregated import WebStatsPreaggregatedTable
from posthog.hogql.database.schema.web_vitals_paths_preaggregated import WebVitalsPathsPreaggregatedTable
from posthog.hogql.database.utils import get_join_field_chain, qualify_join_key_expr
+from posthog.hogql.database.warehouse_join_resolvers import data_warehouse_resolver_params
from posthog.hogql.errors import QueryError, ResolutionError
from posthog.hogql.modifiers import create_default_modifiers_for_team
from posthog.hogql.parser import parse_expr
@@ -1217,7 +1214,7 @@ class Database(BaseModel):
events_table.fields["person"] = LazyJoin(
from_field=["person_id"],
join_table=database.get_table("persons"),
- join_function=join_with_persons_table,
+ resolver=PERSONS,
)
_use_error_tracking_issue_id_from_error_tracking_issue_overrides(database)
@@ -1239,14 +1236,14 @@ class Database(BaseModel):
events_table.fields["session"] = LazyJoin(
from_field=["$session_id"],
join_table=sessions,
- join_function=join_events_table_to_sessions_table_v2,
+ resolver=EVENTS_TO_SESSIONS_V2,
)
replay_events = database.get_table("session_replay_events")
replay_events.fields["session"] = LazyJoin(
from_field=["session_id"],
join_table=sessions,
- join_function=join_replay_table_to_sessions_table_v2,
+ resolver=REPLAY_TO_SESSIONS_V2,
)
cast(LazyJoin, replay_events.fields["events"]).join_table = events_table
@@ -1254,7 +1251,7 @@ class Database(BaseModel):
raw_replay_events.fields["session"] = LazyJoin(
from_field=["session_id"],
join_table=sessions,
- join_function=join_replay_table_to_sessions_table_v2,
+ resolver=REPLAY_TO_SESSIONS_V2,
)
cast(LazyJoin, raw_replay_events.fields["events"]).join_table = events_table
elif not database._is_direct_query() and modifiers.sessionTableVersion == SessionTableVersion.V3:
@@ -1265,14 +1262,14 @@ class Database(BaseModel):
events_table.fields["session"] = LazyJoin(
from_field=["$session_id"],
join_table=sessions,
- join_function=join_events_table_to_sessions_table_v3,
+ resolver=EVENTS_TO_SESSIONS_V3,
)
replay_events = database.get_table("session_replay_events")
replay_events.fields["session"] = LazyJoin(
from_field=["session_id"],
join_table=sessions,
- join_function=join_replay_table_to_sessions_table_v3,
+ resolver=REPLAY_TO_SESSIONS_V3,
)
cast(LazyJoin, replay_events.fields["events"]).join_table = events_table
@@ -1280,7 +1277,7 @@ class Database(BaseModel):
raw_replay_events.fields["session"] = LazyJoin(
from_field=["session_id"],
join_table=sessions,
- join_function=join_replay_table_to_sessions_table_v3,
+ resolver=REPLAY_TO_SESSIONS_V3,
)
cast(LazyJoin, raw_replay_events.fields["events"]).join_table = events_table
@@ -1588,15 +1585,21 @@ class Database(BaseModel):
continue
join_configuration = join.configuration if isinstance(join.configuration, dict) else {}
+ use_experiments = bool(
+ join.joining_table_name == "events" and join_configuration.get("experiments_optimized")
+ )
+ dw_join_kwargs: dict[str, Any] = {
+ "source_table_key": join.source_table_key,
+ "joining_table_key": join.joining_table_key,
+ "joining_table_name": join.joining_table_name,
+ "configuration": join_configuration,
+ }
source_table.fields[join.field_name] = LazyJoin(
from_field=from_field,
to_field=to_field,
join_table=joining_table,
- join_function=(
- join.join_function_for_experiments()
- if "events" == join.joining_table_name and join_configuration.get("experiments_optimized")
- else join.join_function()
- ),
+ resolver=DATA_WAREHOUSE_EXPERIMENTS if use_experiments else DATA_WAREHOUSE,
+ resolver_params=data_warehouse_resolver_params(**dw_join_kwargs),
)
if not database._is_direct_query() and join.source_table_name == "persons":
@@ -1635,9 +1638,11 @@ class Database(BaseModel):
from_field=from_field,
to_field=to_field,
join_table=joining_table,
- # reusing join_function but with different source_table_key since we're joining 'directly' on events
- join_function=join.join_function(
- override_source_table_key=override_source_table_key
+ # reusing the data-warehouse resolver but with a different source_table_key
+ # since we're joining 'directly' on events
+ resolver=DATA_WAREHOUSE,
+ resolver_params=data_warehouse_resolver_params(
+ **dw_join_kwargs, override_source_table_key=override_source_table_key
),
)
else:
@@ -1645,14 +1650,16 @@ class Database(BaseModel):
from_field=from_field,
to_field=to_field,
join_table=joining_table,
- join_function=join.join_function(),
+ resolver=DATA_WAREHOUSE,
+ resolver_params=data_warehouse_resolver_params(**dw_join_kwargs),
)
elif isinstance(person_field, ast.LazyJoin):
person_field.join_table.fields[join.field_name] = LazyJoin( # type: ignore
from_field=from_field,
to_field=to_field,
join_table=joining_table,
- join_function=join.join_function(),
+ resolver=DATA_WAREHOUSE,
+ resolver_params=data_warehouse_resolver_params(**dw_join_kwargs),
)
except Exception as e:
@@ -1690,7 +1697,7 @@ def _use_person_id_from_person_overrides(database: Database) -> None:
table.fields["override"] = LazyJoin(
from_field=["distinct_id"],
join_table=database.get_table("person_distinct_id_overrides"),
- join_function=join_with_person_distinct_id_overrides_table,
+ resolver=PERSON_DISTINCT_ID_OVERRIDES,
)
table.fields["person_id"] = ExpressionField(
name="person_id",
@@ -1732,7 +1739,7 @@ def _use_error_tracking_issue_id_from_error_tracking_issue_overrides(database: D
table.fields["exception_issue_override"] = LazyJoin(
from_field=["fingerprint"],
join_table=ErrorTrackingIssueFingerprintOverridesTable(),
- join_function=join_with_error_tracking_issue_fingerprint_overrides_table,
+ resolver=ERROR_TRACKING_ISSUE_FINGERPRINT_OVERRIDES,
)
table.fields["issue_id"] = ExpressionField(name="issue_id", expr=exprs["issue_id"])
@@ -1740,7 +1747,7 @@ def _use_error_tracking_issue_id_from_error_tracking_issue_overrides(database: D
table.fields["fingerprint_issue_state"] = LazyJoin(
from_field=["fingerprint"],
join_table=ErrorTrackingFingerprintIssueStateTable(),
- join_function=join_with_error_tracking_fingerprint_issue_state_table,
+ resolver=ERROR_TRACKING_FINGERPRINT_ISSUE_STATE,
)
table.fields["issue_id_v2"] = ExpressionField(name="issue_id_v2", expr=exprs["issue_id_v2"])
table.fields["issue_name"] = ExpressionField(name="issue_name", expr=exprs["issue_name"])
diff --git a/posthog/hogql/database/lazy_join_registry.py b/posthog/hogql/database/lazy_join_registry.py
new file mode 100644
index 000000000000..01a779a9d6db
--- /dev/null
+++ b/posthog/hogql/database/lazy_join_registry.py
@@ -0,0 +1,83 @@
+from collections.abc import Callable
+from typing import TYPE_CHECKING
+
+from posthog.hogql.database import lazy_join_tags as tags
+from posthog.hogql.database.schema.account_aggregates import account_notebooks_join, account_tags_join
+from posthog.hogql.database.schema.error_tracking_fingerprint_issue_state import (
+ join_with_error_tracking_fingerprint_issue_state_table,
+)
+from posthog.hogql.database.schema.error_tracking_issue_fingerprint_overrides import (
+ join_with_error_tracking_issue_fingerprint_overrides_table,
+)
+from posthog.hogql.database.schema.groups import join_with_group_n_table
+from posthog.hogql.database.schema.groups_revenue_analytics import join_with_groups_revenue_analytics_table
+from posthog.hogql.database.schema.person_distinct_id_overrides import join_with_person_distinct_id_overrides_table
+from posthog.hogql.database.schema.person_distinct_ids import join_with_person_distinct_ids_table
+from posthog.hogql.database.schema.persons import join_with_persons_table
+from posthog.hogql.database.schema.persons_pdi import persons_pdi_join
+from posthog.hogql.database.schema.persons_revenue_analytics import join_with_persons_revenue_analytics_table
+from posthog.hogql.database.schema.session_replay_events import (
+ join_replay_table_to_sessions_table_v1,
+ join_replay_table_to_sessions_table_v2,
+ join_replay_table_to_sessions_table_v3,
+ join_with_console_logs_log_entries_table,
+ join_with_events_table,
+)
+from posthog.hogql.database.schema.sessions_v1 import join_events_table_to_sessions_table
+from posthog.hogql.database.schema.sessions_v2 import join_events_table_to_sessions_table_v2
+from posthog.hogql.database.schema.sessions_v3 import join_events_table_to_sessions_table_v3
+from posthog.hogql.database.warehouse_join_resolvers import (
+ resolve_data_warehouse_experiments_join,
+ resolve_data_warehouse_join,
+ resolve_foreign_key_join,
+)
+
+if TYPE_CHECKING:
+ from posthog.hogql import ast
+ from posthog.hogql.context import HogQLContext
+ from posthog.hogql.database.models import LazyJoinToAdd
+
+# A lazy-join resolver builds the JOIN ``ast.JoinExpr`` for a lazy join from plain data —
+# the LazyJoin's ``from_field``/``to_field``/``resolver_params`` — plus the runtime
+# resolution context and the query node. Resolvers are keyed by tag so a ``LazyJoin`` can
+# describe its join declaratively (a tag + params) instead of carrying a Python closure,
+# which is what makes a built ``Database`` serializable.
+LazyJoinResolver = Callable[["LazyJoinToAdd", "HogQLContext", "ast.SelectQuery"], "ast.JoinExpr"]
+
+# The explicit, closed list of every lazy-join resolver the engine supports. This is the
+# contract a serialized Database depends on: a consumer (another process, a cache reader, a
+# future non-Python engine) must implement exactly these tags. Add new resolvers here — a
+# tag that isn't listed cannot be resolved.
+RESOLVERS: dict[str, LazyJoinResolver] = {
+ tags.FOREIGN_KEY: resolve_foreign_key_join,
+ tags.DATA_WAREHOUSE: resolve_data_warehouse_join,
+ tags.DATA_WAREHOUSE_EXPERIMENTS: resolve_data_warehouse_experiments_join,
+ tags.PERSONS: join_with_persons_table,
+ tags.PERSONS_PDI: persons_pdi_join,
+ tags.PERSON_DISTINCT_IDS: join_with_person_distinct_ids_table,
+ tags.PERSON_DISTINCT_ID_OVERRIDES: join_with_person_distinct_id_overrides_table,
+ tags.GROUP_N: join_with_group_n_table,
+ tags.GROUPS_REVENUE_ANALYTICS: join_with_groups_revenue_analytics_table,
+ tags.PERSONS_REVENUE_ANALYTICS: join_with_persons_revenue_analytics_table,
+ tags.EVENTS_TO_SESSIONS_V1: join_events_table_to_sessions_table,
+ tags.EVENTS_TO_SESSIONS_V2: join_events_table_to_sessions_table_v2,
+ tags.EVENTS_TO_SESSIONS_V3: join_events_table_to_sessions_table_v3,
+ tags.REPLAY_TO_SESSIONS_V1: join_replay_table_to_sessions_table_v1,
+ tags.REPLAY_TO_SESSIONS_V2: join_replay_table_to_sessions_table_v2,
+ tags.REPLAY_TO_SESSIONS_V3: join_replay_table_to_sessions_table_v3,
+ tags.REPLAY_TO_EVENTS: join_with_events_table,
+ tags.REPLAY_TO_CONSOLE_LOGS: join_with_console_logs_log_entries_table,
+ tags.ERROR_TRACKING_ISSUE_FINGERPRINT_OVERRIDES: join_with_error_tracking_issue_fingerprint_overrides_table,
+ tags.ERROR_TRACKING_FINGERPRINT_ISSUE_STATE: join_with_error_tracking_fingerprint_issue_state_table,
+ tags.ACCOUNT_TAGS: account_tags_join,
+ tags.ACCOUNT_NOTEBOOKS: account_notebooks_join,
+}
+
+
+def get_lazy_join_resolver(name: str) -> LazyJoinResolver:
+ try:
+ return RESOLVERS[name]
+ except KeyError:
+ raise ValueError(
+ f"Unknown lazy join resolver {name!r}. Every supported resolver must be listed in RESOLVERS."
+ ) from None
diff --git a/posthog/hogql/database/lazy_join_tags.py b/posthog/hogql/database/lazy_join_tags.py
new file mode 100644
index 000000000000..b76d6c608d64
--- /dev/null
+++ b/posthog/hogql/database/lazy_join_tags.py
@@ -0,0 +1,27 @@
+# Resolver tags. A LazyJoin stores one of these (plus JSON-able `resolver_params`) instead of
+# a Python closure, so a join is described as plain, serializable data. The tag → implementation
+# mapping lives in `lazy_join_registry.RESOLVERS` — every supported tag must be listed there.
+# This module is import-dependency-free so any module can reference tags without import cycles.
+FOREIGN_KEY = "foreign_key"
+DATA_WAREHOUSE = "data_warehouse"
+DATA_WAREHOUSE_EXPERIMENTS = "data_warehouse_experiments"
+
+PERSONS = "persons"
+PERSONS_PDI = "persons_pdi"
+PERSON_DISTINCT_IDS = "person_distinct_ids"
+PERSON_DISTINCT_ID_OVERRIDES = "person_distinct_id_overrides"
+GROUP_N = "group_n"
+GROUPS_REVENUE_ANALYTICS = "groups_revenue_analytics"
+PERSONS_REVENUE_ANALYTICS = "persons_revenue_analytics"
+EVENTS_TO_SESSIONS_V1 = "events_to_sessions_v1"
+EVENTS_TO_SESSIONS_V2 = "events_to_sessions_v2"
+EVENTS_TO_SESSIONS_V3 = "events_to_sessions_v3"
+REPLAY_TO_SESSIONS_V1 = "replay_to_sessions_v1"
+REPLAY_TO_SESSIONS_V2 = "replay_to_sessions_v2"
+REPLAY_TO_SESSIONS_V3 = "replay_to_sessions_v3"
+REPLAY_TO_EVENTS = "replay_to_events"
+REPLAY_TO_CONSOLE_LOGS = "replay_to_console_logs"
+ERROR_TRACKING_ISSUE_FINGERPRINT_OVERRIDES = "error_tracking_issue_fingerprint_overrides"
+ERROR_TRACKING_FINGERPRINT_ISSUE_STATE = "error_tracking_fingerprint_issue_state"
+ACCOUNT_TAGS = "account_tags"
+ACCOUNT_NOTEBOOKS = "account_notebooks"
diff --git a/posthog/hogql/database/models.py b/posthog/hogql/database/models.py
index 39ce0c12d2b9..993336294231 100644
--- a/posthog/hogql/database/models.py
+++ b/posthog/hogql/database/models.py
@@ -1,5 +1,4 @@
import datetime
-from collections.abc import Callable
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Any, Literal, Optional
@@ -17,7 +16,7 @@ from posthog.hogql.errors import NotImplementedError, ResolutionError
from posthog.clickhouse.workload import Workload
if TYPE_CHECKING:
- from posthog.hogql.ast import LazyJoinType, SelectQuery
+ from posthog.hogql.ast import JoinExpr, LazyJoinType, SelectQuery
from posthog.hogql.base import ConstantType
from posthog.hogql.context import HogQLContext
@@ -377,7 +376,12 @@ class TableNode(BaseModel):
class LazyJoin(FieldOrTable):
model_config = ConfigDict(extra="forbid")
- join_function: Callable[["LazyJoinToAdd", "HogQLContext", "SelectQuery"], Any]
+ # A lazy join is described entirely as plain, serializable data: a `resolver` tag naming a
+ # join recipe in the registry, plus JSON-able `resolver_params` for anything the recipe
+ # needs at resolution time. Keeping the LazyJoin free of closures is what makes the whole
+ # Database serializable and cacheable.
+ resolver: str
+ resolver_params: dict[str, Any] = PydanticField(default_factory=dict)
join_table: Table | str
from_field: list[str | int]
to_field: Optional[list[str | int]] = None
@@ -391,6 +395,13 @@ class LazyJoin(FieldOrTable):
return context.database.get_table(self.join_table)
+ def resolve_join_to_add(
+ self, join_to_add: "LazyJoinToAdd", context: "HogQLContext", node: "SelectQuery"
+ ) -> "JoinExpr":
+ from posthog.hogql.database.lazy_join_registry import get_lazy_join_resolver # noqa: PLC0415 — circular import
+
+ return get_lazy_join_resolver(self.resolver)(join_to_add, context, node)
+
class LazyTable(Table):
"""
diff --git a/posthog/hogql/database/postgres_utils.py b/posthog/hogql/database/postgres_utils.py
index e1d267d1d94f..215eb3e034b3 100644
--- a/posthog/hogql/database/postgres_utils.py
+++ b/posthog/hogql/database/postgres_utils.py
@@ -1,13 +1,11 @@
import dataclasses
-from collections.abc import Callable, Sequence
-from typing import Any, Protocol, cast
+from collections.abc import Sequence
+from typing import Any, Protocol
-from posthog.hogql import ast
-from posthog.hogql.context import HogQLContext
from posthog.hogql.database.direct_postgres_table import DirectPostgresTable
-from posthog.hogql.database.models import LazyJoin, LazyJoinToAdd, Table
+from posthog.hogql.database.lazy_join_tags import FOREIGN_KEY
+from posthog.hogql.database.models import LazyJoin, Table
from posthog.hogql.database.utils import get_join_field_chain
-from posthog.hogql.errors import ResolutionError
from posthog.exceptions_capture import capture_exception
@@ -163,7 +161,7 @@ def _add_foreign_key_lazy_join(
from_field=from_field,
to_field=to_field,
join_table=join_table,
- join_function=_foreign_key_join_function(from_field, to_field),
+ resolver=FOREIGN_KEY,
)
target_table_name = target_hogql_table.name if isinstance(target_hogql_table.name, str) else None
@@ -179,7 +177,7 @@ def _add_foreign_key_lazy_join(
from_field=to_field,
to_field=from_field,
join_table=hogql_table,
- join_function=_foreign_key_join_function(to_field, from_field),
+ resolver=FOREIGN_KEY,
)
@@ -229,42 +227,6 @@ def _is_same_external_scope(
return source_table_name.rsplit(".", 1)[0] == target_table_name.rsplit(".", 1)[0]
-def _foreign_key_join_function(
- from_field: list[str | int], to_field: list[str | int]
-) -> Callable[[LazyJoinToAdd, HogQLContext, ast.SelectQuery], ast.JoinExpr]:
- def _join_function(join_to_add: LazyJoinToAdd, context: HogQLContext, node: ast.SelectQuery):
- join_table = join_to_add.lazy_join.resolve_table(context)
-
- if isinstance(join_table.name, str):
- join_table_chain = cast(list[str | int], join_table.name.split("."))
- else:
- join_table_chain = [join_to_add.to_table]
-
- if not join_to_add.fields_accessed:
- raise ResolutionError(f"No fields requested from {join_to_add.to_table}")
-
- left = ast.Field(chain=[join_to_add.from_table, *from_field])
- right = ast.Field(chain=[join_to_add.to_table, *to_field])
-
- return ast.JoinExpr(
- table=ast.SelectQuery(
- select=[
- ast.Alias(alias=alias, expr=ast.Field(chain=chain))
- for alias, chain in join_to_add.fields_accessed.items()
- ],
- select_from=ast.JoinExpr(table=ast.Field(chain=join_table_chain)),
- ),
- join_type="LEFT JOIN",
- alias=join_to_add.to_table,
- constraint=ast.JoinConstraint(
- expr=ast.CompareOperation(op=ast.CompareOperationOp.Eq, left=left, right=right),
- constraint_type="ON",
- ),
- )
-
- return _join_function
-
-
def _reverse_foreign_key_field_name(from_table: str, target_table: str) -> str:
from_base = from_table.split(".")[-1]
target_base = target_table.split(".")[-1]
diff --git a/posthog/hogql/database/schema/account_aggregates.py b/posthog/hogql/database/schema/account_aggregates.py
index 7316b52459fd..faebddb79e63 100644
--- a/posthog/hogql/database/schema/account_aggregates.py
+++ b/posthog/hogql/database/schema/account_aggregates.py
@@ -10,6 +10,7 @@ join subqueries below can be resolved by the planner.
from posthog.hogql import ast
from posthog.hogql.base import Expr
from posthog.hogql.context import HogQLContext
+from posthog.hogql.database.lazy_join_tags import ACCOUNT_NOTEBOOKS, ACCOUNT_TAGS
from posthog.hogql.database.models import (
DANGEROUS_NoTeamIdCheckTable,
FieldOrTable,
@@ -140,13 +141,13 @@ def _join_on_account_id(select: ast.SelectQuery | ast.SelectSetQuery, join_to_ad
)
-def _account_tags_join(join_to_add: LazyJoinToAdd, context: HogQLContext, node: ast.SelectQuery) -> ast.JoinExpr:
+def account_tags_join(join_to_add: LazyJoinToAdd, context: HogQLContext, node: ast.SelectQuery) -> ast.JoinExpr:
if not join_to_add.fields_accessed:
raise ResolutionError("No fields requested from `accounts.tags`")
return _join_on_account_id(_account_tags_select(), join_to_add)
-def _account_notebooks_join(join_to_add: LazyJoinToAdd, context: HogQLContext, node: ast.SelectQuery) -> ast.JoinExpr:
+def account_notebooks_join(join_to_add: LazyJoinToAdd, context: HogQLContext, node: ast.SelectQuery) -> ast.JoinExpr:
if not join_to_add.fields_accessed:
raise ResolutionError("No fields requested from `accounts.notebooks`")
return _join_on_account_id(_account_notebooks_select(), join_to_add)
@@ -155,11 +156,11 @@ def _account_notebooks_join(join_to_add: LazyJoinToAdd, context: HogQLContext, n
account_tags_lazy_join: LazyJoin = LazyJoin(
from_field=["id"],
join_table=_AccountTagsTable(),
- join_function=_account_tags_join,
+ resolver=ACCOUNT_TAGS,
)
account_notebooks_lazy_join: LazyJoin = LazyJoin(
from_field=["id"],
join_table=_AccountNotebooksTable(),
- join_function=_account_notebooks_join,
+ resolver=ACCOUNT_NOTEBOOKS,
)
diff --git a/posthog/hogql/database/schema/ai_events.py b/posthog/hogql/database/schema/ai_events.py
index f1ba835ac823..a23ef9cb04f9 100644
--- a/posthog/hogql/database/schema/ai_events.py
+++ b/posthog/hogql/database/schema/ai_events.py
@@ -1,3 +1,4 @@
+from posthog.hogql.database.lazy_join_tags import PERSON_DISTINCT_IDS
from posthog.hogql.database.models import (
BooleanDatabaseField,
DateTimeDatabaseField,
@@ -10,10 +11,7 @@ from posthog.hogql.database.models import (
StringJSONDatabaseField,
Table,
)
-from posthog.hogql.database.schema.person_distinct_ids import (
- PersonDistinctIdsTable,
- join_with_person_distinct_ids_table,
-)
+from posthog.hogql.database.schema.person_distinct_ids import PersonDistinctIdsTable
class AiEventsTable(Table):
@@ -88,7 +86,7 @@ class AiEventsTable(Table):
"pdi": LazyJoin(
from_field=["distinct_id"],
join_table=PersonDistinctIdsTable(),
- join_function=join_with_person_distinct_ids_table,
+ resolver=PERSON_DISTINCT_IDS,
),
"person": FieldTraverser(chain=["pdi", "person"]),
}
diff --git a/posthog/hogql/database/schema/cohort_people.py b/posthog/hogql/database/schema/cohort_people.py
index 096b0dee5077..1cbac9fc5298 100644
--- a/posthog/hogql/database/schema/cohort_people.py
+++ b/posthog/hogql/database/schema/cohort_people.py
@@ -1,3 +1,4 @@
+from posthog.hogql.database.lazy_join_tags import PERSONS
from posthog.hogql.database.models import (
FieldOrTable,
IntegerDatabaseField,
@@ -7,7 +8,6 @@ from posthog.hogql.database.models import (
StringDatabaseField,
Table,
)
-from posthog.hogql.database.schema.persons import join_with_persons_table
COHORT_PEOPLE_FIELDS: dict[str, FieldOrTable] = {
"person_id": StringDatabaseField(name="person_id", nullable=False),
@@ -16,7 +16,7 @@ COHORT_PEOPLE_FIELDS: dict[str, FieldOrTable] = {
"person": LazyJoin(
from_field=["person_id"],
join_table="persons",
- join_function=join_with_persons_table,
+ resolver=PERSONS,
),
}
diff --git a/posthog/hogql/database/schema/events.py b/posthog/hogql/database/schema/events.py
index 8b1086ccfe00..0ab607527eae 100644
--- a/posthog/hogql/database/schema/events.py
+++ b/posthog/hogql/database/schema/events.py
@@ -1,3 +1,9 @@
+from posthog.hogql.database.lazy_join_tags import (
+ EVENTS_TO_SESSIONS_V1,
+ GROUP_N,
+ PERSON_DISTINCT_IDS,
+ PERSONS_REVENUE_ANALYTICS,
+)
from posthog.hogql.database.models import (
DatabaseField,
DateTimeDatabaseField,
@@ -11,16 +17,10 @@ from posthog.hogql.database.models import (
Table,
VirtualTable,
)
-from posthog.hogql.database.schema.groups import GroupsTable, join_with_group_n_table
-from posthog.hogql.database.schema.person_distinct_ids import (
- PersonDistinctIdsTable,
- join_with_person_distinct_ids_table,
-)
-from posthog.hogql.database.schema.persons_revenue_analytics import (
- PersonsRevenueAnalyticsTable,
- join_with_persons_revenue_analytics_table,
-)
-from posthog.hogql.database.schema.sessions_v1 import SessionsTableV1, join_events_table_to_sessions_table
+from posthog.hogql.database.schema.groups import GroupsTable
+from posthog.hogql.database.schema.person_distinct_ids import PersonDistinctIdsTable
+from posthog.hogql.database.schema.persons_revenue_analytics import PersonsRevenueAnalyticsTable
+from posthog.hogql.database.schema.sessions_v1 import SessionsTableV1
class EventsPersonSubTable(VirtualTable):
@@ -31,7 +31,7 @@ class EventsPersonSubTable(VirtualTable):
"revenue_analytics": LazyJoin(
from_field=["person_id"],
join_table=PersonsRevenueAnalyticsTable(),
- join_function=join_with_persons_revenue_analytics_table,
+ resolver=PERSONS_REVENUE_ANALYTICS,
),
}
@@ -80,7 +80,7 @@ class EventsTable(Table):
"pdi": LazyJoin(
from_field=["distinct_id"],
join_table=PersonDistinctIdsTable(),
- join_function=join_with_person_distinct_ids_table,
+ resolver=PERSON_DISTINCT_IDS,
),
# Person and group fields on the event itself. Should not be used directly.
"poe": EventsPersonSubTable(),
@@ -96,36 +96,41 @@ class EventsTable(Table):
"group_0": LazyJoin(
from_field=["$group_0"],
join_table=GroupsTable(),
- join_function=join_with_group_n_table(0),
+ resolver=GROUP_N,
+ resolver_params={"group_index": 0},
),
"$group_1": StringDatabaseField(name="$group_1", nullable=False),
"group_1": LazyJoin(
from_field=["$group_1"],
join_table=GroupsTable(),
- join_function=join_with_group_n_table(1),
+ resolver=GROUP_N,
+ resolver_params={"group_index": 1},
),
"$group_2": StringDatabaseField(name="$group_2", nullable=False),
"group_2": LazyJoin(
from_field=["$group_2"],
join_table=GroupsTable(),
- join_function=join_with_group_n_table(2),
+ resolver=GROUP_N,
+ resolver_params={"group_index": 2},
),
"$group_3": StringDatabaseField(name="$group_3", nullable=False),
"group_3": LazyJoin(
from_field=["$group_3"],
join_table=GroupsTable(),
- join_function=join_with_group_n_table(3),
+ resolver=GROUP_N,
+ resolver_params={"group_index": 3},
),
"$group_4": StringDatabaseField(name="$group_4", nullable=False),
"group_4": LazyJoin(
from_field=["$group_4"],
join_table=GroupsTable(),
- join_function=join_with_group_n_table(4),
+ resolver=GROUP_N,
+ resolver_params={"group_index": 4},
),
"session": LazyJoin(
from_field=["$session_id"],
join_table=SessionsTableV1(),
- join_function=join_events_table_to_sessions_table,
+ resolver=EVENTS_TO_SESSIONS_V1,
),
"elements_chain_href": StringDatabaseField(name="elements_chain_href", nullable=False),
"elements_chain_texts": StringArrayDatabaseField(name="elements_chain_texts", nullable=False),
diff --git a/posthog/hogql/database/schema/groups.py b/posthog/hogql/database/schema/groups.py
index da34101dc95c..7b3396e075bc 100644
--- a/posthog/hogql/database/schema/groups.py
+++ b/posthog/hogql/database/schema/groups.py
@@ -1,6 +1,7 @@
from posthog.hogql.ast import SelectQuery
from posthog.hogql.context import HogQLContext
from posthog.hogql.database.argmax import argmax_select
+from posthog.hogql.database.lazy_join_tags import GROUPS_REVENUE_ANALYTICS
from posthog.hogql.database.models import (
DateTimeDatabaseField,
FieldOrTable,
@@ -13,10 +14,7 @@ from posthog.hogql.database.models import (
StringJSONDatabaseField,
Table,
)
-from posthog.hogql.database.schema.groups_revenue_analytics import (
- GroupsRevenueAnalyticsTable,
- join_with_groups_revenue_analytics_table,
-)
+from posthog.hogql.database.schema.groups_revenue_analytics import GroupsRevenueAnalyticsTable
from posthog.hogql.errors import ResolutionError
GROUPS_TABLE_FIELDS: dict[str, FieldOrTable] = {
@@ -29,7 +27,7 @@ GROUPS_TABLE_FIELDS: dict[str, FieldOrTable] = {
"revenue_analytics": LazyJoin(
from_field=["key"],
join_table=GroupsRevenueAnalyticsTable(),
- join_function=join_with_groups_revenue_analytics_table,
+ resolver=GROUPS_REVENUE_ANALYTICS,
),
}
@@ -43,39 +41,42 @@ def select_from_groups_table(requested_fields: dict[str, list[str | int]]):
)
-def join_with_group_n_table(group_index: int):
- def join_with_group_table(
- join_to_add: LazyJoinToAdd,
- context: HogQLContext,
- node: SelectQuery,
- ):
- from posthog.hogql import ast
+def join_with_group_n_table(
+ join_to_add: LazyJoinToAdd,
+ context: HogQLContext,
+ node: SelectQuery,
+):
+ from posthog.hogql import ast
+
+ # Which $group_N events column to join on; carried as plain data instead of being
+ # captured in a closure so the LazyJoin (and the Database holding it) stays serializable.
+ group_index = join_to_add.lazy_join.resolver_params.get("group_index")
+ if group_index is None:
+ raise ResolutionError("group_n lazy join requires resolver_params['group_index']")
+
+ if not join_to_add.fields_accessed:
+ raise ResolutionError("No fields requested from person_distinct_ids")
- if not join_to_add.fields_accessed:
- raise ResolutionError("No fields requested from person_distinct_ids")
+ select_query = select_from_groups_table(join_to_add.fields_accessed)
+ select_query.where = ast.CompareOperation(
+ left=ast.Field(chain=["index"]),
+ op=ast.CompareOperationOp.Eq,
+ right=ast.Constant(value=group_index),
+ )
- select_query = select_from_groups_table(join_to_add.fields_accessed)
- select_query.where = ast.CompareOperation(
- left=ast.Field(chain=["index"]),
+ join_expr = ast.JoinExpr(table=select_query)
+ join_expr.join_type = "LEFT JOIN"
+ join_expr.alias = join_to_add.to_table
+ join_expr.constraint = ast.JoinConstraint(
+ expr=ast.CompareOperation(
op=ast.CompareOperationOp.Eq,
- right=ast.Constant(value=group_index),
- )
-
- join_expr = ast.JoinExpr(table=select_query)
- join_expr.join_type = "LEFT JOIN"
- join_expr.alias = join_to_add.to_table
- join_expr.constraint = ast.JoinConstraint(
- expr=ast.CompareOperation(
- op=ast.CompareOperationOp.Eq,
- left=ast.Field(chain=[join_to_add.from_table, f"$group_{group_index}"]),
- right=ast.Field(chain=[join_to_add.to_table, "key"]),
- ),
- constraint_type="ON",
- )
-
- return join_expr
-
- return join_with_group_table
+ left=ast.Field(chain=[join_to_add.from_table, f"$group_{group_index}"]),
+ right=ast.Field(chain=[join_to_add.to_table, "key"]),
+ ),
+ constraint_type="ON",
+ )
+
+ return join_expr
class RawGroupsTable(Table):
diff --git a/posthog/hogql/database/schema/person_distinct_id_overrides.py b/posthog/hogql/database/schema/person_distinct_id_overrides.py
index 213cc97b45a2..25c812398667 100644
--- a/posthog/hogql/database/schema/person_distinct_id_overrides.py
+++ b/posthog/hogql/database/schema/person_distinct_id_overrides.py
@@ -2,6 +2,7 @@ from posthog.hogql.ast import SelectQuery
from posthog.hogql.constants import HogQLQuerySettings
from posthog.hogql.context import HogQLContext
from posthog.hogql.database.argmax import argmax_select
+from posthog.hogql.database.lazy_join_tags import PERSONS
from posthog.hogql.database.models import (
BooleanDatabaseField,
FieldOrTable,
@@ -13,7 +14,6 @@ from posthog.hogql.database.models import (
StringDatabaseField,
Table,
)
-from posthog.hogql.database.schema.persons import join_with_persons_table
from posthog.hogql.errors import ResolutionError
PERSON_DISTINCT_ID_OVERRIDES_FIELDS: dict[str, FieldOrTable] = {
@@ -23,7 +23,7 @@ PERSON_DISTINCT_ID_OVERRIDES_FIELDS: dict[str, FieldOrTable] = {
"person": LazyJoin(
from_field=["person_id"],
join_table="persons",
- join_function=join_with_persons_table,
+ resolver=PERSONS,
),
}
diff --git a/posthog/hogql/database/schema/person_distinct_ids.py b/posthog/hogql/database/schema/person_distinct_ids.py
index b795cdbf19b5..353c988b3462 100644
--- a/posthog/hogql/database/schema/person_distinct_ids.py
+++ b/posthog/hogql/database/schema/person_distinct_ids.py
@@ -2,6 +2,7 @@ from posthog.hogql.ast import SelectQuery
from posthog.hogql.constants import HogQLQuerySettings
from posthog.hogql.context import HogQLContext
from posthog.hogql.database.argmax import argmax_select
+from posthog.hogql.database.lazy_join_tags import PERSONS
from posthog.hogql.database.models import (
BooleanDatabaseField,
FieldOrTable,
@@ -13,7 +14,6 @@ from posthog.hogql.database.models import (
StringDatabaseField,
Table,
)
-from posthog.hogql.database.schema.persons import join_with_persons_table
from posthog.hogql.errors import ResolutionError
PERSON_DISTINCT_IDS_FIELDS: dict[str, FieldOrTable] = {
@@ -23,7 +23,7 @@ PERSON_DISTINCT_IDS_FIELDS: dict[str, FieldOrTable] = {
"person": LazyJoin(
from_field=["person_id"],
join_table="persons",
- join_function=join_with_persons_table,
+ resolver=PERSONS,
),
}
diff --git a/posthog/hogql/database/schema/persons.py b/posthog/hogql/database/schema/persons.py
index f0ad1c812911..514837ff14bc 100644
--- a/posthog/hogql/database/schema/persons.py
+++ b/posthog/hogql/database/schema/persons.py
@@ -10,6 +10,7 @@ from posthog.hogql.base import Expr
from posthog.hogql.constants import HogQLQuerySettings
from posthog.hogql.context import HogQLContext
from posthog.hogql.database.argmax import argmax_select
+from posthog.hogql.database.lazy_join_tags import PERSONS_PDI, PERSONS_REVENUE_ANALYTICS
from posthog.hogql.database.models import (
BooleanDatabaseField,
DateTimeDatabaseField,
@@ -23,11 +24,8 @@ from posthog.hogql.database.models import (
StringJSONDatabaseField,
Table,
)
-from posthog.hogql.database.schema.persons_pdi import PersonsPDITable, persons_pdi_join
-from posthog.hogql.database.schema.persons_revenue_analytics import (
- PersonsRevenueAnalyticsTable,
- join_with_persons_revenue_analytics_table,
-)
+from posthog.hogql.database.schema.persons_pdi import PersonsPDITable
+from posthog.hogql.database.schema.persons_revenue_analytics import PersonsRevenueAnalyticsTable
from posthog.hogql.database.schema.util.where_clause_extractor import WhereClauseExtractor
from posthog.hogql.errors import ResolutionError
from posthog.hogql.parser import parse_select
@@ -45,12 +43,12 @@ PERSONS_FIELDS: dict[str, FieldOrTable] = {
"pdi": LazyJoin(
from_field=["id"],
join_table=PersonsPDITable(),
- join_function=persons_pdi_join,
+ resolver=PERSONS_PDI,
),
"revenue_analytics": LazyJoin(
from_field=["id"],
join_table=PersonsRevenueAnalyticsTable(),
- join_function=join_with_persons_revenue_analytics_table,
+ resolver=PERSONS_REVENUE_ANALYTICS,
),
}
diff --git a/posthog/hogql/database/schema/session_replay_events.py b/posthog/hogql/database/schema/session_replay_events.py
index 6e10251302fc..aaeb4b69123f 100644
--- a/posthog/hogql/database/schema/session_replay_events.py
+++ b/posthog/hogql/database/schema/session_replay_events.py
@@ -2,6 +2,12 @@ from datetime import datetime
from posthog.hogql.ast import JoinExpr, SelectQuery
from posthog.hogql.context import HogQLContext
+from posthog.hogql.database.lazy_join_tags import (
+ PERSON_DISTINCT_IDS,
+ REPLAY_TO_CONSOLE_LOGS,
+ REPLAY_TO_EVENTS,
+ REPLAY_TO_SESSIONS_V1,
+)
from posthog.hogql.database.models import (
DatabaseField,
DateTimeDatabaseField,
@@ -17,10 +23,7 @@ from posthog.hogql.database.models import (
)
from posthog.hogql.database.schema.events import EventsTable
from posthog.hogql.database.schema.log_entries import ReplayConsoleLogsLogEntriesTable
-from posthog.hogql.database.schema.person_distinct_ids import (
- PersonDistinctIdsTable,
- join_with_person_distinct_ids_table,
-)
+from posthog.hogql.database.schema.person_distinct_ids import PersonDistinctIdsTable
from posthog.hogql.database.schema.sessions_v1 import SessionsTableV1, select_from_sessions_table_v1
from posthog.hogql.database.schema.sessions_v2 import (
select_from_sessions_table_v2,
@@ -215,26 +218,26 @@ SESSION_REPLAY_EVENTS_COMMON_FIELDS: dict[str, FieldOrTable] = {
"events": LazyJoin(
from_field=["session_id"],
join_table=EventsTable(),
- join_function=join_with_events_table,
+ resolver=REPLAY_TO_EVENTS,
),
# this is so that HogQL properties e.g. on test account filters can find the correct column
"properties": FieldTraverser(chain=["events", "properties"]),
"pdi": LazyJoin(
from_field=["distinct_id"],
join_table=PersonDistinctIdsTable(),
- join_function=join_with_person_distinct_ids_table,
+ resolver=PERSON_DISTINCT_IDS,
),
"console_logs": LazyJoin(
from_field=["session_id"],
join_table=ReplayConsoleLogsLogEntriesTable(),
- join_function=join_with_console_logs_log_entries_table,
+ resolver=REPLAY_TO_CONSOLE_LOGS,
),
"person": FieldTraverser(chain=["pdi", "person"]),
"person_id": FieldTraverser(chain=["pdi", "person_id"]),
"session": LazyJoin(
from_field=["session_id"],
join_table=SessionsTableV1(),
- join_function=join_replay_table_to_sessions_table_v1,
+ resolver=REPLAY_TO_SESSIONS_V1,
),
}
diff --git a/posthog/hogql/database/schema/static_cohort_people.py b/posthog/hogql/database/schema/static_cohort_people.py
index 86b71ad20793..b9a3173e9611 100644
--- a/posthog/hogql/database/schema/static_cohort_people.py
+++ b/posthog/hogql/database/schema/static_cohort_people.py
@@ -1,5 +1,5 @@
+from posthog.hogql.database.lazy_join_tags import PERSONS
from posthog.hogql.database.models import FieldOrTable, IntegerDatabaseField, LazyJoin, StringDatabaseField, Table
-from posthog.hogql.database.schema.persons import join_with_persons_table
class StaticCohortPeople(Table):
@@ -10,7 +10,7 @@ class StaticCohortPeople(Table):
"person": LazyJoin(
from_field=["person_id"],
join_table="persons",
- join_function=join_with_persons_table,
+ resolver=PERSONS,
),
}
diff --git a/posthog/hogql/database/schema/util/test/test_predicate_pushdown.py b/posthog/hogql/database/schema/util/test/test_predicate_pushdown.py
index 94d2cc32194d..fd3cced99b5a 100644
--- a/posthog/hogql/database/schema/util/test/test_predicate_pushdown.py
+++ b/posthog/hogql/database/schema/util/test/test_predicate_pushdown.py
@@ -4,6 +4,7 @@ from parameterized import parameterized
from posthog.hogql import ast
from posthog.hogql.context import HogQLContext
+from posthog.hogql.database.lazy_join_tags import FOREIGN_KEY
from posthog.hogql.database.models import LazyJoin
from posthog.hogql.database.schema.events import EventsTable
from posthog.hogql.database.schema.util.where_clause_extractor import (
@@ -35,7 +36,7 @@ def make_lazy_join_type(field: str) -> ast.LazyJoinType:
return ast.LazyJoinType(
table_type=make_events_table_type(),
field=field,
- lazy_join=LazyJoin(from_field=["id"], join_table=EventsTable(), join_function=lambda *args: None),
+ lazy_join=LazyJoin(from_field=["id"], join_table=EventsTable(), resolver=FOREIGN_KEY),
)
diff --git a/posthog/hogql/database/test/test_database.py b/posthog/hogql/database/test/test_database.py
index 753b8e940189..3173012b9300 100644
--- a/posthog/hogql/database/test/test_database.py
+++ b/posthog/hogql/database/test/test_database.py
@@ -28,6 +28,7 @@ from posthog.hogql.database.database import (
get_data_warehouse_table_name,
)
from posthog.hogql.database.direct_postgres_table import DirectPostgresTable
+from posthog.hogql.database.lazy_join_tags import FOREIGN_KEY
from posthog.hogql.database.models import (
DANGEROUS_NoTeamIdCheckTable,
ExpressionField,
@@ -133,7 +134,7 @@ class TestDatabase(BaseTest, QueryMatchingTest):
from_field=["dashboard_id"],
to_field=["id"],
join_table="direct_table",
- join_function=lambda *_args: None,
+ resolver=FOREIGN_KEY,
)
},
postgres_table_name="events",
diff --git a/posthog/hogql/database/test/test_lazy_join_resolvers.py b/posthog/hogql/database/test/test_lazy_join_resolvers.py
new file mode 100644
index 000000000000..0a8763895acc
--- /dev/null
+++ b/posthog/hogql/database/test/test_lazy_join_resolvers.py
@@ -0,0 +1,207 @@
+import json
+from collections.abc import Iterator
+
+from posthog.test.base import BaseTest
+
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
+from posthog.schema import HogQLQueryModifiers, PersonsOnEventsMode, SessionTableVersion
+
+from posthog.hogql import ast
+from posthog.hogql.context import HogQLContext
+from posthog.hogql.database.database import Database
+from posthog.hogql.database.lazy_join_registry import RESOLVERS
+from posthog.hogql.database.lazy_join_tags import DATA_WAREHOUSE, DATA_WAREHOUSE_EXPERIMENTS, GROUP_N
+from posthog.hogql.database.models import LazyJoin, LazyJoinToAdd, Table, TableNode
+from posthog.hogql.database.schema.groups import join_with_group_n_table
+from posthog.hogql.database.warehouse_join_resolvers import (
+ data_warehouse_resolver_params,
+ resolve_data_warehouse_experiments_join,
+)
+from posthog.hogql.errors import ResolutionError
+
+from products.data_tools.backend.models.join import DataWarehouseJoin
+
+
+class TestLazyJoinResolvers(SimpleTestCase):
+ def test_resolver_params_applies_overrides(self):
+ params = data_warehouse_resolver_params(
+ source_table_key="id",
+ joining_table_key="account_id",
+ joining_table_name="events",
+ override_source_table_key="person.id",
+ override_join_type="INNER JOIN",
+ )
+
+ assert params["source_table_key"] == "person.id"
+ assert params["join_type"] == "INNER JOIN"
+ assert params["configuration"] == {}
+
+ def test_unknown_resolver_raises(self):
+ lazy_join = LazyJoin(from_field=["id"], join_table="x", resolver="does_not_exist")
+ with self.assertRaises(ValueError):
+ lazy_join.resolve_join_to_add(None, None, None) # type: ignore[arg-type]
+
+ def test_group_n_join_requires_group_index(self):
+ lazy_join = LazyJoin(from_field=["key"], join_table="groups", resolver=GROUP_N)
+ join_to_add = LazyJoinToAdd(
+ from_table="events",
+ to_table="group_0",
+ lazy_join=lazy_join,
+ lazy_join_type=None, # type: ignore[arg-type]
+ fields_accessed={"key": ["key"]},
+ )
+ with self.assertRaises(ResolutionError):
+ join_with_group_n_table(join_to_add, HogQLContext(team_id=1), ast.SelectQuery(select=[]))
+
+ def test_experiments_join_builds_asof_join_with_timestamp_bounds(self):
+ lazy_join = LazyJoin(
+ from_field=["id"],
+ join_table="events",
+ resolver=DATA_WAREHOUSE_EXPERIMENTS,
+ resolver_params=data_warehouse_resolver_params(
+ source_table_key="user_id",
+ joining_table_key="distinct_id",
+ joining_table_name="events",
+ configuration={"experiments_optimized": True, "experiments_timestamp_key": "created_at"},
+ ),
+ )
+ join_to_add = LazyJoinToAdd(
+ from_table="subscriptions",
+ to_table="events",
+ lazy_join=lazy_join,
+ lazy_join_type=None, # type: ignore[arg-type]
+ fields_accessed={"distinct_id": ["distinct_id"]},
+ )
+
+ def timestamp_bound(op: ast.CompareOperationOp, value: str) -> ast.CompareOperation:
+ return ast.CompareOperation(
+ op=op,
+ left=ast.Alias(alias="created_at", expr=ast.Field(chain=["subscriptions", "created_at"])),
+ right=ast.Constant(value=value),
+ )
+
+ node = ast.SelectQuery(
+ select=[],
+ where=ast.And(
+ exprs=[
+ timestamp_bound(ast.CompareOperationOp.GtEq, "2023-01-01"),
+ timestamp_bound(ast.CompareOperationOp.LtEq, "2023-02-01"),
+ ]
+ ),
+ )
+
+ join_expr = resolve_data_warehouse_experiments_join(join_to_add, HogQLContext(team_id=1), node)
+
+ assert join_expr.join_type == "ASOF LEFT JOIN"
+ assert isinstance(join_expr.table, ast.SelectQuery)
+ assert isinstance(join_expr.table.where, ast.And)
+ # The subquery filters to exposure events and copies the query's timestamp bounds in,
+ # since the subquery can't reference the parent data warehouse table directly.
+ flag_filter, *bounds = join_expr.table.where.exprs
+ assert isinstance(flag_filter, ast.CompareOperation)
+ assert isinstance(flag_filter.right, ast.Constant)
+ assert flag_filter.right.value == "$feature_flag_called"
+ bound_values = [
+ (b.op, b.right.value)
+ for b in bounds
+ if isinstance(b, ast.CompareOperation) and isinstance(b.right, ast.Constant)
+ ]
+ assert bound_values == [
+ (ast.CompareOperationOp.GtEq, "2023-01-01"),
+ (ast.CompareOperationOp.LtEq, "2023-02-01"),
+ ]
+
+
+def _walk_lazy_joins(database: Database) -> Iterator[tuple[str, LazyJoin]]:
+ """Yield every LazyJoin reachable from the database's table tree, with its path for error messages."""
+ seen: set[int] = set()
+
+ def walk_field_or_table(path: str, item: object) -> Iterator[tuple[str, LazyJoin]]:
+ if id(item) in seen:
+ return
+ seen.add(id(item))
+ if isinstance(item, LazyJoin):
+ yield path, item
+ if isinstance(item.join_table, Table):
+ yield from walk_field_or_table(f"{path}.<join_table>", item.join_table)
+ elif isinstance(item, Table):
+ for name, field in item.fields.items():
+ yield from walk_field_or_table(f"{path}.{name}", field)
+
+ def walk_node(path: str, node: TableNode) -> Iterator[tuple[str, LazyJoin]]:
+ if node.table is not None:
+ yield from walk_field_or_table(path, node.table)
+ for name, child in node.children.items():
+ yield from walk_node(f"{path}.{name}", child)
+
+ yield from walk_node("", database.tables)
+
+
+class TestBuiltDatabaseSerializable(BaseTest):
+ """The serializability gate: a built Database must describe every lazy join as plain data —
+ a tag listed in the resolver manifest plus JSON-able params."""
+
+ @parameterized.expand(
+ [
+ ("default", HogQLQueryModifiers()),
+ ("sessions_v3", HogQLQueryModifiers(sessionTableVersion=SessionTableVersion.V3)),
+ (
+ "poe_overrides_joined",
+ HogQLQueryModifiers(personsOnEventsMode=PersonsOnEventsMode.PERSON_ID_OVERRIDE_PROPERTIES_JOINED),
+ ),
+ ]
+ )
+ def test_built_database_lazy_joins_are_serializable(self, _name: str, modifiers: HogQLQueryModifiers) -> None:
+ # A user-defined join, so the walk also covers the data-warehouse attachment path —
+ # the one category whose resolver_params are built from user data at build time.
+ DataWarehouseJoin(
+ team=self.team,
+ source_table_name="cohort_people",
+ source_table_key="person_id",
+ joining_table_name="persons",
+ joining_table_key="id",
+ field_name="new_person",
+ ).save()
+
+ database = Database.create_for(team=self.team, modifiers=modifiers)
+
+ lazy_joins = list(_walk_lazy_joins(database))
+ assert len(lazy_joins) > 15 # sanity: the walker actually reached the schema's joins
+ assert any(lj.resolver == DATA_WAREHOUSE for _, lj in lazy_joins) # the user-defined join got attached
+
+ for path, lazy_join in lazy_joins:
+ assert lazy_join.resolver in RESOLVERS, f"{path} resolver {lazy_join.resolver!r} is not in the manifest"
+ json.dumps(lazy_join.resolver_params) # params must round-trip through JSON
+
+
+class TestLazyJoinManifest(SimpleTestCase):
+ def test_manifest_is_the_explicit_contract(self):
+ """The manifest is the closed contract a serialized Database depends on. Changing this
+ list changes what consumers of a serialized schema must implement — update deliberately."""
+ assert sorted(RESOLVERS) == [
+ "account_notebooks",
+ "account_tags",
+ "data_warehouse",
+ "data_warehouse_experiments",
+ "error_tracking_fingerprint_issue_state",
+ "error_tracking_issue_fingerprint_overrides",
+ "events_to_sessions_v1",
+ "events_to_sessions_v2",
+ "events_to_sessions_v3",
+ "foreign_key",
+ "group_n",
+ "groups_revenue_analytics",
+ "person_distinct_id_overrides",
+ "person_distinct_ids",
+ "persons",
+ "persons_pdi",
+ "persons_revenue_analytics",
+ "replay_to_console_logs",
+ "replay_to_events",
+ "replay_to_sessions_v1",
+ "replay_to_sessions_v2",
+ "replay_to_sessions_v3",
+ ]
diff --git a/posthog/hogql/database/test/test_postgres_table.py b/posthog/hogql/database/test/test_postgres_table.py
index 0e9f3845cd4a..df50b1261a3f 100644
--- a/posthog/hogql/database/test/test_postgres_table.py
+++ b/posthog/hogql/database/test/test_postgres_table.py
@@ -10,11 +10,11 @@ from parameterized import parameterized
from posthog.hogql.context import HogQLContext
from posthog.hogql.database.database import Database
+from posthog.hogql.database.lazy_join_tags import FOREIGN_KEY
from posthog.hogql.database.models import (
DateTimeDatabaseField,
IntegerDatabaseField,
LazyJoin,
- LazyJoinToAdd,
StringDatabaseField,
StringJSONDatabaseField,
TableNode,
@@ -278,25 +278,6 @@ class TestPostgresTable(BaseTest):
)
def test_lazy_join_with_predicate(self):
- from posthog.hogql import ast
-
- def join_fn(join_to_add: LazyJoinToAdd, context: HogQLContext, node: ast.SelectQuery):
- table = join_to_add.lazy_join.join_table
- table_name = table if isinstance(table, str) else table.name
- assert table_name is not None
- join_expr = ast.JoinExpr(table=ast.Field(chain=[table_name]))
- join_expr.join_type = "LEFT JOIN"
- join_expr.alias = join_to_add.to_table
- join_expr.constraint = ast.JoinConstraint(
- expr=ast.CompareOperation(
- op=ast.CompareOperationOp.Eq,
- left=ast.Field(chain=[join_to_add.from_table, "ref_id"]),
- right=ast.Field(chain=[join_to_add.to_table, "id"]),
- ),
- constraint_type="ON",
- )
- return join_expr
-
self.database = Database.create_for(team=self.team)
pg_table = PostgresTable(
@@ -324,8 +305,9 @@ class TestPostgresTable(BaseTest):
"ref_id": IntegerDatabaseField(name="ref_id"),
"details": LazyJoin(
from_field=["ref_id"],
+ to_field=["id"],
join_table=pg_table,
- join_function=join_fn,
+ resolver=FOREIGN_KEY,
),
},
),
@@ -345,7 +327,7 @@ class TestPostgresTable(BaseTest):
)
self.assertEqual(
self._select("SELECT details.name FROM other_table LIMIT 10"),
- f"SELECT other_table__details.name AS name FROM postgresql(%(hogql_val_1_sensitive)s, %(hogql_val_2_sensitive)s, %(hogql_val_0_sensitive)s, %(hogql_val_3_sensitive)s, %(hogql_val_4_sensitive)s) AS other_table LEFT JOIN postgresql(%(hogql_val_6_sensitive)s, %(hogql_val_7_sensitive)s, %(hogql_val_5_sensitive)s, %(hogql_val_8_sensitive)s, %(hogql_val_9_sensitive)s) AS other_table__details ON and(and(equals(other_table__details.team_id, {self.team.pk}), greaterOrEquals(other_table__details.created_at, minus(today(), toIntervalDay(30)))), equals(other_table.ref_id, other_table__details.id)) WHERE equals(other_table.team_id, {self.team.pk}) LIMIT 10",
+ f"SELECT other_table__details.name AS name FROM postgresql(%(hogql_val_1_sensitive)s, %(hogql_val_2_sensitive)s, %(hogql_val_0_sensitive)s, %(hogql_val_3_sensitive)s, %(hogql_val_4_sensitive)s) AS other_table LEFT JOIN (SELECT postgres_table.name AS name, postgres_table.id AS other_table__details___id FROM postgresql(%(hogql_val_6_sensitive)s, %(hogql_val_7_sensitive)s, %(hogql_val_5_sensitive)s, %(hogql_val_8_sensitive)s, %(hogql_val_9_sensitive)s) AS postgres_table WHERE and(equals(postgres_table.team_id, {self.team.pk}), greaterOrEquals(postgres_table.created_at, minus(today(), toIntervalDay(30))))) AS other_table__details ON equals(other_table.ref_id, other_table__details.other_table__details___id) WHERE equals(other_table.team_id, {self.team.pk}) LIMIT 10",
)
def test_predicate_with_nested_property_access(self):
diff --git a/posthog/hogql/database/warehouse_join_resolvers.py b/posthog/hogql/database/warehouse_join_resolvers.py
new file mode 100644
index 000000000000..12d54a5b8e7b
--- /dev/null
+++ b/posthog/hogql/database/warehouse_join_resolvers.py
@@ -0,0 +1,196 @@
+from typing import Any, cast
+
+from posthog.hogql import ast
+from posthog.hogql.context import HogQLContext
+from posthog.hogql.database.models import LazyJoinToAdd
+from posthog.hogql.database.utils import qualify_join_key_expr
+from posthog.hogql.errors import ResolutionError
+
+
+def _qualified_key_expr(table_key: str, table_name: str) -> ast.Expr:
+ expr = qualify_join_key_expr(table_key, table_name)
+ if expr is None:
+ raise ResolutionError("Data Warehouse Join HogQL expression should be a Field or Call node")
+ return expr
+
+
+def resolve_foreign_key_join(join_to_add: LazyJoinToAdd, context: HogQLContext, node: ast.SelectQuery) -> ast.JoinExpr:
+ lazy_join = join_to_add.lazy_join
+ join_table = lazy_join.resolve_table(context)
+
+ if isinstance(join_table.name, str):
+ join_table_chain = cast(list[str | int], join_table.name.split("."))
+ else:
+ join_table_chain = [join_to_add.to_table]
+
+ if not join_to_add.fields_accessed:
+ raise ResolutionError(f"No fields requested from {join_to_add.to_table}")
+
+ left = ast.Field(chain=[join_to_add.from_table, *lazy_join.from_field])
+ right = ast.Field(chain=[join_to_add.to_table, *(lazy_join.to_field or [])])
+
+ return ast.JoinExpr(
+ table=ast.SelectQuery(
+ select=[
+ ast.Alias(alias=alias, expr=ast.Field(chain=chain))
+ for alias, chain in join_to_add.fields_accessed.items()
+ ],
+ select_from=ast.JoinExpr(table=ast.Field(chain=join_table_chain)),
+ ),
+ join_type="LEFT JOIN",
+ alias=join_to_add.to_table,
+ constraint=ast.JoinConstraint(
+ expr=ast.CompareOperation(op=ast.CompareOperationOp.Eq, left=left, right=right),
+ constraint_type="ON",
+ ),
+ )
+
+
+def resolve_data_warehouse_join(
+ join_to_add: LazyJoinToAdd, context: HogQLContext, node: ast.SelectQuery
+) -> ast.JoinExpr:
+ params = join_to_add.lazy_join.resolver_params
+
+ if not join_to_add.fields_accessed:
+ raise ResolutionError(f"No fields requested from {join_to_add.to_table}")
+
+ left = _qualified_key_expr(params["source_table_key"], join_to_add.from_table)
+ right = _qualified_key_expr(params["joining_table_key"], join_to_add.to_table)
+
+ return ast.JoinExpr(
+ table=ast.SelectQuery(
+ select=[
+ ast.Alias(alias=alias, expr=ast.Field(chain=chain))
+ for alias, chain in join_to_add.fields_accessed.items()
+ ],
+ select_from=ast.JoinExpr(
+ table=ast.Field(chain=cast(list[str | int], str(params["joining_table_name"]).split(".")))
+ ),
+ ),
+ join_type=params.get("join_type") or "LEFT JOIN",
+ alias=join_to_add.to_table,
+ constraint=ast.JoinConstraint(
+ expr=ast.CompareOperation(op=ast.CompareOperationOp.Eq, left=left, right=right),
+ constraint_type="ON",
+ ),
+ )
+
+
+def resolve_data_warehouse_experiments_join(
+ join_to_add: LazyJoinToAdd, context: HogQLContext, node: ast.SelectQuery
+) -> ast.JoinExpr:
+ params = join_to_add.lazy_join.resolver_params
+
+ configuration = params.get("configuration")
+ if not isinstance(configuration, dict):
+ raise ResolutionError("experiments_optimized is not configured for this join")
+
+ if params["joining_table_name"] != "events":
+ raise ResolutionError("experiments_optimized is only supported for events table")
+
+ if not configuration.get("experiments_optimized"):
+ raise ResolutionError("experiments_optimized is not enabled for this join")
+
+ timestamp_key = configuration.get("experiments_timestamp_key")
+ if not isinstance(timestamp_key, str) or not timestamp_key:
+ raise ResolutionError("experiments_timestamp_key is not set for this join")
+
+ left = _qualified_key_expr(params["source_table_key"], join_to_add.from_table)
+ right = _qualified_key_expr(params["joining_table_key"], join_to_add.to_table)
+
+ where_exprs: list[ast.Expr] = [
+ ast.CompareOperation(
+ op=ast.CompareOperationOp.Eq,
+ left=ast.Field(chain=["event"]),
+ right=ast.Constant(value="$feature_flag_called"),
+ )
+ ]
+ # :HACK: We need to pull the timestamp gt/lt values from node.where.exprs because
+ # we can't reference the parent data warehouse table in the where clause.
+ if node.where and hasattr(node.where, "exprs"):
+ for expr in node.where.exprs:
+ if isinstance(expr, ast.CompareOperation):
+ if expr.op == ast.CompareOperationOp.GtEq or expr.op == ast.CompareOperationOp.LtEq:
+ # Match within hogql string because it could be 'toDateTime(timestamp)'
+ if isinstance(expr.left, ast.Alias) and timestamp_key in expr.left.expr.to_hogql():
+ where_exprs.append(
+ ast.CompareOperation(op=expr.op, left=ast.Field(chain=["timestamp"]), right=expr.right)
+ )
+
+ return ast.JoinExpr(
+ table=ast.SelectQuery(
+ select=[
+ ast.Alias(
+ alias=name,
+ expr=ast.Field(chain=["events", *(chain if isinstance(chain, list | tuple) else [chain])]),
+ )
+ for name, chain in {
+ **join_to_add.fields_accessed,
+ "event": ["event"],
+ "timestamp": ["timestamp"],
+ "distinct_id": ["distinct_id"],
+ "properties": ["properties"],
+ }.items()
+ ],
+ select_from=ast.JoinExpr(table=ast.Field(chain=["events"])),
+ where=ast.And(exprs=where_exprs),
+ ),
+ # ASOF JOIN finds the most recent matching event that occurred at or before each data warehouse timestamp.
+ #
+ # Why this matters:
+ # When a user performs an action (recorded in data warehouse), we want to know which
+ # experiment variant they were assigned at that moment. The most recent $feature_flag_called
+ # event before their action represents their active variant assignment.
+ #
+ # Example:
+ # Data Warehouse: timestamp=2024-01-03 12:00, distinct_id=user1
+ # Events:
+ # 2024-01-02: (user1, variant='control') <- This event will be joined
+ # 2024-01-03: (user1, variant='test') <- Ignored (occurs after data warehouse timestamp)
+ #
+ # This ensures we capture the correct causal relationship: which experiment variant
+ # was the user assigned to when they performed the action?
+ join_type="ASOF LEFT JOIN",
+ alias=join_to_add.to_table,
+ constraint=ast.JoinConstraint(
+ expr=ast.And(
+ exprs=[
+ ast.CompareOperation(
+ left=ast.Field(chain=[join_to_add.to_table, "event"]),
+ op=ast.CompareOperationOp.Eq,
+ right=ast.Constant(value="$feature_flag_called"),
+ ),
+ ast.CompareOperation(
+ left=left,
+ op=ast.CompareOperationOp.Eq,
+ right=right,
+ ),
+ ast.CompareOperation(
+ left=ast.Field(chain=[join_to_add.from_table, timestamp_key]),
+ op=ast.CompareOperationOp.GtEq,
+ right=ast.Field(chain=[join_to_add.to_table, "timestamp"]),
+ ),
+ ]
+ ),
+ constraint_type="ON",
+ ),
+ )
+
+
+def data_warehouse_resolver_params(
+ *,
+ source_table_key: str,
+ joining_table_key: str,
+ joining_table_name: str,
+ configuration: dict | None = None,
+ override_source_table_key: str | None = None,
+ override_join_type: str | None = None,
+) -> dict[str, Any]:
+ """Build the serializable params the data-warehouse registry resolvers read back at resolution time."""
+ return {
+ "source_table_key": override_source_table_key or source_table_key,
+ "joining_table_key": joining_table_key,
+ "joining_table_name": joining_table_name,
+ "join_type": override_join_type,
+ "configuration": configuration if isinstance(configuration, dict) else {},
+ }
diff --git a/posthog/hogql/test/__snapshots__/test_resolver.ambr b/posthog/hogql/test/__snapshots__/test_resolver.ambr
index 2e4d62af3411..efbe75ddf0dc 100644
--- a/posthog/hogql/test/__snapshots__/test_resolver.ambr
+++ b/posthog/hogql/test/__snapshots__/test_resolver.ambr
@@ -328,7 +328,6 @@
"fingerprint"
],
hidden: False,
- join_function: <function>,
join_table: {
fields: {
assigned_role_id: {
@@ -367,6 +366,8 @@
top_level_settings: None,
workload: None
},
+ resolver: "error_tracking_fingerprint_issue_state",
+ resolver_params: {},
to_field: None
}
table_type: <recursion ...>
@@ -387,7 +388,6 @@
"fingerprint"
],
hidden: False,
- join_function: <function>,
join_table: {
fields: {
assigned_role_id: {
@@ -426,6 +426,8 @@
top_level_settings: None,
workload: None
},
+ resolver: "error_tracking_fingerprint_issue_state",
+ resolver_params: {},
to_field: None
}
table_type: <recursion ...>
@@ -446,7 +448,6 @@
"fingerprint"
],
hidden: False,
- join_function: <function>,
join_table: {
fields: {
assigned_role_id: {
@@ -485,6 +486,8 @@
top_level_settings: None,
workload: None
},
+ resolver: "error_tracking_fingerprint_issue_state",
+ resolver_params: {},
to_field: None
}
table_type: <recursion ...>
@@ -505,7 +508,6 @@
"fingerprint"
],
hidden: False,
- join_function: <function>,
join_table: {
fields: {
assigned_role_id: {
@@ -544,6 +546,8 @@
top_level_settings: None,
workload: None
},
+ resolver: "error_tracking_fingerprint_issue_state",
+ resolver_params: {},
to_field: None
}
table_type: <recursion ...>
@@ -588,7 +592,6 @@
"fingerprint"
],
hidden: False,
- join_function: <function>,
join_table: {
fields: {
assigned_role_id: {
@@ -627,6 +630,8 @@
top_level_settings: None,
workload: None
},
+ resolver: "error_tracking_fingerprint_issue_state",
+ resolver_params: {},
to_field: None
}
table_type: <recursion ...>
@@ -647,7 +652,6 @@
"fingerprint"
],
hidden: False,
- join_function: <function>,
join_table: {
fields: {
assigned_role_id: {
@@ -686,6 +690,8 @@
top_level_settings: None,
workload: None
},
+ resolver: "error_tracking_fingerprint_issue_state",
+ resolver_params: {},
to_field: None
}
table_type: <recursion ...>
@@ -706,7 +712,6 @@
"fingerprint"
],
hidden: False,
- join_function: <function>,
join_table: {
fields: {
assigned_role_id: {
@@ -745,6 +750,8 @@
top_level_settings: None,
workload: None
},
+ resolver: "error_tracking_fingerprint_issue_state",
+ resolver_params: {},
to_field: None
}
table_type: <recursion ...>
@@ -1530,7 +1537,6 @@
"distinct_id"
],
hidden: False,
- join_function: <function>,
join_table: {
fields: {
distinct_id: {
@@ -1551,6 +1557,8 @@
top_level_settings: None,
workload: None
},
+ resolver: "person_distinct_id_overrides",
+ resolver_params: {},
to_field: None
}
table_type: <recursion ...>
@@ -1609,7 +1617,6 @@
"distinct_id"
],
hidden: False,
- join_function: <function>,
join_table: {
fields: {
distinct_id: {
@@ -1630,6 +1637,8 @@
top_level_settings: None,
workload: None
},
+ resolver: "person_distinct_id_overrides",
+ resolver_params: {},
to_field: None
}
table_type: <recursion ...>
@@ -1868,7 +1877,6 @@
"fingerprint"
],
hidden: False,
- join_function: <function>,
join_table: {
fields: {
fingerprint: {
@@ -1886,6 +1894,8 @@
top_level_settings: None,
workload: None
},
+ resolver: "error_tracking_issue_fingerprint_overrides",
+ resolver_params: {},
to_field: None
}
table_type: <recursion ...>
@@ -1944,7 +1954,6 @@
"fingerprint"
],
hidden: False,
- join_function: <function>,
join_table: {
fields: {
fingerprint: {
@@ -1962,6 +1971,8 @@
top_level_settings: None,
workload: None
},
+ resolver: "error_tracking_issue_fingerprint_overrides",
+ resolver_params: {},
to_field: None
}
table_type: <recursion ...>
@@ -2630,7 +2641,6 @@
"distinct_id"
],
hidden: False,
- join_function: <function>,
join_table: {
fields: {
distinct_id: {
@@ -2651,6 +2661,8 @@
top_level_settings: None,
workload: None
},
+ resolver: "person_distinct_id_overrides",
+ resolver_params: {},
to_field: None
}
table_type: <recursion ...>
@@ -2712,7 +2724,6 @@
"distinct_id"
],
hidden: False,
- join_function: <function>,
join_table: {
fields: {
distinct_id: {
@@ -2733,6 +2744,8 @@
top_level_settings: None,
workload: None
},
+ resolver: "person_distinct_id_overrides",
+ resolver_params: {},
to_field: None
}
table_type: <recursion ...>
@@ -3066,7 +3079,6 @@
"fingerprint"
],
hidden: False,
- join_function: <function>,
join_table: {
fields: {
fingerprint: {
@@ -3084,6 +3096,8 @@
top_level_settings: None,
workload: None
},
+ resolver: "error_tracking_issue_fingerprint_overrides",
+ resolver_params: {},
to_field: None
}
table_type: <recursion ...>
@@ -3145,7 +3159,6 @@
"fingerprint"
],
hidden: False,
- join_function: <function>,
join_table: {
fields: {
fingerprint: {
@@ -3163,6 +3176,8 @@
top_level_settings: None,
workload: None
},
+ resolver: "error_tracking_issue_fingerprint_overrides",
+ resolver_params: {},
to_field: None
}
table_type: <recursion ...>
@@ -3278,7 +3293,6 @@
"fingerprint"
],
hidden: False,
- join_function: <function>,
join_table: {
fields: {
assigned_role_id: {
@@ -3317,6 +3331,8 @@
top_level_settings: None,
workload: None
},
+ resolver: "error_tracking_fingerprint_issue_state",
+ resolver_params: {},
to_field: None
}
table_type: <recursion ...>
@@ -3356,7 +3372,6 @@
"fingerprint"
],
hidden: False,
- join_function: <function>,
join_table: {
fields: {
assigned_role_id: {
@@ -3395,6 +3410,8 @@
top_level_settings: None,
workload: None
},
+ resolver: "error_tracking_fingerprint_issue_state",
+ resolver_params: {},
to_field: None
}
table_type: <recursion ...>
@@ -3434,7 +3451,6 @@
"fingerprint"
],
hidden: False,
- join_function: <function>,
join_table: {
fields: {
assigned_role_id: {
@@ -3473,6 +3489,8 @@
top_level_settings: None,
workload: None
},
+ resolver: "error_tracking_fingerprint_issue_state",
+ resolver_params: {},
to_field: None
}
table_type: <recursion ...>
@@ -3512,7 +3530,6 @@
"fingerprint"
],
hidden: False,
- join_function: <function>,
join_table: {
fields: {
assigned_role_id: {
@@ -3551,6 +3568,8 @@
top_level_settings: None,
workload: None
},
+ resolver: "error_tracking_fingerprint_issue_state",
+ resolver_params: {},
to_field: None
}
table_type: <recursion ...>
@@ -3590,7 +3609,6 @@
"fingerprint"
],
hidden: False,
- join_function: <function>,
join_table: {
fields: {
assigned_role_id: {
@@ -3629,6 +3647,8 @@
top_level_settings: None,
workload: None
},
+ resolver: "error_tracking_fingerprint_issue_state",
+ resolver_params: {},
to_field: None
}
table_type: <recursion ...>
@@ -3668,7 +3688,6 @@
"fingerprint"
],
hidden: False,
- join_function: <function>,
join_table: {
fields: {
assigned_role_id: {
@@ -3707,6 +3726,8 @@
top_level_settings: None,
workload: None
},
+ resolver: "error_tracking_fingerprint_issue_state",
+ resolver_params: {},
to_field: None
}
table_type: <recursion ...>
@@ -3746,7 +3767,6 @@
"fingerprint"
],
hidden: False,
- join_function: <function>,
join_table: {
fields: {
assigned_role_id: {
@@ -3785,6 +3805,8 @@
top_level_settings: None,
workload: None
},
+ resolver: "error_tracking_fingerprint_issue_state",
+ resolver_params: {},
to_field: None
}
table_type: <recursion ...>
@@ -5256,7 +5278,6 @@
"fingerprint"
],
hidden: False,
- join_function: <function>,
join_table: {
fields: {
assigned_role_id: {
@@ -5295,6 +5316,8 @@
top_level_settings: None,
workload: None
},
+ resolver: "error_tracking_fingerprint_issue_state",
+ resolver_params: {},
to_field: None
}
table_type: <recursion ...>
@@ -5315,7 +5338,6 @@
"fingerprint"
],
hidden: False,
- join_function: <function>,
join_table: {
fields: {
assigned_role_id: {
@@ -5354,6 +5376,8 @@
top_level_settings: None,
workload: None
},
+ resolver: "error_tracking_fingerprint_issue_state",
+ resolver_params: {},
to_field: None
}
table_type: <recursion ...>
@@ -5374,7 +5398,6 @@
"fingerprint"
],
hidden: False,
- join_function: <function>,
join_table: {
fields: {
assigned_role_id: {
@@ -5413,6 +5436,8 @@
top_level_settings: None,
workload: None
},
+ resolver: "error_tracking_fingerprint_issue_state",
+ resolver_params: {},
to_field: None
}
table_type: <recursion ...>
@@ -5433,7 +5458,6 @@
"fingerprint"
],
hidden: False,
- join_function: <function>,
join_table: {
fields: {
assigned_role_id: {
@@ -5472,6 +5496,8 @@
top_level_settings: None,
workload: None
},
+ resolver: "error_tracking_fingerprint_issue_state",
+ resolver_params: {},
to_field: None
}
table_type: <recursion ...>
@@ -5516,7 +5542,6 @@
"fingerprint"
],
hidden: False,
- join_function: <function>,
join_table: {
fields: {
assigned_role_id: {
@@ -5555,6 +5580,8 @@
top_level_settings: None,
workload: None
},
+ resolver: "error_tracking_fingerprint_issue_state",
+ resolver_params: {},
to_field: None
}
table_type: <recursion ...>
@@ -5575,7 +5602,6 @@
"fingerprint"
],
hidden: False,
- join_function: <function>,
join_table: {
fields: {
assigned_role_id: {
@@ -5614,6 +5640,8 @@
top_level_settings: None,
workload: None
},
+ resolver: "error_tracking_fingerprint_issue_state",
+ resolver_params: {},
to_field: None
}
table_type: <recursion ...>
@@ -5634,7 +5662,6 @@
"fingerprint"
],
hidden: False,
- join_function: <function>,
join_table: {
fields: {
assigned_role_id: {
@@ -5673,6 +5700,8 @@
top_level_settings: None,
workload: None
},
+ resolver: "error_tracking_fingerprint_issue_state",
+ resolver_params: {},
to_field: None
}
table_type: <recursion ...>
@@ -6459,7 +6488,6 @@
"distinct_id"
],
hidden: False,
- join_function: <function>,
join_table: {
fields: {
distinct_id: {
@@ -6480,6 +6508,8 @@
top_level_settings: None,
workload: None
},
+ resolver: "person_distinct_id_overrides",
+ resolver_params: {},
to_field: None
}
table_type: <recursion ...>
@@ -6538,7 +6568,6 @@
"distinct_id"
],
hidden: False,
- join_function: <function>,
join_table: {
fields: {
distinct_id: {
@@ -6559,6 +6588,8 @@
top_level_settings: None,
workload: None
},
+ resolver: "person_distinct_id_overrides",
+ resolver_params: {},
to_field: None
}
table_type: <recursion ...>
@@ -6797,7 +6828,6 @@
"fingerprint"
],
hidden: False,
- join_function: <function>,
join_table: {
fields: {
fingerprint: {
@@ -6815,6 +6845,8 @@
top_level_settings: None,
workload: None
},
+ resolver: "error_tracking_issue_fingerprint_overrides",
+ resolver_params: {},
to_field: None
}
table_type: <recursion ...>
@@ -6873,7 +6905,6 @@
"fingerprint"
],
hidden: False,
- join_function: <function>,
join_table: {
fields: {
fingerprint: {
@@ -6891,6 +6922,8 @@
top_level_settings: None,
workload: None
},
+ resolver: "error_tracking_issue_fingerprint_overrides",
+ resolver_params: {},
to_field: None
}
table_type: <recursion ...>
@@ -7510,7 +7543,6 @@
"distinct_id"
],
hidden: False,
- join_function: <function>,
join_table: {
fields: {
distinct_id: {
@@ -7531,6 +7563,8 @@
top_level_settings: None,
workload: None
},
+ resolver: "person_distinct_id_overrides",
+ resolver_params: {},
to_field: None
}
table_type: <recursion ...>
@@ -7592,7 +7626,6 @@
"distinct_id"
],
hidden: False,
- join_function: <function>,
join_table: {
fields: {
distinct_id: {
@@ -7613,6 +7646,8 @@
top_level_settings: None,
workload: None
},
+ resolver: "person_distinct_id_overrides",
+ resolver_params: {},
to_field: None
}
table_type: <recursion ...>
@@ -7946,7 +7981,6 @@
"fingerprint"
],
hidden: False,
- join_function: <function>,
join_table: {
fields: {
fingerprint: {
@@ -7964,6 +7998,8 @@
top_level_settings: None,
workload: None
},
+ resolver: "error_tracking_issue_fingerprint_overrides",
+ resolver_params: {},
to_field: None
}
table_type: <recursion ...>
@@ -8025,7 +8061,6 @@
"fingerprint"
],
hidden: False,
- join_function: <function>,
join_table: {
fields: {
fingerprint: {
@@ -8043,6 +8078,8 @@
top_level_settings: None,
workload: None
},
+ resolver: "error_tracking_issue_fingerprint_overrides",
+ resolver_params: {},
to_field: None
}
table_type: <recursion ...>
@@ -8158,7 +8195,6 @@
"fingerprint"
],
hidden: False,
- join_function: <function>,
join_table: {
fields: {
assigned_role_id: {
@@ -8197,6 +8233,8 @@
top_level_settings: None,
workload: None
},
+ resolver: "error_tracking_fingerprint_issue_state",
+ resolver_params: {},
to_field: None
}
table_type: <recursion ...>
@@ -8236,7 +8274,6 @@
"fingerprint"
],
hidden: False,
- join_function: <function>,
join_table: {
fields: {
assigned_role_id: {
@@ -8275,6 +8312,8 @@
top_level_settings: None,
workload: None
},
+ resolver: "error_tracking_fingerprint_issue_state",
+ resolver_params: {},
to_field: None
}
table_type: <recursion ...>
@@ -8314,7 +8353,6 @@
"fingerprint"
],
hidden: False,
- join_function: <function>,
join_table: {
fields: {
assigned_role_id: {
@@ -8353,6 +8391,8 @@
top_level_settings: None,
workload: None
},
+ resolver: "error_tracking_fingerprint_issue_state",
+ resolver_params: {},
to_field: None
}
table_type: <recursion ...>
@@ -8392,7 +8432,6 @@
"fingerprint"
],
hidden: False,
- join_function: <function>,
join_table: {
fields: {
assigned_role_id: {
@@ -8431,6 +8470,8 @@
top_level_settings: None,
workload: None
},
+ resolver: "error_tracking_fingerprint_issue_state",
+ resolver_params: {},
to_field: None
}
table_type: <recursion ...>
@@ -8470,7 +8511,6 @@
"fingerprint"
],
hidden: False,
- join_function: <function>,
join_table: {
fields: {
assigned_role_id: {
@@ -8509,6 +8549,8 @@
top_level_settings: None,
workload: None
},
+ resolver: "error_tracking_fingerprint_issue_state",
+ resolver_params: {},
to_field: None
}
table_type: <recursion ...>
@@ -8548,7 +8590,6 @@
"fingerprint"
],
hidden: False,
- join_function: <function>,
join_table: {
fields: {
assigned_role_id: {
@@ -8587,6 +8628,8 @@
top_level_settings: None,
workload: None
},
+ resolver: "error_tracking_fingerprint_issue_state",
+ resolver_params: {},
to_field: None
}
table_type: <recursion ...>
@@ -8626,7 +8669,6 @@
"fingerprint"
],
hidden: False,
- join_function: <function>,
join_table: {
fields: {
assigned_role_id: {
@@ -8665,6 +8707,8 @@
top_level_settings: None,
workload: None
},
+ resolver: "error_tracking_fingerprint_issue_state",
+ resolver_params: {},
to_field: None
}
table_type: <recursion ...>
@@ -9414,7 +9458,6 @@
"distinct_id"
],
hidden: False,
- join_function: <function>,
join_table: {
fields: {
distinct_id: {
@@ -9435,6 +9478,8 @@
top_level_settings: None,
workload: None
},
+ resolver: "person_distinct_id_overrides",
+ resolver_params: {},
to_field: None
}
table_type: <recursion ...>
@@ -9496,7 +9541,6 @@
"distinct_id"
],
hidden: False,
- join_function: <function>,
join_table: {
fields: {
distinct_id: {
@@ -9517,6 +9561,8 @@
top_level_settings: None,
workload: None
},
+ resolver: "person_distinct_id_overrides",
+ resolver_params: {},
to_field: None
}
table_type: <recursion ...>
@@ -9850,7 +9896,6 @@
"fingerprint"
],
hidden: False,
- join_function: <function>,
join_table: {
fields: {
fingerprint: {
@@ -9868,6 +9913,8 @@
top_level_settings: None,
workload: None
},
+ resolver: "error_tracking_issue_fingerprint_overrides",
+ resolver_params: {},
to_field: None
}
table_type: <recursion ...>
@@ -9929,7 +9976,6 @@
"fingerprint"
],
hidden: False,
- join_function: <function>,
join_table: {
fields: {
fingerprint: {
@@ -9947,6 +9993,8 @@
top_level_settings: None,
workload: None
},
+ resolver: "error_tracking_issue_fingerprint_overrides",
+ resolver_params: {},
to_field: None
}
table_type: <recursion ...>
@@ -10062,7 +10110,6 @@
"fingerprint"
],
hidden: False,
- join_function: <function>,
join_table: {
fields: {
assigned_role_id: {
@@ -10101,6 +10148,8 @@
top_level_settings: None,
workload: None
},
+ resolver: "error_tracking_fingerprint_issue_state",
+ resolver_params: {},
to_field: None
}
table_type: <recursion ...>
@@ -10140,7 +10189,6 @@
"fingerprint"
],
hidden: False,
- join_function: <function>,
join_table: {
fields: {
assigned_role_id: {
@@ -10179,6 +10227,8 @@
top_level_settings: None,
workload: None
},
+ resolver: "error_tracking_fingerprint_issue_state",
+ resolver_params: {},
to_field: None
}
table_type: <recursion ...>
@@ -10218,7 +10268,6 @@
"fingerprint"
],
hidden: False,
- join_function: <function>,
join_table: {
fields: {
assigned_role_id: {
@@ -10257,6 +10306,8 @@
top_level_settings: None,
workload: None
},
+ resolver: "error_tracking_fingerprint_issue_state",
+ resolver_params: {},
to_field: None
}
table_type: <recursion ...>
@@ -10296,7 +10347,6 @@
"fingerprint"
],
hidden: False,
- join_function: <function>,
join_table: {
fields: {
assigned_role_id: {
@@ -10335,6 +10385,8 @@
top_level_settings: None,
workload: None
},
+ resolver: "error_tracking_fingerprint_issue_state",
+ resolver_params: {},
to_field: None
}
table_type: <recursion ...>
@@ -10374,7 +10426,6 @@
"fingerprint"
],
hidden: False,
- join_function: <function>,
join_table: {
fields: {
assigned_role_id: {
@@ -10413,6 +10464,8 @@
top_level_settings: None,
workload: None
},
+ resolver: "error_tracking_fingerprint_issue_state",
+ resolver_params: {},
to_field: None
}
table_type: <recursion ...>
@@ -10452,7 +10505,6 @@
"fingerprint"
],
hidden: False,
- join_function: <function>,
join_table: {
fields: {
assigned_role_id: {
@@ -10491,6 +10543,8 @@
top_level_settings: None,
workload: None
},
+ resolver: "error_tracking_fingerprint_issue_state",
+ resolver_params: {},
to_field: None
}
table_type: <recursion ...>
@@ -10530,7 +10584,6 @@
"fingerprint"
],
hidden: False,
- join_function: <function>,
join_table: {
fields: {
assigned_role_id: {
@@ -10569,6 +10622,8 @@
top_level_settings: None,
workload: None
},
+ resolver: "error_tracking_fingerprint_issue_state",
+ resolver_params: {},
to_field: None
}
table_type: <recursion ...>
@@ -11037,7 +11092,6 @@
"distinct_id"
],
hidden: False,
- join_function: <function>,
join_table: {
fields: {
distinct_id: {
@@ -11058,6 +11112,8 @@
top_level_settings: None,
workload: None
},
+ resolver: "person_distinct_id_overrides",
+ resolver_params: {},
to_field: None
}
table_type: <recursion ...>
@@ -11119,7 +11175,6 @@
"distinct_id"
],
hidden: False,
- join_function: <function>,
join_table: {
fields: {
distinct_id: {
@@ -11140,6 +11195,8 @@
top_level_settings: None,
workload: None
},
+ resolver: "person_distinct_id_overrides",
+ resolver_params: {},
to_field: None
}
table_type: <recursion ...>
@@ -11473,7 +11530,6 @@
"fingerprint"
],
hidden: False,
- join_function: <function>,
join_table: {
fields: {
fingerprint: {
@@ -11491,6 +11547,8 @@
top_level_settings: None,
workload: None
},
+ resolver: "error_tracking_issue_fingerprint_overrides",
+ resolver_params: {},
to_field: None
}
table_type: <recursion ...>
@@ -11552,7 +11610,6 @@
"fingerprint"
],
hidden: False,
- join_function: <function>,
join_table: {
fields: {
fingerprint: {
@@ -11570,6 +11627,8 @@
top_level_settings: None,
workload: None
},
+ resolver: "error_tracking_issue_fingerprint_overrides",
+ resolver_params: {},
to_field: None
}
table_type: <recursion ...>
@@ -11685,7 +11744,6 @@
"fingerprint"
],
hidden: False,
- join_function: <function>,
join_table: {
fields: {
assigned_role_id: {
@@ -11724,6 +11782,8 @@
top_level_settings: None,
workload: None
},
+ resolver: "error_tracking_fingerprint_issue_state",
+ resolver_params: {},
to_field: None
}
table_type: <recursion ...>
@@ -11763,7 +11823,6 @@
"fingerprint"
],
hidden: False,
- join_function: <function>,
join_table: {
fields: {
assigned_role_id: {
@@ -11802,6 +11861,8 @@
top_level_settings: None,
workload: None
},
+ resolver: "error_tracking_fingerprint_issue_state",
+ resolver_params: {},
to_field: None
}
table_type: <recursion ...>
@@ -11841,7 +11902,6 @@
"fingerprint"
],
hidden: False,
- join_function: <function>,
join_table: {
fields: {
assigned_role_id: {
@@ -11880,6 +11940,8 @@
top_level_settings: None,
workload: None
},
+ resolver: "error_tracking_fingerprint_issue_state",
+ resolver_params: {},
to_field: None
}
table_type: <recursion ...>
@@ -11919,7 +11981,6 @@
"fingerprint"
],
hidden: False,
- join_function: <function>,
join_table: {
fields: {
assigned_role_id: {
@@ -11958,6 +12019,8 @@
top_level_settings: None,
workload: None
},
+ resolver: "error_tracking_fingerprint_issue_state",
+ resolver_params: {},
to_field: None
}
table_type: <recursion ...>
@@ -11997,7 +12060,6 @@
"fingerprint"
],
hidden: False,
- join_function: <function>,
join_table: {
fields: {
assigned_role_id: {
@@ -12036,6 +12098,8 @@
top_level_settings: None,
workload: None
},
+ resolver: "error_tracking_fingerprint_issue_state",
+ resolver_params: {},
to_field: None
}
table_type: <recursion ...>
@@ -12075,7 +12139,6 @@
"fingerprint"
],
hidden: False,
- join_function: <function>,
join_table: {
fields: {
assigned_role_id: {
@@ -12114,6 +12177,8 @@
top_level_settings: None,
workload: None
},
+ resolver: "error_tracking_fingerprint_issue_state",
+ resolver_params: {},
to_field: None
}
table_type: <recursion ...>
@@ -12153,7 +12218,6 @@
"fingerprint"
],
hidden: False,
- join_function: <function>,
join_table: {
fields: {
assigned_role_id: {
@@ -12192,6 +12256,8 @@
top_level_settings: None,
workload: None
},
+ resolver: "error_tracking_fingerprint_issue_state",
+ resolver_params: {},
to_field: None
}
table_type: <recursion ...>
@@ -14499,8 +14565,9 @@
"person_id"
],
hidden: False,
- join_function: <function>,
join_table: "persons",
+ resolver: "persons",
+ resolver_params: {},
to_field: None
}
table_type: {
@@ -14510,7 +14577,6 @@
"distinct_id"
],
hidden: False,
- join_function: <function>,
join_table: {
fields: {
distinct_id: {
@@ -14531,6 +14597,8 @@
top_level_settings: None,
workload: None
},
+ resolver: "person_distinct_ids",
+ resolver_params: {},
to_field: None
}
table_type: <recursion ...>
@@ -14788,8 +14856,9 @@
"person_id"
],
hidden: False,
- join_function: <function>,
join_table: "persons",
+ resolver: "persons",
+ resolver_params: {},
to_field: None
}
table_type: {
@@ -14799,7 +14868,6 @@
"distinct_id"
],
hidden: False,
- join_function: <function>,
join_table: {
fields: {
distinct_id: {
@@ -14820,6 +14888,8 @@
top_level_settings: None,
workload: None
},
+ resolver: "person_distinct_ids",
+ resolver_params: {},
to_field: None
}
table_type: <recursion ...>
@@ -15073,7 +15143,6 @@
"distinct_id"
],
hidden: False,
- join_function: <function>,
join_table: {
fields: {
distinct_id: {
@@ -15094,6 +15163,8 @@
top_level_settings: None,
workload: None
},
+ resolver: "person_distinct_ids",
+ resolver_params: {},
to_field: None
}
table_type: <recursion ...>
@@ -15349,7 +15420,6 @@
"distinct_id"
],
hidden: False,
- join_function: <function>,
join_table: {
fields: {
distinct_id: {
@@ -15370,6 +15440,8 @@
top_level_settings: None,
workload: None
},
+ resolver: "person_distinct_ids",
+ resolver_params: {},
to_field: None
}
table_type: <recursion ...>
@@ -15472,8 +15544,9 @@
"person_id"
],
hidden: False,
- join_function: <function>,
join_table: "persons",
+ resolver: "persons",
+ resolver_params: {},
to_field: None
}
table_type: <recursion ...>
diff --git a/posthog/hogql/transforms/lazy_tables.py b/posthog/hogql/transforms/lazy_tables.py
index e7935478d11c..c5e24579ff4c 100644
--- a/posthog/hogql/transforms/lazy_tables.py
+++ b/posthog/hogql/transforms/lazy_tables.py
@@ -600,7 +600,7 @@ class LazyTableResolver(TraversingVisitor):
# For all the collected joins, create the join subqueries, and add them to the table.
for to_table, join_scope in joins_to_add.items():
- join_to_add: ast.JoinExpr = join_scope.lazy_join.join_function(
+ join_to_add: ast.JoinExpr = join_scope.lazy_join.resolve_join_to_add(
join_scope,
self.context,
node,
@@ -685,7 +685,7 @@ class LazyTableResolver(TraversingVisitor):
else:
node.select_from = join_to_add
- # Collect any fields or properties that may have been added from the join_function with the LazyJoinType
+ # Collect any fields or properties that may have been added by the join resolver with the LazyJoinType
join_field_collector: list[ast.FieldType | ast.PropertyType] = []
self.field_collectors.append(join_field_collector)
super().visit(join_to_add)
diff --git a/products/data_tools/backend/models/join.py b/products/data_tools/backend/models/join.py
index 3f71af1a9689..7b2b3890d50f 100644
--- a/products/data_tools/backend/models/join.py
+++ b/products/data_tools/backend/models/join.py
@@ -1,16 +1,9 @@
from datetime import datetime
-from typing import Optional, cast
+from typing import cast
from warnings import warn
from django.db import models
-from posthog.hogql import ast
-from posthog.hogql.ast import SelectQuery
-from posthog.hogql.context import HogQLContext
-from posthog.hogql.database.models import LazyJoinToAdd
-from posthog.hogql.database.utils import qualify_join_key_expr
-from posthog.hogql.errors import ResolutionError
-
from posthog.models.utils import CreatedMetaFields, DeletedMetaFields, UUIDTModel
@@ -57,165 +50,3 @@ class DataWarehouseJoin(CreatedMetaFields, UUIDTModel, DeletedMetaFields):
self.deleted = True
self.deleted_at = datetime.now()
self.save()
-
- def join_function(
- self,
- override_source_table_key: Optional[str] = None,
- override_joining_table_key: Optional[str] = None,
- override_join_type: Optional[str] = None,
- ):
- def _join_function(
- join_to_add: LazyJoinToAdd,
- context: HogQLContext,
- node: SelectQuery,
- ):
- _source_table_key = override_source_table_key or self.source_table_key
- _joining_table_key = override_joining_table_key or self.joining_table_key
-
- from posthog.hogql import ast
-
- if not join_to_add.fields_accessed:
- raise ResolutionError(f"No fields requested from {join_to_add.to_table}")
-
- left = self.parse_table_key_expression(_source_table_key, join_to_add.from_table)
- right = self.parse_table_key_expression(_joining_table_key, join_to_add.to_table)
-
- join_expr = ast.JoinExpr(
- table=ast.SelectQuery(
- select=[
- ast.Alias(alias=alias, expr=ast.Field(chain=chain))
- for alias, chain in join_to_add.fields_accessed.items()
- ],
- select_from=ast.JoinExpr(table=ast.Field(chain=self.joining_table_name_chain)),
- ),
- join_type=override_join_type or "LEFT JOIN",
- alias=join_to_add.to_table,
- constraint=ast.JoinConstraint(
- expr=ast.CompareOperation(
- op=ast.CompareOperationOp.Eq,
- left=left,
- right=right,
- ),
- constraint_type="ON",
- ),
- )
- return join_expr
-
- return _join_function
-
- def join_function_for_experiments(self):
- def _join_function_for_experiments(
- join_to_add: LazyJoinToAdd,
- context: HogQLContext,
- node: SelectQuery,
- ):
- if not isinstance(self.configuration, dict):
- raise ResolutionError("experiments_optimized is not configured for this join")
-
- if self.joining_table_name != "events":
- raise ResolutionError("experiments_optimized is only supported for events table")
-
- if not self.configuration.get("experiments_optimized"):
- raise ResolutionError("experiments_optimized is not enabled for this join")
-
- timestamp_key = self.configuration.get("experiments_timestamp_key")
- if not isinstance(timestamp_key, str) or not timestamp_key:
- raise ResolutionError("experiments_timestamp_key is not set for this join")
-
- left = self.parse_table_key_expression(self.source_table_key, join_to_add.from_table)
- right = self.parse_table_key_expression(self.joining_table_key, join_to_add.to_table)
-
- whereExpr: list[ast.Expr] = [
- ast.CompareOperation(
- op=ast.CompareOperationOp.Eq,
- left=ast.Field(chain=["event"]),
- right=ast.Constant(value="$feature_flag_called"),
- )
- ]
- # :HACK: We need to pull the timestamp gt/lt values from node.where.exprs[0] because
- # we can't reference the parent data warehouse table in the where clause.
- if node.where and hasattr(node.where, "exprs"):
- for expr in node.where.exprs:
- if isinstance(expr, ast.CompareOperation):
- if expr.op == ast.CompareOperationOp.GtEq or expr.op == ast.CompareOperationOp.LtEq:
- # Match within hogql string because it could be 'toDateTime(timestamp)'
- if isinstance(expr.left, ast.Alias) and timestamp_key in expr.left.expr.to_hogql():
- whereExpr.append(
- ast.CompareOperation(
- op=expr.op, left=ast.Field(chain=["timestamp"]), right=expr.right
- )
- )
-
- return ast.JoinExpr(
- table=ast.SelectQuery(
- select=[
- ast.Alias(
- alias=name,
- expr=ast.Field(chain=["events", *(chain if isinstance(chain, list | tuple) else [chain])]),
- )
- for name, chain in {
- **join_to_add.fields_accessed,
- "event": ["event"],
- "timestamp": ["timestamp"],
- "distinct_id": ["distinct_id"],
- "properties": ["properties"],
- }.items()
- ],
- select_from=ast.JoinExpr(table=ast.Field(chain=["events"])),
- where=ast.And(exprs=whereExpr),
- ),
- # ASOF JOIN finds the most recent matching event that occurred at or before each data warehouse timestamp.
- #
- # Why this matters:
- # When a user performs an action (recorded in data warehouse), we want to know which
- # experiment variant they were assigned at that moment. The most recent $feature_flag_called
- # event before their action represents their active variant assignment.
- #
- # Example:
- # Data Warehouse: timestamp=2024-01-03 12:00, distinct_id=user1
- # Events:
- # 2024-01-02: (user1, variant='control') <- This event will be joined
- # 2024-01-03: (user1, variant='test') <- Ignored (occurs after data warehouse timestamp)
- #
- # This ensures we capture the correct causal relationship: which experiment variant
- # was the user assigned to when they performed the action?
- join_type="ASOF LEFT JOIN",
- alias=join_to_add.to_table,
- constraint=ast.JoinConstraint(
- expr=ast.And(
- exprs=[
- ast.CompareOperation(
- left=ast.Field(chain=[join_to_add.to_table, "event"]),
- op=ast.CompareOperationOp.Eq,
- right=ast.Constant(value="$feature_flag_called"),
- ),
- ast.CompareOperation(
- left=left,
- op=ast.CompareOperationOp.Eq,
- right=right,
- ),
- ast.CompareOperation(
- left=ast.Field(
- chain=[
- join_to_add.from_table,
- timestamp_key,
- ]
- ),
- op=ast.CompareOperationOp.GtEq,
- right=ast.Field(chain=[join_to_add.to_table, "timestamp"]),
- ),
- ]
- ),
- constraint_type="ON",
- ),
- )
-
- return _join_function_for_experiments
-
- @classmethod
- def parse_table_key_expression(cls, table_key: str, table_name: str) -> ast.Expr:
- expr = qualify_join_key_expr(table_key, table_name)
- if expr is None:
- raise ResolutionError("Data Warehouse Join HogQL expression should be a Field or Call node")
-
- return expr
diff --git a/products/data_warehouse/backend/api/view_link.py b/products/data_warehouse/backend/api/view_link.py
index 7f7b7ac29c86..dcf34f02f088 100644
--- a/products/data_warehouse/backend/api/view_link.py
+++ b/products/data_warehouse/backend/api/view_link.py
@@ -6,8 +6,10 @@ from rest_framework import filters, response, serializers, status, viewsets
from posthog.hogql import ast
from posthog.hogql.context import HogQLContext
from posthog.hogql.database.database import Database
+from posthog.hogql.database.lazy_join_tags import DATA_WAREHOUSE
from posthog.hogql.database.models import LazyJoin
from posthog.hogql.database.utils import get_join_field_chain
+from posthog.hogql.database.warehouse_join_resolvers import data_warehouse_resolver_params
from posthog.hogql.errors import QueryError, SyntaxError
from posthog.hogql.parser import parse_expr, parse_select
from posthog.hogql.query import execute_hogql_query
@@ -221,7 +223,14 @@ class ViewLinkViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewset
from_field=from_field,
to_field=to_field,
join_table=joining_table,
- join_function=join.join_function(override_join_type="INNER JOIN"),
+ resolver=DATA_WAREHOUSE,
+ resolver_params=data_warehouse_resolver_params(
+ source_table_key=join.source_table_key,
+ joining_table_key=join.joining_table_key,
+ joining_table_name=join.joining_table_name,
+ configuration=join.configuration,
+ override_join_type="INNER JOIN",
+ ),
)
validation_query = parse_select(
"SELECT {to_field} FROM {source_table_name} LIMIT 10",