: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
feat(integration): Reject delete if batch exports using integration (#74140)
Tomás Farías Santanaa23c7c8a6f0a
diff --git a/posthog/api/integration.py b/posthog/api/integration.pyindex 11e819855dfd..306cb176932a 100644--- a/posthog/api/integration.py+++ b/posthog/api/integration.py@@ -1,7 +1,8 @@import osimport reimport json-from typing import Any, cast+from collections.abc import Iterable+from typing import Any, Protocol, castfrom urllib.parse import urlencodefrom django.conf import settings@@ -94,6 +95,7 @@ from posthog.rbac.user_access_control import UserAccessControlSerializerMixinfrom posthog.tasks.email import send_integration_access_requestfrom posthog.utils import is_relative_url+from products.batch_exports.backend.models.batch_export import get_batch_exports_using_integrationfrom products.cdp.backend.services.integration_usage import get_enabled_hog_functions_using_integrationfrom products.tasks.backend.facade.api import count_in_progress_runs_for_github_integrationfrom products.workflows.backend.services.integration_usage import get_active_hog_flows_using_integration@@ -177,6 +179,17 @@ def _ensure_oauth_token_valid(instance: Integration) -> None:)+class _HasNameOrId(Protocol):+ id: Any++ @property+ def name(self) -> str | None: ...+++def _concat_names_or_ids(items: Iterable[_HasNameOrId]) -> str:+ return ", ".join(sorted(it.name or str(it.id) for it in items))++class NativeEmailIntegrationSerializer(serializers.Serializer):email = serializers.EmailField()name = serializers.CharField()@@ -978,15 +991,24 @@ class IntegrationViewSet(functions_using_integration = get_enabled_hog_functions_using_integration(team_id=instance.team_id, integration_id=instance.id)+ batch_exports_using_integration = get_batch_exports_using_integration(+ team_id=instance.team_id, integration_id=instance.id+ )+used_by = []+if flows_using_integration:- flow_names = ", ".join(sorted(flow.name or str(flow.id) for flow in flows_using_integration))+ flow_names = _concat_names_or_ids(flows_using_integration)used_by.append(f"active workflows: {flow_names}")+if functions_using_integration:- function_names = ", ".join(- sorted(function.name or str(function.id) for function in functions_using_integration)- )+ function_names = _concat_names_or_ids(functions_using_integration)used_by.append(f"enabled data pipelines: {function_names}")++ if batch_exports_using_integration:+ batch_export_names = _concat_names_or_ids(batch_exports_using_integration)+ used_by.append(f"batch exports: {batch_export_names}")+if used_by:raise ValidationError(f"This integration is used by {' and '.join(used_by)}. "diff --git a/posthog/api/test/test_integration.py b/posthog/api/test/test_integration.pyindex f28dc06d79d4..8da0fc3fcc74 100644--- a/posthog/api/test/test_integration.py+++ b/posthog/api/test/test_integration.py@@ -49,6 +49,7 @@ from posthog.models.user_integration import UserIntegrationfrom posthog.models.utils import hash_key_valuefrom posthog.rate_limit import GitHubRepositoryRefreshThrottle+from products.batch_exports.backend.models import BatchExport, BatchExportDestinationfrom products.cdp.backend.models import HogFunctionfrom products.cdp.backend.models.hog_function_template import HogFunctionTemplatefrom products.workflows.backend.models import HogFlow@@ -4851,6 +4852,19 @@ class TestIntegrationDeletionHogFunctionGuard:assert "Slack notifier" in contentassert Integration.objects.filter(id=self.integration.id).exists()+ def test_destroy_blocked_message_includes_batch_exports(self, client: HttpClient):+ dest = BatchExportDestination.objects.create(+ config={}, type=BatchExportDestination.Destination.AWS_S3, integration=self.integration+ )+ BatchExport.objects.create(name="Test batch export", destination=dest, team=self.team, interval="hour")++ response = self._delete(client)++ assert response.status_code == status.HTTP_400_BAD_REQUEST+ content = response.content.decode()+ assert "Test batch export" in content+ assert Integration.objects.filter(id=self.integration.id).exists()+class TestIntegrationRequestAccessAPI(APIBaseTest):def setUp(self):diff --git a/products/batch_exports/backend/models/batch_export.py b/products/batch_exports/backend/models/batch_export.pyindex c9ea59739232..001a63ecf534 100644--- a/products/batch_exports/backend/models/batch_export.py+++ b/products/batch_exports/backend/models/batch_export.py@@ -487,6 +487,24 @@ class BatchExport(ModelActivityMixin, UUIDTModel):return None+def get_batch_exports_using_integration(team_id: int, integration_id: int) -> list[BatchExport]:+ """Return a list of batch exports using integration_id.++ This is used to check when destroying an integration if it is not in use,+ as otherwise users could get themselves into an undesired state.++ We only consider batch exports that are not deleted, as deleted batch+ exports are not relevant to users.+ """+ return list(+ BatchExport.objects.filter(+ team_id=team_id,+ deleted=False,+ destination__in=BatchExportDestination.objects.filter(integration_id=integration_id),+ ).only("id", "name")+ )++class BatchExportBackfill(UUIDTModel):class Meta:db_table = "posthog_batchexportbackfill"