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(notebooks): run SQLV2 cells on the selected warehouse connection (#76746)

Sinan Kucukkoseler8a2bf4324453
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index 47bed3f56ed8..76469ad8df4b 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -4955,6 +4955,8 @@ const api = {
refs?: Record<string, { node_id: string; kind: 'hogql' | 'local' }>
node_type?: 'hogql' | 'python'
output_name?: string
+ connection_id?: string | null
+ send_raw_query?: boolean
}
): Promise<{ run_id: string }> {
return await new ApiRequest().notebook(notebookId).withAction('sql_v2/run').create({ data })
diff --git a/frontend/src/scenes/notebooks/Nodes/NotebookNodeSQLV2.tsx b/frontend/src/scenes/notebooks/Nodes/NotebookNodeSQLV2.tsx
index 8f003a263239..2bf5dfe31ace 100644
--- a/frontend/src/scenes/notebooks/Nodes/NotebookNodeSQLV2.tsx
+++ b/frontend/src/scenes/notebooks/Nodes/NotebookNodeSQLV2.tsx
@@ -41,6 +41,10 @@ export type NotebookNodeSQLV2Attributes = {
code: string
// Dataframe name other SQLV2 nodes can reference (inlined as a CTE when they join it).
returnVariable: string
+ // Where the cell runs: a direct-query data source id, or null/absent for PostHog's ClickHouse.
+ connectionId?: string | null
+ // Send the code to that connection verbatim instead of compiling it from HogQL.
+ sendRawQuery?: boolean | null
runId?: string | null
result?: NotebookNodeSQLV2Result | null
// How the run that produced `result` ended. An interrupt persists a partial result just
@@ -155,15 +159,21 @@ const Component = ({
const cachedResults = useMemo(() => (result ? toCachedResults(result) : null), [result])
const activeTab = attributes.outputTab === OutputTab.Visualization ? OutputTab.Visualization : OutputTab.Results
- // The stored viz config wins, but the source always tracks the node's current code.
+ // The stored viz config wins, but the source always tracks the node's current code — and the
+ // connection it runs on, so anything the viz layer re-queries lands on the same engine.
const vizQuery = useMemo(
(): DataVisualizationNode => ({
kind: NodeKind.DataVisualizationNode,
display: ChartDisplayType.ActionsLineGraph,
...attributes.vizQuery,
- source: { kind: NodeKind.HogQLQuery, query: attributes.code },
+ source: {
+ kind: NodeKind.HogQLQuery,
+ query: attributes.code,
+ connectionId: attributes.connectionId ?? undefined,
+ sendRawQuery: attributes.connectionId ? !!attributes.sendRawQuery || undefined : undefined,
+ },
}),
- [attributes.vizQuery, attributes.code]
+ [attributes.vizQuery, attributes.code, attributes.connectionId, attributes.sendRawQuery]
)
// Grow a still-too-short node to fit the result each run lands, so output is readable without
@@ -359,9 +369,12 @@ const Settings = ({
attributes={attributes}
updateAttributes={updateAttributes}
tabIdSuffix="datav2"
+ persistConnection
// Refs come from the notebook content, not the tiptap editor: markdown notebooks
// (the only surface with SQLV2 cells) have no tiptap editor at all.
- onRunQuery={(code) => runQuery(code, collectSqlV2Refs(notebookLogic.values.content, nodeId))}
+ onRunQuery={(code, connection) =>
+ runQuery(code, collectSqlV2Refs(notebookLogic.values.content, nodeId), connection)
+ }
runQueryLoading={isRunning}
runQueryDisabledReason={operationBlockReason ?? undefined}
runQueryTooltip="Run SQL query"
@@ -388,6 +401,12 @@ export const NotebookNodeSQLV2 = createPostHogWidgetNode<NotebookNodeSQLV2Attrib
returnVariable: {
default: '',
},
+ connectionId: {
+ default: null,
+ },
+ sendRawQuery: {
+ default: false,
+ },
runId: {
default: null,
},
diff --git a/frontend/src/scenes/notebooks/Nodes/components/NotebookSQLEditor.test.tsx b/frontend/src/scenes/notebooks/Nodes/components/NotebookSQLEditor.test.tsx
index 6528d9cc53b8..7a9dd1befc52 100644
--- a/frontend/src/scenes/notebooks/Nodes/components/NotebookSQLEditor.test.tsx
+++ b/frontend/src/scenes/notebooks/Nodes/components/NotebookSQLEditor.test.tsx
@@ -10,10 +10,12 @@ jest.mock('scenes/data-warehouse/editor/sqlEditorLogic', () => ({
}))
import { act, render, waitFor } from '@testing-library/react'
+import { actions, kea, key, path, props, reducers, selectors } from 'kea'
import { OutputTab, outputPaneLogic } from 'scenes/data-warehouse/editor/outputPaneLogic'
+import { sqlEditorLogic } from 'scenes/data-warehouse/editor/sqlEditorLogic'
-import { NodeKind, ProductKey } from '~/queries/schema/schema-general'
+import { DataVisualizationNode, NodeKind, ProductKey } from '~/queries/schema/schema-general'
import { initKeaTests } from '~/test/init'
import { ChartDisplayType } from '~/types'
@@ -26,6 +28,7 @@ import {
getNotebookSqlEditorOutputTab,
getSqlEditorSourceQuery,
hasAlreadyRunSqlEditorSourceQuery,
+ useNotebookCodeSQLEditorSync,
useNotebookSQLOutputTabSync,
} from './NotebookSQLEditor'
@@ -50,6 +53,65 @@ function OutputTabSyncHarness({
return null
}
+// Stands in for sqlEditorLogic: the code sync reads `queryInput` plus the connection selectors,
+// and the connection selector's only contract with it is `setSourceQuery`. The two selectors
+// mirror the real ones so the stub can't quietly diverge on the raw-mode rule.
+const stubSqlEditorLogic = kea<any>([
+ path(['test', 'stubSqlEditorLogic']),
+ props({} as { tabId: string }),
+ key((logicProps: { tabId: string }) => logicProps.tabId),
+ actions({
+ initialize: true,
+ setQueryInput: (...args: any[]) => ({ queryInput: args[0] as string | null }),
+ setSourceQuery: (...args: any[]) => ({ sourceQuery: args[0] as DataVisualizationNode }),
+ }),
+ reducers({
+ queryInput: [null as string | null, { setQueryInput: (_: any, { queryInput }: any) => queryInput }],
+ sourceQuery: [
+ {
+ kind: NodeKind.DataVisualizationNode,
+ source: { kind: NodeKind.HogQLQuery, query: '' },
+ display: ChartDisplayType.ActionsTable,
+ } as DataVisualizationNode,
+ { setSourceQuery: (_: any, { sourceQuery }: any) => sourceQuery },
+ ],
+ }),
+ selectors({
+ selectedConnectionId: [
+ (s: any) => [s.sourceQuery],
+ (sourceQuery: DataVisualizationNode) => sourceQuery.source.connectionId,
+ ],
+ sendRawQueryEnabled: [
+ (s: any) => [s.sourceQuery, s.selectedConnectionId],
+ (sourceQuery: DataVisualizationNode, selectedConnectionId: string | undefined) =>
+ !!selectedConnectionId && (sourceQuery.source.sendRawQuery ?? false),
+ ],
+ }),
+])
+
+function CodeSyncHarness({
+ code,
+ connectionId,
+ sendRawQuery,
+ tabId,
+ updateAttributes,
+}: {
+ code: string
+ connectionId?: string | null
+ sendRawQuery?: boolean | null
+ tabId: string
+ updateAttributes: jest.Mock
+}): JSX.Element | null {
+ useNotebookCodeSQLEditorSync({
+ attributes: { nodeId: 'node-1', code, connectionId, sendRawQuery },
+ tabId,
+ updateAttributes,
+ persistConnection: true,
+ })
+
+ return null
+}
+
describe('NotebookSQLEditor', () => {
it('adds notebook query tags to HogQL source queries', () => {
const sourceQuery = getSqlEditorSourceQuery({
@@ -198,4 +260,50 @@ describe('NotebookSQLEditor', () => {
expect(lastRunQuery).not.toBeNull()
expect(hasAlreadyRunSqlEditorSourceQuery(sourceQuery!, lastRunQuery)).toBe(false)
})
+
+ it('keeps the selected connection while the code cell is edited', async () => {
+ // The bug: every keystroke rebuilt the source query from scratch, dropping the connection
+ // the user had picked — so the selector snapped back to PostHog mid-typing.
+ initKeaTests()
+ const tabId = 'notebook-sql-connection-keystroke'
+ const logic = stubSqlEditorLogic({ tabId })
+ ;(sqlEditorLogic as unknown as jest.Mock).mockImplementation(() => logic)
+ const updateAttributes = jest.fn()
+
+ render(
+ <CodeSyncHarness code="select 1" connectionId="conn-1" tabId={tabId} updateAttributes={updateAttributes} />
+ )
+ await waitFor(() => expect(logic.values.sourceQuery.source.connectionId).toBe('conn-1'))
+
+ act(() => {
+ logic.actions.setQueryInput('select 2')
+ })
+
+ await waitFor(() => expect(updateAttributes).toHaveBeenCalledWith({ code: 'select 2' }))
+ expect(logic.values.sourceQuery.source.connectionId).toBe('conn-1')
+ })
+
+ it('persists a newly picked connection onto the cell', async () => {
+ // The connection selector writes straight into sqlEditorLogic, so without this the choice
+ // would never reach the run request or survive a reload.
+ initKeaTests()
+ const tabId = 'notebook-sql-connection-persist'
+ const logic = stubSqlEditorLogic({ tabId })
+ ;(sqlEditorLogic as unknown as jest.Mock).mockImplementation(() => logic)
+ const updateAttributes = jest.fn()
+
+ render(<CodeSyncHarness code="select 1" tabId={tabId} updateAttributes={updateAttributes} />)
+ await waitFor(() => expect(logic.values.queryInput).toBe('select 1'))
+
+ act(() => {
+ logic.actions.setSourceQuery({
+ ...logic.values.sourceQuery,
+ source: { ...logic.values.sourceQuery.source, connectionId: 'conn-1', sendRawQuery: true },
+ })
+ })
+
+ await waitFor(() =>
+ expect(updateAttributes).toHaveBeenCalledWith({ connectionId: 'conn-1', sendRawQuery: true })
+ )
+ })
})
diff --git a/frontend/src/scenes/notebooks/Nodes/components/NotebookSQLEditor.tsx b/frontend/src/scenes/notebooks/Nodes/components/NotebookSQLEditor.tsx
index 6ab3d76d6b3b..2937617a9c1f 100644
--- a/frontend/src/scenes/notebooks/Nodes/components/NotebookSQLEditor.tsx
+++ b/frontend/src/scenes/notebooks/Nodes/components/NotebookSQLEditor.tsx
@@ -74,11 +74,26 @@ export const getSqlEditorSourceQuery = (query: QuerySchema): DataVisualizationNo
return null
}
-const buildSourceQuery = (query: string): DataVisualizationNode => ({
+/**
+ * Which connection a code cell runs against, as the node persists it.
+ *
+ * The resolved form (no undefined, raw mode only alongside a connection) is whatever
+ * sqlEditorLogic's `selectedConnectionId` / `sendRawQueryEnabled` say — `setSourceQuery`
+ * normalizes every write through `normalizeRawQuerySource`, so there is nothing to
+ * normalize here beyond the persisted attributes.
+ */
+export interface NotebookSQLConnection {
+ connectionId?: string | null
+ sendRawQuery?: boolean | null
+}
+
+const buildSourceQuery = (query: string, connection: NotebookSQLConnection): DataVisualizationNode => ({
kind: NodeKind.DataVisualizationNode,
source: {
kind: NodeKind.HogQLQuery,
query,
+ connectionId: connection.connectionId ?? undefined,
+ sendRawQuery: connection.sendRawQuery ?? undefined,
tags: {
productKey: ProductKey.NOTEBOOKS,
scene: 'Notebook',
@@ -239,14 +254,17 @@ function useNotebookQuerySQLEditorOutputSync<T extends { query: QuerySchema }>({
return editorSourceQuery
}
-export function useNotebookCodeSQLEditorSync<T extends { code: string }>({
+export function useNotebookCodeSQLEditorSync<T extends { code: string } & NotebookSQLConnection>({
attributes,
updateAttributes,
tabId,
-}: NotebookNodeAttributeProperties<T> & { tabId: string }): void {
+ persistConnection = false,
+}: NotebookNodeAttributeProperties<T> & { tabId: string; persistConnection?: boolean }): void {
const code = typeof attributes.code === 'string' ? attributes.code : ''
const logic = sqlEditorLogic({ tabId, mode: SQLEditorMode.Embedded })
- const { queryInput } = useValues(logic)
+ // The editor's own resolved view of the connection — already normalized, since
+ // `setSourceQuery` runs every write through `normalizeRawQuerySource`.
+ const { queryInput, selectedConnectionId, sendRawQueryEnabled } = useValues(logic)
const { initialize, setQueryInput, setSourceQuery } = useActions(logic)
// Tracks the last `code` and `queryInput` we observed in sync. A real attribute change
@@ -257,6 +275,17 @@ export function useNotebookCodeSQLEditorSync<T extends { code: string }>({
const lastCodeRef = useRef<string | null>(null)
const lastQueryRef = useRef<string | null>(null)
+ const editorConnectionId = selectedConnectionId ?? null
+ const attributeConnectionId = attributes.connectionId ?? null
+ // Mirrors the `sendRawQueryEnabled` selector: raw mode only counts alongside a connection.
+ const attributeSendRawQuery = !!attributeConnectionId && !!attributes.sendRawQuery
+ // Same two-ref reconciliation as the code sync above, for the connection the cell runs on.
+ // Compared as a key so the pair is one scalar — the refs never hold a stale object identity.
+ const attributeConnectionKey = `${attributeConnectionId}:${attributeSendRawQuery}`
+ const editorConnectionKey = `${editorConnectionId}:${sendRawQueryEnabled}`
+ const lastAttributeConnectionRef = useRef<string | null>(null)
+ const lastEditorConnectionRef = useRef<string | null>(null)
+
useEffect(() => {
initialize()
}, [initialize])
@@ -273,7 +302,9 @@ export function useNotebookCodeSQLEditorSync<T extends { code: string }>({
lastCodeRef.current = code
lastQueryRef.current = code
setQueryInput(code)
- setSourceQuery(buildSourceQuery(code))
+ setSourceQuery(
+ buildSourceQuery(code, { connectionId: attributeConnectionId, sendRawQuery: attributeSendRawQuery })
+ )
return
}
@@ -282,9 +313,17 @@ export function useNotebookCodeSQLEditorSync<T extends { code: string }>({
// "Run query" uses what the user is actually looking at. Skip the push when
// queryInput resets to null (e.g. a re-initialize while `code` hasn't changed) —
// otherwise we'd write `code: null` and clear the cell on the next round-trip.
+ // Rebuild from the live sourceQuery, not from scratch: a connection the user picked
+ // moments ago may not have round-tripped through Tiptap yet, and rebuilding from the
+ // attributes would drop it (this is what reset the selector on every keystroke).
lastQueryRef.current = queryInput
if (queryInput !== null) {
- setSourceQuery(buildSourceQuery(queryInput))
+ setSourceQuery(
+ buildSourceQuery(queryInput, {
+ connectionId: editorConnectionId,
+ sendRawQuery: sendRawQueryEnabled,
+ })
+ )
updateAttributes({ code: queryInput } as Partial<NotebookNodeAttributes<T>>)
}
return
@@ -292,7 +331,59 @@ export function useNotebookCodeSQLEditorSync<T extends { code: string }>({
// Both sides match what we last observed but each other doesn't — Tiptap is still
// catching up to a push we already made. Do nothing; the next render will reconcile.
- }, [code, queryInput, setQueryInput, setSourceQuery, updateAttributes])
+ }, [
+ code,
+ queryInput,
+ attributeConnectionId,
+ attributeSendRawQuery,
+ editorConnectionId,
+ sendRawQueryEnabled,
+ setQueryInput,
+ setSourceQuery,
+ updateAttributes,
+ ])
+
+ useEffect(() => {
+ if (!persistConnection || attributeConnectionKey === editorConnectionKey) {
+ lastAttributeConnectionRef.current = attributeConnectionKey
+ lastEditorConnectionRef.current = editorConnectionKey
+ return
+ }
+
+ if (attributeConnectionKey !== lastAttributeConnectionRef.current) {
+ lastAttributeConnectionRef.current = attributeConnectionKey
+ lastEditorConnectionRef.current = attributeConnectionKey
+ setSourceQuery(
+ buildSourceQuery(queryInput ?? code, {
+ connectionId: attributeConnectionId,
+ sendRawQuery: attributeSendRawQuery,
+ })
+ )
+ return
+ }
+
+ if (editorConnectionKey !== lastEditorConnectionRef.current) {
+ // The connection selector writes straight into sqlEditorLogic; persist it on the cell
+ // so the next run targets it and a reload keeps it.
+ lastEditorConnectionRef.current = editorConnectionKey
+ updateAttributes({
+ connectionId: editorConnectionId,
+ sendRawQuery: sendRawQueryEnabled,
+ } as Partial<NotebookNodeAttributes<T>>)
+ }
+ }, [
+ persistConnection,
+ attributeConnectionKey,
+ editorConnectionKey,
+ attributeConnectionId,
+ attributeSendRawQuery,
+ editorConnectionId,
+ sendRawQueryEnabled,
+ code,
+ queryInput,
+ setSourceQuery,
+ updateAttributes,
+ ])
}
export const getNotebookSqlEditorOutputTab = (outputTab: unknown): OutputTab => {
@@ -412,7 +503,7 @@ export function NotebookSQLEditorSettings<T extends { query: QuerySchema }>({
)
}
-export function NotebookCodeSQLEditorSettings<T extends { code: string }>({
+export function NotebookCodeSQLEditorSettings<T extends { code: string } & NotebookSQLConnection>({
attributes,
updateAttributes,
tabIdSuffix,
@@ -422,22 +513,25 @@ export function NotebookCodeSQLEditorSettings<T extends { code: string }>({
runQueryTooltip,
onCancelQuery,
cancelQueryLoading,
+ persistConnection,
}: NotebookNodeAttributeProperties<T> & {
tabIdSuffix: string
- /** Called with the live editor text — `attributes.code` can lag it by a Tiptap round-trip. */
- onRunQuery?: (code: string) => void
+ /** Called with the live editor text and connection — the attributes can lag both by a Tiptap round-trip. */
+ onRunQuery?: (code: string, connection: { connectionId: string | null; sendRawQuery: boolean }) => void
runQueryLoading?: boolean
runQueryDisabledReason?: string
runQueryTooltip?: string
/** With onRunQuery: flips the run button to Cancel while runQueryLoading. */
onCancelQuery?: () => void
cancelQueryLoading?: boolean
+ /** Store the picked connection on the cell. Only for cells whose run actually honors it. */
+ persistConnection?: boolean
}): JSX.Element {
const tabId = useMemo(
() => getNotebookSqlEditorTabId(attributes.nodeId, tabIdSuffix),
[attributes.nodeId, tabIdSuffix]
)
- useNotebookCodeSQLEditorSync({ attributes, updateAttributes, tabId })
+ useNotebookCodeSQLEditorSync({ attributes, updateAttributes, tabId, persistConnection })
const extraTreeSections = useNotebookDataframeTreeSections()
const editorLogic = sqlEditorLogic({ tabId, mode: SQLEditorMode.Embedded })
const { queryInput } = useValues(editorLogic)
@@ -466,15 +560,20 @@ export function NotebookCodeSQLEditorSettings<T extends { code: string }>({
defaultShowDatabaseTree={false}
extraTreeSections={extraTreeSections}
autoFocusQueryPane={autoFocusQueryPane}
- // Read the editor's current text imperatively at run time. The Cmd+Enter keybinding
- // fires a stale closure (and Monaco's keybinding value can come through empty), so a
- // captured `liveCode` would run the previous query. The mounted logic's `queryInput`
- // is the same source the Run button uses; fall back to `liveCode` before first sync.
+ // Read the editor's current text and connection imperatively at run time. The
+ // Cmd+Enter keybinding fires a stale closure (and Monaco's keybinding value can come
+ // through empty), so a captured `liveCode` would run the previous query. The mounted
+ // logic is the same source the Run button uses; fall back to `liveCode` before first
+ // sync. The connection is read here too because a just-picked one may not have
+ // round-tripped through Tiptap into the attributes yet.
onRunQuery={
onRunQuery
? () => {
const current = editorLogic.values.queryInput
- onRunQuery(typeof current === 'string' && current.trim() ? current : liveCode)
+ onRunQuery(typeof current === 'string' && current.trim() ? current : liveCode, {
+ connectionId: editorLogic.values.selectedConnectionId ?? null,
+ sendRawQuery: editorLogic.values.sendRawQueryEnabled,
+ })
}
: undefined
}
diff --git a/frontend/src/scenes/notebooks/Nodes/notebookNodeContent.ts b/frontend/src/scenes/notebooks/Nodes/notebookNodeContent.ts
index f70363fcfd3d..74c2f5d111a9 100644
--- a/frontend/src/scenes/notebooks/Nodes/notebookNodeContent.ts
+++ b/frontend/src/scenes/notebooks/Nodes/notebookNodeContent.ts
@@ -54,6 +54,10 @@ export type NotebookDependencyNode = {
uses: string[]
code?: string
returnVariable?: string
+ // SQLV2 only: the data source the cell runs against, so a chain-dispatched run targets the
+ // same one its own Run button would.
+ connectionId?: string | null
+ sendRawQuery?: boolean
}
export type NotebookDependencyGraph = {
@@ -810,6 +814,8 @@ export const buildNotebookDependencyGraph = (content?: JSONContent | null): Note
usedSqlV2ReturnVariables.add(normalizeSqlIdentifier(returnVariable))
}
const code = typeof attrs.code === 'string' ? attrs.code : ''
+ const connectionId =
+ typeof attrs.connectionId === 'string' && attrs.connectionId ? attrs.connectionId : null
nodes.push({
nodeId: attrs.nodeId ?? '',
nodeType: NotebookNodeType.SQLV2,
@@ -819,6 +825,8 @@ export const buildNotebookDependencyGraph = (content?: JSONContent | null): Note
uses: extractDuckSqlTables(code),
code,
returnVariable,
+ connectionId,
+ sendRawQuery: !!connectionId && !!attrs.sendRawQuery,
})
}
diff --git a/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.test.ts b/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.test.ts
index f716eafbf308..2a69c3f7f6ca 100644
--- a/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.test.ts
+++ b/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.test.ts
@@ -209,6 +209,18 @@ describe('notebookNodeSQLV2Logic', () => {
expect(updateAttributes).toHaveBeenCalledWith({ nodeId: 'n1', runId: 'r1', result: null, runStatus: null })
})
+ it('dispatches a run against the cell’s connection', async () => {
+ // Without this the run reaches the backend with no connection and executes on ClickHouse,
+ // which is what made warehouse queries fail with "Unknown table".
+ mount()
+ logic.actions.runQuery('select 1', {}, { connectionId: 'conn-1', sendRawQuery: true })
+ await expectLogic(logic).toDispatchActions(['runQuery', 'startPolling'])
+ expect(runSpy).toHaveBeenCalledWith(
+ 'nb1',
+ expect.objectContaining({ connection_id: 'conn-1', send_raw_query: true })
+ )
+ })
+
it('dispatches a python run with its node type and output name', async () => {
mount()
logic.actions.runQuery(
diff --git a/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.ts b/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.ts
index d588fd7e67c7..c3f1ccd3fcf8 100644
--- a/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.ts
+++ b/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.ts
@@ -88,6 +88,10 @@ export type NotebookNodeSQLV2DirectRows = {
export interface RunQueryOptions {
nodeType?: 'hogql' | 'python'
outputName?: string
+ // SQL cells only: the data source to run against instead of PostHog, and whether to send the
+ // code to it verbatim. Absent means PostHog's own ClickHouse.
+ connectionId?: string | null
+ sendRawQuery?: boolean
}
export interface NotebookNodeSQLV2LogicProps {
@@ -472,12 +476,13 @@ export const notebookNodeSQLV2Logic = kea<notebookNodeSQLV2LogicType>([
return
}
// Which lane will this run take? Mirrors the backend's routing: python always
- // needs the kernel; SQL needs it only when it reads a local (python-made) frame.
+ // needs the kernel; SQL needs it only when it reads a local (python-made) frame,
+ // and never when it targets an external connection (the sandbox can't reach one).
// The backend stays authoritative — this only drives the kernel panel, never
// dispatch.
const isKernelLane =
opts.nodeType === 'python' ||
- extractDuckSqlTables(code).some((name) => refs[name]?.kind === 'local')
+ (!opts.connectionId && extractDuckSqlTables(code).some((name) => refs[name]?.kind === 'local'))
if (isKernelLane) {
// The backend provisions the sandbox itself when none is running; open the
// kernel panel so the user can watch it come up instead of guessing.
@@ -498,6 +503,11 @@ export const notebookNodeSQLV2Logic = kea<notebookNodeSQLV2LogicType>([
refs,
node_type: opts.nodeType,
output_name: opts.outputName,
+ // Omitted entirely for a PostHog cell — the backend's defaults say the same
+ // thing, and every existing run body stays byte-identical.
+ ...(opts.connectionId
+ ? { connection_id: opts.connectionId, send_raw_query: !!opts.sendRawQuery }
+ : {}),
})
// Mark this as the active run so a still-in-flight poll from a previous run
// can't overwrite this result or stop this run's poller once it resolves.
@@ -534,7 +544,7 @@ export const notebookNodeSQLV2Logic = kea<notebookNodeSQLV2LogicType>([
const opts: RunQueryOptions =
self.nodeType === NotebookNodeType.PythonV2
? { nodeType: 'python', outputName: self.returnVariable }
- : {}
+ : { connectionId: self.connectionId ?? null, sendRawQuery: !!self.sendRawQuery }
actions.runQuery(self.code ?? '', collectSqlV2Refs(content, props.nodeId), opts)
},
startPolling: ({ runId }) => {
diff --git a/products/notebooks/backend/migrations/0013_notebooknoderun_connection_id_and_more.py b/products/notebooks/backend/migrations/0013_notebooknoderun_connection_id_and_more.py
new file mode 100644
index 000000000000..56b1d30ce695
--- /dev/null
+++ b/products/notebooks/backend/migrations/0013_notebooknoderun_connection_id_and_more.py
@@ -0,0 +1,22 @@
+# Generated by Django 5.2.14 on 2026-08-03 14:10
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("notebooks", "0012_kernelruntime_frames_and_more"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="notebooknoderun",
+ name="connection_id",
+ field=models.UUIDField(blank=True, null=True),
+ ),
+ migrations.AddField(
+ model_name="notebooknoderun",
+ name="send_raw_query",
+ field=models.BooleanField(db_default=False, default=False),
+ ),
+ ]
diff --git a/products/notebooks/backend/migrations/max_migration.txt b/products/notebooks/backend/migrations/max_migration.txt
index 7a86ed6f9a95..ba8c194f5704 100644
--- a/products/notebooks/backend/migrations/max_migration.txt
+++ b/products/notebooks/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0012_kernelruntime_frames_and_more
+0013_notebooknoderun_connection_id_and_more
diff --git a/products/notebooks/backend/models.py b/products/notebooks/backend/models.py
index c5288a03f6be..01cabda34e11 100644
--- a/products/notebooks/backend/models.py
+++ b/products/notebooks/backend/models.py
@@ -231,6 +231,14 @@ class NotebookNodeRun(TeamScopedRootMixin, UUIDModel):
# The node's code at run time — paging must re-query what produced the result,
# not whatever the editor holds now.
code = models.TextField(blank=True, default="")
+ # The direct-query data source this run executed against (null = PostHog's own ClickHouse).
+ # Stored, not just passed through, because `code` is only meaningful on the engine that ran
+ # it: a re-query or a cross-cell reference has to target the same one. A plain id rather
+ # than an FK — a deleted source must not take run history with it.
+ connection_id = models.UUIDField(null=True, blank=True)
+ # Whether `code` went to the connection verbatim instead of being compiled from HogQL. Set,
+ # it means `code` is the engine's own dialect and the HogQL parser can't read it.
+ send_raw_query = models.BooleanField(default=False, db_default=False)
status = models.CharField(choices=Status, default=Status.RUNNING, max_length=20)
envelope: JSONField = JSONField(default=None, null=True, blank=True)
result_id = models.UUIDField(null=True, blank=True)
diff --git a/products/notebooks/backend/presentation/views/notebook.py b/products/notebooks/backend/presentation/views/notebook.py
index 65bee20edd4d..ccc0a0fe7dd0 100644
--- a/products/notebooks/backend/presentation/views/notebook.py
+++ b/products/notebooks/backend/presentation/views/notebook.py
@@ -27,6 +27,7 @@ from rest_framework.request import Request
from rest_framework.response import Response
from rest_framework.serializers import BaseSerializer
+from posthog.hogql.direct_connection import INVALID_CONNECTION_ID_ERROR, get_direct_connection_source
from posthog.hogql.errors import ExposedHogQLError
from posthog.hogql.query import execute_hogql_query
@@ -101,6 +102,21 @@ from ee.hogai.utils.asgi import SyncIterableToAsync
logger = structlog.get_logger(__name__)
+# Raised when a cell reads a sibling whose last result lives somewhere this run can't reach.
+_CROSS_ENGINE_REF_ERROR = (
+ "'{name}' last ran on a different connection, so this cell can't read it. "
+ "Point both cells at the same connection and re-run, or inline its query here."
+)
+# Python cells read upstream results through the data plane, which only reaches PostHog.
+_CROSS_ENGINE_REF_ERROR_FOR_PYTHON = (
+ "'{name}' ran on a warehouse connection, and Python cells can only read PostHog results. "
+ "Re-run '{name}' on PostHog to use it here."
+)
+_LOCAL_FRAME_REF_ERROR = (
+ "'{name}' is a Python dataframe, so only a cell running on PostHog can read it. "
+ "Switch this cell to PostHog to use it."
+)
+
def depluralize(string: str | None) -> str | None:
if not string:
@@ -632,6 +648,24 @@ class NotebookViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidD
if not self._has_query_access():
raise PermissionDenied("You need query access to run SQL in a notebook.")
+ def _require_run_connection_access(self, run: NotebookNodeRun, user: User | None) -> None:
+ # Dispatch resolved the source for the user who ran the cell, but the run row outlives
+ # that check and these endpoints serve its rows to anyone with notebook + query access.
+ # Without re-checking, a user denied viewer on the warehouse source could read rows a
+ # colleague's run pulled from it. Notebook + query access does not imply source access.
+ if not run.connection_id:
+ return
+ if (
+ get_direct_connection_source(
+ self.team,
+ str(run.connection_id),
+ user=user,
+ require_pure_direct=run.send_raw_query,
+ )
+ is None
+ ):
+ raise PermissionDenied("You need access to this cell's data source to read its results.")
+
def _current_user(self) -> User | None:
return self.request.user if isinstance(self.request.user, User) else None
@@ -1108,6 +1142,25 @@ class NotebookViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidD
notebook = self._get_notebook_for_kernel()
self._require_query_access()
+ node_type = serializer.validated_data["node_type"]
+ code = serializer.validated_data["code"]
+ output_name = serializer.validated_data["output_name"]
+ # Only SQL nodes carry a connection; python always runs in the kernel against PostHog.
+ connection_id = serializer.validated_data["connection_id"] if node_type != "python" else None
+ send_raw_query = bool(serializer.validated_data["send_raw_query"]) and connection_id is not None
+ if connection_id is not None and (
+ # Resolve up front so a stale or unreachable connection fails the dispatch with the
+ # shared message, rather than surfacing later as an opaque failed run.
+ get_direct_connection_source(
+ self.team,
+ str(connection_id),
+ user=user if isinstance(user, User) else None,
+ require_pure_direct=send_raw_query,
+ )
+ is None
+ ):
+ return Response({"detail": INVALID_CONNECTION_ID_ERROR}, status=400)
+
# Resolve each referenced hogql node to its last-run query (not its live editor text),
# so a join recomputes against the definitions that produced the results on screen.
# Inlining happens once here, so the run stores a self-contained query and paging
@@ -1121,37 +1174,53 @@ class NotebookViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidD
.filter(notebook=notebook, node_id__in=hogql_node_ids, status=NotebookNodeRun.Status.DONE)
.order_by("node_id", "-created_at")
.distinct("node_id")
- .values_list("node_id", "id", "code", "node_type")
+ .values_list("node_id", "id", "code", "node_type", "connection_id", "send_raw_query")
)
- # A SQL node's runs can alternate between hogql and duckdb (Journey 5 rerouting), so a
- # kind=hogql ref is only trustworthy when the node's LATEST result really is hogql —
- # a duckdb run's code is raw, non-self-contained SQL naming kernel frames, and inlining
- # it as a CTE would ship it to ClickHouse. Treat that node as not-run instead.
- latest_by_node: dict[str, tuple[str, str]] = {
- node_id: (str(run_id), code)
- for node_id, run_id, code, run_type in latest_runs
- if run_type == NotebookNodeRun.NodeType.HOGQL
- }
+ # A ref is only inlinable when the upstream node's LATEST run executed the same way this
+ # one will. A SQL node's runs can alternate between hogql and duckdb (Journey 5
+ # rerouting) and between engines, and its stored code only means anything on the engine
+ # that produced it — a duckdb run's code names kernel frames, and a connection run's is
+ # that warehouse's SQL. Inlining either elsewhere would ship the wrong query.
+ latest_by_node: dict[str, tuple[str, str]] = {}
+ other_engine_nodes: set[str] = set()
+ for other_node_id, run_id, run_code, run_type, run_connection_id, run_send_raw in latest_runs:
+ if run_type != NotebookNodeRun.NodeType.HOGQL:
+ continue
+ if run_connection_id == connection_id and bool(run_send_raw) == send_raw_query:
+ latest_by_node[other_node_id] = (str(run_id), run_code)
+ else:
+ other_engine_nodes.add(other_node_id)
+ cross_engine_error = _CROSS_ENGINE_REF_ERROR_FOR_PYTHON if node_type == "python" else _CROSS_ENGINE_REF_ERROR
refs: dict[str, SQLV2Ref] = {}
for name, spec in ref_specs.items():
if spec["kind"] == "local":
- refs[name] = SQLV2Ref(kind="local")
- else:
- latest = latest_by_node.get(spec["node_id"])
- refs[name] = SQLV2Ref(
- kind="hogql",
- node_id=spec["node_id"],
- run_id=latest[0] if latest else None,
- last_run_code=latest[1] if latest else None,
+ # A kernel frame lives in the sandbox, which only reaches PostHog's own data — a
+ # connection run can't be rerouted there, so mark it unusable instead.
+ refs[name] = (
+ SQLV2Ref(kind="hogql", node_id=None, unavailable_reason=_LOCAL_FRAME_REF_ERROR.format(name=name))
+ if connection_id is not None
+ else SQLV2Ref(kind="local")
)
- node_type = serializer.validated_data["node_type"]
- code = serializer.validated_data["code"]
- output_name = serializer.validated_data["output_name"]
+ continue
+ latest = latest_by_node.get(spec["node_id"])
+ refs[name] = SQLV2Ref(
+ kind="hogql",
+ node_id=spec["node_id"],
+ run_id=latest[0] if latest else None,
+ last_run_code=latest[1] if latest else None,
+ unavailable_reason=(
+ cross_engine_error.format(name=name) if spec["node_id"] in other_engine_nodes else None
+ ),
+ )
try:
if node_type == "python":
# A python node stores its code as-is; referenced frames become kernel inputs,
# keyed by the upstream run_id so a re-run yields a fresh (not stale) frame.
run_code, inputs = code, resolve_python_node_inputs(code, refs)
+ elif send_raw_query:
+ # Raw SQL is the connection's own dialect, so the HogQL parser can't read it and
+ # there is nothing to inline: it reaches the engine exactly as written.
+ run_code, inputs = code, []
else:
# A SQL node pushes to ClickHouse — unless it references a local frame, which
# reroutes it to the sandbox's DuckDB (Journey 5).
@@ -1170,6 +1239,8 @@ class NotebookViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidD
node_id=serializer.validated_data["node_id"],
code=run_code,
node_type=node_type,
+ connection_id=connection_id,
+ send_raw_query=send_raw_query,
status=NotebookNodeRun.Status.RUNNING,
)
@@ -1245,7 +1316,14 @@ class NotebookViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidD
# Direct (hogql) runs have no callback: this poll advances the row from the async
# query status, and while the manager's result is alive it also returns the full
# capped row set for client-side paging (`rows`, absent once expired).
+ #
+ # It runs before the access gate on purpose. This poll is the only thing that moves a
+ # direct run to a terminal state, and the only place its expiry watchdog fires, so
+ # gating first would strand the run RUNNING forever if the source was deleted or the
+ # caller lost access mid-query. Advancing the row leaks nothing — the gate below still
+ # decides whether any of it is returned.
rows = sync_direct_run(run)
+ self._require_run_connection_access(run, user)
# Interrupted runs keep their envelope too: the walkthrough (Journey 9) promises the
# captured stdout/stderr arrive with the final envelope even when the user stopped it.
@@ -1286,6 +1364,7 @@ class NotebookViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidD
raise Http404()
if run is None:
raise Http404()
+ self._require_run_connection_access(run, user)
if run.status != NotebookNodeRun.Status.DONE:
return Response({"detail": "Run has no result to page."}, status=400)
diff --git a/products/notebooks/backend/sql_v2_direct.py b/products/notebooks/backend/sql_v2_direct.py
index 2e77cbf0ca4a..ac484d75f667 100644
--- a/products/notebooks/backend/sql_v2_direct.py
+++ b/products/notebooks/backend/sql_v2_direct.py
@@ -10,6 +10,7 @@ the query status (`sync_direct_run`) because the manager has no completion callb
Kernel-lane runs (python/duckdb) keep the Temporal -> sandbox dispatch in sql_v2.py.
"""
+import re
import hmac
import hashlib
from typing import TYPE_CHECKING, Any
@@ -17,6 +18,7 @@ from typing import TYPE_CHECKING, Any
from django.conf import settings
from django.utils import timezone
+import sqlparse
import structlog
from posthog.hogql import ast
@@ -68,21 +70,69 @@ def notebook_direct_query_id(run_id: str) -> str:
).hexdigest()
-def _wrap_hogql_page_query(query: str, limit: int, offset: int) -> str:
+# Leading whitespace and comments, so the keyword check below sees the real first word.
+_LEADING_NOISE = re.compile(r"^(?:\s+|--[^\n]*\n?|/\*.*?\*/)+", re.DOTALL)
+# Statements that return rows but are not valid inside a derived table. Postgres (and so the
+# managed warehouse) admits these in raw mode — only MySQL restricts raw SQL to SELECT — and
+# they all produce tiny introspection results, so serving them unbounded is safe. Anything
+# unrecognized still gets wrapped: an over-eager bound is a syntax error the user can see,
+# while an over-eager pass-through would put an unbounded scan into the result store.
+_UNWRAPPABLE_LEADING_KEYWORDS = frozenset({"explain", "show", "describe", "desc", "pragma"})
+
+
+def _leading_keyword(query: str) -> str:
+ words = _LEADING_NOISE.sub("", query).split(None, 1)
+ return words[0].lower() if words else ""
+
+
+def _strip_statement_terminator(query: str) -> str:
+ """Drop the statement's ``;``, which parses cleanly but breaks once a LIMIT is appended or
+ the query is wrapped as a subquery.
+
+ The terminator is not always the last character: ``select 1; -- note`` is still one
+ statement to sqlparse, so it reaches here with the ``;`` buried mid-string, and wrapping
+ that as a subquery is a hard syntax error on Postgres and MySQL. Only the ``;`` token is
+ removed; a trailing comment is left where the user put it. (A trailing *block* comment
+ splits into a second statement, which the engine's single-statement guard rejects before
+ this point, so it never gets here.)
+ """
+ query = query.rstrip()
+ if query.endswith(";"):
+ return query[:-1].rstrip()
+
+ statements = sqlparse.parse(query)
+ if len(statements) != 1:
+ return query
+
+ tokens = list(statements[0].flatten())
+ for index in range(len(tokens) - 1, -1, -1):
+ token = tokens[index]
+ if token.is_whitespace or token.ttype in sqlparse.tokens.Comment:
+ continue
+ if token.ttype is sqlparse.tokens.Punctuation and token.value == ";":
+ return "".join(t.value for position, t in enumerate(tokens) if position != index).rstrip()
+ break
+ return query
+
+
+def _wrap_page_query(query: str, limit: int, offset: int) -> str:
"""Cap a page by wrapping the query in an outer ``select * from (...) limit/offset``.
The fallback for shapes where setting the bound on the query itself would change its
meaning: a paged offset or a query with its own OFFSET (both need result-set pagination
over the query's output), a set query (no single outer LIMIT), or a non-constant LIMIT.
The outer LIMIT does not push into an aggregated view, so prefer `apply_page_bounds`,
- which does.
-
- The inner query is validated HogQL and the wrapper is re-parsed as HogQL downstream, so
- there is no raw-SQL injection; limit/offset are int()-cast. The newline before the closing
- paren keeps a trailing line comment (`-- …`) in the user's query from swallowing the wrapper.
+ which does. Raw (engine-dialect) queries have no pushdown analysis available and always
+ land here.
+
+ The derived table is aliased because Postgres and MySQL reject an unaliased subquery in
+ FROM; HogQL accepts the alias and ignores it. The inner query is either validated HogQL
+ re-parsed downstream, or engine SQL the connection's own raw-SQL guard still vets, so
+ there is no injection; limit/offset are int()-cast. The newline before the closing paren
+ keeps a trailing line comment (`-- …`) in the user's query from swallowing the wrapper.
"""
# nosemgrep: semgrep.rules.security.hogql-fstring-audit
- return f"select * from ({query}\n) limit {int(limit)} offset {int(offset)}"
+ return f"select * from ({query}\n) as posthog_notebook_page limit {int(limit)} offset {int(offset)}"
def apply_page_bounds(query: str, limit: int, offset: int) -> str:
@@ -95,21 +145,16 @@ def apply_page_bounds(query: str, limit: int, offset: int) -> str:
re-print a parsed AST, which drops table-function arguments (`numbers(50001)`); a trailing
`;` is stripped first, since it parses but breaks once a LIMIT is appended or wrapped.
- Everything else falls back to `_wrap_hogql_page_query`: a query with its own LIMIT already
+ Everything else falls back to `_wrap_page_query`: a query with its own LIMIT already
pushes down through the wrapper's inner subquery, and a paged offset, a query with its own
OFFSET, a set query, or an unparseable query all need the wrapper's outer bound.
"""
- # A trailing `;` parses cleanly but breaks once we append LIMIT (or wrap the query as a
- # subquery), so normalize it away for both lanes. HogQL is single-statement, so this only
- # ever drops the terminator, never a second statement.
- query = query.rstrip()
- if query.endswith(";"):
- query = query[:-1].rstrip()
+ query = _strip_statement_terminator(query)
try:
parsed = parse_select(query)
except ExposedHogQLError:
- return _wrap_hogql_page_query(query, limit, offset)
+ return _wrap_page_query(query, limit, offset)
if (
offset == 0
@@ -124,7 +169,20 @@ def apply_page_bounds(query: str, limit: int, offset: int) -> str:
# nosemgrep: semgrep.rules.security.hogql-fstring-audit
return f"{query}\nlimit {int(limit)}"
- return _wrap_hogql_page_query(query, limit, offset)
+ return _wrap_page_query(query, limit, offset)
+
+
+def apply_raw_page_bounds(query: str, limit: int, offset: int) -> str:
+ """Bound a raw (engine-dialect) query, which the HogQL parser can't read.
+
+ No pushdown analysis is possible without parsing, so this is `apply_page_bounds`'s
+ wrapper fallback with the parse step skipped — except for the statements that cannot be
+ nested at all, which are served as written rather than turned into a syntax error.
+ """
+ query = _strip_statement_terminator(query)
+ if _leading_keyword(query) in _UNWRAPPABLE_LEADING_KEYWORDS:
+ return query
+ return _wrap_page_query(query, limit, offset)
def enqueue_direct_run(team: "Team", user: "User | None", run: NotebookNodeRun) -> None:
@@ -134,13 +192,26 @@ def enqueue_direct_run(team: "Team", user: "User | None", run: NotebookNodeRun)
access control, the per-team concurrency limiter, and the Redis status/result
store all come with it. Fetches one extra row past the cache ceiling so
`sync_direct_run` can detect has_more, mirroring the kernel's capped fetch.
+
+ A run bound to an external connection rides the same lane: the query runner routes it
+ to that source's engine, so nothing here needs to know which engine that is.
"""
- bounded = apply_page_bounds(run.code, limit=RESULT_CACHE_ROWS + 1, offset=0)
+ limit, offset = RESULT_CACHE_ROWS + 1, 0
+ bounded = (
+ apply_raw_page_bounds(run.code, limit, offset)
+ if run.send_raw_query
+ else apply_page_bounds(run.code, limit, offset)
+ )
+ query_json: dict[str, Any] = {"kind": "HogQLQuery", "query": bounded}
+ if run.connection_id:
+ query_json["connectionId"] = str(run.connection_id)
+ if run.send_raw_query:
+ query_json["sendRawQuery"] = True
with tags_context(product=Product.NOTEBOOKS, feature=Feature.QUERY, team_id=team.id):
enqueue_process_query_task(
team=team,
user_id=user.id if user else None,
- query_json={"kind": "HogQLQuery", "query": bounded},
+ query_json=query_json,
query_id=notebook_direct_query_id(str(run.id)),
# A Run click always executes; never serve a stale cached result.
refresh_requested=True,
diff --git a/products/notebooks/backend/sql_v2_kernel_architecture.md b/products/notebooks/backend/sql_v2_kernel_architecture.md
index d650c2f6efd0..c55c64a3afec 100644
--- a/products/notebooks/backend/sql_v2_kernel_architecture.md
+++ b/products/notebooks/backend/sql_v2_kernel_architecture.md
@@ -122,6 +122,17 @@ The routing rule (from the walkthrough, now concrete) — applied by the **backe
- `node.type == hogql` and **all** inputs are `hogql` → the **direct lane** (`sql_v2_direct.py`): the backend enqueues the inlined query on the async query manager and the run never reaches the sandbox at all — no kernel required, results land on the run row via the result poll. This amends walkthrough decision 4 ("the sandbox drives execution"): the backend routes, and the sandbox drives only kernel-lane runs. The server's own hogql handling (capped fetch, result cache, `/page` re-query) remains only for runs dispatched before the direct lane and is slated for removal.
- anything else (Python node, DuckDB node, or a HogQL node would go here if we ever allow HogQL over local frames — we don't; that's what DuckDB syntax is for) → materialize `hogql` inputs to frame files, run in the kernel. Dispatch provisions the kernel itself when none is running (the run is the user's ask for compute; the panel is presentation, not a prerequisite).
+### External connections
+
+A SQL cell can target a direct-query data source (the SQL editor's connection selector, rendered in the notebook's database tree) instead of PostHog's ClickHouse.
+The cell persists `connectionId` / `sendRawQuery`, the run request carries them, and `NotebookNodeRun` stores them — they reach the query runner as the `HogQLQuery` fields of the same name, so the engine choice is entirely the runner's concern.
+
+Consequences the lanes have to respect:
+
+- A connection run always takes the **direct lane**. The sandbox only reaches PostHog data, so a connection cell that reads a Python frame is rejected at dispatch rather than rerouted to DuckDB.
+- `code` only means something on the engine that ran it, so a ref is inlined as a CTE only when the upstream cell's latest run used the _same_ connection and the same raw mode. Anything else is refused at dispatch with a cross-engine message instead of being silently shipped to the wrong engine.
+- **Raw mode carries no references at all.** The HogQL parser can't read the engine's dialect, so there is nothing to inline and nothing to bound in place: `apply_raw_page_bounds` wraps the query in an aliased derived table (Postgres and MySQL reject an unaliased one) and the engine sees the rest verbatim.
+
## Result store and paging
`/page` reads `/data/results/<result_id>.arrow` in the **server** process (pyarrow mmap slice, or a read-only DuckDB connection for sorted/filtered pages). Consequences:
diff --git a/products/notebooks/backend/sql_v2_references.py b/products/notebooks/backend/sql_v2_references.py
index 881c12c47a6a..afea476784ee 100644
--- a/products/notebooks/backend/sql_v2_references.py
+++ b/products/notebooks/backend/sql_v2_references.py
@@ -50,12 +50,17 @@ class SQLV2Ref:
last_run_code identify its latest completed run (both None if it has never completed
one); kind "local" is a frame a Python node bound in the kernel namespace — it has
no query, only a name.
+
+ `unavailable_reason` marks a ref this run can't use even though the upstream cell has
+ run — a cross-engine reference, say. It replaces the generic "has not been run yet"
+ message, and only surfaces when the query actually reads the name.
"""
kind: str # "hogql" | "local"
node_id: str | None = None
run_id: str | None = None
last_run_code: str | None = None
+ unavailable_reason: str | None = None
class _ReferenceCollector(TraversingVisitor):
@@ -114,14 +119,15 @@ def _ordering_dependencies(query: ast.Expr, candidates: set[str]) -> set[str]:
return _collect(_NameReferenceCollector(candidates), query)
-def resolve_sql_v2_references(code: str, refs: dict[str, str | None]) -> str:
+def resolve_sql_v2_references(code: str, refs: dict[str, str | None], unavailable: dict[str, str] | None = None) -> str:
"""Return `code` with every referenced upstream definition inlined as a CTE.
`refs` maps a node's dataframe name to its **last-run** HogQL — the exact query that
produced the result the user is looking at — or None when that node has never
completed a run. A name absent from `refs` (e.g. a real table like ``events``) is
left untouched; a name present but None that `code` actually references raises,
- since there is no definition to join against yet.
+ since there is no definition to join against yet. `unavailable` overrides that
+ message per name for refs unusable for a more specific reason.
Names not actually referenced by `code` (transitively) are ignored. Returns `code`
unchanged when it references none of them, so a plain single-node run is byte-for-byte
@@ -144,7 +150,9 @@ def resolve_sql_v2_references(code: str, refs: dict[str, str | None]) -> str:
if name not in parsed:
raw = refs[name]
if raw is None or not raw.strip():
- raise SQLV2ReferenceError(f"Referenced node '{name}' has not been run yet — run it first.")
+ raise SQLV2ReferenceError(
+ (unavailable or {}).get(name) or f"Referenced node '{name}' has not been run yet — run it first."
+ )
try:
parsed[name] = parse_select(raw)
except ExposedHogQLError as exc:
@@ -225,6 +233,8 @@ def _hogql_input(name: str, ref: SQLV2Ref) -> dict[str, Any]:
"""The materialization spec for one HogQL ref: the executor fetches its last-run query to a
local Arrow file keyed by the upstream run_id, so the same run reuses its frame while a
re-run materializes fresh data and the node's superseded frames get evicted."""
+ if ref.unavailable_reason:
+ raise SQLV2ReferenceError(ref.unavailable_reason)
if ref.run_id is None or ref.last_run_code is None or not ref.last_run_code.strip():
raise SQLV2ReferenceError(f"Referenced node '{name}' has not been run yet — run it first.")
return {
@@ -275,7 +285,8 @@ def resolve_sql_node_run(code: str, refs: dict[str, SQLV2Ref]) -> tuple[str, str
"""
local_names = {name for name, ref in refs.items() if name and ref.kind == "local"}
hogql_refs = {name: ref for name, ref in refs.items() if name and ref.kind == "hogql"}
- hogql_codes = {name: ref.last_run_code for name, ref in hogql_refs.items()}
+ hogql_codes = {name: None if ref.unavailable_reason else ref.last_run_code for name, ref in hogql_refs.items()}
+ unavailable = {name: ref.unavailable_reason for name, ref in hogql_refs.items() if ref.unavailable_reason}
referenced_locals: set[str] = set()
referenced_hogql: set[str] = set()
if local_names:
@@ -295,7 +306,7 @@ def resolve_sql_node_run(code: str, refs: dict[str, SQLV2Ref]) -> tuple[str, str
referenced_hogql = found - local_names
if not referenced_locals:
- return "hogql", resolve_sql_v2_references(code, hogql_codes), []
+ return "hogql", resolve_sql_v2_references(code, hogql_codes, unavailable), []
inputs: list[dict[str, Any]] = []
for name in sorted(referenced_locals | referenced_hogql):
diff --git a/products/notebooks/backend/sql_v2_serializers.py b/products/notebooks/backend/sql_v2_serializers.py
index 51ee0a32817d..65cc5311bb09 100644
--- a/products/notebooks/backend/sql_v2_serializers.py
+++ b/products/notebooks/backend/sql_v2_serializers.py
@@ -62,6 +62,23 @@ class NotebookSQLV2RunRequestSerializer(serializers.Serializer):
"DuckDB; a python node materializes the hogql refs its code reads as pandas frames."
),
)
+ connection_id = serializers.UUIDField(
+ required=False,
+ allow_null=True,
+ default=None,
+ help_text=(
+ "SQL nodes only: id of a direct-query-capable external data source to run against "
+ "instead of PostHog's ClickHouse. Omit to query PostHog."
+ ),
+ )
+ send_raw_query = serializers.BooleanField(
+ required=False,
+ default=False,
+ help_text=(
+ "Send the code to the selected connection verbatim instead of compiling it from HogQL "
+ "first. Ignored without connection_id, and incompatible with references to other cells."
+ ),
+ )
class NotebookSQLV2PageRequestSerializer(serializers.Serializer):
diff --git a/products/notebooks/backend/test/test_sql_v2.py b/products/notebooks/backend/test/test_sql_v2.py
index 5d85d22dae15..1eee105f1a39 100644
--- a/products/notebooks/backend/test/test_sql_v2.py
+++ b/products/notebooks/backend/test/test_sql_v2.py
@@ -28,6 +28,7 @@ from posthog.constants import AvailableFeature
from posthog.models.organization import OrganizationMembership
from posthog.models.scoping import team_scope
from posthog.models.user import User
+from posthog.models.utils import UUIDT
from products.notebooks.backend.kernel_package import kernel_package_bytes_and_hash
from products.notebooks.backend.models import KernelRuntime, Notebook, NotebookNodeRun
@@ -58,7 +59,12 @@ from products.notebooks.backend.sql_v2 import (
)
from products.notebooks.backend.sql_v2_callback import MAX_ENVELOPE_BYTES
from products.notebooks.backend.sql_v2_data_plane import _rows_to_arrow_bytes
-from products.notebooks.backend.sql_v2_direct import apply_page_bounds, notebook_direct_query_id, sync_direct_run
+from products.notebooks.backend.sql_v2_direct import (
+ apply_page_bounds,
+ apply_raw_page_bounds,
+ notebook_direct_query_id,
+ sync_direct_run,
+)
from products.notebooks.backend.temporal.sql_v2 import (
SQLV2RunInput,
dispatch_sql_v2_run_activity,
@@ -150,6 +156,52 @@ class TestSQLV2ApplyPageBounds(SimpleTestCase):
assert isinstance(parsed.select_from.table, ast.SelectQuery | ast.SelectSetQuery)
assert isinstance(parsed.limit, ast.Constant) and parsed.limit.value == limit
+ @parameterized.expand(
+ [
+ ("plain", "select * from credit.billing_credits"),
+ ("trailing_semicolon", "select * from credit.billing_credits;"),
+ ]
+ )
+ def test_raw_bounding_wraps_with_an_alias(self, _name: str, query: str) -> None:
+ # Raw SQL is the connection's dialect, so it can't be parsed to find a pushdown spot —
+ # it is always wrapped. The derived table needs an alias or Postgres and MySQL reject it,
+ # and a trailing ';' would end the statement before the bound.
+ out = apply_raw_page_bounds(query, limit=301, offset=0)
+ assert (
+ out == "select * from (select * from credit.billing_credits\n) as posthog_notebook_page limit 301 offset 0"
+ )
+
+ @parameterized.expand(
+ [
+ ("explain", "explain select 1"),
+ ("uppercase", "EXPLAIN ANALYZE select 1"),
+ ("show", "show search_path"),
+ ("behind_a_comment", "-- why is this slow\nexplain select 1"),
+ ]
+ )
+ def test_raw_bounding_leaves_unnestable_statements_alone(self, _name: str, query: str) -> None:
+ # Postgres admits EXPLAIN/SHOW in raw mode (only MySQL restricts raw SQL to SELECT), and
+ # neither is valid inside a derived table. Wrapping them turns a query that works in the
+ # SQL editor into a syntax error, so they reach the engine as written.
+ assert apply_raw_page_bounds(query, limit=301, offset=0) == query
+
+ def test_raw_bounding_still_wraps_a_select_behind_a_comment(self) -> None:
+ # The leading-keyword check skips comments, so it must not mistake a commented SELECT
+ # for something unnestable and ship an unbounded scan into the result store.
+ out = apply_raw_page_bounds("-- daily totals\nselect * from users", limit=301, offset=0)
+ assert out.startswith("select * from (-- daily totals\nselect * from users")
+ assert out.endswith(") as posthog_notebook_page limit 301 offset 0")
+
+ def test_terminator_is_stripped_even_behind_a_trailing_comment(self) -> None:
+ # `select 1; -- note` is a single statement to sqlparse, so it passes the engine's
+ # single-statement guard and lands here with the ';' mid-string. Wrapping that as a
+ # derived table is a hard syntax error on Postgres and MySQL. The comment stays put.
+ out = apply_raw_page_bounds("select * from users; -- daily totals", limit=301, offset=0)
+ assert ";" not in out.split(") as posthog_notebook_page")[0]
+ assert (
+ out == "select * from (select * from users -- daily totals\n) as posthog_notebook_page limit 301 offset 0"
+ )
+
class TestSQLV2Callback(APIBaseTest):
def setUp(self):
@@ -650,6 +702,197 @@ class TestSQLV2Run(APIBaseTest):
self.assertEqual(run.status, NotebookNodeRun.Status.FAILED)
+@patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)
+class TestSQLV2RunOnAConnection(APIBaseTest):
+ def setUp(self):
+ super().setUp()
+ self.notebook = Notebook.objects.create(team=self.team, short_id="nbconn1")
+ self.run_url = f"/api/projects/{self.team.id}/notebooks/{self.notebook.short_id}/sql_v2/run/"
+ self.source_id = UUIDT()
+ # The source is another product's model, which this one may not import (tach). Notebooks
+ # only ever reaches it through core's resolver, so stub that seam: what this suite owns is
+ # whether notebooks calls it with the right arguments and honors its verdict. The
+ # resolver's own RBAC behavior is covered by the direct-connection tests in core.
+ patcher = patch(
+ "products.notebooks.backend.presentation.views.notebook.get_direct_connection_source",
+ return_value=SimpleNamespace(id=self.source_id),
+ )
+ self.mock_resolve_source = patcher.start()
+ self.addCleanup(patcher.stop)
+
+ def _post(self, **data: Any):
+ return self.client.post(self.run_url, data={"node_id": "n1", **data}, format="json")
+
+ def _record_done_run(self, node_id: str, code: str, connection_id: str | None = None) -> None:
+ with team_scope(self.team.id):
+ NotebookNodeRun.objects.create(
+ team=self.team,
+ notebook=self.notebook,
+ node_id=node_id,
+ code=code,
+ connection_id=connection_id,
+ status=NotebookNodeRun.Status.DONE,
+ )
+
+ @patch("products.notebooks.backend.sql_v2_direct.enqueue_process_query_task")
+ def test_connection_reaches_the_enqueued_query(self, mock_enqueue, _mock_enabled):
+ # The bug: the cell's connection was dropped at dispatch, so a warehouse query ran
+ # against ClickHouse and failed with "Unknown table". The id has to ride the query.
+ response = self._post(code="select * from public.users", connection_id=str(self.source_id))
+ self.assertEqual(response.status_code, 200)
+ run = NotebookNodeRun.objects.for_team(self.team.id).get(id=response.json()["run_id"])
+ self.assertEqual(str(run.connection_id), str(self.source_id))
+ self.assertFalse(run.send_raw_query)
+ query_json = mock_enqueue.call_args.kwargs["query_json"]
+ self.assertEqual(query_json["connectionId"], str(self.source_id))
+ self.assertNotIn("sendRawQuery", query_json)
+
+ @patch("products.notebooks.backend.sql_v2_direct.enqueue_process_query_task")
+ def test_raw_mode_ships_engine_sql_untouched(self, mock_enqueue, _mock_enabled):
+ # Raw SQL never reaches the HogQL parser: `::text` and friends would fail to parse, and
+ # a query the parser did accept must still arrive verbatim inside the row bound.
+ response = self._post(
+ code="select id::text from credit.billing_credits",
+ connection_id=str(self.source_id),
+ send_raw_query=True,
+ )
+ self.assertEqual(response.status_code, 200)
+ run = NotebookNodeRun.objects.for_team(self.team.id).get(id=response.json()["run_id"])
+ self.assertTrue(run.send_raw_query)
+ self.assertEqual(run.code, "select id::text from credit.billing_credits")
+ query_json = mock_enqueue.call_args.kwargs["query_json"]
+ self.assertTrue(query_json["sendRawQuery"])
+ self.assertIn("select id::text from credit.billing_credits", query_json["query"])
+ # Raw mode reads whatever the connection exposes, so it must be gated on a pure-direct
+ # source and on this user — a resolver call that dropped either would silently widen access.
+ resolve_kwargs = self.mock_resolve_source.call_args.kwargs
+ self.assertEqual(resolve_kwargs["user"], self.user)
+ self.assertTrue(resolve_kwargs["require_pure_direct"])
+
+ @patch("products.notebooks.backend.presentation.views.notebook.enqueue_direct_run")
+ def test_unknown_connection_fails_the_dispatch(self, mock_enqueue, _mock_enabled):
+ # Fail here rather than stranding a run that can only report an opaque error later.
+ self.mock_resolve_source.return_value = None
+ response = self._post(code="select 1", connection_id=str(UUIDT()))
+ self.assertEqual(response.status_code, 400)
+ self.assertIn("connectionId", response.json()["detail"])
+ mock_enqueue.assert_not_called()
+ self.assertFalse(NotebookNodeRun.objects.for_team(self.team.id).exists())
+
+ @parameterized.expand(
+ [
+ ("connection_cell_reading_a_posthog_cell", True),
+ ("posthog_cell_reading_a_connection_cell", False),
+ ]
+ )
+ @patch("products.notebooks.backend.presentation.views.notebook.enqueue_direct_run")
+ def test_cross_engine_reference_is_rejected(self, _name, run_on_connection, mock_enqueue, _mock_enabled):
+ # Both directions: a cell's stored SQL only means anything on the engine that ran it, so
+ # inlining it as a CTE elsewhere would silently ship the wrong query.
+ self._record_done_run(
+ "node-df1", "select id from events", connection_id=None if run_on_connection else str(self.source_id)
+ )
+ response = self._post(
+ code="select * from df1",
+ refs={"df1": {"node_id": "node-df1"}},
+ connection_id=str(self.source_id) if run_on_connection else None,
+ )
+ self.assertEqual(response.status_code, 400)
+ self.assertIn("last ran on a different connection", response.json()["detail"])
+ mock_enqueue.assert_not_called()
+
+ @patch("products.notebooks.backend.presentation.views.notebook.start_sql_v2_run_workflow")
+ def test_python_reading_a_connection_cell_says_what_to_do(self, mock_start, _mock_enabled):
+ # A Python cell materializes upstream results through the data plane, which only reaches
+ # PostHog — so it must say that, not tell the user to move a Python cell onto a warehouse.
+ self._record_done_run("node-wh", "select * from public.users", connection_id=str(self.source_id))
+ response = self._post(
+ code="print(wh_df.head())",
+ node_type="python",
+ refs={"wh_df": {"node_id": "node-wh"}},
+ )
+ self.assertEqual(response.status_code, 400)
+ self.assertIn("Python cells can only read PostHog results", response.json()["detail"])
+ mock_start.assert_not_called()
+
+ @patch("products.notebooks.backend.sql_v2_direct.enqueue_process_query_task")
+ def test_same_connection_reference_still_inlines(self, mock_enqueue, _mock_enabled):
+ # The rejection above must not swallow the ordinary case: two cells on one connection
+ # still compose, so the guard can't just refuse every ref once a connection is set.
+ self._record_done_run("node-df1", "select id from events", connection_id=str(self.source_id))
+ response = self._post(
+ code="select * from df1",
+ refs={"df1": {"node_id": "node-df1"}},
+ connection_id=str(self.source_id),
+ )
+ self.assertEqual(response.status_code, 200)
+ run = NotebookNodeRun.objects.for_team(self.team.id).get(id=response.json()["run_id"])
+ self.assertIn("WITH df1 AS (SELECT id FROM events)", run.code)
+ mock_enqueue.assert_called_once()
+
+ def test_reading_a_connection_run_needs_source_access(self, _mock_enabled):
+ # Dispatch gated the source, but the run row outlives that check and this endpoint serves
+ # its rows to anyone with notebook + query access. Without a re-check a member denied
+ # viewer on the warehouse could poll a colleague's run and read what it pulled.
+ with team_scope(self.team.id):
+ run = NotebookNodeRun.objects.create(
+ team=self.team,
+ notebook=self.notebook,
+ node_id="n1",
+ code="select * from public.users",
+ connection_id=self.source_id,
+ envelope={"status": "ok", "columns": ["id"], "first_page": [[1]]},
+ status=NotebookNodeRun.Status.DONE,
+ )
+ url = f"/api/projects/{self.team.id}/notebooks/{self.notebook.short_id}/sql_v2/runs/{run.id}/"
+ response = self.client.get(url)
+ self.assertEqual(response.status_code, 200)
+ self.assertEqual(response.json()["result"]["first_page"], [[1]])
+ # The read must be resolved for the caller, not for whoever ran the cell.
+ self.assertEqual(self.mock_resolve_source.call_args.kwargs["user"], self.user)
+
+ self.mock_resolve_source.return_value = None
+ self.assertEqual(self.client.get(url).status_code, 403)
+
+ def test_losing_source_access_mid_run_still_lets_the_run_reach_a_terminal_state(self, _mock_enabled):
+ # This poll is the only thing that advances a direct run, and the only place its expiry
+ # watchdog fires. Gating before that would strand the run RUNNING forever once access
+ # went away — so the row must still finish even though the caller is refused its rows.
+ with freeze_time("2026-07-01T00:00:00Z"), team_scope(self.team.id):
+ run = NotebookNodeRun.objects.create(
+ team=self.team,
+ notebook=self.notebook,
+ node_id="n1",
+ code="select * from public.users",
+ connection_id=self.source_id,
+ status=NotebookNodeRun.Status.RUNNING,
+ )
+ self.mock_resolve_source.return_value = None
+
+ url = f"/api/projects/{self.team.id}/notebooks/{self.notebook.short_id}/sql_v2/runs/{run.id}/"
+ self.assertEqual(self.client.get(url).status_code, 403)
+
+ run.refresh_from_db()
+ self.assertEqual(run.status, NotebookNodeRun.Status.FAILED)
+
+ @patch("products.notebooks.backend.presentation.views.notebook.start_sql_v2_run_workflow")
+ @patch("products.notebooks.backend.presentation.views.notebook.enqueue_direct_run")
+ def test_local_frame_reference_never_reroutes_a_connection_run_to_the_sandbox(
+ self, mock_enqueue, mock_start, _mock_enabled
+ ):
+ # Without the guard this takes Journey 5's DuckDB reroute, where the sandbox would run
+ # the query against a kernel frame instead of the warehouse the user picked.
+ response = self._post(
+ code="select * from new_events",
+ refs={"new_events": {"node_id": "node-py", "kind": "local"}},
+ connection_id=str(self.source_id),
+ )
+ self.assertEqual(response.status_code, 400)
+ self.assertIn("Python dataframe", response.json()["detail"])
+ mock_start.assert_not_called()
+ mock_enqueue.assert_not_called()
+
+
class _RecordingSandbox:
"""Stands in for the docker/Modal sandbox: records control-plane calls."""
diff --git a/products/notebooks/frontend/generated/api.schemas.ts b/products/notebooks/frontend/generated/api.schemas.ts
index 8752c12f54f4..3721cea3d80c 100644
--- a/products/notebooks/frontend/generated/api.schemas.ts
+++ b/products/notebooks/frontend/generated/api.schemas.ts
@@ -427,6 +427,13 @@ export interface NotebookSQLV2RunRequestApi {
output_name?: string
/** Available upstream nodes, keyed by dataframe name. A SQL node inlines referenced hogql refs as CTEs — unless it references a local ref, which reroutes the run to the sandbox's DuckDB; a python node materializes the hogql refs its code reads as pandas frames. */
refs?: NotebookSQLV2RunRequestApiRefs
+ /**
+ * SQL nodes only: id of a direct-query-capable external data source to run against instead of PostHog's ClickHouse. Omit to query PostHog.
+ * @nullable
+ */
+ connection_id?: string | null
+ /** Send the code to the selected connection verbatim instead of compiling it from HogQL first. Ignored without connection_id, and incompatible with references to other cells. */
+ send_raw_query?: boolean
}
export interface NotebookSQLV2RunResponseApi {
diff --git a/products/notebooks/frontend/generated/api.zod.ts b/products/notebooks/frontend/generated/api.zod.ts
index e935e01f8ebd..63357d4f9829 100644
--- a/products/notebooks/frontend/generated/api.zod.ts
+++ b/products/notebooks/frontend/generated/api.zod.ts
@@ -377,6 +377,7 @@ export const NotebooksKernelStopCreateBody = /* @__PURE__ */ zod.object({
export const notebooksSqlV2RunCreateBodyNodeTypeDefault = `hogql`
export const notebooksSqlV2RunCreateBodyOutputNameDefault = ``
export const notebooksSqlV2RunCreateBodyRefsKindDefault = `hogql`
+export const notebooksSqlV2RunCreateBodySendRawQueryDefault = false
export const NotebooksSqlV2RunCreateBody = /* @__PURE__ */ zod.object({
node_id: zod.string().describe('ProseMirror node id of the SQLV2 node being run.'),
@@ -414,4 +415,16 @@ export const NotebooksSqlV2RunCreateBody = /* @__PURE__ */ zod.object({
.describe(
"Available upstream nodes, keyed by dataframe name. A SQL node inlines referenced hogql refs as CTEs — unless it references a local ref, which reroutes the run to the sandbox's DuckDB; a python node materializes the hogql refs its code reads as pandas frames."
),
+ connection_id: zod
+ .uuid()
+ .nullish()
+ .describe(
+ "SQL nodes only: id of a direct-query-capable external data source to run against instead of PostHog's ClickHouse. Omit to query PostHog."
+ ),
+ send_raw_query: zod
+ .boolean()
+ .default(notebooksSqlV2RunCreateBodySendRawQueryDefault)
+ .describe(
+ 'Send the code to the selected connection verbatim instead of compiling it from HogQL first. Ignored without connection_id, and incompatible with references to other cells.'
+ ),
})
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 2aec0ebb3357..90cd83809c4a 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -43605,6 +43605,13 @@ export namespace Schemas {
output_name?: string;
/** Available upstream nodes, keyed by dataframe name. A SQL node inlines referenced hogql refs as CTEs — unless it references a local ref, which reroutes the run to the sandbox's DuckDB; a python node materializes the hogql refs its code reads as pandas frames. */
refs?: NotebookSQLV2RunRequestRefs;
+ /**
+ * SQL nodes only: id of a direct-query-capable external data source to run against instead of PostHog's ClickHouse. Omit to query PostHog.
+ * @nullable
+ */
+ connection_id?: string | null;
+ /** Send the code to the selected connection verbatim instead of compiling it from HogQL first. Ignored without connection_id, and incompatible with references to other cells. */
+ send_raw_query?: boolean;
}
export interface NotebookSQLV2RunResponse {