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): sync-method-aware schema toggle and sync links (#61032)

Daniel RCc49b8be80bcc
diff --git a/products/data_warehouse/backend/api/external_data_source.py b/products/data_warehouse/backend/api/external_data_source.py
index 3afda70802b7..b3b547af5e25 100644
--- a/products/data_warehouse/backend/api/external_data_source.py
+++ b/products/data_warehouse/backend/api/external_data_source.py
@@ -1328,6 +1328,11 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
)
is_cdc_schema = sync_type == "cdc"
+ # A CDC table the user isn't enabling hasn't been "set up" — leave its sync method
+ # blank so the schemas UI prompts the user to configure it before it can sync, rather
+ # than presetting `cdc` on every discovered table. Only tables the user actively
+ # enables get a concrete CDC method + config.
+ cdc_not_set_up = is_cdc_schema and not should_sync
if requires_incremental_fields and new_source_model.supports_scheduled_sync:
# If the caller didn't provide primary_key_columns, fall back to whatever the
# source detected during schema discovery. Otherwise we rely on sync-time
@@ -1342,7 +1347,7 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
"schema_metadata": schema_metadata,
**({"primary_key_columns": effective_primary_key_columns} if effective_primary_key_columns else {}),
}
- elif is_cdc_schema:
+ elif is_cdc_schema and not cdc_not_set_up:
cdc_table_mode = schema.get("cdc_table_mode", "consolidated")
sync_type_config = {
"cdc_mode": "snapshot",
@@ -1357,7 +1362,7 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
# and the value prop is near-real-time. Other sync types use the 6h default.
schema_sync_frequency_interval = (
timedelta(minutes=5)
- if is_cdc_schema and new_source_model.supports_scheduled_sync
+ if is_cdc_schema and not cdc_not_set_up and new_source_model.supports_scheduled_sync
else timedelta(hours=6)
)
schema_model = ExternalDataSchema.objects.create(
@@ -1365,7 +1370,7 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
team=self.team,
source=new_source_model,
should_sync=should_sync,
- sync_type=sync_type if new_source_model.supports_scheduled_sync else None,
+ sync_type=(None if cdc_not_set_up else sync_type) if new_source_model.supports_scheduled_sync else None,
sync_time_of_day=sync_time_of_day if new_source_model.supports_scheduled_sync else None,
sync_type_config=sync_type_config,
description=source_schema.description if source_schema else 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.py
index 204f29a20f31..026adbe75f3a 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
@@ -2453,6 +2453,119 @@ class TestExternalDataSource(APIBaseTest):
mock_add_table.assert_called_once()
assert mock_add_table.call_args.args[1:] == ("analytics", "events")
+ @patch("products.data_warehouse.backend.api.external_data_source.is_cdc_enabled_for_team", return_value=True)
+ @patch("posthog.temporal.data_imports.sources.postgres.cdc.adapter.PostgresCDCAdapter.add_table")
+ @patch("products.data_warehouse.backend.api.external_data_source.ExternalDataSourceViewSet._setup_cdc_resources")
+ @patch("products.data_warehouse.backend.api.external_data_source.get_primary_key_columns")
+ @patch("products.data_warehouse.backend.api.external_data_source.cdc_pg_connection")
+ @patch("products.data_warehouse.backend.api.external_data_source.SourceRegistry.get_source")
+ def test_create_postgres_cdc_leaves_unenabled_schemas_without_sync_type(
+ self,
+ mock_get_source,
+ mock_cdc_pg_connection,
+ mock_get_primary_key_columns,
+ mock_setup_cdc_resources,
+ mock_add_table,
+ _mock_is_cdc_enabled_for_team,
+ ):
+ # A CDC source discovers every table, but the user only enables a few. Tables the user
+ # didn't enable haven't had a sync method set up, so they must be created with a blank
+ # sync_type (the schemas UI keys off this to prompt setup). Only the enabled table gets
+ # the concrete `cdc` method + config + publication add.
+ source_mock = mock_get_source.return_value
+ source_mock.validate_config.return_value = (True, [])
+ parsed_config = Mock()
+ parsed_config.schema = "analytics"
+ parsed_config.to_dict.return_value = {
+ "host": "localhost",
+ "port": 5432,
+ "database": "app",
+ "user": "user",
+ "password": "pass",
+ "schema": "analytics",
+ }
+ source_mock.parse_config.return_value = parsed_config
+ source_mock.validate_credentials.return_value = (True, None)
+ source_mock.get_schemas.return_value = [
+ SourceSchema(
+ name="analytics.events",
+ supports_incremental=False,
+ supports_append=False,
+ supports_cdc=True,
+ columns=[("id", "integer", False)],
+ foreign_keys=[],
+ source_schema="analytics",
+ source_table_name="events",
+ ),
+ SourceSchema(
+ name="analytics.sessions",
+ supports_incremental=False,
+ supports_append=False,
+ supports_cdc=True,
+ columns=[("id", "integer", False)],
+ foreign_keys=[],
+ source_schema="analytics",
+ source_table_name="sessions",
+ ),
+ ]
+
+ mock_cdc_pg_connection.return_value.__enter__.return_value = object()
+ mock_cdc_pg_connection.return_value.__exit__.return_value = None
+ mock_get_primary_key_columns.return_value = {"events": ["id"]}
+
+ def setup_cdc_resources(_adapter, source_model, _payload):
+ source_model.job_inputs = {
+ **(source_model.job_inputs or {}),
+ "cdc_enabled": True,
+ "cdc_management_mode": "posthog",
+ "cdc_slot_name": "test_slot",
+ "cdc_publication_name": "test_pub",
+ }
+ source_model.save(update_fields=["job_inputs", "updated_at"])
+ return None
+
+ mock_setup_cdc_resources.side_effect = setup_cdc_resources
+
+ response = self.client.post(
+ f"/api/environments/{self.team.pk}/external_data_sources/",
+ data={
+ "source_type": "Postgres",
+ "created_via": "web",
+ "payload": {
+ "host": "localhost",
+ "port": 5432,
+ "database": "app",
+ "user": "user",
+ "password": "pass",
+ "schema": "analytics",
+ "cdc_enabled": True,
+ "schemas": [
+ {"name": "analytics.events", "should_sync": True, "sync_type": "cdc"},
+ {"name": "analytics.sessions", "should_sync": False, "sync_type": "cdc"},
+ ],
+ },
+ },
+ )
+
+ assert response.status_code == status.HTTP_201_CREATED, response.content
+
+ enabled = ExternalDataSchema.objects.get(team_id=self.team.pk, name="analytics.events")
+ assert enabled.sync_type == ExternalDataSchema.SyncType.CDC
+ assert enabled.sync_type_config["cdc_mode"] == "snapshot"
+ assert enabled.sync_type_config["cdc_table_mode"] == "consolidated"
+
+ unenabled = ExternalDataSchema.objects.get(team_id=self.team.pk, name="analytics.sessions")
+ assert unenabled.sync_type is None
+ assert unenabled.should_sync is False
+ # No CDC config noise — just the discovered metadata so column selection still works.
+ assert "cdc_mode" not in unenabled.sync_type_config
+ assert "cdc_table_mode" not in unenabled.sync_type_config
+
+ # Only the enabled table is added to the replication publication. The adapter reads the
+ # publication name from config itself, so the call is just (source, schema, table).
+ mock_add_table.assert_called_once()
+ assert mock_add_table.call_args.args[1:] == ("analytics", "events")
+
@patch("products.data_warehouse.backend.api.external_data_source.is_cdc_enabled_for_team", return_value=True)
@patch("posthog.temporal.data_imports.sources.postgres.cdc.adapter.PostgresCDCAdapter.add_table")
@patch("products.data_warehouse.backend.api.external_data_source.ExternalDataSourceViewSet._setup_cdc_resources")
diff --git a/products/data_warehouse/frontend/scenes/SchemaScene/ConfigurationTab.tsx b/products/data_warehouse/frontend/scenes/SchemaScene/ConfigurationTab.tsx
index da528a9907ad..20917c07602d 100644
--- a/products/data_warehouse/frontend/scenes/SchemaScene/ConfigurationTab.tsx
+++ b/products/data_warehouse/frontend/scenes/SchemaScene/ConfigurationTab.tsx
@@ -59,9 +59,18 @@ export interface ConfigurationTabProps {
schema: ExternalDataSourceSchema
source: ExternalDataSource | null
section: SchemaConfigurationSection
+ onConfigureSyncMethod: () => void
+ onViewSyncHistory: () => void
}
-export function ConfigurationTab({ sourceId, schema, source, section }: ConfigurationTabProps): JSX.Element {
+export function ConfigurationTab({
+ sourceId,
+ schema,
+ source,
+ section,
+ onConfigureSyncMethod,
+ onViewSyncHistory,
+}: ConfigurationTabProps): JSX.Element {
const logic = sourceSettingsLogic({ id: sourceId })
const { isProjectTime, refreshingSchemas } = useValues(logic)
const { setIsProjectTime, updateSchema, reloadSchema, resyncSchema, cancelSchema, deleteTable, refreshSchemas } =
@@ -76,6 +85,8 @@ export function ConfigurationTab({ sourceId, schema, source, section }: Configur
reloadSchema={reloadSchema}
cancelSchema={cancelSchema}
updateSchema={updateSchema}
+ onConfigureSyncMethod={onConfigureSyncMethod}
+ onViewSyncHistory={onViewSyncHistory}
/>
)
case 'sync-method':
@@ -128,12 +139,16 @@ function DetailsSection({
reloadSchema,
cancelSchema,
updateSchema,
+ onConfigureSyncMethod,
+ onViewSyncHistory,
}: {
source: ExternalDataSource | null
schema: ExternalDataSourceSchema
reloadSchema: (schema: ExternalDataSourceSchema) => void
cancelSchema: (schema: ExternalDataSourceSchema) => void
updateSchema: (schema: ExternalDataSourceSchema) => void
+ onConfigureSyncMethod: () => void
+ onViewSyncHistory: () => void
}): JSX.Element {
return (
<div>
@@ -153,12 +168,14 @@ function DetailsSection({
</div>
<SourceEditorAction source={source}>
<LemonSwitch
- disabledReason={
- schema.sync_type === null ? 'You must set up the sync method first' : undefined
- }
checked={schema.should_sync}
label={schema.should_sync ? 'Syncing' : 'Disabled'}
onChange={(active) => {
+ if (active && !schema.sync_type) {
+ // No sync method saved yet — open the sync method section to set one up.
+ onConfigureSyncMethod()
+ return
+ }
if (!active && schema.sync_type === 'cdc') {
LemonDialog.open({
title: 'Disable CDC table?',
@@ -283,6 +300,9 @@ function DetailsSection({
)}
</SourceEditorAction>
)}
+ <LemonButton type="secondary" onClick={onViewSyncHistory}>
+ View sync history
+ </LemonButton>
</div>
</div>
)
diff --git a/products/data_warehouse/frontend/scenes/SchemaScene/SchemaScene.tsx b/products/data_warehouse/frontend/scenes/SchemaScene/SchemaScene.tsx
index c10c8fe0c990..57269f190108 100644
--- a/products/data_warehouse/frontend/scenes/SchemaScene/SchemaScene.tsx
+++ b/products/data_warehouse/frontend/scenes/SchemaScene/SchemaScene.tsx
@@ -1,4 +1,5 @@
import { BindLogic, useActions, useValues } from 'kea'
+import { combineUrl, router } from 'kea-router'
import { useEffect } from 'react'
import { LemonButton, LemonSkeleton } from '@posthog/lemon-ui'
@@ -8,6 +9,7 @@ import { FEATURE_FLAGS } from 'lib/constants'
import { LemonTab, LemonTabs } from 'lib/lemon-ui/LemonTabs'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { SceneExport } from 'scenes/sceneTypes'
+import { urls } from 'scenes/urls'
import { SceneContent } from '~/layout/scenes/components/SceneContent'
import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
@@ -110,6 +112,14 @@ function SchemaSceneContent({ sourceId, schemaId }: SchemaSceneProps): JSX.Eleme
schema={schema}
source={source}
section={currentSection}
+ onConfigureSyncMethod={() => setCurrentSection('sync-method')}
+ onViewSyncHistory={() =>
+ router.actions.push(
+ combineUrl(urls.dataWarehouseSource(sourceId, 'syncs'), {
+ schema: schema.name,
+ }).url
+ )
+ }
/>
}
/>
diff --git a/products/data_warehouse/frontend/scenes/SourceScene/tabs/SchemasTab.tsx b/products/data_warehouse/frontend/scenes/SourceScene/tabs/SchemasTab.tsx
index 0a91fc77eea8..fadcdf7e3cf1 100644
--- a/products/data_warehouse/frontend/scenes/SourceScene/tabs/SchemasTab.tsx
+++ b/products/data_warehouse/frontend/scenes/SourceScene/tabs/SchemasTab.tsx
@@ -1,5 +1,5 @@
import { BindLogic, useActions, useValues } from 'kea'
-import { router } from 'kea-router'
+import { combineUrl, router } from 'kea-router'
import { useEffect, useState } from 'react'
import { IconInfo } from '@posthog/icons'
@@ -274,7 +274,11 @@ function ManagedSchemaTable({
}
const openSyncsForSchema = (): void => {
setSelectedSchemas([schema.name])
- router.actions.push(urls.dataWarehouseSource(prefixedSourceId, 'syncs'))
+ router.actions.push(
+ combineUrl(urls.dataWarehouseSource(prefixedSourceId, 'syncs'), {
+ schema: schema.name,
+ }).url
+ )
}
const tagContent = (
<LemonTag
@@ -376,11 +380,21 @@ function ManagedSchemaTable({
return (
<SourceEditorAction source={source}>
<LemonSwitch
- disabledReason={
- schema.sync_type === null ? 'Set up the sync method first' : undefined
- }
checked={schema.should_sync}
onChange={(active) => {
+ if (active && !schema.sync_type) {
+ // No sync method saved yet — send the user to set one up
+ // before the schema can be enabled.
+ router.actions.push(
+ urls.dataWarehouseSourceSchema(
+ prefixedSourceId,
+ schema.id,
+ 'configuration',
+ 'sync-method'
+ )
+ )
+ return
+ }
if (!active && schema.sync_type === 'cdc') {
LemonDialog.open({
title: 'Disable CDC table?',
diff --git a/products/data_warehouse/frontend/scenes/SourceScene/tabs/SyncsTab.tsx b/products/data_warehouse/frontend/scenes/SourceScene/tabs/SyncsTab.tsx
index 7e9601cfce3f..db72c23e467f 100644
--- a/products/data_warehouse/frontend/scenes/SourceScene/tabs/SyncsTab.tsx
+++ b/products/data_warehouse/frontend/scenes/SourceScene/tabs/SyncsTab.tsx
@@ -1,4 +1,5 @@
import { useActions, useValues } from 'kea'
+import { router } from 'kea-router'
import { useEffect } from 'react'
import { LemonButton, LemonDivider, LemonTable, LemonTag, LemonTagType, Tooltip } from '@posthog/lemon-ui'
@@ -37,6 +38,16 @@ export const SyncsTab = ({ id }: SyncsTabProps): JSX.Element => {
const { loadJobs, loadMoreJobs, setSelectedSchemas } = useActions(logic)
const showDebugLogs = user?.is_staff || user?.is_impersonated
+ // Apply a `?schema=<name>` deep link once on mount so links from the schemas list and the
+ // schema configuration page land here pre-filtered to a single schema.
+ useEffect(() => {
+ const schemaParam = router.values.searchParams.schema
+ if (schemaParam) {
+ setSelectedSchemas(Array.isArray(schemaParam) ? schemaParam : [schemaParam])
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [])
+
useEffect(() => {
if (!source || source.access_method === 'direct') {
return
diff --git a/products/data_warehouse/frontend/shared/components/forms/SyncMethodForm.tsx b/products/data_warehouse/frontend/shared/components/forms/SyncMethodForm.tsx
index ae79a302ad39..22e4e75dc1aa 100644
--- a/products/data_warehouse/frontend/shared/components/forms/SyncMethodForm.tsx
+++ b/products/data_warehouse/frontend/shared/components/forms/SyncMethodForm.tsx
@@ -173,10 +173,7 @@ export const SyncMethodForm = forwardRef<SyncMethodFormHandle, SyncMethodFormPro
)
useEffect(() => {
- setRadioValue(
- schema.sync_type ??
- (schema.supports_webhooks ? 'webhook' : incrementalSyncSupported.disabled ? 'append' : 'incremental')
- )
+ setRadioValue(getInitialRadioState(schema, !incrementalSyncSupported.disabled, !appendSyncSupported.disabled))
setIncrementalFieldValue(defaultField)
setAppendFieldValue(defaultField)
setPrimaryKeyColumns(schema.primary_key_columns ?? (primaryKeyLocked ? [] : (resolvedDetectedPks ?? [])))