Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(notebooks): join SQLV2 nodes by referencing their results (#68419)

Sinan Kucukkoseler80668e1fcded
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index c1ecc5dbf614..f9f86bc890ca 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -4916,7 +4916,7 @@ const api = {
},
async sqlV2Run(
notebookId: NotebookType['short_id'],
- data: { node_id: string; code: string }
+ data: { node_id: string; code: string; refs?: Record<string, string> }
): 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 1a4e61de7d3f..85f307af4a15 100644
--- a/frontend/src/scenes/notebooks/Nodes/NotebookNodeSQLV2.tsx
+++ b/frontend/src/scenes/notebooks/Nodes/NotebookNodeSQLV2.tsx
@@ -1,6 +1,8 @@
import { useActions, useMountedLogic, useValues } from 'kea'
import { useMemo } from 'react'
+import { IconCornerDownRight } from '@posthog/icons'
+
import { LemonTabs } from 'lib/lemon-ui/LemonTabs'
import { OutputTab } from 'scenes/data-warehouse/editor/outputPaneLogic'
import { createPostHogWidgetNode } from 'scenes/notebooks/Nodes/NodeWrapper'
@@ -11,9 +13,10 @@ import { ChartDisplayType } from '~/types'
import { NotebookNodeAttributeProperties, NotebookNodeProps, NotebookNodeType } from '../types'
import { NotebookDataframeTable } from './components/NotebookDataframeTable'
+import { getCellLabel } from './components/NotebookNodeTitle'
import { NotebookCodeSQLEditorSettings } from './components/NotebookSQLEditor'
import { notebookNodeLogic } from './notebookNodeLogic'
-import { SQL_V2_DEFAULT_PAGE_SIZE, notebookNodeSQLV2Logic } from './notebookNodeSQLV2Logic'
+import { SQL_V2_DEFAULT_PAGE_SIZE, collectSqlV2Refs, notebookNodeSQLV2Logic } from './notebookNodeSQLV2Logic'
import { NotebookDataframeResult } from './pythonExecution'
export type NotebookNodeSQLV2Result = {
@@ -26,6 +29,8 @@ export type NotebookNodeSQLV2Result = {
export type NotebookNodeSQLV2Attributes = {
code: string
+ // Dataframe name other SQLV2 nodes can reference (inlined as a CTE when they join it).
+ returnVariable: string
runId?: string | null
result?: NotebookNodeSQLV2Result | null
outputTab?: OutputTab | null
@@ -65,7 +70,8 @@ const Component = ({
updateAttributes,
}: NotebookNodeProps<NotebookNodeSQLV2Attributes>): JSX.Element | null => {
const nodeLogic = useMountedLogic(notebookNodeLogic)
- const { nodeId, notebookLogic, expanded } = useValues(nodeLogic)
+ const { nodeId, notebookLogic, expanded, sqlV2ReturnVariableUsage } = useValues(nodeLogic)
+ const { navigateToNode } = useActions(nodeLogic)
const notebookShortId = notebookLogic.props.shortId
const dataLogic = notebookNodeSQLV2Logic({
@@ -78,6 +84,9 @@ const Component = ({
const { isRunning, runError, page, pageSize, pageResult, pageLoading, operationBlockReason } = useValues(dataLogic)
const { setPage, setPageSize } = useActions(dataLogic)
+ const usageLabel = (nodeType: NotebookNodeType, nodeIndex: number | undefined, title: string): string =>
+ title.trim() || getCellLabel(nodeIndex, nodeType) || 'SQL'
+
const result = attributes.result ?? null
// Page 1 at the default size comes straight from the envelope; other pages re-query CH.
const dataframeResult = useMemo(() => {
@@ -197,6 +206,38 @@ const Component = ({
</div>
) : null}
</div>
+ <div
+ className="flex shrink-0 items-center gap-2 text-xs text-muted border-t p-2"
+ onClick={(event) => event.stopPropagation()}
+ onMouseDown={(event) => event.stopPropagation()}
+ >
+ <span className="font-mono mt-0.5">
+ <IconCornerDownRight />
+ </span>
+ <input
+ type="text"
+ // A dataframe name other SQL nodes reference by table name (`from sql_df`).
+ className="rounded border border-border px-1.5 py-0.5 text-xs font-mono bg-bg-light text-default focus:outline-none focus:ring-1 focus:ring-primary"
+ value={attributes.returnVariable ?? ''}
+ onChange={(event) => updateAttributes({ returnVariable: event.target.value })}
+ spellCheck={false}
+ />
+ {sqlV2ReturnVariableUsage.length > 0 ? (
+ <span className="text-muted">
+ Used in{' '}
+ {sqlV2ReturnVariableUsage.map((usage) => (
+ <button
+ key={usage.nodeId}
+ type="button"
+ className="text-muted hover:text-default underline underline-offset-2 ml-1"
+ onClick={() => navigateToNode(usage.nodeId)}
+ >
+ {usageLabel(usage.nodeType, usage.nodeIndex, usage.title)}
+ </button>
+ ))}
+ </span>
+ ) : null}
+ </div>
</div>
)
}
@@ -224,7 +265,9 @@ const Settings = ({
attributes={attributes}
updateAttributes={updateAttributes}
tabIdSuffix="datav2"
- onRunQuery={(code) => runQuery(code)}
+ // 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))}
runQueryLoading={isRunning}
runQueryDisabledReason={operationBlockReason ?? undefined}
runQueryTooltip="Run SQL (v2) query"
@@ -244,6 +287,9 @@ export const NotebookNodeSQLV2 = createPostHogWidgetNode<NotebookNodeSQLV2Attrib
code: {
default: '',
},
+ returnVariable: {
+ default: 'sql_df',
+ },
runId: {
default: null,
},
diff --git a/frontend/src/scenes/notebooks/Nodes/notebookNodeContent.test.ts b/frontend/src/scenes/notebooks/Nodes/notebookNodeContent.test.ts
new file mode 100644
index 000000000000..9f806fe562bb
--- /dev/null
+++ b/frontend/src/scenes/notebooks/Nodes/notebookNodeContent.test.ts
@@ -0,0 +1,58 @@
+import { buildMarkdownNotebookContent, serializeMarkdownNotebookComponent } from '../Notebook/markdownNotebookV2'
+import { NotebookNodeType } from '../types'
+import { buildNotebookDependencyGraph } from './notebookNodeContent'
+
+describe('buildNotebookDependencyGraph', () => {
+ const sqlV2Node = (nodeId: string, returnVariable: string, code: string): Record<string, unknown> => ({
+ type: NotebookNodeType.SQLV2,
+ attrs: { nodeId, returnVariable, code },
+ })
+
+ it('links a SQLV2 node to a downstream SQLV2 node that references it by table name', () => {
+ // The "Used in" back-links depend on SQLV2 producing an export and its reader listing it as a use.
+ const content = {
+ type: 'doc',
+ content: [sqlV2Node('a', 'df1', 'select id from events'), sqlV2Node('b', 'joined', 'select * from df1')],
+ }
+ const graph = buildNotebookDependencyGraph(content)
+ expect(graph.downstreamUsageByNode['a'].df1.map((usage) => usage.nodeId)).toEqual(['b'])
+ expect(graph.upstreamSourcesByNode['b'].df1.nodeId).toEqual('a')
+ })
+
+ it('disambiguates two nodes that share a return variable so a reference links to only the first', () => {
+ // Without the uniquification pass both nodes would export `sql_df` and `from sql_df`
+ // would ambiguously attribute to both; the second node's export becomes `sql_df_2`.
+ const content = {
+ type: 'doc',
+ content: [
+ sqlV2Node('a', 'sql_df', 'select id from events'),
+ sqlV2Node('b', 'sql_df', 'select id from persons'),
+ sqlV2Node('c', 'joined', 'select * from sql_df'),
+ ],
+ }
+ const graph = buildNotebookDependencyGraph(content)
+ expect(graph.nodesById['b'].exports).toEqual(['sql_df_2'])
+ expect(graph.downstreamUsageByNode['a'].sql_df.map((usage) => usage.nodeId)).toEqual(['c'])
+ expect(graph.upstreamSourcesByNode['c'].sql_df.nodeId).toEqual('a')
+ })
+
+ it('links SQLV2 cells inside a markdown notebook', () => {
+ // Markdown notebooks hold cells as tags inside one markdown attribute; without
+ // expanding them the graph is empty and the "Used in" back-links never render.
+ const markdown = [
+ serializeMarkdownNotebookComponent('SQLV2', {
+ nodeId: 'a',
+ returnVariable: 'df1',
+ code: 'select id from events',
+ }),
+ serializeMarkdownNotebookComponent('SQLV2', {
+ nodeId: 'b',
+ returnVariable: 'joined',
+ code: 'select * from df1',
+ }),
+ ].join('\n\n')
+ const graph = buildNotebookDependencyGraph(buildMarkdownNotebookContent(markdown))
+ expect(graph.downstreamUsageByNode['a'].df1.map((usage) => usage.nodeId)).toEqual(['b'])
+ expect(graph.upstreamSourcesByNode['b'].df1.nodeId).toEqual('a')
+ })
+})
diff --git a/frontend/src/scenes/notebooks/Nodes/notebookNodeContent.ts b/frontend/src/scenes/notebooks/Nodes/notebookNodeContent.ts
index 4c2ea32e30b2..1dea80c8101c 100644
--- a/frontend/src/scenes/notebooks/Nodes/notebookNodeContent.ts
+++ b/frontend/src/scenes/notebooks/Nodes/notebookNodeContent.ts
@@ -1,5 +1,7 @@
+import { parseMarkdownNotebook } from 'lib/components/MarkdownNotebook/markdown'
import { JSONContent } from 'lib/components/RichContentEditor/types'
+import { NOTEBOOK_NODE_TYPE_TO_MARKDOWN_TAG } from '../Notebook/markdownNotebookV2'
import { NotebookNodeType } from '../types'
export type PythonNodeSummary = {
@@ -27,6 +29,15 @@ export type HogqlSqlNodeSummary = {
title: string
}
+export type SqlV2NodeSummary = {
+ nodeId: string
+ code: string
+ returnVariable: string
+ tablesUsed: string[]
+ sqlV2Index: number
+ title: string
+}
+
export type NotebookDependencyUsage = {
nodeId: string
nodeType: NotebookNodeType
@@ -223,6 +234,126 @@ export const getUniqueHogqlReturnVariable = (
return resolvedReturnVariable
}
+// SQLV2 nodes reference upstream nodes by bare table name (like DuckSQL) but use HogQL
+// identifiers (like the HogQL node), so they reuse both extraction helpers.
+export const resolveSqlV2ReturnVariable = (returnVariable: string): string => {
+ return returnVariable.trim() || 'sql_df'
+}
+
+const buildUniqueSqlV2ReturnVariable = (baseReturnVariable: string, used: Set<string>): string => {
+ const normalizedBase = normalizeSqlIdentifier(baseReturnVariable)
+ if (!used.has(normalizedBase)) {
+ return baseReturnVariable
+ }
+
+ let suffix = 2
+ while (true) {
+ const candidate = `${baseReturnVariable}_${suffix}`
+ if (!used.has(normalizeSqlIdentifier(candidate))) {
+ return candidate
+ }
+ suffix += 1
+ }
+}
+
+export const getUniqueSqlV2ReturnVariable = (
+ nodes: SqlV2NodeSummary[],
+ nodeId: string,
+ fallbackReturnVariable: string
+): string => {
+ const used = new Set<string>()
+ let resolvedReturnVariable = resolveSqlV2ReturnVariable(fallbackReturnVariable)
+ let resolvedFromNodes = false
+
+ nodes.forEach((node) => {
+ const baseReturnVariable = resolveSqlV2ReturnVariable(node.returnVariable)
+ const uniqueReturnVariable = buildUniqueSqlV2ReturnVariable(baseReturnVariable, used)
+ used.add(normalizeSqlIdentifier(uniqueReturnVariable))
+
+ if (node.nodeId === nodeId) {
+ resolvedReturnVariable = uniqueReturnVariable
+ resolvedFromNodes = true
+ }
+ })
+
+ if (!resolvedFromNodes) {
+ resolvedReturnVariable = buildUniqueSqlV2ReturnVariable(resolvedReturnVariable, used)
+ }
+
+ return resolvedReturnVariable
+}
+
+// Markdown notebooks hold their cells as component tags inside a single markdown attribute,
+// so walking the tiptap JSON alone never finds them. Expand `<SQLV2 …>` tags into
+// tiptap-shaped nodes so the collectors and the dependency graph see the same cells in both
+// notebook formats. Scoped to SQLV2: expanding the other node types here would change their
+// (currently markdown-blind) summaries and disambiguated naming.
+const expandMarkdownNotebookSqlV2Nodes = (node: any): JSONContent[] => {
+ if (typeof node?.attrs?.markdown !== 'string') {
+ return []
+ }
+ return parseMarkdownNotebook(node.attrs.markdown).nodes.flatMap((block) =>
+ block.type === 'component' && block.tagName === NOTEBOOK_NODE_TYPE_TO_MARKDOWN_TAG[NotebookNodeType.SQLV2]
+ ? [
+ {
+ type: NotebookNodeType.SQLV2,
+ attrs: {
+ ...block.props,
+ // Prefer the persisted nodeId prop: the parsed block id is a content
+ // fingerprint, which drifts from the live cell id as soon as any prop
+ // changes (running a cell writes runId/result into its props).
+ nodeId:
+ typeof block.props.nodeId === 'string' && block.props.nodeId
+ ? block.props.nodeId
+ : block.id,
+ },
+ },
+ ]
+ : []
+ )
+}
+
+export const collectSqlV2Nodes = (content?: JSONContent | null): SqlV2NodeSummary[] => {
+ if (!content || typeof content !== 'object') {
+ return []
+ }
+
+ const nodes: SqlV2NodeSummary[] = []
+ const usedReturnVariables = new Set<string>()
+
+ const walk = (node: any): void => {
+ if (!node || typeof node !== 'object') {
+ return
+ }
+ if (node.type === NotebookNodeType.SQLV2) {
+ const attrs = node.attrs ?? {}
+ const code = typeof attrs.code === 'string' ? attrs.code : ''
+ const baseReturnVariable = resolveSqlV2ReturnVariable(
+ typeof attrs.returnVariable === 'string' ? attrs.returnVariable : 'sql_df'
+ )
+ const returnVariable = buildUniqueSqlV2ReturnVariable(baseReturnVariable, usedReturnVariables)
+ usedReturnVariables.add(normalizeSqlIdentifier(returnVariable))
+ nodes.push({
+ nodeId: attrs.nodeId ?? '',
+ code,
+ returnVariable,
+ tablesUsed: extractDuckSqlTables(code),
+ sqlV2Index: nodes.length + 1,
+ title: typeof attrs.title === 'string' ? attrs.title : '',
+ })
+ }
+ if (node.type === NotebookNodeType.MarkdownNotebook) {
+ expandMarkdownNotebookSqlV2Nodes(node).forEach(walk)
+ }
+ if (Array.isArray(node.content)) {
+ node.content.forEach(walk)
+ }
+ }
+
+ walk(content)
+ return nodes
+}
+
export const collectPythonNodes = (content?: JSONContent | null): PythonNodeSummary[] => {
if (!content || typeof content !== 'object') {
return []
@@ -358,8 +489,10 @@ export const buildNotebookDependencyGraph = (content?: JSONContent | null): Note
let pythonIndex = 0
let duckSqlIndex = 0
let hogqlSqlIndex = 0
+ let sqlV2Index = 0
const usedDuckSqlReturnVariables = new Set<string>()
const usedHogqlReturnVariables = new Set<string>()
+ const usedSqlV2ReturnVariables = new Set<string>()
const walk = (node: any): void => {
if (!node || typeof node !== 'object') {
@@ -425,6 +558,31 @@ export const buildNotebookDependencyGraph = (content?: JSONContent | null): Note
})
}
+ if (node.type === NotebookNodeType.SQLV2) {
+ const attrs = node.attrs ?? {}
+ sqlV2Index += 1
+ const baseReturnVariable = resolveSqlV2ReturnVariable(
+ typeof attrs.returnVariable === 'string' ? attrs.returnVariable : 'sql_df'
+ )
+ const returnVariable = buildUniqueSqlV2ReturnVariable(baseReturnVariable, usedSqlV2ReturnVariables)
+ usedSqlV2ReturnVariables.add(normalizeSqlIdentifier(returnVariable))
+ const code = typeof attrs.code === 'string' ? attrs.code : ''
+ nodes.push({
+ nodeId: attrs.nodeId ?? '',
+ nodeType: NotebookNodeType.SQLV2,
+ nodeIndex: sqlV2Index,
+ title: typeof attrs.title === 'string' ? attrs.title : '',
+ exports: returnVariable ? [returnVariable] : [],
+ uses: extractDuckSqlTables(code),
+ code,
+ returnVariable,
+ })
+ }
+
+ if (node.type === NotebookNodeType.MarkdownNotebook) {
+ expandMarkdownNotebookSqlV2Nodes(node).forEach(walk)
+ }
+
if (Array.isArray(node.content)) {
node.content.forEach(walk)
}
diff --git a/frontend/src/scenes/notebooks/Nodes/notebookNodeLogic.ts b/frontend/src/scenes/notebooks/Nodes/notebookNodeLogic.ts
index c166f0debfe2..986e119b652c 100644
--- a/frontend/src/scenes/notebooks/Nodes/notebookNodeLogic.ts
+++ b/frontend/src/scenes/notebooks/Nodes/notebookNodeLogic.ts
@@ -46,6 +46,7 @@ import {
extractHogqlPlaceholders,
getUniqueDuckSqlReturnVariable,
getUniqueHogqlReturnVariable,
+ getUniqueSqlV2ReturnVariable,
resolveDuckSqlReturnVariable,
resolveHogqlReturnVariable,
} from './notebookNodeContent'
@@ -966,6 +967,7 @@ export const notebookNodeLogic = kea<notebookNodeLogicType>([
'pythonNodeSummaries',
'duckSqlNodeSummaries',
'hogqlSqlNodeSummaries',
+ 'sqlV2NodeSummaries',
'dependencyGraph',
'notebook',
'kernelInfo',
@@ -1205,6 +1207,16 @@ export const notebookNodeLogic = kea<notebookNodeLogicType>([
(dependencyGraph, nodeId, hogqlSqlReturnVariable): NotebookDependencyUsage[] =>
dependencyGraph.downstreamUsageByNode[nodeId]?.[hogqlSqlReturnVariable] ?? [],
],
+ sqlV2ReturnVariable: [
+ (s) => [s.sqlV2NodeSummaries, s.nodeId, s.nodeAttributes],
+ (sqlV2NodeSummaries, nodeId, nodeAttributes): string =>
+ getUniqueSqlV2ReturnVariable(sqlV2NodeSummaries, nodeId, nodeAttributes.returnVariable ?? ''),
+ ],
+ sqlV2ReturnVariableUsage: [
+ (s) => [s.dependencyGraph, s.nodeId, s.sqlV2ReturnVariable],
+ (dependencyGraph, nodeId, sqlV2ReturnVariable): NotebookDependencyUsage[] =>
+ dependencyGraph.downstreamUsageByNode[nodeId]?.[sqlV2ReturnVariable] ?? [],
+ ],
usageByVariable: [
(s) => [s.dependencyGraph, s.exportedGlobals, s.nodeId],
diff --git a/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.test.ts b/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.test.ts
index 9812e0bb3169..2e432204975c 100644
--- a/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.test.ts
+++ b/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.test.ts
@@ -1,10 +1,13 @@
import { expectLogic } from 'kea-test-utils'
import api from 'lib/api'
+import { JSONContent } from 'lib/components/RichContentEditor/types'
import { initKeaTests } from '~/test/init'
-import { notebookNodeSQLV2Logic } from './notebookNodeSQLV2Logic'
+import { buildMarkdownNotebookContent, serializeMarkdownNotebookComponent } from '../Notebook/markdownNotebookV2'
+import { NotebookNodeType } from '../types'
+import { collectSqlV2Refs, notebookNodeSQLV2Logic } from './notebookNodeSQLV2Logic'
describe('notebookNodeSQLV2Logic', () => {
let logic: ReturnType<typeof notebookNodeSQLV2Logic.build>
@@ -32,6 +35,58 @@ describe('notebookNodeSQLV2Logic', () => {
jest.restoreAllMocks()
})
+ describe('collectSqlV2Refs', () => {
+ const sqlNode = (nodeId: string, returnVariable: string): JSONContent => ({
+ type: NotebookNodeType.SQLV2,
+ attrs: { nodeId, returnVariable },
+ })
+
+ const doc = (...children: JSONContent[]): JSONContent => ({
+ type: 'doc',
+ content: children,
+ })
+
+ it('maps each named sibling to its node id, excluding the running node itself', () => {
+ // Including self would inline the node as a CTE of its own name — a cycle the backend rejects.
+ const document = doc(sqlNode('a', 'df1'), sqlNode('self', 'df2'), sqlNode('c', 'df3'))
+ expect(collectSqlV2Refs(document, 'self')).toEqual({ df1: 'a', df3: 'c' })
+ })
+
+ it('disambiguates duplicate names the way the dependency graph does', () => {
+ // Raw attributes would let node b shadow node a under the shared name —
+ // the join would silently run against the wrong node's data.
+ const document = doc(sqlNode('a', 'sql_df'), sqlNode('b', 'sql_df'), sqlNode('self', 'sql_df'))
+ expect(collectSqlV2Refs(document, 'self')).toEqual({ sql_df: 'a', sql_df_2: 'b' })
+ })
+
+ it('resolves blank names to the default the dependency graph shows', () => {
+ const document = doc(sqlNode('a', ''), sqlNode('b', ' '))
+ expect(collectSqlV2Refs(document, 'self')).toEqual({ sql_df: 'a', sql_df_2: 'b' })
+ })
+
+ it('finds SQLV2 nodes nested inside other content', () => {
+ const document = doc({ type: 'column', content: [sqlNode('a', 'df1')] })
+ expect(collectSqlV2Refs(document, 'self')).toEqual({ df1: 'a' })
+ })
+
+ it('collects refs from markdown notebook cells, preferring their persisted nodeId', () => {
+ // Markdown notebooks (the only surface with SQLV2 cells) hold cells as tags inside
+ // one markdown attribute — a tiptap-only walk returns {} and every ref breaks with
+ // "Unknown table". Persisted nodeIds must win over parsed ids: parsed block ids are
+ // content fingerprints that drift from the run's recorded node_id on any prop change.
+ const markdown = [
+ serializeMarkdownNotebookComponent('SQLV2', { nodeId: 'a', returnVariable: 'df1', code: 'select 1' }),
+ serializeMarkdownNotebookComponent('SQLV2', { nodeId: 'self', returnVariable: 'df2', code: '' }),
+ serializeMarkdownNotebookComponent('SQLV2', { returnVariable: 'df3', code: 'select 3' }),
+ ].join('\n\n')
+ const refs = collectSqlV2Refs(buildMarkdownNotebookContent(markdown), 'self')
+ expect(refs.df1).toEqual('a')
+ expect(refs.df2).toBeUndefined()
+ // Without a persisted nodeId the cell falls back to its parsed fingerprint id.
+ expect(refs.df3).toMatch(/^mdn-/)
+ })
+ })
+
it('rejects blank code before dispatching a run', async () => {
mount()
logic.actions.runQuery(' ')
@@ -45,9 +100,10 @@ describe('notebookNodeSQLV2Logic', () => {
mount()
logic.actions.runQuery('select 1')
await expectLogic(logic).toDispatchActions(['runQuery', 'startPolling', 'pollResult'])
- expect(runSpy).toHaveBeenCalledWith('nb1', { node_id: 'n1', code: 'select 1' })
- // The run id is persisted so a reload/remount can recover the in-flight run.
- expect(updateAttributes).toHaveBeenCalledWith({ runId: 'r1', result: null })
+ expect(runSpy).toHaveBeenCalledWith('nb1', { node_id: 'n1', code: 'select 1', refs: {} })
+ // runId is persisted so a reload/remount can recover the in-flight run; nodeId is
+ // pinned so the markdown cell's fingerprint id can't drift away from the run's node_id.
+ expect(updateAttributes).toHaveBeenCalledWith({ nodeId: 'n1', runId: 'r1', result: null })
})
it('maps a done envelope into the node result and stops the spinner', async () => {
diff --git a/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.ts b/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.ts
index 0c745b18cf9d..7210cd62207b 100644
--- a/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.ts
+++ b/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.ts
@@ -1,12 +1,29 @@
import { actions, afterMount, beforeUnmount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import api from 'lib/api'
+import { JSONContent } from 'lib/components/RichContentEditor/types'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { NotebookOperation, notebookOperationsLogic } from '../Notebook/notebookOperationsLogic'
+import { collectSqlV2Nodes } from './notebookNodeContent'
import { NotebookNodeSQLV2Result } from './NotebookNodeSQLV2'
import type { notebookNodeSQLV2LogicType } from './notebookNodeSQLV2LogicType'
+// Map every SQLV2 sibling's dataframe name -> node id, excluding the running node itself.
+// Delegates to collectSqlV2Nodes so duplicate names get the same disambiguated form the
+// dependency graph shows (sql_df, sql_df_2, …) — raw attributes would let a later duplicate
+// silently shadow the node the user actually referenced. The backend resolves each referenced
+// node to its last-run query and inlines it as a CTE — the frontend only supplies the wiring.
+export function collectSqlV2Refs(doc: JSONContent | null | undefined, selfNodeId: string): Record<string, string> {
+ const refs: Record<string, string> = {}
+ for (const node of collectSqlV2Nodes(doc)) {
+ if (node.nodeId && node.nodeId !== selfNodeId) {
+ refs[node.returnVariable] = node.nodeId
+ }
+ }
+ return refs
+}
+
const POLL_INTERVAL_MS = 1000
const MAX_POLL_ATTEMPTS = 150 // ~2.5 minutes at 1s
@@ -25,7 +42,11 @@ export interface NotebookNodeSQLV2LogicProps {
// Current node attributes, so a fresh mount can recover an in-flight/finished run by its runId.
runId?: string | null
hasResult?: boolean
- updateAttributes: (attrs: { runId?: string | null; result?: NotebookNodeSQLV2Result | null }) => void
+ updateAttributes: (attrs: {
+ nodeId?: string
+ runId?: string | null
+ result?: NotebookNodeSQLV2Result | null
+ }) => void
}
export const notebookNodeSQLV2Logic = kea<notebookNodeSQLV2LogicType>([
@@ -40,7 +61,9 @@ export const notebookNodeSQLV2Logic = kea<notebookNodeSQLV2LogicType>([
],
})),
actions({
- runQuery: (code: string) => ({ code }),
+ // refs maps each named sibling node's dataframe name to its HogQL; the backend
+ // inlines the ones this query references as CTEs (Journey 3).
+ runQuery: (code: string, refs: Record<string, string> = {}) => ({ code, refs }),
startPolling: (runId: string) => ({ runId }),
pollResult: (runId: string) => ({ runId }),
stopPolling: true,
@@ -162,7 +185,7 @@ export const notebookNodeSQLV2Logic = kea<notebookNodeSQLV2LogicType>([
return {
setPage: loadCurrentPage,
setPageSize: loadCurrentPage,
- runQuery: async ({ code }) => {
+ runQuery: async ({ code, refs }) => {
if (!code.trim()) {
actions.setRunError('Query is empty — type some HogQL first.')
actions.setIsRunning(false)
@@ -180,11 +203,15 @@ export const notebookNodeSQLV2Logic = kea<notebookNodeSQLV2LogicType>([
const { run_id } = await api.notebooks.sqlV2Run(props.notebookShortId, {
node_id: props.nodeId,
code,
+ refs,
})
// 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.
cache.activeRunId = run_id
- props.updateAttributes({ runId: run_id, result: null })
+ // Persisting nodeId pins the cell's identity: markdown-notebook cell ids are
+ // content fingerprints otherwise, so without the pin any later prop change
+ // would orphan this run's node_id and break refs to this cell.
+ props.updateAttributes({ nodeId: props.nodeId, runId: run_id, result: null })
actions.startPolling(run_id)
} catch (error) {
actions.setRunError(error instanceof Error ? error.message : 'Failed to run query')
diff --git a/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.tsx b/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.tsx
index 4d59de59ec71..bfe586218d03 100644
--- a/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.tsx
+++ b/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.tsx
@@ -56,6 +56,7 @@ import { useUploadFiles } from 'lib/hooks/useUploadFiles'
import { LemonFileInput } from 'lib/lemon-ui/LemonFileInput'
import { Spinner } from 'lib/lemon-ui/Spinner'
import { type FeatureFlagsSet } from 'lib/logic/featureFlagLogic'
+import { uuid } from 'lib/utils/dom'
import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
import { NODE_ICONS } from '../nodeIcons'
@@ -156,7 +157,18 @@ export const MARKDOWN_NODE_DEFINITIONS: {
{ tagName: 'HogQLSQL', category: 'SQL', label: 'SQL (HogQL)' },
// insertCommand makes it show in the markdown insert menu; the feature-flag gate in
// getMarkdownRegistryForFeatureFlags strips it when revamped-py-notebooks is off.
- { tagName: 'SQLV2', category: 'SQL', label: 'SQL (v2)', insertCommand: { aliases: ['data', 'sql'] } },
+ {
+ tagName: 'SQLV2',
+ category: 'SQL',
+ label: 'SQL (v2)',
+ insertCommand: {
+ aliases: ['data', 'sql'],
+ // New cells get a durable nodeId up front: parsed markdown block ids are content
+ // fingerprints, so without a persisted id every prop change (running the cell
+ // writes runId/result) would orphan the cell's run history and cross-cell refs.
+ defaultProps: () => ({ ...getDefaultPropsForNodeType(NotebookNodeType.SQLV2), nodeId: uuid() }),
+ },
+ },
{ tagName: 'RecordingPlaylist', category: 'Data', label: 'Session recordings' },
{ tagName: 'Experiment', category: 'Experiment' },
{ tagName: 'Image', category: 'Media', EditComponent: ImageEdit },
diff --git a/frontend/src/scenes/notebooks/Notebook/notebookLogic.ts b/frontend/src/scenes/notebooks/Notebook/notebookLogic.ts
index 39c766eafee3..595537e1c8dd 100644
--- a/frontend/src/scenes/notebooks/Notebook/notebookLogic.ts
+++ b/frontend/src/scenes/notebooks/Notebook/notebookLogic.ts
@@ -78,6 +78,7 @@ import {
collectHogqlSqlNodes,
collectNodeIndices,
collectPythonNodes,
+ collectSqlV2Nodes,
} from '../Nodes/notebookNodeContent'
import { notebookNodeLogicType } from '../Nodes/notebookNodeLogicType'
// NOTE: Annoyingly, if we import this then kea logic type-gen generates
@@ -1211,6 +1212,7 @@ export const notebookLogic = kea<notebookLogicType>([
pythonNodeSummaries: [(s) => [s.content], (content) => collectPythonNodes(content)],
duckSqlNodeSummaries: [(s) => [s.content], (content) => collectDuckSqlNodes(content)],
hogqlSqlNodeSummaries: [(s) => [s.content], (content) => collectHogqlSqlNodes(content)],
+ sqlV2NodeSummaries: [(s) => [s.content], (content) => collectSqlV2Nodes(content)],
dependencyGraph: [(s) => [s.content], (content) => buildNotebookDependencyGraph(content)],
pythonNodeIndices: [
diff --git a/products/notebooks/backend/presentation/views/notebook.py b/products/notebooks/backend/presentation/views/notebook.py
index 0e1692424637..9efcb54db9b5 100644
--- a/products/notebooks/backend/presentation/views/notebook.py
+++ b/products/notebooks/backend/presentation/views/notebook.py
@@ -61,6 +61,7 @@ from products.notebooks.backend.sql_v2 import (
is_sql_v2_enabled,
sql_v2_page_lock_key,
)
+from products.notebooks.backend.sql_v2_references import SQLV2ReferenceError, resolve_sql_v2_references
from products.notebooks.backend.sql_v2_serializers import (
NotebookSQLV2PageRequestSerializer,
NotebookSQLV2RunRequestSerializer,
@@ -919,11 +920,32 @@ class NotebookViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidD
notebook = self._get_notebook_for_kernel()
self._require_query_access()
+ # Resolve each referenced 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 re-queries it
+ # without re-resolving refs.
+ ref_node_ids: dict[str, str] = serializer.validated_data.get("refs") or {}
+ # One DISTINCT ON query fetches the latest DONE run for every referenced node at once.
+ code_by_node_id: dict[str, str] = dict(
+ NotebookNodeRun.objects.for_team(self.team_id)
+ .filter(notebook=notebook, node_id__in=set(ref_node_ids.values()), status=NotebookNodeRun.Status.DONE)
+ .order_by("node_id", "-created_at")
+ .distinct("node_id")
+ .values_list("node_id", "code")
+ )
+ last_run_code: dict[str, str | None] = {
+ name: code_by_node_id.get(node_id) for name, node_id in ref_node_ids.items()
+ }
+ try:
+ resolved_code = resolve_sql_v2_references(serializer.validated_data["code"], last_run_code)
+ except SQLV2ReferenceError as e:
+ return Response({"detail": str(e)}, status=400)
+
run = NotebookNodeRun.objects.create(
team_id=self.team_id,
notebook=notebook,
node_id=serializer.validated_data["node_id"],
- code=serializer.validated_data["code"],
+ code=resolved_code,
status=NotebookNodeRun.Status.RUNNING,
)
@@ -934,7 +956,7 @@ class NotebookViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidD
notebook_short_id=notebook.short_id,
team_id=self.team_id,
user_id=user.id if isinstance(user, User) else None,
- code=serializer.validated_data["code"],
+ code=resolved_code,
)
)
except Exception:
diff --git a/products/notebooks/backend/sql_v2_references.py b/products/notebooks/backend/sql_v2_references.py
new file mode 100644
index 000000000000..9b4016260a31
--- /dev/null
+++ b/products/notebooks/backend/sql_v2_references.py
@@ -0,0 +1,126 @@
+"""Resolve SQLV2 node references by inlining upstream node queries as CTEs (Journey 3).
+
+A SQLV2 node is a HogQL *query definition*, not a materialized frame. When one node
+references another by its dataframe name — ``select … from df1 join df2`` — the whole
+thing recomputes in ClickHouse with the referenced definitions inlined as CTEs
+(decision 1 in the journey walkthroughs). We do that inlining here, once, at dispatch:
+the run stores the self-contained query, so paging (a re-query of the same node) reuses
+it verbatim and the data plane never has to know about references.
+
+Only names the query actually reaches are inlined, transitively and in dependency order
+(a CTE must be printed before the CTEs that use it). A name the query shadows with its
+own ``WITH`` is left alone. Broken definitions that nothing references are never parsed,
+so an unrelated malformed node can't fail a run.
+"""
+
+from posthog.hogql import ast
+from posthog.hogql.context import HogQLContext
+from posthog.hogql.errors import ExposedHogQLError
+from posthog.hogql.parser import parse_select
+from posthog.hogql.printer import print_prepared_ast
+from posthog.hogql.visitor import TraversingVisitor
+
+
+class SQLV2ReferenceError(Exception):
+ """A reference could not be resolved (cycle, or a referenced definition won't parse). User-facing."""
+
+
+class _TableReferenceCollector(TraversingVisitor):
+ """Collect the FROM/JOIN targets of a query that name one of `candidates`.
+
+ Only bare single-identifier tables count — ``from df1`` matches, a column called
+ ``df1`` does not — so a reference is a genuine table position, not any mention.
+ """
+
+ def __init__(self, candidates: set[str]) -> None:
+ self.candidates = candidates
+ self.found: set[str] = set()
+
+ def visit_join_expr(self, node: ast.JoinExpr) -> None:
+ table = node.table
+ if isinstance(table, ast.Field) and len(table.chain) == 1 and table.chain[0] in self.candidates:
+ name = table.chain[0]
+ if isinstance(name, str):
+ self.found.add(name)
+ super().visit_join_expr(node)
+
+
+def _references(query: ast.SelectQuery | ast.SelectSetQuery, candidates: set[str]) -> set[str]:
+ collector = _TableReferenceCollector(candidates)
+ collector.visit(query)
+ # A name the query defines as its own CTE shadows the ref — don't pull it in.
+ own_ctes = set(query.ctes.keys()) if isinstance(query, ast.SelectQuery) and query.ctes else set()
+ return collector.found - own_ctes
+
+
+def resolve_sql_v2_references(code: str, refs: dict[str, str | 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.
+
+ 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
+ what the user wrote.
+
+ Raises SQLV2ReferenceError on a reference cycle, an unparseable referenced
+ definition, or a referenced node that has not been run; the caller surfaces it.
+ """
+ candidates = {name for name in refs if name}
+ if not candidates:
+ return code
+
+ main = parse_select(code)
+ if not _references(main, candidates):
+ return code
+
+ parsed: dict[str, ast.SelectQuery | ast.SelectSetQuery] = {}
+
+ def parse_ref(name: str) -> ast.SelectQuery | ast.SelectSetQuery:
+ 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.")
+ try:
+ parsed[name] = parse_select(raw)
+ except ExposedHogQLError as exc:
+ raise SQLV2ReferenceError(f"Referenced query '{name}' is invalid: {exc}") from exc
+ return parsed[name]
+
+ # Depth-first post-order so each CTE is emitted before the ones that use it; the GRAY
+ # marker catches cycles (a name reached while still on the stack).
+ WHITE, GRAY, BLACK = 0, 1, 2
+ color: dict[str, int] = {}
+ order: list[str] = []
+
+ def visit(name: str) -> None:
+ color[name] = GRAY
+ for dependency in sorted(_references(parse_ref(name), candidates)):
+ if color.get(dependency) == GRAY:
+ raise SQLV2ReferenceError(f"Reference cycle through '{dependency}'.")
+ if color.get(dependency, WHITE) == WHITE:
+ visit(dependency)
+ color[name] = BLACK
+ order.append(name)
+
+ for start in sorted(_references(main, candidates)):
+ if color.get(start, WHITE) == WHITE:
+ visit(start)
+
+ # The merged WITH hangs off a SelectQuery; wrap a top-level UNION so it can carry one.
+ # The f-string embeds only `code`, already validated as HogQL by parse_select above; the
+ # wrap is re-parsed here and printed via the AST printer, so no raw SQL reaches ClickHouse.
+ # nosemgrep: semgrep.rules.security.hogql-fstring-audit
+ root = main if isinstance(main, ast.SelectQuery) else parse_select(f"select * from ({code})")
+ if not isinstance(root, ast.SelectQuery): # narrow for the type checker; the wrap is always a SelectQuery
+ return code
+ ctes: dict[str, ast.CTE] = dict(root.ctes or {})
+ for name in order:
+ # setdefault so the user's own CTE of the same name always wins over a node ref.
+ ctes.setdefault(name, ast.CTE(name=name, expr=parse_ref(name), cte_type="subquery"))
+ root.ctes = ctes
+
+ return print_prepared_ast(root, context=HogQLContext(team_id=None), dialect="hogql")
diff --git a/products/notebooks/backend/sql_v2_serializers.py b/products/notebooks/backend/sql_v2_serializers.py
index 7b6b8c567fa6..80183991dbb4 100644
--- a/products/notebooks/backend/sql_v2_serializers.py
+++ b/products/notebooks/backend/sql_v2_serializers.py
@@ -6,6 +6,16 @@ class NotebookSQLV2RunRequestSerializer(serializers.Serializer):
code = serializers.CharField(
help_text="The HogQL the node contains; the sandbox runs it through the data plane. Must not be blank.",
)
+ refs = serializers.DictField(
+ child=serializers.CharField(),
+ required=False,
+ default=dict,
+ help_text=(
+ "Available upstream nodes, mapping each named node's dataframe name to its ProseMirror "
+ "node id. The backend inlines the ones this node references as CTEs using each node's "
+ "last-run query (not its live editor text); unreferenced entries are ignored."
+ ),
+ )
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 3a2a06b9bd76..82850b455701 100644
--- a/products/notebooks/backend/test/test_sql_v2.py
+++ b/products/notebooks/backend/test/test_sql_v2.py
@@ -10,6 +10,7 @@ from http.server import ThreadingHTTPServer
from types import SimpleNamespace
from typing import Any
+from freezegun import freeze_time
from posthog.test.base import APIBaseTest
from unittest.mock import patch
@@ -193,6 +194,68 @@ class TestSQLV2Run(APIBaseTest):
self.assertEqual(NotebookNodeRun.objects.for_team(self.team.id).filter(notebook=self.notebook).count(), 0)
mock_start.assert_not_called()
+ def _record_done_run(self, node_id: str, code: str) -> None:
+ with team_scope(self.team.id):
+ NotebookNodeRun.objects.create(
+ team=self.team,
+ notebook=self.notebook,
+ node_id=node_id,
+ code=code,
+ status=NotebookNodeRun.Status.DONE,
+ )
+
+ @patch("products.notebooks.backend.presentation.views.notebook.start_sql_v2_run_workflow")
+ @patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)
+ def test_run_inlines_referenced_nodes_last_run_query_as_ctes(self, _mock_enabled, mock_start):
+ # Paging re-queries run.code, so the stored + dispatched query must already carry the
+ # referenced definitions as CTEs — and it must be each node's last run, not its live text.
+ self._record_done_run("node-df1", "select id from events")
+ self._record_done_run("node-df2", "select id from persons")
+ response = self.client.post(
+ self.run_url,
+ data={
+ "node_id": "join-node",
+ "code": "select * from df1 join df2 on df1.id = df2.id",
+ "refs": {"df1": "node-df1", "df2": "node-df2"},
+ },
+ format="json",
+ )
+ 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)
+ self.assertIn("df2 AS (SELECT id FROM persons)", run.code)
+ self.assertEqual(mock_start.call_args.args[0].code, run.code)
+
+ @patch("products.notebooks.backend.presentation.views.notebook.start_sql_v2_run_workflow")
+ @patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)
+ def test_run_uses_the_latest_done_run_of_a_referenced_node(self, _mock_enabled, mock_start):
+ # An edited-then-rerun upstream: only its most recent run should be inlined.
+ with freeze_time("2026-07-04T00:00:00Z"):
+ self._record_done_run("node-df1", "select 1 as old_col")
+ with freeze_time("2026-07-04T00:01:00Z"):
+ self._record_done_run("node-df1", "select 2 as new_col")
+ response = self.client.post(
+ self.run_url,
+ data={"node_id": "c", "code": "select * from df1", "refs": {"df1": "node-df1"}},
+ format="json",
+ )
+ self.assertEqual(response.status_code, 200)
+ run = NotebookNodeRun.objects.for_team(self.team.id).get(id=response.json()["run_id"])
+ self.assertIn("new_col", run.code)
+ self.assertNotIn("old_col", run.code)
+
+ @patch("products.notebooks.backend.presentation.views.notebook.start_sql_v2_run_workflow")
+ @patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)
+ def test_run_rejects_referencing_a_never_run_node(self, _mock_enabled, mock_start):
+ response = self.client.post(
+ self.run_url,
+ data={"node_id": "c", "code": "select * from df1", "refs": {"df1": "node-df1"}},
+ format="json",
+ )
+ self.assertEqual(response.status_code, 400)
+ self.assertEqual(NotebookNodeRun.objects.for_team(self.team.id).filter(node_id="c").count(), 0)
+ mock_start.assert_not_called()
+
@patch(
"products.notebooks.backend.presentation.views.notebook.start_sql_v2_run_workflow",
side_effect=RuntimeError("temporal unavailable"),
diff --git a/products/notebooks/backend/test/test_sql_v2_references.py b/products/notebooks/backend/test/test_sql_v2_references.py
new file mode 100644
index 000000000000..11cd4e832b6e
--- /dev/null
+++ b/products/notebooks/backend/test/test_sql_v2_references.py
@@ -0,0 +1,83 @@
+from django.test import SimpleTestCase
+
+from products.notebooks.backend.sql_v2_references import SQLV2ReferenceError, resolve_sql_v2_references
+
+
+class TestResolveSQLV2References(SimpleTestCase):
+ def test_query_referencing_nothing_is_returned_verbatim(self):
+ # Paging and the run row store this string as-is; rewriting a plain run would break both.
+ self.assertEqual(resolve_sql_v2_references("select 1", {"df1": "select id from events"}), "select 1")
+
+ def test_no_refs_is_returned_verbatim(self):
+ self.assertEqual(resolve_sql_v2_references("select * from df1", {}), "select * from df1")
+
+ def test_referenced_nodes_are_inlined_as_ctes(self):
+ resolved = resolve_sql_v2_references(
+ "select * from df1 join df2 on df1.id = df2.id",
+ {"df1": "select id from events", "df2": "select id from persons"},
+ )
+ self.assertIn("WITH df1 AS (SELECT id FROM events)", resolved)
+ self.assertIn("df2 AS (SELECT id FROM persons)", resolved)
+ self.assertIn("df1 JOIN df2", resolved)
+
+ def test_transitive_reference_is_ordered_before_its_user(self):
+ # df2 reads df1, so df1's CTE must be printed first or ClickHouse can't resolve it.
+ resolved = resolve_sql_v2_references(
+ "select * from df2",
+ {"df1": "select id from events", "df2": "select id from df1 where id > 0"},
+ )
+ self.assertLess(resolved.index("df1 AS"), resolved.index("df2 AS"))
+
+ def test_unreferenced_definitions_are_not_inlined_or_parsed(self):
+ # A malformed node nobody references must never fail an unrelated run.
+ resolved = resolve_sql_v2_references(
+ "select * from df1",
+ {"df1": "select id from events", "broken": "select from where syntax("},
+ )
+ self.assertIn("df1 AS", resolved)
+ self.assertNotIn("broken", resolved)
+
+ def test_user_defined_cte_shadows_a_node_of_the_same_name(self):
+ # `with df1 as (...)` is the user's own frame — don't replace it with the node's definition.
+ resolved = resolve_sql_v2_references(
+ "with df1 as (select 9 as n) select * from df1",
+ {"df1": "select id from events"},
+ )
+ self.assertNotIn("from events", resolved.lower())
+
+ def test_user_with_clause_is_preserved_when_merging_refs(self):
+ resolved = resolve_sql_v2_references(
+ "with mine as (select 1 as x) select * from mine join df1 on true",
+ {"df1": "select id from events"},
+ )
+ self.assertIn("mine AS", resolved)
+ self.assertIn("df1 AS", resolved)
+
+ def test_top_level_union_referencing_a_node_is_wrapped_with_the_cte(self):
+ # A SelectSetQuery can't carry a WITH, so it gets wrapped in a SELECT that can.
+ resolved = resolve_sql_v2_references(
+ "select * from df1 union all select id from events",
+ {"df1": "select id from events"},
+ )
+ self.assertIn("WITH df1 AS", resolved)
+ self.assertIn("UNION ALL", resolved)
+
+ def test_reference_cycle_raises(self):
+ with self.assertRaises(SQLV2ReferenceError):
+ resolve_sql_v2_references(
+ "select * from a",
+ {"a": "select * from b", "b": "select * from a"},
+ )
+
+ def test_invalid_referenced_definition_raises(self):
+ with self.assertRaises(SQLV2ReferenceError):
+ resolve_sql_v2_references("select * from df1", {"df1": "select from where ("})
+
+ def test_referencing_a_never_run_node_raises(self):
+ # df1 is a known node (present in refs) but has no last-run definition to inline.
+ with self.assertRaises(SQLV2ReferenceError):
+ resolve_sql_v2_references("select * from df1", {"df1": None})
+
+ def test_unreferenced_never_run_node_is_ignored(self):
+ # A never-run node nobody references must not block the run.
+ self.assertEqual(resolve_sql_v2_references("select 1", {"df1": None}), "select 1")
diff --git a/pyproject.toml b/pyproject.toml
index bfc5beeb0550..9048c3daa41a 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -580,6 +580,7 @@ ignore_imports = [
"products.notebooks.backend.presentation.views.notebook -> products.notebooks.backend.python_analysis",
"products.notebooks.backend.presentation.views.notebook -> products.notebooks.backend.query_validation",
"products.notebooks.backend.presentation.views.notebook -> products.notebooks.backend.sql_v2",
+ "products.notebooks.backend.presentation.views.notebook -> products.notebooks.backend.sql_v2_references",
"products.notebooks.backend.presentation.views.notebook -> products.notebooks.backend.sql_v2_serializers",
"products.notebooks.backend.presentation.views.notebook -> products.notebooks.backend.temporal.client",
"products.notebooks.backend.presentation.views.notebook -> products.notebooks.backend.temporal.sql_v2",