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 resolver and schema layer import without Django (#71568)

George Munyorof565ee7295e1
diff --git a/posthog/exchange_rate_constants.py b/posthog/exchange_rate_constants.py
new file mode 100644
index 000000000000..457af9ad5bc5
--- /dev/null
+++ b/posthog/exchange_rate_constants.py
@@ -0,0 +1,15 @@
+# Django-free home for the exchange-rate ClickHouse dictionary constants. Kept out of
+# posthog.models.exchange_rate.sql (whose package __init__ boots the Django ORM) so the HogQL
+# engine — schema tables and the printer — can reference them without booting Django.
+# posthog.models.exchange_rate.sql re-exports these for existing callers.
+
+EXCHANGE_RATE_TABLE_NAME = "exchange_rate"
+EXCHANGE_RATE_DICTIONARY_NAME = "exchange_rate_dict"
+
+# Storing 10 decimal places is more than enough
+# Ideally we should have gone with 4 because that's all we need for most currencies
+# but Bitcoin messes this up because it's so valuable compared to the Dollar (our base currency)
+#
+# If Bitcoin ever moons it even further, we can increase this to 12 or 14
+# but for now 10 is more than enough
+EXCHANGE_RATE_DECIMAL_PRECISION = 10
diff --git a/posthog/hogql/database/database.py b/posthog/hogql/database/database.py
index c41e678fca5e..caa8258641ea 100644
--- a/posthog/hogql/database/database.py
+++ b/posthog/hogql/database/database.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
import io
import copy
import pickle
@@ -11,8 +13,6 @@ from functools import cache
from typing import TYPE_CHECKING, Any, Literal, Optional, Union, cast
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
-from django.db.models import Prefetch, Q
-
import structlog
from opentelemetry import trace
from pydantic import BaseModel, ConfigDict
@@ -144,31 +144,16 @@ from posthog.hogql.parser import parse_expr
from posthog.hogql.timings import HogQLTimings
from posthog.exceptions_capture import capture_exception
-from posthog.models.group_type_mapping import get_group_types_for_project
-from posthog.models.organization import OrganizationMembership
-from posthog.models.team.team import Team, WeekStartDay
from posthog.ph_client import feature_enabled_or_false
-from posthog.rbac.user_access_control import NO_ACCESS_LEVEL, UserAccessControl
from posthog.schema_enums import DatabaseSerializedFieldType, PersonsOnEventsMode, SessionTableVersion
from posthog.scopes import APIScopeObject
-from posthog.shared_link_user import SharedLinkUser
from posthog.synthetic_user import SyntheticUser
-from products.data_tools.backend.models.join import DataWarehouseJoin
-from products.data_warehouse.backend.facade.hogql import get_warehouse_sync_warnings
-from products.revenue_analytics.backend.views import RevenueAnalyticsBaseView
-from products.warehouse_sources.backend.facade.models import (
- DataWarehouseCredential,
- DataWarehouseTable,
- DataWarehouseTableColumns,
- ExternalDataJob,
- ExternalDataSchema,
- ExternalDataSource,
-)
-from products.warehouse_sources.backend.facade.types import ExternalDataSourceType
-
-# posthog.schema (the pydantic models) is runtime-imported inside serialize()/serialize_fields()
-# so it stays off django.setup(), where this module loads via the warehouse/data-modeling models.
+# The Django ORM / products models below are imported lazily inside the functions that build a
+# Database (Database._fetch_sources / _build_from_sources / serialize and their helpers) so this
+# module — and the HogQL resolver/printer that import it — load without django.setup(). The
+# type-only references live in TYPE_CHECKING; posthog.schema (pydantic) is likewise runtime-imported
+# inside serialize()/serialize_fields().
if TYPE_CHECKING:
from posthog.schema import (
DatabaseSchemaDataWarehouseTable,
@@ -183,8 +168,20 @@ if TYPE_CHECKING:
)
from posthog.models import User
+ from posthog.models.team.team import Team, WeekStartDay
+ from posthog.rbac.user_access_control import UserAccessControl
+ from posthog.shared_link_user import SharedLinkUser
from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery
+ from products.data_tools.backend.models.join import DataWarehouseJoin
+ from products.revenue_analytics.backend.views import RevenueAnalyticsBaseView
+ from products.warehouse_sources.backend.facade.models import (
+ DataWarehouseCredential,
+ DataWarehouseTable,
+ DataWarehouseTableColumns,
+ ExternalDataSchema,
+ ExternalDataSource,
+ )
tracer = trace.get_tracer(__name__)
@@ -206,10 +203,10 @@ class HogQLDatabaseSources:
"""All I/O Database._build_from_sources needs, fetched up front by Database._fetch_sources so the
build phase runs without any queries."""
- team: "Team"
- user: Optional["User | SyntheticUser | SharedLinkUser"]
+ team: Team
+ user: Optional[User | SyntheticUser | SharedLinkUser]
connection_id: str | None
- modifiers: "HogQLQueryModifiers"
+ modifiers: HogQLQueryModifiers
is_managed_viewset_enabled: bool
is_hogql_warehouse_access_control_enabled: bool
is_data_catalog_enabled: bool
@@ -217,20 +214,20 @@ class HogQLDatabaseSources:
bypass_warehouse_access_control: bool
direct_connection_metadata: dict[str, Any] | None
# Access-control decision, computed from a warmed UserAccessControl so build does no AC queries.
- user_access_control: Optional["UserAccessControl"]
+ user_access_control: Optional[UserAccessControl]
denied_system_table_names: set[str] # node names under the "system" node to remove during build
group_types: list[dict[str, Any]]
- saved_queries: list["DataWarehouseSavedQuery"]
- endpoint_saved_queries: list["DataWarehouseSavedQuery"]
- revenue_views: list["RevenueAnalyticsBaseView"]
- warehouse_tables: list["DataWarehouseTable"] # filtered to what build needs, schemas preloaded
- data_warehouse_joins: list["DataWarehouseJoin"]
+ saved_queries: list[DataWarehouseSavedQuery]
+ endpoint_saved_queries: list[DataWarehouseSavedQuery]
+ revenue_views: list[RevenueAnalyticsBaseView]
+ warehouse_tables: list[DataWarehouseTable] # filtered to what build needs, schemas preloaded
+ data_warehouse_joins: list[DataWarehouseJoin]
# dataWarehouseEventsModifiers path: saved query per modifier table name (None if no matching row).
- event_modifier_saved_queries: dict[str, Optional["DataWarehouseSavedQuery"]]
+ event_modifier_saved_queries: dict[str, Optional[DataWarehouseSavedQuery]]
# Dual-mode: a synced (warehouse) source queried live via connection_id. Its physical rows are
# synced S3 copies, so the build derives virtual DirectSQLTables from these schema rows instead.
- virtual_source: Optional["ExternalDataSource"] = None
- virtual_schemas: list["ExternalDataSchema"] = dataclasses.field(default_factory=list)
+ virtual_source: Optional[ExternalDataSource] = None
+ virtual_schemas: list[ExternalDataSchema] = dataclasses.field(default_factory=list)
type DatabaseSchemaTable = (
@@ -468,15 +465,20 @@ def _system_table_access_scopes() -> tuple[tuple[str, APIScopeObject], ...]:
def _compute_system_table_access_decision(
- team: "Team",
- user: Optional["User | SyntheticUser | SharedLinkUser"],
- user_access_control: Optional["UserAccessControl"] = None,
-) -> tuple[Optional["UserAccessControl"], set[str]]:
+ team: Team,
+ user: Optional[User | SyntheticUser | SharedLinkUser],
+ user_access_control: Optional[UserAccessControl] = None,
+) -> tuple[Optional[UserAccessControl], set[str]]:
"""Decide which scoped system tables to hide, doing the access-control I/O here so the build phase
can apply the result without querying. Returns the warmed UserAccessControl (preloaded, so later
reads are query-free) and the system-node table names to remove.
Pass user_access_control when it's already preloaded to reuse the instance and avoid an extra query."""
+ # Lazy imports keep the Django ORM off this module's import path.
+ from posthog.models.organization import OrganizationMembership # noqa: PLC0415
+ from posthog.rbac.user_access_control import NO_ACCESS_LEVEL, UserAccessControl # noqa: PLC0415
+ from posthog.shared_link_user import SharedLinkUser # noqa: PLC0415
+
scoped_tables = _system_table_access_scopes()
# Anonymous or synthetic principal: keep only access-controlled tables its scopes cover (none for shared link / team token).
@@ -515,7 +517,7 @@ class Database(BaseModel):
_direct_access_warehouse_table_names: set[str] = set()
# Warnings about data warehouse tables (failed/paused/billing-limited/stale syncs),
# keyed by HogQL DataWarehouseTable.table_id (str(Django table UUID)).
- _data_warehouse_sync_warnings: dict[str, list["DataWarehouseSyncWarning"]] = {}
+ _data_warehouse_sync_warnings: dict[str, list[DataWarehouseSyncWarning]] = {}
_timezone: str | None
_week_start_day: WeekStartDay | None
@@ -548,6 +550,8 @@ class Database(BaseModel):
return self._timezone or "UTC"
def get_week_start_day(self) -> WeekStartDay:
+ from posthog.models.team.team import WeekStartDay # noqa: PLC0415
+
return self._week_start_day or WeekStartDay.SUNDAY
def get_serialization_errors(self) -> dict[str, str]:
@@ -764,7 +768,7 @@ class Database(BaseModel):
]
def _apply_system_table_access(
- self, user_access_control: Optional["UserAccessControl"], denied_system_table_names: set[str]
+ self, user_access_control: Optional[UserAccessControl], denied_system_table_names: set[str]
) -> None:
"""Apply the precomputed access-control decision from _compute_system_table_access_decision,
without querying."""
@@ -783,7 +787,7 @@ class Database(BaseModel):
self._denied_tables = {f"system.{name}" for name in removed}
- def _is_warehouse_table_denied(self, table: "DataWarehouseTable") -> bool:
+ def _is_warehouse_table_denied(self, table: DataWarehouseTable) -> bool:
"""
Returns True if the user can't query this warehouse table.
Userless context (no UserAccessControl) fails closed - every table is denied.
@@ -824,6 +828,8 @@ class Database(BaseModel):
include_only: set[str] | None = None,
include_hidden_posthog_tables: bool = False,
) -> dict[str, DatabaseSchemaTable]:
+ from django.db.models import Prefetch # noqa: PLC0415
+
from posthog.schema import ( # noqa: PLC0415
DatabaseSchemaDataWarehouseTable,
DatabaseSchemaEndpointTable,
@@ -836,7 +842,13 @@ class Database(BaseModel):
HogQLQuery,
)
- from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery
+ from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery # noqa: PLC0415
+ from products.revenue_analytics.backend.views import RevenueAnalyticsBaseView # noqa: PLC0415
+ from products.warehouse_sources.backend.facade.models import ( # noqa: PLC0415
+ DataWarehouseTable,
+ ExternalDataJob,
+ ExternalDataSource,
+ )
tables: dict[str, DatabaseSchemaTable] = {}
@@ -1133,15 +1145,15 @@ class Database(BaseModel):
def create_for(
team_id: int | None = None,
*,
- team: Optional["Team"] = None,
- user: Optional["User | SyntheticUser | SharedLinkUser"] = None,
- user_access_control: Optional["UserAccessControl"] = None,
- modifiers: "HogQLQueryModifiers | None" = None,
+ team: Optional[Team] = None,
+ user: Optional[User | SyntheticUser | SharedLinkUser] = None,
+ user_access_control: Optional[UserAccessControl] = None,
+ modifiers: HogQLQueryModifiers | None = None,
timings: HogQLTimings | None = None,
connection_id: str | None = None,
bypass_warehouse_access_control: bool = False,
build_postgres_foreign_keys: bool = True,
- ) -> "Database":
+ ) -> Database:
if timings is None:
timings = HogQLTimings()
@@ -1163,10 +1175,10 @@ class Database(BaseModel):
def _fetch_sources(
team_id: int | None = None,
*,
- team: Optional["Team"] = None,
- user: Optional["User | SyntheticUser | SharedLinkUser"] = None,
- user_access_control: Optional["UserAccessControl"] = None,
- modifiers: "HogQLQueryModifiers | None" = None,
+ team: Optional[Team] = None,
+ user: Optional[User | SyntheticUser | SharedLinkUser] = None,
+ user_access_control: Optional[UserAccessControl] = None,
+ modifiers: HogQLQueryModifiers | None = None,
timings: HogQLTimings | None = None,
connection_id: str | None = None,
bypass_warehouse_access_control: bool = False,
@@ -1178,7 +1190,17 @@ class Database(BaseModel):
db_span = trace.get_current_span()
- from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery
+ # Lazy imports keep the Django ORM off this module's import path.
+ from posthog.models.group_type_mapping import get_group_types_for_project # noqa: PLC0415
+ from posthog.models.team.team import Team # noqa: PLC0415
+ from posthog.shared_link_user import SharedLinkUser # noqa: PLC0415
+
+ from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery # noqa: PLC0415
+ from products.data_tools.backend.models.join import DataWarehouseJoin # noqa: PLC0415
+ from products.warehouse_sources.backend.facade.models import ( # noqa: PLC0415
+ DataWarehouseTable,
+ ExternalDataSource,
+ )
with timings.measure("team", emit_span=True):
if team_id is None and team is None:
@@ -1470,7 +1492,7 @@ class Database(BaseModel):
sources: HogQLDatabaseSources,
timings: HogQLTimings | None = None,
build_postgres_foreign_keys: bool = True,
- ) -> "Database":
+ ) -> Database:
"""Construct the HogQL Database purely from already-fetched sources. Performs no I/O: every
Postgres query and feature-flag check was done up front in Database._fetch_sources."""
if timings is None:
@@ -1478,7 +1500,14 @@ class Database(BaseModel):
db_span = trace.get_current_span()
- from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery
+ # Lazy imports keep the Django ORM / products models off this module's import path.
+ from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery # noqa: PLC0415
+ from products.data_warehouse.backend.facade.hogql import get_warehouse_sync_warnings # noqa: PLC0415
+ from products.warehouse_sources.backend.facade.models import ( # noqa: PLC0415
+ DataWarehouseTable,
+ ExternalDataSource,
+ )
+ from products.warehouse_sources.backend.facade.types import ExternalDataSourceType # noqa: PLC0415
team = sources.team
team_id = team.pk
@@ -1816,7 +1845,7 @@ class Database(BaseModel):
def define_mappings(
root_node: TableNode,
- get_table: Callable[[Any], Union[DataWarehouseTable, "DataWarehouseSavedQuery"]],
+ get_table: Callable[[Any], Union[DataWarehouseTable, DataWarehouseSavedQuery]],
) -> TableNode:
table: Table | None = None
@@ -1919,7 +1948,7 @@ class Database(BaseModel):
# Resolve a modifier's table model from already-fetched sources, raising DoesNotExist when no
# row matches just as the eager path's `.latest()` did.
- def _saved_query_model_for(wm: Any) -> "DataWarehouseSavedQuery":
+ def _saved_query_model_for(wm: Any) -> DataWarehouseSavedQuery:
saved_query = sources.event_modifier_saved_queries.get(wm.table_name)
if saved_query is None:
raise DataWarehouseSavedQuery.DoesNotExist(
@@ -2076,6 +2105,8 @@ class Database(BaseModel):
def get_data_warehouse_table_name(source: ExternalDataSource | None, table_name: str):
+ from products.warehouse_sources.backend.facade.models import ExternalDataSource # noqa: PLC0415
+
if source is None:
return table_name
@@ -2213,7 +2244,7 @@ def _setup_group_key_fields(database: Database, group_types: list[dict[str, Any]
)
-def _use_virtual_fields(database: Database, modifiers: "HogQLQueryModifiers", timings: HogQLTimings) -> None:
+def _use_virtual_fields(database: Database, modifiers: HogQLQueryModifiers, timings: HogQLTimings) -> None:
events_table = database.get_table("events")
persons_table = database.get_table("persons")
groups_table = database.get_table("groups")
@@ -2294,7 +2325,13 @@ def _constant_type_to_serialized_field_type(constant_type: ast.ConstantType) ->
HOGQL_CHARACTERS_TO_BE_WRAPPED = ["@", "-", "!", "$", "+"]
-NOT_DELETED_Q = Q(deleted=False) | Q(deleted__isnull=True)
+
+
+def _not_deleted_q():
+ # Built lazily so the Django ORM stays off this module's import path.
+ from django.db.models import Q # noqa: PLC0415
+
+ return Q(deleted=False) | Q(deleted__isnull=True)
def _attach_external_data_sources(
@@ -2308,6 +2345,8 @@ def _attach_external_data_sources(
deferred by default; callers that build that branch (direct-query mode) pass defer_job_inputs=False
so the few sources they hydrate keep it loaded rather than lazily reloading it per table.
"""
+ from products.warehouse_sources.backend.facade.models import ExternalDataSource # noqa: PLC0415
+
source_ids = {
table.external_data_source_id for table in warehouse_tables if table.external_data_source_id is not None
}
@@ -2336,10 +2375,12 @@ def _preload_active_external_data_schemas(warehouse_tables: Sequence[DataWarehou
if not tables_by_id:
return
+ from products.warehouse_sources.backend.facade.models import ExternalDataSchema # noqa: PLC0415
+
schemas_by_table_id: dict[str, list[ExternalDataSchema]] = defaultdict(list)
# Reuse the owning table's already-hydrated source instead of joining it per schema, which would
# re-decrypt job_inputs on the same few sources thousands of times.
- for schema in ExternalDataSchema.objects.filter(NOT_DELETED_Q, table_id__in=list(tables_by_id.keys())):
+ for schema in ExternalDataSchema.objects.filter(_not_deleted_q(), table_id__in=list(tables_by_id.keys())):
owning_table = tables_by_id.get(str(schema.table_id))
owning_source = owning_table.external_data_source if owning_table is not None else None
if owning_source is not None and schema.source_id == owning_source.pk:
@@ -2356,6 +2397,8 @@ def _attach_decrypted_credentials(warehouse_tables: Sequence[DataWarehouseTable]
Tables and views share a handful of credentials, so a bulk fetch keeps Fernet decryption to
O(credentials) instead of the O(tables) a per-row join would cost.
"""
+ from products.warehouse_sources.backend.facade.models import DataWarehouseCredential # noqa: PLC0415
+
credential_ids = {table.credential_id for table in warehouse_tables if table.credential_id is not None}
credentials_by_id: dict[Any, DataWarehouseCredential] = {}
if credential_ids:
@@ -2368,6 +2411,8 @@ def _attach_decrypted_credentials(warehouse_tables: Sequence[DataWarehouseTable]
def _get_active_external_data_schemas(warehouse_table: DataWarehouseTable) -> list[ExternalDataSchema]:
+ from products.warehouse_sources.backend.facade.models import ExternalDataSchema # noqa: PLC0415
+
active_external_data_schemas = cast(
Optional[list[ExternalDataSchema]],
getattr(warehouse_table, "_active_external_data_schemas", None),
@@ -2378,7 +2423,7 @@ def _get_active_external_data_schemas(warehouse_table: DataWarehouseTable) -> li
if warehouse_table.external_data_source_id is None:
return []
- return list(ExternalDataSchema.objects.filter(NOT_DELETED_Q, table_id=warehouse_table.id))
+ return list(ExternalDataSchema.objects.filter(_not_deleted_q(), table_id=warehouse_table.id))
def _strip_external_source_prefix(source: ExternalDataSource, table_name: str) -> str:
@@ -2404,6 +2449,8 @@ def _strip_external_source_prefix(source: ExternalDataSource, table_name: str) -
def _get_warehouse_table_keys(warehouse_table: DataWarehouseTable, *, direct_query: bool) -> list[str]:
+ from products.warehouse_sources.backend.facade.models import ExternalDataSource # noqa: PLC0415
+
source = warehouse_table.external_data_source
if source is not None and source.access_method == ExternalDataSource.AccessMethod.DIRECT and direct_query:
return [warehouse_table.name]
@@ -2416,6 +2463,8 @@ def _should_include_connection_table(
*,
connection_id: str,
) -> bool:
+ from products.warehouse_sources.backend.facade.models import ExternalDataSource # noqa: PLC0415
+
source = warehouse_table.external_data_source
if source is None or source.access_method != ExternalDataSource.AccessMethod.DIRECT:
return False
@@ -2452,7 +2501,7 @@ def serialize_fields(
table_chain: list[str],
db_columns: DataWarehouseTableColumns | None = None,
table_type: Literal["posthog"] | Literal["external"] = "posthog",
-) -> list["DatabaseSchemaField"]:
+) -> list[DatabaseSchemaField]:
from posthog.schema import DatabaseSchemaField # noqa: PLC0415
from posthog.hogql.resolver import resolve_types_from_table
diff --git a/posthog/hogql/database/postgres_utils.py b/posthog/hogql/database/postgres_utils.py
index 67473d110eb4..6c0f605f970a 100644
--- a/posthog/hogql/database/postgres_utils.py
+++ b/posthog/hogql/database/postgres_utils.py
@@ -1,6 +1,8 @@
+from __future__ import annotations
+
import dataclasses
from collections.abc import Sequence
-from typing import Any, Protocol
+from typing import TYPE_CHECKING, Any, Protocol
from posthog.hogql.database.direct_sql_table import DirectSQLTable
from posthog.hogql.database.lazy_join_tags import FOREIGN_KEY
@@ -9,7 +11,8 @@ from posthog.hogql.database.utils import get_join_field_chain
from posthog.exceptions_capture import capture_exception
-from products.warehouse_sources.backend.facade.models import DataWarehouseTable, ExternalDataSchema, ExternalDataSource
+if TYPE_CHECKING:
+ from products.warehouse_sources.backend.facade.models import DataWarehouseTable, ExternalDataSchema
class DatabaseTableLookup(Protocol):
@@ -213,6 +216,9 @@ def _is_same_external_scope(
if source_table_name is None or target_table_name is None:
return False
+ # noqa keeps the warehouse ORM off this module's import path — only needed when a Database is built.
+ from products.warehouse_sources.backend.facade.models import ExternalDataSource # noqa: PLC0415
+
source = warehouse_table.external_data_source
if source is not None and source.access_method == ExternalDataSource.AccessMethod.DIRECT:
return isinstance(target_hogql_table, DirectSQLTable) and target_hogql_table.external_data_source_id == str(
diff --git a/posthog/hogql/database/schema/events.py b/posthog/hogql/database/schema/events.py
index e75c16f0bfd1..b6174a1cab85 100644
--- a/posthog/hogql/database/schema/events.py
+++ b/posthog/hogql/database/schema/events.py
@@ -22,10 +22,11 @@ from posthog.hogql.database.schema.person_distinct_ids import PersonDistinctIdsT
from posthog.hogql.database.schema.persons_revenue_analytics import PersonsRevenueAnalyticsTable
from posthog.hogql.database.schema.sessions_v1 import SessionsTableV1
-from posthog.models.event.sql import DISTRIBUTED_EVENTS_JSON_TABLE
-
def events_table_clickhouse_table_ref(context) -> str:
+ # lazy import keeps the events SQL module (Django ORM) off this module's import path
+ from posthog.models.event.sql import DISTRIBUTED_EVENTS_JSON_TABLE # noqa: PLC0415
+
return DISTRIBUTED_EVENTS_JSON_TABLE if context.uses_new_events_schema() else "events"
diff --git a/posthog/hogql/database/schema/exchange_rate.py b/posthog/hogql/database/schema/exchange_rate.py
index 4ca0bc587ab0..12d786971063 100644
--- a/posthog/hogql/database/schema/exchange_rate.py
+++ b/posthog/hogql/database/schema/exchange_rate.py
@@ -9,12 +9,13 @@ from posthog.hogql.database.models import (
StringDatabaseField,
)
-from posthog.models.exchange_rate.sql import EXCHANGE_RATE_DECIMAL_PRECISION
-from posthog.models.team.team import Team
+from posthog.exchange_rate_constants import EXCHANGE_RATE_DECIMAL_PRECISION
if TYPE_CHECKING:
from posthog.schema import RevenueAnalyticsEventItem
+ from posthog.models.team.team import Team
+
class ExchangeRateTable(DANGEROUS_NoTeamIdCheckTable):
description: str = (
@@ -53,7 +54,7 @@ def convert_currency_call(
# Given an event config and the base config, figure out what the currency should look like
-def currency_expression_for_events(team: Team, event_config: "RevenueAnalyticsEventItem") -> ast.Expr:
+def currency_expression_for_events(team: "Team", event_config: "RevenueAnalyticsEventItem") -> ast.Expr:
# Shouldn't happen but we need it here to make the type checker happy
if not event_config.revenueCurrencyProperty:
return ast.Constant(value=team.base_currency)
@@ -74,7 +75,7 @@ def currency_expression_for_events(team: Team, event_config: "RevenueAnalyticsEv
# - Check whether the event is the one we're looking for
# - Convert the revenue to the base currency if needed
def revenue_comparison_and_value_exprs_for_events(
- team: Team,
+ team: "Team",
event_config: "RevenueAnalyticsEventItem",
do_currency_conversion: bool = True,
amount_expr: ast.Expr | None = None,
diff --git a/posthog/hogql/database/schema/groups_revenue_analytics.py b/posthog/hogql/database/schema/groups_revenue_analytics.py
index e36ecab85a80..130f4719a59c 100644
--- a/posthog/hogql/database/schema/groups_revenue_analytics.py
+++ b/posthog/hogql/database/schema/groups_revenue_analytics.py
@@ -14,7 +14,7 @@ from posthog.hogql.database.models import (
from posthog.hogql.database.schema.util.revenue_analytics import get_table_kind, is_event_view
from posthog.hogql.errors import ResolutionError
-from posthog.models.exchange_rate.sql import EXCHANGE_RATE_DECIMAL_PRECISION
+from posthog.exchange_rate_constants import EXCHANGE_RATE_DECIMAL_PRECISION
from posthog.schema_enums import DatabaseSchemaManagedViewTableKind
ZERO_DECIMAL = ast.Call(
diff --git a/posthog/hogql/database/schema/persons.py b/posthog/hogql/database/schema/persons.py
index ef3aa5096d2a..6bc207435cc3 100644
--- a/posthog/hogql/database/schema/persons.py
+++ b/posthog/hogql/database/schema/persons.py
@@ -1,4 +1,4 @@
-from typing import Optional, Self, cast
+from typing import TYPE_CHECKING, Optional, Self, cast
import posthoganalytics
@@ -29,9 +29,11 @@ from posthog.hogql.errors import ResolutionError
from posthog.hogql.parser import parse_select
from posthog.hogql.visitor import CloningVisitor, clone_expr
-from posthog.models.organization import Organization
from posthog.schema_enums import PersonsArgMaxVersion
+if TYPE_CHECKING:
+ from posthog.models.organization import Organization
+
PERSONS_FIELDS: dict[str, FieldOrTable] = {
"id": StringDatabaseField(
name="id", nullable=False, description="Stable person identifier; join target for `events.person_id`."
diff --git a/posthog/hogql/database/schema/persons_pdi.py b/posthog/hogql/database/schema/persons_pdi.py
index 19eee1eefe36..6d1ad4381a02 100644
--- a/posthog/hogql/database/schema/persons_pdi.py
+++ b/posthog/hogql/database/schema/persons_pdi.py
@@ -1,3 +1,5 @@
+from typing import TYPE_CHECKING
+
import posthoganalytics
from posthog.hogql.ast import SelectQuery
@@ -14,7 +16,8 @@ from posthog.hogql.database.models import (
)
from posthog.hogql.errors import ResolutionError
-from posthog.models.organization import Organization
+if TYPE_CHECKING:
+ from posthog.models.organization import Organization
# :NOTE: We already have person_distinct_ids.py, which most tables link to. This persons_pdi.py is a hack to
diff --git a/posthog/hogql/database/schema/persons_revenue_analytics.py b/posthog/hogql/database/schema/persons_revenue_analytics.py
index 165bdf3b0468..fe1bee5f06cf 100644
--- a/posthog/hogql/database/schema/persons_revenue_analytics.py
+++ b/posthog/hogql/database/schema/persons_revenue_analytics.py
@@ -14,7 +14,7 @@ from posthog.hogql.database.models import (
from posthog.hogql.database.schema.util.revenue_analytics import get_table_kind, is_event_view
from posthog.hogql.errors import ResolutionError
-from posthog.models.exchange_rate.sql import EXCHANGE_RATE_DECIMAL_PRECISION
+from posthog.exchange_rate_constants import EXCHANGE_RATE_DECIMAL_PRECISION
from posthog.schema_enums import DatabaseSchemaManagedViewTableKind
ZERO_DECIMAL = ast.Call(
diff --git a/posthog/hogql/database/schema/sessions_v1.py b/posthog/hogql/database/schema/sessions_v1.py
index 9266cabf1e50..990cdff4f9fd 100644
--- a/posthog/hogql/database/schema/sessions_v1.py
+++ b/posthog/hogql/database/schema/sessions_v1.py
@@ -21,15 +21,9 @@ from posthog.hogql.database.schema.channel_type import DEFAULT_CHANNEL_TYPES, Ch
from posthog.hogql.database.schema.util.where_clause_extractor import SessionMinTimestampWhereClauseExtractorV1
from posthog.hogql.errors import ResolutionError
-from posthog.models.sessions.sql import (
- SELECT_SESSION_PROP_STRING_VALUES_SQL,
- SELECT_SESSION_PROP_STRING_VALUES_SQL_WITH_FILTER,
-)
from posthog.queries.insight import insight_sync_execute
from posthog.schema_enums import BounceRatePageViewMode
-from products.event_definitions.backend.models.property_definition import PropertyType
-
if TYPE_CHECKING:
from posthog.models.team import Team
@@ -464,6 +458,9 @@ def get_lazy_session_table_properties_v1(search: Optional[str]):
"$end_pathname",
}
+ # lazy import keeps the event-definitions ORM off this module's import path
+ from products.event_definitions.backend.models.property_definition import PropertyType # noqa: PLC0415
+
# some fields should have a specific property type which isn't derivable from the type of database field
property_type_overrides = {
"$session_duration": PropertyType.Duration,
@@ -532,6 +529,12 @@ SESSION_PROPERTY_TO_RAW_SESSIONS_EXPR_MAP = {
def get_lazy_session_table_values_v1(key: str, search_term: Optional[str], team: "Team"):
+ # lazy import keeps the sessions SQL module (Django ORM) off this module's import path
+ from posthog.models.sessions.sql import ( # noqa: PLC0415
+ SELECT_SESSION_PROP_STRING_VALUES_SQL,
+ SELECT_SESSION_PROP_STRING_VALUES_SQL_WITH_FILTER,
+ )
+
# the sessions table does not have a properties json object like the events and person tables
if key == "$channel_type":
diff --git a/posthog/hogql/database/schema/sessions_v2.py b/posthog/hogql/database/schema/sessions_v2.py
index bfb48db12c26..4f9df3bdac3b 100644
--- a/posthog/hogql/database/schema/sessions_v2.py
+++ b/posthog/hogql/database/schema/sessions_v2.py
@@ -27,15 +27,9 @@ from posthog.hogql.database.schema.util.where_clause_extractor import (
from posthog.hogql.errors import ResolutionError
from posthog.hogql.modifiers import create_default_modifiers_for_team
-from posthog.models.raw_sessions.sessions_v2 import (
- RAW_SELECT_SESSION_PROP_STRING_VALUES_SQL,
- RAW_SELECT_SESSION_PROP_STRING_VALUES_SQL_WITH_FILTER,
-)
from posthog.queries.insight import insight_sync_execute
from posthog.schema_enums import BounceRatePageViewMode, SessionsV2JoinMode
-from products.event_definitions.backend.models.property_definition import PropertyType
-
if TYPE_CHECKING:
from posthog.schema import CustomChannelRule
@@ -572,6 +566,9 @@ def get_lazy_session_table_properties_v2(search: Optional[str]):
"$exit_pathname",
}
+ # lazy import keeps the event-definitions ORM off this module's import path
+ from products.event_definitions.backend.models.property_definition import PropertyType # noqa: PLC0415
+
# some fields should have a specific property type which isn't derivable from the type of database field
property_type_overrides = {
"$session_duration": PropertyType.Duration,
@@ -646,6 +643,12 @@ SESSION_PROPERTY_TO_RAW_SESSIONS_EXPR_MAP = {
def get_lazy_session_table_values_v2(key: str, search_term: Optional[str], team: "Team"):
+ # lazy import keeps the raw-sessions SQL module (Django ORM) off this module's import path
+ from posthog.models.raw_sessions.sessions_v2 import ( # noqa: PLC0415
+ RAW_SELECT_SESSION_PROP_STRING_VALUES_SQL,
+ RAW_SELECT_SESSION_PROP_STRING_VALUES_SQL_WITH_FILTER,
+ )
+
# the sessions table does not have a properties json object like the events and person tables
if key == "$channel_type":
diff --git a/posthog/hogql/database/schema/sessions_v3.py b/posthog/hogql/database/schema/sessions_v3.py
index 602dd91fa5c8..b0956e363976 100644
--- a/posthog/hogql/database/schema/sessions_v3.py
+++ b/posthog/hogql/database/schema/sessions_v3.py
@@ -24,14 +24,8 @@ from posthog.hogql.database.schema.util.where_clause_extractor import SessionMin
from posthog.hogql.errors import ResolutionError
from posthog.hogql.modifiers import create_default_modifiers_for_team
-from posthog.models.raw_sessions.sessions_v3 import (
- RAW_SELECT_SESSION_PROP_STRING_VALUES_SQL_V3,
- RAW_SELECT_SESSION_PROP_STRING_VALUES_SQL_WITH_FILTER_V3,
- SESSION_V3_LOWER_TIER_AD_IDS,
-)
from posthog.queries.insight import insight_sync_execute
-
-from products.event_definitions.backend.models.property_definition import PropertyType
+from posthog.raw_sessions_v3_ad_ids import SESSION_V3_LOWER_TIER_AD_IDS
if TYPE_CHECKING:
from posthog.schema import CustomChannelRule
@@ -536,6 +530,9 @@ def get_lazy_session_table_properties_v3(search: Optional[str]):
"$exit_pathname",
}
+ # lazy import keeps the event-definitions ORM off this module's import path
+ from products.event_definitions.backend.models.property_definition import PropertyType # noqa: PLC0415
+
# some fields should have a specific property type which isn't derivable from the type of database field
property_type_overrides = {
"$session_duration": PropertyType.Duration,
@@ -604,6 +601,12 @@ for session_ad_id in SESSION_V3_LOWER_TIER_AD_IDS:
def get_lazy_session_table_values_v3(key: str, search_term: Optional[str], team: "Team"):
+ # lazy import keeps the raw-sessions SQL module (Django ORM) off this module's import path
+ from posthog.models.raw_sessions.sessions_v3 import ( # noqa: PLC0415
+ RAW_SELECT_SESSION_PROP_STRING_VALUES_SQL_V3,
+ RAW_SELECT_SESSION_PROP_STRING_VALUES_SQL_WITH_FILTER_V3,
+ )
+
# the sessions table does not have a properties json object like the events and person tables
if key == "$channel_type":
diff --git a/posthog/hogql/functions/embed_text.py b/posthog/hogql/functions/embed_text.py
index b4b53ea36308..c195e1ae3ba7 100644
--- a/posthog/hogql/functions/embed_text.py
+++ b/posthog/hogql/functions/embed_text.py
@@ -1,12 +1,18 @@
+from typing import TYPE_CHECKING
+
from posthog.hogql import ast
-from posthog.api.embedding_worker import generate_embedding
-from posthog.models.team.team import Team
+if TYPE_CHECKING:
+ from posthog.models.team.team import Team
# Takes an embed text call, calls out to the embedding worker,
# and then returns an embedding.
-def resolve_embed_text(team: Team | int | None, node: ast.Call) -> ast.Constant:
+def resolve_embed_text(team: "Team | int | None", node: ast.Call) -> ast.Constant:
+ # Lazy imports keep the embedding worker (API layer) and Django ORM off this module's import path.
+ from posthog.api.embedding_worker import generate_embedding # noqa: PLC0415
+ from posthog.models.team.team import Team # noqa: PLC0415
+
args = node.args
if team is None:
diff --git a/posthog/hogql/printer/access_control.py b/posthog/hogql/printer/access_control.py
index d318c15eb8fe..8541df85ca0d 100644
--- a/posthog/hogql/printer/access_control.py
+++ b/posthog/hogql/printer/access_control.py
@@ -7,8 +7,6 @@ from posthog.hogql import ast
from posthog.hogql.context import HogQLContext
from posthog.hogql.database.postgres_table import PostgresTable
-from posthog.rbac.user_access_control import resource_to_display_name
-
if TYPE_CHECKING:
from posthog.schema import AccessControlFilterWarning
@@ -25,6 +23,8 @@ def build_access_control_warning(resources: Iterable["APIScopeObject"]) -> Optio
AccessControlFilterWarning, # noqa: PLC0415 — keeps posthog.schema off django.setup() via this module
)
+ from posthog.rbac.user_access_control import resource_to_display_name # noqa: PLC0415
+
sorted_resources = sorted(resources)
if not sorted_resources:
return None
diff --git a/posthog/hogql/printer/base.py b/posthog/hogql/printer/base.py
index b338fceae7e5..71fface8998a 100644
--- a/posthog/hogql/printer/base.py
+++ b/posthog/hogql/printer/base.py
@@ -2,7 +2,7 @@ import re
from collections.abc import Iterable
from datetime import date, datetime
from difflib import get_close_matches
-from typing import Any, ClassVar, Optional, cast, get_args
+from typing import TYPE_CHECKING, Any, ClassVar, Optional, cast, get_args
from uuid import UUID
from django.conf import settings as django_settings
@@ -34,10 +34,12 @@ from posthog.hogql.resolver_utils import lookup_field_by_name
from posthog.hogql.visitor import Visitor, clone_expr
from posthog.clickhouse.kafka_engine import json_extract_trim_quotes
-from posthog.models.team.team import WeekStartDay
from posthog.schema_enums import PersonsOnEventsMode
from posthog.uuidt import UUIDT
+if TYPE_CHECKING:
+ from posthog.models.team.team import WeekStartDay
+
MAX_PLACEHOLDER_MACRO_EXPANSION_DEPTH = 8
@@ -1525,7 +1527,9 @@ class BasePrinter(Visitor[str]):
return "UTC"
return self.context.database.get_timezone() if self.context.database else "UTC"
- def _get_week_start_day(self) -> WeekStartDay:
+ def _get_week_start_day(self) -> "WeekStartDay":
+ from posthog.models.team.team import WeekStartDay # noqa: PLC0415
+
return self.context.database.get_week_start_day() if self.context.database else WeekStartDay.SUNDAY
def _is_type_nullable(self, node_type: ast.Type) -> bool | None:
diff --git a/posthog/hogql/printer/clickhouse.py b/posthog/hogql/printer/clickhouse.py
index 77d704fd439b..53232642c72f 100644
--- a/posthog/hogql/printer/clickhouse.py
+++ b/posthog/hogql/printer/clickhouse.py
@@ -34,9 +34,8 @@ from posthog.hogql.restricted_properties import restricted_property_keys_for_tab
from posthog.hogql.type_system import parse_sql_runtime_type
from posthog.hogql.visitor import GetFieldsTraverser, clone_expr
+from posthog.exchange_rate_constants import EXCHANGE_RATE_DECIMAL_PRECISION, EXCHANGE_RATE_DICTIONARY_NAME
from posthog.models.event.sql import EVENTS_PROPERTIES_JSON_SUBCOLUMNS, PERSON_PROPERTIES_JSON_SUBCOLUMNS
-from posthog.models.exchange_rate.sql import EXCHANGE_RATE_DECIMAL_PRECISION, EXCHANGE_RATE_DICTIONARY_NAME
-from posthog.models.team.team import WeekStartDay
from posthog.uuidt import UUIDT
@@ -278,6 +277,8 @@ class ClickHousePrinter(BasePrinter):
args = [*args[:-1], "6", *args[-1:]]
if node.name == "toStartOfWeek" and len(node.args) == 1:
+ from posthog.models.team.team import WeekStartDay # noqa: PLC0415
+
# If week mode hasn't been specified, use the project's default.
# For Monday-based weeks mode 3 is used (which is ISO 8601), for Sunday-based mode 0 (CH default)
args.insert(1, WeekStartDay(self._get_week_start_day()).clickhouse_mode)
diff --git a/posthog/hogql/printer/utils.py b/posthog/hogql/printer/utils.py
index 7e429c20ef72..9fd2657bcaad 100644
--- a/posthog/hogql/printer/utils.py
+++ b/posthog/hogql/printer/utils.py
@@ -5,6 +5,8 @@ from posthog.schema_enums import InCohortVia, PropertyGroupsMode
if TYPE_CHECKING:
from posthog.schema import HogQLQueryModifiers
+ from posthog.models.team import Team
+
from posthog.hogql import ast
from posthog.hogql.base import _T_AST
from posthog.hogql.constants import SQL_TARGET_DIALECTS, HogQLDialect, HogQLGlobalSettings
@@ -46,7 +48,6 @@ from posthog.hogql.visitor import clone_expr
from posthog.hogql.workload import WorkloadCollector
from posthog.clickhouse.workload import Workload
-from posthog.models.team import Team
from posthog.models.team.event_retention import events_retention_months_for_team
from products.access_control.backend.property_access_control import get_restricted_properties_for_team
@@ -64,7 +65,7 @@ PRINTER_CLASSES: dict[HogQLDialect, type[BasePrinter]] = {
def to_printed_hogql(
query: ast.Expr,
- team: Team,
+ team: "Team",
modifiers: "HogQLQueryModifiers | None" = None,
*,
bypass_warehouse_access_control: bool = False,
diff --git a/posthog/hogql/test/test_no_django_imports.py b/posthog/hogql/test/test_no_django_imports.py
index f8fd353cf151..6234f36770b6 100644
--- a/posthog/hogql/test/test_no_django_imports.py
+++ b/posthog/hogql/test/test_no_django_imports.py
@@ -9,6 +9,8 @@ import subprocess
# importing it in a fresh interpreter raises AppRegistryNotReady and this test fails.
DJANGO_FREE_MODULES = [
"posthog.uuidt",
+ "posthog.exchange_rate_constants",
+ "posthog.raw_sessions_v3_ad_ids",
"posthog.hogql.ast",
"posthog.hogql.base",
"posthog.hogql.visitor",
@@ -19,6 +21,12 @@ DJANGO_FREE_MODULES = [
"posthog.hogql.functions.mapping",
"posthog.hogql.database.models",
"posthog.hogql.parser",
+ # database.database transitively imports every schema table module, so importing it here
+ # guards the whole schema layer; the resolver is the headline Seam 0 win (parse -> resolve
+ # -> AST with no django.setup()). The printer stays coupled until the property-metadata
+ # providers land (it transitively imports the property transforms).
+ "posthog.hogql.database.database",
+ "posthog.hogql.resolver",
]
_CHILD = f"""
@@ -27,8 +35,11 @@ for mod in {DJANGO_FREE_MODULES!r}:
importlib.import_module(mod)
from posthog.hogql import ast
from posthog.hogql.parser import parse_expr, parse_select
+from posthog.hogql.database.database import Database
assert isinstance(parse_select("select 1"), ast.SelectQuery)
assert isinstance(parse_expr("1 + 1"), ast.Expr)
+# The static table catalog builds without Django — no team, no ORM.
+assert Database(include_posthog_tables=True).has_table("events")
print("DJANGO_FREE_OK")
"""
diff --git a/posthog/models/exchange_rate/sql.py b/posthog/models/exchange_rate/sql.py
index 7fb311f6ee94..2ac15e210ede 100644
--- a/posthog/models/exchange_rate/sql.py
+++ b/posthog/models/exchange_rate/sql.py
@@ -106,16 +106,13 @@ def HISTORICAL_EXCHANGE_RATE_TUPLES():
yield (date, currency, rate)
-EXCHANGE_RATE_TABLE_NAME = "exchange_rate"
-EXCHANGE_RATE_DICTIONARY_NAME = "exchange_rate_dict"
-
-# Storing 10 decimal places is more than enough
-# Ideally we should have gone with 4 because that's all we need for most currencies
-# but Bitcoin messes this up because it's so valuable compared to the Dollar (our base currency)
-#
-# If Bitcoin ever moons it even further, we can increase this to 12 or 14
-# but for now 10 is more than enough
-EXCHANGE_RATE_DECIMAL_PRECISION = 10
+# Re-exported from the Django-free posthog.exchange_rate_constants module so the HogQL engine can
+# use them without booting Django; kept importable here for existing callers.
+from posthog.exchange_rate_constants import ( # noqa: E402
+ EXCHANGE_RATE_DECIMAL_PRECISION,
+ EXCHANGE_RATE_DICTIONARY_NAME,
+ EXCHANGE_RATE_TABLE_NAME,
+)
# `version` is used to ensure the latest version is kept, see https://clickhouse.com/docs/engines/table-engines/mergetree-family/replacingmergetree
diff --git a/posthog/models/raw_sessions/sessions_v3.py b/posthog/models/raw_sessions/sessions_v3.py
index 726d0e4bca37..6fdab7782910 100644
--- a/posthog/models/raw_sessions/sessions_v3.py
+++ b/posthog/models/raw_sessions/sessions_v3.py
@@ -235,23 +235,9 @@ def ALTER_SHARDED_RAW_SESSIONS_TABLE_SETTINGS_V3():
)
-SESSION_V3_LOWER_TIER_AD_IDS = [
- "gclsrc",
- "dclid",
- "gbraid",
- "wbraid",
- "msclkid",
- "twclid",
- "li_fat_id",
- "mc_cid",
- "igshid",
- "ttclid",
- "epik",
- "qclid",
- "sccid",
- "_kx",
- "irclid",
-]
+# Re-exported from the Django-free posthog.raw_sessions_v3_ad_ids module so the HogQL schema can
+# use it without booting Django; kept importable here for existing callers.
+from posthog.raw_sessions_v3_ad_ids import SESSION_V3_LOWER_TIER_AD_IDS # noqa: E402
new_line = "\n"
diff --git a/posthog/raw_sessions_v3_ad_ids.py b/posthog/raw_sessions_v3_ad_ids.py
new file mode 100644
index 000000000000..bb5e36f4c265
--- /dev/null
+++ b/posthog/raw_sessions_v3_ad_ids.py
@@ -0,0 +1,22 @@
+# Django-free home for the raw-sessions-v3 lower-tier ad-id list. Kept out of
+# posthog.models.raw_sessions.sessions_v3 (whose package __init__ boots the Django ORM) so the
+# HogQL sessions_v3 schema table can build its field catalog at import without booting Django.
+# posthog.models.raw_sessions.sessions_v3 re-exports this for existing callers.
+
+SESSION_V3_LOWER_TIER_AD_IDS = [
+ "gclsrc",
+ "dclid",
+ "gbraid",
+ "wbraid",
+ "msclkid",
+ "twclid",
+ "li_fat_id",
+ "mc_cid",
+ "igshid",
+ "ttclid",
+ "epik",
+ "qclid",
+ "sccid",
+ "_kx",
+ "irclid",
+]