: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): ignore deleted-source tables when resolving names (#61855)
Marcus Hofa56e881127d0
diff --git a/posthog/hogql/database/database.py b/posthog/hogql/database/database.pyindex c1d1383a925e..7cde87395659 100644--- a/posthog/hogql/database/database.py+++ b/posthog/hogql/database/database.py@@ -708,8 +708,13 @@ class Database(BaseModel):to_attr="latest_completed_job",),)- .filter(Q(deleted=False) | Q(deleted__isnull=True), team_id=context.team_id)- .order_by("external_data_source__prefix", "external_data_source__source_type", "name")+ # `queryable()` drops soft-deleted tables and orphans of a soft-deleted source, so an+ # orphan can't shadow the live table sharing its name in the SQL editor catalog.+ .queryable()+ .filter(team_id=context.team_id)+ # The catalog is built last-write-wins per table key, so order created_at ascending to+ # land the newest row last when two live tables share a name — matching tree resolution.+ .order_by("external_data_source__prefix", "external_data_source__source_type", "name", "created_at"))if self._is_direct_query():warehouse_tables_query = warehouse_tables_query.filter(external_data_source_id=self._connection_id)@@ -1168,9 +1173,14 @@ class Database(BaseModel):with timings.measure("select"):tables_query = (+ # `queryable()` drops soft-deleted tables and orphans left by a soft-deleted+ # source, so an orphan can't shadow the live table sharing its name.DataWarehouseTable.raw_objects.filter(team_id=team.pk)- .exclude(deleted=True)+ .queryable().select_related("credential", "external_data_source")+ # Deterministic tiebreak when two live tables share a name: newest wins, since+ # name collisions resolve first-come-first-served when added to the table tree.+ .order_by("-created_at"))if database._is_direct_query():tables_query = tables_query.filter(external_data_source_id=database._connection_id)diff --git a/posthog/hogql/database/test/__snapshots__/test_database.ambr b/posthog/hogql/database/test/__snapshots__/test_database.ambrindex 2d11964291a8..bcb1e55ce946 100644--- a/posthog/hogql/database/test/__snapshots__/test_database.ambr+++ b/posthog/hogql/database/test/__snapshots__/test_database.ambr@@ -237,8 +237,11 @@WHERE ("posthog_datawarehousetable"."team_id" = 99999AND NOT ("posthog_datawarehousetable"."deleted"AND "posthog_datawarehousetable"."deleted" IS NOT NULL)+ AND NOT ("posthog_externaldatasource"."deleted"+ AND "posthog_externaldatasource"."deleted" IS NOT NULL)AND NOT ("posthog_externaldatasource"."access_method" = 'direct'AND "posthog_externaldatasource"."access_method" IS NOT NULL))+ ORDER BY "posthog_datawarehousetable"."created_at" DESC'''# ---# name: TestDatabase.test_database_with_warehouse_tables_and_saved_queries_n_plus_1.4@@ -469,8 +472,11 @@WHERE ("posthog_datawarehousetable"."team_id" = 99999AND NOT ("posthog_datawarehousetable"."deleted"AND "posthog_datawarehousetable"."deleted" IS NOT NULL)+ AND NOT ("posthog_externaldatasource"."deleted"+ AND "posthog_externaldatasource"."deleted" IS NOT NULL)AND NOT ("posthog_externaldatasource"."access_method" = 'direct'AND "posthog_externaldatasource"."access_method" IS NOT NULL))+ ORDER BY "posthog_datawarehousetable"."created_at" DESC'''# ---# name: TestDatabase.test_database_with_warehouse_tables_and_saved_queries_n_plus_1.9diff --git a/posthog/hogql/database/test/test_database.py b/posthog/hogql/database/test/test_database.pyindex 35e87fb43a74..6e92604681f9 100644--- a/posthog/hogql/database/test/test_database.py+++ b/posthog/hogql/database/test/test_database.py@@ -37,6 +37,7 @@ from posthog.hogql.database.models import (TableNode,)from posthog.hogql.database.postgres_table import PostgresTable+from posthog.hogql.database.s3_table import DataWarehouseTable as HogQLDataWarehouseTablefrom posthog.hogql.errors import ExposedHogQLErrorfrom posthog.hogql.modifiers import create_default_modifiers_for_teamfrom posthog.hogql.parser import parse_expr, parse_select@@ -382,6 +383,78 @@ class TestDatabase(BaseTest, QueryMatchingTest):assert field.type == "string"assert field.schema_valid is True+ def _create_warehouse_table(self, *, name, url_pattern, source=None, credential=None):+ return DataWarehouseTable.objects.create(+ name=name,+ format="Parquet",+ team=self.team,+ external_data_source=source,+ credential=credential,+ url_pattern=url_pattern,+ columns={"id": {"hogql": "StringDatabaseField", "clickhouse": "Nullable(String)", "schema_valid": True}},+ )++ def test_create_hogql_database_ignores_tables_of_deleted_sources(self):+ # A table left behind by a soft-deleted source must not shadow the live table that a+ # re-connected source created under the same name (the orphan-table resolution bug).+ credential = DataWarehouseCredential.objects.create(team=self.team, access_key="k", access_secret="s")++ deleted_source = ExternalDataSource.objects.create(+ team=self.team,+ source_id="old",+ connection_id="old",+ status=ExternalDataSource.Status.COMPLETED,+ source_type=ExternalDataSourceType.STRIPE,+ )+ # Created first, so without the fix it would win the first-come tree insertion. Mark the+ # source — not the table — deleted to reproduce the orphan state (table.deleted stays False).+ self._create_warehouse_table(+ name="pull_requests", url_pattern="s3://orphan/*", source=deleted_source, credential=credential+ )+ deleted_source.deleted = True+ deleted_source.save()++ live_source = ExternalDataSource.objects.create(+ team=self.team,+ source_id="new",+ connection_id="new",+ status=ExternalDataSource.Status.COMPLETED,+ source_type=ExternalDataSourceType.STRIPE,+ )+ self._create_warehouse_table(+ name="pull_requests", url_pattern="s3://live/*", source=live_source, credential=credential+ )++ database = Database.create_for(team=self.team)++ assert database.has_table("pull_requests")+ assert cast(HogQLDataWarehouseTable, database.get_table("pull_requests")).url == "s3://live/*"++ def test_create_hogql_database_keeps_self_managed_table_without_source(self):+ # Guards the deleted-source exclusion against the Django exclude()-with-NULL gotcha:+ # a self-managed table (no source) must still resolve.+ credential = DataWarehouseCredential.objects.create(team=self.team, access_key="k", access_secret="s")+ self._create_warehouse_table(name="self_managed", url_pattern="s3://self/*", credential=credential)++ database = Database.create_for(team=self.team)++ assert database.has_table("self_managed")+ assert cast(HogQLDataWarehouseTable, database.get_table("self_managed")).url == "s3://self/*"++ def test_create_hogql_database_resolves_duplicate_live_table_names_to_newest(self):+ # Two live tables share a name (e.g. a re-sync produced a duplicate): newest wins.+ credential = DataWarehouseCredential.objects.create(team=self.team, access_key="k", access_secret="s")+ older = self._create_warehouse_table(name="pull_requests", url_pattern="s3://older/*", credential=credential)+ newer = self._create_warehouse_table(name="pull_requests", url_pattern="s3://newer/*", credential=credential)++ # Pin created_at explicitly (bypasses auto_now_add) so the tiebreak is deterministic.+ DataWarehouseTable.objects.filter(pk=older.pk).update(created_at="2024-01-01T00:00:00+00:00")+ DataWarehouseTable.objects.filter(pk=newer.pk).update(created_at="2024-06-01T00:00:00+00:00")++ database = Database.create_for(team=self.team)++ assert cast(HogQLDataWarehouseTable, database.get_table("pull_requests")).url == "s3://newer/*"+def test_serialize_database_warehouse_table_source_query_count(self):source = ExternalDataSource.objects.create(team=self.team,diff --git a/posthog/session_recordings/test/__snapshots__/test_session_recording_playlist.ambr b/posthog/session_recordings/test/__snapshots__/test_session_recording_playlist.ambrindex 401ab2e028ca..25abbdd495a4 100644--- a/posthog/session_recordings/test/__snapshots__/test_session_recording_playlist.ambr+++ b/posthog/session_recordings/test/__snapshots__/test_session_recording_playlist.ambr@@ -1274,8 +1274,11 @@WHERE ("posthog_datawarehousetable"."team_id" = 99999AND NOT ("posthog_datawarehousetable"."deleted"AND "posthog_datawarehousetable"."deleted" IS NOT NULL)+ AND NOT ("posthog_externaldatasource"."deleted"+ AND "posthog_externaldatasource"."deleted" IS NOT NULL)AND NOT ("posthog_externaldatasource"."access_method" = 'direct'AND "posthog_externaldatasource"."access_method" IS NOT NULL))+ ORDER BY "posthog_datawarehousetable"."created_at" DESC'''# ---# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.34@@ -2516,8 +2519,11 @@WHERE ("posthog_datawarehousetable"."team_id" = 99999AND NOT ("posthog_datawarehousetable"."deleted"AND "posthog_datawarehousetable"."deleted" IS NOT NULL)+ AND NOT ("posthog_externaldatasource"."deleted"+ AND "posthog_externaldatasource"."deleted" IS NOT NULL)AND NOT ("posthog_externaldatasource"."access_method" = 'direct'AND "posthog_externaldatasource"."access_method" IS NOT NULL))+ ORDER BY "posthog_datawarehousetable"."created_at" DESC'''# ---# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.57diff --git a/posthog/session_recordings/test/__snapshots__/test_session_recordings.ambr b/posthog/session_recordings/test/__snapshots__/test_session_recordings.ambrindex 0ee0e2b9ebf8..408fac3548f5 100644--- a/posthog/session_recordings/test/__snapshots__/test_session_recordings.ambr+++ b/posthog/session_recordings/test/__snapshots__/test_session_recordings.ambr@@ -146,8 +146,11 @@WHERE ("posthog_datawarehousetable"."team_id" = 99999AND NOT ("posthog_datawarehousetable"."deleted"AND "posthog_datawarehousetable"."deleted" IS NOT NULL)+ AND NOT ("posthog_externaldatasource"."deleted"+ AND "posthog_externaldatasource"."deleted" IS NOT NULL)AND NOT ("posthog_externaldatasource"."access_method" = 'direct'AND "posthog_externaldatasource"."access_method" IS NOT NULL))+ ORDER BY "posthog_datawarehousetable"."created_at" DESC'''# ---# name: TestSessionRecordings.test_get_session_recordings_returns_newest_first.11@@ -967,8 +970,11 @@WHERE ("posthog_datawarehousetable"."team_id" = 99999AND NOT ("posthog_datawarehousetable"."deleted"AND "posthog_datawarehousetable"."deleted" IS NOT NULL)+ AND NOT ("posthog_externaldatasource"."deleted"+ AND "posthog_externaldatasource"."deleted" IS NOT NULL)AND NOT ("posthog_externaldatasource"."access_method" = 'direct'AND "posthog_externaldatasource"."access_method" IS NOT NULL))+ ORDER BY "posthog_datawarehousetable"."created_at" DESC'''# ---# name: TestSessionRecordings.test_get_session_recordings_scenarios_0_basic_listing.11@@ -1784,8 +1790,11 @@WHERE ("posthog_datawarehousetable"."team_id" = 99999AND NOT ("posthog_datawarehousetable"."deleted"AND "posthog_datawarehousetable"."deleted" IS NOT NULL)+ AND NOT ("posthog_externaldatasource"."deleted"+ AND "posthog_externaldatasource"."deleted" IS NOT NULL)AND NOT ("posthog_externaldatasource"."access_method" = 'direct'AND "posthog_externaldatasource"."access_method" IS NOT NULL))+ ORDER BY "posthog_datawarehousetable"."created_at" DESC'''# ---# name: TestSessionRecordings.test_get_session_recordings_scenarios_1_multiple_snapshots.11@@ -2597,8 +2606,11 @@WHERE ("posthog_datawarehousetable"."team_id" = 99999AND NOT ("posthog_datawarehousetable"."deleted"AND "posthog_datawarehousetable"."deleted" IS NOT NULL)+ AND NOT ("posthog_externaldatasource"."deleted"+ AND "posthog_externaldatasource"."deleted" IS NOT NULL)AND NOT ("posthog_externaldatasource"."access_method" = 'direct'AND "posthog_externaldatasource"."access_method" IS NOT NULL))+ ORDER BY "posthog_datawarehousetable"."created_at" DESC'''# ---# name: TestSessionRecordings.test_get_session_recordings_scenarios_2_many_distinct_ids.11@@ -3410,8 +3422,11 @@WHERE ("posthog_datawarehousetable"."team_id" = 99999AND NOT ("posthog_datawarehousetable"."deleted"AND "posthog_datawarehousetable"."deleted" IS NOT NULL)+ AND NOT ("posthog_externaldatasource"."deleted"+ AND "posthog_externaldatasource"."deleted" IS NOT NULL)AND NOT ("posthog_externaldatasource"."access_method" = 'direct'AND "posthog_externaldatasource"."access_method" IS NOT NULL))+ ORDER BY "posthog_datawarehousetable"."created_at" DESC'''# ---# name: TestSessionRecordings.test_get_session_recordings_sorted_0_descending_original_.11@@ -4227,8 +4242,11 @@WHERE ("posthog_datawarehousetable"."team_id" = 99999AND NOT ("posthog_datawarehousetable"."deleted"AND "posthog_datawarehousetable"."deleted" IS NOT NULL)+ AND NOT ("posthog_externaldatasource"."deleted"+ AND "posthog_externaldatasource"."deleted" IS NOT NULL)AND NOT ("posthog_externaldatasource"."access_method" = 'direct'AND "posthog_externaldatasource"."access_method" IS NOT NULL))+ ORDER BY "posthog_datawarehousetable"."created_at" DESC'''# ---# name: TestSessionRecordings.test_get_session_recordings_sorted_1_descending.11@@ -5044,8 +5062,11 @@WHERE ("posthog_datawarehousetable"."team_id" = 99999AND NOT ("posthog_datawarehousetable"."deleted"AND "posthog_datawarehousetable"."deleted" IS NOT NULL)+ AND NOT ("posthog_externaldatasource"."deleted"+ AND "posthog_externaldatasource"."deleted" IS NOT NULL)AND NOT ("posthog_externaldatasource"."access_method" = 'direct'AND "posthog_externaldatasource"."access_method" IS NOT NULL))+ ORDER BY "posthog_datawarehousetable"."created_at" DESC'''# ---# name: TestSessionRecordings.test_get_session_recordings_sorted_2_ascending.11@@ -5915,8 +5936,11 @@WHERE ("posthog_datawarehousetable"."team_id" = 99999AND NOT ("posthog_datawarehousetable"."deleted"AND "posthog_datawarehousetable"."deleted" IS NOT NULL)+ AND NOT ("posthog_externaldatasource"."deleted"+ AND "posthog_externaldatasource"."deleted" IS NOT NULL)AND NOT ("posthog_externaldatasource"."access_method" = 'direct'AND "posthog_externaldatasource"."access_method" IS NOT NULL))+ ORDER BY "posthog_datawarehousetable"."created_at" DESC'''# ---# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.102@@ -6872,8 +6896,11 @@WHERE ("posthog_datawarehousetable"."team_id" = 99999AND NOT ("posthog_datawarehousetable"."deleted"AND "posthog_datawarehousetable"."deleted" IS NOT NULL)+ AND NOT ("posthog_externaldatasource"."deleted"+ AND "posthog_externaldatasource"."deleted" IS NOT NULL)AND NOT ("posthog_externaldatasource"."access_method" = 'direct'AND "posthog_externaldatasource"."access_method" IS NOT NULL))+ ORDER BY "posthog_datawarehousetable"."created_at" DESC'''# ---# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.118@@ -7783,8 +7810,11 @@WHERE ("posthog_datawarehousetable"."team_id" = 99999AND NOT ("posthog_datawarehousetable"."deleted"AND "posthog_datawarehousetable"."deleted" IS NOT NULL)+ AND NOT ("posthog_externaldatasource"."deleted"+ AND "posthog_externaldatasource"."deleted" IS NOT NULL)AND NOT ("posthog_externaldatasource"."access_method" = 'direct'AND "posthog_externaldatasource"."access_method" IS NOT NULL))+ ORDER BY "posthog_datawarehousetable"."created_at" DESC'''# ---# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.134@@ -8747,8 +8777,11 @@WHERE ("posthog_datawarehousetable"."team_id" = 99999AND NOT ("posthog_datawarehousetable"."deleted"AND "posthog_datawarehousetable"."deleted" IS NOT NULL)+ AND NOT ("posthog_externaldatasource"."deleted"+ AND "posthog_externaldatasource"."deleted" IS NOT NULL)AND NOT ("posthog_externaldatasource"."access_method" = 'direct'AND "posthog_externaldatasource"."access_method" IS NOT NULL))+ ORDER BY "posthog_datawarehousetable"."created_at" DESC'''# ---# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.15@@ -9676,8 +9709,11 @@WHERE ("posthog_datawarehousetable"."team_id" = 99999AND NOT ("posthog_datawarehousetable"."deleted"AND "posthog_datawarehousetable"."deleted" IS NOT NULL)+ AND NOT ("posthog_externaldatasource"."deleted"+ AND "posthog_externaldatasource"."deleted" IS NOT NULL)AND NOT ("posthog_externaldatasource"."access_method" = 'direct'AND "posthog_externaldatasource"."access_method" IS NOT NULL))+ ORDER BY "posthog_datawarehousetable"."created_at" DESC'''# ---# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.166@@ -10328,8 +10364,11 @@WHERE ("posthog_datawarehousetable"."team_id" = 99999AND NOT ("posthog_datawarehousetable"."deleted"AND "posthog_datawarehousetable"."deleted" IS NOT NULL)+ AND NOT ("posthog_externaldatasource"."deleted"+ AND "posthog_externaldatasource"."deleted" IS NOT NULL)AND NOT ("posthog_externaldatasource"."access_method" = 'direct'AND "posthog_externaldatasource"."access_method" IS NOT NULL))+ ORDER BY "posthog_datawarehousetable"."created_at" DESC'''# ---# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.22@@ -11179,8 +11218,11 @@WHERE ("posthog_datawarehousetable"."team_id" = 99999AND NOT ("posthog_datawarehousetable"."deleted"AND "posthog_datawarehousetable"."deleted" IS NOT NULL)+ AND NOT ("posthog_externaldatasource"."deleted"+ AND "posthog_externaldatasource"."deleted" IS NOT NULL)AND NOT ("posthog_externaldatasource"."access_method" = 'direct'AND "posthog_externaldatasource"."access_method" IS NOT NULL))+ ORDER BY "posthog_datawarehousetable"."created_at" DESC'''# ---# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.38@@ -12078,8 +12120,11 @@WHERE ("posthog_datawarehousetable"."team_id" = 99999AND NOT ("posthog_datawarehousetable"."deleted"AND "posthog_datawarehousetable"."deleted" IS NOT NULL)+ AND NOT ("posthog_externaldatasource"."deleted"+ AND "posthog_externaldatasource"."deleted" IS NOT NULL)AND NOT ("posthog_externaldatasource"."access_method" = 'direct'AND "posthog_externaldatasource"."access_method" IS NOT NULL))+ ORDER BY "posthog_datawarehousetable"."created_at" DESC'''# ---# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.54@@ -12951,8 +12996,11 @@WHERE ("posthog_datawarehousetable"."team_id" = 99999AND NOT ("posthog_datawarehousetable"."deleted"AND "posthog_datawarehousetable"."deleted" IS NOT NULL)+ AND NOT ("posthog_externaldatasource"."deleted"+ AND "posthog_externaldatasource"."deleted" IS NOT NULL)AND NOT ("posthog_externaldatasource"."access_method" = 'direct'AND "posthog_externaldatasource"."access_method" IS NOT NULL))+ ORDER BY "posthog_datawarehousetable"."created_at" DESC'''# ---# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.7@@ -13854,8 +13902,11 @@WHERE ("posthog_datawarehousetable"."team_id" = 99999AND NOT ("posthog_datawarehousetable"."deleted"AND "posthog_datawarehousetable"."deleted" IS NOT NULL)+ AND NOT ("posthog_externaldatasource"."deleted"+ AND "posthog_externaldatasource"."deleted" IS NOT NULL)AND NOT ("posthog_externaldatasource"."access_method" = 'direct'AND "posthog_externaldatasource"."access_method" IS NOT NULL))+ ORDER BY "posthog_datawarehousetable"."created_at" DESC'''# ---# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.86@@ -14113,8 +14164,11 @@WHERE ("posthog_datawarehousetable"."team_id" = 99999AND NOT ("posthog_datawarehousetable"."deleted"AND "posthog_datawarehousetable"."deleted" IS NOT NULL)+ AND NOT ("posthog_externaldatasource"."deleted"+ AND "posthog_externaldatasource"."deleted" IS NOT NULL)AND NOT ("posthog_externaldatasource"."access_method" = 'direct'AND "posthog_externaldatasource"."access_method" IS NOT NULL))+ ORDER BY "posthog_datawarehousetable"."created_at" DESC'''# ---# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.90diff --git a/products/warehouse_sources/backend/models/table.py b/products/warehouse_sources/backend/models/table.pyindex 90b182de2a42..e37eccf87e8b 100644--- a/products/warehouse_sources/backend/models/table.py+++ b/products/warehouse_sources/backend/models/table.py@@ -2,7 +2,7 @@ import csvimport timefrom datetime import datetimefrom io import StringIO-from typing import TYPE_CHECKING, Any, NotRequired, Optional, TypedDict+from typing import TYPE_CHECKING, Any, NotRequired, Optional, TypedDict, castfrom uuid import UUIDfrom django.db import models@@ -94,15 +94,30 @@ class DataWarehouseTableIntrospectedColumn(TypedDict):type DataWarehouseTableIntrospectedColumns = dict[str, DataWarehouseTableIntrospectedColumn]-class DataWarehouseTableManager(models.Manager):- def get_queryset(self):- return (+class DataWarehouseTableQuerySet(models.QuerySet["DataWarehouseTable"]):+ def queryable(self) -> "DataWarehouseTableQuerySet":+ # A table you can actually query: not soft-deleted, and not orphaned by a soft-deleted source.+ return self.exclude(deleted=True).exclude(external_data_source__deleted=True)+++# `Manager.from_queryset(...)` can't be used as a base class here because it also overrides+# `get_queryset()` — mypy/django-stubs can't model that dynamic base. Wire the queryset class in+# manually instead so `objects.queryable()` and the eager-loading `get_queryset()` both work.+class DataWarehouseTableManager(models.Manager["DataWarehouseTable"]):+ _queryset_class = DataWarehouseTableQuerySet++ def get_queryset(self) -> DataWarehouseTableQuerySet:+ return cast(+ DataWarehouseTableQuerySet,super().get_queryset().select_related("created_by", "external_data_source")- .prefetch_related("externaldataschema_set")+ .prefetch_related("externaldataschema_set"),)+ def queryable(self) -> DataWarehouseTableQuerySet:+ return self.get_queryset().queryable()+class DataWarehouseTable(CreatedMetaFields, UpdatedMetaFields, UUIDTModel, DeletedMetaFields):# loading external_data_source and credentials is easily N+1,@@ -111,7 +126,7 @@ class DataWarehouseTable(CreatedMetaFields, UpdatedMetaFields, UUIDTModel, Deletobjects = DataWarehouseTableManager()# Use if it's certain externaldataschemas aren't needed- raw_objects = models.Manager()+ raw_objects = DataWarehouseTableQuerySet.as_manager()class TableFormat(models.TextChoices):CSV = "CSV", "CSV"diff --git a/products/warehouse_sources/backend/models/util.py b/products/warehouse_sources/backend/models/util.pyindex dc292a7841cb..0f41fd073087 100644--- a/products/warehouse_sources/backend/models/util.py+++ b/products/warehouse_sources/backend/models/util.py@@ -4,8 +4,6 @@ from ipaddress import IPv6Address, ip_addressfrom typing import TYPE_CHECKING, Any, Protocol, Unionfrom urllib.parse import urlparse-from django.db.models import Q-from posthog.hogql.database.models import (BooleanDatabaseField,DatabaseField,@@ -46,8 +44,11 @@ def get_view_or_table_by_name(team, name) -> Union["DataWarehouseSavedQuery", "Dtable_names = [f"{chain[1]}_{chain[0]}_{chain[2]}", f"{chain[1]}{chain[0]}_{chain[2]}"]table: DataWarehouseSavedQuery | DataWarehouseTable | None = (- DataWarehouseTable.objects.filter(Q(deleted__isnull=True) | Q(deleted=False))+ # `queryable()` ignores soft-deleted tables and orphans of a soft-deleted source.+ DataWarehouseTable.objects.queryable().filter(team=team, name__in=table_names)+ # Deterministic resolution when more than one live table matches: newest wins.+ .order_by("-created_at").first())if table is None:diff --git a/products/warehouse_sources/backend/tests/test_util.py b/products/warehouse_sources/backend/tests/test_util.pynew file mode 100644index 000000000000..6f5828603b9d--- /dev/null+++ b/products/warehouse_sources/backend/tests/test_util.py@@ -0,0 +1,82 @@+from posthog.test.base import BaseTest++from products.data_warehouse.backend.types import ExternalDataSourceType+from products.warehouse_sources.backend.models.credential import DataWarehouseCredential+from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource+from products.warehouse_sources.backend.models.table import DataWarehouseTable+from products.warehouse_sources.backend.models.util import get_view_or_table_by_name+++class TestGetViewOrTableByName(BaseTest):+ def _create_warehouse_table(self, *, name, url_pattern, source=None, credential=None) -> DataWarehouseTable:+ return DataWarehouseTable.objects.create(+ name=name,+ format="Parquet",+ team=self.team,+ external_data_source=source,+ credential=credential,+ url_pattern=url_pattern,+ columns={"id": {"hogql": "StringDatabaseField", "clickhouse": "Nullable(String)", "schema_valid": True}},+ )++ def test_ignores_tables_of_deleted_sources(self):+ # A table orphaned by a soft-deleted source must not shadow the live table re-created under+ # the same name — this is the path that feeds joins and series table resolution.+ credential = DataWarehouseCredential.objects.create(team=self.team, access_key="k", access_secret="s")++ deleted_source = ExternalDataSource.objects.create(+ team=self.team,+ source_id="old",+ connection_id="old",+ status=ExternalDataSource.Status.COMPLETED,+ source_type=ExternalDataSourceType.STRIPE,+ )+ self._create_warehouse_table(+ name="pull_requests", url_pattern="s3://orphan/*", source=deleted_source, credential=credential+ )+ deleted_source.deleted = True+ deleted_source.save()++ live_source = ExternalDataSource.objects.create(+ team=self.team,+ source_id="new",+ connection_id="new",+ status=ExternalDataSource.Status.COMPLETED,+ source_type=ExternalDataSourceType.STRIPE,+ )+ live_table = self._create_warehouse_table(+ name="pull_requests", url_pattern="s3://live/*", source=live_source, credential=credential+ )++ resolved = get_view_or_table_by_name(self.team, "pull_requests")++ assert isinstance(resolved, DataWarehouseTable)+ assert resolved.pk == live_table.pk+ assert resolved.url_pattern == "s3://live/*"++ def test_keeps_self_managed_table_without_source(self):+ # Guards the deleted-source exclusion against the Django exclude()-with-NULL gotcha:+ # a self-managed table (no source) must still resolve.+ credential = DataWarehouseCredential.objects.create(team=self.team, access_key="k", access_secret="s")+ table = self._create_warehouse_table(name="self_managed", url_pattern="s3://self/*", credential=credential)++ resolved = get_view_or_table_by_name(self.team, "self_managed")++ assert isinstance(resolved, DataWarehouseTable)+ assert resolved.pk == table.pk++ def test_resolves_duplicate_live_table_names_to_newest(self):+ # Two live tables share a name (e.g. a re-sync produced a duplicate): newest wins.+ credential = DataWarehouseCredential.objects.create(team=self.team, access_key="k", access_secret="s")+ older = self._create_warehouse_table(name="pull_requests", url_pattern="s3://older/*", credential=credential)+ newer = self._create_warehouse_table(name="pull_requests", url_pattern="s3://newer/*", credential=credential)++ # Pin created_at explicitly (bypasses auto_now_add) so the tiebreak is deterministic.+ DataWarehouseTable.objects.filter(pk=older.pk).update(created_at="2024-01-01T00:00:00+00:00")+ DataWarehouseTable.objects.filter(pk=newer.pk).update(created_at="2024-06-01T00:00:00+00:00")++ resolved = get_view_or_table_by_name(self.team, "pull_requests")++ assert isinstance(resolved, DataWarehouseTable)+ assert resolved.pk == newer.pk+ assert resolved.url_pattern == "s3://newer/*"