The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
fix(studio): confirm destructive notebook queries (#49658)
Charis17d15ee1e2ff
diff --git a/apps/studio/components/interfaces/Explorer/ExplorerNotebookTab.tsx b/apps/studio/components/interfaces/Explorer/ExplorerNotebookTab.tsxindex 06007bd406a..2d97f1576cd 100644--- a/apps/studio/components/interfaces/Explorer/ExplorerNotebookTab.tsx+++ b/apps/studio/components/interfaces/Explorer/ExplorerNotebookTab.tsx@@ -33,6 +33,7 @@ import { useEffect, useEffectEvent, useRef, useState } from 'react'import { toast } from 'sonner'import {AiIconAnimation,+ Badge,Button,Checkbox,DropdownMenu,@@ -45,7 +46,11 @@ import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'import { EmptyStatePresentational } from 'ui-patterns/EmptyStatePresentational'import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'-import { findMutatingQueryCells } from './ExplorerNotebookTab.utils'+import {+ findQueryCellsMatchingSql,+ isMutatingSql,+ type QueryCellSummary,+} from './ExplorerNotebookTab.utils'import {ExplorerToolbar,ExplorerToolbarAction,@@ -58,6 +63,7 @@ import { MarkdownCell } from './MarkdownCell'import { QueryCell } from './QueryCell'import { type QueryEditorHandle } from './QueryEditor'import { createMarkdownCellSkeleton, createQueryCellSkeleton } from './utils'+import { checkDestructiveQuery } from '@/components/interfaces/SQLEditor/SQLEditor.utils'import { ButtonTooltip } from '@/components/ui/ButtonTooltip'import { useContentDeleteMutation } from '@/data/content/content-delete-mutation'import {@@ -102,9 +108,10 @@ export const ExplorerNotebookTab = () => {const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false)const [isSaveBeforeAnalyzeOpen, setIsSaveBeforeAnalyzeOpen] = useState(false)const [isSaveConflictOpen, setIsSaveConflictOpen] = useState(false)- const [pendingMutationCells, setPendingMutationCells] = useState<- { id: string; title: string }[] | null- >(null)+ const [pendingQueryMatches, setPendingQueryMatches] = useState<{+ destructiveQueries: QueryCellSummary[]+ mutatingQueries: QueryCellSummary[]+ } | null>(null)const [skipMutatingCells, setSkipMutatingCells] = useState(false)const queryCellRefs = useRef(new Map<string, QueryEditorHandle>())const savedContentRef = useRef<typeof content>(undefined)@@ -184,25 +191,33 @@ export const ExplorerNotebookTab = () => {const handleRunNotebook = () => {const freshCells = getFreshCells()- const mutatingCells = findMutatingQueryCells({+ const { destructiveQueries, mutatingQueries } = findQueryCellsMatchingSql({cells: freshCells,getLiveSql: (cellId) => queryCellRefs.current.get(cellId)?.getSql(),+ matchers: {+ destructiveQueries: checkDestructiveQuery,+ mutatingQueries: isMutatingSql,+ },})- if (mutatingCells.length === 0) {+ if (mutatingQueries.length === 0) {runNotebook({ cellIdsToRun: freshCells.filter(isQueryCell).map((cell) => cell._id) })} else {setSkipMutatingCells(false)- setPendingMutationCells(mutatingCells)+ setPendingQueryMatches({ destructiveQueries, mutatingQueries })}}const handleConfirmRunNotebook = () => {- const mutatingCellIds = new Set((pendingMutationCells ?? []).map((cell) => cell.id))+ const mutatingCellIds = new Set(+ (pendingQueryMatches?.mutatingQueries ?? []).map((cell) => cell.id)+ )+ const freshCells = getFreshCells()+ const freshQueryCellIds = freshCells.filter(isQueryCell).map((cell) => cell._id)const cellIdsToRun = skipMutatingCells- ? queryCellIds.filter((id) => !mutatingCellIds.has(id))- : queryCellIds+ ? freshQueryCellIds.filter((id) => !mutatingCellIds.has(id))+ : freshQueryCellIds- setPendingMutationCells(null)+ setPendingQueryMatches(null)runNotebook({ cellIdsToRun, force: true })}@@ -546,22 +561,27 @@ export const ExplorerNotebookTab = () => {<ConfirmationModalsize="small"- visible={pendingMutationCells !== null}+ visible={pendingQueryMatches !== null}title="Confirm to run notebook"confirmLabel={skipMutatingCells ? 'Run read-only cells' : 'Run all cells'}variant="warning"- onCancel={() => setPendingMutationCells(null)}+ onCancel={() => setPendingQueryMatches(null)}onConfirm={handleConfirmRunNotebook}><p className="text-sm">- This notebook has {pendingMutationCells?.length ?? 0}{' '}- {pendingMutationCells?.length === 1 ? 'query' : 'queries'} that{' '}- {pendingMutationCells?.length === 1 ? 'modifies' : 'modify'} data or schema and cannot be- undone once run:+ This notebook has {pendingQueryMatches?.mutatingQueries.length ?? 0}{' '}+ {pendingQueryMatches?.mutatingQueries.length === 1 ? 'query' : 'queries'} that{' '}+ {pendingQueryMatches?.mutatingQueries.length === 1 ? 'modifies' : 'modify'} data or schema+ and cannot be undone once run:</p><ul className="text-sm list-disc pl-4 mt-2">- {pendingMutationCells?.map((cell) => (- <li key={cell.id}>{cell.title}</li>+ {pendingQueryMatches?.mutatingQueries.map((cell) => (+ <li key={cell.id} className="flex items-center gap-2">+ {cell.title}+ {pendingQueryMatches.destructiveQueries.some(({ id }) => id === cell.id) && (+ <Badge variant="destructive">Destructive</Badge>+ )}+ </li>))}</ul><FormItemLayoutdiff --git a/apps/studio/components/interfaces/Explorer/ExplorerNotebookTab.utils.test.ts b/apps/studio/components/interfaces/Explorer/ExplorerNotebookTab.utils.test.tsindex ee346c23e76..1bee6c16038 100644--- a/apps/studio/components/interfaces/Explorer/ExplorerNotebookTab.utils.test.ts+++ b/apps/studio/components/interfaces/Explorer/ExplorerNotebookTab.utils.test.ts@@ -1,7 +1,8 @@import { untrustedSql } from '@supabase/pg-meta'import { describe, expect, it } from 'vitest'-import { findMutatingQueryCells, isMutatingSql } from './ExplorerNotebookTab.utils'+import { findQueryCellsMatchingSql, isMutatingSql } 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'@@ -40,6 +41,16 @@ describe('isMutatingSql', () => {})describe('findMutatingQueryCells', () => {+ const matchMutatingQueries = (+ cells: readonly Cell[],+ getLiveSql?: (cellId: string) => string | undefined+ ) =>+ findQueryCellsMatchingSql({+ cells,+ getLiveSql,+ matchers: { mutatingQueries: isMutatingSql },+ }).mutatingQueries+const readOnlyDatabaseCell: Cell = {_tag: 'database_cell',_id: 'cell-1',@@ -74,24 +85,24 @@ describe('findMutatingQueryCells', () => {}it('returns an empty array when there are no mutating database cells', () => {- expect(findMutatingQueryCells({ cells: [readOnlyDatabaseCell, markdownCell] })).toEqual([])+ expect(matchMutatingQueries([readOnlyDatabaseCell, markdownCell])).toEqual([])})it('flags mutating database cells with their id and title', () => {- expect(findMutatingQueryCells({ cells: [readOnlyDatabaseCell, mutatingDatabaseCell] })).toEqual(- [{ id: 'cell-2', title: 'Cleanup' }]- )+ expect(matchMutatingQueries([readOnlyDatabaseCell, mutatingDatabaseCell])).toEqual([+ { id: 'cell-2', title: 'Cleanup' },+ ])})it('excludes log cells even when their SQL looks mutating', () => {- expect(findMutatingQueryCells({ cells: [mutatingDatabaseCell, mutatingLogCell] })).toEqual([+ expect(matchMutatingQueries([mutatingDatabaseCell, mutatingLogCell])).toEqual([{ id: 'cell-2', title: 'Cleanup' },])})it('falls back to "Untitled query" when a mutating cell has no title', () => {const untitledCell: Cell = { ...mutatingDatabaseCell, title: undefined }- expect(findMutatingQueryCells({ cells: [untitledCell] })).toEqual([+ expect(matchMutatingQueries([untitledCell])).toEqual([{ id: 'cell-2', title: 'Untitled query' },])})@@ -100,9 +111,7 @@ describe('findMutatingQueryCells', () => {const getLiveSql = (cellId: string) =>cellId === 'cell-1' ? 'delete from auth.users' : undefined- expect(- findMutatingQueryCells({ cells: [readOnlyDatabaseCell, mutatingDatabaseCell], getLiveSql })- ).toEqual([+ expect(matchMutatingQueries([readOnlyDatabaseCell, mutatingDatabaseCell], getLiveSql)).toEqual([{ id: 'cell-1', title: 'Signups' },{ id: 'cell-2', title: 'Cleanup' },])@@ -112,16 +121,74 @@ describe('findMutatingQueryCells', () => {const getLiveSql = (cellId: string) =>cellId === 'cell-2' ? 'select * from auth.users' : undefined- expect(- findMutatingQueryCells({ cells: [readOnlyDatabaseCell, mutatingDatabaseCell], getLiveSql })- ).toEqual([{ id: 'cell-2', title: 'Cleanup' }])+ expect(matchMutatingQueries([readOnlyDatabaseCell, mutatingDatabaseCell], getLiveSql)).toEqual([+ { id: 'cell-2', title: 'Cleanup' },+ ])})it('falls back to the stored SQL when the live getter has nothing for a cell', () => {const getLiveSql = () => undefined+ expect(matchMutatingQueries([readOnlyDatabaseCell, mutatingDatabaseCell], getLiveSql)).toEqual([+ { id: 'cell-2', title: 'Cleanup' },+ ])+ })+})++describe('findQueryCellsMatchingSql', () => {+ const readOnlyCell: Cell = {+ _tag: 'database_cell',+ _id: 'cell-1',+ title: 'Signups',+ view: 'table',+ unchecked_sql: untrustedSql('select * from auth.users'),+ row_limit: 50,+ }+ const destructiveCell: Cell = {+ _tag: 'database_cell',+ _id: 'cell-2',+ title: 'Drop users',+ view: 'table',+ unchecked_sql: untrustedSql('select 1; drop table users'),+ row_limit: 50,+ }++ it('returns only cells containing destructive SQL', () => {+ expect(+ findQueryCellsMatchingSql({+ cells: [readOnlyCell, destructiveCell],+ matchers: {+ destructiveQueries: checkDestructiveQuery,+ mutatingQueries: isMutatingSql,+ },+ })+ ).toEqual({+ destructiveQueries: [{ id: 'cell-2', title: 'Drop users' }],+ mutatingQueries: [{ id: 'cell-2', title: 'Drop users' }],+ })+ })++ it('ignores destructive SQL inside comments', () => {+ const commentedCell: Cell = {+ ...readOnlyCell,+ unchecked_sql: untrustedSql('-- drop table users\nselect 1'),+ }++ expect(+ findQueryCellsMatchingSql({+ cells: [commentedCell],+ matchers: { destructiveQueries: checkDestructiveQuery },+ }).destructiveQueries+ ).toEqual([])+ })++ it('uses live SQL when it adds a destructive operation', () => {expect(- findMutatingQueryCells({ cells: [readOnlyDatabaseCell, mutatingDatabaseCell], getLiveSql })- ).toEqual([{ id: 'cell-2', title: 'Cleanup' }])+ findQueryCellsMatchingSql({+ cells: [readOnlyCell],+ getLiveSql: () => 'truncate table users',+ matchers: { destructiveQueries: checkDestructiveQuery },+ }).destructiveQueries+ ).toEqual([{ id: 'cell-1', title: 'Signups' }])})})diff --git a/apps/studio/components/interfaces/Explorer/ExplorerNotebookTab.utils.ts b/apps/studio/components/interfaces/Explorer/ExplorerNotebookTab.utils.tsindex db101184810..462cf4a0559 100644--- a/apps/studio/components/interfaces/Explorer/ExplorerNotebookTab.utils.ts+++ b/apps/studio/components/interfaces/Explorer/ExplorerNotebookTab.utils.ts@@ -1,11 +1,56 @@import { type Snapshot } from 'valtio'-import { type Cell, type DatabaseCell } from '@/data/content/notebooks/notebook-schema'+import { type Cell } from '@/data/content/notebooks/notebook-schema'import { removeCommentsFromSql } from '@/lib/helpers'const MUTATING_STATEMENT_REGEX =/^\s*(insert|update|delete|create|alter|drop|truncate|grant|revoke|merge)\b/i+export type QueryCellSummary = { id: string; title: string }++type FindQueryCellsArgs = {+ cells: readonly Snapshot<Cell>[]+ /**+ * Lets a caller also check each cell's live editor buffer as well. The store+ * only updates on a Monaco blur commit, which fires asynchronously, so a scan+ * against the store alone can miss SQL typed just before the run click.+ */+ getLiveSql?: (cellId: string) => string | undefined+}++type SqlMatchers = Record<string, (sql: string) => boolean>++/**+ * Finds database cells that match one or more SQL predicates in a single pass.+ */+export function findQueryCellsMatchingSql<T extends SqlMatchers>({+ cells,+ getLiveSql,+ matchers,+}: FindQueryCellsArgs & {+ matchers: T+}): Record<keyof T, QueryCellSummary[]> {+ const matchingCells = {} as Record<keyof T, QueryCellSummary[]>+ for (const name in matchers) {+ matchingCells[name] = []+ }++ cells.forEach((cell) => {+ if (cell._tag !== 'database_cell') return++ const sql = [cell.unchecked_sql, getLiveSql?.(cell._id)].filter(+ (value): value is string => value !== undefined+ )+ const summary = { id: cell._id, title: cell.title ?? 'Untitled query' }++ for (const name in matchers) {+ if (sql.some(matchers[name])) matchingCells[name].push(summary)+ }+ })++ return matchingCells+}+/*** Whether `sql` contains any statement that writes to data or schema, as opposed to a* read-only query. Checked per `;`-delimited statement so a mutating statement anywhere@@ -15,27 +60,3 @@ export function isMutatingSql(sql: string): boolean {const cleanedSql = removeCommentsFromSql(sql)return cleanedSql.split(';').some((statement) => MUTATING_STATEMENT_REGEX.test(statement))}--/**- * The database cells whose SQL mutates data or schema, for flagging before a notebook-wide run.- */-export function findMutatingQueryCells({- cells,- getLiveSql,-}: {- cells: readonly Snapshot<Cell>[]- /**- * Lets a caller also check each cell's live editor buffer as well. The store- * only updates on a Monaco blur commit, which fires asynchronously, so a scan- * against the store alone can miss SQL typed just before the run click.- * */- getLiveSql?: (cellId: string) => string | undefined-}): { id: string; title: string }[] {- return cells- .filter((cell): cell is Snapshot<DatabaseCell> => cell._tag === 'database_cell')- .filter((cell) => {- const liveSql = getLiveSql?.(cell._id)- return isMutatingSql(cell.unchecked_sql) || (liveSql !== undefined && isMutatingSql(liveSql))- })- .map((cell) => ({ id: cell._id, title: cell.title ?? 'Untitled query' }))-}diff --git a/apps/studio/components/interfaces/Explorer/__tests__/ExplorerNotebookTab.test.tsx b/apps/studio/components/interfaces/Explorer/__tests__/ExplorerNotebookTab.test.tsxindex 3e7d3522ceb..bbbec8e9226 100644--- a/apps/studio/components/interfaces/Explorer/__tests__/ExplorerNotebookTab.test.tsx+++ b/apps/studio/components/interfaces/Explorer/__tests__/ExplorerNotebookTab.test.tsx@@ -228,21 +228,62 @@ describe('ExplorerNotebookTab', () => {expect(queries).toHaveLength(0)})- it('runs every cell, including the mutating one, when confirmed with "Run all cells"', async () => {+ it('labels destructive queries and runs all cells after one confirmation', async () => {const queries = mockDatabaseQueryRequests()renderNotebookTab()await userEvent.click(await screen.findByRole('button', { name: 'Run notebook' }))- await screen.findByRole('dialog', { name: 'Confirm to run notebook' })+ const dialog = await screen.findByRole('dialog', { name: 'Confirm to run notebook' })+ expect(within(dialog).getByText('Mutating query')).toBeInTheDocument()+ expect(within(dialog).getByText('Destructive')).toBeInTheDocument()+ expect(queries).toHaveLength(0)- await userEvent.click(screen.getByRole('button', { name: 'Run all cells' }))+ await userEvent.click(within(dialog).getByRole('button', { name: 'Run all cells' }))await waitFor(() => expect(queries).toHaveLength(2))expect(queries.some((query) => query.includes('select 1'))).toBe(true)expect(queries.some((query) => query.includes('delete from foo'))).toBe(true)})+ it('runs no cells when the combined confirmation is cancelled', async () => {+ const queries = mockDatabaseQueryRequests()++ renderNotebookTab()++ await userEvent.click(await screen.findByRole('button', { name: 'Run notebook' }))+ const dialog = await screen.findByRole('dialog', { name: 'Confirm to run notebook' })+ await userEvent.click(within(dialog).getByRole('button', { name: 'Cancel' }))++ await waitFor(() =>+ expect(+ screen.queryByRole('dialog', { name: 'Confirm to run notebook' })+ ).not.toBeInTheDocument()+ )+ expect(queries).toHaveLength(0)+ })++ it('does not label non-destructive mutations', async () => {+ seedNotebook([+ readOnlyCell,+ createQueryCellSkeleton({+ title: 'Add signup',+ sql: "insert into signups values ('test')",+ }),+ ])+ const queries = mockDatabaseQueryRequests()++ renderNotebookTab()++ await userEvent.click(await screen.findByRole('button', { name: 'Run notebook' }))+ const dialog = await screen.findByRole('dialog', { name: 'Confirm to run notebook' })+ expect(within(dialog).queryByText('Destructive')).not.toBeInTheDocument()++ await userEvent.click(within(dialog).getByRole('button', { name: 'Run all cells' }))++ await waitFor(() => expect(queries).toHaveLength(2))+ })+it('picks up a SQL commit that lands after this render but before the click handler runs', async () => {seedNotebook([readOnlyCell])const queries = mockDatabaseQueryRequests()@@ -291,6 +332,8 @@ describe('ExplorerNotebookTab', () => {const dialog = await screen.findByRole('dialog', { name: 'Confirm to run notebook' })expect(within(dialog).getByText('Read-only query')).toBeInTheDocument()expect(queries).toHaveLength(0)++ expect(within(dialog).getByText('Destructive')).toBeInTheDocument()})it('runs only the read-only cells when "Skip these queries" is checked', async () => {