Skip to content

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

Add copy notebook as markdown action (#50200)

Joshen Lim8ac64a4349c9
diff --git a/apps/studio/components/interfaces/Explorer/ExplorerNotebookTab.tsx b/apps/studio/components/interfaces/Explorer/ExplorerNotebookTab.tsx
index b0fc1af2124..811eabe4407 100644
--- a/apps/studio/components/interfaces/Explorer/ExplorerNotebookTab.tsx
+++ b/apps/studio/components/interfaces/Explorer/ExplorerNotebookTab.tsx
@@ -16,6 +16,7 @@ import { useQueryClient } from '@tanstack/react-query'
import { LOCAL_STORAGE_KEYS, useParams } from 'common'
import {
Check,
+ Copy,
FileText,
Keyboard,
Loader2,
@@ -36,6 +37,7 @@ import {
Badge,
Button,
Checkbox,
+ copyToClipboard,
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
@@ -49,6 +51,7 @@ import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
import {
findQueryCellsMatchingSql,
isMutatingSql,
+ notebookToMarkdown,
type QueryCellSummary,
} from './ExplorerNotebookTab.utils'
import {
@@ -312,6 +315,22 @@ export const ExplorerNotebookTab = () => {
}
}
+ const handleCopyAsMarkdown = async () => {
+ try {
+ await copyToClipboard(
+ notebookToMarkdown({
+ name: name ?? '',
+ cells,
+ getResult: (cellId) => queryCellRefs.current.get(cellId)?.getResult(),
+ }),
+ () => toast.success('Copied notebook as Markdown to clipboard')
+ )
+ } catch (err: unknown) {
+ const message = err instanceof Error ? err.message : String(err)
+ toast.error('Failed to copy notebook as Markdown: ' + message)
+ }
+ }
+
const handleConfirmDeleteNotebook = () => {
if (!ref || !id) return
deleteNotebook({ projectRef: ref, ids: [id] })
@@ -419,6 +438,10 @@ export const ExplorerNotebookTab = () => {
</div>
{isIntellisenseEnabled && <Check className="text-brand" size={16} />}
</DropdownMenuItem>
+ <DropdownMenuItem className="gap-x-2" onClick={handleCopyAsMarkdown}>
+ <Copy size={14} />
+ <span>Copy as Markdown</span>
+ </DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem className="gap-x-2" onClick={() => setIsDeleteModalOpen(true)}>
<Trash size={14} />
diff --git a/apps/studio/components/interfaces/Explorer/ExplorerNotebookTab.utils.test.ts b/apps/studio/components/interfaces/Explorer/ExplorerNotebookTab.utils.test.ts
index 1bee6c16038..9b4feca2e98 100644
--- a/apps/studio/components/interfaces/Explorer/ExplorerNotebookTab.utils.test.ts
+++ b/apps/studio/components/interfaces/Explorer/ExplorerNotebookTab.utils.test.ts
@@ -1,10 +1,16 @@
import { untrustedSql } from '@supabase/pg-meta'
+import dayjs from 'dayjs'
import { describe, expect, it } from 'vitest'
-import { findQueryCellsMatchingSql, isMutatingSql } from './ExplorerNotebookTab.utils'
+import {
+ findQueryCellsMatchingSql,
+ isMutatingSql,
+ notebookToMarkdown,
+} from './ExplorerNotebookTab.utils'
import { checkDestructiveQuery } from '@/components/interfaces/SQLEditor/SQLEditor.utils'
import { type Cell } from '@/data/content/notebooks/notebook-schema'
import { untrustedLogSql } from '@/data/logs/safe-analytics-sql'
+import { isoDateTimeString } from '@/lib/iso-datetime'
describe('isMutatingSql', () => {
it('returns false for a read-only query', () => {
@@ -192,3 +198,145 @@ describe('findQueryCellsMatchingSql', () => {
).toEqual([{ id: 'cell-1', title: 'Signups' }])
})
})
+
+describe('notebookToMarkdown', () => {
+ const markdownCell: Cell = {
+ _tag: 'markdown_cell',
+ _id: 'cell-1',
+ text: '## Notes\n\nSome context here.',
+ }
+
+ const databaseCell: Cell = {
+ _tag: 'database_cell',
+ _id: 'cell-2',
+ title: 'Signups',
+ view: 'table',
+ unchecked_sql: untrustedSql('select * from auth.users'),
+ row_limit: 50,
+ }
+
+ const relativeLogCell: Cell = {
+ _tag: 'log_cell',
+ _id: 'cell-3',
+ title: 'Edge errors',
+ view: 'table',
+ unchecked_sql: untrustedLogSql('select * from edge_logs where status_code >= 500'),
+ time_range: { _tag: 'relative_time_range', unit: 'hour', amount: 24 },
+ }
+
+ const absoluteRangeStart = isoDateTimeString('2026-01-01T00:00:00.000Z')!
+ const absoluteRangeEnd = isoDateTimeString('2026-01-02T00:00:00.000Z')!
+
+ const absoluteLogCell: Cell = {
+ _tag: 'log_cell',
+ _id: 'cell-4',
+ title: undefined,
+ view: 'table',
+ unchecked_sql: untrustedLogSql('select * from postgres_logs'),
+ time_range: {
+ _tag: 'absolute_time_range',
+ start: absoluteRangeStart,
+ end: absoluteRangeEnd,
+ },
+ }
+
+ it('renders the notebook name as a heading followed by each cell in order', () => {
+ const result = notebookToMarkdown({ name: 'My notebook', cells: [markdownCell, databaseCell] })
+
+ expect(result).toBe(
+ [
+ '# My notebook',
+ '## Notes\n\nSome context here.',
+ '### Signups (Postgres)\n\n```sql\nselect * from auth.users\n```',
+ ].join('\n\n')
+ )
+ })
+
+ it('falls back to "Untitled query" when a query cell has no title', () => {
+ const result = notebookToMarkdown({ name: 'Notebook', cells: [absoluteLogCell] })
+ expect(result).toContain('### Untitled query (Logs — ClickHouse)')
+ })
+
+ it('labels a relative time range in plain English', () => {
+ const result = notebookToMarkdown({ name: 'Notebook', cells: [relativeLogCell] })
+ expect(result).toContain('_Time range: Last 24 hours_')
+ })
+
+ it('formats an absolute time range as a start → end pair in local time', () => {
+ const result = notebookToMarkdown({ name: 'Notebook', cells: [absoluteLogCell] })
+ const expectedBound = (value: string) => dayjs(value).format('MMM D, YYYY h:mm A')
+ expect(result).toContain(
+ `_Time range: ${expectedBound(absoluteRangeStart)} → ${expectedBound(absoluteRangeEnd)}_`
+ )
+ })
+
+ it('omits the results section when the cell has not been run this session', () => {
+ const result = notebookToMarkdown({
+ name: 'Notebook',
+ cells: [databaseCell],
+ getResult: () => undefined,
+ })
+ expect(result).not.toContain('**Results:**')
+ expect(result).not.toContain('**Error:**')
+ })
+
+ it('renders the last result as a markdown table when present', () => {
+ const result = notebookToMarkdown({
+ name: 'Notebook',
+ cells: [databaseCell],
+ getResult: (cellId) =>
+ cellId === 'cell-2'
+ ? { sql: databaseCell.unchecked_sql, rows: [{ id: 1, email: '[email protected]' }] }
+ : undefined,
+ })
+
+ expect(result).toContain(
+ '**Results:**\n\n| id | email |\n| -- | ------------- |\n| 1 | [email protected] |'
+ )
+ })
+
+ it('omits the results section when the cell ran but returned no rows', () => {
+ const result = notebookToMarkdown({
+ name: 'Notebook',
+ cells: [databaseCell],
+ getResult: () => ({ sql: databaseCell.unchecked_sql, rows: [] }),
+ })
+ expect(result).not.toContain('**Results:**')
+ })
+
+ it('shows the error instead of a results table when the last run failed', () => {
+ const result = notebookToMarkdown({
+ name: 'Notebook',
+ cells: [databaseCell],
+ getResult: () => ({
+ sql: databaseCell.unchecked_sql,
+ error: { message: 'relation "foo" does not exist' },
+ }),
+ })
+
+ expect(result).toContain('**Error:** relation "foo" does not exist')
+ expect(result).not.toContain('**Results:**')
+ })
+
+ it('omits a stale result whose recorded SQL no longer matches the cell', () => {
+ const result = notebookToMarkdown({
+ name: 'Notebook',
+ cells: [databaseCell],
+ getResult: () => ({ sql: 'select * from auth.identities', rows: [{ id: 1 }] }),
+ })
+
+ expect(result).not.toContain('**Results:**')
+ })
+
+ it('widens the code fence when the SQL contains a comment or string with embedded backticks', () => {
+ const sql = "select 1 -- a ```sql``` code block\nunion all select '`literal`'"
+ const cellWithBackticks: Cell = {
+ ...databaseCell,
+ unchecked_sql: untrustedSql(sql),
+ }
+
+ const result = notebookToMarkdown({ name: 'Notebook', cells: [cellWithBackticks] })
+
+ expect(result).toContain(`\`\`\`\`sql\n${sql}\n\`\`\`\``)
+ })
+})
diff --git a/apps/studio/components/interfaces/Explorer/ExplorerNotebookTab.utils.ts b/apps/studio/components/interfaces/Explorer/ExplorerNotebookTab.utils.ts
index 462cf4a0559..effff88fcd2 100644
--- a/apps/studio/components/interfaces/Explorer/ExplorerNotebookTab.utils.ts
+++ b/apps/studio/components/interfaces/Explorer/ExplorerNotebookTab.utils.ts
@@ -1,5 +1,8 @@
import { type Snapshot } from 'valtio'
+import { type QueryResult } from './types'
+import { convertResultsToMarkdown } from '@/components/interfaces/SQLEditor/UtilityPanel/Results.utils'
+import { formatTimeRange } from '@/components/ui/AIAssistantPanel/AssistantNotebookPreview.utils'
import { type Cell } from '@/data/content/notebooks/notebook-schema'
import { removeCommentsFromSql } from '@/lib/helpers'
@@ -60,3 +63,73 @@ export function isMutatingSql(sql: string): boolean {
const cleanedSql = removeCommentsFromSql(sql)
return cleanedSql.split(';').some((statement) => MUTATING_STATEMENT_REGEX.test(statement))
}
+
+/**
+ * A query cell's last in-session result rendered as a markdown table, or its error if the
+ * last run failed — whichever is more useful to paste. Undefined when the cell hasn't been
+ * run this session (results aren't persisted with the notebook, see QueryCell's local result
+ * state), or when `currentSql` has since diverged from the SQL that produced the result —
+ * e.g. the cell was edited but not rerun — since pairing stale results with the current SQL
+ * would misrepresent what that query actually returns.
+ */
+function formatQueryResult(
+ result: QueryResult | undefined,
+ currentSql: string
+): string | undefined {
+ if (!result || result.sql !== currentSql) return undefined
+ if (result.error) return `**Error:** ${result.error.message}`
+
+ const table = result.rows ? convertResultsToMarkdown([...result.rows]) : undefined
+ return table ? `**Results:**\n\n${table}` : undefined
+}
+
+/**
+ * A backtick fence long enough to enclose `content` without being closed early by a run of
+ * backticks inside it (e.g. a SQL comment or string literal quoting markdown).
+ */
+function getCodeFence(content: string): string {
+ const longestBacktickRun = Math.max(0, ...(content.match(/`+/g)?.map((run) => run.length) ?? []))
+ return '`'.repeat(Math.max(3, longestBacktickRun + 1))
+}
+
+/**
+ * Renders a notebook as a markdown document meant to be pasted into an external agent:
+ * markdown cells verbatim, query cells as a labelled SQL block. A log cell's `time_range`
+ * is called out separately since it's applied as a request parameter rather than baked
+ * into the SQL text.
+ */
+export function notebookToMarkdown({
+ name,
+ cells,
+ getResult,
+}: {
+ name: string
+ cells: readonly Snapshot<Cell>[]
+ getResult?: (cellId: string) => QueryResult | undefined
+}): string {
+ const sections = cells.map((cell) => {
+ switch (cell._tag) {
+ case 'markdown_cell':
+ return cell.text
+ case 'database_cell':
+ case 'log_cell': {
+ const header =
+ cell._tag === 'database_cell'
+ ? `### ${cell.title ?? 'Untitled query'} (Postgres)`
+ : `### ${cell.title ?? 'Untitled query'} (Logs — ClickHouse)\n\n_Time range: ${formatTimeRange(cell.time_range)}_`
+
+ const fence = getCodeFence(cell.unchecked_sql)
+
+ return [
+ header,
+ `${fence}sql\n${cell.unchecked_sql}\n${fence}`,
+ formatQueryResult(getResult?.(cell._id), cell.unchecked_sql),
+ ]
+ .filter((part): part is string => part !== undefined)
+ .join('\n\n')
+ }
+ }
+ })
+
+ return [`# ${name}`, ...sections].join('\n\n')
+}
diff --git a/apps/studio/components/interfaces/Explorer/QueryCell/QueryCell.utils.test.ts b/apps/studio/components/interfaces/Explorer/QueryCell/QueryCell.utils.test.ts
index 2480bdc709a..43aec754b38 100644
--- a/apps/studio/components/interfaces/Explorer/QueryCell/QueryCell.utils.test.ts
+++ b/apps/studio/components/interfaces/Explorer/QueryCell/QueryCell.utils.test.ts
@@ -8,6 +8,7 @@ import {
getCellDisplay,
setCellRowLimit,
setCellSql,
+ shouldInvalidateResultOnSourceChange,
toQueryModel,
} from './QueryCell.utils'
import { type ChartConfig, type QueryCell } from '@/data/content/notebooks/notebook-schema'
@@ -110,6 +111,53 @@ describe('changeCellSource', () => {
})
})
+describe('shouldInvalidateResultOnSourceChange', () => {
+ it('invalidates when the backend changes from database to logs', () => {
+ expect(
+ shouldInvalidateResultOnSourceChange(DATABASE_CELL, {
+ _tag: 'logs',
+ time_range: LOG_CELL.time_range,
+ })
+ ).toBe(true)
+ })
+
+ it('invalidates when the backend changes from logs to database', () => {
+ expect(
+ shouldInvalidateResultOnSourceChange(LOG_CELL, {
+ _tag: 'database',
+ database_identifier: undefined,
+ })
+ ).toBe(true)
+ })
+
+ it('invalidates a log cell result when the time range changes', () => {
+ expect(
+ shouldInvalidateResultOnSourceChange(LOG_CELL, {
+ _tag: 'logs',
+ time_range: { _tag: 'relative_time_range', unit: 'day', amount: 7 },
+ })
+ ).toBe(true)
+ })
+
+ it('keeps a log cell result when the time range is unchanged', () => {
+ expect(
+ shouldInvalidateResultOnSourceChange(LOG_CELL, {
+ _tag: 'logs',
+ time_range: { ...LOG_CELL.time_range },
+ })
+ ).toBe(false)
+ })
+
+ it('keeps a database cell result when only the connected database changes', () => {
+ expect(
+ shouldInvalidateResultOnSourceChange(DATABASE_CELL, {
+ _tag: 'database',
+ database_identifier: 'replica-2',
+ })
+ ).toBe(false)
+ })
+})
+
describe('setCellSql', () => {
it('writes the text back onto a database cell without touching its source', () => {
expect(setCellSql(DATABASE_CELL, 'select 1')).toEqual({
diff --git a/apps/studio/components/interfaces/Explorer/QueryCell/QueryCell.utils.ts b/apps/studio/components/interfaces/Explorer/QueryCell/QueryCell.utils.ts
index 5eabf93bd83..8fb58d3113d 100644
--- a/apps/studio/components/interfaces/Explorer/QueryCell/QueryCell.utils.ts
+++ b/apps/studio/components/interfaces/Explorer/QueryCell/QueryCell.utils.ts
@@ -1,4 +1,5 @@
import { untrustedSql } from '@supabase/pg-meta'
+import isEqual from 'lodash/isEqual'
import { type Snapshot } from 'valtio'
import { type ExplorerQueryModel } from '../QueryEditor'
@@ -91,6 +92,26 @@ export function changeCellSource(cell: Snapshot<QueryCell>, source: QuerySourceB
}
}
+/**
+ * Whether a source change makes a cell's last in-session result stale enough to clear.
+ * A backend change (database ↔ logs) invalidates outright, since another engine returns
+ * unrelated columns. A log cell's time range is a request parameter rather than part of the
+ * SQL text (see notebookToMarkdown), so a plain SQL-text comparison wouldn't catch a result
+ * that's stale only because the range moved — that has to be checked here instead.
+ */
+export function shouldInvalidateResultOnSourceChange(
+ cell: Snapshot<QueryCell>,
+ source: QuerySourceBinding
+): boolean {
+ const isBackendChange = (source._tag === 'logs') !== (cell._tag === 'log_cell')
+ const isTimeRangeChange =
+ source._tag === 'logs' &&
+ cell._tag === 'log_cell' &&
+ !isEqual(source.time_range, cell.time_range)
+
+ return isBackendChange || isTimeRangeChange
+}
+
/**
* Writes the editor's text back onto a cell, branded for that cell's dialect. Separate
* from `cloneQueryCell` so the brand stays correlated with the cell tag in one narrowing
diff --git a/apps/studio/components/interfaces/Explorer/QueryCell/index.tsx b/apps/studio/components/interfaces/Explorer/QueryCell/index.tsx
index 6a04b126bfb..10af63b4537 100644
--- a/apps/studio/components/interfaces/Explorer/QueryCell/index.tsx
+++ b/apps/studio/components/interfaces/Explorer/QueryCell/index.tsx
@@ -15,6 +15,7 @@ import {
getCellDisplay,
setCellRowLimit,
setCellSql,
+ shouldInvalidateResultOnSourceChange,
toQueryModel,
} from './QueryCell.utils'
import { SortableSection } from '@/components/ui/SortableSection'
@@ -77,11 +78,8 @@ export const QueryCell = forwardRef<QueryEditorHandle, QueryCellProps>(function
const handleSourceChange = (source: QuerySourceBinding) => {
// The query text carries over (see `changeCellSource`), so the editor's buffer stays
- // valid — but a result the old backend produced does not, since another engine
- // returns unrelated columns.
- const isBackendChange = (source._tag === 'logs') !== (cell._tag === 'log_cell')
- if (isBackendChange) setResult(undefined)
-
+ // valid — but a result run against the old source (backend or time range) does not.
+ if (shouldInvalidateResultOnSourceChange(cell, source)) setResult(undefined)
updateQueryCell((candidate) => changeCellSource(candidate, source))
}
diff --git a/apps/studio/components/interfaces/Explorer/QueryEditor/QueryResultRenderer.tsx b/apps/studio/components/interfaces/Explorer/QueryEditor/QueryResultRenderer.tsx
index fb29b99e92d..711584f9e8a 100644
--- a/apps/studio/components/interfaces/Explorer/QueryEditor/QueryResultRenderer.tsx
+++ b/apps/studio/components/interfaces/Explorer/QueryEditor/QueryResultRenderer.tsx
@@ -49,7 +49,7 @@ export const QueryResultRenderer = ({
}
if ((rows ?? []).length === 0) {
- return <p className="text-xs text-foreground-lighter py-8">Success. No rows returned</p>
+ return <p className="text-xs text-foreground-lighter p-3">Success. No rows returned</p>
}
if (rows && rows.length > 0) {
diff --git a/apps/studio/components/interfaces/Explorer/QueryEditor/index.tsx b/apps/studio/components/interfaces/Explorer/QueryEditor/index.tsx
index 4aa80d762e2..90fe7685c2b 100644
--- a/apps/studio/components/interfaces/Explorer/QueryEditor/index.tsx
+++ b/apps/studio/components/interfaces/Explorer/QueryEditor/index.tsx
@@ -116,6 +116,8 @@ export type QueryEditorHandle = {
getSql: () => string
/** Formats the editor's SQL in place and commits the result, same as the SQL Editor's Prettify SQL action. */
prettify: () => Promise<void>
+ /** The last result this cell produced in this session, or undefined if it hasn't been run. */
+ getResult: () => QueryResult | undefined
}
type QueryEditorProps = {
@@ -379,6 +381,7 @@ export const QueryEditor = forwardRef<QueryEditorHandle, QueryEditorProps>(funct
run: (force = false) => handleRunQuery({ shouldForce: force }),
getSql: () => sqlRef.current,
prettify: handlePrettify,
+ getResult: () => result,
}))
useEffect(() => {
diff --git a/apps/studio/components/interfaces/SQLEditor/UtilityPanel/Results.utils.test.ts b/apps/studio/components/interfaces/SQLEditor/UtilityPanel/Results.utils.test.ts
index f1fb5d068fa..d3e264256d5 100644
--- a/apps/studio/components/interfaces/SQLEditor/UtilityPanel/Results.utils.test.ts
+++ b/apps/studio/components/interfaces/SQLEditor/UtilityPanel/Results.utils.test.ts
@@ -60,6 +60,36 @@ describe('Results.utils', () => {
const md = convertResultsToMarkdown(results)
expect(md).toContain('{"role":"admin"}')
})
+
+ it('should escape pipe characters so a value cannot split into extra columns', () => {
+ const results = [{ id: 1, name: 'a|b' }]
+ const md = convertResultsToMarkdown(results)
+ const rows = md!.split('\n')
+ // header + separator + one data row, not more
+ expect(rows).toHaveLength(3)
+ expect(rows[2]).toContain('a\\|b')
+ })
+
+ it('should escape backslashes so an escaped pipe cannot be forged', () => {
+ const results = [{ id: 1, name: 'a\\|b' }]
+ const md = convertResultsToMarkdown(results)
+ expect(md).toContain('a\\\\\\|b')
+ })
+
+ it('should replace newlines with <br> so a multiline value cannot create extra table rows', () => {
+ const results = [
+ { id: 1, query: 'select 1;\nselect 2;' },
+ { id: 2, query: 'select 3;\r\nselect 4;' },
+ { id: 3, query: 'select 5;\rselect 6;' },
+ ]
+ const md = convertResultsToMarkdown(results)
+ const rows = md!.split('\n')
+ // header + separator + 3 data rows, not more
+ expect(rows).toHaveLength(5)
+ expect(rows[2]).toContain('select 1;<br>select 2;')
+ expect(rows[3]).toContain('select 3;<br>select 4;')
+ expect(rows[4]).toContain('select 5;<br>select 6;')
+ })
})
describe('convertResultsToJSON', () => {
diff --git a/apps/studio/components/interfaces/SQLEditor/UtilityPanel/Results.utils.ts b/apps/studio/components/interfaces/SQLEditor/UtilityPanel/Results.utils.ts
index 3791f6c9c61..83bf9212e0e 100644
--- a/apps/studio/components/interfaces/SQLEditor/UtilityPanel/Results.utils.ts
+++ b/apps/studio/components/interfaces/SQLEditor/UtilityPanel/Results.utils.ts
@@ -22,8 +22,13 @@ export function convertResultsToMarkdown(results: ResultRow[]): string | undefin
if (formatted.length === 0) return undefined
const columns = Object.keys(formatted[0])
- const rows = formatted.map((row) => columns.map((col) => String(row[col] ?? '')))
- const table = [columns, ...rows]
+ const escapeCell = (value: string) =>
+ value
+ .replace(/\\/g, '\\\\')
+ .replace(/\|/g, '\\|')
+ .replace(/\r\n|\r|\n/g, '<br>')
+ const rows = formatted.map((row) => columns.map((col) => escapeCell(String(row[col] ?? ''))))
+ const table = [columns.map(escapeCell), ...rows]
return markdownTable(table)
}