: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(data-warehouse): bulk actions, filters, sorting on the schemas table (#61025)
Daniel RCd1c1c28d8a20
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 8ec0afceda31..3d6ed84c7c0b 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -4675,9 +4675,9 @@ snapshots:scenes-app-data-warehouse-editor-upstream-graph--with-graph--light:hash: v1.k794b7964.3fe5d6bd03f992da9c2dd13af16f53ffaae17590db416f9b963c2fc838551b54.ULQER6t0lWp3L-BLATI0B64TJgjhJr2sNtyvwnXpeFYscenes-app-data-warehouse-settings-schemas--default--dark:- hash: v1.k794b7964.8a77e7a0171fcd435c6595297bf027b8f0a241439ee5921ba1e98ac8989fde19.heCouatVYmHaFYRqmD6XBpq_K1abbgOOnCJSBR9O1ok+ hash: v1.k794b7964.f63eec588ee7cf4aae7394caaf42ef000fe6ee9e4c92611f70a1de609de258ad.k8PvcZvu-w75qhYEx0dNXUbh5SoT-9pObguvhGzTRrgscenes-app-data-warehouse-settings-schemas--default--light:- hash: v1.k794b7964.f44aebec23a383bf47c5310e229767e329dc9a52d220851265c86e2531dfd8f6.cg8SBdNPjYob5gTIonGhj0QupXWDzvTSG73043B7QEk+ hash: v1.k794b7964.18626812d4b56d76787437924e1bc585c0d290b2d3d5a82acef06ad862687d31.T90_pbE7tLkoXwZml5VYlGjFqOKnGtCJsNfB3J76Xioscenes-app-error-project-unavailable--access-revoked--dark:hash: v1.k794b7964.551951688a4131cbd9c0d08e553c79238fb9831c6e227e3854eb3596a95d5725.lEJkOr35uSHLqc-IqIYv7Z2bc4-rjbJut0zmTNBae6Yscenes-app-error-project-unavailable--access-revoked--light:diff --git a/frontend/src/lib/lemon-ui/LemonTable/BulkSelectionBar.tsx b/frontend/src/lib/lemon-ui/LemonTable/BulkSelectionBar.tsxindex 76b31bc7e86b..8357a32fe9d4 100644--- a/frontend/src/lib/lemon-ui/LemonTable/BulkSelectionBar.tsx+++ b/frontend/src/lib/lemon-ui/LemonTable/BulkSelectionBar.tsx@@ -1,3 +1,5 @@+import clsx from 'clsx'+import { LemonButton } from 'lib/lemon-ui/LemonButton'import { BulkSelectionConfig, BulkSelectionContext, BulkSelectionKey } from './useBulkSelection'@@ -20,7 +22,12 @@ export function BulkSelectionBar<T extends Record<string, any>, K extends BulkSeconst word = context.selectedCount === 1 ? singular : pluralreturn (- <div className="flex items-center justify-end gap-2 min-h-9 px-1 LemonTable__bulk-selection-bar">+ <div+ className={clsx(+ 'flex items-center justify-end gap-2 min-h-9 px-1 LemonTable__bulk-selection-bar',+ config.barClassName+ )}+ ><span className="text-secondary text-sm">{context.selectedCount} {word} selected</span>diff --git a/frontend/src/lib/lemon-ui/LemonTable/useBulkSelection.ts b/frontend/src/lib/lemon-ui/LemonTable/useBulkSelection.tsindex de3187f01dc5..4bbeb771d64c 100644--- a/frontend/src/lib/lemon-ui/LemonTable/useBulkSelection.ts+++ b/frontend/src/lib/lemon-ui/LemonTable/useBulkSelection.ts@@ -36,6 +36,8 @@ export interface BulkSelectionConfig<T extends Record<string, any>, K extends Bu/** Initial selection (uncontrolled). Read once on mount; later changes are ignored.* Useful for stories and test scaffolds that want to render the bar pre-populated. */initialSelectedKeys?: ReadonlyArray<K>+ /** Extra classes for the bulk-action bar wrapper (e.g. spacing). Opt-in so other tables are unaffected. */+ barClassName?: string}export interface UseBulkSelectionResult<T, K extends BulkSelectionKey = BulkSelectionKey> {diff --git a/posthog/session_recordings/queries/test/listing_recordings/__snapshots__/test_session_recording_list_from_query.ambr b/posthog/session_recordings/queries/test/listing_recordings/__snapshots__/test_session_recording_list_from_query.ambrindex 4d81dc6a2021..800a3fff4b5e 100644--- a/posthog/session_recordings/queries/test/listing_recordings/__snapshots__/test_session_recording_list_from_query.ambr+++ b/posthog/session_recordings/queries/test/listing_recordings/__snapshots__/test_session_recording_list_from_query.ambr@@ -1122,7 +1122,7 @@WHERE and(equals(s.team_id, 99999), greaterOrEquals(s.min_first_timestamp, toDateTime64('2020-12-29 00:00:00.000000', 6, 'UTC')), lessOrEquals(s.min_first_timestamp, toDateTime64('today', 6, 'UTC')), globalIn(s.session_id,(SELECT nullIf(nullIf(events.`$session_id`, ''), 'null') AS session_idFROM events- WHERE and(equals(events.team_id, 99999), notEmpty(nullIf(nullIf(events.`$session_id`, ''), 'null')), lessOrEquals(events.timestamp, now64(6, 'UTC')), equals(events.mat_pp_email, 'bla'), greaterOrEquals(events.timestamp, toDateTime64('2020-12-28 00:00:00.000000', 6, 'UTC')))+ WHERE and(equals(events.team_id, 99999), notEmpty(nullIf(nullIf(events.`$session_id`, ''), 'null')), lessOrEquals(events.timestamp, now64(6, 'UTC')), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.person_properties, 'email'), ''), 'null'), '^"|"$', ''), 'bla'), 0), greaterOrEquals(events.timestamp, toDateTime64('2020-12-28 00:00:00.000000', 6, 'UTC')))GROUP BY nullIf(nullIf(events.`$session_id`, ''), 'null')HAVING 1ORDER BY min(toTimeZone(events.timestamp, 'UTC')) DESCdiff --git a/products/data_warehouse/backend/api/external_data_schema.py b/products/data_warehouse/backend/api/external_data_schema.pyindex c33698f12d4b..168c18bd4795 100644--- a/products/data_warehouse/backend/api/external_data_schema.py+++ b/products/data_warehouse/backend/api/external_data_schema.py@@ -124,6 +124,10 @@ def _reset_cdc_for_full_resnapshot(instance: ExternalDataSchema) -> None:instance.save(update_fields=["status"])+# Sync frequencies that only CDC schemas may use. Every other sync type floors at 5 minutes.+CDC_ONLY_SYNC_FREQUENCIES = {"1min"}++class ExternalDataSchemaSerializer(serializers.ModelSerializer):table = serializers.SerializerMethodField(read_only=True)incremental = serializers.SerializerMethodField(read_only=True)@@ -515,6 +519,21 @@ class ExternalDataSchemaSerializer(serializers.ModelSerializer):was_sync_time_of_day_updated = Falsesource = instance.source+ # Sub-5-minute cadence is only valid for CDC. Enforce server-side so API/MCP callers (not+ # just the UI) can't drop a non-CDC schema below the allowed floor. We validate the+ # frequency the schema will actually end up with — the new value if one is supplied, else+ # the existing interval — against the sync type it will end up with. This also catches+ # switching a 1-minute CDC schema to a non-CDC type without re-sending the frequency.+ resulting_sync_type = sync_type if "sync_type" in data else instance.sync_type+ resulting_frequency = sync_frequency+ if not resulting_frequency and instance.sync_frequency_interval is not None:+ resulting_frequency = sync_frequency_interval_to_sync_frequency(instance.sync_frequency_interval)+ if resulting_frequency in CDC_ONLY_SYNC_FREQUENCIES and resulting_sync_type != ExternalDataSchema.SyncType.CDC:+ raise ValidationError(+ "A 1-minute sync frequency is only available for CDC schemas. "+ "The fastest frequency for other sync types is 5 minutes."+ )+if sync_frequency:sync_frequency_interval = sync_frequency_to_sync_frequency_interval(sync_frequency)diff --git a/products/data_warehouse/backend/api/test/test_external_data_schema.py b/products/data_warehouse/backend/api/test/test_external_data_schema.pyindex 6ee672b949a2..2258f9dde7ce 100644--- a/products/data_warehouse/backend/api/test/test_external_data_schema.py+++ b/products/data_warehouse/backend/api/test/test_external_data_schema.py@@ -500,6 +500,86 @@ class TestExternalDataSchema(APIBaseTest):schema.refresh_from_db()assert schema.sync_type_config["primary_key_columns"] == ["id"]+ @parameterized.expand(+ [+ ("incremental", ExternalDataSchema.SyncType.INCREMENTAL, 400),+ ("full_refresh", ExternalDataSchema.SyncType.FULL_REFRESH, 400),+ ("cdc", ExternalDataSchema.SyncType.CDC, 200),+ ]+ )+ def test_update_schema_one_minute_frequency_only_for_cdc(self, _name, sync_type, expected_status):+ # A 1-minute cadence is CDC-only. The backend must enforce this regardless of caller+ # (UI, API, or MCP) so non-CDC schemas can't be pushed below the 5-minute floor.+ is_cdc = sync_type == ExternalDataSchema.SyncType.CDC+ source = ExternalDataSource.objects.create(+ team=self.team,+ source_type=ExternalDataSourceType.POSTGRES if is_cdc else ExternalDataSourceType.STRIPE,+ job_inputs={"host": "h", "port": 5432, "database": "d", "user": "u", "password": "p", "schema": "public"},+ )+ schema = ExternalDataSchema.objects.create(+ name="public.orders",+ team=self.team,+ source=source,+ should_sync=True,+ status=ExternalDataSchema.Status.COMPLETED,+ sync_type=sync_type,+ sync_type_config={"primary_key_columns": ["id"]} if is_cdc else {},+ )++ with (+ mock.patch(+ "products.data_warehouse.backend.api.external_data_schema.is_cdc_enabled_for_team",+ return_value=True,+ ),+ mock.patch(+ "products.data_warehouse.backend.api.external_data_schema.external_data_workflow_exists",+ return_value=False,+ ),+ mock.patch("products.data_warehouse.backend.api.external_data_schema.sync_external_data_job_workflow"),+ mock.patch("products.data_warehouse.backend.api.external_data_schema.sync_cdc_extraction_schedule"),+ ):+ response = self.client.patch(+ f"/api/environments/{self.team.pk}/external_data_schemas/{schema.id}",+ data={"sync_frequency": "1min"},+ )++ assert response.status_code == expected_status, response.content+ if expected_status == 400:+ assert "cdc" in str(response.json()).lower()+ schema.refresh_from_db()+ # Rejected before the interval is persisted.+ assert schema.sync_frequency_interval != timedelta(minutes=1)++ def test_update_schema_one_minute_cannot_survive_switch_away_from_cdc(self):+ # Closing the gap where a CDC schema on a 1-minute schedule is switched to a non-CDC sync+ # type without re-sending sync_frequency — the existing 1-minute interval must be rejected.+ source = ExternalDataSource.objects.create(+ team=self.team,+ source_type=ExternalDataSourceType.POSTGRES,+ job_inputs={"host": "h", "port": 5432, "database": "d", "user": "u", "password": "p", "schema": "public"},+ )+ schema = ExternalDataSchema.objects.create(+ name="public.orders",+ team=self.team,+ source=source,+ should_sync=True,+ status=ExternalDataSchema.Status.COMPLETED,+ sync_type=ExternalDataSchema.SyncType.CDC,+ sync_type_config={"primary_key_columns": ["id"]},+ sync_frequency_interval=timedelta(minutes=1),+ )++ response = self.client.patch(+ f"/api/environments/{self.team.pk}/external_data_schemas/{schema.id}",+ data={"sync_type": "incremental"},+ )++ assert response.status_code == 400, response.content+ assert "cdc" in str(response.json()).lower()+ schema.refresh_from_db()+ assert schema.sync_frequency_interval == timedelta(minutes=1)+ assert schema.sync_type == ExternalDataSchema.SyncType.CDC+def test_update_schema_enable_should_sync_rejects_cdc_without_primary_key(self):# Schemas already in CDC mode with an empty primary_key_columns (created before the# API gate landed) must not be re-enabled until a PK is added on the source side.diff --git a/products/data_warehouse/frontend/scenes/SchemaScene/ConfigurationTab.tsx b/products/data_warehouse/frontend/scenes/SchemaScene/ConfigurationTab.tsxindex 86bb1d8df848..a4fc736b7fba 100644--- a/products/data_warehouse/frontend/scenes/SchemaScene/ConfigurationTab.tsx+++ b/products/data_warehouse/frontend/scenes/SchemaScene/ConfigurationTab.tsx@@ -36,6 +36,7 @@ import {import {StatusTagSetting,SyncFrequencyLabelMap,+ allowedSyncFrequencies,defaultQuery,syncAnchorIntervalToHumanReadable,} from 'products/data_warehouse/frontend/utils'@@ -567,14 +568,9 @@ function ScheduleSection({}): JSX.Element {const { loadSchema } = useActions(schemaSceneLogic({ sourceId, schemaId: schema.id }))const isCdc = schema.sync_type === 'cdc'- const makeOption = (value: DataWarehouseSyncInterval): LemonSelectOption<DataWarehouseSyncInterval> => ({- value,- label: SyncFrequencyLabelMap[value],- })- const cdcOnlyOptions: LemonSelectOption<DataWarehouseSyncInterval>[] = [makeOption('1min')]- const standardOptions: LemonSelectOption<DataWarehouseSyncInterval>[] = (- ['5min', '15min', '30min', '1hour', '6hour', '12hour', '24hour', '7day', '30day'] as const- ).map(makeOption)+ const frequencyOptions: LemonSelectOption<DataWarehouseSyncInterval>[] = allowedSyncFrequencies(+ schema.sync_type+ ).map((value) => ({ value, label: SyncFrequencyLabelMap[value] }))const [draftFrequency, setDraftFrequency] = useState<DataWarehouseSyncInterval>(schema.sync_frequency || (isCdc ? '5min' : '6hour')@@ -642,7 +638,7 @@ function ScheduleSection({}value={draftFrequency}onChange={(value) => setDraftFrequency(value as DataWarehouseSyncInterval)}- options={isCdc ? [...cdcOnlyOptions, ...standardOptions] : standardOptions}+ options={frequencyOptions}/></div><AnchorTimeFielddiff --git a/products/data_warehouse/frontend/scenes/SourceScene/tabs/SchemasTab.tsx b/products/data_warehouse/frontend/scenes/SourceScene/tabs/SchemasTab.tsxindex fadcdf7e3cf1..e1baecd8b6b0 100644--- a/products/data_warehouse/frontend/scenes/SourceScene/tabs/SchemasTab.tsx+++ b/products/data_warehouse/frontend/scenes/SourceScene/tabs/SchemasTab.tsx@@ -7,6 +7,7 @@ import {LemonButton,LemonDialog,LemonInput,+ LemonSelect,LemonSwitch,LemonTable,LemonTag,@@ -19,6 +20,7 @@ import { TZLabel } from 'lib/components/TZLabel'import { FEATURE_FLAGS } from 'lib/constants'import { dayjs } from 'lib/dayjs'import { More } from 'lib/lemon-ui/LemonButton/More'+import { LemonMenu } from 'lib/lemon-ui/LemonMenu'import { LemonTableLink } from 'lib/lemon-ui/LemonTable/LemonTableLink'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { pluralize } from 'lib/utils'@@ -26,18 +28,30 @@ import { teamLogic } from 'scenes/teamLogic'import { urls } from 'scenes/urls'import { ExternalDataSourceType, ProductIntentContext, ProductKey } from '~/queries/schema/schema-general'-import { ExternalDataSource, ExternalDataSourceSchema } from '~/types'+import { DataWarehouseSyncInterval, ExternalDataSource, ExternalDataSourceSchema } from '~/types'import { DATA_WAREHOUSE_APP_SOURCE } from 'products/data_warehouse/frontend/shared/components/metrics/DataWarehouseMetrics'-import { SourceEditorAction } from 'products/data_warehouse/frontend/shared/components/SourceEditorAction'+import {+ SourceEditorAction,+ useSourceEditorAccess,+} from 'products/data_warehouse/frontend/shared/components/SourceEditorAction'import { sourceManagementLogic } from 'products/data_warehouse/frontend/shared/logics/sourceManagementLogic'-import { StatusTagSetting, SyncFrequencyLabelMap, SyncTypeLabelMap } from 'products/data_warehouse/frontend/utils'+import {+ SYNC_FREQUENCY_ORDER,+ StatusTagSetting,+ SyncFrequencyLabelMap,+ SyncTypeLabelMap,+ allowedSyncFrequencies,+} from 'products/data_warehouse/frontend/utils'import { DirectQuerySchemasTab } from './DirectQuerySchemasTab'import { sourceSettingsLogic } from './sourceSettingsLogic'const REVENUE_ENABLED_SOURCES: ExternalDataSourceType[] = ['Stripe']+const frequencyRank = (frequency: DataWarehouseSyncInterval | null | undefined): number =>+ frequency ? SYNC_FREQUENCY_ORDER.indexOf(frequency) : -1+export interface SchemasTabProps {id: string}@@ -71,12 +85,19 @@ function ManagedSchemasTab({ id }: { id: string }): JSX.Element {filteredSchemas,showEnabledSchemasOnly,schemaNameFilter,+ statusFilter,+ syncMethodFilter,+ frequencyFilter,+ schemaFilterOptions,syncingNow,refreshingSchemas,} = useValues(sourceSettingsLogic)const {setShowEnabledSchemasOnly,setSchemaNameFilter,+ setStatusFilter,+ setSyncMethodFilter,+ setFrequencyFilter,syncNow,refreshSchemas,updateSchema,@@ -108,6 +129,42 @@ function ManagedSchemasTab({ id }: { id: string }): JSX.Element {value={schemaNameFilter}onChange={setSchemaNameFilter}/>+ <LemonSelect+ size="small"+ placeholder="All statuses"+ value={statusFilter}+ onChange={setStatusFilter}+ options={[+ { value: null, label: 'All statuses' },+ ...schemaFilterOptions.statuses.map((status) => ({ value: status, label: status })),+ ]}+ />+ <LemonSelect+ size="small"+ placeholder="All sync methods"+ value={syncMethodFilter}+ onChange={setSyncMethodFilter}+ options={[+ { value: null, label: 'All sync methods' },+ ...schemaFilterOptions.syncMethods.map((method) => ({+ value: method === 'none' ? 'none' : method,+ label: method === 'none' ? 'Not set up' : SyncTypeLabelMap[method],+ })),+ ]}+ />+ <LemonSelect+ size="small"+ placeholder="All frequencies"+ value={frequencyFilter}+ onChange={setFrequencyFilter}+ options={[+ { value: null, label: 'All frequencies' },+ ...schemaFilterOptions.frequencies.map((frequency) => ({+ value: frequency,+ label: SyncFrequencyLabelMap[frequency],+ })),+ ]}+ /><span className="text-muted text-sm">{pluralize(filteredSchemas.length, 'schema', 'schemas')}</span></div><div className="flex items-center gap-2">@@ -140,7 +197,7 @@ function ManagedSchemasTab({ id }: { id: string }): JSX.Element {: undefined}>- Sync now+ Sync all enabled schemas</LemonButton></SourceEditorAction><SourceEditorAction source={source}>@@ -227,6 +284,7 @@ function ManagedSchemaTable({}: ManagedSchemaTableProps): JSX.Element {const { schemaReloadingById } = useValues(sourceManagementLogic)const { setSelectedSchemas } = useActions(sourceSettingsLogic)+ const { disabledReason: editDisabledReason } = useSourceEditorAccess(source)const [initialLoad, setInitialLoad] = useState(true)useEffect(() => {@@ -241,10 +299,20 @@ function ManagedSchemaTable({loading={initialLoad}disableTableWhileLoading={false}pagination={{ pageSize: 100, hideOnSinglePage: true }}+ bulkSelection={{+ getKey: (schema) => schema.id,+ isRowSelectable: () => (editDisabledReason ? { disabledReason: editDisabledReason } : true),+ noun: ['schema', 'schemas'],+ barClassName: 'mb-2',+ renderActions: (ctx) => (+ <SchemaBulkActions schemas={ctx.selectedRecords} clearSelection={ctx.clearSelection} />+ ),+ }}columns={[{title: 'Schema',key: 'name',+ sorter: (a, b) => (a.label ?? a.name).localeCompare(b.label ?? b.name),render: function RenderName(_, schema) {const name = schema.label ?? schema.namereturn (@@ -268,6 +336,7 @@ function ManagedSchemaTable({{title: 'Status',key: 'status',+ sorter: (a, b) => (a.status ?? '').localeCompare(b.status ?? ''),render: (_, schema) => {if (!schema.status) {return <span className="text-muted">—</span>@@ -311,11 +380,15 @@ function ManagedSchemaTable({{title: 'Frequency',key: 'sync_frequency',+ sorter: (a, b) => frequencyRank(a.sync_frequency) - frequencyRank(b.sync_frequency),render: (_, schema) => (schema.sync_frequency ? SyncFrequencyLabelMap[schema.sync_frequency] : '—'),},{title: 'Last synced',key: 'last_synced_at',+ sorter: (a, b) =>+ (a.last_synced_at ? dayjs(a.last_synced_at).valueOf() : 0) -+ (b.last_synced_at ? dayjs(b.last_synced_at).valueOf() : 0),render: (_, schema) =>schema.last_synced_at ? (<TZLabel time={schema.last_synced_at} formatDate="MMM DD, YYYY" formatTime="HH:mm" />@@ -327,6 +400,7 @@ function ManagedSchemaTable({title: 'Rows synced',key: 'rows_synced',align: 'right',+ sorter: (a, b) => (a.table?.row_count ?? 0) - (b.table?.row_count ?? 0),render: (_, schema) => {if (schema.table) {return schema.table.row_count?.toLocaleString() ?? 0@@ -477,6 +551,119 @@ function ManagedSchemaTable({)}+function SchemaBulkActions({+ schemas,+ clearSelection,+}: {+ schemas: readonly ExternalDataSourceSchema[]+ clearSelection: () => void+}): JSX.Element {+ const { bulkDisable, bulkSetFrequency, bulkSyncNow, bulkResync, bulkDeleteData } = useActions(sourceSettingsLogic)++ // Wrap every action so the selection clears once it's been kicked off.+ const run = (action: () => void): void => {+ action()+ clearSelection()+ }++ const selected = [...schemas]+ const count = selected.length++ // Only offer frequencies every selected schema supports. Non-CDC schemas floor at 5min, so a+ // mixed selection falls back to the non-CDC set (which CDC also supports).+ const allCdc = selected.length > 0 && selected.every((schema) => schema.sync_type === 'cdc')+ const frequencyOptions = allowedSyncFrequencies(allCdc ? 'cdc' : 'incremental')++ const onDisable = (): void => {+ const hasDataLossType = selected.some((schema) => schema.sync_type === 'cdc' || schema.sync_type === 'webhook')+ if (!hasDataLossType) {+ run(() => bulkDisable(selected))+ return+ }+ LemonDialog.open({+ title: `Disable ${pluralize(count, 'schema', 'schemas')}?`,+ description:+ 'Some selected tables use CDC or webhook sync. Disabling stops consuming changes — re-enabling them later requires a full resync to avoid missing data.',+ primaryButton: {+ children: 'Disable',+ status: 'danger',+ onClick: () => run(() => bulkDisable(selected)),+ },+ secondaryButton: { children: 'Cancel', type: 'tertiary' },+ })+ }++ return (+ <>+ <LemonButton type="secondary" size="small" onClick={onDisable}>+ Disable+ </LemonButton>+ <LemonMenu+ items={frequencyOptions.map((interval) => ({+ label: SyncFrequencyLabelMap[interval],+ onClick: () => run(() => bulkSetFrequency(selected, interval)),+ }))}+ >+ <LemonButton type="secondary" size="small">+ Set frequency+ </LemonButton>+ </LemonMenu>+ <LemonButton type="secondary" size="small" onClick={() => run(() => bulkSyncNow(selected))}>+ Sync now+ </LemonButton>+ <More+ size="small"+ overlay={+ <>+ <LemonButton+ type="tertiary"+ size="xsmall"+ fullWidth+ status="danger"+ onClick={() =>+ LemonDialog.open({+ title: `Delete tables and resync ${pluralize(count, 'schema', 'schemas')}?`,+ description:+ 'Existing data for the selected tables is deleted and re-imported from scratch. Only recommended if there is a data-quality issue with previously imported data.',+ primaryButton: {+ children: 'Delete and resync',+ status: 'danger',+ onClick: () => run(() => bulkResync(selected)),+ },+ secondaryButton: { children: 'Cancel', type: 'tertiary' },+ })+ }+ >+ Delete tables and resync+ </LemonButton>+ <LemonButton+ type="tertiary"+ size="xsmall"+ fullWidth+ status="danger"+ onClick={() =>+ LemonDialog.open({+ title: `Delete ${pluralize(count, 'table', 'tables')} from PostHog?`,+ description:+ 'Removes the synced tables from PostHog. The data in the source is not touched.',+ primaryButton: {+ children: 'Delete from PostHog',+ status: 'danger',+ onClick: () => run(() => bulkDeleteData(selected)),+ },+ secondaryButton: { children: 'Cancel', type: 'tertiary' },+ })+ }+ >+ Delete tables from PostHog+ </LemonButton>+ </>+ }+ />+ </>+ )+}+function SchemaRowMore({source,schema,diff --git a/products/data_warehouse/frontend/scenes/SourceScene/tabs/sourceSettingsLogic.test.ts b/products/data_warehouse/frontend/scenes/SourceScene/tabs/sourceSettingsLogic.test.tsindex 44768bf4259f..ec010d2ddea4 100644--- a/products/data_warehouse/frontend/scenes/SourceScene/tabs/sourceSettingsLogic.test.ts+++ b/products/data_warehouse/frontend/scenes/SourceScene/tabs/sourceSettingsLogic.test.ts@@ -1,6 +1,23 @@import type { SourceFieldConfig } from '~/queries/schema/schema-general'+import type { ExternalDataSourceSchema } from '~/types'-import { isSensitiveCredentialField, removeEmptySensitiveValues } from './sourceSettingsLogic'+import {+ clampFrequencyForSchema,+ isSensitiveCredentialField,+ removeEmptySensitiveValues,+ runBulkSchemaAction,+ schemasEligibleForSync,+} from './sourceSettingsLogic'++function makeSchema(overrides: Partial<ExternalDataSourceSchema>): ExternalDataSourceSchema {+ return {+ id: 'schema-id',+ name: 'public.table',+ should_sync: false,+ sync_type: null,+ ...overrides,+ } as ExternalDataSourceSchema+}describe('isSensitiveCredentialField', () => {it('treats password-typed fields as sensitive', () => {@@ -173,3 +190,54 @@ describe('removeEmptySensitiveValues', () => {expect(value).toEqual({ feature: { enabled: true } })})})++describe('schemasEligibleForSync', () => {+ it('keeps only schemas that are enabled with a sync method', () => {+ const schemas = [+ makeSchema({ id: 'a', sync_type: 'incremental', should_sync: true }),+ makeSchema({ id: 'b', sync_type: 'incremental', should_sync: false }), // disabled+ makeSchema({ id: 'c', sync_type: null, should_sync: true }), // no method+ makeSchema({ id: 'd', sync_type: 'cdc', should_sync: true }),+ ]+ expect(schemasEligibleForSync(schemas).map((s) => s.id)).toEqual(['a', 'd'])+ })++ it('returns an empty list when nothing is eligible', () => {+ expect(schemasEligibleForSync([makeSchema({ sync_type: null, should_sync: true })])).toEqual([])+ })+})++describe('clampFrequencyForSchema', () => {+ it('floors non-CDC schemas at 5 minutes', () => {+ const incremental = makeSchema({ sync_type: 'incremental' })+ expect(clampFrequencyForSchema('1min', incremental)).toBe('5min')+ expect(clampFrequencyForSchema('5min', incremental)).toBe('5min')+ expect(clampFrequencyForSchema('1hour', incremental)).toBe('1hour')+ })++ it('lets CDC schemas go down to 1 minute', () => {+ const cdc = makeSchema({ sync_type: 'cdc' })+ expect(clampFrequencyForSchema('1min', cdc)).toBe('1min')+ expect(clampFrequencyForSchema('6hour', cdc)).toBe('6hour')+ })+})++describe('runBulkSchemaAction', () => {+ it('invokes the action for every schema and reports zero failures on success', async () => {+ const schemas = [makeSchema({ id: 'a' }), makeSchema({ id: 'b' })]+ const action = jest.fn().mockResolvedValue(undefined)+ const failed = await runBulkSchemaAction(schemas, action)+ expect(action).toHaveBeenCalledTimes(2)+ expect(action).toHaveBeenCalledWith('a')+ expect(action).toHaveBeenCalledWith('b')+ expect(failed).toBe(0)+ })++ it('counts rejected actions without throwing', async () => {+ const schemas = [makeSchema({ id: 'a' }), makeSchema({ id: 'b' }), makeSchema({ id: 'c' })]+ const action = jest.fn((id: string) => (id === 'b' ? Promise.reject(new Error('boom')) : Promise.resolve()))+ const failed = await runBulkSchemaAction(schemas, action)+ expect(failed).toBe(1)+ expect(action).toHaveBeenCalledTimes(3)+ })+})diff --git a/products/data_warehouse/frontend/scenes/SourceScene/tabs/sourceSettingsLogic.ts b/products/data_warehouse/frontend/scenes/SourceScene/tabs/sourceSettingsLogic.tsindex 0e29ef8c6a33..f0c642ce78c2 100644--- a/products/data_warehouse/frontend/scenes/SourceScene/tabs/sourceSettingsLogic.ts+++ b/products/data_warehouse/frontend/scenes/SourceScene/tabs/sourceSettingsLogic.ts@@ -7,12 +7,13 @@ import posthog from 'posthog-js'import { lemonToast } from '@posthog/lemon-ui'import api from 'lib/api'-import { objectsEqual } from 'lib/utils'+import { objectsEqual, pluralize } from 'lib/utils'import { sceneLogic } from 'scenes/sceneLogic'import { urls } from 'scenes/urls'import { SourceConfig, SourceFieldConfig } from '~/queries/schema/schema-general'import {+ DataWarehouseSyncInterval,ExternalDataJob,ExternalDataJobStatus,ExternalDataSchemaStatus,@@ -20,6 +21,8 @@ import {ExternalDataSourceSchema,} from '~/types'+import { SYNC_FREQUENCY_ORDER, clampSyncFrequency } from 'products/data_warehouse/frontend/utils'+import { sourcesDataLogic } from '../../../shared/logics/sourcesDataLogic'import { availableSourcesLogic } from '../../NewSourceScene/availableSourcesLogic'import { SSH_FIELD, getErrorsForFields } from '../../NewSourceScene/sourceWizardLogic'@@ -219,6 +222,44 @@ export const removeEmptySensitiveValues = (fields: SourceFieldConfig[], valueObj}}+// Run a per-schema API action across many schemas; returns how many failed.+export async function runBulkSchemaAction(+ schemas: ExternalDataSourceSchema[],+ action: (schemaId: string) => Promise<unknown>+): Promise<number> {+ const results = await Promise.allSettled(schemas.map((schema) => action(schema.id)))+ return results.filter((result) => result.status === 'rejected').length+}++// Only schemas that are enabled with a configured sync method can be synced on demand.+export function schemasEligibleForSync(schemas: ExternalDataSourceSchema[]): ExternalDataSourceSchema[] {+ return schemas.filter((schema) => !!schema.sync_type && schema.should_sync)+}++export function clampFrequencyForSchema(+ requested: DataWarehouseSyncInterval,+ schema: ExternalDataSourceSchema+): DataWarehouseSyncInterval {+ return clampSyncFrequency(requested, schema.sync_type)+}++function reportBulkResult(verb: string, total: number, failed: number, skipped: number, skipReason = ''): void {+ const succeeded = total - failed+ const parts = [`${verb} ${pluralize(succeeded, 'schema', 'schemas')}`]+ if (failed > 0) {+ parts.push(`${failed} failed`)+ }+ if (skipped > 0) {+ parts.push(`skipped ${skipped}${skipReason ? ` ${skipReason}` : ''}`)+ }+ const message = parts.join(', ')+ if (failed > 0) {+ lemonToast.error(message)+ } else {+ lemonToast.success(message)+ }+}+export const sourceSettingsLogic = kea<sourceSettingsLogicType>([path(['products', 'dataWarehouse', 'sourceSettingsLogic']),props({} as SourceSettingsLogicProps),@@ -233,11 +274,22 @@ export const sourceSettingsLogic = kea<sourceSettingsLogicType>([resyncSchema: (schema: ExternalDataSourceSchema) => ({ schema }),cancelSchema: (schema: ExternalDataSourceSchema) => ({ schema }),deleteTable: (schema: ExternalDataSourceSchema) => ({ schema }),+ bulkDisable: (schemas: ExternalDataSourceSchema[]) => ({ schemas }),+ bulkSetFrequency: (schemas: ExternalDataSourceSchema[], frequency: DataWarehouseSyncInterval) => ({+ schemas,+ frequency,+ }),+ bulkSyncNow: (schemas: ExternalDataSourceSchema[]) => ({ schemas }),+ bulkResync: (schemas: ExternalDataSourceSchema[]) => ({ schemas }),+ bulkDeleteData: (schemas: ExternalDataSourceSchema[]) => ({ schemas }),setCanLoadMoreJobs: (canLoadMoreJobs: boolean) => ({ canLoadMoreJobs }),setIsProjectTime: (isProjectTime: boolean) => ({ isProjectTime }),setSelectedSchemas: (schemaNames: string[]) => ({ schemaNames }),setShowEnabledSchemasOnly: (showEnabledSchemasOnly: boolean) => ({ showEnabledSchemasOnly }),setSchemaNameFilter: (schemaNameFilter: string) => ({ schemaNameFilter }),+ setStatusFilter: (status: string | null) => ({ status }),+ setSyncMethodFilter: (syncMethod: string | null) => ({ syncMethod }),+ setFrequencyFilter: (frequency: DataWarehouseSyncInterval | null) => ({ frequency }),syncNow: true,setSyncingNow: (syncing: boolean) => ({ syncing }),refreshSchemas: true,@@ -383,6 +435,26 @@ export const sourceSettingsLogic = kea<sourceSettingsLogicType>([setSchemaNameFilter: (_, { schemaNameFilter }) => schemaNameFilter,},],+ // null = no filter applied (show all). For sync method, the sentinel 'none' matches+ // schemas with no sync method set up yet.+ statusFilter: [+ null as string | null,+ {+ setStatusFilter: (_, { status }) => status,+ },+ ],+ syncMethodFilter: [+ null as string | null,+ {+ setSyncMethodFilter: (_, { syncMethod }) => syncMethod,+ },+ ],+ frequencyFilter: [+ null as DataWarehouseSyncInterval | null,+ {+ setFrequencyFilter: (_, { frequency }) => frequency,+ },+ ],syncingNow: [false as boolean,{@@ -433,8 +505,22 @@ export const sourceSettingsLogic = kea<sourceSettingsLogicType>([},],filteredSchemas: [- (s) => [s.source, s.showEnabledSchemasOnly, s.schemaNameFilter],- (source, showEnabledSchemasOnly, schemaNameFilter): ExternalDataSourceSchema[] => {+ (s) => [+ s.source,+ s.showEnabledSchemasOnly,+ s.schemaNameFilter,+ s.statusFilter,+ s.syncMethodFilter,+ s.frequencyFilter,+ ],+ (+ source,+ showEnabledSchemasOnly,+ schemaNameFilter,+ statusFilter,+ syncMethodFilter,+ frequencyFilter+ ): ExternalDataSourceSchema[] => {if (!source?.schemas) {return []}@@ -446,9 +532,51 @@ export const sourceSettingsLogic = kea<sourceSettingsLogicType>([const filter = schemaNameFilter.toLowerCase()schemas = schemas.filter((schema) => (schema.label ?? schema.name).toLowerCase().includes(filter))}+ if (statusFilter) {+ schemas = schemas.filter((schema) => schema.status === statusFilter)+ }+ if (syncMethodFilter) {+ schemas = schemas.filter((schema) =>+ syncMethodFilter === 'none' ? !schema.sync_type : schema.sync_type === syncMethodFilter+ )+ }+ if (frequencyFilter) {+ schemas = schemas.filter((schema) => schema.sync_frequency === frequencyFilter)+ }return schemas},],+ // Distinct values present across the source's schemas, for populating the filter dropdowns.+ schemaFilterOptions: [+ (s) => [s.source],+ (+ source+ ): {+ statuses: string[]+ syncMethods: (Exclude<ExternalDataSourceSchema['sync_type'], null> | 'none')[]+ frequencies: DataWarehouseSyncInterval[]+ } => {+ const schemas = source?.schemas ?? []+ const statuses = new Set<string>()+ const syncMethods = new Set<Exclude<ExternalDataSourceSchema['sync_type'], null> | 'none'>()+ const frequencies = new Set<DataWarehouseSyncInterval>()+ for (const schema of schemas) {+ if (schema.status) {+ statuses.add(schema.status)+ }+ syncMethods.add(schema.sync_type ?? 'none')+ if (schema.sync_frequency) {+ frequencies.add(schema.sync_frequency)+ }+ }+ return {+ statuses: Array.from(statuses),+ syncMethods: Array.from(syncMethods),+ // Order shortest→longest for a readable dropdown rather than schema-encounter order.+ frequencies: SYNC_FREQUENCY_ORDER.filter((frequency) => frequencies.has(frequency)),+ }+ },+ ],}),forms(({ values, actions }) => ({sourceConfig: {@@ -837,6 +965,67 @@ export const sourceSettingsLogic = kea<sourceSettingsLogicType>([}}},+ bulkDisable: ({ schemas }) => {+ // Reuse the debounced single-schema update — these coalesce into one bulk PATCH.+ schemas.forEach((schema) => actions.updateSchema({ ...schema, should_sync: false }))+ lemonToast.success(`Disabled ${pluralize(schemas.length, 'schema', 'schemas')}`)+ },+ bulkSetFrequency: ({ schemas, frequency }) => {+ // Non-CDC schemas can't sync faster than every 5 minutes — clamp so a bulk edit+ // never pushes them below their allowed floor.+ let clamped = 0+ schemas.forEach((schema) => {+ const effective = clampFrequencyForSchema(frequency, schema)+ if (effective !== frequency) {+ clamped+++ }+ actions.updateSchema({ ...schema, sync_frequency: effective })+ })+ const base = `Updated sync frequency for ${pluralize(schemas.length, 'schema', 'schemas')}`+ lemonToast.success(clamped > 0 ? `${base} (${clamped} kept at their 5 min minimum)` : base)+ },+ bulkSyncNow: async ({ schemas }) => {+ // Only schemas that are enabled with a sync method can sync.+ const eligible = schemasEligibleForSync(schemas)+ const skipped = schemas.length - eligible.length+ if (eligible.length === 0) {+ lemonToast.warning('None of the selected schemas are enabled with a sync method')+ return+ }+ const failed = await runBulkSchemaAction(eligible, (id) => api.externalDataSchemas.reload(id))+ actions.loadSource()+ actions.loadJobs()+ posthog.capture('schemas bulk synced', {+ sourceType: values.source?.source_type,+ count: eligible.length,+ })+ reportBulkResult(+ 'Started sync for',+ eligible.length,+ failed,+ skipped,+ 'disabled or missing sync method'+ )+ },+ bulkResync: async ({ schemas }) => {+ const failed = await runBulkSchemaAction(schemas, (id) => api.externalDataSchemas.resync(id))+ actions.loadSource()+ actions.loadJobs()+ posthog.capture('schemas bulk resynced', {+ sourceType: values.source?.source_type,+ count: schemas.length,+ })+ reportBulkResult('Resyncing', schemas.length, failed, 0)+ },+ bulkDeleteData: async ({ schemas }) => {+ const failed = await runBulkSchemaAction(schemas, (id) => api.externalDataSchemas.delete_data(id))+ actions.loadSource()+ posthog.capture('schemas bulk data deleted', {+ sourceType: values.source?.source_type,+ count: schemas.length,+ })+ reportBulkResult('Deleted data for', schemas.length, failed, 0)+ },}}),afterMount(({ actions }) => {diff --git a/products/data_warehouse/frontend/utils.ts b/products/data_warehouse/frontend/utils.tsindex 47cf7d98913f..bc6dd8f70f9b 100644--- a/products/data_warehouse/frontend/utils.ts+++ b/products/data_warehouse/frontend/utils.ts@@ -180,6 +180,31 @@ export const SyncFrequencyLabelMap: Record<DataWarehouseSyncInterval, string> ='30day': 'Monthly',}+// Sync frequencies ordered shortest→longest. Object key order above is the single source of truth.+export const SYNC_FREQUENCY_ORDER = Object.keys(SyncFrequencyLabelMap) as DataWarehouseSyncInterval[]++// Sub-5-minute cadence is CDC-only; every other sync type floors at 5 minutes. This is the one+// place that rule lives — the schedule picker, bulk edits, and the clamp all derive from it.+export const CDC_ONLY_SYNC_FREQUENCIES: DataWarehouseSyncInterval[] = ['1min']++// Frequencies a given sync type is allowed to use. (The backend enforces the same rule in+// ExternalDataSchemaSerializer — keep them in sync if this changes.)+export function allowedSyncFrequencies(syncType: string | null | undefined): DataWarehouseSyncInterval[] {+ if (syncType === 'cdc') {+ return SYNC_FREQUENCY_ORDER+ }+ return SYNC_FREQUENCY_ORDER.filter((frequency) => !CDC_ONLY_SYNC_FREQUENCIES.includes(frequency))+}++// Raise a requested frequency to the fastest one the sync type permits (e.g. 1min → 5min for non-CDC).+export function clampSyncFrequency(+ requested: DataWarehouseSyncInterval,+ syncType: string | null | undefined+): DataWarehouseSyncInterval {+ const allowed = allowedSyncFrequencies(syncType)+ return allowed.includes(requested) ? requested : allowed[0]+}+export const StatusTagSetting: Record<ExternalDataJobStatus | ExternalDataSchemaStatus, LemonTagType> = {[ExternalDataJobStatus.Running]: 'primary',[ExternalDataJobStatus.Completed]: 'success',