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(sql-editor): lazy load the database schema tree (#81881)

Marius Andra7ebcc8667c52
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 04fba2680942..872220f80ba6 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -494,6 +494,7 @@ export const FEATURE_FLAGS = {
SIGNUP_AA_TEST_4_WAY: 'signup-aa-test-4-way', // owner: @andehen #team-experiments multivariate=control,test-1,test-2,test-3
SLACK_DWH: 'slack-dwh', // owner: @MarconLP #team-warehouse-sources
SQL_EDITOR_BI_MODE: 'sql-editor-bi-mode', // owner: @mariusandra #team-data-tools
+ SQL_EDITOR_LAZY_SCHEMA: 'sql-editor-lazy-schema', // owner: @mariusandra #team-data-tools
SQL_EDITOR_VIM_MODE: 'sql-editor-vim-mode', // owner: @arthurdedeus
SQL_INSIGHT_DATE_FILTER_NOTICE: 'sql-insight-date-filter-notice', // owner: #team-product-analytics, gates the notice on SQL insights affected by the date filter resolution fix
SSE_DASHBOARDS: 'sse-dashboards', // owner: @aspicer #team-analytics-platform
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index a34d26955390..2600f40724ba 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -19179,6 +19179,10 @@
"description": "Optional direct external data source id for schema introspection",
"type": "string"
},
+ "includeFields": {
+ "description": "When false, skip serializing each table's fields (`fields` comes back empty). Defaults to true.",
+ "type": "boolean"
+ },
"kind": {
"const": "DatabaseSchemaQuery",
"type": "string"
@@ -19190,6 +19194,13 @@
"response": {
"$ref": "#/definitions/DatabaseSchemaQueryResponse"
},
+ "tables": {
+ "description": "Only serialize these tables (keys as returned in the response, e.g. `events` or `zendesk.groups`). Omit for all tables.",
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
"tags": {
"$ref": "#/definitions/QueryLogTags"
},
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index 2127792feae0..37f4d59c35db 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -5792,6 +5792,10 @@ export interface DatabaseSchemaQuery extends DataNode<DatabaseSchemaQueryRespons
kind: NodeKind.DatabaseSchemaQuery
/** Optional direct external data source id for schema introspection */
connectionId?: string
+ /** Only serialize these tables (keys as returned in the response, e.g. `events` or `zendesk.groups`). Omit for all tables. */
+ tables?: string[]
+ /** When false, skip serializing each table's fields (`fields` comes back empty). Defaults to true. */
+ includeFields?: boolean
}
export type DatabaseSerializedFieldType =
diff --git a/frontend/src/scenes/data-management/database/databaseTableListLogic.test.ts b/frontend/src/scenes/data-management/database/databaseTableListLogic.test.ts
index 4ca74baba8a3..54ffd9ed76f2 100644
--- a/frontend/src/scenes/data-management/database/databaseTableListLogic.test.ts
+++ b/frontend/src/scenes/data-management/database/databaseTableListLogic.test.ts
@@ -210,4 +210,154 @@ describe('databaseTableListLogic', () => {
expect(logic.values.connectionId).toEqual('conn-123')
expect(logic.values.allTables.map((table) => table.name)).toEqual(['ducklake_accounts'])
})
+
+ describe('lazy schema loading', () => {
+ const shallowTables = {
+ events: { name: 'events', type: 'posthog', fields: {} },
+ persons: { name: 'persons', type: 'posthog', fields: {} },
+ }
+ const eventsFields = {
+ uuid: { name: 'uuid', hogql_value: 'uuid', type: 'string', schema_valid: true },
+ }
+
+ const loadShallow = async (): Promise<void> => {
+ ;(performQuery as jest.Mock).mockResolvedValueOnce({ tables: shallowTables, joins: [] })
+ await logic.asyncActions.loadDatabase({ shallow: true })
+ }
+
+ beforeEach(() => {
+ logic = databaseTableListLogic()
+ logic.mount()
+ })
+
+ it('a shallow load requests no fields and marks the schema incomplete', async () => {
+ await loadShallow()
+
+ expect((performQuery as jest.Mock).mock.calls[0][0]).toMatchObject({ includeFields: false })
+ expect(logic.values.databaseFieldsComplete).toBe(false)
+ expect(logic.values.allTables.map((table) => table.name)).toEqual(['events', 'persons'])
+
+ ;(performQuery as jest.Mock).mockResolvedValueOnce({ tables: shallowTables, joins: [] })
+ await logic.asyncActions.loadDatabase({ force: true })
+ expect(logic.values.databaseFieldsComplete).toBe(true)
+ })
+
+ it('hydrateTableFields merges the requested tables and flags missing ones as errors', async () => {
+ await loadShallow()
+ ;(performQuery as jest.Mock).mockResolvedValueOnce({
+ tables: { events: { ...shallowTables.events, fields: eventsFields } },
+ joins: [],
+ })
+
+ await logic.asyncActions.hydrateTableFields(['events', 'gone_table'])
+
+ expect((performQuery as jest.Mock).mock.calls[1][0]).toMatchObject({
+ tables: ['events'],
+ })
+ expect(logic.values.database?.tables['events'].fields).toEqual(eventsFields)
+ expect(logic.values.database?.tables['persons'].fields).toEqual({})
+ expect(logic.values.tableFieldsStatus).toMatchObject({ events: 'loaded' })
+ // 'gone_table' isn't in the schema at all, so it's filtered before the request.
+ expect(logic.values.tableFieldsStatus['gone_table']).toBeUndefined()
+ })
+
+ it('hydrateTableFields skips tables that are already loaded or loading', async () => {
+ await loadShallow()
+ ;(performQuery as jest.Mock).mockResolvedValueOnce({
+ tables: { events: { ...shallowTables.events, fields: eventsFields } },
+ joins: [],
+ })
+ await logic.asyncActions.hydrateTableFields(['events'])
+ expect(performQuery).toHaveBeenCalledTimes(2)
+
+ await logic.asyncActions.hydrateTableFields(['events'])
+ expect(performQuery).toHaveBeenCalledTimes(2)
+ })
+
+ it('does not let a stale hydration failure overwrite fields loaded for another connection', async () => {
+ logic.actions.setConnection('conn-old')
+ await loadShallow()
+
+ let rejectStaleHydration: ((reason?: unknown) => void) | undefined
+ ;(performQuery as jest.Mock).mockImplementationOnce(
+ () =>
+ new Promise<never>((_, reject) => {
+ rejectStaleHydration = reject
+ })
+ )
+ const staleHydration = logic.asyncActions.hydrateTableFields(['events'])
+
+ logic.actions.setConnection('conn-new')
+ await loadShallow()
+ ;(performQuery as jest.Mock).mockResolvedValueOnce({
+ tables: { events: { ...shallowTables.events, fields: eventsFields } },
+ joins: [],
+ })
+ await logic.asyncActions.hydrateTableFields(['events'])
+
+ expect(logic.values.database?.tables['events'].fields).toEqual(eventsFields)
+ expect(logic.values.tableFieldsStatus).toMatchObject({ events: 'loaded' })
+
+ rejectStaleHydration?.(new Error('Stale connection failed'))
+ await staleHydration
+
+ expect(logic.values.database?.tables['events'].fields).toEqual(eventsFields)
+ expect(logic.values.tableFieldsStatus).toMatchObject({ events: 'loaded' })
+ })
+
+ it('treats a requested table missing from the response as terminal', async () => {
+ await loadShallow()
+ ;(performQuery as jest.Mock).mockResolvedValueOnce({ tables: {}, joins: [] })
+
+ await logic.asyncActions.hydrateTableFields(['events'])
+
+ expect(logic.values.tableFieldsStatus).toMatchObject({ events: 'missing' })
+ expect(logic.values.database?.tables['events']).toBeUndefined()
+ expect(logic.values.databaseFieldsComplete).toBe(false)
+
+ ;(performQuery as jest.Mock).mockResolvedValueOnce({
+ tables: { persons: { ...shallowTables.persons, fields: eventsFields } },
+ joins: [],
+ })
+ await logic.asyncActions.hydrateTableFields(['events', 'persons'])
+
+ expect(logic.values.databaseFieldsComplete).toBe(true)
+ expect((performQuery as jest.Mock).mock.calls[2][0]).toMatchObject({ tables: ['persons'] })
+
+ await logic.asyncActions.hydrateTableFields(['events'])
+ expect(performQuery).toHaveBeenCalledTimes(3)
+ })
+
+ it('ensureAllTableFields hydrates every table in place and marks the schema complete', async () => {
+ await loadShallow()
+ ;(performQuery as jest.Mock).mockResolvedValueOnce({
+ tables: {
+ events: { ...shallowTables.events, fields: eventsFields },
+ persons: { ...shallowTables.persons, fields: eventsFields },
+ },
+ joins: [],
+ })
+
+ logic.actions.ensureAllTableFields()
+ await expectLogic(logic).toFinishAllListeners()
+
+ // Upgrades through the merge path, so `databaseLoading` never blanks consumers.
+ expect((performQuery as jest.Mock).mock.calls[1][0]).toMatchObject({
+ tables: ['events', 'persons'],
+ })
+ expect(logic.values.databaseFieldsComplete).toBe(true)
+ expect(logic.values.database?.tables['persons'].fields).toEqual(eventsFields)
+ })
+
+ it('a full load does not piggyback on an in-flight shallow request', () => {
+ ;(performQuery as jest.Mock).mockImplementation(() => new Promise(() => {}))
+
+ logic.actions.loadDatabase({ shallow: true })
+ expect(performQuery).toHaveBeenCalledTimes(1)
+
+ logic.actions.loadDatabase()
+ expect(performQuery).toHaveBeenCalledTimes(2)
+ expect((performQuery as jest.Mock).mock.calls[1][0].includeFields).toBeUndefined()
+ })
+ })
})
diff --git a/frontend/src/scenes/data-management/database/databaseTableListLogic.ts b/frontend/src/scenes/data-management/database/databaseTableListLogic.ts
index 70ae8e4d4c30..5333c6c92366 100644
--- a/frontend/src/scenes/data-management/database/databaseTableListLogic.ts
+++ b/frontend/src/scenes/data-management/database/databaseTableListLogic.ts
@@ -34,8 +34,11 @@ const toMapById = <T extends { id: string }>(items: T[]): Record<string, T> =>
{} as Record<string, T>
)
+export type TableFieldsStatus = Record<string, 'loading' | 'loaded' | 'error' | 'missing'>
+
let inFlightDatabaseLoadKey: string | null = null
let inFlightDatabaseLoadPromise: Promise<Required<DatabaseSchemaQueryResponse> | null> | null = null
+let inFlightDatabaseLoadIsShallow = false
// Monotonic epoch advanced only when a load issues a fresh request. A newer load (e.g. one
// triggered by a schema mutation via refreshDatabaseSchema) supersedes older in-flight ones, so a
@@ -55,6 +58,7 @@ export interface databaseTableListLogicValues {
dataWarehouseTablesMap: Record<string, DatabaseSchemaDataWarehouseTable | DatabaseSchemaViewTable>
dataWarehouseTablesMapById: Record<string, DatabaseSchemaDataWarehouseTable | DatabaseSchemaViewTable>
database: Required<DatabaseSchemaQueryResponse> | null
+ databaseFieldsComplete: boolean
databaseLoadError: string | null
databaseLoading: boolean
endpointTables: DatabaseSchemaEndpointTable[]
@@ -67,6 +71,7 @@ export interface databaseTableListLogicValues {
searchTerm: string
systemTables: DatabaseSchemaTable[]
systemTablesMap: Record<string, DatabaseSchemaTable>
+ tableFieldsStatus: TableFieldsStatus
views: DatabaseSchemaViewTable[]
viewsMap: Record<string, DatabaseSchemaEndpointTable | DatabaseSchemaManagedViewTable | DatabaseSchemaViewTable>
viewsMapById: Record<string, DatabaseSchemaEndpointTable | DatabaseSchemaManagedViewTable | DatabaseSchemaViewTable>
@@ -74,8 +79,28 @@ export interface databaseTableListLogicValues {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface databaseTableListLogicActions {
- loadDatabase: ({ force }?: { force?: boolean }) => {
+ ensureAllTableFields: () => {
+ value: true
+ }
+ hydrateTableFields: (tableNames: string[]) => {
+ tableNames: string[]
+ }
+ hydrateTableFieldsFailure: (tableNames: string[]) => {
+ tableNames: string[]
+ }
+ hydrateTableFieldsStart: (tableNames: string[]) => {
+ tableNames: string[]
+ }
+ hydrateTableFieldsSuccess: (
+ tableNames: string[],
+ tables: Record<string, DatabaseSchemaTable>
+ ) => {
+ tableNames: string[]
+ tables: Record<string, DatabaseSchemaTable>
+ }
+ loadDatabase: ({ force, shallow }?: { force?: boolean; shallow?: boolean }) => {
force?: boolean
+ shallow?: boolean
}
loadDatabaseFailure: (
error: string,
@@ -88,11 +113,13 @@ export interface databaseTableListLogicActions {
database: Required<DatabaseSchemaQueryResponse> | null,
payload?: {
force?: boolean
+ shallow?: boolean
}
) => {
database: Required<DatabaseSchemaQueryResponse> | null
payload?: {
force?: boolean
+ shallow?: boolean
}
}
refreshDatabaseSchema: () => {
@@ -104,6 +131,9 @@ export interface databaseTableListLogicActions {
setConnection: (connectionId: string | null) => {
connectionId: string | null
}
+ setDatabaseFieldsComplete: (complete: boolean) => {
+ complete: boolean
+ }
setSearchTerm: (searchTerm: string) => {
searchTerm: string
}
@@ -169,22 +199,43 @@ export const databaseTableListLogic = kea<databaseTableListLogicType>([
// shared and outlives the SQL editor, so without an explicit reset every other consumer
// (sources list, taxonomic filters, joins) keeps seeing the connection's tables.
resetConnectionScope: true,
+ hydrateTableFields: (tableNames: string[]) => ({ tableNames }),
+ hydrateTableFieldsStart: (tableNames: string[]) => ({ tableNames }),
+ hydrateTableFieldsSuccess: (tableNames: string[], tables: Record<string, DatabaseSchemaTable>) => ({
+ tableNames,
+ tables,
+ }),
+ hydrateTableFieldsFailure: (tableNames: string[]) => ({ tableNames }),
+ setDatabaseFieldsComplete: (complete: boolean) => ({ complete }),
+ // Upgrade a shallow (table names only) schema to a full one. Consumers that read
+ // `fields` across many tables at once (search, join modal, expressions) call this.
+ ensureAllTableFields: true,
}),
- loaders(({ values }) => ({
+ loaders(({ values, actions }) => ({
database: [
null as Required<DatabaseSchemaQueryResponse> | null,
{
loadDatabase: async ({
force,
- }: { force?: boolean } = {}): Promise<Required<DatabaseSchemaQueryResponse> | null> => {
+ shallow,
+ }: {
+ force?: boolean
+ shallow?: boolean
+ } = {}): Promise<Required<DatabaseSchemaQueryResponse> | null> => {
const requestConnectionId = values.connectionId ?? undefined
const requestKey = requestConnectionId ?? '__posthog__'
// Non-forced loads may piggyback on an identical in-flight request and adopt its
// epoch (they don't start a new generation). A forced refresh always issues a
// fresh request so it can never return pre-mutation data (and never waits on a
- // hung stale request).
- if (!force && inFlightDatabaseLoadKey === requestKey && inFlightDatabaseLoadPromise) {
+ // hung stale request). A full load never piggybacks on a shallow request — it
+ // would come back without any fields.
+ if (
+ !force &&
+ inFlightDatabaseLoadKey === requestKey &&
+ inFlightDatabaseLoadPromise &&
+ (shallow || !inFlightDatabaseLoadIsShallow)
+ ) {
const epoch = inFlightDatabaseLoadEpoch
const result = await inFlightDatabaseLoadPromise
// Reading `values` post-unmount throws kea's path-not-found error.
@@ -202,12 +253,14 @@ export const databaseTableListLogic = kea<databaseTableListLogicType>([
setLatestVersionsOnQuery({
kind: NodeKind.DatabaseSchemaQuery,
connectionId: requestConnectionId,
+ includeFields: shallow ? false : undefined,
}) as DatabaseSchemaQuery
)
inFlightDatabaseLoadKey = requestKey
inFlightDatabaseLoadPromise = request
inFlightDatabaseLoadEpoch = epoch
+ inFlightDatabaseLoadIsShallow = !!shallow
let database: Required<DatabaseSchemaQueryResponse> | null = null
try {
@@ -237,6 +290,7 @@ export const databaseTableListLogic = kea<databaseTableListLogicType>([
return values.database
}
+ actions.setDatabaseFieldsComplete(!shallow)
return database
},
},
@@ -244,6 +298,59 @@ export const databaseTableListLogic = kea<databaseTableListLogicType>([
})),
reducers({
searchTerm: ['', { setSearchTerm: (_, { searchTerm }) => searchTerm }],
+ database: {
+ hydrateTableFieldsSuccess: (state, { tableNames, tables }) => {
+ if (!state) {
+ return state
+ }
+ const nextTables = { ...state.tables, ...tables }
+ for (const tableName of tableNames) {
+ if (!(tableName in tables)) {
+ delete nextTables[tableName]
+ }
+ }
+ return { ...state, tables: nextTables }
+ },
+ },
+ // False while the store only holds a shallow schema (table names and metadata, no fields).
+ databaseFieldsComplete: [
+ true,
+ {
+ setDatabaseFieldsComplete: (_, { complete }) => complete,
+ },
+ ],
+ tableFieldsStatus: [
+ {} as TableFieldsStatus,
+ {
+ hydrateTableFieldsStart: (state, { tableNames }) => {
+ const next = { ...state }
+ for (const name of tableNames) {
+ next[name] = 'loading'
+ }
+ return next
+ },
+ hydrateTableFieldsSuccess: (state, { tableNames, tables }) => {
+ const next = { ...state }
+ for (const name of tableNames) {
+ next[name] = name in tables ? 'loaded' : 'missing'
+ }
+ return next
+ },
+ hydrateTableFieldsFailure: (state, { tableNames }) => {
+ const next = { ...state }
+ for (const name of tableNames) {
+ next[name] = 'error'
+ }
+ return next
+ },
+ // Any full or shallow reload replaces `database.tables` wholesale, so per-table
+ // hydration state no longer describes the store.
+ loadDatabaseSuccess: () => ({}),
+ loadDatabaseFailure: () => ({}),
+ setConnection: () => ({}),
+ resetConnectionScope: () => ({}),
+ },
+ ],
// Without this the logic settles on `database: null, databaseLoading: false` after a failed
// load, which every consumer reads as "loaded, and the project has no tables".
databaseLoadError: [
@@ -429,10 +536,101 @@ export const databaseTableListLogic = kea<databaseTableListLogicType>([
{ resultEqualityCheck: objectsEqual },
],
}),
- listeners(({ actions }) => ({
+ listeners(({ actions, values }) => ({
refreshDatabaseSchema: () => {
actions.loadDatabase({ force: true })
},
+ hydrateTableFields: async ({ tableNames }) => {
+ const requestConnectionId = values.connectionId ?? undefined
+ const tables = values.database?.tables ?? {}
+ const toLoad = tableNames.filter((name) => {
+ const status = values.tableFieldsStatus[name]
+ if (status === 'loading' || status === 'loaded' || status === 'missing') {
+ return false
+ }
+ const table = tables[name]
+ // Unknown tables can't be hydrated; tables with fields already are.
+ return !!table && Object.keys(table.fields).length === 0
+ })
+ if (values.databaseFieldsComplete || toLoad.length === 0) {
+ return
+ }
+
+ const epoch = latestDatabaseLoadEpoch
+ actions.hydrateTableFieldsStart(toLoad)
+ try {
+ const response = await performQuery(
+ setLatestVersionsOnQuery({
+ kind: NodeKind.DatabaseSchemaQuery,
+ connectionId: requestConnectionId,
+ tables: toLoad,
+ }) as DatabaseSchemaQuery
+ )
+ if (!databaseTableListLogic.isMounted()) {
+ return
+ }
+ // A newer full/shallow load replaced the store while we were fetching — its tables
+ // (and any statuses) supersede this response.
+ if (epoch !== latestDatabaseLoadEpoch || (values.connectionId ?? undefined) !== requestConnectionId) {
+ return
+ }
+ actions.hydrateTableFieldsSuccess(toLoad, response.tables ?? {})
+ // Once every table's fields are in the store, it's equivalent to a full load.
+ const tablesNow = values.database?.tables ?? {}
+ const statusNow = values.tableFieldsStatus
+ const allLoaded = Object.values(tablesNow).every(
+ (table) =>
+ Object.keys(table.fields).length > 0 ||
+ statusNow[table.name] === 'loaded' ||
+ statusNow[table.name] === 'missing'
+ )
+ if (allLoaded) {
+ actions.setDatabaseFieldsComplete(true)
+ }
+ } catch {
+ if (!databaseTableListLogic.isMounted()) {
+ return
+ }
+ // Same staleness guard as the success path: a rejection from a superseded request
+ // must not stamp errors onto the schema that replaced it.
+ if (epoch !== latestDatabaseLoadEpoch || (values.connectionId ?? undefined) !== requestConnectionId) {
+ return
+ }
+ actions.hydrateTableFieldsFailure(toLoad)
+ }
+ },
+ loadDatabaseSuccess: async ({ payload }, breakpoint) => {
+ if (!payload?.shallow || values.databaseFieldsComplete) {
+ return
+ }
+ // A shallow load renders the table tree immediately; upgrade to the full schema in the
+ // background so every other consumer of this shared store (taxonomic filters, join
+ // modal, insights) still converges on complete field data. The delay lets tables the
+ // user expands right away hydrate through their own small requests first; tables
+ // already loaded or loading are skipped by the upgrade.
+ await breakpoint(3000)
+ actions.ensureAllTableFields()
+ },
+ ensureAllTableFields: () => {
+ if (values.databaseFieldsComplete && values.database) {
+ return
+ }
+ // A full (non-shallow) load is already in flight and will land complete fields.
+ if (values.databaseLoading && !inFlightDatabaseLoadIsShallow) {
+ return
+ }
+ const tables = values.database?.tables
+ if (tables && Object.keys(tables).length > 0) {
+ // Upgrade in place: hydrating every table merges fields into the store without
+ // flipping `databaseLoading`, so consumers keep rendering the shallow schema
+ // meanwhile. Tables already loading/loaded are skipped, errored ones retried.
+ actions.hydrateTableFields(Object.keys(tables))
+ return
+ }
+ // Nothing loaded yet. A shallow request may be in flight under the same key; force a
+ // fresh full request rather than piggybacking on it.
+ actions.loadDatabase({ force: inFlightDatabaseLoadIsShallow && !!inFlightDatabaseLoadPromise })
+ },
// Reload immediately: the cached `database` still holds the connection's schema, and
// consumers that only load when `database` is empty would otherwise never refetch it.
resetConnectionScope: () => {
diff --git a/frontend/src/scenes/data-warehouse/editor/sidebar/queryDatabaseLogic.test.ts b/frontend/src/scenes/data-warehouse/editor/sidebar/queryDatabaseLogic.test.ts
index 90fd57b4bbae..91391c34fe6c 100644
--- a/frontend/src/scenes/data-warehouse/editor/sidebar/queryDatabaseLogic.test.ts
+++ b/frontend/src/scenes/data-warehouse/editor/sidebar/queryDatabaseLogic.test.ts
@@ -1,6 +1,9 @@
+import { expectLogic } from 'kea-test-utils'
+
import { newInternalTab } from 'lib/utils/newInternalTab'
import { databaseTableListLogic } from 'scenes/data-management/database/databaseTableListLogic'
+import { performQuery } from '~/queries/query'
import { initKeaTests } from '~/test/init'
import {
@@ -12,6 +15,7 @@ import {
} from './queryDatabaseLogic'
jest.mock('lib/utils/newInternalTab')
+jest.mock('~/queries/query')
describe('queryDatabaseLogic', () => {
it('groups direct connection tables into schema folders', () => {
@@ -287,14 +291,82 @@ describe('queryDatabaseLogic', () => {
})
})
+ describe('lazy schema hydration', () => {
+ let logic: ReturnType<typeof queryDatabaseLogic.build>
+ let dbLogic: ReturnType<typeof databaseTableListLogic.build>
+
+ const findTableNode = (): any =>
+ logic.values.treeData
+ .find((item) => item.record?.type === 'sources')
+ ?.children?.find((child) => child.id === 'source-posthog')
+ ?.children?.find((child) => child.id === 'table-events')
+
+ beforeEach(async () => {
+ initKeaTests()
+ // Earlier tests persist expanded folders; a restored expansion would trigger hydration
+ // before the assertions below stage their own state.
+ localStorage.clear()
+ ;(performQuery as jest.Mock).mockResolvedValue({ tables: {}, joins: [] })
+ logic = queryDatabaseLogic()
+ logic.mount()
+ dbLogic = databaseTableListLogic.findMounted()! as ReturnType<typeof databaseTableListLogic.build>
+ await expectLogic(dbLogic).toFinishAllListeners()
+ dbLogic.actions.loadDatabaseSuccess({
+ tables: { events: { id: 'events', name: 'events', type: 'posthog', fields: {} } },
+ joins: [],
+ })
+ dbLogic.actions.setDatabaseFieldsComplete(false)
+ })
+
+ afterEach(() => {
+ logic.unmount()
+ jest.clearAllMocks()
+ })
+
+ it('renders a hydration placeholder, hydrates on expand, then shows the columns', async () => {
+ const placeholder = findTableNode()?.children?.[0]
+ expect(placeholder?.type).toEqual('loading-indicator')
+ expect(placeholder?.record?.pendingTableName).toEqual('events')
+
+ logic.actions.toggleFolderOpen('table-events', false)
+ await expectLogic(dbLogic).toFinishAllListeners()
+
+ expect(performQuery).toHaveBeenCalledWith(expect.objectContaining({ tables: ['events'] }))
+
+ dbLogic.actions.hydrateTableFieldsSuccess(['events'], {
+ events: {
+ id: 'events',
+ name: 'events',
+ type: 'posthog',
+ fields: { uuid: { name: 'uuid', hogql_value: 'uuid', type: 'string', schema_valid: true } },
+ } as any,
+ })
+
+ const columnNames = findTableNode()?.children?.map((child: any) => child.name)
+ expect(columnNames).toEqual(['uuid'])
+ })
+
+ it('shows an error node when hydrating a table failed', () => {
+ dbLogic.actions.hydrateTableFieldsStart(['events'])
+ dbLogic.actions.hydrateTableFieldsFailure(['events'])
+
+ const errorNode = findTableNode()?.children?.[0]
+ expect(errorNode?.record?.type).toEqual('fields-load-error')
+ })
+ })
+
describe('direct connection state', () => {
let logic: ReturnType<typeof queryDatabaseLogic.build>
- beforeEach(() => {
+ beforeEach(async () => {
initKeaTests()
+ ;(performQuery as jest.Mock).mockResolvedValue({ tables: {}, joins: [] })
logic = queryDatabaseLogic()
logic.mount()
- databaseTableListLogic.findMounted()?.actions.setConnection('source-id')
+ const databaseLogic = databaseTableListLogic.findMounted()!
+ await expectLogic(databaseLogic).toFinishAllListeners()
+ databaseLogic.actions.setConnection('source-id')
+ ;(performQuery as jest.Mock).mockClear()
})
afterEach(() => {
@@ -327,5 +399,47 @@ describe('queryDatabaseLogic', () => {
expect.stringContaining('/data-management/sources/managed-source-id/schemas')
)
})
+
+ it('hydrates a table restored as expanded in the displayed direct-connection tree', async () => {
+ const databaseLogic = databaseTableListLogic.findMounted()!
+ databaseLogic.actions.loadDatabaseSuccess({
+ tables: {
+ 'public.accounts': {
+ id: 'accounts',
+ name: 'public.accounts',
+ type: 'data_warehouse',
+ fields: {},
+ source: {
+ id: 'source-id',
+ status: 'Running',
+ source_type: 'Postgres',
+ prefix: '',
+ access_method: 'direct',
+ },
+ },
+ },
+ joins: [],
+ } as any)
+ databaseLogic.actions.setDatabaseFieldsComplete(false)
+ ;(performQuery as jest.Mock).mockResolvedValueOnce({
+ tables: {
+ 'public.accounts': {
+ id: 'accounts',
+ name: 'public.accounts',
+ type: 'data_warehouse',
+ fields: {
+ id: { name: 'id', hogql_value: 'id', type: 'string', schema_valid: true },
+ },
+ },
+ },
+ joins: [],
+ })
+
+ logic.actions.setExpandedFolders(['schema-public', 'table-public.accounts'], 'source-id')
+ await expectLogic(databaseLogic).toFinishAllListeners()
+
+ expect(performQuery).toHaveBeenCalledWith(expect.objectContaining({ tables: ['public.accounts'] }))
+ expect(databaseLogic.values.database?.tables['public.accounts'].fields).toHaveProperty('id')
+ })
})
})
diff --git a/frontend/src/scenes/data-warehouse/editor/sidebar/queryDatabaseLogic.tsx b/frontend/src/scenes/data-warehouse/editor/sidebar/queryDatabaseLogic.tsx
index d60dd464629f..9c2bf1e960c8 100644
--- a/frontend/src/scenes/data-warehouse/editor/sidebar/queryDatabaseLogic.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/sidebar/queryDatabaseLogic.tsx
@@ -23,7 +23,7 @@ import { LemonTreeRef, TreeDataItem } from 'lib/lemon-ui/LemonTree/LemonTree'
import { FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { createFuse, IFuseOptions } from 'lib/utils/fuseSearch'
import { newInternalTab } from 'lib/utils/newInternalTab'
-import { databaseTableListLogic } from 'scenes/data-management/database/databaseTableListLogic'
+import { TableFieldsStatus, databaseTableListLogic } from 'scenes/data-management/database/databaseTableListLogic'
import { POSTHOG_WAREHOUSE } from 'scenes/data-warehouse/editor/connectionSelectorLogic'
import { urls } from 'scenes/urls'
import { userLogic } from 'scenes/userLogic'
@@ -147,6 +147,38 @@ type FieldTraversalOptions = {
expandedLazyNodeIds?: Set<string>
visitedColumnPaths?: Set<string>
depth?: number
+ hydration?: TableFieldsHydration
+}
+
+// With a shallow (lazy) schema load, tables arrive without fields; this tracks which tables'
+// fields the store actually holds so the tree can show spinners and request the missing ones.
+type TableFieldsHydration = {
+ databaseFieldsComplete: boolean
+ tableFieldsStatus: TableFieldsStatus
+}
+
+type TableFieldsState = 'ready' | 'pending' | 'error'
+
+const getTableFieldsState = (
+ tableName: string,
+ fields: Record<string, DatabaseSchemaField> | undefined,
+ hydration?: TableFieldsHydration
+): TableFieldsState => {
+ const status = hydration?.tableFieldsStatus[tableName]
+ if (status === 'error') {
+ return 'error'
+ }
+ if (!hydration || hydration.databaseFieldsComplete) {
+ return 'ready'
+ }
+ if (fields && Object.keys(fields).length > 0) {
+ return 'ready'
+ }
+ if (status === 'loaded') {
+ // Hydrated and the table genuinely has no fields.
+ return 'ready'
+ }
+ return 'pending'
}
export type SearchTreeSourceContext = {
@@ -193,6 +225,41 @@ const normalizeTableLookupKey = (tableName?: string | null): string | null => {
return tableName.replaceAll('`', '')
}
+const findTreeItemById = (nodes: TreeDataItem[], id: string): TreeDataItem | null => {
+ for (const node of nodes) {
+ if (node.id === id) {
+ return node
+ }
+ if (node.children) {
+ const found = findTreeItemById(node.children, id)
+ if (found) {
+ return found
+ }
+ }
+ }
+ return null
+}
+
+// Which table's fields a tree node needs once expanded: the table itself, or for join/traverser
+// nodes the joined table on the other side.
+const getHydrationTableNamesForNode = (node: TreeDataItem): string[] => {
+ const record = node.record as Record<string, any> | undefined
+ if (!record) {
+ return []
+ }
+ if ((record.type === 'table' || record.type === 'endpoint') && record.table?.name) {
+ return [record.table.name]
+ }
+ if ((record.type === 'lazy-table' || record.type === 'field-traverser') && record.referencedTable) {
+ const name = normalizeTableLookupKey(record.referencedTable)
+ return name ? [name] : []
+ }
+ if (record.type === 'managed-view' && record.view?.name) {
+ return [record.view.name]
+ }
+ return []
+}
+
const getPrimaryKeyName = (tableName: string, fields: DatabaseSchemaField[]): string | null => {
const fieldNames = new Set(fields.map((field) => field.name))
const baseTableName = tableName.split('.').pop() ?? tableName
@@ -369,6 +436,37 @@ const createLazyTablePlaceholderNode = (lazyNodeId: string): TreeDataItem => {
}
}
+// Placeholder shown while a table's fields are being lazy loaded. `pendingTableName` marks the
+// table to hydrate; the tree subscription collects these for every visible placeholder.
+const createPendingFieldsNode = (nodeId: string, pendingTableName: string): TreeDataItem => {
+ return {
+ id: `${nodeId}-fields-pending/`,
+ name: 'Loading...',
+ displayName: <>Loading...</>,
+ icon: <Spinner />,
+ disableSelect: true,
+ type: 'loading-indicator',
+ record: {
+ type: 'pending-fields',
+ pendingTableName,
+ },
+ }
+}
+
+const createFieldsErrorNode = (nodeId: string): TreeDataItem => {
+ return {
+ id: `${nodeId}-fields-error/`,
+ name: "Couldn't load columns",
+ displayName: <span className="text-danger">Couldn't load columns</span>,
+ icon: <IconWarning className="text-danger" />,
+ disableSelect: true,
+ type: 'node',
+ record: {
+ type: 'fields-load-error',
+ },
+ }
+}
+
// A failed schema load must not look like an empty project: say it failed and offer the retry.
const createSchemaErrorNodes = (prefix: string, onRetry: () => void): TreeDataItem[] => [
{
@@ -502,6 +600,39 @@ const createLazyTableChildren = (
)
}
+// Children of an expanded lazy-join node. When the joined table exists but its fields haven't been
+// lazy loaded yet, show a hydration placeholder instead of a false "Empty folder".
+const createExpandedLazyTableChildren = (
+ lazyNodeId: string,
+ tableName: string,
+ field: DatabaseSchemaField,
+ isSearch: boolean,
+ columnPath: string,
+ tableLookup: TableLookup | undefined,
+ options: FieldTraversalOptions | undefined
+): TreeDataItem[] => {
+ const normalizedTableName = normalizeTableLookupKey(field.table)
+ const referencedTable = field.table
+ ? (tableLookup?.[field.table] ?? (normalizedTableName ? tableLookup?.[normalizedTableName] : undefined))
+ : undefined
+
+ if (referencedTable) {
+ const state = getTableFieldsState(referencedTable.name, referencedTable.fields, options?.hydration)
+ if (state === 'pending') {
+ return [createPendingFieldsNode(lazyNodeId, referencedTable.name)]
+ }
+ if (state === 'error') {
+ return [createFieldsErrorNode(lazyNodeId)]
+ }
+ }
+
+ const lazyChildren = createLazyTableChildren(tableName, field, isSearch, columnPath, tableLookup, {
+ ...options,
+ expandedLazyNodeIds: options?.expandedLazyNodeIds ?? new Set<string>(),
+ })
+ return lazyChildren.length > 0 ? lazyChildren : [createLazyTableEmptyNode(lazyNodeId)]
+}
+
const createViewTableChildren = (
tableName: string,
field: DatabaseSchemaField,
@@ -587,13 +718,16 @@ const createTraversedLazyTableNode = (
): TreeDataItem => {
const lazyNodeId = `${isSearch ? 'search-' : ''}lazy-traverser-${tableName}-${columnPath}`
const isExpanded = options?.expandedLazyNodeIds?.has(lazyNodeId)
- const lazyChildren = isExpanded
- ? createLazyTableChildren(tableName, traversedField, isSearch, columnPath, tableLookup, options)
- : []
const children = isExpanded
- ? lazyChildren.length > 0
- ? lazyChildren
- : [createLazyTableEmptyNode(lazyNodeId)]
+ ? createExpandedLazyTableChildren(
+ lazyNodeId,
+ tableName,
+ traversedField,
+ isSearch,
+ columnPath,
+ tableLookup,
+ options
+ )
: [createLazyTablePlaceholderNode(lazyNodeId)]
return {
@@ -678,6 +812,7 @@ const createFieldNode = (
expandedLazyNodeIds,
visitedColumnPaths: nextVisitedColumnPaths,
depth: depth + 1,
+ hydration: options?.hydration,
}
if (field.type === 'virtual_table') {
const children =
@@ -762,18 +897,16 @@ const createFieldNode = (
if (field.type === 'lazy_table') {
const lazyNodeId = `${isSearch ? 'search-' : ''}lazy-${tableName}-${columnPath}`
const isExpanded = expandedLazyNodeIds ? expandedLazyNodeIds.has(lazyNodeId) : false
- const lazyExpandedIds = expandedLazyNodeIds ?? new Set<string>()
- const lazyChildren = isExpanded
- ? createLazyTableChildren(tableName, field, isSearch, columnPath, tableLookup, {
- ...nextOptions,
- expandedLazyNodeIds: lazyExpandedIds,
- })
- : []
-
const children = isExpanded
- ? lazyChildren.length > 0
- ? lazyChildren
- : [createLazyTableEmptyNode(lazyNodeId)]
+ ? createExpandedLazyTableChildren(
+ lazyNodeId,
+ tableName,
+ field,
+ isSearch,
+ columnPath,
+ tableLookup,
+ nextOptions
+ )
: [createLazyTablePlaceholderNode(lazyNodeId)]
return {
@@ -841,23 +974,32 @@ const createTableNode = (
tableLookup?: TableLookup,
options?: {
expandedLazyNodeIds?: Set<string>
+ hydration?: TableFieldsHydration
}
): TreeDataItem => {
+ const tableId = `${isSearch ? 'search-' : ''}table-${table.name}`
const tableChildren: TreeDataItem[] = []
if ('fields' in table) {
- sortFieldsWithPrimary(table.name, Object.values(table.fields))
- .filter((field) => !shouldHideField(field))
- .forEach((field: DatabaseSchemaField) => {
- tableChildren.push(
- createFieldNode(table.name, field, isSearch, field.name, tableLookup, {
- expandedLazyNodeIds: options?.expandedLazyNodeIds,
- })
- )
- })
+ const fieldsState = getTableFieldsState(table.name, table.fields, options?.hydration)
+ if (fieldsState === 'pending') {
+ tableChildren.push(createPendingFieldsNode(tableId, table.name))
+ } else if (fieldsState === 'error') {
+ tableChildren.push(createFieldsErrorNode(tableId))
+ } else {
+ sortFieldsWithPrimary(table.name, Object.values(table.fields))
+ .filter((field) => !shouldHideField(field))
+ .forEach((field: DatabaseSchemaField) => {
+ tableChildren.push(
+ createFieldNode(table.name, field, isSearch, field.name, tableLookup, {
+ expandedLazyNodeIds: options?.expandedLazyNodeIds,
+ hydration: options?.hydration,
+ })
+ )
+ })
+ }
}
- const tableId = `${isSearch ? 'search-' : ''}table-${table.name}`
return {
id: tableId,
name: table.name,
@@ -931,6 +1073,7 @@ const createViewNode = (
tableLookup?: TableLookup,
options?: {
expandedLazyNodeIds?: Set<string>
+ hydration?: TableFieldsHydration
},
schemaTable?: DatabaseSchemaTable,
isMaterializing = false
@@ -948,6 +1091,7 @@ const createViewNode = (
viewChildren.push(
createFieldNode(view.name, column, isSearch, column.name, tableLookup, {
expandedLazyNodeIds: options?.expandedLazyNodeIds,
+ hydration: options?.hydration,
})
)
})
@@ -985,21 +1129,29 @@ const createManagedViewNode = (
tableLookup?: TableLookup,
options?: {
expandedLazyNodeIds?: Set<string>
+ hydration?: TableFieldsHydration
}
): TreeDataItem => {
+ const managedViewId = `${isSearch ? 'search-' : ''}managed-view-${managedView.id}`
const viewChildren: TreeDataItem[] = []
- sortFieldsWithPrimary(managedView.name, Object.values(managedView.fields))
- .filter((field) => !shouldHideField(field))
- .forEach((field: DatabaseSchemaField) => {
- viewChildren.push(
- createFieldNode(managedView.name, field, isSearch, field.name, tableLookup, {
- expandedLazyNodeIds: options?.expandedLazyNodeIds,
- })
- )
- })
-
- const managedViewId = `${isSearch ? 'search-' : ''}managed-view-${managedView.id}`
+ const fieldsState = getTableFieldsState(managedView.name, managedView.fields, options?.hydration)
+ if (fieldsState === 'pending') {
+ viewChildren.push(createPendingFieldsNode(managedViewId, managedView.name))
+ } else if (fieldsState === 'error') {
+ viewChildren.push(createFieldsErrorNode(managedViewId))
+ } else {
+ sortFieldsWithPrimary(managedView.name, Object.values(managedView.fields))
+ .filter((field) => !shouldHideField(field))
+ .forEach((field: DatabaseSchemaField) => {
+ viewChildren.push(
+ createFieldNode(managedView.name, field, isSearch, field.name, tableLookup, {
+ expandedLazyNodeIds: options?.expandedLazyNodeIds,
+ hydration: options?.hydration,
+ })
+ )
+ })
+ }
return {
id: managedViewId,
@@ -1020,23 +1172,32 @@ const createEndpointNode = (
matches: FuseSearchMatch[] | null = null,
isSearch = false,
tableLookup?: TableLookup,
- options?: { expandedLazyNodeIds?: Set<string> }
+ options?: { expandedLazyNodeIds?: Set<string>; hydration?: TableFieldsHydration }
): TreeDataItem => {
+ const endpointNodeId = `${isSearch ? 'search-' : ''}endpoint-${endpointTable.id}`
const children: TreeDataItem[] = []
- sortFieldsWithPrimary(endpointTable.name, Object.values(endpointTable.fields))
- .filter((column) => !shouldHideField(column))
- .forEach((column) => {
- children.push(
- createFieldNode(endpointTable.name, column, isSearch, column.name, tableLookup, {
- expandedLazyNodeIds: options?.expandedLazyNodeIds,
- })
- )
- })
+ const fieldsState = getTableFieldsState(endpointTable.name, endpointTable.fields, options?.hydration)
+ if (fieldsState === 'pending') {
+ children.push(createPendingFieldsNode(endpointNodeId, endpointTable.name))
+ } else if (fieldsState === 'error') {
+ children.push(createFieldsErrorNode(endpointNodeId))
+ } else {
+ sortFieldsWithPrimary(endpointTable.name, Object.values(endpointTable.fields))
+ .filter((column) => !shouldHideField(column))
+ .forEach((column) => {
+ children.push(
+ createFieldNode(endpointTable.name, column, isSearch, column.name, tableLookup, {
+ expandedLazyNodeIds: options?.expandedLazyNodeIds,
+ hydration: options?.hydration,
+ })
+ )
+ })
+ }
const displayName = endpointTable.name.replace(/_v\d+$/, '')
return {
- id: `${isSearch ? 'search-' : ''}endpoint-${endpointTable.id}`,
+ id: endpointNodeId,
name: displayName,
type: 'node',
icon: <IconEndpoints />,
@@ -1058,6 +1219,7 @@ const createSourceFolderNode = (
tableLookup?: TableLookup,
options?: {
expandedLazyNodeIds?: Set<string>
+ hydration?: TableFieldsHydration
}
): TreeDataItem => {
const sourceChildren: TreeDataItem[] = []
@@ -1436,6 +1598,7 @@ export interface queryDatabaseLogicValues {
connectionId: string | null // databaseTableListLogic
dataWarehouseTables: DatabaseSchemaDataWarehouseTable[] // databaseTableListLogic
dataWarehouseTablesMap: Record<string, DatabaseSchemaDataWarehouseTable | DatabaseSchemaViewTable> // databaseTableListLogic
+ databaseFieldsComplete: boolean // databaseTableListLogic
databaseLoadError: string | null // databaseTableListLogic
databaseLoading: boolean // databaseTableListLogic
latestEndpointTables: DatabaseSchemaEndpointTable[] // databaseTableListLogic
@@ -1444,6 +1607,7 @@ export interface queryDatabaseLogicValues {
posthogTablesMap: Record<string, DatabaseSchemaTable> // databaseTableListLogic
systemTables: DatabaseSchemaTable[] // databaseTableListLogic
systemTablesMap: Record<string, DatabaseSchemaTable> // databaseTableListLogic
+ tableFieldsStatus: TableFieldsStatus // databaseTableListLogic
viewsMapById: Record<string, DatabaseSchemaEndpointTable | DatabaseSchemaManagedViewTable | DatabaseSchemaViewTable> // databaseTableListLogic
drafts: DataWarehouseSavedQueryDraft[] // draftsLogic
draftsResponseLoading: boolean // draftsLogic
@@ -1570,6 +1734,12 @@ export interface queryDatabaseLogicActions {
types?: string[][]
}
} // dataWarehouseViewsLogic
+ ensureAllTableFields: () => {
+ value: true
+ } // databaseTableListLogic
+ hydrateTableFields: (tableNames: string[]) => {
+ tableNames: string[]
+ } // databaseTableListLogic
refreshDatabaseSchema: () => {
value: true
} // databaseTableListLogic
@@ -1825,7 +1995,9 @@ export interface queryDatabaseLogicMeta {
featureFlags: FeatureFlagsSet,
queryTabState: QueryTabState | null,
expandedFolders: string[],
- materializingViewIds: string[]
+ materializingViewIds: string[],
+ databaseFieldsComplete: boolean,
+ tableFieldsStatus: TableFieldsStatus
) => TreeDataItem[]
displayedTreeData: (
searchTerm: string,
@@ -1926,6 +2098,8 @@ export const queryDatabaseLogic = kea<queryDatabaseLogicType>([
'allTablesMap',
'latestEndpointTables',
'connectionId',
+ 'databaseFieldsComplete',
+ 'tableFieldsStatus',
],
dataWarehouseViewsLogic,
[
@@ -1959,7 +2133,7 @@ export const queryDatabaseLogic = kea<queryDatabaseLogicType>([
draftsLogic,
['loadDrafts', 'renameDraft', 'loadMoreDrafts'],
databaseTableListLogic,
- ['refreshDatabaseSchema'],
+ ['refreshDatabaseSchema', 'hydrateTableFields', 'ensureAllTableFields'],
],
})),
reducers({
@@ -2637,6 +2811,8 @@ export const queryDatabaseLogic = kea<queryDatabaseLogicType>([
s.queryTabState,
s.expandedFolders,
s.materializingViewIds,
+ s.databaseFieldsComplete,
+ s.tableFieldsStatus,
],
(
treeDataContext: TreeDataContext,
@@ -2649,7 +2825,9 @@ export const queryDatabaseLogic = kea<queryDatabaseLogicType>([
featureFlags: FeatureFlagsSet,
queryTabState: QueryTabState | null,
expandedFolders: string[],
- materializingViewIds: string[]
+ materializingViewIds: string[],
+ databaseFieldsComplete: boolean,
+ tableFieldsStatus: TableFieldsStatus
): TreeDataItem[] => {
const {
allPosthogTables,
@@ -2672,7 +2850,8 @@ export const queryDatabaseLogic = kea<queryDatabaseLogicType>([
savedQuerySchemaTables: allTablesMap,
})
const expandedLazyNodeIds = new Set(expandedFolders.filter(isLazyNodeId))
- const tableNodeOptions = { expandedLazyNodeIds }
+ const hydration: TableFieldsHydration = { databaseFieldsComplete, tableFieldsStatus }
+ const tableNodeOptions = { expandedLazyNodeIds, hydration }
const schemaFailedWithNoTables =
!!databaseLoadError && !databaseLoading && Object.keys(allTablesMap).length === 0
@@ -3138,6 +3317,27 @@ export const queryDatabaseLogic = kea<queryDatabaseLogicType>([
} else {
actions.setExpandedFolders([...expandedFolders, folderId], values.connectionId)
}
+ // With a lazy-loaded schema, expanding a node is what triggers fetching its columns.
+ // Going through the tree node (rather than parsing the id) also retries failed loads.
+ const node = findTreeItemById(values.displayedTreeData, folderId)
+ if (node) {
+ const tableNames = getHydrationTableNamesForNode(node)
+ if (tableNames.length > 0) {
+ actions.hydrateTableFields(tableNames)
+ }
+ }
+ }
+ },
+ selectSchema: ({ schema }) => {
+ // The sidebar overlay lists the selected table's columns, so make sure they're loaded.
+ if (schema && 'name' in schema && schema.name) {
+ actions.hydrateTableFields([schema.name])
+ }
+ },
+ setSearchTerm: ({ searchTerm }) => {
+ // Search matches on column names too, which a lazy-loaded schema doesn't have yet.
+ if (searchTerm) {
+ actions.ensureAllTableFields()
}
},
selectSourceTable: ({ tableName }) => {
@@ -3156,7 +3356,29 @@ export const queryDatabaseLogic = kea<queryDatabaseLogicType>([
},
})),
subscriptions(({ actions, values }) => ({
+ // Hydrate fields for every visible "Loading..." placeholder. Covers expansion restored from
+ // persisted state and nodes that were expanded before the shallow schema arrived; the
+ // hydrate action itself dedupes tables that are already loading or settled.
displayedTreeData: (displayedTreeData: TreeDataItem[]) => {
+ const expanded = new Set(values.searchTerm ? values.expandedSearchFolders : values.expandedFolders)
+ const pendingTableNames = new Set<string>()
+ const collect = (nodes: TreeDataItem[]): void => {
+ for (const node of nodes) {
+ const record = node.record as Record<string, any> | undefined
+ if (record?.type === 'pending-fields' && record.pendingTableName) {
+ pendingTableNames.add(record.pendingTableName)
+ continue
+ }
+ if (node.children && expanded.has(node.id)) {
+ collect(node.children)
+ }
+ }
+ }
+ collect(displayedTreeData)
+ if (pendingTableNames.size > 0) {
+ actions.hydrateTableFields(Array.from(pendingTableNames))
+ }
+
if (values.searchTerm || !shouldUseDirectConnectionTree(values.connectionId)) {
return
}
diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx
index 27d218755c70..b33f656290a9 100644
--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx
@@ -690,10 +690,12 @@ export interface sqlEditorLogicActions {
args_0?:
| {
force?: boolean
+ shallow?: boolean
}
| undefined
) => {
force?: boolean
+ shallow?: boolean
} // databaseTableListLogic
resetConnectionScope: () => {
value: true
@@ -1173,6 +1175,20 @@ function releaseConnectionScope(tabId: string, scopedConnectionId: string | null
return scopedConnectionId !== null && ![...connectionScopeOwners.values()].includes(scopedConnectionId)
}
+// With the lazy schema flag on, the editor first loads only table names and metadata; the schema
+// tree hydrates each table's columns on expansion.
+function schemaLoadOptions(
+ featureFlags: FeatureFlagsSet,
+ force = false
+): { force?: boolean; shallow?: boolean } | undefined {
+ const shallow = !!featureFlags[FEATURE_FLAGS.SQL_EDITOR_LAZY_SCHEMA]
+ if (!shallow) {
+ // With the flag off, emit exactly the payloads this logic emitted before lazy loading.
+ return force ? { force } : undefined
+ }
+ return { force, shallow }
+}
+
export const sqlEditorLogic = kea<sqlEditorLogicType>([
path(['data-warehouse', 'editor', 'sqlEditorLogic']),
props({ mode: SQLEditorMode.FullScene } as SqlEditorLogicProps),
@@ -3048,7 +3064,7 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
cache.lastSelectedConnectionId = selectedConnectionId
claimConnectionScope(props.tabId, selectedConnectionId)
actions.setConnection(selectedConnectionId ?? null)
- actions.loadDatabase()
+ actions.loadDatabase(schemaLoadOptions(values.featureFlags))
if (selectedConnectionId) {
// Capability data must load wherever a connection is in play — including
// surfaces that never render the connection selector.
@@ -3316,7 +3332,7 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
) {
if (shouldSyncDatabaseConnection && !values.databaseLoading) {
actions.setConnection(expectedDatabaseConnectionId)
- actions.loadDatabase()
+ actions.loadDatabase(schemaLoadOptions(values.featureFlags))
}
return
}
@@ -3658,7 +3674,7 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
if (connectionIdFromHash === undefined && shouldSyncDatabaseConnection && !values.databaseLoading) {
actions.setConnection(expectedDatabaseConnectionId)
- actions.loadDatabase()
+ actions.loadDatabase(schemaLoadOptions(values.featureFlags))
}
},
})),
@@ -3867,7 +3883,7 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
// stuck true (a load that never settled), the plain guard would skip the reload and the
// editor would sit on "Loading..." forever. On remount we still need data, so force a
// fresh request to bypass any hung in-flight load.
- actions.loadDatabase(values.databaseLoading ? { force: true } : undefined)
+ actions.loadDatabase(schemaLoadOptions(values.featureFlags, values.databaseLoading))
}
}),
beforeUnmount(({ actions, values, cache, props }) => {
diff --git a/frontend/src/scenes/data-warehouse/expressionModalLogic.tsx b/frontend/src/scenes/data-warehouse/expressionModalLogic.tsx
index 7585d692d3f9..3ad71ccfa924 100644
--- a/frontend/src/scenes/data-warehouse/expressionModalLogic.tsx
+++ b/frontend/src/scenes/data-warehouse/expressionModalLogic.tsx
@@ -64,10 +64,12 @@ export interface expressionModalLogicActions {
args_0?:
| {
force?: boolean
+ shallow?: boolean
}
| undefined
) => {
force?: boolean
+ shallow?: boolean
} // databaseTableListLogic
closeExpressionModal: () => {
value: true
diff --git a/frontend/src/scenes/data-warehouse/scene/viewsTabLogic.ts b/frontend/src/scenes/data-warehouse/scene/viewsTabLogic.ts
index 5d4fdf80b5bc..7492f18ccc29 100644
--- a/frontend/src/scenes/data-warehouse/scene/viewsTabLogic.ts
+++ b/frontend/src/scenes/data-warehouse/scene/viewsTabLogic.ts
@@ -62,10 +62,12 @@ export interface viewsTabLogicActions {
args_0?:
| {
force?: boolean
+ shallow?: boolean
}
| undefined
) => {
force?: boolean
+ shallow?: boolean
} // databaseTableListLogic
closeAccessControlModal: () => {
value: true
diff --git a/frontend/src/scenes/data-warehouse/settings/dataWarehouseSettingsSceneLogic.ts b/frontend/src/scenes/data-warehouse/settings/dataWarehouseSettingsSceneLogic.ts
index 404c49b0267e..25e287eec0d6 100644
--- a/frontend/src/scenes/data-warehouse/settings/dataWarehouseSettingsSceneLogic.ts
+++ b/frontend/src/scenes/data-warehouse/settings/dataWarehouseSettingsSceneLogic.ts
@@ -108,14 +108,19 @@ export interface dataWarehouseSettingsSceneLogicActions {
types?: string[][]
}
} // dataWarehouseViewsLogic
+ ensureAllTableFields: () => {
+ value: true
+ } // databaseTableListLogic
loadDatabase: (
args_0?:
| {
force?: boolean
+ shallow?: boolean
}
| undefined
) => {
force?: boolean
+ shallow?: boolean
} // databaseTableListLogic
loadDatabaseFailure: (
error: string,
@@ -129,12 +134,14 @@ export interface dataWarehouseSettingsSceneLogicActions {
payload?:
| {
force?: boolean
+ shallow?: boolean
}
| undefined
) => {
database: Required<DatabaseSchemaQueryResponse> | null
payload?: {
force?: boolean
+ shallow?: boolean
}
} // databaseTableListLogic
refreshDatabaseSchema: () => {
@@ -233,7 +240,13 @@ export const dataWarehouseSettingsSceneLogic = kea<dataWarehouseSettingsSceneLog
dataWarehouseViewsLogic,
['deleteDataWarehouseSavedQuery', 'updateDataWarehouseSavedQuery', 'updateDataWarehouseSavedQuerySuccess'],
databaseTableListLogic,
- ['loadDatabase', 'refreshDatabaseSchema', 'loadDatabaseSuccess', 'loadDatabaseFailure'],
+ [
+ 'loadDatabase',
+ 'refreshDatabaseSchema',
+ 'loadDatabaseSuccess',
+ 'loadDatabaseFailure',
+ 'ensureAllTableFields',
+ ],
],
})),
actions(({ values }) => ({
@@ -507,6 +520,10 @@ export const dataWarehouseSettingsSceneLogic = kea<dataWarehouseSettingsSceneLog
afterMount(({ actions, values }) => {
if (!values.database && !values.databaseLoading) {
actions.loadDatabase()
+ } else {
+ // The store may hold a shallow (fields-less) schema left by the SQL editor; the schema
+ // editing panel and the taxonomic data warehouse groups need fields.
+ actions.ensureAllTableFields()
}
}),
])
diff --git a/frontend/src/scenes/data-warehouse/viewLinkLogic.tsx b/frontend/src/scenes/data-warehouse/viewLinkLogic.tsx
index 1ff52f591d7b..a9ff00fd5a0f 100644
--- a/frontend/src/scenes/data-warehouse/viewLinkLogic.tsx
+++ b/frontend/src/scenes/data-warehouse/viewLinkLogic.tsx
@@ -117,14 +117,19 @@ export interface viewLinkLogicValues {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface viewLinkLogicActions {
+ hydrateTableFields: (tableNames: string[]) => {
+ tableNames: string[]
+ } // databaseTableListLogic
loadDatabase: (
args_0?:
| {
force?: boolean
+ shallow?: boolean
}
| undefined
) => {
force?: boolean
+ shallow?: boolean
} // databaseTableListLogic
loadJoins: () => any // joinsLogic
autofillFieldName: (fieldName: string) => {
@@ -287,7 +292,7 @@ export const viewLinkLogic = kea<viewLinkLogicType>([
path(['scenes', 'data-warehouse', 'viewLinkLogic']),
connect(() => ({
values: [databaseTableListLogic, ['allTables']],
- actions: [databaseTableListLogic, ['loadDatabase'], joinsLogic, ['loadJoins']],
+ actions: [databaseTableListLogic, ['loadDatabase', 'hydrateTableFields'], joinsLogic, ['loadJoins']],
})),
actions(({ values }) => ({
selectJoiningTable: (selectedTableName: string) => ({ selectedTableName }),
@@ -530,10 +535,18 @@ export const viewLinkLogic = kea<viewLinkLogicType>([
listeners(({ actions, values }) => ({
toggleNewJoinModal: ({ join }) => {
actions.setViewLinkValues(join ?? NEW_VIEW_LINK)
+ const preselected = [join?.source_table_name, join?.joining_table_name].filter(Boolean) as string[]
+ if (preselected.length > 0) {
+ actions.hydrateTableFields(preselected)
+ }
actions.validateJoin()
},
toggleEditJoinModal: ({ join }) => {
actions.setViewLinkValues(join)
+ const joinTables = [join.source_table_name, join.joining_table_name].filter(Boolean) as string[]
+ if (joinTables.length > 0) {
+ actions.hydrateTableFields(joinTables)
+ }
actions.validateJoin()
},
setViewLinkValue: ({ name }) => {
@@ -543,12 +556,20 @@ export const viewLinkLogic = kea<viewLinkLogicType>([
actions.validateJoin()
}
},
- selectSourceTable: async () => {
+ selectSourceTable: async ({ selectedTableName }) => {
actions.setViewLinkValue('source_table_key', null)
+ if (selectedTableName) {
+ // The key picker lists this table's columns; with a lazy-loaded schema they may
+ // not be in the store yet.
+ actions.hydrateTableFields([selectedTableName])
+ }
actions.validateJoin()
},
selectJoiningTable: async ({ selectedTableName }) => {
actions.setViewLinkValue('joining_table_key', null)
+ if (selectedTableName) {
+ actions.hydrateTableFields([selectedTableName])
+ }
if (selectedTableName && !values.fieldNameTouched) {
actions.autofillFieldName(selectedTableName.replaceAll('.', '_'))
}
diff --git a/frontend/src/scenes/hog-functions/filters/HogFunctionFilters.tsx b/frontend/src/scenes/hog-functions/filters/HogFunctionFilters.tsx
index b45322680550..3486a8fb3915 100644
--- a/frontend/src/scenes/hog-functions/filters/HogFunctionFilters.tsx
+++ b/frontend/src/scenes/hog-functions/filters/HogFunctionFilters.tsx
@@ -119,10 +119,15 @@ export function HogFunctionFilters({
// The table matcher's column suggestions read from databaseTableListLogic, which isn't loaded
// automatically in this scene — kick it off when a warehouse table is the source.
const { dataWarehouseTables, dataWarehouseTablesMap } = useValues(databaseTableListLogic)
- const { loadDatabase } = useActions(databaseTableListLogic)
+ const { loadDatabase, ensureAllTableFields } = useActions(databaseTableListLogic)
useEffect(() => {
- if (isDataWarehouse && !dataWarehouseTables.length) {
- loadDatabase()
+ if (isDataWarehouse) {
+ if (!dataWarehouseTables.length) {
+ loadDatabase()
+ } else {
+ // The store may hold a shallow (fields-less) schema left by the SQL editor.
+ ensureAllTableFields()
+ }
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isDataWarehouse])
diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic.ts b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic.ts
index 0c2e3844226d..67751bb46961 100644
--- a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic.ts
+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic.ts
@@ -298,10 +298,12 @@ export interface marketingAnalyticsLogicActions {
args_0?:
| {
force?: boolean
+ shallow?: boolean
}
| undefined
) => {
force?: boolean
+ shallow?: boolean
} // sourceManagementLogic
loadSources: () => {
value: true
diff --git a/posthog/api/services/query.py b/posthog/api/services/query.py
index 3ad9a7482296..f31e5e77e31b 100644
--- a/posthog/api/services/query.py
+++ b/posthog/api/services/query.py
@@ -191,7 +191,12 @@ def process_database_schema_query(
modifiers=create_default_modifiers_for_team(team),
)
context = HogQLContext(team_id=team.pk, team=team, database=database, user=user)
- serialized_tables = database.serialize(context, include_hidden_posthog_tables=True)
+ serialized_tables = database.serialize(
+ context,
+ include_only=set(query.tables) if query.tables else None,
+ include_hidden_posthog_tables=True,
+ include_fields=query.includeFields is not False,
+ )
except (APIException, ExposedHogQLError, ResolutionError, UserAccessControlError):
# These already carry an actionable message, and the query view maps them to a 4xx.
raise
diff --git a/posthog/api/test/test_query_service.py b/posthog/api/test/test_query_service.py
index b471d4c6df35..45927fd0b4cc 100644
--- a/posthog/api/test/test_query_service.py
+++ b/posthog/api/test/test_query_service.py
@@ -153,6 +153,22 @@ class TestQueryService(APIBaseTest):
joining_table_name__in={"selected_table", "selected_table_2"},
)
+ def test_database_schema_query_supports_shallow_and_filtered_modes(self):
+ full = cast(DatabaseSchemaQueryResponse, process_query_model(self.team, DatabaseSchemaQuery()))
+ shallow = cast(
+ DatabaseSchemaQueryResponse, process_query_model(self.team, DatabaseSchemaQuery(includeFields=False))
+ )
+ filtered = cast(
+ DatabaseSchemaQueryResponse, process_query_model(self.team, DatabaseSchemaQuery(tables=["events"]))
+ )
+
+ assert set(shallow.tables.keys()) == set(full.tables.keys())
+ assert all(table.fields == {} for table in shallow.tables.values())
+ assert full.tables["events"].fields != {}
+
+ assert set(filtered.tables.keys()) == {"events"}
+ assert filtered.tables["events"] == full.tables["events"]
+
@parameterized.expand(
[
("resolve", "resolve_database_for_connection"),
diff --git a/posthog/hogql/database/database.py b/posthog/hogql/database/database.py
index 9c521ac5e100..d44ef6f1def4 100644
--- a/posthog/hogql/database/database.py
+++ b/posthog/hogql/database/database.py
@@ -928,6 +928,7 @@ class Database(BaseModel):
context: HogQLContext,
include_only: set[str] | None = None,
include_hidden_posthog_tables: bool = False,
+ include_fields: bool = True,
) -> dict[str, DatabaseSchemaTable]:
from django.db.models import Prefetch # noqa: PLC0415
@@ -968,13 +969,15 @@ class Database(BaseModel):
if include_only and table_name not in include_only:
continue
- field_input: dict[str, Any] = {}
- table = self.get_table(table_name)
- if isinstance(table, Table):
- field_input = _schema_field_input(table)
+ fields_dict: dict[str, DatabaseSchemaField] = {}
+ if include_fields:
+ field_input: dict[str, Any] = {}
+ table = self.get_table(table_name)
+ if isinstance(table, Table):
+ field_input = _schema_field_input(table)
- fields = serialize_fields(field_input, context, table_name.split("."), table_type="posthog")
- fields_dict = {field.name: field for field in fields}
+ fields = serialize_fields(field_input, context, table_name.split("."), table_type="posthog")
+ fields_dict = {field.name: field for field in fields}
tables[table_name] = DatabaseSchemaPostHogTable(fields=fields_dict, id=table_name, name=table_name)
# System tables
@@ -983,13 +986,15 @@ class Database(BaseModel):
if include_only and table_key not in include_only:
continue
- system_field_input: dict[str, Any] = {}
- table = self.get_table(table_key)
- if isinstance(table, Table):
- system_field_input = _schema_field_input(table)
+ fields_dict = {}
+ if include_fields:
+ system_field_input: dict[str, Any] = {}
+ table = self.get_table(table_key)
+ if isinstance(table, Table):
+ system_field_input = _schema_field_input(table)
- fields = serialize_fields(system_field_input, context, table_key.split("."), table_type="posthog")
- fields_dict = {field.name: field for field in fields}
+ fields = serialize_fields(system_field_input, context, table_key.split("."), table_type="posthog")
+ fields_dict = {field.name: field for field in fields}
tables[table_key] = DatabaseSchemaSystemTable(fields=fields_dict, id=table_key, name=table_key)
# Data Warehouse Tables and Views - Fetch all related data in one go
@@ -1081,15 +1086,17 @@ class Database(BaseModel):
continue
try:
- field_input = {}
- table = self.get_table(table_key)
- if isinstance(table, Table):
- field_input = table.fields
+ fields_dict = {}
+ if include_fields:
+ field_input = {}
+ table = self.get_table(table_key)
+ if isinstance(table, Table):
+ field_input = table.fields
- fields = serialize_fields(
- field_input, context, table_key.split("."), warehouse_table.columns, table_type="external"
- )
- fields_dict = {field.name: field for field in fields}
+ fields = serialize_fields(
+ field_input, context, table_key.split("."), warehouse_table.columns, table_type="external"
+ )
+ fields_dict = {field.name: field for field in fields}
# The table is also queryable by its raw underscore name, which is registered
# separately from the dotted `table_key`. Surface it so search matches either form.
@@ -1162,9 +1169,12 @@ class Database(BaseModel):
# Not built for this connection (unusable columns, or access-denied).
continue
- fields = serialize_fields(table.fields, context, table_key.split("."), table_type="external")
+ dual_fields_dict: dict[str, DatabaseSchemaField] = {}
+ if include_fields:
+ fields = serialize_fields(table.fields, context, table_key.split("."), table_type="external")
+ dual_fields_dict = {field.name: field for field in fields}
tables[table_key] = DatabaseSchemaDataWarehouseTable(
- fields={field.name: field for field in fields},
+ fields=dual_fields_dict,
id=str(schema_row.id),
name=table_key,
schema=DatabaseSchemaSchema(
@@ -1199,8 +1209,10 @@ class Database(BaseModel):
except QueryError:
continue
- fields = serialize_fields(view.fields, context, view_name.split("."), table_type="external")
- fields_dict = {field.name: field for field in fields}
+ fields_dict = {}
+ if include_fields:
+ fields = serialize_fields(view.fields, context, view_name.split("."), table_type="external")
+ fields_dict = {field.name: field for field in fields}
if isinstance(view, RevenueAnalyticsBaseView):
tables[view_name] = DatabaseSchemaManagedViewTable(
diff --git a/posthog/hogql/database/test/test_database.py b/posthog/hogql/database/test/test_database.py
index 9472296cdd73..186198f67f3e 100644
--- a/posthog/hogql/database/test/test_database.py
+++ b/posthog/hogql/database/test/test_database.py
@@ -352,6 +352,62 @@ class TestDatabase(BaseTest, QueryMatchingTest):
for table_name in posthog_table_names:
assert serialized_database.get(table_name) is not None
+ def test_serialize_database_without_fields_matches_full_metadata(self):
+ credential = DataWarehouseCredential.objects.create(access_key="blah", access_secret="blah", team=self.team)
+ warehouse_table = DataWarehouseTable.objects.create(
+ name="warehouse_table",
+ format="Parquet",
+ team=self.team,
+ credential=credential,
+ url_pattern="https://bucket.s3/data/*",
+ columns={"id": {"hogql": "StringDatabaseField", "clickhouse": "Nullable(String)", "schema_valid": True}},
+ row_count=42,
+ )
+ DataWarehouseSavedQuery.objects.create(
+ team=self.team,
+ name="warehouse_view",
+ query={"query": "SELECT id FROM warehouse_table"},
+ columns={"id": "String"},
+ table=warehouse_table,
+ status=DataWarehouseSavedQuery.Status.COMPLETED,
+ )
+
+ database = Database.create_for(team=self.team, user=self.user)
+ context = HogQLContext(team_id=self.team.pk, database=database)
+ full = database.serialize(context, include_hidden_posthog_tables=True)
+ shallow = database.serialize(context, include_hidden_posthog_tables=True, include_fields=False)
+
+ assert set(shallow.keys()) == set(full.keys())
+ assert "warehouse_table" in shallow
+ assert "warehouse_view" in shallow
+ for table_name, shallow_table in shallow.items():
+ assert shallow_table.fields == {}, table_name
+ assert shallow_table.model_dump(exclude={"fields"}) == full[table_name].model_dump(exclude={"fields"}), (
+ table_name
+ )
+
+ def test_serialize_database_include_only_returns_same_fields_as_full_serialization(self):
+ credential = DataWarehouseCredential.objects.create(access_key="blah", access_secret="blah", team=self.team)
+ DataWarehouseTable.objects.create(
+ name="warehouse_table",
+ format="Parquet",
+ team=self.team,
+ credential=credential,
+ url_pattern="https://bucket.s3/data/*",
+ columns={"id": {"hogql": "StringDatabaseField", "clickhouse": "Nullable(String)", "schema_valid": True}},
+ )
+
+ database = Database.create_for(team=self.team, user=self.user)
+ context = HogQLContext(team_id=self.team.pk, database=database)
+ full = database.serialize(context, include_hidden_posthog_tables=True)
+ subset = database.serialize(
+ context, include_only={"events", "warehouse_table"}, include_hidden_posthog_tables=True
+ )
+
+ assert set(subset.keys()) == {"events", "warehouse_table"}
+ for table_name, subset_table in subset.items():
+ assert subset_table == full[table_name], table_name
+
def test_apply_schema_scope_removes_lazy_joins_to_hidden_direct_tables(self):
database = Database()
events = PostgresTable(
diff --git a/posthog/hogql/database/test/test_database_schema_payload.py b/posthog/hogql/database/test/test_database_schema_payload.py
new file mode 100644
index 000000000000..2114846fecf7
--- /dev/null
+++ b/posthog/hogql/database/test/test_database_schema_payload.py
@@ -0,0 +1,64 @@
+import json
+import time
+
+from posthog.test.base import BaseTest
+
+from posthog.hogql.context import HogQLContext
+from posthog.hogql.database.database import Database
+
+from products.warehouse_sources.backend.facade.models import DataWarehouseCredential, DataWarehouseTable
+
+TABLE_COUNT = 40
+COLUMN_COUNT = 120
+
+
+class TestDatabaseSchemaPayload(BaseTest):
+ def test_shallow_serialization_collapses_payload_for_large_schemas(self):
+ # Reproduces the SQL editor lag: a project with many warehouse tables/columns makes the
+ # full DatabaseSchemaQuery payload huge. Run with `pytest -s` to see the timings.
+ credential = DataWarehouseCredential.objects.create(access_key="key", access_secret="secret", team=self.team)
+ columns = {
+ f"column_{i}": {"hogql": "StringDatabaseField", "clickhouse": "Nullable(String)", "schema_valid": True}
+ for i in range(COLUMN_COUNT)
+ }
+ DataWarehouseTable.objects.bulk_create(
+ DataWarehouseTable(
+ name=f"big_table_{i}",
+ format="Parquet",
+ team=self.team,
+ credential=credential,
+ url_pattern=f"https://bucket.s3/data_{i}/*",
+ columns=columns,
+ )
+ for i in range(TABLE_COUNT)
+ )
+
+ database = Database.create_for(team=self.team, user=self.user)
+ context = HogQLContext(team_id=self.team.pk, database=database)
+
+ start = time.perf_counter()
+ full = database.serialize(context, include_hidden_posthog_tables=True)
+ full_seconds = time.perf_counter() - start
+
+ start = time.perf_counter()
+ shallow = database.serialize(context, include_hidden_posthog_tables=True, include_fields=False)
+ shallow_seconds = time.perf_counter() - start
+
+ start = time.perf_counter()
+ one_table = database.serialize(context, include_only={"big_table_0"}, include_hidden_posthog_tables=True)
+ one_table_seconds = time.perf_counter() - start
+
+ full_bytes = len(json.dumps({name: table.model_dump() for name, table in full.items()}))
+ shallow_bytes = len(json.dumps({name: table.model_dump() for name, table in shallow.items()}))
+ one_table_bytes = len(json.dumps({name: table.model_dump() for name, table in one_table.items()}))
+
+ print( # noqa: T201
+ f"\nDatabaseSchemaQuery payload for {TABLE_COUNT} warehouse tables x {COLUMN_COUNT} columns:"
+ f"\n full: {full_bytes / 1024:8.1f} KB in {full_seconds * 1000:7.1f} ms"
+ f"\n shallow: {shallow_bytes / 1024:8.1f} KB in {shallow_seconds * 1000:7.1f} ms"
+ f"\n one table: {one_table_bytes / 1024:8.1f} KB in {one_table_seconds * 1000:7.1f} ms"
+ )
+
+ assert set(shallow.keys()) == set(full.keys())
+ assert shallow_bytes < full_bytes / 10
+ assert one_table_bytes < full_bytes / 10
diff --git a/posthog/schema.py b/posthog/schema.py
index 1bf8e899f6a7..7ef647c87269 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -28042,9 +28042,20 @@ class DatabaseSchemaQuery(BaseModel):
default=None,
description="Optional direct external data source id for schema introspection",
)
+ includeFields: bool | None = Field(
+ default=None,
+ description=("When false, skip serializing each table's fields (`fields` comes back empty). Defaults to true."),
+ )
kind: Literal["DatabaseSchemaQuery"] = "DatabaseSchemaQuery"
modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")
response: DatabaseSchemaQueryResponse | None = None
+ tables: list[str] | None = Field(
+ default=None,
+ description=(
+ "Only serialize these tables (keys as returned in the response, e.g."
+ " `events` or `zendesk.groups`). Omit for all tables."
+ ),
+ )
tags: QueryLogTags | None = None
version: float | None = Field(default=None, description="version of the node, used for schema migrations")
diff --git a/products/customer_analytics/frontend/components/Accounts/accountsColumnConfigLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountsColumnConfigLogic.ts
index 5d72b8c4d951..f8deddb83d62 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountsColumnConfigLogic.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountsColumnConfigLogic.ts
@@ -426,14 +426,19 @@ export interface accountsColumnConfigLogicValues {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface accountsColumnConfigLogicActions {
+ ensureAllTableFields: () => {
+ value: true
+ } // databaseTableListLogic
loadDatabase: (
args_0?:
| {
force?: boolean
+ shallow?: boolean
}
| undefined
) => {
force?: boolean
+ shallow?: boolean
} // databaseTableListLogic
loadJoins: () => any // joinsLogic
addSqlExpression: () => {
@@ -604,7 +609,7 @@ export const accountsColumnConfigLogic = kea<accountsColumnConfigLogicType>([
joinsLogic,
['joins as warehouseJoins', 'joinsLoading as warehouseJoinsLoading'],
],
- actions: [databaseTableListLogic, ['loadDatabase'], joinsLogic, ['loadJoins']],
+ actions: [databaseTableListLogic, ['loadDatabase', 'ensureAllTableFields'], joinsLogic, ['loadJoins']],
// Keep propertyDefinitionsModel mounted so the seeded custom-property definitions
// (see loadCustomPropertyDefinitionsSuccess) survive until the filter UI reads them.
logic: [propertyDefinitionsModel],
@@ -947,6 +952,10 @@ export const accountsColumnConfigLogic = kea<accountsColumnConfigLogicType>([
// databaseTableListLogic dedupes concurrent calls internally.
if (!values.allTablesMap || Object.keys(values.allTablesMap).length === 0) {
actions.loadDatabase()
+ } else {
+ // The store may hold a shallow (fields-less) schema left by the SQL editor; the
+ // column picker needs every table's fields.
+ actions.ensureAllTableFields()
}
actions.loadCustomPropertyDefinitions()
actions.loadRelationshipDefinitions()
diff --git a/products/data_catalog/frontend/certificationsLogic.tsx b/products/data_catalog/frontend/certificationsLogic.tsx
index d1e36bb1da37..07a483f29146 100644
--- a/products/data_catalog/frontend/certificationsLogic.tsx
+++ b/products/data_catalog/frontend/certificationsLogic.tsx
@@ -72,10 +72,12 @@ export interface certificationsLogicActions {
args_0?:
| {
force?: boolean
+ shallow?: boolean
}
| undefined
) => {
force?: boolean
+ shallow?: boolean
} // databaseTableListLogic
certifyCertification: (id: string) => {
id: string
diff --git a/products/data_warehouse/frontend/scenes/NewSourceScene/fileUploadSourceLogic.tsx b/products/data_warehouse/frontend/scenes/NewSourceScene/fileUploadSourceLogic.tsx
index e1839e33398a..71665774d363 100644
--- a/products/data_warehouse/frontend/scenes/NewSourceScene/fileUploadSourceLogic.tsx
+++ b/products/data_warehouse/frontend/scenes/NewSourceScene/fileUploadSourceLogic.tsx
@@ -148,10 +148,12 @@ export interface fileUploadSourceLogicActions {
args_0?:
| {
force?: boolean
+ shallow?: boolean
}
| undefined
) => {
force?: boolean
+ shallow?: boolean
} // databaseTableListLogic
resetFileUpload: (values?: FileUploadForm) => {
values?: FileUploadForm
diff --git a/products/data_warehouse/frontend/scenes/NewSourceScene/selfManagedSourceLogic.tsx b/products/data_warehouse/frontend/scenes/NewSourceScene/selfManagedSourceLogic.tsx
index dea597da9459..b3bb502de1ab 100644
--- a/products/data_warehouse/frontend/scenes/NewSourceScene/selfManagedSourceLogic.tsx
+++ b/products/data_warehouse/frontend/scenes/NewSourceScene/selfManagedSourceLogic.tsx
@@ -108,10 +108,12 @@ export interface selfManagedSourceLogicActions {
args_0?:
| {
force?: boolean
+ shallow?: boolean
}
| undefined
) => {
force?: boolean
+ shallow?: boolean
} // databaseTableListLogic
addConditionSet: () => {
value: true
diff --git a/products/data_warehouse/frontend/shared/logics/joinsLogic.ts b/products/data_warehouse/frontend/shared/logics/joinsLogic.ts
index 711183d1f5d7..47c0246d04a8 100644
--- a/products/data_warehouse/frontend/shared/logics/joinsLogic.ts
+++ b/products/data_warehouse/frontend/shared/logics/joinsLogic.ts
@@ -1,4 +1,4 @@
-import { MakeLogicType, afterMount, connect, kea, path, selectors } from 'kea'
+import { MakeLogicType, afterMount, connect, kea, listeners, path, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import api from 'lib/api'
@@ -34,6 +34,9 @@ export interface joinsLogicValues {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface joinsLogicActions {
+ hydrateTableFields: (tableNames: string[]) => {
+ tableNames: string[]
+ } // databaseTableListLogic
loadJoins: () => any
loadJoinsFailure: (
error: string,
@@ -88,6 +91,19 @@ export const joinsLogic = kea<joinsLogicType>([
}),
connect(() => ({
values: [databaseTableListLogic, ['allTablesMap']],
+ actions: [databaseTableListLogic, ['hydrateTableFields']],
+ })),
+ listeners(({ actions, values }) => ({
+ loadJoinsSuccess: () => {
+ // `columnsJoinedToPersons` reads the joined tables' fields, which a shallow (lazy)
+ // schema load leaves empty; request them explicitly.
+ const joinedTableNames = values.personTableJoins
+ .map((join) => join.joining_table_name)
+ .filter((name): name is string => !!name)
+ if (joinedTableNames.length > 0) {
+ actions.hydrateTableFields(joinedTableNames)
+ }
+ },
})),
selectors({
personTableJoins: [
diff --git a/products/data_warehouse/frontend/shared/logics/sourceManagementLogic.ts b/products/data_warehouse/frontend/shared/logics/sourceManagementLogic.ts
index a7f927a16ad0..e20cd5d8e37e 100644
--- a/products/data_warehouse/frontend/shared/logics/sourceManagementLogic.ts
+++ b/products/data_warehouse/frontend/shared/logics/sourceManagementLogic.ts
@@ -81,14 +81,19 @@ export interface sourceManagementLogicValues {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface sourceManagementLogicActions {
+ ensureAllTableFields: () => {
+ value: true
+ } // databaseTableListLogic
loadDatabase: (
args_0?:
| {
force?: boolean
+ shallow?: boolean
}
| undefined
) => {
force?: boolean
+ shallow?: boolean
} // databaseTableListLogic
loadJoins: () => any // joinsLogic
loadSources: () => {
@@ -229,7 +234,7 @@ export const sourceManagementLogic = kea<sourceManagementLogicType>([
],
actions: [
databaseTableListLogic,
- ['loadDatabase'],
+ ['ensureAllTableFields', 'loadDatabase'],
joinsLogic,
['loadJoins'],
sourcesDataLogic,
@@ -548,8 +553,12 @@ export const sourceManagementLogic = kea<sourceManagementLogicType>([
},
})),
afterMount(({ actions, values }) => {
- if (!values.database) {
- actions.loadDatabase()
+ if (!values.databaseLoading) {
+ if (!values.database) {
+ actions.loadDatabase()
+ } else {
+ actions.ensureAllTableFields()
+ }
}
actions.loadSources()
}),
diff --git a/products/data_warehouse/frontend/shared/logics/tests/sourceManagementLogic.test.ts b/products/data_warehouse/frontend/shared/logics/tests/sourceManagementLogic.test.ts
index 65291f5d6cc3..1ad4526c61ab 100644
--- a/products/data_warehouse/frontend/shared/logics/tests/sourceManagementLogic.test.ts
+++ b/products/data_warehouse/frontend/shared/logics/tests/sourceManagementLogic.test.ts
@@ -148,4 +148,24 @@ describe('sourceManagementLogic', () => {
],
})
})
+
+ it('does not supersede an in-flight shallow schema load when mounted', async () => {
+ let resolveShallowLoad: ((value: DatabaseSchemaQueryResponse) => void) | undefined
+ ;(performQuery as jest.Mock).mockImplementationOnce(
+ () =>
+ new Promise<DatabaseSchemaQueryResponse>((resolve) => {
+ resolveShallowLoad = resolve
+ })
+ )
+ databaseLogic.mount()
+
+ const shallowLoad = databaseLogic.asyncActions.loadDatabase({ shallow: true })
+ logic.mount()
+
+ expect(performQuery).toHaveBeenCalledTimes(1)
+ expect(performQuery).toHaveBeenCalledWith(expect.objectContaining({ includeFields: false }))
+
+ resolveShallowLoad?.({ tables: {}, joins: [] } as DatabaseSchemaQueryResponse)
+ await shallowLoad
+ })
})
diff --git a/products/workflows/frontend/Workflows/hogflows/registry/triggers/data_warehouse_table.tsx b/products/workflows/frontend/Workflows/hogflows/registry/triggers/data_warehouse_table.tsx
index ab56a958d52b..469b7896bac9 100644
--- a/products/workflows/frontend/Workflows/hogflows/registry/triggers/data_warehouse_table.tsx
+++ b/products/workflows/frontend/Workflows/hogflows/registry/triggers/data_warehouse_table.tsx
@@ -36,7 +36,7 @@ function StepTriggerConfigurationDataWarehouseTable({ node }: { node: any }): JS
const { actionValidationErrorsById } = useValues(workflowLogic)
const { externalDataSourceTables, dataWarehouseTables, dataWarehouseTablesMap, databaseLoading } =
useValues(databaseTableListLogic)
- const { loadDatabase } = useActions(databaseTableListLogic)
+ const { loadDatabase, ensureAllTableFields } = useActions(databaseTableListLogic)
useEffect(() => {
// The list isn't loaded automatically on mount, so kick it off when the panel opens.
@@ -44,6 +44,9 @@ function StepTriggerConfigurationDataWarehouseTable({ node }: { node: any }): JS
// self-managed tables (which have no source) doesn't refetch on every mount.
if (!dataWarehouseTables.length) {
loadDatabase()
+ } else {
+ // The store may hold a shallow (fields-less) schema left by the SQL editor.
+ ensureAllTableFields()
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 085195033f69..93467a1c60c5 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -19804,10 +19804,14 @@ export namespace Schemas {
export interface DatabaseSchemaQuery {
/** Optional direct external data source id for schema introspection */
connectionId?: string | null;
+ /** When false, skip serializing each table's fields (`fields` comes back empty). Defaults to true. */
+ includeFields?: boolean | null;
kind?: 'DatabaseSchemaQuery';
/** Modifiers used when performing the query */
modifiers?: HogQLQueryModifiers | null;
response?: DatabaseSchemaQueryResponse | null;
+ /** Only serialize these tables (keys as returned in the response, e.g. `events` or `zendesk.groups`). Omit for all tables. */
+ tables?: string[] | null;
tags?: QueryLogTags | null;
/** version of the node, used for schema migrations */
version?: number | null;