:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): direct connect for synced sources in SQL editor and settings (#70562)
Daniel RC54e181b8ad14
diff --git a/frontend/src/scenes/data-warehouse/editor/ConnectionSelector.tsx b/frontend/src/scenes/data-warehouse/editor/ConnectionSelector.tsxindex f49f232027ab..ebf76e7b87a7 100644--- a/frontend/src/scenes/data-warehouse/editor/ConnectionSelector.tsx+++ b/frontend/src/scenes/data-warehouse/editor/ConnectionSelector.tsx@@ -3,6 +3,7 @@ import { router } from 'kea-router'import { IconGear } from '@posthog/icons'+import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'import { LemonSelect, LemonSelectOption } from 'lib/lemon-ui/LemonSelect'import { newInternalTab } from 'lib/utils/newInternalTab'import { urls } from 'scenes/urls'@@ -33,7 +34,12 @@ export function ConnectionSelector({ tabId }: ConnectionSelectorProps): JSX.Elemconst { sourceQuery, selectedConnectionId } = useValues(logic)const { connectionOptions, connectionOptionsLoading, connectionSelectOptions } =useValues(connectionSelectorLogic())+ const { maybeLoadConnectionOptions } = useActions(connectionSelectorLogic())const { setSourceQuery, syncUrlWithQuery } = useActions(logic)++ useOnMountEffect(() => {+ maybeLoadConnectionOptions()+ })const connectionSelectorValue = getConnectionSelectorValue(connectionOptions,connectionOptionsLoading,@@ -90,6 +96,8 @@ export function ConnectionSelector({ tabId }: ConnectionSelectorProps): JSX.Elemreturn}+ // sqlEditorLogic's selectedConnectionId subscription re-enables raw SQL mode+ // for raw-only (supports_hogql=false) connections.setSourceQuery({...sourceQueryWithoutLegacyConnectionId,source: {diff --git a/frontend/src/scenes/data-warehouse/editor/QueryWindow.tsx b/frontend/src/scenes/data-warehouse/editor/QueryWindow.tsxindex 599aedbada91..333b71e006b0 100644--- a/frontend/src/scenes/data-warehouse/editor/QueryWindow.tsx+++ b/frontend/src/scenes/data-warehouse/editor/QueryWindow.tsx@@ -90,6 +90,7 @@ export function QueryWindow({activeQueryOffset,selectedConnectionId,sendRawQueryEnabled,+ selectedConnectionSupportsHogQL,} = useValues(logic)const {@@ -109,7 +110,8 @@ export function QueryWindow({const { editorVimModeEnabled } = useValues(userPreferencesLogic)const { setEditorVimModeEnabled } = useActions(userPreferencesLogic)const { isDatabaseTreeCollapsed } = useValues(editorSizingLogic)- const canSendRawQuery = !!selectedConnectionId+ // Raw-only connections are forced to raw SQL mode — no toggle to show.+ const canSendRawQuery = !!selectedConnectionId && selectedConnectionSupportsHogQLconst debouncedMaxToolQueryInput = useDebouncedValue(queryInput, EMBEDDED_MAX_TOOL_CONTEXT_DEBOUNCE_MS)const debouncedMaxToolSourceQuery = useDebouncedValue(sourceQuery, EMBEDDED_MAX_TOOL_CONTEXT_DEBOUNCE_MS)const executeSqlToolStateRef = useRef({ queryInput, sourceQuery })diff --git a/frontend/src/scenes/data-warehouse/editor/connectionSelectorLogic.test.ts b/frontend/src/scenes/data-warehouse/editor/connectionSelectorLogic.test.tsindex d1218c50cfe9..3c6b0c63e4b9 100644--- a/frontend/src/scenes/data-warehouse/editor/connectionSelectorLogic.test.ts+++ b/frontend/src/scenes/data-warehouse/editor/connectionSelectorLogic.test.ts@@ -29,6 +29,17 @@ describe('connectionSelectorLogic', () => {id: 'conn-123',prefix: 'warehouse',engine: 'postgres',+ source_type: 'Postgres',+ access_method: 'direct',+ supports_hogql: true,+ },+ {+ id: 'conn-456',+ prefix: 'prod',+ engine: null,+ source_type: 'MySQL',+ access_method: 'warehouse',+ supports_hogql: true,},])})@@ -37,12 +48,22 @@ describe('connectionSelectorLogic', () => {logic?.unmount()})- it('loads connection options on mount', async () => {+ it('does not fetch on mount — embedded editors mount this logic without the selector', async () => {logic = connectionSelectorLogic()logic.mount()await expectLogic(logic).toFinishAllListeners()+ expect(mockConnectionsList).not.toHaveBeenCalled()+ })++ it('loads connection options when the selector requests them', async () => {+ logic = connectionSelectorLogic()+ logic.mount()+ logic.actions.maybeLoadConnectionOptions()++ await expectLogic(logic).toFinishAllListeners()+expect(mockConnectionsList).toHaveBeenCalledTimes(1)expect(logic.values.connectionSelectOptions[0].options).toEqual(expect.arrayContaining([@@ -52,6 +73,12 @@ describe('connectionSelectorLogic', () => {label: 'warehouse (Postgres)',managementUrl: urls.dataWarehouseSource('managed-conn-123'),}),+ // Synced source: no detected engine — label derives from source_type + synced marker+ expect.objectContaining({+ value: 'conn-456',+ label: 'prod (MySQL · synced)',+ managementUrl: urls.dataWarehouseSource('managed-conn-456'),+ }),]))expect(logic.values.connectionSelectOptions[1].options).toEqual(diff --git a/frontend/src/scenes/data-warehouse/editor/connectionSelectorLogic.ts b/frontend/src/scenes/data-warehouse/editor/connectionSelectorLogic.tsindex 7650fc9b3df8..899275e2f1ff 100644--- a/frontend/src/scenes/data-warehouse/editor/connectionSelectorLogic.ts+++ b/frontend/src/scenes/data-warehouse/editor/connectionSelectorLogic.ts@@ -1,4 +1,4 @@-import { afterMount, connect, kea, listeners, path, selectors } from 'kea'+import { actions, connect, kea, listeners, path, selectors } from 'kea'import { loaders } from 'kea-loaders'import { ApiConfig } from 'lib/api'@@ -57,7 +57,9 @@ const ENGINE_ICONS: Record<ConnectionEngine, string> = {redshift: IconRedshift,}-function getConnectionEngine(source: Pick<ExternalDataSourceConnectionOptionApi, 'engine'>): ConnectionEngine {+function getConnectionEngine(+ source: Pick<ExternalDataSourceConnectionOptionApi, 'engine' | 'source_type'>+): ConnectionEngine {if (source.engine === 'duckdb' ||source.engine === 'mysql' ||@@ -66,6 +68,11 @@ function getConnectionEngine(source: Pick<ExternalDataSourceConnectionOptionApi,) {return source.engine}+ // Synced sources have no detected connection engine — derive it from the source type.+ const sourceTypeEngine = source.source_type?.toLowerCase()+ if (sourceTypeEngine && sourceTypeEngine in ENGINE_LABELS) {+ return sourceTypeEngine as ConnectionEngine+ }return 'postgres'}@@ -90,6 +97,9 @@ export const connectionSelectorLogic = kea<connectionSelectorLogicType>([connect(() => ({actions: [sourcesDataLogic, ['loadSourcesSuccess']],})),+ actions({+ maybeLoadConnectionOptions: true,+ }),loaders(() => ({connectionOptions: [null as ExternalDataSourceConnectionOptionApi[] | null,@@ -121,10 +131,13 @@ export const connectionSelectorLogic = kea<connectionSelectorLogicType>([? [{ value: LOADING_CONNECTIONS, label: 'Loading...', disabled: true }]: (connectionOptions ?? []).map((source) => {const engine = getConnectionEngine(source)+ const isSynced = source.access_method === 'warehouse'return {value: source.id,- label: `${source.prefix ? source.prefix : source.id} (${ENGINE_LABELS[engine]})`,+ label: `${source.prefix ? source.prefix : source.id} (${ENGINE_LABELS[engine]}${+ isSynced ? ' · synced' : ''+ })`,iconSrc: ENGINE_ICONS[engine],managementUrl: urls.dataWarehouseSource(`managed-${source.id}`),}@@ -171,14 +184,20 @@ export const connectionSelectorLogic = kea<connectionSelectorLogicType>([},],}),- afterMount(({ actions, values }) => {- if (values.connectionOptions === null && !values.connectionOptionsLoading) {- actions.loadConnectionOptions()- }- }),- listeners(({ actions }) => ({+ // No afterMount auto-load: sqlEditorLogic connects this logic, so it mounts with every+ // embedded SQL editor (notebooks, logs, endpoints). Only surfaces that render the+ // connection selector should pay for the fetch — they call maybeLoadConnectionOptions.+ listeners(({ actions, values }) => ({+ maybeLoadConnectionOptions: () => {+ if (values.connectionOptions === null && !values.connectionOptionsLoading) {+ actions.loadConnectionOptions()+ }+ },loadSourcesSuccess: () => {- actions.loadConnectionOptions()+ // Refresh only where the options were fetched in the first place.+ if (values.connectionOptions !== null) {+ actions.loadConnectionOptions()+ }},})),])diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.tsindex 9b29b8d287eb..d2cfa076a294 100644--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts@@ -204,6 +204,7 @@ describe('sqlEditorLogic', () => {'/api/environments/:team_id/data_modeling_jobs/recent/': [],'/api/environments/:team_id/data_modeling_jobs/running/': [],'/api/environments/:team_id/data_modeling_nodes/lineage/': { nodes: [], edges: [] },+ '/api/projects/:team_id/external_data_sources/connections/': [],'/api/user_home_settings/@me/': {},},post: {@@ -1392,6 +1393,44 @@ describe('sqlEditorLogic', () => {expect(String(router.values.hashParams.raw)).toEqual('1')})+ it('forces raw SQL mode when the selected connection does not support HogQL', async () => {+ useMocks({+ get: {+ '/api/projects/:team_id/external_data_sources/connections/': [+ 200,+ [+ {+ id: 'raw-conn-1',+ prefix: 'mssql',+ engine: null,+ source_type: 'MSSQL',+ access_method: 'direct',+ supports_hogql: false,+ },+ ],+ ],+ },+ })+ logic = sqlEditorLogic({+ tabId: TAB_ID,+ monaco: createMockMonaco(),+ editor: createMockEditor(),+ })+ logic.mount()++ // No connection selector mounted here — selecting a connection must load the+ // capability data by itself (embedded editors, URL restores).+ router.actions.push(urls.sqlEditor(), undefined, { q: 'SELECT 1', c: 'raw-conn-1' })++ await expectLogic(logic).toDispatchActions(['setSourceQuery', 'createTab', 'updateTab'])+ await expectLogic(logic).toDispatchActions(['setSendRawQuery'])++ expect(logic.values.selectedConnectionSupportsHogQL).toEqual(false)+ expect(logic.values.sourceQuery.source.sendRawQuery).toEqual(true)+ expect(logic.values.sendRawQueryEnabled).toEqual(true)+ expect(String(router.values.hashParams.raw)).toEqual('1')+ })+it('strips legacy top-level connection ids when source query changes', async () => {logic = sqlEditorLogic({tabId: TAB_ID,diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsxindex a85167ab7b50..355eaf515969 100644--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx@@ -86,6 +86,7 @@ import { validateEndpointName } from 'products/endpoints/frontend/common'import { dataWarehouseViewsLogic } from '../saved_queries/dataWarehouseViewsLogic'import { validateSavedQueryName } from '../saved_queries/savedQueryNameValidation'import { dataModelingLogic } from '../scene/dataModelingLogic'+import { connectionSelectorLogic } from './connectionSelectorLogic'import { draftsLogic } from './draftsLogic'import { fixSQLErrorsLogic } from './fixSQLErrorsLogic'import { findInnermostSelectAtOffset, findQueryAtCursor, type QueryRange, splitQueries } from './multiQueryUtils'@@ -469,6 +470,8 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([['featureFlags'],sourcesDataLogic,['dataWarehouseSources'],+ connectionSelectorLogic,+ ['connectionOptions'],databaseTableListLogic,['database', 'databaseLoading', 'connectionId as databaseConnectionId'],outputPaneLogic({ tabId: props.tabId }),@@ -497,6 +500,8 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([['saveAsDraft', 'deleteDraft', 'saveAsDraftSuccess', 'deleteDraftSuccess'],databaseTableListLogic,['setConnection', 'loadDatabase'],+ connectionSelectorLogic,+ ['loadConnectionOptionsSuccess', 'maybeLoadConnectionOptions'],],})),actions(() => ({@@ -642,6 +647,7 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([setEditorSource: (source: SqlEditorSource) => ({ source }),runSubquery: true,setSendRawQuery: (sendRawQuery: boolean) => ({ sendRawQuery }),+ enforceConnectionRawQueryMode: true,setDashboardId: (dashboardId: number | null) => ({ dashboardId }),openMaterializationModal: (view?: DataWarehouseSavedQuery) => ({view,@@ -1141,6 +1147,20 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([})actions.syncUrlWithQuery()},+ enforceConnectionRawQueryMode: () => {+ // Raw-only connections cannot compile HogQL — force raw SQL mode.+ if (+ values.selectedConnectionId &&+ !values.selectedConnectionSupportsHogQL &&+ !values.sourceQuery.source.sendRawQuery+ ) {+ actions.setSendRawQuery(true)+ }+ },+ // Options can load after a connection was restored from the URL.+ loadConnectionOptionsSuccess: () => {+ actions.enforceConnectionRawQueryMode()+ },runSubquery: async () => {if (!props.editor) {actions.runQuery()@@ -2119,6 +2139,12 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([cache.lastSelectedConnectionId = selectedConnectionIdactions.setConnection(selectedConnectionId ?? null)actions.loadDatabase()+ if (selectedConnectionId) {+ // Capability data must load wherever a connection is in play — including+ // surfaces that never render the connection selector.+ actions.maybeLoadConnectionOptions()+ }+ actions.enforceConnectionRawQueryMode()},})),selectors({@@ -2211,6 +2237,17 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([(s) => [s.sourceQuery, s.selectedConnectionId],(sourceQuery, selectedConnectionId) => !!selectedConnectionId && (sourceQuery.source.sendRawQuery ?? false),],+ selectedConnectionSupportsHogQL: [+ (s) => [s.connectionOptions, s.selectedConnectionId],+ (connectionOptions, selectedConnectionId): boolean => {+ if (!selectedConnectionId) {+ return true+ }+ const option = connectionOptions?.find((option) => option.id === selectedConnectionId)+ // Unknown connections (options still loading) default to HogQL.+ return option ? option.supports_hogql !== false : true+ },+ ],isEditingMaterializedView: [(s) => [s.editingView],(editingView) => {diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex bc6b4c5ab0f5..e62e7006031f 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -6157,6 +6157,7 @@ export interface ExternalDataSourceCreatePayload {prefix?: stringdescription?: stringaccess_method?: 'warehouse' | 'direct'+ direct_query_enabled?: booleancreated_via: 'web' | 'api' | 'mcp'payload: Record<string, any>}@@ -6178,8 +6179,9 @@ export interface ExternalDataSource {prefix: string | nulldescription: string | nullaccess_method?: 'warehouse' | 'direct'+ direct_query_enabled?: booleancreated_via: 'web' | 'api' | 'mcp' | 'wizard' | null- engine?: 'duckdb' | 'postgres' | 'mysql' | null+ engine?: 'duckdb' | 'postgres' | 'mysql' | 'snowflake' | 'redshift' | nulllatest_error: string | nulllast_run_at?: Dayjsschemas: ExternalDataSourceSchema[]diff --git a/playwright/e2e/sql-editor-dual-mode-postgres.spec.ts b/playwright/e2e/sql-editor-dual-mode-postgres.spec.tsnew file mode 100644index 000000000000..3305faf2a24e--- /dev/null+++ b/playwright/e2e/sql-editor-dual-mode-postgres.spec.ts@@ -0,0 +1,181 @@+import { execFileSync } from 'node:child_process'++import { expect, LOGIN_PASSWORD, LOGIN_USERNAME, test } from '../utils/playwright-test-core'++async function callProjectApi(+ page: import('@playwright/test').Page,+ path: string,+ init: { method: string; body?: unknown }+): Promise<any> {+ return await page.evaluate(+ async ({ path, method, body }) => {+ const csrfToken =+ document.cookie+ .split(';')+ .map((cookie) => cookie.trim())+ .find((cookie) => cookie.startsWith('posthog_csrftoken='))+ ?.split('=')+ .slice(1)+ .join('=') || ''++ if (!csrfToken) {+ throw new Error('CSRF cookie missing in browser context')+ }++ const response = await fetch(path, {+ method,+ credentials: 'include',+ headers: {+ 'Content-Type': 'application/json',+ 'X-CSRFToken': decodeURIComponent(csrfToken),+ },+ body: body === undefined ? undefined : JSON.stringify(body),+ })++ if (!response.ok) {+ throw new Error(`${method} ${path} failed: ${response.status} ${await response.text()}`)+ }++ const text = await response.text()+ return text ? JSON.parse(text) : null+ },+ { path, method: init.method, body: init.body }+ )+}++test.describe('SQL Editor dual-mode synced Postgres source', () => {+ test('live-queries a synced source with direct query enabled', async ({ page }) => {+ test.setTimeout(180000)+ const sourceName = `playwright_dual_${Date.now()}`+ const tableName = `playwright_dual_mode_${Date.now()}`+ let sourceId: string | null = null++ try {+ execFileSync('psql', [+ 'postgresql://posthog:[email protected]:5432/posthog',+ '-c',+ `+ DROP TABLE IF EXISTS ${tableName};+ CREATE TABLE ${tableName} (+ id integer primary key,+ label text not null+ );+ INSERT INTO ${tableName} (id, label) VALUES (1, 'alpha'), (2, 'beta');+ `,+ ])+ await page.goto('/login')+ await page.evaluate(+ async ({ email, password }) => {+ await fetch('/api/login/', {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ },+ body: JSON.stringify({ email, password }),+ })+ },+ { email: LOGIN_USERNAME, password: LOGIN_PASSWORD }+ )+ await page.goto('/')+ await expect(page).toHaveURL(/\/project\/\d+/)++ await test.step('Create a synced Postgres source with live queries enabled', async () => {+ const data = await callProjectApi(page, '/api/projects/@current/external_data_sources/', {+ method: 'POST',+ body: {+ source_type: 'Postgres',+ access_method: 'warehouse',+ direct_query_enabled: true,+ prefix: sourceName,+ payload: {+ source_type: 'Postgres',+ host: 'localhost',+ port: '5432',+ database: 'posthog',+ user: 'posthog',+ password: 'posthog',+ schema: 'public',+ schemas: [+ {+ name: tableName,+ should_sync: true,+ sync_type: null,+ incremental_field: null,+ incremental_field_type: null,+ sync_time_of_day: null,+ },+ ],+ },+ },+ })+ sourceId = data.id as string+ })++ await test.step('Refresh schemas so schema metadata is captured', async () => {+ await callProjectApi(+ page,+ `/api/projects/@current/external_data_sources/${sourceId}/refresh_schemas/`,+ {+ method: 'POST',+ }+ )+ })++ await test.step('Run a HogQL query against the synced connection', async () => {+ await page.goToMenuItem('sql-editor')+ await expect(page.locator('[data-attr=editor-scene]')).toBeVisible({ timeout: 60000 })++ const connectionSelector = page.getByRole('button', { name: /PostHog \(ClickHouse\)/ })+ await connectionSelector.click()+ await page.getByRole('menuitem', { name: `${sourceName} (Postgres · synced)` }).click()++ // CodeEditor lazy-loads monaco, so the container renders before the editor+ // mounts — clicking too early focuses nothing and the keystrokes are lost.+ await page+ .locator('[data-attr=hogql-query-editor] [data-editor-ready="true"]')+ .first()+ .waitFor({ state: 'visible' })+ await page.locator('[data-attr=hogql-query-editor]').click()+ await page+ .locator('[data-attr=hogql-query-editor]')+ .press(`${process.platform === 'darwin' ? 'Meta' : 'Control'}+A`)+ await page.locator('[data-attr=hogql-query-editor]').press('Delete')+ // refresh_schemas qualifies schema rows in place (table -> public.table), and the+ // live connection catalog is keyed by the row name — so query the qualified name.+ await page+ .locator('[data-attr=hogql-query-editor]')+ .pressSequentially(`SELECT id, label FROM public.${tableName} ORDER BY id`)+ await page.locator('[data-attr=sql-editor-run-button]').click()+ await expect(page.locator('[data-attr=sql-editor-run-button]')).toContainText('Cancel')+ await expect(page.locator('[data-attr=sql-editor-run-button]')).toContainText('Run', { timeout: 60000 })++ await expect(page.locator('[data-attr=sql-editor-output-pane-empty-state]')).not.toBeVisible()+ await expect+ .poll(async () => await page.locator('body').innerText(), { timeout: 60000 })+ .toContain('alpha')+ await expect+ .poll(async () => await page.locator('body').innerText(), { timeout: 60000 })+ .toContain('beta')+ })+ } finally {+ if (sourceId) {+ try {+ await callProjectApi(page, `/api/projects/@current/external_data_sources/${sourceId}/`, {+ method: 'DELETE',+ })+ } catch {+ // Best-effort cleanup for the source created during the test.+ }+ }+ try {+ execFileSync('psql', [+ 'postgresql://posthog:[email protected]:5432/posthog',+ '-c',+ `DROP TABLE IF EXISTS ${tableName};`,+ ])+ } catch {+ // Best-effort cleanup for the table created during the test.+ }+ }+ })+})diff --git a/products/data_warehouse/frontend/scenes/NewSourceScene/NewSourceScene.tsx b/products/data_warehouse/frontend/scenes/NewSourceScene/NewSourceScene.tsxindex a8c42c324f3c..63f2fd59092e 100644--- a/products/data_warehouse/frontend/scenes/NewSourceScene/NewSourceScene.tsx+++ b/products/data_warehouse/frontend/scenes/NewSourceScene/NewSourceScene.tsx@@ -29,7 +29,7 @@ import { AccessControlLevel, AccessControlResourceType, Breadcrumb } from '~/typimport SchemaForm from '../../shared/components/forms/SchemaForm'import { supportsDirectQuery } from '../../shared/components/forms/schemaGroupingUtils'-import SourceForm, { SourceAccessMethodSelector } from '../../shared/components/forms/SourceForm'+import SourceForm, { SourceAccessMethodSelector, getSourceQueryMode } from '../../shared/components/forms/SourceForm'import { SyncProgressStep } from '../../shared/components/forms/SyncProgressStep'import { WebhookSetupForm } from '../../shared/components/forms/WebhookSetupForm'import { FreeHistoricalSyncsBanner } from '../../shared/components/FreeHistoricalSyncsBanner'@@ -304,10 +304,17 @@ function InternalSourcesWizard(props: NewSourcesWizardProps): JSX.Element {{showAccessMethodSelector && (<><SourceAccessMethodSelector- value={selectedAccessMethod}- onChange={(accessMethod) => {- updateSource({ access_method: accessMethod })+ value={getSourceQueryMode(+ selectedAccessMethod,+ (sourceConnectionDetails?.direct_query_enabled as boolean | undefined) ??+ source.direct_query_enabled+ )}+ onChange={(mode) => {+ const accessMethod = mode === 'direct' ? 'direct' : 'warehouse'+ const directQueryEnabled = mode === 'warehouse_and_direct'+ updateSource({ access_method: accessMethod, direct_query_enabled: directQueryEnabled })setSourceConnectionDetailsValue('access_method', accessMethod)+ setSourceConnectionDetailsValue('direct_query_enabled', directQueryEnabled)}}/><LemonDivider className="my-4" />diff --git a/products/data_warehouse/frontend/scenes/NewSourceScene/NewSourceWizard.test.ts b/products/data_warehouse/frontend/scenes/NewSourceScene/NewSourceWizard.test.tsindex d4b46551d6cb..4976263ed348 100644--- a/products/data_warehouse/frontend/scenes/NewSourceScene/NewSourceWizard.test.ts+++ b/products/data_warehouse/frontend/scenes/NewSourceScene/NewSourceWizard.test.ts@@ -1,4 +1,5 @@import { getEffectiveAccessMethod } from './NewSourceScene'+import { resolveCreateDirectQueryEnabled } from './sourceWizardLogic'describe('NewSourceWizard', () => {describe('getEffectiveAccessMethod', () => {@@ -10,4 +11,15 @@ describe('NewSourceWizard', () => {expect(getEffectiveAccessMethod(3, 'direct', 'warehouse')).toEqual('warehouse')})})++ describe('resolveCreateDirectQueryEnabled', () => {+ it.each<[string, { access_method?: string; direct_query_enabled?: boolean }, string, boolean | undefined]>([+ ['synced direct-capable source defaults to enabled', {}, 'Postgres', true],+ ['toggle switched off is respected', { direct_query_enabled: false }, 'Postgres', false],+ ['pure direct source omits the flag', { access_method: 'direct' }, 'Postgres', undefined],+ ['non-direct-capable source omits the flag', {}, 'Stripe', undefined],+ ])('%s', (_description, sourceValues, connectorName, expected) => {+ expect(resolveCreateDirectQueryEnabled(sourceValues, connectorName)).toEqual(expected)+ })+ })})diff --git a/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic.tsx b/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic.tsxindex 6ad7e4ec92ed..253f78a00db7 100644--- a/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic.tsx+++ b/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic.tsx@@ -228,6 +228,21 @@ export function shouldHydrateSourceFromUrl(return !(selectedConnector?.name === source.name && currentAccessMethod === urlAccessMethod && currentStep > 1)}+/**+ * Resolve the `direct_query_enabled` create-payload value. Synced direct-capable sources+ * default to live queries enabled unless the toggle was switched off; the flag is omitted+ * for pure direct sources (backend ignores it) and for sources that can't be live-queried.+ */+export function resolveCreateDirectQueryEnabled(+ sourceValues: { access_method?: string; direct_query_enabled?: boolean },+ connectorName: string+): boolean | undefined {+ if (!supportsDirectQuery(connectorName) || sourceValues.access_method === 'direct') {+ return undefined+ }+ return sourceValues.direct_query_enabled !== false+}+function webhookResultHasNoPendingInputs(webhookResult: WebhookCreateResult | null | undefined): boolean {return !!webhookResult?.success && (webhookResult.pending_inputs?.length ?? 0) === 0}@@ -561,6 +576,7 @@ export const sourceWizardLogic = kea<sourceWizardLogicType>([prefix: stringdescription: stringaccess_method: 'warehouse' | 'direct'+ direct_query_enabled?: booleanpayload: Record<string, any>},{@@ -569,6 +585,8 @@ export const sourceWizardLogic = kea<sourceWizardLogicType>([prefix: source.prefix ?? state.prefix,description: source.description ?? state.description,access_method: source.access_method ?? state.access_method,+ direct_query_enabled:+ 'direct_query_enabled' in source ? source.direct_query_enabled : state.direct_query_enabled,payload: {...state.payload,...source.payload,@@ -1712,6 +1730,10 @@ export const sourceWizardLogic = kea<sourceWizardLogicType>([const payload: Record<string, any> = {...sourceValues,access_method: isDirectQueryMode ? 'direct' : 'warehouse',+ direct_query_enabled: resolveCreateDirectQueryEnabled(+ sourceValues,+ values.selectedConnector.name+ ),source_type: values.selectedConnector.name,}actions.setIsLoading(true)diff --git a/products/data_warehouse/frontend/scenes/SourceScene/tabs/ConfigurationTab.tsx b/products/data_warehouse/frontend/scenes/SourceScene/tabs/ConfigurationTab.tsxindex 8ab49ad146c5..3c827a39e628 100644--- a/products/data_warehouse/frontend/scenes/SourceScene/tabs/ConfigurationTab.tsx+++ b/products/data_warehouse/frontend/scenes/SourceScene/tabs/ConfigurationTab.tsx@@ -5,6 +5,7 @@ import { useEffect, useState } from 'react'import { LemonButton, LemonSkeleton } from '@posthog/lemon-ui'import { AccessControlAction } from 'lib/components/AccessControlAction'+import { urls } from 'scenes/urls'import { AccessControlLevel, AccessControlResourceType } from '~/types'@@ -45,6 +46,7 @@ function UpdateSourceConnectionFormContainer(): JSX.Element {}setSourceConfigValue(['access_method'], source.access_method ?? 'warehouse')+ setSourceConfigValue(['direct_query_enabled'], source.direct_query_enabled ?? false)setSourceConfigValue(['prefix'], source.prefix ?? '')setSourceConfigValue(['description'], source.description ?? '')setJobInputs({@@ -55,6 +57,7 @@ function UpdateSourceConnectionFormContainer(): JSX.Element {// It's also the reason why it can't live in the kea logic - the selector will update on object reference changes}, [source?.access_method,+ source?.direct_query_enabled,source?.prefix,source?.description,setSourceConfigValue,@@ -75,6 +78,10 @@ function UpdateSourceConnectionFormContainer(): JSX.Element {<SourceFormComponentshowPrefix={false}showDescription={true}+ showDirectQueryToggle+ directQueryEditorUrl={+ source.direct_query_enabled ? urls.sqlEditor({ connectionId: source.id }) : undefined+ }sourceConfig={sourceFieldConfig}jobInputs={jobInputs}initialAccessMethod={source.access_method ?? 'warehouse'}diff --git a/products/data_warehouse/frontend/scenes/SourceScene/tabs/SchemasTab.tsx b/products/data_warehouse/frontend/scenes/SourceScene/tabs/SchemasTab.tsxindex 7e487676e12f..c8f8cefea54b 100644--- a/products/data_warehouse/frontend/scenes/SourceScene/tabs/SchemasTab.tsx+++ b/products/data_warehouse/frontend/scenes/SourceScene/tabs/SchemasTab.tsx@@ -36,7 +36,10 @@ import {ExternalDataSourceSchema,} from '~/types'-import { splitQualifiedTableName } from 'products/data_warehouse/frontend/shared/components/forms/schemaGroupingUtils'+import {+ splitQualifiedTableName,+ supportsDirectQuery,+} from 'products/data_warehouse/frontend/shared/components/forms/schemaGroupingUtils'import { DATA_WAREHOUSE_APP_SOURCE } from 'products/data_warehouse/frontend/shared/components/metrics/DataWarehouseMetrics'import {SourceEditorAction,@@ -185,6 +188,16 @@ function ManagedSchemasTab({ id }: { id: string }): JSX.Element {<span className="text-muted text-sm">{pluralize(filteredSchemas.length, 'schema', 'schemas')}</span></div><div className="flex items-center gap-2 shrink-0">+ {source?.direct_query_enabled && supportsDirectQuery(source.source_type) && (+ <LemonButton+ type="secondary"+ to={urls.sqlEditor({ connectionId: id })}+ tooltip="Open the SQL editor with this source selected as a live connection"+ data-attr="schemas-tab-query-directly"+ >+ Query directly+ </LemonButton>+ )}<SourceEditorAction source={source}><LemonButtontype="secondary"diff --git a/products/data_warehouse/frontend/scenes/SourceScene/tabs/sourceSettingsLogic.ts b/products/data_warehouse/frontend/scenes/SourceScene/tabs/sourceSettingsLogic.tsindex e6bbed80d023..ad6f52d3d1f8 100644--- a/products/data_warehouse/frontend/scenes/SourceScene/tabs/sourceSettingsLogic.ts+++ b/products/data_warehouse/frontend/scenes/SourceScene/tabs/sourceSettingsLogic.ts@@ -694,7 +694,7 @@ export const sourceSettingsLogic = kea<sourceSettingsLogicType>([allowBlankSensitiveFields: true,})},- submit: async ({ payload = {}, description, prefix, access_method }) => {+ submit: async ({ payload = {}, description, prefix, access_method, direct_query_enabled }) => {const sanitizedPayload = clonePayloadPreservingFiles(payload) as Record<string, any>if (values.sourceFieldConfig?.fields) {removeEmptySensitiveValues(values.sourceFieldConfig.fields, sanitizedPayload)@@ -736,6 +736,10 @@ export const sourceSettingsLogic = kea<sourceSettingsLogicType>([job_inputs: newJobInputs,prefix: prefix !== undefined ? prefix : values.source?.prefix,access_method: access_method !== undefined ? access_method : values.source?.access_method,+ direct_query_enabled:+ direct_query_enabled !== undefined+ ? direct_query_enabled+ : values.source?.direct_query_enabled,description: description !== '' ? description : (values.source?.description ?? null),})actions.loadSource()diff --git a/products/data_warehouse/frontend/shared/components/SourceIcon.tsx b/products/data_warehouse/frontend/shared/components/SourceIcon.tsxindex ea1382d2430f..f6f265e39d3b 100644--- a/products/data_warehouse/frontend/shared/components/SourceIcon.tsx+++ b/products/data_warehouse/frontend/shared/components/SourceIcon.tsx@@ -102,7 +102,7 @@ export function SourceIcon({disableTooltip = false,}: {type: string- engine?: 'duckdb' | 'postgres' | 'mysql' | 'snowflake' | null+ engine?: 'duckdb' | 'postgres' | 'mysql' | 'snowflake' | 'redshift' | nullsize?: 'xsmall' | 'small' | 'medium'sizePx?: numberdisableTooltip?: booleandiff --git a/products/data_warehouse/frontend/shared/components/forms/SourceForm.tsx b/products/data_warehouse/frontend/shared/components/forms/SourceForm.tsxindex ecee8ebcf0aa..4f7990fde18f 100644--- a/products/data_warehouse/frontend/shared/components/forms/SourceForm.tsx+++ b/products/data_warehouse/frontend/shared/components/forms/SourceForm.tsx@@ -12,6 +12,7 @@ import {LemonSwitch,LemonTag,LemonTextArea,+ Link,} from '@posthog/lemon-ui'import { IntegrationChoice } from 'lib/components/CyclotronJob/integrations/IntegrationChoice'@@ -49,6 +50,9 @@ export interface SourceFormProps {showPrefix?: booleanshowDescription?: booleanshowAccessMethodSelector?: boolean+ showDirectQueryToggle?: boolean+ /** When set, the live-queries toggle shows a link to the SQL editor with this connection preselected. */+ directQueryEditorUrl?: stringshowCdcConfig?: booleanjobInputs?: Record<string, any>initialAccessMethod?: 'warehouse' | 'direct'@@ -60,19 +64,33 @@ export interface SourceFormProps {oauthRedirectUrl?: string}+/** How a new source will be queried: synced only, synced + live queries, or live only. */+export type SourceQueryMode = 'warehouse' | 'warehouse_and_direct' | 'direct'++export function getSourceQueryMode(+ accessMethod: 'warehouse' | 'direct',+ directQueryEnabled: boolean | undefined+): SourceQueryMode {+ if (accessMethod === 'direct') {+ return 'direct'+ }+ // New synced sources default to live queries enabled.+ return directQueryEnabled === false ? 'warehouse' : 'warehouse_and_direct'+}+export function SourceAccessMethodSelector({value,onChange,}: {- value: 'warehouse' | 'direct'- onChange: (value: 'warehouse' | 'direct') => void+ value: SourceQueryMode+ onChange: (value: SourceQueryMode) => void}): JSX.Element {return (<LemonField.Pure label="How should PostHog query this source?"><LemonRadiodata-attr="postgres-access-method"value={value}- onChange={(newValue) => onChange(newValue as 'warehouse' | 'direct')}+ onChange={(newValue) => onChange(newValue as SourceQueryMode)}options={[{value: 'warehouse',@@ -96,8 +114,20 @@ export function SourceAccessMethodSelector({</LemonTag></div><div className="text-xs text-secondary">- Run queries live against this database connection. Data from this source can't- be joined with PostHog data.+ Only run queries live against this database connection, without syncing anything.+ Data from this source can't be joined with PostHog data.+ </div>+ </div>+ ),+ },+ {+ value: 'warehouse_and_direct',+ label: (+ <div>+ <div>Sync and query live</div>+ <div className="text-xs text-secondary">+ Sync selected tables into PostHog-managed storage, and also run live queries against+ this database from the SQL editor.</div></div>),@@ -712,6 +742,8 @@ export function SourceFormComponent({showPrefix = true,showDescription,showAccessMethodSelector = true,+ showDirectQueryToggle = false,+ directQueryEditorUrl,showCdcConfig = true,jobInputs,initialAccessMethod,@@ -779,19 +811,54 @@ export function SourceFormComponent({{!isUpdateMode && supportsDirectQuery(sourceConfig.name) && showAccessMethodSelector && (<><LemonField name="access_method">- {({ value, onChange }) => (- <SourceAccessMethodSelector- value={(value as 'warehouse' | 'direct' | undefined) || selectedAccessMethod}- onChange={(nextValue) => {- setSelectedAccessMethod(nextValue)- onChange(nextValue)- }}- />+ {({ value: accessMethodValue, onChange: onChangeAccessMethod }) => (+ <LemonField name="direct_query_enabled">+ {({ value: directQueryEnabledValue, onChange: onChangeDirectQueryEnabled }) => (+ <SourceAccessMethodSelector+ value={getSourceQueryMode(+ (accessMethodValue as 'warehouse' | 'direct' | undefined) ||+ selectedAccessMethod,+ directQueryEnabledValue+ )}+ onChange={(mode) => {+ const nextAccessMethod = mode === 'direct' ? 'direct' : 'warehouse'+ setSelectedAccessMethod(nextAccessMethod)+ onChangeAccessMethod(nextAccessMethod)+ onChangeDirectQueryEnabled(mode === 'warehouse_and_direct')+ }}+ />+ )}+ </LemonField>)}</LemonField><LemonDivider /></>)}+ {showDirectQueryToggle &&+ supportsDirectQuery(sourceConfig.name) &&+ selectedAccessMethod === 'warehouse' && (+ <LemonField+ name="direct_query_enabled"+ help="Run live queries against this database from the SQL editor, in addition to syncing tables to the warehouse."+ >+ {({ value, onChange }) => (+ <div className="flex items-center gap-3">+ <LemonSwitch+ checked={!!value}+ onChange={onChange}+ label="Enable live queries"+ bordered+ data-attr="direct-query-enabled-toggle"+ />+ {directQueryEditorUrl && (+ <Link to={directQueryEditorUrl} data-attr="direct-query-open-sql-editor">+ Open in SQL editor+ </Link>+ )}+ </div>+ )}+ </LemonField>+ )}{isDirectQuerySource && (<LemonFieldname="prefix"diff --git a/products/warehouse_sources/mcp/tools.yaml b/products/warehouse_sources/mcp/tools.yamlindex 48c09a2b4c7e..c4becf15625d 100644--- a/products/warehouse_sources/mcp/tools.yaml+++ b/products/warehouse_sources/mcp/tools.yaml@@ -252,9 +252,12 @@ tools:title: List direct-query connectionsdescription: >List external data sources that can be used as a connectionId when running execute-sql against an external- source (direct-query Postgres and MySQL connections). Returns a lightweight id, prefix, and engine for each- — unlike external-data-sources-list, it does not include warehouse import sources or table schemas. Use this- to discover valid connectionId values.+ source: pure direct-query connections (Postgres, MySQL, Snowflake, Redshift) plus synced warehouse sources+ that have live queries enabled (direct_query_enabled). Returns a lightweight id, prefix, engine,+ source_type, access_method ('direct' for pure live-query sources, 'warehouse' for synced sources with live+ queries on), and supports_hogql for each; when supports_hogql is false, only raw SQL (sendRawQuery) works.+ Unlike external-data-sources-list, it does not include table schemas or sources that cannot be live-queried.+ Use this to discover valid connectionId values.external-data-sources-create:operation: external_data_sources_createenabled: truediff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 8fa4678c1c0b..64dc0b63984b 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -3596,7 +3596,7 @@}},"external-data-sources-connections-list": {- "description": "List external data sources that can be used as a connectionId when running execute-sql against an external source (direct-query Postgres and MySQL connections). Returns a lightweight id, prefix, and engine for each — unlike external-data-sources-list, it does not include warehouse import sources or table schemas. Use this to discover valid connectionId values.",+ "description": "List external data sources that can be used as a connectionId when running execute-sql against an external source: pure direct-query connections (Postgres, MySQL, Snowflake, Redshift) plus synced warehouse sources that have live queries enabled (direct_query_enabled). Returns a lightweight id, prefix, engine, source_type, access_method ('direct' for pure live-query sources, 'warehouse' for synced sources with live queries on), and supports_hogql for each; when supports_hogql is false, only raw SQL (sendRawQuery) works. Unlike external-data-sources-list, it does not include table schemas or sources that cannot be live-queried. Use this to discover valid connectionId values.","category": "Warehouse sources","feature": "warehouse_sources","summary": "List direct-query connections",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 0dd98840c6ec..e53e0a7d5cf7 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -3793,7 +3793,7 @@}},"external-data-sources-connections-list": {- "description": "List external data sources that can be used as a connectionId when running execute-sql against an external source (direct-query Postgres and MySQL connections). Returns a lightweight id, prefix, and engine for each — unlike external-data-sources-list, it does not include warehouse import sources or table schemas. Use this to discover valid connectionId values.",+ "description": "List external data sources that can be used as a connectionId when running execute-sql against an external source: pure direct-query connections (Postgres, MySQL, Snowflake, Redshift) plus synced warehouse sources that have live queries enabled (direct_query_enabled). Returns a lightweight id, prefix, engine, source_type, access_method ('direct' for pure live-query sources, 'warehouse' for synced sources with live queries on), and supports_hogql for each; when supports_hogql is false, only raw SQL (sendRawQuery) works. Unlike external-data-sources-list, it does not include table schemas or sources that cannot be live-queried. Use this to discover valid connectionId values.","category": "Warehouse sources","feature": "warehouse_sources","summary": "List direct-query connections",