: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): skip HogQL Database build on source list endpoint (#65445)
Tom Owersf6f9d06b1187
diff --git a/products/data_warehouse/backend/api/external_data_schema.py b/products/data_warehouse/backend/api/external_data_schema.pyindex 2568cc9c58d3..c188ab84203a 100644--- a/products/data_warehouse/backend/api/external_data_schema.py+++ b/products/data_warehouse/backend/api/external_data_schema.py@@ -424,17 +424,23 @@ class ExternalDataSchemaSerializer(serializers.ModelSerializer):def get_table(self, schema: ExternalDataSchema) -> Optional[dict]:from products.data_warehouse.backend.api.table import SimpleTableSerializer- hogql_context = self.context.get("database", None)- if not hogql_context:- hogql_context = Database.create_for(- team_id=self.context["team_id"],- user=cast(User, self.context["request"].user),- )-if schema.table and schema.table.deleted:return None- return SimpleTableSerializer(schema.table, context={"database": hogql_context}).data or None+ # Serializing table columns requires the full HogQL Database, which is expensive to build.+ # Callers that don't need columns (e.g. the source list) set include_columns=False so we skip it.+ include_columns = self.context.get("include_columns", True)+ table_context: dict[str, Any] = {"include_columns": include_columns, "team_id": self.context.get("team_id")}+ if include_columns:+ hogql_context = self.context.get("database", None)+ if not hogql_context:+ hogql_context = Database.create_for(+ team_id=self.context["team_id"],+ user=cast(User, self.context["request"].user),+ )+ table_context["database"] = hogql_context++ return SimpleTableSerializer(schema.table, context=table_context).data or Nonedef to_representation(self, instance: ExternalDataSchema) -> dict:ret = super().to_representation(instance)diff --git a/products/data_warehouse/backend/api/external_data_source.py b/products/data_warehouse/backend/api/external_data_source.pyindex d981686e80d3..58208960fc8c 100644--- a/products/data_warehouse/backend/api/external_data_source.py+++ b/products/data_warehouse/backend/api/external_data_source.py@@ -1321,7 +1321,13 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixidef get_serializer_context(self) -> dict[str, Any]:context = super().get_serializer_context()- context["database"] = Database.create_for(team_id=self.team_id, user=cast(User, self.request.user))+ # Building the full HogQL Database and serializing per-schema table columns is expensive+ # and only needed when a caller reads `schemas[].table.columns` — which the source list view+ # never does (it only reads name/row_count). Gate both to single-source reads.+ include_columns = self.action != "list"+ context["include_columns"] = include_columns+ if include_columns:+ context["database"] = Database.create_for(team_id=self.team_id, user=cast(User, self.request.user))return contextdiff --git a/products/data_warehouse/backend/api/table.py b/products/data_warehouse/backend/api/table.pyindex e24ce668aa6e..6046ca17c2c5 100644--- a/products/data_warehouse/backend/api/table.py+++ b/products/data_warehouse/backend/api/table.py@@ -216,6 +216,11 @@ class SimpleTableSerializer(UserAccessControlSerializerMixin, serializers.ModelSreturn get_data_warehouse_table_name(table.external_data_source, table.name)def get_columns(self, table: DataWarehouseTable) -> list[SerializedField]:+ # Callers that don't consume columns (e.g. the source list) skip the expensive HogQL+ # field serialization entirely by passing include_columns=False.+ if not self.context.get("include_columns", True):+ return []+database = self.context.get("database", None)team_id = self.context.get("team_id", None)diff --git a/products/data_warehouse/backend/api/test/test_external_data_source.py b/products/data_warehouse/backend/api/test/test_external_data_source.pyindex fa0aab7c5e57..ed718b119aaa 100644--- a/products/data_warehouse/backend/api/test/test_external_data_source.py+++ b/products/data_warehouse/backend/api/test/test_external_data_source.py@@ -1472,13 +1472,55 @@ class TestExternalDataSource(APIBaseTest):self._create_external_data_source()# A cached instance setting lookup can shave off one query depending on test order.- with self.assertNumQueries(FuzzyInt(23, 25)):+ # The list no longer builds the full HogQL Database (only needed to serialize table columns,+ # which the list omits), so it's much cheaper than the single-source read path.+ with self.assertNumQueries(FuzzyInt(13, 15)):response = self.client.get(f"/api/environments/{self.team.pk}/external_data_sources/")payload = response.json()self.assertEqual(response.status_code, 200)self.assertEqual(len(payload["results"]), 2)+ def test_list_omits_table_columns_but_retrieve_includes_them(self):+ source = ExternalDataSource.objects.create(+ team_id=self.team.pk,+ source_id=str(uuid.uuid4()),+ connection_id=str(uuid.uuid4()),+ destination_id=str(uuid.uuid4()),+ source_type="Postgres",+ created_by=self.user,+ prefix="test",+ access_method=ExternalDataSource.AccessMethod.DIRECT,+ job_inputs={"host": "localhost", "port": 5432},+ )+ table = DataWarehouseTable.objects.create(+ name="Accounts",+ format=DataWarehouseTable.TableFormat.Parquet,+ team=self.team,+ url_pattern=DIRECT_POSTGRES_URL_PATTERN,+ external_data_source=source,+ columns={"id": {"clickhouse": "Int32", "hogql": "integer", "valid": True}},+ )+ ExternalDataSchema.objects.create(+ team_id=self.team.pk,+ source_id=source.pk,+ name="Accounts",+ should_sync=True,+ table=table,+ )++ # The list view never reads schemas[].table.columns, so it skips the expensive+ # HogQL field serialization and returns an empty column list.+ list_payload = self.client.get(f"/api/environments/{self.team.pk}/external_data_sources/").json()+ list_table = list_payload["results"][0]["schemas"][0]["table"]+ self.assertEqual(list_table["name"], "Accounts")+ self.assertEqual(list_table["columns"], [])++ # The single-source read still populates columns for the schema detail page.+ retrieve_payload = self.client.get(f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}").json()+ retrieve_columns = retrieve_payload["schemas"][0]["table"]["columns"]+ self.assertTrue(any(column["key"] == "id" for column in retrieve_columns))+def _create_searchable_source(self, source_type: str, prefix: str) -> ExternalDataSource:return ExternalDataSource.objects.create(team_id=self.team.pk,