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): fetch single schema on schema config page (#61209)

Daniel RCd33d3ba0561c
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index 8d9c0e163a8f..5c36d5145234 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -123,6 +123,7 @@ import {
Experiment,
ExportedAssetType,
ExternalDataJob,
+ ExternalDataSchemaWithSource,
ExternalDataSource,
ExternalDataSourceConnectionOption,
ExternalDataSourceCreatePayload,
@@ -5768,6 +5769,9 @@ const api = {
},
externalDataSchemas: {
+ async get(schemaId: ExternalDataSourceSchema['id']): Promise<ExternalDataSchemaWithSource> {
+ return await new ApiRequest().externalDataSourceSchema(schemaId).get()
+ },
async update(
schemaId: ExternalDataSourceSchema['id'],
data: Partial<ExternalDataSourceSchema>
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index c1d714887f13..f127940c3a1f 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -5999,6 +5999,19 @@ export interface ExternalDataSourceSchema extends SimpleExternalDataSourceSchema
available_columns?: { name: string; data_type?: string; is_nullable?: boolean }[]
}
+/** Lightweight parent-source summary embedded in the single-schema retrieve endpoint. */
+export interface ExternalDataSchemaSourceSummary {
+ id: string
+ source_type: ExternalDataSourceType
+ supports_column_selection?: boolean
+ user_access_level: AccessControlLevel | null
+}
+
+export interface ExternalDataSchemaWithSource extends ExternalDataSourceSchema {
+ /** Populated only on the single-schema retrieve endpoint; `null` when serialized elsewhere. */
+ source: ExternalDataSchemaSourceSummary | null
+}
+
export enum ExternalDataSchemaStatus {
Running = 'Running',
Completed = 'Completed',
diff --git a/products/data_warehouse/backend/api/external_data_schema.py b/products/data_warehouse/backend/api/external_data_schema.py
index ecd13d3fa187..c33698f12d4b 100644
--- a/products/data_warehouse/backend/api/external_data_schema.py
+++ b/products/data_warehouse/backend/api/external_data_schema.py
@@ -57,6 +57,16 @@ from products.warehouse_sources.backend.models.external_data_source import Exter
logger = structlog.get_logger(__name__)
+def source_supports_column_selection(source_type: str) -> bool:
+ try:
+ source = SourceRegistry.get_source(ExternalDataSourceType(source_type))
+ except Exception as e:
+ capture_exception(e)
+ return False
+ # `bool()` guards against test mocks whose attribute access returns a Mock — orjson can't serialize.
+ return bool(source.supports_column_selection)
+
+
_CDC_WRITE_TARGETS_BY_TABLE_MODE: dict[str, frozenset[str]] = {
"consolidated": frozenset({"consolidated"}),
"cdc_only": frozenset({"cdc_history"}),
@@ -181,6 +191,14 @@ class ExternalDataSchemaSerializer(serializers.ModelSerializer):
help_text="Source-side column metadata (name, data type, nullable) discovered for this schema. "
"Empty until the source has been refreshed via `refresh_schemas`.",
)
+ # `source` shadows DRF's reserved `Field.source` attribute, so mypy flags the assignment;
+ # the runtime behaviour (a read-only SerializerMethodField backed by get_source) is correct.
+ source = serializers.SerializerMethodField( # type: ignore[assignment]
+ read_only=True,
+ help_text="Lightweight parent-source summary (id, source_type, column-selection support, the requesting "
+ "user's access level). Only populated on the single-schema retrieve endpoint — `null` elsewhere — so "
+ "read-only views can render without fetching the full source and all its schemas.",
+ )
class Meta:
model = ExternalDataSchema
@@ -205,6 +223,7 @@ class ExternalDataSchemaSerializer(serializers.ModelSerializer):
"cdc_table_mode",
"enabled_columns",
"available_columns",
+ "source",
]
read_only_fields = [
@@ -217,6 +236,7 @@ class ExternalDataSchemaSerializer(serializers.ModelSerializer):
"status",
"description",
"available_columns",
+ "source",
]
@extend_schema_field(
@@ -248,6 +268,36 @@ class ExternalDataSchemaSerializer(serializers.ModelSerializer):
if isinstance(column, dict) and isinstance(column.get("name"), str)
]
+ @extend_schema_field(
+ {
+ "type": "object",
+ "nullable": True,
+ "properties": {
+ "id": {"type": "string"},
+ "source_type": {"type": "string"},
+ "supports_column_selection": {"type": "boolean"},
+ "user_access_level": {"type": "string", "nullable": True},
+ },
+ }
+ )
+ def get_source(self, schema: ExternalDataSchema) -> dict[str, Any] | None:
+ # Gated to the retrieve action (via `include_source` context) so the source endpoint's
+ # nested schema serialization and the schema `list` don't pay for the SourceRegistry lookup.
+ if not self.context.get("include_source"):
+ return None
+ source = schema.source
+ user_access_level = None
+ view = self.context.get("view")
+ user_access_control = getattr(view, "user_access_control", None)
+ if user_access_control is not None:
+ user_access_level = user_access_control.get_user_access_level(source)
+ return {
+ "id": str(source.id),
+ "source_type": source.source_type,
+ "supports_column_selection": source_supports_column_selection(source.source_type),
+ "user_access_level": user_access_level,
+ }
+
def get_status(self, schema: ExternalDataSchema) -> str | None:
if schema.status == ExternalDataSchema.Status.BILLING_LIMIT_REACHED:
return "Billing limits"
@@ -756,10 +806,16 @@ class ExternalDataSchemaViewset(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
def get_serializer_context(self) -> dict[str, Any]:
context = super().get_serializer_context()
context["database"] = Database.create_for(team_id=self.team_id)
+ # Only the single-schema retrieve embeds the parent-source summary (see ExternalDataSchemaSerializer.get_source).
+ context["include_source"] = self.action == "retrieve"
return context
def safely_get_queryset(self, queryset):
- return queryset.exclude(deleted=True).prefetch_related("created_by").order_by(self.ordering)
+ queryset = queryset.exclude(deleted=True).prefetch_related("created_by")
+ if self.action == "retrieve":
+ # retrieve serializes the source summary + table; pull them in one round-trip.
+ queryset = queryset.select_related("source", "table__credential", "table__external_data_source")
+ return queryset.order_by(self.ordering)
def destroy(self, request: Request, *args: Any, **kwargs: Any) -> Response:
instance: ExternalDataSchema = self.get_object()
diff --git a/products/data_warehouse/backend/api/external_data_source.py b/products/data_warehouse/backend/api/external_data_source.py
index 361718198a37..df57d8094efa 100644
--- a/products/data_warehouse/backend/api/external_data_source.py
+++ b/products/data_warehouse/backend/api/external_data_source.py
@@ -63,6 +63,7 @@ from products.data_modeling.backend.models.datawarehouse_managed_viewset import
from products.data_warehouse.backend.api.external_data_schema import (
ExternalDataSchemaSerializer,
SimpleExternalDataSchemaSerializer,
+ source_supports_column_selection,
)
from products.data_warehouse.backend.data_load.service import (
bulk_create_external_data_job_schedules,
@@ -625,13 +626,7 @@ class ExternalDataSourceSerializers(UserAccessControlSerializerMixin, serializer
return False
def get_supports_column_selection(self, instance: ExternalDataSource) -> bool:
- try:
- source = SourceRegistry.get_source(ExternalDataSourceType(instance.source_type))
- except Exception as e:
- capture_exception(e)
- return False
- # `bool()` guards against test mocks whose attribute access returns a Mock — orjson can't serialize.
- return bool(source.supports_column_selection)
+ return source_supports_column_selection(instance.source_type)
def get_status(self, instance: ExternalDataSource) -> str:
active_schemas: list[ExternalDataSchema] = list(instance.active_schemas) # type: ignore
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.py
index 162a165dc56b..6ee672b949a2 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
@@ -1862,3 +1862,49 @@ class TestAvailableColumnsAcrossSqlSources(APIBaseTest):
)
assert response.status_code == 200, response.json()
assert response.json()["supports_column_selection"] is expected
+
+
+class TestExternalDataSchemaRetrieveSource(APIBaseTest):
+ def _create(self, source_type: ExternalDataSourceType = ExternalDataSourceType.STRIPE):
+ source = ExternalDataSource.objects.create(
+ team=self.team,
+ source_type=source_type,
+ job_inputs={"auth_method": {"selection": "api_key", "stripe_secret_key": "123"}},
+ )
+ schema = ExternalDataSchema.objects.create(name="Customers", team=self.team, source=source)
+ return source, schema
+
+ @parameterized.expand(
+ [
+ (ExternalDataSourceType.STRIPE, False),
+ (ExternalDataSourceType.POSTGRES, True),
+ ]
+ )
+ def test_retrieve_includes_source_summary(
+ self, source_type: ExternalDataSourceType, expected_supports_column_selection: bool
+ ):
+ source, schema = self._create(source_type=source_type)
+ response = self.client.get(f"/api/environments/{self.team.pk}/external_data_schemas/{schema.id}/")
+ assert response.status_code == 200, response.json()
+ summary = response.json()["source"]
+ assert summary["id"] == str(source.id)
+ assert summary["source_type"] == source_type.value
+ assert summary["supports_column_selection"] is expected_supports_column_selection
+ assert "user_access_level" in summary
+
+ def test_list_omits_source_summary(self):
+ self._create()
+ response = self.client.get(f"/api/environments/{self.team.pk}/external_data_schemas/")
+ assert response.status_code == 200
+ results = response.json()["results"]
+ assert len(results) > 0
+ assert all(item["source"] is None for item in results)
+
+ def test_retrieve_cross_team_is_404(self):
+ other_team = create_team(organization=self.organization)
+ source = ExternalDataSource.objects.create(
+ team=other_team, source_type=ExternalDataSourceType.STRIPE, job_inputs={}
+ )
+ schema = ExternalDataSchema.objects.create(name="Customers", team=other_team, source=source)
+ response = self.client.get(f"/api/environments/{self.team.pk}/external_data_schemas/{schema.id}/")
+ assert response.status_code == 404
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 6591862dce28..2cfb13444e19 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
@@ -1304,6 +1304,7 @@ class TestExternalDataSource(APIBaseTest):
"cdc_table_mode": "consolidated",
"enabled_columns": None,
"available_columns": [],
+ "source": None,
}
],
)
diff --git a/products/data_warehouse/frontend/generated/api.schemas.ts b/products/data_warehouse/frontend/generated/api.schemas.ts
index c7e3c727924f..aed1b9ac2ecc 100644
--- a/products/data_warehouse/frontend/generated/api.schemas.ts
+++ b/products/data_warehouse/frontend/generated/api.schemas.ts
@@ -196,6 +196,18 @@ export type ExternalDataSchemaApiAvailableColumnsItem = {
is_nullable?: boolean
}
+/**
+ * Lightweight parent-source summary (id, source_type, column-selection support, the requesting user's access level). Only populated on the single-schema retrieve endpoint — `null` elsewhere — so read-only views can render without fetching the full source and all its schemas.
+ * @nullable
+ */
+export type ExternalDataSchemaApiSource = {
+ readonly id?: string
+ readonly source_type?: string
+ readonly supports_column_selection?: boolean
+ /** @nullable */
+ readonly user_access_level?: string | null
+} | null
+
export interface ExternalDataSchemaApi {
readonly id: string
readonly name: string
@@ -275,6 +287,11 @@ export interface ExternalDataSchemaApi {
enabled_columns?: string[] | null
/** Source-side column metadata (name, data type, nullable) discovered for this schema. Empty until the source has been refreshed via `refresh_schemas`. */
readonly available_columns: readonly ExternalDataSchemaApiAvailableColumnsItem[]
+ /**
+ * Lightweight parent-source summary (id, source_type, column-selection support, the requesting user's access level). Only populated on the single-schema retrieve endpoint — `null` elsewhere — so read-only views can render without fetching the full source and all its schemas.
+ * @nullable
+ */
+ readonly source: ExternalDataSchemaApiSource
}
export interface PaginatedExternalDataSchemaListApi {
@@ -297,6 +314,18 @@ export type PatchedExternalDataSchemaApiAvailableColumnsItem = {
is_nullable?: boolean
}
+/**
+ * Lightweight parent-source summary (id, source_type, column-selection support, the requesting user's access level). Only populated on the single-schema retrieve endpoint — `null` elsewhere — so read-only views can render without fetching the full source and all its schemas.
+ * @nullable
+ */
+export type PatchedExternalDataSchemaApiSource = {
+ readonly id?: string
+ readonly source_type?: string
+ readonly supports_column_selection?: boolean
+ /** @nullable */
+ readonly user_access_level?: string | null
+} | null
+
export interface PatchedExternalDataSchemaApi {
readonly id?: string
readonly name?: string
@@ -376,6 +405,11 @@ export interface PatchedExternalDataSchemaApi {
enabled_columns?: string[] | null
/** Source-side column metadata (name, data type, nullable) discovered for this schema. Empty until the source has been refreshed via `refresh_schemas`. */
readonly available_columns?: readonly PatchedExternalDataSchemaApiAvailableColumnsItem[]
+ /**
+ * Lightweight parent-source summary (id, source_type, column-selection support, the requesting user's access level). Only populated on the single-schema retrieve endpoint — `null` elsewhere — so read-only views can render without fetching the full source and all its schemas.
+ * @nullable
+ */
+ readonly source?: PatchedExternalDataSchemaApiSource
}
/**
diff --git a/products/data_warehouse/frontend/scenes/SchemaScene/ConfigurationTab.tsx b/products/data_warehouse/frontend/scenes/SchemaScene/ConfigurationTab.tsx
index 20917c07602d..86bb1d8df848 100644
--- a/products/data_warehouse/frontend/scenes/SchemaScene/ConfigurationTab.tsx
+++ b/products/data_warehouse/frontend/scenes/SchemaScene/ConfigurationTab.tsx
@@ -40,10 +40,8 @@ import {
syncAnchorIntervalToHumanReadable,
} from 'products/data_warehouse/frontend/utils'
-import { syncMethodModalLogic } from '../SourceScene/syncMethodModalLogic'
import { ColumnSelectionPicker } from '../SourceScene/tabs/ColumnSelectionModal'
-import { sourceSettingsLogic } from '../SourceScene/tabs/sourceSettingsLogic'
-import { SchemaConfigurationSection } from './schemaSceneLogic'
+import { SchemaConfigurationSection, schemaSceneLogic } from './schemaSceneLogic'
// null means "all columns" on either side, so switching to null after a partial list flags
// every previously-excluded column as added.
@@ -71,7 +69,7 @@ export function ConfigurationTab({
onConfigureSyncMethod,
onViewSyncHistory,
}: ConfigurationTabProps): JSX.Element {
- const logic = sourceSettingsLogic({ id: sourceId })
+ const logic = schemaSceneLogic({ sourceId, schemaId: schema.id })
const { isProjectTime, refreshingSchemas } = useValues(logic)
const { setIsProjectTime, updateSchema, reloadSchema, resyncSchema, cancelSchema, deleteTable, refreshSchemas } =
useActions(logic)
@@ -317,13 +315,12 @@ function SyncMethodSection({
source: ExternalDataSource | null
schema: ExternalDataSourceSchema
}): JSX.Element {
- // We use syncMethodModalLogic only for loading the schema's incremental fields — saving goes
- // through a direct bulkUpdateSchemas call so the logic's reset-on-success listener (used by
- // the modal flow in the new source wizard) doesn't blow the inline form back into a loading state.
- const logic = syncMethodModalLogic({ schema })
+ // Incremental fields + saving both go through schemaSceneLogic — deliberately NOT
+ // syncMethodModalLogic, which connects sourceManagementLogic and would mount + poll the full
+ // sources list (the heavy `external_data_sources` fetch this page is meant to avoid).
+ const logic = schemaSceneLogic({ sourceId, schemaId: schema.id })
const { schemaIncrementalFields, schemaIncrementalFieldsLoading } = useValues(logic)
- const { loadSchemaIncrementalFields } = useActions(logic)
- const { loadSource } = useActions(sourceSettingsLogic({ id: sourceId }))
+ const { loadSchemaIncrementalFields, loadSchema } = useActions(logic)
const formRef = useRef<SyncMethodFormHandle>(null)
const [saveDisabledReason, setSaveDisabledReason] = useState<string | undefined>()
@@ -333,8 +330,8 @@ function SyncMethodSection({
// Load incremental fields only when the schema id changes. We intentionally exclude the kea
// action refs from the deps — if they aren't stable, the effect would re-fire on every parent
- // re-render (e.g. the 5s sourceSettingsLogic auto-refresh), reset `schemaIncrementalFields`
- // to null, unmount the form, and blow away the user's in-progress radio/field selections.
+ // re-render, reset `schemaIncrementalFields` to null, unmount the form, and blow away the
+ // user's in-progress radio/field selections.
useEffect(() => {
loadSchemaIncrementalFields(schema.id)
// eslint-disable-next-line react-hooks/exhaustive-deps
@@ -361,7 +358,7 @@ function SyncMethodSection({
...(syncType === 'cdc' && cdcTableMode ? { cdc_table_mode: cdcTableMode } : {}),
})
lemonToast.success('Sync method saved')
- loadSource()
+ loadSchema()
} catch (e: any) {
lemonToast.error(e?.message || "Can't save sync method at this time")
} finally {
@@ -568,7 +565,7 @@ function ScheduleSection({
isProjectTime: boolean
setIsProjectTime: (v: boolean) => void
}): JSX.Element {
- const { loadSource } = useActions(sourceSettingsLogic({ id: sourceId }))
+ const { loadSchema } = useActions(schemaSceneLogic({ sourceId, schemaId: schema.id }))
const isCdc = schema.sync_type === 'cdc'
const makeOption = (value: DataWarehouseSyncInterval): LemonSelectOption<DataWarehouseSyncInterval> => ({
value,
@@ -615,7 +612,7 @@ function ScheduleSection({
},
])
lemonToast.success('Schedule saved')
- loadSource()
+ loadSchema()
} catch (e: any) {
lemonToast.error(e?.message || "Can't save schedule at this time")
} finally {
diff --git a/products/data_warehouse/frontend/scenes/SchemaScene/SchemaScene.tsx b/products/data_warehouse/frontend/scenes/SchemaScene/SchemaScene.tsx
index 57269f190108..1456d300a689 100644
--- a/products/data_warehouse/frontend/scenes/SchemaScene/SchemaScene.tsx
+++ b/products/data_warehouse/frontend/scenes/SchemaScene/SchemaScene.tsx
@@ -1,4 +1,4 @@
-import { BindLogic, useActions, useValues } from 'kea'
+import { useActions, useValues } from 'kea'
import { combineUrl, router } from 'kea-router'
import { useEffect } from 'react'
@@ -17,7 +17,6 @@ import { ProductKey } from '~/queries/schema/schema-general'
import { cleanSourceId } from 'products/data_warehouse/frontend/utils'
-import { sourceSettingsLogic } from '../SourceScene/tabs/sourceSettingsLogic'
import { ConfigurationTab } from './ConfigurationTab'
import { MetricsTab } from './MetricsTab'
import {
@@ -50,18 +49,11 @@ export function SchemaScene({ sourceId, schemaId }: SchemaSceneProps): JSX.Eleme
return <NotFound object="Data warehouse schema" />
}
- const cleanedSourceId = cleanSourceId(sourceId)
- const settingsLogicProps = { id: cleanedSourceId, availableSources: {} }
-
- return (
- <BindLogic logic={sourceSettingsLogic} props={settingsLogicProps}>
- <SchemaSceneContent sourceId={sourceId} schemaId={schemaId} />
- </BindLogic>
- )
+ return <SchemaSceneContent sourceId={sourceId} schemaId={schemaId} />
}
function SchemaSceneContent({ sourceId, schemaId }: SchemaSceneProps): JSX.Element {
- const { currentTab, currentSection, schema, source, sourceLoading } = useValues(
+ const { currentTab, currentSection, schema, source, schemaDataLoading, supportsColumnSelection } = useValues(
schemaSceneLogic({ sourceId, schemaId })
)
const { setCurrentTab, setCurrentSection } = useActions(schemaSceneLogic({ sourceId, schemaId }))
@@ -69,7 +61,7 @@ function SchemaSceneContent({ sourceId, schemaId }: SchemaSceneProps): JSX.Eleme
const cleanedSourceId = cleanSourceId(sourceId)
const showMetrics = !!featureFlags[FEATURE_FLAGS.DWH_SOURCE_METRICS]
- const showColumnsSection = source?.supports_column_selection === true
+ const showColumnsSection = supportsColumnSelection
const visibleSections = SCHEMA_CONFIGURATION_SECTIONS.filter((key) => key !== 'columns' || showColumnsSection)
useEffect(() => {
@@ -84,7 +76,7 @@ function SchemaSceneContent({ sourceId, schemaId }: SchemaSceneProps): JSX.Eleme
}
}, [showColumnsSection, currentSection, setCurrentSection])
- if (sourceLoading && !source) {
+ if (schemaDataLoading && !schema) {
return (
<SceneContent>
<LemonSkeleton className="w-full h-12" />
diff --git a/products/data_warehouse/frontend/scenes/SchemaScene/schemaSceneLogic.ts b/products/data_warehouse/frontend/scenes/SchemaScene/schemaSceneLogic.ts
index 4d7bc9d123d3..21a2a8be23e5 100644
--- a/products/data_warehouse/frontend/scenes/SchemaScene/schemaSceneLogic.ts
+++ b/products/data_warehouse/frontend/scenes/SchemaScene/schemaSceneLogic.ts
@@ -1,15 +1,27 @@
-import { actions, afterMount, beforeUnmount, connect, kea, key, path, props, reducers, selectors } from 'kea'
+import { actions, afterMount, kea, key, listeners, path, props, reducers, selectors } from 'kea'
+import { loaders } from 'kea-loaders'
import { actionToUrl, urlToAction } from 'kea-router'
+import posthog from 'posthog-js'
+import { lemonToast } from '@posthog/lemon-ui'
+
+import api from 'lib/api'
import { Scene } from 'scenes/sceneTypes'
import { urls } from 'scenes/urls'
import { SIDE_PANEL_CONTEXT_KEY, SidePanelSceneContext } from '~/layout/navigation-3000/sidepanel/types'
-import { ActivityScope, Breadcrumb, ExternalDataSourceSchema } from '~/types'
+import {
+ ActivityScope,
+ Breadcrumb,
+ ExternalDataSchemaStatus,
+ ExternalDataSchemaWithSource,
+ ExternalDataSource,
+ ExternalDataSourceSchema,
+ SchemaIncrementalFieldsResponse,
+} from '~/types'
import { cleanSourceId } from 'products/data_warehouse/frontend/utils'
-import { sourceSettingsLogic } from '../SourceScene/tabs/sourceSettingsLogic'
import type { schemaSceneLogicType } from './schemaSceneLogicType'
export const SCHEMA_SCENE_TABS = ['configuration', 'metrics'] as const
@@ -26,23 +38,73 @@ export interface SchemaSceneProps {
schemaId: string
}
+// Mirrors the bulk-update payload built by sourceSettingsLogic, but for a single schema.
+function buildSchemaUpdatePayload(schema: ExternalDataSourceSchema): Partial<ExternalDataSourceSchema> {
+ return {
+ should_sync: schema.should_sync,
+ sync_type: schema.sync_type,
+ incremental_field: schema.incremental_field,
+ incremental_field_type: schema.incremental_field_type,
+ sync_frequency: schema.sync_frequency,
+ sync_time_of_day: schema.sync_time_of_day,
+ cdc_table_mode: schema.cdc_table_mode,
+ enabled_columns: schema.enabled_columns ?? null,
+ }
+}
+
export const schemaSceneLogic = kea<schemaSceneLogicType>([
props({} as SchemaSceneProps),
- key(({ sourceId, schemaId }) => `${sourceId}-${schemaId}`),
+ // Schema ids are globally unique, so keying on schemaId alone lets the scene and ConfigurationTab
+ // resolve the same instance even though they pass a differently-prefixed sourceId.
+ key(({ schemaId }) => schemaId),
path((key) => ['products', 'dataWarehouse', 'schemaSceneLogic', key]),
- connect((props: SchemaSceneProps) => ({
- values: [sourceSettingsLogic({ id: cleanSourceId(props.sourceId) }), ['source', 'sourceLoading']],
- actions: [
- sourceSettingsLogic({ id: cleanSourceId(props.sourceId) }),
- ['pausePolling', 'resumePolling', 'loadSource'],
- ],
- })),
actions({
setCurrentTab: (tab: SchemaSceneTab) => ({ tab }),
setCurrentSection: (section: SchemaConfigurationSection) => ({ section }),
_setCurrentTab: (tab: SchemaSceneTab) => ({ tab }),
_setCurrentSection: (section: SchemaConfigurationSection) => ({ section }),
+ setIsProjectTime: (isProjectTime: boolean) => ({ isProjectTime }),
+ setRefreshingSchemas: (refreshing: boolean) => ({ refreshing }),
+ updateSchema: (schema: ExternalDataSourceSchema) => ({ schema }),
+ reloadSchema: (schema: ExternalDataSourceSchema) => ({ schema }),
+ resyncSchema: (schema: ExternalDataSourceSchema) => ({ schema }),
+ cancelSchema: (schema: ExternalDataSourceSchema) => ({ schema }),
+ deleteTable: (schema: ExternalDataSourceSchema) => ({ schema }),
+ refreshSchemas: true,
}),
+ loaders(({ props }) => ({
+ schemaData: [
+ null as ExternalDataSchemaWithSource | null,
+ {
+ loadSchema: async () => {
+ try {
+ return await api.externalDataSchemas.get(props.schemaId)
+ } catch (error: any) {
+ if (error?.status === 404) {
+ return null
+ }
+ throw error
+ }
+ },
+ },
+ ],
+ // Sync-method options for the schema (live call to the remote source). Kept here so the
+ // sync-method section doesn't need syncMethodModalLogic, which would mount + poll the
+ // full sources list via sourceManagementLogic.
+ schemaIncrementalFields: [
+ null as SchemaIncrementalFieldsResponse | null,
+ {
+ loadSchemaIncrementalFields: async (schemaId: string) => {
+ try {
+ return await api.externalDataSchemas.incremental_fields(schemaId)
+ } catch (e: any) {
+ lemonToast.error(e?.data?.message ?? e?.message ?? e)
+ throw e
+ }
+ },
+ },
+ ],
+ })),
reducers(() => ({
currentTab: [
DEFAULT_SCHEMA_SCENE_TAB as SchemaSceneTab,
@@ -58,17 +120,36 @@ export const schemaSceneLogic = kea<schemaSceneLogicType>([
_setCurrentSection: (_, { section }) => section,
},
],
+ isProjectTime: [
+ false as boolean,
+ {
+ setIsProjectTime: (_, { isProjectTime }) => isProjectTime,
+ },
+ ],
+ refreshingSchemas: [
+ false as boolean,
+ {
+ setRefreshingSchemas: (_, { refreshing }) => refreshing,
+ refreshSchemas: () => true,
+ },
+ ],
})),
selectors({
- schema: [
- (s) => [s.source, (_, props) => props.schemaId],
- (source, schemaId): ExternalDataSourceSchema | null => {
- return source?.schemas.find((item) => item.id === schemaId) ?? null
- },
+ schema: [(s) => [s.schemaData], (schemaData): ExternalDataSourceSchema | null => schemaData],
+ source: [
+ (s) => [s.schemaData],
+ // The summary carries exactly the fields the page reads (source_type, user_access_level,
+ // supports_column_selection); cast to the full type so existing prop signatures are unchanged.
+ (schemaData): ExternalDataSource | null =>
+ (schemaData?.source ?? null) as unknown as ExternalDataSource | null,
+ ],
+ supportsColumnSelection: [
+ (s) => [s.schemaData],
+ (schemaData): boolean => !!schemaData?.source?.supports_column_selection,
],
breadcrumbs: [
- (s) => [s.source, s.schema, (_, props) => props.sourceId],
- (source, schema, sourceId): Breadcrumb[] => {
+ (s) => [s.schemaData, (_, props) => props.sourceId],
+ (schemaData, sourceId): Breadcrumb[] => {
return [
{
key: Scene.Sources,
@@ -78,13 +159,13 @@ export const schemaSceneLogic = kea<schemaSceneLogicType>([
},
{
key: Scene.DataWarehouseSource,
- name: source?.source_type || 'Source',
+ name: schemaData?.source?.source_type || 'Source',
path: urls.dataWarehouseSource(sourceId, 'schemas'),
iconType: 'data_pipeline',
},
{
key: Scene.DataWarehouseSourceSchema,
- name: schema?.label ?? schema?.name ?? 'Schema',
+ name: schemaData?.label ?? schemaData?.name ?? 'Schema',
iconType: 'data_pipeline',
},
]
@@ -106,6 +187,109 @@ export const schemaSceneLogic = kea<schemaSceneLogicType>([
},
],
}),
+ listeners(({ actions, values, props }) => ({
+ updateSchema: async ({ schema }) => {
+ const current = values.schemaData
+ if (current) {
+ actions.loadSchemaSuccess({ ...current, ...schema })
+ }
+ try {
+ await api.externalDataSchemas.update(schema.id, buildSchemaUpdatePayload(schema))
+ } catch (e: any) {
+ lemonToast.error(e?.message || "Can't update schema at this time")
+ } finally {
+ actions.loadSchema()
+ }
+ },
+ reloadSchema: async ({ schema }) => {
+ const current = values.schemaData
+ if (current) {
+ actions.loadSchemaSuccess({ ...current, status: ExternalDataSchemaStatus.Running })
+ }
+ try {
+ await api.externalDataSchemas.reload(schema.id)
+ posthog.capture('schema reloaded', { sourceType: values.source?.source_type })
+ } catch (e: any) {
+ lemonToast.error(e?.message || 'Cant reload schema at this time')
+ } finally {
+ actions.loadSchema()
+ }
+ },
+ resyncSchema: async ({ schema }) => {
+ const current = values.schemaData
+ if (current) {
+ actions.loadSchemaSuccess({ ...current, status: ExternalDataSchemaStatus.Running })
+ }
+ try {
+ await api.externalDataSchemas.resync(schema.id)
+ posthog.capture('schema resynced', { sourceType: values.source?.source_type })
+ } catch (e: any) {
+ lemonToast.error(e?.message || 'Cant refresh schema at this time')
+ } finally {
+ actions.loadSchema()
+ }
+ },
+ cancelSchema: async ({ schema }) => {
+ try {
+ await api.externalDataSchemas.cancel(schema.id)
+ posthog.capture('schema sync cancelled', { sourceType: values.source?.source_type })
+ lemonToast.success('Sync cancelled')
+ } catch (e: any) {
+ lemonToast.error(e?.message || "Can't cancel sync at this time")
+ } finally {
+ actions.loadSchema()
+ }
+ },
+ deleteTable: async ({ schema }) => {
+ try {
+ await api.externalDataSchemas.delete_data(schema.id)
+ posthog.capture('schema data deleted', { sourceType: values.source?.source_type })
+ lemonToast.success(`Data for ${schema.label ?? schema.name} has been deleted`)
+ } catch (e: any) {
+ lemonToast.error(e?.message || "Can't delete data at this time")
+ } finally {
+ actions.loadSchema()
+ }
+ },
+ refreshSchemas: async () => {
+ try {
+ const {
+ added = 0,
+ deleted = 0,
+ total_tables_seen = 0,
+ } = await api.externalDataSources.refreshSchemas(cleanSourceId(props.sourceId))
+ actions.loadSchema()
+ posthog.capture('schemas refreshed', {
+ sourceType: values.source?.source_type,
+ added,
+ deleted,
+ total_tables_seen,
+ })
+ if (total_tables_seen === 0) {
+ const deletedSuffix =
+ deleted > 0
+ ? ` ${deleted} previously tracked table(s) were removed from the tracking list.`
+ : ''
+ lemonToast.warning(
+ `No tables found. Check the source credentials, permissions, and configuration.${deletedSuffix}`
+ )
+ return
+ }
+ if (added === 0 && deleted === 0) {
+ lemonToast.success(`No schema changes — all ${total_tables_seen} table(s) already tracked.`)
+ return
+ }
+ const counts = [added > 0 ? `${added} added` : null, deleted > 0 ? `${deleted} deleted` : null]
+ .filter(Boolean)
+ .join(' / ')
+ lemonToast.success(`Schemas refreshed: ${counts}`)
+ } catch (e: any) {
+ lemonToast.error(e?.message || "Can't refresh schemas at this time")
+ } finally {
+ actions.setRefreshingSchemas(false)
+ }
+ },
+ })),
actionToUrl(({ props, values }) => ({
setCurrentTab: () => {
return urls.dataWarehouseSourceSchema(
@@ -129,8 +313,8 @@ export const schemaSceneLogic = kea<schemaSceneLogicType>([
const applyTabAndSection = (tab: SchemaSceneTab, section?: SchemaConfigurationSection): void => {
if (!initialNavigation) {
- // User navigated back to this scene — refresh data since polling is paused.
- actions.loadSource()
+ // User navigated back to this scene — refetch the schema since the page does not poll.
+ actions.loadSchema()
}
initialNavigation = false
@@ -163,9 +347,6 @@ export const schemaSceneLogic = kea<schemaSceneLogicType>([
}
}),
afterMount(({ actions }) => {
- actions.pausePolling()
- }),
- beforeUnmount(({ actions }) => {
- actions.resumePolling()
+ actions.loadSchema()
}),
])
diff --git a/products/logs/frontend/scenes/LogsAlertNotificationDetailScene/LogsAlertNotificationDetailScene.tsx b/products/logs/frontend/scenes/LogsAlertNotificationDetailScene/LogsAlertNotificationDetailScene.tsx
index c376f244ebbb..0d3d69fb66ec 100644
--- a/products/logs/frontend/scenes/LogsAlertNotificationDetailScene/LogsAlertNotificationDetailScene.tsx
+++ b/products/logs/frontend/scenes/LogsAlertNotificationDetailScene/LogsAlertNotificationDetailScene.tsx
@@ -57,7 +57,7 @@ export function LogsAlertNotificationDetailScene(): JSX.Element {
if (firstSlackIntegration) {
loadAllSlackChannels()
}
- }, [firstSlackIntegration?.id, loadAllSlackChannels])
+ }, [firstSlackIntegration?.id, loadAllSlackChannels, firstSlackIntegration])
const loading = alertLoading || hogFunctionsLoading
const displayLabel = destinationGroup ? resolveGroupLabel(destinationGroup, slackChannels) : 'Destination'
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 9c4d7de23fca..1f52a187ab43 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -16480,6 +16480,18 @@ export namespace Schemas {
is_nullable?: boolean;
};
+ /**
+ * Lightweight parent-source summary (id, source_type, column-selection support, the requesting user's access level). Only populated on the single-schema retrieve endpoint — `null` elsewhere — so read-only views can render without fetching the full source and all its schemas.
+ * @nullable
+ */
+ export type ExternalDataSchemaSource = {
+ readonly id?: string;
+ readonly source_type?: string;
+ readonly supports_column_selection?: boolean;
+ /** @nullable */
+ readonly user_access_level?: string | null;
+ } | null;
+
/**
* * `full_refresh` - full_refresh
* `incremental` - incremental
@@ -16627,6 +16639,11 @@ export namespace Schemas {
enabled_columns?: string[] | null;
/** Source-side column metadata (name, data type, nullable) discovered for this schema. Empty until the source has been refreshed via `refresh_schemas`. */
readonly available_columns: readonly ExternalDataSchemaAvailableColumnsItem[];
+ /**
+ * Lightweight parent-source summary (id, source_type, column-selection support, the requesting user's access level). Only populated on the single-schema retrieve endpoint — `null` elsewhere — so read-only views can render without fetching the full source and all its schemas.
+ * @nullable
+ */
+ readonly source: ExternalDataSchemaSource;
}
export interface ExternalDataSourceBulkUpdateSchema {
@@ -28176,6 +28193,18 @@ export namespace Schemas {
is_nullable?: boolean;
};
+ /**
+ * Lightweight parent-source summary (id, source_type, column-selection support, the requesting user's access level). Only populated on the single-schema retrieve endpoint — `null` elsewhere — so read-only views can render without fetching the full source and all its schemas.
+ * @nullable
+ */
+ export type PatchedExternalDataSchemaSource = {
+ readonly id?: string;
+ readonly source_type?: string;
+ readonly supports_column_selection?: boolean;
+ /** @nullable */
+ readonly user_access_level?: string | null;
+ } | null;
+
export interface PatchedExternalDataSchema {
readonly id?: string;
readonly name?: string;
@@ -28255,6 +28284,11 @@ export namespace Schemas {
enabled_columns?: string[] | null;
/** Source-side column metadata (name, data type, nullable) discovered for this schema. Empty until the source has been refreshed via `refresh_schemas`. */
readonly available_columns?: readonly PatchedExternalDataSchemaAvailableColumnsItem[];
+ /**
+ * Lightweight parent-source summary (id, source_type, column-selection support, the requesting user's access level). Only populated on the single-schema retrieve endpoint — `null` elsewhere — so read-only views can render without fetching the full source and all its schemas.
+ * @nullable
+ */
+ readonly source?: PatchedExternalDataSchemaSource;
}
export interface PatchedExternalDataSourceBulkUpdateSchemas {