:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(data-warehouse): build HogQL database lazily on view-link requests (#66846)
posthog[bot]4497cccb71c9
diff --git a/products/data_warehouse/backend/presentation/views/view_link.py b/products/data_warehouse/backend/presentation/views/view_link.pyindex 5bd80ada7bed..61b5f3489008 100644--- a/products/data_warehouse/backend/presentation/views/view_link.py+++ b/products/data_warehouse/backend/presentation/views/view_link.py@@ -34,6 +34,9 @@ class ViewLinkValidationMixin:team_id=team_id,user=cast(User, self.context["request"].user), # type: ignore[attr-defined])+ # Cache on the shared context so a list response builds the database at most+ # once instead of once per serialized row.+ self.context["database"] = database # type: ignore[attr-defined]return databasedef get_table_name(self, table_name: str) -> str:@@ -178,12 +181,6 @@ class ViewLinkViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsetdef get_serializer_class(self):return self.serializer_classes.get(self.action, self.serializer_classes["default"])- def get_serializer_context(self):- context = super().get_serializer_context()- user = cast(User, self.request.user)- context["database"] = Database.create_for(team_id=self.team_id, user=user)- return context-def safely_get_queryset(self, queryset):return queryset.prefetch_related("created_by").order_by(self.ordering)@@ -210,7 +207,11 @@ class ViewLinkViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsetserializer.is_valid(raise_exception=True)join = DataWarehouseJoin(**request.data)- database = serializer.context["database"]+ # is_valid() builds and caches the database via the serializer's lazy fallback;+ # fall back to an explicit build to stay correct if that ever stops happening.+ database = serializer.context.get("database") or Database.create_for(+ team_id=self.team_id, user=cast(User, request.user)+ )source_table_name = serializer.validated_data["source_table_name"]source_table = database.get_table(source_table_name)diff --git a/products/data_warehouse/backend/tests/api/test_view_link.py b/products/data_warehouse/backend/tests/api/test_view_link.pyindex 08a833acc7ab..b9f38d480c88 100644--- a/products/data_warehouse/backend/tests/api/test_view_link.py+++ b/products/data_warehouse/backend/tests/api/test_view_link.py@@ -8,6 +8,7 @@ from rest_framework import statusfrom posthog.schema import HogQLQueryResponse+from posthog.hogql.database.database import Databasefrom posthog.hogql.query import HogQLQueryExecutorfrom products.data_tools.backend.models.join import DataWarehouseJoin@@ -19,6 +20,8 @@ from products.warehouse_sources.backend.facade.models import ()from products.warehouse_sources.backend.facade.types import ExternalDataSourceType+VIEW_LINK_PATH = "products.data_warehouse.backend.presentation.views.view_link"+class TestViewLinkQuery(APIBaseTest):def test_create(self):@@ -240,6 +243,54 @@ class TestViewLinkQuery(APIBaseTest):self.assertEqual(DataWarehouseJoin.objects.all().count(), 0)+ def test_list_empty_does_not_build_database(self):+ # An empty list must not eagerly build the full HogQL database, which is a heavy+ # chain of serial Postgres queries that previously ran on every single request.+ with patch(f"{VIEW_LINK_PATH}.Database.create_for", wraps=Database.create_for) as mock_create_for:+ response = self.client.get(f"/api/environments/{self.team.id}/warehouse_view_links/")++ self.assertEqual(response.status_code, 200)+ self.assertEqual(response.json()["results"], [])+ mock_create_for.assert_not_called()++ def test_delete_does_not_build_database(self):+ join = DataWarehouseJoin.objects.create(+ team=self.team,+ source_table_name="events",+ source_table_key="distinct_id",+ joining_table_name="persons",+ joining_table_key="id",+ field_name="some_field",+ configuration=None,+ )++ with patch(f"{VIEW_LINK_PATH}.Database.create_for", wraps=Database.create_for) as mock_create_for:+ response = self.client.delete(f"/api/environments/{self.team.id}/warehouse_view_links/{join.id}/")++ self.assertEqual(response.status_code, 204, response.content)+ mock_create_for.assert_not_called()++ def test_list_builds_database_at_most_once(self):+ for field_name, joining_table in (("a_field", "persons"), ("b_field", "groups"), ("c_field", "cohorts")):+ DataWarehouseJoin.objects.create(+ team=self.team,+ source_table_name="events",+ source_table_key="distinct_id",+ joining_table_name=joining_table,+ joining_table_key="id",+ field_name=field_name,+ configuration=None,+ )++ # A populated list resolves each row's table names against the database, but it must+ # build the database once for the whole response — not once per serialized row.+ with patch(f"{VIEW_LINK_PATH}.Database.create_for", wraps=Database.create_for) as mock_create_for:+ response = self.client.get(f"/api/environments/{self.team.id}/warehouse_view_links/")++ self.assertEqual(response.status_code, 200)+ self.assertEqual(len(response.json()["results"]), 3)+ self.assertEqual(mock_create_for.call_count, 1)+def test_list(self):join1 = DataWarehouseJoin.objects.create(team=self.team,