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.

fix(data-warehouse): show native trino schemas in sql editor (#121756)

Eric Duong59715f6e3603
diff --git a/docs/internal/managed-warehouse-sql-editor.md b/docs/internal/managed-warehouse-sql-editor.md
index 2e7a5240a2bd..cb6d064cca18 100644
--- a/docs/internal/managed-warehouse-sql-editor.md
+++ b/docs/internal/managed-warehouse-sql-editor.md
@@ -49,6 +49,8 @@ If Redis is unavailable, SQL editor queries and managed warehouse schema discove
## Hosted Trino opt-in
+Selecting **PostHog (Trino)** loads the warehouse catalog into a schema/table tree, including columns on expansion. The catalog is discovered with the same user credential and access checks as native Trino queries. It does not include the default PostHog catalog or saved-query folders. Switching back to **PostHog (ClickHouse)** restores the default catalog. Discovery failures show a retry action instead of falling back to PostHog tables.
+
The same `managed-warehouse-trino-query` organization feature flag adds **PostHog (Trino)** directly below **PostHog (ClickHouse)** in the SQL editor connection selector. The default PostHog target remains unchanged. The backend checks the same flag before execution and cache reads; selecting the target in a URL does not grant access.
While this flag is enabled, the selector hides **PostHog (Managed warehouse)** from the menu so the built-in choices are ClickHouse and Trino. Existing queries that select the managed connection retain their connection ID, label and execution behavior. The managed option returns when the flag is disabled. Ordinary external connections remain visible.
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 3665f8af3657..77aaf7a9162d 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -10395,9 +10395,9 @@ snapshots:
scenes-app-data-warehouse-sql-editor--harness-logo-in-results--light:
hash: v1.k794b7964.261adb2063efa109811c70908e6d117f1efa1229135bcd341ec2da3507b5975b.tvMMteHD7B5av-EjfaSoJx8R3FPAPozw8oL3Ur4_lM4
scenes-app-data-warehouse-sql-editor--hosted-trino--dark:
- hash: v1.k794b7964.9c5c2408b68039d1989e4b7d52a787ba6739326a0207118bed07db27c6385eda.slBWrouzz0S3bARV3vpB-WyUyyu4o7c3oCcvLPi-8kw
+ hash: v1.k794b7964.ed1e698c1e589fef66b1788f5ce8144a60e3dd45d2f4f75b5ba4035379eb90ed.CQYsVP8IhyvD6ayH0_G6E-lbEDtJL15sNlk9tr3X94Q
scenes-app-data-warehouse-sql-editor--hosted-trino--light:
- hash: v1.k794b7964.edeb19cea3ae7e50344b0df94be3e99cae5eb79d315dfd30d78bc8b3843410b8.du5LaVfvGqlWPkWOgYtB_Dp27ltGmpj6p1pvOm0vM08
+ hash: v1.k794b7964.647221a6ff5285e22a729959258f9080f822b8b637fb9e356d64858ffc810297.xDMwpQ08PB4xYTX3ilprjooK9Q-2nzPa1Kv2Sx9V4sg
scenes-app-data-warehouse-sql-editor--lazy-schema--dark:
hash: v1.k794b7964.520af6c94de8ab081cff352b32dbee68c1054c8fdc6632a87bcecccaf497cf5d.SBsaeAFwZNnQLj-vhwcaUBLbOT1r7VTPn8dgApUR_Mw
scenes-app-data-warehouse-sql-editor--lazy-schema--light:
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index 8948f6814fd5..f872347a4720 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -21345,6 +21345,11 @@
"description": "Optional direct external data source id for schema introspection",
"type": "string"
},
+ "executionTarget": {
+ "description": "Select the native managed Trino catalog instead of the default PostHog catalog.",
+ "enum": ["default", "managed_trino"],
+ "type": "string"
+ },
"includeFields": {
"description": "When false, skip serializing each table's fields (`fields` comes back empty). Defaults to true.",
"type": "boolean"
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index 096061c4af79..1cc99f7d43ef 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -6716,6 +6716,8 @@ export interface DatabaseSchemaQueryResponse {
export interface DatabaseSchemaQuery extends DataNode<DatabaseSchemaQueryResponse> {
kind: NodeKind.DatabaseSchemaQuery
+ /** Select the native managed Trino catalog instead of the default PostHog catalog. */
+ executionTarget?: 'default' | 'managed_trino'
/** 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. */
diff --git a/frontend/src/scenes/data-management/database/databaseTableListLogic.test.ts b/frontend/src/scenes/data-management/database/databaseTableListLogic.test.ts
index b627993ad2bf..3119eeac302a 100644
--- a/frontend/src/scenes/data-management/database/databaseTableListLogic.test.ts
+++ b/frontend/src/scenes/data-management/database/databaseTableListLogic.test.ts
@@ -6,7 +6,7 @@ import { urls } from 'scenes/urls'
import { performQuery } from '~/queries/query'
import { initKeaTests } from '~/test/init'
-import { databaseTableListLogic } from './databaseTableListLogic'
+import { MANAGED_TRINO_SCHEMA_SCOPE, databaseTableListLogic } from './databaseTableListLogic'
jest.mock('~/queries/query')
@@ -159,57 +159,63 @@ describe('databaseTableListLogic', () => {
expect(logic.values.allTables.map((table) => table.name)).toEqual(['events'])
})
- it('does not let a stale schema response overwrite the selected connection schema', async () => {
- let resolvePosthogQuery:
- | ((value: { tables: Record<string, { name: string; type: 'posthog' }>; joins: never[] }) => void)
- | undefined
- let resolveDirectQuery:
- | ((value: { tables: Record<string, { name: string; type: 'data_warehouse' }>; joins: never[] }) => void)
- | undefined
+ it.each(['conn-123', MANAGED_TRINO_SCHEMA_SCOPE])(
+ 'discards stale default schema responses after selecting %s',
+ async (scope) => {
+ let resolvePosthogQuery:
+ | ((value: { tables: Record<string, { name: string; type: 'posthog' }>; joins: never[] }) => void)
+ | undefined
+ let resolveDirectQuery:
+ | ((value: {
+ tables: Record<string, { name: string; type: 'data_warehouse' }>
+ joins: never[]
+ }) => void)
+ | undefined
- ;(performQuery as jest.Mock)
- .mockImplementationOnce(
- () =>
- new Promise((resolve) => {
- resolvePosthogQuery = resolve
- })
- )
- .mockImplementationOnce(
- () =>
- new Promise((resolve) => {
- resolveDirectQuery = resolve
- })
- )
+ ;(performQuery as jest.Mock)
+ .mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ resolvePosthogQuery = resolve
+ })
+ )
+ .mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ resolveDirectQuery = resolve
+ })
+ )
- logic = databaseTableListLogic()
- logic.mount()
+ logic = databaseTableListLogic()
+ logic.mount()
- const posthogRequest = logic.asyncActions.loadDatabase()
+ const posthogRequest = logic.asyncActions.loadDatabase()
- logic.actions.setConnection('conn-123')
- const directRequest = logic.asyncActions.loadDatabase()
+ logic.actions.setConnection(scope)
+ const directRequest = logic.asyncActions.loadDatabase()
- resolveDirectQuery?.({
- tables: {
- ducklake_accounts: { name: 'ducklake_accounts', type: 'data_warehouse' },
- },
- joins: [],
- })
- await directRequest
+ resolveDirectQuery?.({
+ tables: {
+ ducklake_accounts: { name: 'ducklake_accounts', type: 'data_warehouse' },
+ },
+ joins: [],
+ })
+ await directRequest
- expect(logic.values.allTables.map((table) => table.name)).toEqual(['ducklake_accounts'])
+ expect(logic.values.allTables.map((table) => table.name)).toEqual(['ducklake_accounts'])
- resolvePosthogQuery?.({
- tables: {
- events: { name: 'events', type: 'posthog' },
- },
- joins: [],
- })
- await posthogRequest
+ resolvePosthogQuery?.({
+ tables: {
+ events: { name: 'events', type: 'posthog' },
+ },
+ joins: [],
+ })
+ await posthogRequest
- expect(logic.values.connectionId).toEqual('conn-123')
- expect(logic.values.allTables.map((table) => table.name)).toEqual(['ducklake_accounts'])
- })
+ expect(logic.values.connectionId).toEqual(scope)
+ expect(logic.values.allTables.map((table) => table.name)).toEqual(['ducklake_accounts'])
+ }
+ )
describe('lazy schema loading', () => {
const shallowTables = {
@@ -398,4 +404,43 @@ describe('databaseTableListLogic', () => {
expect((performQuery as jest.Mock).mock.calls[1][0].includeFields).toBeUndefined()
})
})
+ it('keeps native Trino scope when loading, hydrating, and refreshing its catalog', async () => {
+ logic = databaseTableListLogic()
+ logic.mount()
+ logic.actions.setConnection(MANAGED_TRINO_SCHEMA_SCOPE)
+ ;(performQuery as jest.Mock).mockResolvedValueOnce({
+ tables: {
+ 'analytics.orders': {
+ id: 'analytics.orders',
+ name: 'analytics.orders',
+ type: 'data_warehouse',
+ fields: {},
+ },
+ },
+ joins: [],
+ })
+ await logic.asyncActions.loadDatabase({ shallow: true })
+ expect(performQuery).toHaveBeenLastCalledWith(
+ expect.objectContaining({
+ executionTarget: 'managed_trino',
+ includeFields: false,
+ })
+ )
+ expect((performQuery as jest.Mock).mock.lastCall[0].connectionId).toBeUndefined()
+ logic.actions.hydrateTableFields(['analytics.orders'])
+ await expectLogic(logic).toFinishAllListeners()
+ expect(performQuery).toHaveBeenLastCalledWith(
+ expect.objectContaining({
+ executionTarget: 'managed_trino',
+ tables: ['analytics.orders'],
+ })
+ )
+ logic.actions.refreshDatabaseSchema()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(performQuery).toHaveBeenLastCalledWith(expect.objectContaining({ executionTarget: 'managed_trino' }))
+ logic.actions.resetConnectionScope()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(performQuery).toHaveBeenLastCalledWith(expect.objectContaining({ connectionId: undefined }))
+ expect((performQuery as jest.Mock).mock.lastCall[0].executionTarget).toBeUndefined()
+ })
})
diff --git a/frontend/src/scenes/data-management/database/databaseTableListLogic.ts b/frontend/src/scenes/data-management/database/databaseTableListLogic.ts
index ea1f4749b129..82b5682da323 100644
--- a/frontend/src/scenes/data-management/database/databaseTableListLogic.ts
+++ b/frontend/src/scenes/data-management/database/databaseTableListLogic.ts
@@ -18,6 +18,13 @@ import { setLatestVersionsOnQuery } from '~/queries/utils'
import { parseEndpointModelName } from 'products/data_modeling/frontend/endpointModelName'
+export const MANAGED_TRINO_SCHEMA_SCOPE = 'managed_trino'
+
+export const getDatabaseSchemaQueryScope = (
+ scope: string | undefined
+): Pick<DatabaseSchemaQuery, 'connectionId' | 'executionTarget'> =>
+ scope === MANAGED_TRINO_SCHEMA_SCOPE ? { executionTarget: 'managed_trino' } : { connectionId: scope }
+
const toMapByName = <T extends { name: string }>(items: T[]): Record<string, T> =>
items.reduce(
(acc, cur) => {
@@ -254,7 +261,7 @@ export const databaseTableListLogic = kea<databaseTableListLogicType>([
const request = performQuery(
setLatestVersionsOnQuery({
kind: NodeKind.DatabaseSchemaQuery,
- connectionId: requestConnectionId,
+ ...getDatabaseSchemaQueryScope(requestConnectionId),
includeFields: shallow ? false : undefined,
}) as DatabaseSchemaQuery
)
@@ -569,7 +576,7 @@ export const databaseTableListLogic = kea<databaseTableListLogicType>([
const response = await performQuery(
setLatestVersionsOnQuery({
kind: NodeKind.DatabaseSchemaQuery,
- connectionId: requestConnectionId,
+ ...getDatabaseSchemaQueryScope(requestConnectionId),
tables: toLoad,
}) as DatabaseSchemaQuery
)
diff --git a/frontend/src/scenes/data-warehouse/editor/sidebar/QueryDatabase.tsx b/frontend/src/scenes/data-warehouse/editor/sidebar/QueryDatabase.tsx
index 0085b37ed198..78c29e936777 100644
--- a/frontend/src/scenes/data-warehouse/editor/sidebar/QueryDatabase.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/sidebar/QueryDatabase.tsx
@@ -38,6 +38,10 @@ import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'
import { copyToClipboard } from 'lib/utils/copyToClipboard'
import { cn } from 'lib/utils/css-classes'
import { newInternalTab } from 'lib/utils/newInternalTab'
+import {
+ MANAGED_TRINO_SCHEMA_SCOPE,
+ getDatabaseSchemaQueryScope,
+} from 'scenes/data-management/database/databaseTableListLogic'
import { PropertyDefinitionEditModal } from 'scenes/data-management/properties/PropertyDefinitionEditModal'
import { OutputTab } from 'scenes/data-warehouse/editor/outputPaneLogic'
import { sqlEditorLogic } from 'scenes/data-warehouse/editor/sqlEditorLogic'
@@ -309,6 +313,12 @@ export const QueryDatabase = ({
}
}
+ const isManagedTrino = connectionId === MANAGED_TRINO_SCHEMA_SCOPE
+ const schemaQueryScope = {
+ ...getDatabaseSchemaQueryScope(connectionId && connectionId !== POSTHOG_WAREHOUSE ? connectionId : undefined),
+ ...(isManagedTrino ? { sendRawQuery: true } : {}),
+ }
+
const isPreviewableViewItem = (item: TreeDataItem): boolean => {
return ['view', 'managed-view', 'endpoint'].includes(item.record?.type)
}
@@ -320,7 +330,6 @@ export const QueryDatabase = ({
const table = item.record?.tableName || item.name
const previewQuery = `SELECT * FROM ${escapePropertyAsHogQLIdentifier(table)} LIMIT 100`
- const nextConnectionId = connectionId && connectionId !== POSTHOG_WAREHOUSE ? connectionId : undefined
if (isEmbeddedMode) {
setActiveTab(OutputTab.Results)
@@ -328,7 +337,7 @@ export const QueryDatabase = ({
...sourceQuery,
source: {
...sourceQuery.source,
- connectionId: nextConnectionId,
+ ...schemaQueryScope,
query: previewQuery,
},
})
@@ -341,7 +350,7 @@ export const QueryDatabase = ({
urls.sqlEditor({
query: previewQuery,
outputTab: OutputTab.Results,
- connectionId: nextConnectionId,
+ ...schemaQueryScope,
})
)
}
@@ -752,16 +761,17 @@ export const QueryDatabase = ({
if (item.record?.type === 'table') {
// Per-object access control only exists for actual warehouse tables, not posthog/system tables
const warehouseTableId =
- warehouseAccessControlEnabled && item.record.table?.type === 'data_warehouse'
+ warehouseAccessControlEnabled && !isManagedTrino && item.record.table?.type === 'data_warehouse'
? item.record.table?.id
: null
- const tableLineageTarget: LineageTarget | null = isEmbeddedMode
- ? null
- : item.record.table?.type === 'data_warehouse'
- ? { lookup: 'warehouse_table', id: item.record.table.id }
- : item.record.table?.type === 'posthog'
- ? { lookup: 'posthog_table', id: item.record.table.name }
- : null
+ const tableLineageTarget: LineageTarget | null =
+ isEmbeddedMode || isManagedTrino
+ ? null
+ : item.record.table?.type === 'data_warehouse'
+ ? { lookup: 'warehouse_table', id: item.record.table.id }
+ : item.record.table?.type === 'posthog'
+ ? { lookup: 'posthog_table', id: item.record.table.name }
+ : null
return (
<DropdownMenuGroup>
@@ -769,12 +779,10 @@ export const QueryDatabase = ({
asChild
onClick={(e) => {
e.stopPropagation()
- const nextConnectionId =
- connectionId && connectionId !== POSTHOG_WAREHOUSE ? connectionId : undefined
router.actions.push(
urls.sqlEditor({
query: buildSelectAllQuery(item.name, null),
- connectionId: nextConnectionId,
+ ...schemaQueryScope,
})
)
}}
@@ -782,44 +790,52 @@ export const QueryDatabase = ({
<ButtonPrimitive menuItem>Query</ButtonPrimitive>
</DropdownMenuItem>
{tableLineageTarget ? <SeeLineageMenuItem target={tableLineageTarget} /> : null}
- <DropdownMenuItem
- asChild
- onClick={(e) => {
- e.stopPropagation()
- if (addJoinAccessDisabledReason) {
- return
- }
- selectSourceTable(item.name)
- }}
- >
- <ButtonPrimitive
- menuItem
- disabledReasons={
- addJoinAccessDisabledReason ? { [addJoinAccessDisabledReason]: true } : {}
- }
- >
- Add join
- </ButtonPrimitive>
- </DropdownMenuItem>
- <DropdownMenuItem
- asChild
- onClick={(e) => {
- e.stopPropagation()
- if (addJoinAccessDisabledReason) {
- return
- }
- openNewExpressionModal(item.name)
- }}
- >
- <ButtonPrimitive
- menuItem
- disabledReasons={
- addJoinAccessDisabledReason ? { [addJoinAccessDisabledReason]: true } : {}
- }
- >
- Add expression
- </ButtonPrimitive>
- </DropdownMenuItem>
+ {!isManagedTrino && (
+ <>
+ <DropdownMenuItem
+ asChild
+ onClick={(e) => {
+ e.stopPropagation()
+ if (addJoinAccessDisabledReason) {
+ return
+ }
+ selectSourceTable(item.name)
+ }}
+ >
+ <ButtonPrimitive
+ menuItem
+ disabledReasons={
+ addJoinAccessDisabledReason
+ ? { [addJoinAccessDisabledReason]: true }
+ : {}
+ }
+ >
+ Add join
+ </ButtonPrimitive>
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ asChild
+ onClick={(e) => {
+ e.stopPropagation()
+ if (addJoinAccessDisabledReason) {
+ return
+ }
+ openNewExpressionModal(item.name)
+ }}
+ >
+ <ButtonPrimitive
+ menuItem
+ disabledReasons={
+ addJoinAccessDisabledReason
+ ? { [addJoinAccessDisabledReason]: true }
+ : {}
+ }
+ >
+ Add expression
+ </ButtonPrimitive>
+ </DropdownMenuItem>
+ </>
+ )}
<DropdownMenuItem
asChild
onClick={(e) => {
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 a074230330ba..41d2c63a8e36 100644
--- a/frontend/src/scenes/data-warehouse/editor/sidebar/queryDatabaseLogic.test.ts
+++ b/frontend/src/scenes/data-warehouse/editor/sidebar/queryDatabaseLogic.test.ts
@@ -3,7 +3,10 @@ import { expectLogic } from 'kea-test-utils'
import { FEATURE_FLAGS } from 'lib/constants'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { newInternalTab } from 'lib/utils/newInternalTab'
-import { databaseTableListLogic } from 'scenes/data-management/database/databaseTableListLogic'
+import {
+ MANAGED_TRINO_SCHEMA_SCOPE,
+ databaseTableListLogic,
+} from 'scenes/data-management/database/databaseTableListLogic'
import { propertyDefinitionsList } from '~/generated/core/api'
import { performQuery } from '~/queries/query'
@@ -981,7 +984,8 @@ describe('queryDatabaseLogic', () => {
)
})
- it('hides drafts, unsaved queries and metrics when showing a direct connection schema', () => {
+ it.each(['source-id', MANAGED_TRINO_SCHEMA_SCOPE])('hides unrelated folders for schema scope %s', (scope) => {
+ databaseTableListLogic.findMounted()?.actions.setConnection(scope)
featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.EDITOR_DRAFTS], {
[FEATURE_FLAGS.EDITOR_DRAFTS]: true,
})
@@ -1015,6 +1019,13 @@ describe('queryDatabaseLogic', () => {
expect(logic.values.displayedTreeData.map((item) => item.name)).toEqual(['public'])
})
+ it('shows an empty native catalog without a source configuration link', () => {
+ const databaseLogic = databaseTableListLogic.findMounted()!
+ databaseLogic.actions.setConnection(MANAGED_TRINO_SCHEMA_SCOPE)
+ databaseLogic.actions.loadDatabaseSuccess({ tables: {}, joins: [] })
+ expect(logic.values.displayedTreeData.map((item) => item.name)).toEqual(['No queryable tables'])
+ })
+
it('hydrates a table restored as expanded in the displayed direct-connection tree', async () => {
const databaseLogic = databaseTableListLogic.findMounted()!
databaseLogic.actions.loadDatabaseSuccess({
diff --git a/frontend/src/scenes/data-warehouse/editor/sidebar/queryDatabaseLogic.tsx b/frontend/src/scenes/data-warehouse/editor/sidebar/queryDatabaseLogic.tsx
index 7954ca1aaee4..0c48f7c8178a 100644
--- a/frontend/src/scenes/data-warehouse/editor/sidebar/queryDatabaseLogic.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/sidebar/queryDatabaseLogic.tsx
@@ -26,7 +26,11 @@ import { FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { uuid } from 'lib/utils/dom'
import { createFuse, IFuseOptions } from 'lib/utils/fuseSearch'
import { newInternalTab } from 'lib/utils/newInternalTab'
-import { TableFieldsStatus, databaseTableListLogic } from 'scenes/data-management/database/databaseTableListLogic'
+import {
+ MANAGED_TRINO_SCHEMA_SCOPE,
+ TableFieldsStatus,
+ databaseTableListLogic,
+} from 'scenes/data-management/database/databaseTableListLogic'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
import { userLogic } from 'scenes/userLogic'
@@ -3538,7 +3542,8 @@ export const queryDatabaseLogic = kea<queryDatabaseLogicType>([
return createSchemaErrorNodes('direct-connection', () => actions.refreshDatabaseSchema())
}
if (!databaseLoading && !hasLoadedTables) {
- return createDirectConnectionEmptyNodes(connectionId)
+ const emptyNodes = createDirectConnectionEmptyNodes(connectionId)
+ return connectionId === MANAGED_TRINO_SCHEMA_SCOPE ? emptyNodes.slice(0, 1) : emptyNodes
}
return [
diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts
index 5c8771d66a5b..95231567599c 100644
--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts
+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts
@@ -8,7 +8,10 @@ import { LemonDialog } from '@posthog/lemon-ui'
import { FEATURE_FLAGS, OrganizationMembershipLevel } from 'lib/constants'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { databaseTableListLogic } from 'scenes/data-management/database/databaseTableListLogic'
+import {
+ MANAGED_TRINO_SCHEMA_SCOPE,
+ databaseTableListLogic,
+} from 'scenes/data-management/database/databaseTableListLogic'
import { draftsLogic } from 'scenes/data-warehouse/editor/draftsLogic'
import { dataWarehouseViewsLogic } from 'scenes/data-warehouse/saved_queries/dataWarehouseViewsLogic'
import { insightsApi } from 'scenes/insights/utils/api'
@@ -2705,6 +2708,7 @@ describe('sqlEditorLogic', () => {
expect(String(router.values.hashParams.raw ?? '')).toEqual(rawMode ? '1' : '')
expect(router.values.hashParams.engine).toEqual('managed_trino')
expect(router.values.hashParams.c).toBeUndefined()
+ expect(databaseTableListLogic.findMounted()?.values.connectionId).toEqual(MANAGED_TRINO_SCHEMA_SCOPE)
await runDebouncedAction(() => logic.actions.setQueryInput('SELECT count() FROM events'))
expect(router.values.hashParams.engine).toEqual('managed_trino')
expect(logic.values.sendRawQueryEnabled).toEqual(rawMode)
@@ -2716,15 +2720,17 @@ describe('sqlEditorLogic', () => {
expect(logic.values.sourceQuery.source.query).toEqual('SELECT 1')
expect(logic.values.sourceQuery.source.sendRawQuery).toBeUndefined()
expect(router.values.hashParams.engine).toBeUndefined()
+ expect(databaseTableListLogic.findMounted()?.values.connectionId).toBeNull()
})
- it('restores the hosted target from the URL', async () => {
+ it.each([false, true])('restores the hosted target and raw mode %s from the URL', async (sendRawQuery) => {
logic = sqlEditorLogic({ tabId: TAB_ID, monaco: createMockMonaco(), editor: createMockEditor() })
logic.mount()
- router.actions.push(urls.sqlEditor(), undefined, { q: 'SELECT 1', engine: 'managed_trino' })
+ router.actions.push(urls.sqlEditor({ query: 'SELECT 1', executionTarget: 'managed_trino', sendRawQuery }))
await expectLogic(logic).toDispatchActions(['setSourceQuery', 'createTab', 'updateTab'])
expect(logic.values.sourceQuery.source.executionTarget).toEqual('managed_trino')
- expect(logic.values.sendRawQueryEnabled).toEqual(false)
+ expect(logic.values.sendRawQueryEnabled).toEqual(sendRawQuery)
+ expect(databaseTableListLogic.findMounted()?.values.connectionId).toEqual(MANAGED_TRINO_SCHEMA_SCOPE)
})
it.each([{ c: 'conn-123' }, { engine: 'managed_trino' }])(
diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx
index f93e31518a1a..2a9e8c6e972c 100644
--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx
@@ -52,7 +52,10 @@ import { slugify } from 'lib/utils/strings'
import { backLinkParams, withBackLink } from 'scenes/analytics/analyticsBackLink'
import { DashboardLoadAction, dashboardLogic } from 'scenes/dashboard/dashboardLogic'
import { liveDashboardIds } from 'scenes/dashboard/liveDashboardIds'
-import { databaseTableListLogic } from 'scenes/data-management/database/databaseTableListLogic'
+import {
+ MANAGED_TRINO_SCHEMA_SCOPE,
+ databaseTableListLogic,
+} from 'scenes/data-management/database/databaseTableListLogic'
import {
filtersPlaceholderBindings,
parseQueryTablesAndColumns,
@@ -673,6 +676,7 @@ export interface sqlEditorLogicValues {
selectedDirectSource: ExternalDataSourceConnectionOptionApi | undefined
selectedQueryColumns: Record<string, boolean>
selectedQueryTablesAndColumns: Record<string, Record<string, boolean>>
+ selectedSchemaConnectionId: string | undefined
sendRawQueryEnabled: boolean
showAgentHints: boolean
singleStatement: boolean
@@ -1241,6 +1245,10 @@ export interface sqlEditorLogicMeta {
) => boolean
exportContext: (sourceQuery: DataVisualizationNode) => ExportContext
selectedConnectionId: (sourceQuery: DataVisualizationNode) => string | undefined
+ selectedSchemaConnectionId: (
+ sourceQuery: DataVisualizationNode,
+ selectedConnectionId: string | undefined
+ ) => string | undefined
selectedDirectSource: (
connectionOptions: ExternalDataSourceConnectionOptionApi[] | null,
selectedConnectionId: string | undefined
@@ -2169,7 +2177,7 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
}
// Opening another query can replace sourceQuery without changing the connection,
- // so the selectedConnectionId subscription does not run again.
+ // so the schema scope subscription does not run again.
actions.enforceConnectionRawQueryMode()
// Focus the editor after creating a new tab
@@ -3570,16 +3578,16 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
}
}
},
- selectedConnectionId: (selectedConnectionId) => {
- if (cache.lastSelectedConnectionId === selectedConnectionId) {
+ selectedSchemaConnectionId: (selectedConnectionId) => {
+ if (cache.lastSchemaConnectionId === selectedConnectionId) {
return
}
- cache.lastSelectedConnectionId = selectedConnectionId
+ cache.lastSchemaConnectionId = selectedConnectionId
claimConnectionScope(props.tabId, selectedConnectionId)
actions.setConnection(selectedConnectionId ?? null)
actions.loadDatabase(schemaLoadOptions())
- if (selectedConnectionId) {
+ if (values.selectedConnectionId) {
// Capability data must load wherever a connection is in play — including
// surfaces that never render the connection selector.
actions.maybeLoadConnectionOptions()
@@ -3716,6 +3724,13 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
: undefined
},
],
+ selectedSchemaConnectionId: [
+ (s) => [s.sourceQuery, s.selectedConnectionId],
+ (sourceQuery: DataVisualizationNode, selectedConnectionId: string | undefined): string | undefined =>
+ sourceQuery.source.executionTarget === 'managed_trino'
+ ? MANAGED_TRINO_SCHEMA_SCOPE
+ : selectedConnectionId,
+ ],
selectedDirectSource: [
(s) => [s.connectionOptions, s.selectedConnectionId],
(
@@ -3968,7 +3983,7 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
},
}
}
- const expectedDatabaseConnectionId = values.selectedConnectionId ?? null
+ const expectedDatabaseConnectionId = values.selectedSchemaConnectionId ?? null
const shouldSyncDatabaseConnection =
values.databaseConnectionId !== expectedDatabaseConnectionId || !values.database
@@ -4400,14 +4415,14 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
}
if (connectionIdFromHash === undefined && shouldSyncDatabaseConnection && !values.databaseLoading) {
- actions.setConnection(expectedDatabaseConnectionId)
+ actions.setConnection(values.selectedSchemaConnectionId ?? null)
actions.loadDatabase(schemaLoadOptions())
}
},
})),
afterMount(({ actions, props, values, cache }) => {
- cache.lastSelectedConnectionId = values.selectedConnectionId
- claimConnectionScope(props.tabId, values.selectedConnectionId)
+ cache.lastSchemaConnectionId = values.selectedSchemaConnectionId
+ claimConnectionScope(props.tabId, values.selectedSchemaConnectionId)
cache.activeQueryDecorationIds = [] as string[]
cache.decorationGeneration = 0
@@ -4598,7 +4613,7 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
applyResult(range, decorations)
}
- const expectedDatabaseConnectionId = values.selectedConnectionId ?? null
+ const expectedDatabaseConnectionId = values.selectedSchemaConnectionId ?? null
const shouldSyncDatabaseConnection =
values.databaseConnectionId !== expectedDatabaseConnectionId || !values.database
const hasExplicitEditorUrlState =
@@ -4610,7 +4625,7 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
(isEmbeddedSQLEditorMode(props.mode ?? SQLEditorMode.FullScene) || !hasExplicitEditorUrlState) &&
shouldSyncDatabaseConnection
) {
- actions.setConnection(values.selectedConnectionId ?? null)
+ actions.setConnection(values.selectedSchemaConnectionId ?? null)
// `databaseTableListLogic` is a shared singleton. If a prior visit left `databaseLoading`
// 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
diff --git a/frontend/src/scenes/urls.ts b/frontend/src/scenes/urls.ts
index 023f0870845d..31f92f9352f8 100644
--- a/frontend/src/scenes/urls.ts
+++ b/frontend/src/scenes/urls.ts
@@ -7,6 +7,7 @@ import {
DataTableNode,
VisualizationNode,
HogQLFilters,
+ HogQLQuery,
ProductKey,
SharingConfigurationSettings,
} from '~/queries/schema/schema-general'
@@ -90,6 +91,8 @@ export const urls = {
endpointName,
source,
connectionId,
+ executionTarget,
+ sendRawQuery,
dashboard,
filters,
metricName,
@@ -104,6 +107,8 @@ export const urls = {
endpointName?: string
source?: string
connectionId?: string
+ executionTarget?: HogQLQuery['executionTarget']
+ sendRawQuery?: boolean
dashboard?: number
/** Applied on top of the opened query/insight — carries unsaved view-mode filter edits into the editor */
filters?: HogQLFilters
@@ -156,6 +161,12 @@ export const urls = {
if (connectionId) {
hashParams.set('c', connectionId)
}
+ if (executionTarget) {
+ hashParams.set('engine', executionTarget === 'managed_trino' ? 'managed_trino' : 'posthog')
+ }
+ if (sendRawQuery) {
+ hashParams.set('raw', '1')
+ }
if (filters) {
hashParams.set('filters', JSON.stringify(filters))
}
diff --git a/posthog/api/services/query.py b/posthog/api/services/query.py
index b564c28e07af..fd7743aff437 100644
--- a/posthog/api/services/query.py
+++ b/posthog/api/services/query.py
@@ -71,6 +71,7 @@ from posthog.schema_migrations.upgrade import upgrade
from products.access_control.backend.facade.user_access_control import UserAccessControl, UserAccessControlError
from products.data_tools.backend.models.join import DataWarehouseJoin
+from products.managed_warehouse.backend.facade.query_execution import get_managed_trino_schema
from common.hogvm.python.debugger import color_bytecode
@@ -467,6 +468,14 @@ def process_query_dict(
def process_database_schema_query(
team: Team, query: DatabaseSchemaQuery, *, user: Optional[User] = None
) -> DatabaseSchemaQueryResponse:
+ if query.executionTarget == "managed_trino":
+ try:
+ return get_managed_trino_schema(query, team=team, user=user)
+ except (APIException, ExposedHogQLError, UserAccessControlError):
+ raise
+ except Exception as error:
+ capture_exception(error, {"team_id": team.pk, "query_kind": "DatabaseSchemaQuery"})
+ raise DatabaseSchemaUnavailable() from error
return _build_database_schema_query(team, query, user=user).response
diff --git a/posthog/schema.py b/posthog/schema.py
index ea5eaace3341..1de4cd5828e6 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -32039,6 +32039,10 @@ class DatabaseSchemaQuery(BaseModel):
default=None,
description="Optional direct external data source id for schema introspection",
)
+ executionTarget: ExecutionTarget | None = Field(
+ default=None,
+ description=("Select the native managed Trino catalog instead of the default PostHog catalog."),
+ )
includeFields: bool | None = Field(
default=None,
description=("When false, skip serializing each table's fields (`fields` comes back empty). Defaults to true."),
diff --git a/posthog/schema_enums.py b/posthog/schema_enums.py
index 1198bad7aeeb..5f8eecd6ee28 100644
--- a/posthog/schema_enums.py
+++ b/posthog/schema_enums.py
@@ -1120,6 +1120,11 @@ class DatabaseSchemaManagedViewTableKind(StrEnum):
REVENUE_ANALYTICS_SUBSCRIPTION = "revenue_analytics_subscription"
+class ExecutionTarget(StrEnum):
+ DEFAULT = "default"
+ MANAGED_TRINO = "managed_trino"
+
+
class DatabaseSchemaTableCertificationStatus(StrEnum):
CERTIFIED = "certified"
DEPRECATED = "deprecated"
@@ -1792,11 +1797,6 @@ class HogQLAlertEvaluation(StrEnum):
ANY_ROW = "any_row"
-class ExecutionTarget(StrEnum):
- DEFAULT = "default"
- MANAGED_TRINO = "managed_trino"
-
-
class BounceRatePageViewMode(StrEnum):
COUNT_PAGEVIEWS = "count_pageviews"
UNIQ_URLS = "uniq_urls"
diff --git a/products/managed_warehouse/backend/facade/query_execution.py b/products/managed_warehouse/backend/facade/query_execution.py
index 502204fa8d1c..87a4b8c638dc 100644
--- a/products/managed_warehouse/backend/facade/query_execution.py
+++ b/products/managed_warehouse/backend/facade/query_execution.py
@@ -3,7 +3,7 @@ from __future__ import annotations
from typing import TYPE_CHECKING
if TYPE_CHECKING:
- from posthog.schema import HogQLQuery, HogQLQueryResponse
+ from posthog.schema import DatabaseSchemaQuery, DatabaseSchemaQueryResponse, HogQLQuery, HogQLQueryResponse
from posthog.hogql.constants import HogQLGlobalSettings, LimitContext
from posthog.hogql.timings import HogQLTimings
@@ -52,3 +52,13 @@ def execute_managed_trino_query(
timings=timings,
limit_context=limit_context,
)
+
+
+def get_managed_trino_schema(
+ query: DatabaseSchemaQuery, *, team: Team, user: User | None
+) -> DatabaseSchemaQueryResponse:
+ from products.managed_warehouse.backend.query_schema import (
+ get_managed_trino_schema as get_schema, # noqa: PLC0415 -- keeps optional Trino drivers off Django startup
+ )
+
+ return get_schema(query, team=team, user=user)
diff --git a/products/managed_warehouse/backend/query_schema.py b/products/managed_warehouse/backend/query_schema.py
new file mode 100644
index 000000000000..c1a44dea518e
--- /dev/null
+++ b/products/managed_warehouse/backend/query_schema.py
@@ -0,0 +1,68 @@
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+from posthog.schema import (
+ DatabaseSchemaDataWarehouseTable,
+ DatabaseSchemaField,
+ DatabaseSchemaQuery,
+ DatabaseSchemaQueryResponse,
+ DatabaseSerializedFieldType,
+ HogQLQuery,
+)
+
+from posthog.hogql.direct_sql.trino_adapter import bounded_trino_cursor
+from posthog.hogql.escape_sql import quote_hogql_identifier
+
+from products.managed_warehouse.backend.facade.contracts import ManagedWarehouseTrinoConnectionUnavailable
+from products.managed_warehouse.backend.logic.sql_editor_trino import MANAGED_TRINO_SCHEMA_DISCOVERY_TIMEOUT_SECONDS
+from products.managed_warehouse.backend.query_execution import validate_managed_trino_query
+from products.managed_warehouse.backend.trino_connection import connect_managed_warehouse_trino
+from products.warehouse_sources.backend.facade.models import trino_column_to_dwh_column
+from products.warehouse_sources.backend.facade.source_management import discover_trino_catalog
+
+if TYPE_CHECKING:
+ from posthog.models import Team, User
+
+
+def get_managed_trino_schema(
+ query: DatabaseSchemaQuery, *, team: Team, user: User | None
+) -> DatabaseSchemaQueryResponse:
+ validate_managed_trino_query(
+ HogQLQuery(
+ query="SELECT 1", executionTarget="managed_trino", connectionId=query.connectionId, sendRawQuery=True
+ ),
+ team,
+ user,
+ )
+ assert user is not None
+ with connect_managed_warehouse_trino(
+ str(team.organization_id), principal=f"posthog:sql-editor:team:{team.pk}:user:{user.pk}"
+ ) as connection:
+ with bounded_trino_cursor(connection, MANAGED_TRINO_SCHEMA_DISCOVERY_TIMEOUT_SECONDS, team_id=team.pk) as (
+ cursor,
+ watchdog,
+ ):
+ if not connection.catalog:
+ raise ManagedWarehouseTrinoConnectionUnavailable("Trino did not return a warehouse catalog")
+ tables = discover_trino_catalog(
+ cursor, catalog=connection.catalog, names=query.tables, include_columns=query.includeFields is not False
+ )
+ watchdog.check()
+
+ response = DatabaseSchemaQueryResponse(tables={}, joins=[])
+ for table in tables:
+ name = f"{table.schema}.{table.name}"
+ fields: dict[str, DatabaseSchemaField] = {}
+ for column in table.columns:
+ column_type = trino_column_to_dwh_column(column.name, column.data_type, column.nullable)
+ fields[column.name] = DatabaseSchemaField(
+ name=column.name,
+ hogql_value=quote_hogql_identifier(column.name),
+ type=DatabaseSerializedFieldType(column_type["hogql"]),
+ schema_valid=True,
+ )
+ response.tables[name] = DatabaseSchemaDataWarehouseTable(
+ id=name, name=name, fields=fields, type="data_warehouse"
+ )
+ return response
diff --git a/products/managed_warehouse/backend/tests/test_query_schema.py b/products/managed_warehouse/backend/tests/test_query_schema.py
new file mode 100644
index 000000000000..7f6c65a10ec9
--- /dev/null
+++ b/products/managed_warehouse/backend/tests/test_query_schema.py
@@ -0,0 +1,92 @@
+from contextlib import nullcontext
+from uuid import UUID
+
+import pytest
+from unittest.mock import MagicMock, PropertyMock, patch
+
+from posthog.schema import DatabaseSchemaQuery
+
+from posthog.hogql.errors import ExposedHogQLError
+
+from posthog.api.services.query import process_database_schema_query
+from posthog.clickhouse.query_tagging import AccessMethod, QueryTags
+from posthog.exceptions import DatabaseSchemaUnavailable
+from posthog.models import Team, User
+
+
[email protected]("include_fields,table_names", [(False, None), (True, None), (True, ["analytics.orders"])])
+def test_native_schema_uses_warehouse_inventory(include_fields: bool, table_names: list[str] | None) -> None:
+ team = Team(id=7, organization_id=UUID("00000000-0000-0000-0000-000000000001"))
+ user = User(id=9)
+ cursor = MagicMock()
+ cursor.fetchall.side_effect = [
+ [("analytics", "orders"), ("posthog", "events_example")],
+ [("analytics", "orders", "order id", "bigint", "NO")],
+ [("posthog", "events_example", "event", "varchar", "YES")],
+ ]
+ connection = MagicMock(catalog="example_catalog")
+ connection.cursor.return_value = cursor
+ with (
+ patch("posthoganalytics.feature_enabled", return_value=True),
+ patch("products.managed_warehouse.backend.query_execution.get_query_tags", return_value=QueryTags()),
+ patch(
+ "products.managed_warehouse.backend.query_execution.UserAccessControl.has_project_access",
+ new_callable=PropertyMock,
+ return_value=True,
+ ),
+ patch("products.managed_warehouse.backend.query_schema.MANAGED_TRINO_SCHEMA_DISCOVERY_TIMEOUT_SECONDS", 10),
+ patch(
+ "products.managed_warehouse.backend.query_schema.connect_managed_warehouse_trino",
+ return_value=nullcontext(connection),
+ ) as connect,
+ ):
+ response = process_database_schema_query(
+ team,
+ DatabaseSchemaQuery(executionTarget="managed_trino", includeFields=include_fields, tables=table_names),
+ user=user,
+ )
+ assert set(response.tables) == (set(table_names) if table_names else {"analytics.orders", "posthog.events_example"})
+ assert response.joins == []
+ assert "events" not in response.tables
+ if include_fields:
+ field = response.tables["analytics.orders"].fields["order id"]
+ assert field.type == "integer"
+ assert field.hogql_value == "`order id`"
+ else:
+ assert all(not table.fields for table in response.tables.values())
+ assert cursor.execute.call_count == 1
+ connect.assert_called_once_with(str(team.organization_id), principal="posthog:sql-editor:team:7:user:9")
+ cursor.close.assert_called_once()
+
+
[email protected]("failure", ["flag", "anonymous", "token", "project", "connection", "discovery"])
+def test_native_schema_rejects_unavailable_access_without_loading_default_catalog(failure: str) -> None:
+ team = Team(id=7, organization_id=UUID("00000000-0000-0000-0000-000000000001"))
+ with (
+ patch("posthoganalytics.feature_enabled", return_value=failure != "flag"),
+ patch(
+ "products.managed_warehouse.backend.query_execution.get_query_tags",
+ return_value=QueryTags(access_method=AccessMethod.PERSONAL_API_KEY if failure == "token" else None),
+ ),
+ patch(
+ "products.managed_warehouse.backend.query_execution.UserAccessControl.has_project_access",
+ new_callable=PropertyMock,
+ return_value=failure != "project",
+ ),
+ patch(
+ "products.managed_warehouse.backend.query_schema.connect_managed_warehouse_trino",
+ side_effect=RuntimeError("discovery failed"),
+ ) as connect,
+ patch("posthog.api.services.query.resolve_database_for_connection") as default_catalog,
+ patch("posthog.api.services.query.capture_exception"),
+ pytest.raises(DatabaseSchemaUnavailable if failure == "discovery" else ExposedHogQLError),
+ ):
+ process_database_schema_query(
+ team,
+ DatabaseSchemaQuery(
+ executionTarget="managed_trino", connectionId="external" if failure == "connection" else None
+ ),
+ user=None if failure == "anonymous" else User(id=9),
+ )
+ default_catalog.assert_not_called()
+ assert connect.call_count == (1 if failure == "discovery" else 0)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/trino/trino.py b/products/warehouse_sources/backend/temporal/data_imports/sources/trino/trino.py
index cd7a995d408e..f46f29356091 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/trino/trino.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/trino/trino.py
@@ -385,7 +385,12 @@ def discover_trino_schemas(
def discover_trino_catalog(
- cursor: Cursor, *, catalog: str, schema: str | None = None, names: list[str] | None = None
+ cursor: Cursor,
+ *,
+ catalog: str,
+ schema: str | None = None,
+ names: list[str] | None = None,
+ include_columns: bool = True,
) -> list[DiscoveredTrinoTable]:
escaped_catalog = catalog.replace(chr(34), chr(34) * 2)
table_query = (
@@ -412,6 +417,10 @@ def discover_trino_catalog(
tables: dict[tuple[str, str], list[TrinoColumn]] = {}
for schema_name, table_names in table_names_by_schema.items():
+ for table_name in table_names:
+ tables[(schema_name, table_name)] = []
+ if not include_columns:
+ continue
for table_name_batch in batched(table_names, TRINO_COLUMN_DISCOVERY_TABLE_BATCH_SIZE, strict=False):
placeholders = ", ".join("?" for _ in table_name_batch)
column_query = (
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 8e750621bbec..da5bcd525aad 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -30875,6 +30875,8 @@ export namespace Schemas {
export interface DatabaseSchemaQuery {
/** Optional direct external data source id for schema introspection */
connectionId?: string | null;
+ /** Select the native managed Trino catalog instead of the default PostHog catalog. */
+ executionTarget?: ExecutionTarget | null;
/** When false, skip serializing each table's fields (`fields` comes back empty). Defaults to true. */
includeFields?: boolean | null;
kind?: 'DatabaseSchemaQuery';