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.

feat(data-warehouse): attach several sources to a destination in one request (#113425)

Tom Owersbbd629690aee
diff --git a/products/warehouse_sources/backend/presentation/views/external_data_destination.py b/products/warehouse_sources/backend/presentation/views/external_data_destination.py
index e8980c6670ae..90306af80723 100644
--- a/products/warehouse_sources/backend/presentation/views/external_data_destination.py
+++ b/products/warehouse_sources/backend/presentation/views/external_data_destination.py
@@ -3,7 +3,7 @@ from typing import Any, Optional, cast
from django.db import transaction
from django.db.models import Q
-from drf_spectacular.utils import extend_schema_field
+from drf_spectacular.utils import extend_schema, extend_schema_field
from rest_framework import serializers, status, viewsets
from rest_framework.exceptions import PermissionDenied, ValidationError
from rest_framework.request import Request
@@ -11,20 +11,25 @@ from rest_framework.response import Response
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.scoped_related_fields import TeamScopedPrimaryKeyRelatedField
+from posthog.api.utils import action
from posthog.models.integration import Integration
from posthog.permissions import is_service_auth
from products.access_control.backend.facade.user_access_control import access_level_satisfied_for_resource
+from products.data_warehouse.backend.facade.api import is_any_external_data_schema_paused
from products.warehouse_sources.backend.facade.models import (
ExternalDataDestination,
ExternalDataSchema,
ExternalDataSource,
+ ExternalDataSourceDestination,
)
from products.warehouse_sources.backend.presentation.destination_connection_check import (
CheckFailure,
DestinationConnectionCheckError,
check_postgres_destination,
)
+from products.warehouse_sources.backend.presentation.views.destination_links import MAX_DESTINATIONS_PER_LINK
+from products.warehouse_sources.backend.presentation.views.external_data_schema import resync_schema
# Which Integration kind holds the credentials for each destination type. A type absent from
# this map needs no integration; the PostHog warehouse is the only such type today.
@@ -61,6 +66,38 @@ class SyncedSourceSerializer(serializers.Serializer):
)
+class AddSourcesRequestSerializer(serializers.Serializer):
+ source_ids = serializers.ListField(
+ child=serializers.UUIDField(),
+ allow_empty=False,
+ max_length=50,
+ help_text="IDs of up to 50 existing sources to attach to this destination.",
+ )
+ resync = serializers.BooleanField(
+ default=False, help_text="Start a full resync for each enabled table newly attached."
+ )
+
+
+class SkippedSourceSerializer(serializers.Serializer):
+ id = serializers.UUIDField(help_text="ID of the source that was not attached.")
+ name = serializers.CharField(help_text="Name of the source that was not attached.")
+ reason = serializers.CharField(help_text="Why the source was not attached.")
+
+
+class ResyncFailureSerializer(serializers.Serializer):
+ schema_id = serializers.UUIDField(help_text="ID of the table whose resync did not start.")
+ detail = serializers.CharField(help_text="Why the resync did not start.")
+
+
+class AddSourcesResponseSerializer(serializers.Serializer):
+ attached = SyncedSourceSerializer(many=True, help_text="Sources newly attached to this destination.")
+ skipped = SkippedSourceSerializer(many=True, help_text="Sources that were not attached and their reasons.")
+ tables_resyncing = serializers.IntegerField(help_text="Number of tables sent for a full resync.")
+ resync_failures = ResyncFailureSerializer(
+ many=True, help_text="Tables whose resync did not start. The sources are still attached."
+ )
+
+
def _source_summary(source: ExternalDataSource, *, via_table_override: bool = False) -> dict[str, Any]:
# Prefix is part of how a person recognizes a source, since one connector can be added twice.
return {
@@ -290,13 +327,15 @@ class ExternalDataDestinationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewS
requires_resource_level_access = True
# `.unscoped()` is import-safe (the fail-closed manager raises on `.all()` without team
# context); the mixin scopes every request by team_id.
- queryset = ExternalDataDestination.objects.unscoped().exclude(deleted=True)
+ queryset = ExternalDataDestination.objects.unscoped().all()
serializer_class = ExternalDataDestinationSerializer
ordering = "name"
def safely_get_queryset(self, queryset: Any) -> Any:
# Prefetched so `synced_sources` reads relations already in memory: two extra queries for
# the whole page rather than two per destination.
+ if self.action != "add_sources":
+ queryset = queryset.exclude(deleted=True)
return (
queryset.filter(team_id=self.team_id)
.prefetch_related("source_links__source", "schema_links__schema__source")
@@ -361,6 +400,100 @@ class ExternalDataDestinationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewS
if level is None or not access_level_satisfied_for_resource("warehouse_table", level, "editor"):
raise PermissionDenied("You do not have editor access to every table wired to this destination.")
+ @extend_schema(request=AddSourcesRequestSerializer, responses={200: AddSourcesResponseSerializer})
+ @action(methods=["POST"], detail=True)
+ def add_sources(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ destination: ExternalDataDestination = self.get_object()
+ if destination.deleted:
+ raise ValidationError({"destination": "This destination was deleted."})
+
+ serializer = AddSourcesRequestSerializer(data=request.data)
+ serializer.is_valid(raise_exception=True)
+ source_ids = serializer.validated_data["source_ids"]
+ team_id = self.team_id
+ sources = list(ExternalDataSource.objects.filter(team_id=team_id, id__in=source_ids).exclude(deleted=True))
+ by_id = {str(source.id): source for source in sources}
+ missing = {str(source_id) for source_id in source_ids} - by_id.keys()
+ if missing:
+ raise ValidationError({"source_ids": f"Unknown sources: {', '.join(sorted(missing))}"})
+ # Mirrors the source and schema viewsets, which reject writes to sources PostHog manages.
+ if any(source.is_system_managed for source in sources):
+ raise PermissionDenied("Sources managed by PostHog cannot be changed through this API.")
+ # Reject before attaching anything, so a billing pause never leaves links without a resync.
+ if serializer.validated_data["resync"] and is_any_external_data_schema_paused(team_id):
+ raise ValidationError(
+ {"resync": "Monthly sync limit reached. Please increase your billing limit to resume syncing."}
+ )
+
+ self._assert_can_mutate(destination)
+ if not is_service_auth(request):
+ for source in sources:
+ level = self.user_access_control.get_user_access_level(source)
+ if level is None or not access_level_satisfied_for_resource("external_data_source", level, "editor"):
+ raise PermissionDenied("You do not have editor access to every selected source.")
+ schemas = (
+ ExternalDataSchema.objects.filter(team_id=team_id, source_id__in=source_ids)
+ .exclude(deleted=True)
+ .select_related("table", "source")
+ )
+ for schema in schemas:
+ level = self.user_access_control.get_user_access_level(schema.table or schema.source)
+ if level is None or not access_level_satisfied_for_resource("warehouse_table", level, "editor"):
+ raise PermissionDenied("You do not have editor access to every table in these sources.")
+
+ attached: list[dict[str, Any]] = []
+ skipped: list[dict[str, str]] = []
+ attached_sources: list[ExternalDataSource] = []
+ for source_id in dict.fromkeys(str(source_id) for source_id in source_ids):
+ source = by_id[source_id]
+ reason: str | None = None
+ with transaction.atomic():
+ ExternalDataSource.objects.select_for_update(of=("self",)).get(pk=source.id, team_id=team_id)
+ links = ExternalDataSourceDestination.objects.for_team(team_id).filter(source=source)
+ if links.filter(destination=destination).exists():
+ reason = "Already attached."
+ elif links.filter(enabled=True).count() >= MAX_DESTINATIONS_PER_LINK:
+ reason = f"Source already has {MAX_DESTINATIONS_PER_LINK} enabled destinations."
+ else:
+ ExternalDataSourceDestination.objects.for_team(team_id).create(
+ team_id=team_id, source=source, destination=destination
+ )
+ if reason:
+ skipped.append({"id": source_id, "name": _source_summary(source)["name"], "reason": reason})
+ else:
+ attached.append(_source_summary(source))
+ attached_sources.append(source)
+
+ tables_resyncing = 0
+ resync_failures: list[dict[str, str]] = []
+ if serializer.validated_data["resync"]:
+ for source in attached_sources:
+ for schema in ExternalDataSchema.objects.filter(
+ team_id=team_id, source=source, should_sync=True, deleted=False
+ ):
+ # The links are already committed, so report a table that fails to start instead of
+ # erroring: a retry would skip these sources as already attached.
+ try:
+ result = resync_schema(schema)
+ except ValidationError as e:
+ resync_failures.append({"schema_id": str(schema.id), "detail": str(e.detail)})
+ continue
+ if result.status_code != status.HTTP_200_OK:
+ resync_failures.append({"schema_id": str(schema.id), "detail": str(result.data)})
+ continue
+ tables_resyncing += 1
+
+ return Response(
+ AddSourcesResponseSerializer(
+ {
+ "attached": attached,
+ "skipped": skipped,
+ "tables_resyncing": tables_resyncing,
+ "resync_failures": resync_failures,
+ }
+ ).data
+ )
+
def perform_update(self, serializer: serializers.BaseSerializer) -> None:
# `.instance` is `Any | None` on the base serializer type, but `update`/`partial_update`
# always construct this viewset's serializer with the existing instance to update.
diff --git a/products/warehouse_sources/backend/presentation/views/external_data_schema.py b/products/warehouse_sources/backend/presentation/views/external_data_schema.py
index 30715c25732e..3725f7676759 100644
--- a/products/warehouse_sources/backend/presentation/views/external_data_schema.py
+++ b/products/warehouse_sources/backend/presentation/views/external_data_schema.py
@@ -258,6 +258,58 @@ def _trigger_schema_sync(instance: ExternalDataSchema) -> None:
sync_external_data_job_workflow(instance, create=True, should_sync=instance.should_sync)
+def resync_schema(instance: ExternalDataSchema) -> Response:
+ if is_any_external_data_schema_paused(instance.team_id):
+ return Response(
+ status=status.HTTP_400_BAD_REQUEST,
+ data={"message": "Monthly sync limit reached. Please increase your billing limit to resume syncing."},
+ )
+
+ cdc_resync = instance.is_cdc
+ if cdc_resync:
+ # Capture must finish a reset that overlaps a running streaming sync.
+ if hand_reset_to_capture_if_sync_running(instance, logger):
+ return Response(status=status.HTTP_200_OK)
+ else:
+ latest_running_job = (
+ ExternalDataJob.objects.filter(schema_id=instance.pk, team_id=instance.team_id)
+ .order_by("-created_at")
+ .first()
+ )
+ if latest_running_job and latest_running_job.workflow_id and latest_running_job.status == "Running":
+ cancel_external_data_workflow(latest_running_job.workflow_id)
+
+ updates: dict[str, Any] = {"reset_pipeline": True}
+ removes: list[str] = []
+ if cdc_resync:
+ updates["cdc_mode"] = "snapshot"
+ removes = ["cdc_last_log_position", CDC_RESET_PENDING_KEY]
+ # Keep buffered changes that capture wrote after the snapshot began.
+ if resnapshot_stays_in_buffer(instance):
+ updates[CDC_SNAPSHOT_LANE_KEY] = BUFFER_LANE
+
+ # Save the reset before the workflow reads this schema, under the helper's row lock.
+ extra: dict[str, Any] = {"initial_sync_complete": False} if cdc_resync else {}
+ instance.sync_type_config = update_sync_type_config_keys(
+ instance.id, instance.team_id, updates=updates, removes=removes, extra_model_fields=extra
+ )
+ if cdc_resync:
+ instance.initial_sync_complete = False
+
+ try:
+ _trigger_schema_sync(instance)
+ except temporalio.service.RPCError as e:
+ # Leave the reset pending, but do not show Running without a workflow.
+ logger.exception(f"Could not trigger external data job for schema {instance.id}", exc_info=e)
+ return Response(
+ data={"detail": "Couldn't start the sync. Try again in a few minutes."},
+ status=status.HTTP_400_BAD_REQUEST,
+ )
+
+ mark_schema_running_unless_halted(instance)
+ return Response(status=status.HTTP_200_OK)
+
+
# Sync frequencies below the 5-minute floor. No longer accepted as input (dropped from the
# serializer's choices), but rows written before the floor may still carry one until the
# migrate_sub_5min_sync_frequencies command bumps them — so the interval mappings keep parsing
@@ -2070,70 +2122,9 @@ class ExternalDataSchemaViewset(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
},
)
@action(methods=["POST"], detail=True)
- def resync(self, request: Request, *args: Any, **kwargs: Any):
+ def resync(self, request: Request, *args: Any, **kwargs: Any) -> Response:
instance: ExternalDataSchema = self.get_object()
-
- if is_any_external_data_schema_paused(self.team_id):
- return Response(
- status=status.HTTP_400_BAD_REQUEST,
- data={"message": "Monthly sync limit reached. Please increase your billing limit to resume syncing."},
- )
-
- cdc_resync = instance.is_cdc
- if cdc_resync:
- # A sync that hands over after the reset would leave the reset pending on a streaming
- # table, whose next run wipes it. Capture finishes the reset once that sync stops.
- if hand_reset_to_capture_if_sync_running(instance, logger):
- return Response(status=status.HTTP_200_OK)
- else:
- latest_running_job = (
- ExternalDataJob.objects.filter(schema_id=instance.pk, team_id=instance.team_id)
- .order_by("-created_at")
- .first()
- )
- if latest_running_job and latest_running_job.workflow_id and latest_running_job.status == "Running":
- cancel_external_data_workflow(latest_running_job.workflow_id)
-
- updates: dict[str, Any] = {"reset_pipeline": True}
- removes: list[str] = []
- if cdc_resync:
- # Reset CDC state so the next run does a full re-snapshot
- updates["cdc_mode"] = "snapshot"
- removes = ["cdc_last_log_position", CDC_RESET_PENDING_KEY]
- # Without the marker, the next capture run would empty the buffer, deleting changes a
- # capture run already in progress wrote after the snapshot started reading.
- if resnapshot_stays_in_buffer(instance):
- updates[CDC_SNAPSHOT_LANE_KEY] = BUFFER_LANE
-
- # Merge under a row lock so this reset can't clobber a concurrent CDC extract activity's
- # sync_type_config writes. Persist BEFORE triggering the workflow so the Postgres source
- # sees cdc_mode="snapshot" when it reloads the schema from DB — otherwise a race: the
- # workflow starts, loads stale "streaming" mode, consumes the change buffer instead, and
- # the full-refresh never runs.
- # initial_sync_complete is saved in the same transaction as cdc_mode via extra_model_fields
- # so no reader can observe cdc_mode="snapshot" with initial_sync_complete=True.
- extra: dict[str, Any] = {"initial_sync_complete": False} if cdc_resync else {}
- instance.sync_type_config = update_sync_type_config_keys(
- instance.id, instance.team_id, updates=updates, removes=removes, extra_model_fields=extra
- )
- if cdc_resync:
- instance.initial_sync_complete = False
-
- try:
- _trigger_schema_sync(instance)
- except temporalio.service.RPCError as e:
- # Only mark the schema Running once the trigger succeeded: a Running status with no
- # workflow behind it sticks forever (nothing finalizes it) and blocks cancel. The
- # sync_type_config reset above stays; the schema's intent is still "resync next run".
- logger.exception(f"Could not trigger external data job for schema {instance.id}", exc_info=e)
- return Response(
- data={"detail": "Couldn't start the sync. Try again in a few minutes."},
- status=status.HTTP_400_BAD_REQUEST,
- )
-
- mark_schema_running_unless_halted(instance)
-
- return Response(status=status.HTTP_200_OK)
+ return resync_schema(instance)
@extend_schema(
request=None,
diff --git a/products/warehouse_sources/backend/tests/api/test_external_data_destination.py b/products/warehouse_sources/backend/tests/api/test_external_data_destination.py
index a6a4a5b18e1a..87db6a367e6e 100644
--- a/products/warehouse_sources/backend/tests/api/test_external_data_destination.py
+++ b/products/warehouse_sources/backend/tests/api/test_external_data_destination.py
@@ -1,3 +1,5 @@
+from uuid import uuid4
+
import pytest
from posthog.test.base import APIBaseTest
from unittest.mock import patch
@@ -8,11 +10,13 @@ from django.test.utils import CaptureQueriesContext
from parameterized import parameterized
from rest_framework import status
from rest_framework.exceptions import PermissionDenied
+from rest_framework.response import Response
from posthog.constants import AvailableFeature
from posthog.models.integration import Integration
from posthog.models.user import User
+from products.access_control.backend.facade.user_access_control import UserAccessControl
from products.access_control.backend.models.access_control import AccessControl
from products.warehouse_sources.backend.models.external_data_destination import (
ExternalDataDestination,
@@ -22,6 +26,7 @@ from products.warehouse_sources.backend.models.external_data_destination import
)
from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
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.presentation.destination_connection_check import (
FAILURE_MESSAGES,
CheckFailure,
@@ -312,6 +317,205 @@ class TestExternalDataDestinationAPI(DestinationAPITestBase):
assert destination.name == "analytics postgres"
+class TestAddSources(DestinationAPITestBase):
+ def setUp(self) -> None:
+ super().setUp()
+ self.destination = self._create_destination()
+ self.url = f"{self.base}/{self.destination.id}/add_sources/"
+
+ def _source(self, name: str) -> ExternalDataSource:
+ return ExternalDataSource.objects.create(
+ team=self.team,
+ source_id=name,
+ connection_id=f"{name}-connection",
+ status="Running",
+ source_type=ExternalDataSourceType.STRIPE,
+ )
+
+ def test_attaches_two_sources_and_keeps_existing_destinations(self) -> None:
+ second = self._source("second")
+ previous = self._create_destination(name="previous")
+ ExternalDataSourceDestination.objects.for_team(self.team.pk).create(
+ team_id=self.team.pk, source=self.source, destination=previous
+ )
+
+ response = self.client.post(self.url, {"source_ids": [str(self.source.id), str(second.id)]}, format="json")
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert [entry["id"] for entry in response.json()["attached"]] == [str(self.source.id), str(second.id)]
+ assert response.json()["skipped"] == []
+ assert response.json()["tables_resyncing"] == 0
+ links = ExternalDataSourceDestination.objects.for_team(self.team.pk)
+ assert set(links.filter(source=self.source, enabled=True).values_list("destination_id", flat=True)) == {
+ previous.id,
+ self.destination.id,
+ }
+ assert list(links.filter(source=second, enabled=True).values_list("destination_id", flat=True)) == [
+ self.destination.id
+ ]
+
+ def test_already_attached_source_is_skipped_without_duplicate(self) -> None:
+ ExternalDataSourceDestination.objects.for_team(self.team.pk).create(
+ team_id=self.team.pk, source=self.source, destination=self.destination
+ )
+
+ response = self.client.post(self.url, {"source_ids": [str(self.source.id)]}, format="json")
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert response.json()["attached"] == []
+ assert response.json()["skipped"][0]["id"] == str(self.source.id)
+ assert response.json()["skipped"][0]["reason"] == "Already attached."
+ assert (
+ ExternalDataSourceDestination.objects.for_team(self.team.pk)
+ .filter(source=self.source, destination=self.destination)
+ .count()
+ == 1
+ )
+
+ def test_limit_skips_one_source_and_attaches_another(self) -> None:
+ second = self._source("second")
+ for index in range(10):
+ other = ExternalDataDestination.objects.for_team(self.team.pk).create(
+ team_id=self.team.pk, type=ExternalDataDestination.Type.POSTGRES, name=f"other-{index}"
+ )
+ ExternalDataSourceDestination.objects.for_team(self.team.pk).create(
+ team_id=self.team.pk, source=self.source, destination=other
+ )
+
+ response = self.client.post(self.url, {"source_ids": [str(self.source.id), str(second.id)]}, format="json")
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert [entry["id"] for entry in response.json()["attached"]] == [str(second.id)]
+ assert response.json()["skipped"][0]["id"] == str(self.source.id)
+ assert "10 enabled destinations" in response.json()["skipped"][0]["reason"]
+ assert (
+ not ExternalDataSourceDestination.objects.for_team(self.team.pk)
+ .filter(source=self.source, destination=self.destination)
+ .exists()
+ )
+
+ @parameterized.expand([("empty", []), ("too_many", [str(uuid4()) for _ in range(51)])])
+ def test_rejects_invalid_source_count(self, _name: str, source_ids: list[str]) -> None:
+ response = self.client.post(self.url, {"source_ids": source_ids}, format="json")
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert ExternalDataSourceDestination.objects.for_team(self.team.pk).count() == 0
+
+ def test_unknown_source_is_rejected_and_named(self) -> None:
+ unknown = str(uuid4())
+
+ response = self.client.post(self.url, {"source_ids": [str(self.source.id), unknown]}, format="json")
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert unknown in str(response.json())
+ assert ExternalDataSourceDestination.objects.for_team(self.team.pk).count() == 0
+
+ def test_soft_deleted_destination_is_rejected(self) -> None:
+ self.destination.deleted = True
+ self.destination.save(update_fields=["deleted"])
+
+ response = self.client.post(self.url, {"source_ids": [str(self.source.id)]}, format="json")
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert ExternalDataSourceDestination.objects.for_team(self.team.pk).count() == 0
+
+ def test_resync_false_does_not_start_a_resync(self) -> None:
+ with patch(
+ "products.warehouse_sources.backend.presentation.views.external_data_destination.resync_schema"
+ ) as resync:
+ response = self.client.post(self.url, {"source_ids": [str(self.source.id)], "resync": False}, format="json")
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert response.json()["tables_resyncing"] == 0
+ resync.assert_not_called()
+
+ def test_resync_true_only_starts_enabled_tables_on_new_sources(self) -> None:
+ disabled = ExternalDataSchema.objects.create(
+ team=self.team, source=self.source, name="disabled", should_sync=False
+ )
+ with patch(
+ "products.warehouse_sources.backend.presentation.views.external_data_destination.resync_schema",
+ return_value=Response(status=status.HTTP_200_OK),
+ ) as resync:
+ response = self.client.post(self.url, {"source_ids": [str(self.source.id)], "resync": True}, format="json")
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert response.json()["tables_resyncing"] == 1
+ resync.assert_called_once()
+ assert resync.call_args.args[0].id == self.schema.id
+ assert resync.call_args.args[0].id != disabled.id
+
+ def test_rejects_system_managed_sources(self) -> None:
+ self.source.connection_metadata = {"system_managed": True}
+ self.source.save(update_fields=["connection_metadata"])
+
+ response = self.client.post(self.url, {"source_ids": [str(self.source.id)], "resync": True}, format="json")
+
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+ assert ExternalDataSourceDestination.objects.for_team(self.team.pk).count() == 0
+
+ def test_resync_true_rejected_before_attaching_when_syncs_are_paused(self) -> None:
+ with patch(
+ "products.warehouse_sources.backend.presentation.views.external_data_destination.is_any_external_data_schema_paused",
+ return_value=True,
+ ):
+ response = self.client.post(self.url, {"source_ids": [str(self.source.id)], "resync": True}, format="json")
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert ExternalDataSourceDestination.objects.for_team(self.team.pk).count() == 0
+
+ def test_resync_failure_is_reported_and_links_are_kept(self) -> None:
+ with patch(
+ "products.warehouse_sources.backend.presentation.views.external_data_destination.resync_schema",
+ return_value=Response(status=status.HTTP_400_BAD_REQUEST, data={"detail": "boom"}),
+ ):
+ response = self.client.post(self.url, {"source_ids": [str(self.source.id)], "resync": True}, format="json")
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ body = response.json()
+ assert body["tables_resyncing"] == 0
+ assert [failure["schema_id"] for failure in body["resync_failures"]] == [str(self.schema.id)]
+ assert len(body["attached"]) == 1
+ assert ExternalDataSourceDestination.objects.for_team(self.team.pk).count() == 1
+
+ def test_requires_editor_on_selected_source_tables(self) -> None:
+ table = DataWarehouseTable.objects.create(name="charges", team=self.team, external_data_source=self.source)
+ self.schema.table = table
+ self.schema.save(update_fields=["table"])
+
+ original = UserAccessControl.get_user_access_level
+
+ def access_level(uac: UserAccessControl, obj: object, *args: object, **kwargs: object) -> str | None:
+ # Only the source and its table are overridden; the team keeps its real project-level access.
+ if obj == table:
+ return "viewer"
+ if obj == self.source:
+ return "editor"
+ return original(uac, obj, *args, **kwargs) # type: ignore[arg-type]
+
+ with patch.object(UserAccessControl, "get_user_access_level", access_level):
+ response = self.client.post(self.url, {"source_ids": [str(self.source.id)]}, format="json")
+
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+ assert ExternalDataSourceDestination.objects.for_team(self.team.pk).count() == 0
+
+ def test_requires_editor_on_tables_already_wired_to_destination(self) -> None:
+ second = self._source("second")
+ ExternalDataSourceDestination.objects.for_team(self.team.pk).create(
+ team_id=self.team.pk, source=self.source, destination=self.destination
+ )
+
+ with patch.object(ExternalDataDestinationViewSet, "_assert_can_mutate", side_effect=PermissionDenied("nope")):
+ response = self.client.post(self.url, {"source_ids": [str(second.id)]}, format="json")
+
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+ assert (
+ not ExternalDataSourceDestination.objects.for_team(self.team.pk)
+ .filter(source=second, destination=self.destination)
+ .exists()
+ )
+
+
class TestSyncedSources(DestinationAPITestBase):
def _listing(self) -> dict:
results = self.client.get(self.base).json()["results"]
diff --git a/products/warehouse_sources/frontend/generated/api.schemas.ts b/products/warehouse_sources/frontend/generated/api.schemas.ts
index 5e265a094c8c..726092dc5473 100644
--- a/products/warehouse_sources/frontend/generated/api.schemas.ts
+++ b/products/warehouse_sources/frontend/generated/api.schemas.ts
@@ -126,6 +126,43 @@ export interface PatchedExternalDataDestinationApi {
readonly synced_sources?: readonly SyncedSourceApi[]
}
+export interface AddSourcesRequestApi {
+ /**
+ * IDs of up to 50 existing sources to attach to this destination.
+ * @maxItems 50
+ */
+ source_ids: string[]
+ /** Start a full resync for each enabled table newly attached. */
+ resync?: boolean
+}
+
+export interface SkippedSourceApi {
+ /** ID of the source that was not attached. */
+ id: string
+ /** Name of the source that was not attached. */
+ name: string
+ /** Why the source was not attached. */
+ reason: string
+}
+
+export interface ResyncFailureApi {
+ /** ID of the table whose resync did not start. */
+ schema_id: string
+ /** Why the resync did not start. */
+ detail: string
+}
+
+export interface AddSourcesResponseApi {
+ /** Sources newly attached to this destination. */
+ attached: SyncedSourceApi[]
+ /** Sources that were not attached and their reasons. */
+ skipped: SkippedSourceApi[]
+ /** Number of tables sent for a full resync. */
+ tables_resyncing: number
+ /** Tables whose resync did not start. The sources are still attached. */
+ resync_failures: ResyncFailureApi[]
+}
+
/**
* * `full_refresh` - full_refresh
* * `incremental` - incremental
diff --git a/products/warehouse_sources/frontend/generated/api.ts b/products/warehouse_sources/frontend/generated/api.ts
index 6213ea147c0f..b597b093ec05 100644
--- a/products/warehouse_sources/frontend/generated/api.ts
+++ b/products/warehouse_sources/frontend/generated/api.ts
@@ -9,6 +9,8 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'
* OpenAPI spec version: 1.0.0
*/
import type {
+ AddSourcesRequestApi,
+ AddSourcesResponseApi,
CdcEnableResponseApi,
CdcPrerequisitesResponseApi,
CdcStatusApi,
@@ -228,6 +230,30 @@ export const externalDataDestinationsDestroy = async (
})
}
+export const getExternalDataDestinationsAddSourcesCreateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/external_data_destinations/${id}/add_sources/`
+}
+
+/**
+ * Manage where warehouse sources write their synced rows.
+ *
+ * A destination can be attached to several sources, or to a single table on a source.
+ * Credentials come from an integration, so one connection can be reused across syncs.
+ */
+export const externalDataDestinationsAddSourcesCreate = async (
+ projectId: string,
+ id: string,
+ addSourcesRequestApi: AddSourcesRequestApi,
+ options?: RequestInit
+): Promise<AddSourcesResponseApi> => {
+ return apiMutator<AddSourcesResponseApi>(getExternalDataDestinationsAddSourcesCreateUrl(projectId, id), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(addSourcesRequestApi),
+ })
+}
+
export const getExternalDataSchemasListUrl = (projectId: string, params?: ExternalDataSchemasListParams) => {
const normalizedParams = new URLSearchParams()
diff --git a/products/warehouse_sources/frontend/generated/api.zod.ts b/products/warehouse_sources/frontend/generated/api.zod.ts
index 14e53aa39cb0..3c69d1d49c35 100644
--- a/products/warehouse_sources/frontend/generated/api.zod.ts
+++ b/products/warehouse_sources/frontend/generated/api.zod.ts
@@ -116,6 +116,27 @@ export const ExternalDataDestinationsPartialUpdateBody = /* @__PURE__ */ zod.obj
),
})
+/**
+ * Manage where warehouse sources write their synced rows.
+ *
+ * A destination can be attached to several sources, or to a single table on a source.
+ * Credentials come from an integration, so one connection can be reused across syncs.
+ */
+export const externalDataDestinationsAddSourcesCreateBodySourceIdsMax = 50
+
+export const externalDataDestinationsAddSourcesCreateBodyResyncDefault = false
+
+export const ExternalDataDestinationsAddSourcesCreateBody = /* @__PURE__ */ zod.object({
+ source_ids: zod
+ .array(zod.uuid())
+ .max(externalDataDestinationsAddSourcesCreateBodySourceIdsMax)
+ .describe('IDs of up to 50 existing sources to attach to this destination.'),
+ resync: zod
+ .boolean()
+ .default(externalDataDestinationsAddSourcesCreateBodyResyncDefault)
+ .describe('Start a full resync for each enabled table newly attached.'),
+})
+
export const externalDataSchemasUpdateBodyIncrementalFieldLookbackSecondsMin = 0
export const externalDataSchemasUpdateBodyIncrementalFieldLookbackSecondsMax = 5184000
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 168fddeb5a3e..41c1f12905bc 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -11273,6 +11273,57 @@ export namespace Schemas {
uploads: UploadTarget[];
}
+ export interface AddSourcesRequest {
+ /**
+ * IDs of up to 50 existing sources to attach to this destination.
+ * @maxItems 50
+ */
+ source_ids: string[];
+ /** Start a full resync for each enabled table newly attached. */
+ resync?: boolean;
+ }
+
+ /**
+ * One source that writes to a destination. Shape only — never used to deserialize.
+ */
+ export interface SyncedSource {
+ /** The source's id. */
+ id: string;
+ /** How the source is labelled in the UI, prefix included. */
+ name: string;
+ /** Which connector this is, e.g. Stripe or Postgres. */
+ source_type: string;
+ /** True when only some of the source's tables reach this destination, through their own override. */
+ via_table_override: boolean;
+ }
+
+ export interface SkippedSource {
+ /** ID of the source that was not attached. */
+ id: string;
+ /** Name of the source that was not attached. */
+ name: string;
+ /** Why the source was not attached. */
+ reason: string;
+ }
+
+ export interface ResyncFailure {
+ /** ID of the table whose resync did not start. */
+ schema_id: string;
+ /** Why the resync did not start. */
+ detail: string;
+ }
+
+ export interface AddSourcesResponse {
+ /** Sources newly attached to this destination. */
+ attached: SyncedSource[];
+ /** Sources that were not attached and their reasons. */
+ skipped: SkippedSource[];
+ /** Number of tables sent for a full resync. */
+ tables_resyncing: number;
+ /** Tables whose resync did not start. The sources are still attached. */
+ resync_failures: ResyncFailure[];
+ }
+
export interface AddSuppressionRequest {
/**
* The email address to suppress. Will not receive any messages until removed.
@@ -46055,20 +46106,6 @@ export namespace Schemas {
S3: 'S3',
} as const;
- /**
- * One source that writes to a destination. Shape only — never used to deserialize.
- */
- export interface SyncedSource {
- /** The source's id. */
- id: string;
- /** How the source is labelled in the UI, prefix included. */
- name: string;
- /** Which connector this is, e.g. Stripe or Postgres. */
- source_type: string;
- /** True when only some of the source's tables reach this destination, through their own override. */
- via_table_override: boolean;
- }
-
export interface ExternalDataDestination {
readonly id: string;
/** Where synced rows are written. The PostHog warehouse is managed for you, so you cannot create one here.