Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

Implement run notebook functionality (#49178)

Joshen Lim7adc83ee39b3
diff --git a/apps/studio/components/interfaces/Explorer/ExplorerNotebookTab.tsx b/apps/studio/components/interfaces/Explorer/ExplorerNotebookTab.tsx
index 0579a193645..adc39e12076 100644
--- a/apps/studio/components/interfaces/Explorer/ExplorerNotebookTab.tsx
+++ b/apps/studio/components/interfaces/Explorer/ExplorerNotebookTab.tsx
@@ -13,6 +13,7 @@ import {
} from '@dnd-kit/sortable'
import { useParams } from 'common'
import { FileText, Notebook, NotebookText, Play, Save, SquareCode } from 'lucide-react'
+import { useRef, useState } from 'react'
import { AiIconAnimation, Button } from 'ui'
import { EmptyStatePresentational } from 'ui-patterns/EmptyStatePresentational'
@@ -25,6 +26,7 @@ import {
} from './ExplorerToolbar'
import { MarkdownCell } from './MarkdownCell'
import { QueryCell } from './QueryCell'
+import { type QueryEditorHandle } from './QueryEditor'
import { createMarkdownCellSkeleton, createQueryCellSkeleton } from './utils'
import { ButtonTooltip } from '@/components/ui/ButtonTooltip'
import { isQueryCell } from '@/data/content/notebooks/notebook-schema'
@@ -39,6 +41,10 @@ export const ExplorerNotebookTab = () => {
const currentNotebook = useCurrentNotebook()
const { name, content } = currentNotebook?.notebook ?? {}
const cells = content?.cells ?? []
+ const queryCellIds = cells.filter(isQueryCell).map((cell) => cell.id)
+
+ const [isRunningNotebook, setIsRunningNotebook] = useState(false)
+ const queryCellRefs = useRef(new Map<string, QueryEditorHandle>())
const sensors = useSensors(
useSensor(PointerSensor, { activationConstraint: { distance: 8 } }),
@@ -53,6 +59,17 @@ export const ExplorerNotebookTab = () => {
}
}
+ const handleRunNotebook = async () => {
+ setIsRunningNotebook(true)
+ try {
+ await Promise.allSettled(
+ queryCellIds.map((cellId) => queryCellRefs.current.get(cellId)?.run())
+ )
+ } finally {
+ setIsRunningNotebook(false)
+ }
+ }
+
const handleDragEnd = (event: DragEndEvent) => {
const { active, over } = event
if (!id || !over || active.id === over.id) return
@@ -81,7 +98,14 @@ export const ExplorerNotebookTab = () => {
<ExplorerToolbarAction icon={<AiIconAnimation size={16} />}>
Analyze
</ExplorerToolbarAction>
- <ExplorerToolbarAction icon={<Play />} tooltip="Run notebook" />
+ <ExplorerToolbarAction
+ aria-label="Run notebook"
+ icon={<Play />}
+ tooltip="Run notebook"
+ loading={isRunningNotebook}
+ disabled={isRunningNotebook || queryCellIds.length === 0}
+ onClick={handleRunNotebook}
+ />
<ExplorerToolbarAction icon={<Save />} tooltip="Save changes" />
</ExplorerToolbarActions>
</ExplorerToolbar>
@@ -115,7 +139,14 @@ export const ExplorerNotebookTab = () => {
<div className="flex flex-col gap-y-4">
{cells.map((cell) =>
isQueryCell(cell) ? (
- <QueryCell key={cell.id} cell={cell} />
+ <QueryCell
+ key={cell.id}
+ cell={cell}
+ ref={(instance) => {
+ if (instance) queryCellRefs.current.set(cell.id, instance)
+ else queryCellRefs.current.delete(cell.id)
+ }}
+ />
) : (
<MarkdownCell key={cell.id} cell={cell} />
)
diff --git a/apps/studio/components/interfaces/Explorer/QueryCell/index.tsx b/apps/studio/components/interfaces/Explorer/QueryCell/index.tsx
index 80adb841a03..dec95340133 100644
--- a/apps/studio/components/interfaces/Explorer/QueryCell/index.tsx
+++ b/apps/studio/components/interfaces/Explorer/QueryCell/index.tsx
@@ -1,9 +1,9 @@
-import { useState } from 'react'
+import { forwardRef, useState } from 'react'
import { type Snapshot } from 'valtio'
import { AddCellDropdown } from '../AddCellDropdown'
import { MoveCellDropdownContent } from '../MoveCellDropdownContent'
-import { QueryEditor } from '../QueryEditor'
+import { QueryEditor, type QueryEditorHandle } from '../QueryEditor'
import { type QueryDisplay, type QueryResult } from '../types'
import {
changeCellSource,
@@ -28,7 +28,10 @@ interface QueryCellProps {
}
/** Notebook adapter around the shared QueryEditor. */
-export const QueryCell = ({ cell }: QueryCellProps) => {
+export const QueryCell = forwardRef<QueryEditorHandle, QueryCellProps>(function QueryCell(
+ { cell },
+ ref
+) {
const snap = useNotebooksStateSnapshot()
const currentNotebook = useCurrentNotebook()
@@ -92,6 +95,7 @@ export const QueryCell = ({ cell }: QueryCellProps) => {
gripClassName="mt-2 opacity-0 group-hover:opacity-100 has-[[data-state=open]]:opacity-100 transition"
>
<QueryEditor
+ ref={ref}
id={cell.id}
variant="embedded"
title={title}
@@ -109,4 +113,4 @@ export const QueryCell = ({ cell }: QueryCellProps) => {
/>
</SortableSection>
)
-}
+})
diff --git a/apps/studio/components/interfaces/Explorer/QueryEditor/index.tsx b/apps/studio/components/interfaces/Explorer/QueryEditor/index.tsx
index 5fdf763e0f6..9812f213582 100644
--- a/apps/studio/components/interfaces/Explorer/QueryEditor/index.tsx
+++ b/apps/studio/components/interfaces/Explorer/QueryEditor/index.tsx
@@ -1,7 +1,7 @@
import { acceptUntrustedSql, untrustedSql, type UntrustedSqlFragment } from '@supabase/pg-meta'
import { useFlag } from 'common'
import { CodeSquare, Eye, EyeOff, Play } from 'lucide-react'
-import { useState, type ReactNode } from 'react'
+import { forwardRef, useImperativeHandle, useState, type ReactNode } from 'react'
import { cn } from 'ui'
import { resolveLogTimeRange } from '../../QuerySources/LogTimeRange.utils'
@@ -86,28 +86,35 @@ export type QueryEditorProps = {
onDisplayChange?: (display: QueryDisplay) => void
}
+export type QueryEditorHandle = {
+ run: () => Promise<void>
+}
+
/**
* Shared query editor used by query tabs, notebook cells, and other Explorer surfaces.
* The consuming surface owns persistence and surrounding chrome; this component owns
* query-level UI and execution behavior.
*/
-export const QueryEditor = ({
- id,
- variant,
- title,
- query,
- result,
- roleImpersonationState,
- display,
- toolbarActions,
- onTitleChange,
- onSqlChange,
- onSqlCommit,
- onSourceChange,
- onResultChange,
- onRowLimitChange,
- onDisplayChange,
-}: QueryEditorProps) => {
+export const QueryEditor = forwardRef<QueryEditorHandle, QueryEditorProps>(function QueryEditor(
+ {
+ id,
+ variant,
+ title,
+ query,
+ result,
+ roleImpersonationState,
+ display,
+ toolbarActions,
+ onTitleChange,
+ onSqlChange,
+ onSqlCommit,
+ onSourceChange,
+ onResultChange,
+ onRowLimitChange,
+ onDisplayChange,
+ }: QueryEditorProps,
+ ref
+) {
const sql = query.uncheckedSql
const sqlRef = useLatest<string>(sql)
const onSqlCommitRef = useLatest(onSqlCommit)
@@ -132,12 +139,12 @@ export const QueryEditor = ({
}
)
- const { mutate: executeSql, isPending: isExecutingSql } = useExecuteSqlMutation({
+ const { mutateAsync: executeSql, isPending: isExecutingSql } = useExecuteSqlMutation({
onSuccess: (data) => onResultChange({ rows: data.result }),
onError: (error) => onResultChange({ error }),
})
- const { mutate: executeLogsSql, isPending: isExecutingLogs } = useExecuteLogsSqlMutation({
+ const { mutateAsync: executeLogsSql, isPending: isExecutingLogs } = useExecuteLogsSqlMutation({
onSuccess: (data) => onResultChange({ rows: data.rows as readonly Record<string, unknown>[] }),
onError: (error) => onResultChange({ error }),
})
@@ -154,7 +161,7 @@ export const QueryEditor = ({
* decided by `query._tag`, the same discriminant that picks the execution endpoint, so
* Postgres SQL cannot reach the analytics wire or vice versa.
*/
- const handleRunQuery = (rawSql: string = sql) => {
+ const handleRunQuery = async (rawSql: string = sql) => {
if (!project || isBusy || rawSql.trim().length === 0) return
onSqlCommit?.(rawSql)
@@ -167,12 +174,12 @@ export const QueryEditor = ({
return
}
- executeLogsSql({
+ await executeLogsSql({
projectRef: project.ref,
sql: acceptUntrustedLogsSql(untrustedLogSql(rawSql)),
range: resolveLogTimeRange(query.time_range),
endpoint: QUERY_SOURCE_REGISTRY.logs.endpoint,
- })
+ }).catch(() => {})
return
}
@@ -189,7 +196,7 @@ export const QueryEditor = ({
return
}
- executeSql({
+ await executeSql({
projectRef: project.ref,
connectionString,
sql: wrapWithRoleImpersonation(limitedSql.sql, roleImpersonationState),
@@ -197,9 +204,11 @@ export const QueryEditor = ({
contextualInvalidation: true,
isStatementTimeoutDisabled: true,
isRoleImpersonationEnabled: isRoleImpersonationEnabled(roleImpersonationState?.role),
- })
+ }).catch(() => {})
}
+ useImperativeHandle(ref, () => ({ run: () => handleRunQuery() }))
+
const Shell = variant === 'viewport' ? ExplorerQueryViewport : ExplorerQuery
return (
@@ -286,4 +295,4 @@ export const QueryEditor = ({
</ExplorerQueryFooter>
</Shell>
)
-}
+})
diff --git a/apps/studio/components/interfaces/Explorer/__tests__/ExplorerNotebookTab.test.tsx b/apps/studio/components/interfaces/Explorer/__tests__/ExplorerNotebookTab.test.tsx
new file mode 100644
index 00000000000..882d79dfb94
--- /dev/null
+++ b/apps/studio/components/interfaces/Explorer/__tests__/ExplorerNotebookTab.test.tsx
@@ -0,0 +1,133 @@
+import { screen, waitFor } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { HttpResponse } from 'msw'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { ExplorerNotebookTab } from '../ExplorerNotebookTab'
+import { createMarkdownCellSkeleton, createQueryCellSkeleton } from '../utils'
+import { untrustedLogSql } from '@/data/logs/safe-analytics-sql'
+import { notebooksState } from '@/state/notebooks/notebooks-state'
+import type { Notebook, StateNotebook } from '@/state/notebooks/types'
+import { createTabsState, TabsStateContext } from '@/state/tabs'
+import { customRender } from '@/tests/lib/custom-render'
+import { addAPIMock } from '@/tests/lib/msw'
+import { setupSqlEditorMocks } from '@/tests/lib/sql-editor-test-utils'
+import type { Notebooks } from '@/types'
+
+const testContext = vi.hoisted(() => ({
+ flags: { otelLegacyLogs: true } as Record<string, boolean>,
+}))
+
+vi.mock('common', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('common')>()
+ return {
+ ...actual,
+ IS_PLATFORM: true,
+ useParams: () => ({ ref: 'default', id: 'notebook-test' }),
+ useFlag: (flag: string) => testContext.flags[flag] ?? false,
+ }
+})
+
+vi.mock('@/components/ui/CodeEditor/CodeEditor', () => ({
+ CodeEditor: ({ value }: { value: string }) => (
+ <textarea aria-label="SQL editor" value={value} readOnly />
+ ),
+}))
+
+vi.mock('../QueryEditor/QuerySourceMenu', () => ({
+ QuerySourceMenu: () => null,
+}))
+
+const NOTEBOOK_ID = 'notebook-test'
+
+const databaseCell = createQueryCellSkeleton({ sql: 'select 1' })
+const logCell = {
+ _tag: 'log_cell' as const,
+ id: 'log-cell-1',
+ view: 'table' as const,
+ chart: undefined,
+ unchecked_sql: untrustedLogSql('select * from edge_logs limit 1'),
+ time_range: { _tag: 'relative_time_range' as const, amount: 1, unit: 'hour' as const },
+}
+const markdownCell = createMarkdownCellSkeleton()
+
+/**
+ * Assigns directly into the store rather than going through `setNotebook` — that helper
+ * no-ops when a notebook with content already exists, which would make reseeding between
+ * tests (or within one, for the empty-notebook case) silently keep the previous cells.
+ */
+const seedNotebook = (cells: Notebooks.Cell[]) => {
+ const notebook: Notebook = {
+ id: NOTEBOOK_ID,
+ type: 'notebook',
+ name: 'Test notebook',
+ visibility: 'project',
+ favorite: false,
+ owner_id: 1,
+ project_id: 1,
+ content: { schema_version: 1, cells },
+ }
+ const stateNotebook: StateNotebook = { projectRef: 'default', notebook, status: 'saved' }
+ notebooksState.notebooks[NOTEBOOK_ID] = stateNotebook
+}
+
+const renderNotebookTab = () =>
+ customRender(
+ <TabsStateContext.Provider value={createTabsState('default')}>
+ <ExplorerNotebookTab />
+ </TabsStateContext.Provider>
+ )
+
+beforeEach(() => {
+ setupSqlEditorMocks()
+ testContext.flags.otelLegacyLogs = true
+ for (const id of Object.keys(notebooksState.notebooks)) {
+ delete notebooksState.notebooks[id]
+ }
+ seedNotebook([databaseCell, logCell, markdownCell])
+})
+
+afterEach(() => notebooksState.needsSaving.clear())
+
+describe('ExplorerNotebookTab', () => {
+ it('runs every database and log cell, and skips markdown cells, on "Run notebook"', async () => {
+ const dbRequests: Request[] = []
+ addAPIMock({
+ method: 'post',
+ path: '/platform/pg-meta/:ref/query',
+ response: ({ request }) => {
+ dbRequests.push(request)
+ return HttpResponse.json([{ result: 1 }])
+ },
+ })
+
+ const logRequests: Request[] = []
+ addAPIMock({
+ method: 'post',
+ path: '/platform/projects/:ref/analytics/endpoints/logs.all.otel',
+ response: ({ request }) => {
+ logRequests.push(request)
+ return HttpResponse.json({ result: [] })
+ },
+ })
+
+ renderNotebookTab()
+
+ const runNotebookButton = await screen.findByRole('button', { name: 'Run notebook' })
+ await waitFor(() => expect(runNotebookButton).toBeEnabled())
+ await userEvent.click(runNotebookButton)
+
+ await waitFor(() => expect(dbRequests).toHaveLength(1))
+ await waitFor(() => expect(logRequests).toHaveLength(1))
+ await waitFor(() => expect(runNotebookButton).toBeEnabled())
+ })
+
+ it('disables "Run notebook" when the notebook has no database or log cells', async () => {
+ seedNotebook([createMarkdownCellSkeleton()])
+
+ renderNotebookTab()
+
+ const runNotebookButton = await screen.findByRole('button', { name: 'Run notebook' })
+ expect(runNotebookButton).toBeDisabled()
+ })
+})