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): namespace grouping in Schemas tab + generic multi-schema utils (#63108)

Daniel RCb57cb9a7cafe
diff --git a/.agents/skills/implementing-warehouse-sources/SKILL.md b/.agents/skills/implementing-warehouse-sources/SKILL.md
index 4d67a82acb97..8e4709aa8696 100644
--- a/.agents/skills/implementing-warehouse-sources/SKILL.md
+++ b/.agents/skills/implementing-warehouse-sources/SKILL.md
@@ -182,6 +182,26 @@ Save state **after** yielding each batch, not before — so if we crash we re-yi
- In `source_for_pipeline`, call `self.get_webhook_source_manager(inputs)` and pass its iterator alongside the pull iterator so a single sync pulls historical + webhook-delivered rows.
- Populate `SourceSchema.supports_webhooks=True` only for endpoints where webhooks are actually viable (usually incremental/append-only ones).
+## Multi-schema SQL database sources
+
+SQL DB sources (Postgres, MSSQL, Snowflake, Redshift today) can import tables from **every namespace (schema) in one connection**: a blank namespace field discovers tables across all non-system namespaces, the wizard groups them by namespace, and sync writes one warehouse table per `namespace.table`. Reference implementation: `postgres/postgres.py` + `PostgresImplementation`; the shared seam lives in `common/sql/`.
+
+The capability marker is the source's `schema` field being **optional** (`required=False`) in `get_source_config` — `is_multi_schema_capable_sql_source()` (`products/data_warehouse/backend/sql_warehouse_migration.py`) keys off it, so flipping the field optional is what turns on the viewset migration behavior. Treat `None` / `""` / whitespace as "all namespaces" (`normalize_namespace` in `common/sql/location.py`) and never emit `WHERE table_schema = ''`.
+
+Checklist for bringing a SQL source to multi-schema parity:
+
+1. **Namespace field optional** — `required=False` on the `schema` field, rerun `pnpm run generate:source-configs`. Keep `database` required: the database/catalog stays fixed per connection.
+2. **Multi-namespace discovery** — in `get_columns`, `get_primary_keys`, index/row-count/foreign-key helpers: when the namespace is blank, drop the `WHERE table_schema = <ns>` predicate (excluding system namespaces like `information_schema`, `pg_catalog`, `sys`) and return **qualified display names** (`namespace.table`). Keep the single-namespace fast path when the field is set.
+3. **Implement `get_source_metadata`** — return `SourceMetadata(catalog_by_table, schema_by_table, table_name_by_table)` keyed by the qualified display name. `SQLSource.get_schemas` stamps it onto each `SourceSchema`, and `reconcile_schema_metadata` persists it into `ExternalDataSchema.sync_type_config["schema_metadata"]`.
+4. **Per-row routing in `build_pipeline`** — resolve `(schema, table_name, response_name)` with `resolve_source_location` (`common/sql/location.py`): per-row metadata → dotted-name self-heal → config namespace. Run SQL against the resolved schema + **unqualified** table; set `SourceResponse.name = response_name` (`dwh_storage_key or schema.name`, normalized) — never the bare table name, or the row's Delta path moves and orphans synced data.
+5. **Thread the resolved namespace through every streaming/stats helper** — table metadata, row stats, average row size, partition settings, chunk size, primary-key lookup all take `(schema, table)`. Missing one degrades silently (no partitioning / wrong stats).
+6. **Never feed a dotted display name to an identifier quoter** — `quote("a.b")` yields one wrong identifier. Split into `(schema, table)` first and use `quote_qualified` (`common/sql/identifiers.py`).
+7. **Naming layers are derived, never stored** — display name `analytics.users`; S3/Delta subdir `analytics_users` (normalized `response_name`); HogQL table `{prefix}_analytics_users`. The one stored exception is `dwh_storage_key`, which pins a migrated legacy row to its original Delta path.
+8. **Legacy migration is capability-driven, not source-type-gated** — when a user clears the namespace on an existing single-schema source, `sql_warehouse_migration.py` renames rows to qualified form and stamps `dwh_storage_key`, preserving synced data with no re-sync. Don't add `source_type == "..."` branches to the shared layer.
+9. **Tests** — two namespaces with the same table name stay distinct end to end; blank-namespace discovery excludes system namespaces; per-row routing hits the right namespace; legacy single-namespace sources keep working; migrated rows keep their legacy Delta path.
+
+Discovery cost: `validate_credentials` and `database_schema` run discovery with no name filter, so a blank namespace on a catalog with hundreds of schemas must not issue per-table queries per namespace — batch the listing queries or cap enumeration (see Snowflake's `SHOW PRIMARY KEYS` handling).
+
## Outbound HTTP must go through the tracked transport
Every HTTP call from `posthog/temporal/data_imports/sources/**` must go through `make_tracked_session()` (from
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 15bebdb2e788..9849f2bdc8fd 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -4890,6 +4890,10 @@ snapshots:
hash: v1.k794b7964.f63eec588ee7cf4aae7394caaf42ef000fe6ee9e4c92611f70a1de609de258ad.k8PvcZvu-w75qhYEx0dNXUbh5SoT-9pObguvhGzTRrg
scenes-app-data-warehouse-settings-schemas--default--light:
hash: v1.k794b7964.18626812d4b56d76787437924e1bc585c0d290b2d3d5a82acef06ad862687d31.T90_pbE7tLkoXwZml5VYlGjFqOKnGtCJsNfB3J76Xio
+ scenes-app-data-warehouse-settings-schemas--multi-schema--dark:
+ hash: v1.k794b7964.b255a3c1197cc622c87d3d303f9383b1383ef2757909ec2a8226eaafad21e3ba.jKeujVd-NHbkQU7l7h42HpO-bFuzisnnokpXKTJPg48
+ scenes-app-data-warehouse-settings-schemas--multi-schema--light:
+ hash: v1.k794b7964.58438be90ae39f31b85e0960ef8d68faa19d5012d36974f54144705370476233.WpCHH6hiYT3C4TYv4rV4-m_rcQwwF3VlU4G8M_WbVXg
scenes-app-error-project-unavailable--access-revoked--dark:
hash: v1.k794b7964.0574501d1036cac7563c61590dfb8b3d64192e239cbad126d754b9905b4f3ee1._MDyv82QyHN-dApRaQoppTvESKRRZP_p6MB5PKLrjeg
scenes-app-error-project-unavailable--access-revoked--light:
diff --git a/posthog/temporal/data_imports/sources/mssql/source.py b/posthog/temporal/data_imports/sources/mssql/source.py
index 60a5f9be8b47..9408cf13538b 100644
--- a/posthog/temporal/data_imports/sources/mssql/source.py
+++ b/posthog/temporal/data_imports/sources/mssql/source.py
@@ -126,7 +126,7 @@ class MSSQLSource(SQLSource[MSSQLSourceConfig], SSHTunnelMixin, ValidateDatabase
label="Schema",
type=SourceFieldInputConfigType.TEXT,
required=False,
- placeholder="dbo",
+ placeholder="Leave blank to import all schemas",
secret=False,
),
SourceFieldSSHTunnelConfig(name="ssh_tunnel", label="Use SSH tunnel?"),
diff --git a/posthog/temporal/data_imports/sources/snowflake/snowflake.py b/posthog/temporal/data_imports/sources/snowflake/snowflake.py
index b4316cd115a5..5f27dc69d8b2 100644
--- a/posthog/temporal/data_imports/sources/snowflake/snowflake.py
+++ b/posthog/temporal/data_imports/sources/snowflake/snowflake.py
@@ -378,25 +378,24 @@ class SnowflakeImplementation(
if not display_by_pair:
return result
- schemas = {schema for schema, _table in display_by_pair}
- table_names = {table for _schema, table in display_by_pair}
+ # Match exact (schema, table) pairs — independent IN clauses over schemas and table
+ # names would cross-product and also fetch every same-named table in other schemas.
+ pairs = sorted(display_by_pair)
try:
with conn.cursor() as cursor:
if cursor is None:
raise Exception("Can't create cursor to Snowflake")
- schema_placeholders = ",".join(["%s"] * len(schemas))
- table_placeholders = ",".join(["%s"] * len(table_names))
+ pair_predicate = " OR ".join(["(TABLE_SCHEMA = %s AND TABLE_NAME = %s)"] * len(pairs))
cursor.execute(
f"""
SELECT TABLE_SCHEMA, TABLE_NAME, CLUSTERING_KEY
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_CATALOG = %s
- AND TABLE_SCHEMA IN ({schema_placeholders})
- AND TABLE_NAME IN ({table_placeholders})
+ AND ({pair_predicate})
""",
- (config.database, *schemas, *table_names),
+ (config.database, *(value for pair in pairs for value in pair)),
)
for table_schema, table_name, clustering_key in cursor:
diff --git a/posthog/temporal/data_imports/sources/snowflake/source.py b/posthog/temporal/data_imports/sources/snowflake/source.py
index 1ceb41e11193..50f7c8b21485 100644
--- a/posthog/temporal/data_imports/sources/snowflake/source.py
+++ b/posthog/temporal/data_imports/sources/snowflake/source.py
@@ -163,7 +163,7 @@ class SnowflakeSource(SQLSource[SnowflakeSourceConfig]):
label="Schema (optional)",
type=SourceFieldInputConfigType.TEXT,
required=False,
- placeholder="leave blank to list tables from all schemas",
+ placeholder="Leave blank to import all schemas",
secret=False,
),
],
diff --git a/posthog/temporal/data_imports/sources/snowflake/tests/test_snowflake.py b/posthog/temporal/data_imports/sources/snowflake/tests/test_snowflake.py
index 33e67fff2561..b80b16c62193 100644
--- a/posthog/temporal/data_imports/sources/snowflake/tests/test_snowflake.py
+++ b/posthog/temporal/data_imports/sources/snowflake/tests/test_snowflake.py
@@ -425,6 +425,8 @@ class TestGetLeadingIndexColumns:
assert out is not None
assert out["analytics.users"] == {"CREATED_AT"}
assert out["sales.users"] == {"SIGNED_UP"}
+ # The query matches exact (schema, table) pairs, not a schemas × table-names cross-product.
+ assert cursor.execute.call_args.args[1] == ("DB", "analytics", "users", "sales", "users")
class TestGetSourceMetadata:
diff --git a/products/data_warehouse/backend/sql_warehouse_migration.py b/products/data_warehouse/backend/sql_warehouse_migration.py
index 969dfa9f5d4a..e91e8962a9d2 100644
--- a/products/data_warehouse/backend/sql_warehouse_migration.py
+++ b/products/data_warehouse/backend/sql_warehouse_migration.py
@@ -33,8 +33,8 @@ def _source_has_optional_schema_field(source: Any) -> bool:
def is_multi_schema_capable_sql_source(source_type: ExternalDataSourceType | str) -> bool:
"""True when the registered source for `source_type` has an optional (blank-able) `schema` field.
- The optional field is the opt-in marker (Postgres today). Resolved via `get_all_sources`, not the
- test-mockable `get_source`, so the gate stays config-driven.
+ The optional field is the opt-in marker (Postgres, MSSQL, Snowflake, Redshift today). Resolved via
+ `get_all_sources`, not the test-mockable `get_source`, so the gate stays config-driven.
"""
try:
resolved_type = ExternalDataSourceType(source_type)
diff --git a/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic.tsx b/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic.tsx
index ef406219cf0b..88ddb2c25375 100644
--- a/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic.tsx
+++ b/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic.tsx
@@ -39,10 +39,10 @@ import {
} from '~/types'
import {
- getDefaultExpandedDirectQuerySchemaKeys,
- groupDirectQueryTablesBySchema,
- splitDirectQueryTableName,
-} from '../../shared/components/forms/directQuerySchemaUtils'
+ getDefaultExpandedSchemaKeys,
+ groupTablesBySchema,
+ splitQualifiedTableName,
+} from '../../shared/components/forms/schemaGroupingUtils'
import type { WebhookCreateResult } from '../../shared/components/forms/WebhookSetupForm'
import { sourceManagementLogic } from '../../shared/logics/sourceManagementLogic'
import { selfManagedSourceLogic } from './selfManagedSourceLogic'
@@ -271,7 +271,7 @@ const resolveIncrementalField = (fields: IncrementalField[]): IncrementalField |
return undefined
}
-function syncExpandedDirectQuerySchemaKeys(
+function syncExpandedSchemaGroupKeys(
actions: sourceWizardLogicType['actions'],
values: sourceWizardLogicType['values']
): void {
@@ -279,12 +279,12 @@ function syncExpandedDirectQuerySchemaKeys(
return
}
- const fingerprint = values.groupedDirectQuerySchemaKeys.join('|')
- if (values.groupedDirectQuerySchemaKeysFingerprint === fingerprint) {
+ const fingerprint = values.schemaGroupKeys.join('|')
+ if (values.schemaGroupKeysFingerprint === fingerprint) {
return
}
- actions.syncExpandedDirectQuerySchemaKeys(values.groupedDirectQuerySchemaKeys, fingerprint)
+ actions.syncExpandedSchemaGroupKeys(values.schemaGroupKeys, fingerprint)
}
export interface SourceWizardLogicProps {
@@ -355,10 +355,10 @@ export const sourceWizardLogic = kea<sourceWizardLogicType>([
openSyncMethodModal: (schema: ExternalDataSourceSyncSchema) => ({ schema }),
cancelSyncMethodModal: true,
toggleAllTables: (selectAll: boolean, tableNames?: string[]) => ({ selectAll, tableNames }),
- toggleDirectQuerySchemaGroup: (schemaName: string, shouldSync: boolean) => ({ schemaName, shouldSync }),
+ toggleSchemaGroup: (schemaName: string, shouldSync: boolean) => ({ schemaName, shouldSync }),
setSchemaNameFilter: (schemaNameFilter: string) => ({ schemaNameFilter }),
- setExpandedDirectQuerySchemaKeys: (expandedSchemaKeys: string[]) => ({ expandedSchemaKeys }),
- syncExpandedDirectQuerySchemaKeys: (groupedSchemaKeys: string[], fingerprint: string) => ({
+ setExpandedSchemaGroupKeys: (expandedSchemaKeys: string[]) => ({ expandedSchemaKeys }),
+ syncExpandedSchemaGroupKeys: (groupedSchemaKeys: string[], fingerprint: string) => ({
groupedSchemaKeys,
fingerprint,
}),
@@ -489,11 +489,11 @@ export const sourceWizardLogic = kea<sourceWizardLogicType>([
},
},
],
- expandedDirectQuerySchemaKeys: [
+ expandedSchemaGroupKeys: [
[] as string[],
{
- setExpandedDirectQuerySchemaKeys: (_, { expandedSchemaKeys }) => expandedSchemaKeys,
- syncExpandedDirectQuerySchemaKeys: (state, { groupedSchemaKeys }) => {
+ setExpandedSchemaGroupKeys: (_, { expandedSchemaKeys }) => expandedSchemaKeys,
+ syncExpandedSchemaGroupKeys: (state, { groupedSchemaKeys }) => {
const nextKeys = state.filter((key) => groupedSchemaKeys.includes(key))
return nextKeys.length > 0 ? nextKeys : groupedSchemaKeys
},
@@ -501,10 +501,10 @@ export const sourceWizardLogic = kea<sourceWizardLogicType>([
clearSource: () => [],
},
],
- groupedDirectQuerySchemaKeysFingerprint: [
+ schemaGroupKeysFingerprint: [
'',
{
- syncExpandedDirectQuerySchemaKeys: (_, { fingerprint }) => fingerprint,
+ syncExpandedSchemaGroupKeys: (_, { fingerprint }) => fingerprint,
onClear: () => '',
clearSource: () => '',
},
@@ -914,19 +914,18 @@ export const sourceWizardLogic = kea<sourceWizardLogicType>([
return enabledCount === totalCount ? true : enabledCount > 0 ? 'indeterminate' : false
},
],
- directQueryDefaultSchema: [
+ configuredSchemaName: [
(s) => [s.source],
(source): string | null => (typeof source.payload.schema === 'string' ? source.payload.schema : null),
],
- groupedDirectQueryDatabaseSchema: [
- (s) => [s.filteredDatabaseSchema, s.directQueryDefaultSchema],
- (filteredDatabaseSchema, directQueryDefaultSchema) =>
- groupDirectQueryTablesBySchema(filteredDatabaseSchema, directQueryDefaultSchema),
+ groupedDatabaseSchema: [
+ (s) => [s.filteredDatabaseSchema, s.configuredSchemaName],
+ (filteredDatabaseSchema, configuredSchemaName) =>
+ groupTablesBySchema(filteredDatabaseSchema, (schema) => schema.table, configuredSchemaName),
],
- groupedDirectQuerySchemaKeys: [
- (s) => [s.groupedDirectQueryDatabaseSchema],
- (groupedDirectQueryDatabaseSchema) =>
- getDefaultExpandedDirectQuerySchemaKeys(groupedDirectQueryDatabaseSchema),
+ schemaGroupKeys: [
+ (s) => [s.groupedDatabaseSchema],
+ (groupedDatabaseSchema) => getDefaultExpandedSchemaKeys(groupedDatabaseSchema),
],
modalTitle: [
(s) => [s.currentStep, s.isDirectQueryMode],
@@ -989,7 +988,7 @@ export const sourceWizardLogic = kea<sourceWizardLogicType>([
actions.touchSourceConnectionDetailsField('prefix')
},
setInitialConnector: () => {
- syncExpandedDirectQuerySchemaKeys(actions, values)
+ syncExpandedSchemaGroupKeys(actions, values)
actions.resetSourceForm()
},
resetSourceForm: ({ accessMethod }) => {
@@ -1004,28 +1003,27 @@ export const sourceWizardLogic = kea<sourceWizardLogicType>([
)
},
setDatabaseSchemas: () => {
- syncExpandedDirectQuerySchemaKeys(actions, values)
+ syncExpandedSchemaGroupKeys(actions, values)
},
updateSource: () => {
- syncExpandedDirectQuerySchemaKeys(actions, values)
+ syncExpandedSchemaGroupKeys(actions, values)
},
- toggleDirectQuerySchemaGroup: ({ schemaName, shouldSync }) => {
+ toggleSchemaGroup: ({ schemaName, shouldSync }) => {
actions.setDatabaseSchemas(
values.databaseSchema.map((schema) => ({
...schema,
should_sync:
- splitDirectQueryTableName(schema.table, values.directQueryDefaultSchema).schemaName ===
- schemaName
+ splitQualifiedTableName(schema.table, values.configuredSchemaName).schemaName === schemaName
? schema.permission_error
? false
: shouldSync
: schema.should_sync,
}))
)
- actions.setExpandedDirectQuerySchemaKeys(
+ actions.setExpandedSchemaGroupKeys(
shouldSync
- ? Array.from(new Set([...values.expandedDirectQuerySchemaKeys, schemaName]))
- : values.expandedDirectQuerySchemaKeys.filter((key) => key !== schemaName)
+ ? Array.from(new Set([...values.expandedSchemaGroupKeys, schemaName]))
+ : values.expandedSchemaGroupKeys.filter((key) => key !== schemaName)
)
},
saveFormStateBeforeRedirect: () => {
@@ -1463,7 +1461,7 @@ export const sourceWizardLogic = kea<sourceWizardLogicType>([
}
},
selectConnector: ({ connector, accessMethod }) => {
- syncExpandedDirectQuerySchemaKeys(actions, values)
+ syncExpandedSchemaGroupKeys(actions, values)
actions.resetSourceForm(accessMethod)
actions.addProductIntent({
@@ -1492,7 +1490,7 @@ export const sourceWizardLogic = kea<sourceWizardLogicType>([
},
toggleAllTables: () => {
// databaseSchema reducer already applied the toggle; re-emit so the
- // setDatabaseSchemas listener (syncExpandedDirectQuerySchemaKeys) fires.
+ // setDatabaseSchemas listener (syncExpandedSchemaGroupKeys) fires.
actions.setDatabaseSchemas(values.databaseSchema)
},
})),
diff --git a/products/data_warehouse/frontend/scenes/NewSourceScene/tests/sourceWizardLogic.test.ts b/products/data_warehouse/frontend/scenes/NewSourceScene/tests/sourceWizardLogic.test.ts
index caa5094e559f..b3ea444475d1 100644
--- a/products/data_warehouse/frontend/scenes/NewSourceScene/tests/sourceWizardLogic.test.ts
+++ b/products/data_warehouse/frontend/scenes/NewSourceScene/tests/sourceWizardLogic.test.ts
@@ -728,7 +728,7 @@ describe('sourceWizardLogic', () => {
}
})
- it('toggleDirectQuerySchemaGroup skips permission_error rows in a group', () => {
+ it('toggleSchemaGroup skips permission_error rows in a group', () => {
const { logic, unmount } = mountWithSchemas([
buildSchema({ table: 'public.customers' }),
buildSchema({ table: 'public.charges', permission_error: 'Missing scope' }),
@@ -736,7 +736,7 @@ describe('sourceWizardLogic', () => {
])
try {
- logic.actions.toggleDirectQuerySchemaGroup('public', true)
+ logic.actions.toggleSchemaGroup('public', true)
const byTable = Object.fromEntries(logic.values.databaseSchema.map((s) => [s.table, s]))
expect(byTable['public.customers'].should_sync).toBe(true)
expect(byTable['public.invoices'].should_sync).toBe(true)
diff --git a/products/data_warehouse/frontend/scenes/SourceScene/tabs/SchemasTab.stories.tsx b/products/data_warehouse/frontend/scenes/SourceScene/tabs/SchemasTab.stories.tsx
index 347b134a735d..0e8ea42319c7 100644
--- a/products/data_warehouse/frontend/scenes/SourceScene/tabs/SchemasTab.stories.tsx
+++ b/products/data_warehouse/frontend/scenes/SourceScene/tabs/SchemasTab.stories.tsx
@@ -40,3 +40,31 @@ export default meta
export const Default: Story = {
args: {},
}
+
+// Multi-schema SQL source: qualified `namespace.table` schema names spanning two
+// namespaces, including the same table name in both, rendered as collapsible groups.
+const MULTI_SCHEMA_TABLE_NAMES = ['dbo.users', 'dbo.orders', 'dbo.invoices', 'sales.users', 'sales.leads']
+
+const multiSchemaSourceMock = {
+ ...externalDataSourceResponseMock,
+ source_type: 'MSSQL',
+ prefix: 'mssql_',
+ job_inputs: { schema: '' },
+ schemas: externalDataSourceResponseMock.schemas
+ .slice(0, MULTI_SCHEMA_TABLE_NAMES.length)
+ .map((schema, index) => ({ ...schema, name: MULTI_SCHEMA_TABLE_NAMES[index] })),
+}
+
+export const MultiSchema: Story = {
+ render: (props) => {
+ useStorybookMocks({
+ get: {
+ '/api/environments/:team_id/external_data_sources/:id': () => {
+ return [200, multiSchemaSourceMock]
+ },
+ },
+ })
+
+ return <SchemasTab {...props} />
+ },
+}
diff --git a/products/data_warehouse/frontend/scenes/SourceScene/tabs/SchemasTab.tsx b/products/data_warehouse/frontend/scenes/SourceScene/tabs/SchemasTab.tsx
index 9c9732f311ba..7b89a1e6615a 100644
--- a/products/data_warehouse/frontend/scenes/SourceScene/tabs/SchemasTab.tsx
+++ b/products/data_warehouse/frontend/scenes/SourceScene/tabs/SchemasTab.tsx
@@ -5,6 +5,7 @@ import { useEffect, useState } from 'react'
import { IconInfo } from '@posthog/icons'
import {
LemonButton,
+ LemonCollapse,
LemonDialog,
LemonInput,
LemonSelect,
@@ -35,6 +36,7 @@ import {
ExternalDataSourceSchema,
} from '~/types'
+import { splitQualifiedTableName } from 'products/data_warehouse/frontend/shared/components/forms/schemaGroupingUtils'
import { DATA_WAREHOUSE_APP_SOURCE } from 'products/data_warehouse/frontend/shared/components/metrics/DataWarehouseMetrics'
import {
SourceEditorAction,
@@ -88,6 +90,7 @@ function ManagedSchemasTab({ id }: { id: string }): JSX.Element {
source,
sourceLoading,
filteredSchemas,
+ groupedFilteredSchemas,
showEnabledSchemasOnly,
schemaNameFilter,
statusFilter,
@@ -228,19 +231,57 @@ function ManagedSchemasTab({ id }: { id: string }): JSX.Element {
</SourceEditorAction>
</div>
</div>
- <ManagedSchemaTable
- schemas={filteredSchemas}
- isLoading={sourceLoading}
- source={source}
- sourceId={id}
- prefixedSourceId={prefixedSourceId}
- updateSchema={updateSchema}
- reloadSchema={reloadSchema}
- resyncSchema={resyncSchema}
- cancelSchema={cancelSchema}
- deleteTable={deleteTable}
- showMetrics={showMetrics}
- />
+ {groupedFilteredSchemas.length > 1 ? (
+ <div className="border rounded bg-bg-light">
+ <LemonCollapse
+ multiple
+ embedded
+ defaultActiveKeys={groupedFilteredSchemas.map((group) => group.schemaName)}
+ panels={groupedFilteredSchemas.map(({ schemaName, tables }) => ({
+ key: schemaName,
+ header: (
+ <div className="flex items-center justify-between gap-3 w-full">
+ <span className="font-semibold truncate">{schemaName}</span>
+ <span className="text-xs text-muted-alt whitespace-nowrap">
+ {tables.filter((schema) => schema.should_sync).length} of {tables.length}{' '}
+ enabled
+ </span>
+ </div>
+ ),
+ content: (
+ <ManagedSchemaTable
+ schemas={tables}
+ inSchemaGroup
+ isLoading={sourceLoading}
+ source={source}
+ sourceId={id}
+ prefixedSourceId={prefixedSourceId}
+ updateSchema={updateSchema}
+ reloadSchema={reloadSchema}
+ resyncSchema={resyncSchema}
+ cancelSchema={cancelSchema}
+ deleteTable={deleteTable}
+ showMetrics={showMetrics}
+ />
+ ),
+ }))}
+ />
+ </div>
+ ) : (
+ <ManagedSchemaTable
+ schemas={filteredSchemas}
+ isLoading={sourceLoading}
+ source={source}
+ sourceId={id}
+ prefixedSourceId={prefixedSourceId}
+ updateSchema={updateSchema}
+ reloadSchema={reloadSchema}
+ resyncSchema={resyncSchema}
+ cancelSchema={cancelSchema}
+ deleteTable={deleteTable}
+ showMetrics={showMetrics}
+ />
+ )}
{source?.source_type &&
REVENUE_ENABLED_SOURCES.includes(source.source_type) &&
featureFlags[FEATURE_FLAGS.REVENUE_ANALYTICS] && (
@@ -281,6 +322,8 @@ interface ManagedSchemaTableProps {
cancelSchema: (schema: ExternalDataSourceSchema) => void
deleteTable: (schema: ExternalDataSourceSchema) => void
showMetrics: boolean
+ /** Rendered inside a namespace group — the group header already shows the namespace, so strip it from row names. */
+ inSchemaGroup?: boolean
}
function ManagedSchemaTable({
@@ -295,6 +338,7 @@ function ManagedSchemaTable({
cancelSchema,
deleteTable,
showMetrics,
+ inSchemaGroup = false,
}: ManagedSchemaTableProps): JSX.Element {
const { schemaReloadingById } = useValues(sourceManagementLogic)
const { inProgressRowsBySchema } = useValues(sourceSettingsLogic)
@@ -329,7 +373,8 @@ function ManagedSchemaTable({
key: 'name',
sorter: (a, b) => (a.label ?? a.name).localeCompare(b.label ?? b.name),
render: function RenderName(_, schema) {
- const name = schema.label ?? schema.name
+ const fullName = schema.label ?? schema.name
+ const name = inSchemaGroup ? splitQualifiedTableName(fullName).tableName : fullName
return (
<LemonTableLink
to={urls.dataWarehouseSourceSchema(prefixedSourceId, schema.id)}
diff --git a/products/data_warehouse/frontend/scenes/SourceScene/tabs/sourceSettingsLogic.ts b/products/data_warehouse/frontend/scenes/SourceScene/tabs/sourceSettingsLogic.ts
index b4f548c66404..4f03f879cc82 100644
--- a/products/data_warehouse/frontend/scenes/SourceScene/tabs/sourceSettingsLogic.ts
+++ b/products/data_warehouse/frontend/scenes/SourceScene/tabs/sourceSettingsLogic.ts
@@ -20,6 +20,7 @@ import {
ExternalDataSourceSchema,
} from '~/types'
+import { groupTablesBySchema } from 'products/data_warehouse/frontend/shared/components/forms/schemaGroupingUtils'
import { SYNC_FREQUENCY_ORDER, clampSyncFrequency } from 'products/data_warehouse/frontend/utils'
import { sourcesDataLogic } from '../../../shared/logics/sourcesDataLogic'
@@ -560,6 +561,18 @@ export const sourceSettingsLogic = kea<sourceSettingsLogicType>([
return schemas
},
],
+ // Multi-schema SQL sources have qualified schema names (`namespace.table`); group them by
+ // namespace so the Schemas tab matches the wizard's grouping. Single-namespace sources
+ // produce one group and render as a flat table.
+ groupedFilteredSchemas: [
+ (s) => [s.filteredSchemas, s.source],
+ (filteredSchemas, source): { schemaName: string; tables: ExternalDataSourceSchema[] }[] =>
+ groupTablesBySchema(
+ filteredSchemas,
+ (schema) => schema.name,
+ typeof source?.job_inputs?.schema === 'string' ? source.job_inputs.schema : null
+ ),
+ ],
// Distinct values present across the source's schemas, for populating the filter dropdowns.
schemaFilterOptions: [
(s) => [s.source],
diff --git a/products/data_warehouse/frontend/shared/components/forms/SchemaForm.test.ts b/products/data_warehouse/frontend/shared/components/forms/SchemaForm.test.ts
index cf8960e3b9d2..31b0e8cc2551 100644
--- a/products/data_warehouse/frontend/shared/components/forms/SchemaForm.test.ts
+++ b/products/data_warehouse/frontend/shared/components/forms/SchemaForm.test.ts
@@ -1,11 +1,7 @@
import type { ExternalDataSourceSyncSchema } from '~/types'
-import {
- getDefaultExpandedDirectQuerySchemaKeys,
- groupDirectQueryTablesBySchema,
- splitDirectQueryTableName,
-} from './directQuerySchemaUtils'
import { getDirectQuerySelectionDescription } from './SchemaForm'
+import { getDefaultExpandedSchemaKeys, groupTablesBySchema, splitQualifiedTableName } from './schemaGroupingUtils'
const makeSchema = (table: string): ExternalDataSourceSyncSchema => ({
table,
@@ -38,26 +34,25 @@ describe('SchemaForm', () => {
})
it('splits fully qualified table names into schema and table labels', () => {
- expect(splitDirectQueryTableName('public.events')).toEqual({
+ expect(splitQualifiedTableName('public.events')).toEqual({
schemaName: 'public',
tableName: 'events',
})
})
it('uses the selected schema as a fallback for unqualified table names', () => {
- expect(splitDirectQueryTableName('events', 'public')).toEqual({
+ expect(splitQualifiedTableName('events', 'public')).toEqual({
schemaName: 'public',
tableName: 'events',
})
})
- it('groups direct query tables by schema', () => {
+ it('groups tables by schema', () => {
expect(
- groupDirectQueryTablesBySchema([
- makeSchema('analytics.pageviews'),
- makeSchema('public.events'),
- makeSchema('analytics.sessions'),
- ])
+ groupTablesBySchema(
+ [makeSchema('analytics.pageviews'), makeSchema('public.events'), makeSchema('analytics.sessions')],
+ (schema) => schema.table
+ )
).toEqual([
{
schemaName: 'analytics',
@@ -70,14 +65,13 @@ describe('SchemaForm', () => {
])
})
- it('expands all direct query schema groups by default', () => {
+ it('expands all schema groups by default', () => {
expect(
- getDefaultExpandedDirectQuerySchemaKeys(
- groupDirectQueryTablesBySchema([
- makeSchema('analytics.pageviews'),
- makeSchema('public.events'),
- makeSchema('analytics.sessions'),
- ])
+ getDefaultExpandedSchemaKeys(
+ groupTablesBySchema(
+ [makeSchema('analytics.pageviews'), makeSchema('public.events'), makeSchema('analytics.sessions')],
+ (schema) => schema.table
+ )
)
).toEqual(['analytics', 'public'])
})
diff --git a/products/data_warehouse/frontend/shared/components/forms/SchemaForm.tsx b/products/data_warehouse/frontend/shared/components/forms/SchemaForm.tsx
index 281a13d070b1..61172e881ab5 100644
--- a/products/data_warehouse/frontend/shared/components/forms/SchemaForm.tsx
+++ b/products/data_warehouse/frontend/shared/components/forms/SchemaForm.tsx
@@ -22,7 +22,7 @@ import { SyncTypeLabelMap } from 'products/data_warehouse/frontend/utils'
import { sourceWizardLogic } from '../../../scenes/NewSourceScene/sourceWizardLogic'
import { ColumnSelectionPicker } from '../../../scenes/SourceScene/tabs/ColumnSelectionModal'
-import { splitDirectQueryTableName } from './directQuerySchemaUtils'
+import { splitQualifiedTableName } from './schemaGroupingUtils'
import { SyncMethodForm } from './SyncMethodForm'
export function getDirectQuerySelectionDescription(selectedSchema?: string | null): string {
@@ -55,8 +55,8 @@ export default function SchemaForm(): JSX.Element {
toggleSchemaShouldSync,
toggleAllTables,
openSyncMethodModal,
- toggleDirectQuerySchemaGroup,
- setExpandedDirectQuerySchemaKeys,
+ toggleSchemaGroup,
+ setExpandedSchemaGroupKeys,
setSchemaNameFilter,
setSchemaSyncedColumns,
} = useActions(sourceWizardLogic)
@@ -70,8 +70,8 @@ export default function SchemaForm(): JSX.Element {
tablesAllToggledOn,
source,
selectedConnector,
- groupedDirectQueryDatabaseSchema,
- expandedDirectQuerySchemaKeys,
+ groupedDatabaseSchema,
+ expandedSchemaGroupKeys,
} = useValues(sourceWizardLogic)
const onClickCheckbox = (schema: ExternalDataSourceSyncSchema, checked: boolean): void => {
@@ -386,20 +386,18 @@ export default function SchemaForm(): JSX.Element {
)}
<div className="flex-1 min-h-0 overflow-y-auto">
{isDirectQueryMode ? (
- groupedDirectQueryDatabaseSchema.length > 0 ? (
+ groupedDatabaseSchema.length > 0 ? (
<div className="border rounded bg-bg-light">
<LemonCollapse
multiple
embedded
activeKeys={
- groupedDirectQueryDatabaseSchema.length === 1
- ? groupedDirectQueryDatabaseSchema.map(
- (g: { schemaName: string }) => g.schemaName
- )
- : expandedDirectQuerySchemaKeys
+ groupedDatabaseSchema.length === 1
+ ? groupedDatabaseSchema.map((g: { schemaName: string }) => g.schemaName)
+ : expandedSchemaGroupKeys
}
- onChange={setExpandedDirectQuerySchemaKeys}
- panels={groupedDirectQueryDatabaseSchema.map(({ schemaName, tables }) => {
+ onChange={setExpandedSchemaGroupKeys}
+ panels={groupedDatabaseSchema.map(({ schemaName, tables }) => {
const selectedTablesCount = tables.filter((table) => table.should_sync).length
return {
@@ -411,7 +409,7 @@ export default function SchemaForm(): JSX.Element {
checked={getSchemaSelectionState(tables)}
stopPropagation
onChange={(checked) =>
- toggleDirectQuerySchemaGroup(schemaName, checked)
+ toggleSchemaGroup(schemaName, checked)
}
/>
<span className="font-semibold truncate">{schemaName}</span>
@@ -430,7 +428,7 @@ export default function SchemaForm(): JSX.Element {
const tooltip =
suggestedTablesMap[schema.table] ??
'This table is suggested to be enabled for this source'
- const { tableName } = splitDirectQueryTableName(
+ const { tableName } = splitQualifiedTableName(
schema.table,
source.payload.schema
)
@@ -528,14 +526,14 @@ export default function SchemaForm(): JSX.Element {
) : (
<div className="border rounded px-4 py-8 text-center text-muted-alt">No tables found</div>
)
- ) : groupedDirectQueryDatabaseSchema.length > 1 ? (
+ ) : groupedDatabaseSchema.length > 1 ? (
<div className="border rounded bg-bg-light">
<LemonCollapse
multiple
embedded
- activeKeys={expandedDirectQuerySchemaKeys}
- onChange={setExpandedDirectQuerySchemaKeys}
- panels={groupedDirectQueryDatabaseSchema.map(
+ activeKeys={expandedSchemaGroupKeys}
+ onChange={setExpandedSchemaGroupKeys}
+ panels={groupedDatabaseSchema.map(
({
schemaName,
tables,
@@ -550,9 +548,7 @@ export default function SchemaForm(): JSX.Element {
<LemonCheckbox
checked={getSchemaSelectionState(tables)}
stopPropagation
- onChange={(checked) =>
- toggleDirectQuerySchemaGroup(schemaName, checked)
- }
+ onChange={(checked) => toggleSchemaGroup(schemaName, checked)}
/>
<span className="font-semibold truncate">{schemaName}</span>
</div>
diff --git a/products/data_warehouse/frontend/shared/components/forms/directQuerySchemaUtils.ts b/products/data_warehouse/frontend/shared/components/forms/schemaGroupingUtils.ts
similarity index 60%
rename from products/data_warehouse/frontend/shared/components/forms/directQuerySchemaUtils.ts
rename to products/data_warehouse/frontend/shared/components/forms/schemaGroupingUtils.ts
index a61f82437292..d7f4ad0fbfb5 100644
--- a/products/data_warehouse/frontend/shared/components/forms/directQuerySchemaUtils.ts
+++ b/products/data_warehouse/frontend/shared/components/forms/schemaGroupingUtils.ts
@@ -1,8 +1,6 @@
import { groupBy } from 'lib/utils'
-import { ExternalDataSourceSyncSchema } from '~/types'
-
-export function splitDirectQueryTableName(
+export function splitQualifiedTableName(
table: string,
fallbackSchema?: string | null
): { schemaName: string; tableName: string } {
@@ -22,19 +20,18 @@ export function splitDirectQueryTableName(
}
}
-export function groupDirectQueryTablesBySchema(
- schemas: ExternalDataSourceSyncSchema[],
+export function groupTablesBySchema<T>(
+ schemas: T[],
+ getTableName: (item: T) => string,
fallbackSchema?: string | null
-): { schemaName: string; tables: ExternalDataSourceSyncSchema[] }[] {
+): { schemaName: string; tables: T[] }[] {
return Object.entries(
- groupBy(schemas, (schema) => splitDirectQueryTableName(schema.table, fallbackSchema).schemaName)
+ groupBy(schemas, (schema) => splitQualifiedTableName(getTableName(schema), fallbackSchema).schemaName)
)
.sort(([schemaA], [schemaB]) => schemaA.localeCompare(schemaB))
.map(([schemaName, tables]) => ({ schemaName, tables }))
}
-export function getDefaultExpandedDirectQuerySchemaKeys(
- groupedSchemas: { schemaName: string; tables: ExternalDataSourceSyncSchema[] }[]
-): string[] {
+export function getDefaultExpandedSchemaKeys<T>(groupedSchemas: { schemaName: string; tables: T[] }[]): string[] {
return groupedSchemas.map((group) => group.schemaName)
}