Skip to content

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

Chore/update without where warning (#28458)

Terry Sutton7d5c62c518fe
diff --git a/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx b/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx
index eb2169b87e6..5ed72998a2e 100644
--- a/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx
+++ b/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx
@@ -1,13 +1,14 @@
import type { Monaco } from '@monaco-editor/react'
import { useQueryClient } from '@tanstack/react-query'
import { motion } from 'framer-motion'
-import { ChevronUp, Loader2 } from 'lucide-react'
+import { AlertTriangle, ChevronUp, Loader2 } from 'lucide-react'
import dynamic from 'next/dynamic'
import { useRouter } from 'next/router'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { toast } from 'sonner'
import { format } from 'sql-formatter'
+import { Separator } from '@ui/components/SidePanel/SidePanel'
import { useParams, useTelemetryProps } from 'common'
import { GridFooter } from 'components/ui/GridFooter'
import { useSqlDebugMutation } from 'data/ai/sql-debug-mutation'
@@ -53,7 +54,7 @@ import {
Tooltip_Shadcn_,
cn,
} from 'ui'
-import ConfirmModal from 'ui-patterns/Dialogs/ConfirmDialog'
+import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'
import { subscriptionHasHipaaAddon } from '../Billing/Subscription/Subscription.utils'
import AISchemaSuggestionPopover from './AISchemaSuggestionPopover'
import { AiAssistantPanel } from './AiAssistantPanel'
@@ -76,6 +77,7 @@ import {
compareAsModification,
compareAsNewSnippet,
createSqlSnippetSkeleton,
+ isUpdateWithoutWhere,
suffixWithLimit,
} from './SQLEditor.utils'
import UtilityPanel from './UtilityPanel/UtilityPanel'
@@ -132,7 +134,10 @@ const SQLEditor = () => {
const hasHipaaAddon = subscriptionHasHipaaAddon(subscription)
const [isAiOpen, setIsAiOpen] = useLocalStorageQuery(LOCAL_STORAGE_KEYS.SQL_EDITOR_AI_OPEN, true)
- const [isConfirmModalOpen, setIsConfirmModalOpen] = useState(false)
+
+ const [showPotentialIssuesModal, setShowPotentialIssuesModal] = useState(false)
+ const [queryHasDestructiveOperations, setQueryHasDestructiveOperations] = useState(false)
+ const [queryHasUpdateWithoutWhere, setQueryHasUpdateWithoutWhere] = useState(false)
const isOptedInToAI = useOrgOptedIntoAi()
const [selectedSchemas] = useSchemasForAi(project?.ref!)
@@ -288,10 +293,23 @@ const SQLEditor = () => {
? (selectedValue || editorRef.current?.getValue()) ?? snippet.snippet.content.sql
: selectedValue || editorRef.current?.getValue()
- const containsDestructiveOperations = checkDestructiveQuery(sql)
+ let queryHasIssues = false
+
+ const destructiveOperations = checkDestructiveQuery(sql)
+ if (!force && destructiveOperations) {
+ setShowPotentialIssuesModal(true)
+ setQueryHasDestructiveOperations(true)
+ queryHasIssues = true
+ }
+
+ const updateWithoutWhereClause = isUpdateWithoutWhere(sql)
+ if (!force && updateWithoutWhereClause) {
+ setShowPotentialIssuesModal(true)
+ setQueryHasUpdateWithoutWhere(true)
+ queryHasIssues = true
+ }
- if (!force && containsDestructiveOperations) {
- setIsConfirmModalOpen(true)
+ if (queryHasIssues) {
return
}
@@ -616,22 +634,59 @@ const SQLEditor = () => {
return (
<>
- <ConfirmModal
- visible={isConfirmModalOpen}
- title="Destructive operation"
- danger
- description="We've detected a potentially destructive operation in the query. Please confirm that you would like to execute this query."
- buttonLabel="Run destructive query"
- onSelectCancel={() => {
- setIsConfirmModalOpen(false)
- // [Joshen] Somehow calling this immediately doesn't work, hence the timeout
+ <ConfirmationModal
+ visible={showPotentialIssuesModal}
+ size="large"
+ title={`Potential issue${queryHasDestructiveOperations && queryHasUpdateWithoutWhere ? 's' : ''} detected with your query`}
+ confirmLabel="Run this query"
+ variant="warning"
+ alert={{
+ base: {
+ variant: 'warning',
+ },
+ title:
+ queryHasDestructiveOperations && queryHasUpdateWithoutWhere
+ ? 'The following potential issues have been detected:'
+ : 'The following potential issue has been detected:',
+ description: 'Ensure that these are intentional before executing this query',
+ }}
+ onCancel={() => {
+ setShowPotentialIssuesModal(false)
+ setQueryHasDestructiveOperations(false)
+ setQueryHasUpdateWithoutWhere(false)
setTimeout(() => editorRef.current?.focus(), 100)
}}
- onSelectConfirm={() => {
- setIsConfirmModalOpen(false)
+ onConfirm={() => {
+ setShowPotentialIssuesModal(false)
executeQuery(true)
}}
- />
+ >
+ <div className="text-sm">
+ <ul className="border rounded-md grid bg-surface-200">
+ {queryHasDestructiveOperations && (
+ <li className="grid pt-3 pb-2 px-4">
+ <span className="font-bold">Query has destructive operation</span>
+ <span className="text-foreground-lighter">
+ Make sure you are not accidentally removing something important.
+ </span>
+ </li>
+ )}
+ {queryHasDestructiveOperations && queryHasUpdateWithoutWhere && <Separator />}
+ {queryHasUpdateWithoutWhere && (
+ <li className="grid pt-2 pb-3 px-4 gap-1">
+ <span className="font-bold">Query uses update without a where clause</span>
+ <span className="text-foreground-lighter">
+ Without a <code className="text-xs">where</code> clause, this could update all
+ rows in the table.
+ </span>
+ </li>
+ )}
+ </ul>
+ </div>
+ <p className="mt-4 text-sm text-foreground-light">
+ Please confirm that you would like to execute this query.
+ </p>
+ </ConfirmationModal>
<ResizablePanelGroup
className="flex h-full"
diff --git a/apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.test.ts b/apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.test.ts
index 0f966c253de..16a7f7e90a3 100644
--- a/apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.test.ts
+++ b/apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.test.ts
@@ -1,4 +1,10 @@
-import { checkIfAppendLimitRequired, suffixWithLimit } from './SQLEditor.utils'
+import { stripIndent } from 'common-tags'
+import {
+ checkDestructiveQuery,
+ checkIfAppendLimitRequired,
+ isUpdateWithoutWhere,
+ suffixWithLimit,
+} from './SQLEditor.utils'
describe('SQLEditor.utils.ts:checkIfAppendLimitRequired', () => {
test('Should return false if limit passed is <= 0', () => {
@@ -127,3 +133,116 @@ describe('SQLEditor.utils.ts:suffixWithLimit', () => {
expect(formattedSql).toBe('select * from countries limit 100;')
})
})
+
+describe(`SQLEditor.utils.ts:checkDestructiveQuery`, () => {
+ it('drop statement matches', () => {
+ const match = checkDestructiveQuery('drop table films, distributors;')
+
+ expect(match).toBe(true)
+ })
+
+ it('truncate statement matches', () => {
+ const match = checkDestructiveQuery('truncate films;')
+
+ expect(match).toBe(true)
+ })
+
+ it('delete statement matches', () => {
+ const match = checkDestructiveQuery("delete from films where kind <> 'Musical';")
+
+ expect(match).toBe(true)
+ })
+
+ it('delete statement after another statement matches', () => {
+ const match = checkDestructiveQuery(stripIndent`
+ select * from films;
+
+ delete from films where kind <> 'Musical';
+ `)
+
+ expect(match).toBe(true)
+ })
+
+ it("rls policy containing delete doesn't match", () => {
+ const match = checkDestructiveQuery(stripIndent`
+ create policy "Users can delete their own files"
+ on storage.objects for delete to authenticated using (
+ bucket id = 'files' and (select auth.uid()) = owner
+ );
+ `)
+
+ expect(match).toBe(false)
+ })
+
+ it('capitalized statement matches', () => {
+ const match = checkDestructiveQuery("DELETE FROM films WHERE kind <> 'Musical';")
+
+ expect(match).toBe(true)
+ })
+
+ it("comment containing keyword doesn't match", () => {
+ const match = checkDestructiveQuery(stripIndent`
+ -- Going to drop this in here, might delete later
+ select * from films;
+ `)
+
+ expect(match).toBe(false)
+ })
+})
+
+describe('SQLEditor.utils:updateWithoutWhere', () => {
+ it('contains an update query with a where clause', () => {
+ const match = isUpdateWithoutWhere(stripIndent`
+ UPDATE public.countries SET name = 'New Name' WHERE id = 1;
+ `)
+
+ expect(match).toBe(false)
+ })
+
+ it('contains an update query without a where clause', () => {
+ const match = isUpdateWithoutWhere(stripIndent`
+ UPDATE public.countries SET name = 'New Name';
+ `)
+
+ expect(match).toBe(true)
+ })
+
+ it('contains an update query, with quoted identifiers with a where clause', () => {
+ const match = isUpdateWithoutWhere(stripIndent`
+ UPDATE "public"."countries" SET name = 'New Name' WHERE id = 1;
+ `)
+
+ expect(match).toBe(false)
+ })
+
+ it('contains an update query, with quoted identifiers without a where clause', () => {
+ const match = isUpdateWithoutWhere(stripIndent`
+ UPDATE "public"."countries" SET name = 'New Name';
+ `)
+
+ expect(match).toBe(true)
+ })
+
+ it('contains both an update query and a delete query, triggers destructive', () => {
+ const match = checkDestructiveQuery(stripIndent`
+ delete from countries; update countries set name = 'hello';
+ `)
+
+ expect(match).toBe(true)
+ })
+
+ it('contains both an update query and a delete query, triggers no where', () => {
+ const match = isUpdateWithoutWhere(stripIndent`
+ delete from countries; update countries set name = 'hello';
+ `)
+
+ expect(match).toBe(true)
+ })
+ it('contains both an update query and a delete query, triggers no where', () => {
+ const match = isUpdateWithoutWhere(stripIndent`
+ delete from countries; update countries set name = 'hello';
+ `)
+
+ expect(match).toBe(true)
+ })
+})
diff --git a/apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.ts b/apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.ts
index 4cce7028521..623e4a51aff 100644
--- a/apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.ts
+++ b/apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.ts
@@ -95,7 +95,20 @@ export function getDiffTypeDropdownLabel(diffType: DiffType) {
}
export function checkDestructiveQuery(sql: string) {
- return destructiveSqlRegex.some((regex) => regex.test(removeCommentsFromSql(sql)))
+ const cleanedSql = removeCommentsFromSql(sql)
+ return destructiveSqlRegex.some((regex) => regex.test(cleanedSql))
+}
+
+// Function to check for UPDATE queries without WHERE clause
+export function isUpdateWithoutWhere(sql: string): boolean {
+ const updateWithoutWhereRegex =
+ /(?:^|;)\s*update\s+(?:"[\w.]+"\."[\w.]+"|[\w.]+)\s+set\s+[\w\W]+?(?!\s*where\s)/is
+ const updateStatements = sql
+ .split(';')
+ .filter((statement) => statement.trim().toLowerCase().startsWith('update'))
+ return updateStatements.some(
+ (statement) => updateWithoutWhereRegex.test(statement) && !/where\s/i.test(statement)
+ )
}
export const generateMigrationCliCommand = (id: string, name: string, isNpx = false) =>
diff --git a/apps/studio/tests/unit/destructive-query-check.test.ts b/apps/studio/tests/unit/destructive-query-check.test.ts
deleted file mode 100644
index d25426900a7..00000000000
--- a/apps/studio/tests/unit/destructive-query-check.test.ts
+++ /dev/null
@@ -1,58 +0,0 @@
-import { stripIndent } from 'common-tags'
-import { checkDestructiveQuery } from 'components/interfaces/SQLEditor/SQLEditor.utils'
-
-describe(`destructive query check`, () => {
- it('drop statement matches', () => {
- const match = checkDestructiveQuery('drop table films, distributors;')
-
- expect(match).toBe(true)
- })
-
- it('truncate statement matches', () => {
- const match = checkDestructiveQuery('truncate films;')
-
- expect(match).toBe(true)
- })
-
- it('delete statement matches', () => {
- const match = checkDestructiveQuery("delete from films where kind <> 'Musical';")
-
- expect(match).toBe(true)
- })
-
- it('delete statement after another statement matches', () => {
- const match = checkDestructiveQuery(stripIndent`
- select * from films;
-
- delete from films where kind <> 'Musical';
- `)
-
- expect(match).toBe(true)
- })
-
- it("rls policy containing delete doesn't match", () => {
- const match = checkDestructiveQuery(stripIndent`
- create policy "Users can delete their own files"
- on storage.objects for delete to authenticated using (
- bucket id = 'files' and (select auth.uid()) = owner
- );
- `)
-
- expect(match).toBe(false)
- })
-
- it('capitalized statement matches', () => {
- const match = checkDestructiveQuery("DELETE FROM films WHERE kind <> 'Musical';")
-
- expect(match).toBe(true)
- })
-
- it("comment containing keyword doesn't match", () => {
- const match = checkDestructiveQuery(stripIndent`
- -- Going to drop this in here, might delete later
- select * from films;
- `)
-
- expect(match).toBe(false)
- })
-})
diff --git a/packages/ui-patterns/Dialogs/ConfirmDialog.tsx b/packages/ui-patterns/Dialogs/ConfirmDialog.tsx
index 80aba0f849b..3f6aace4a28 100644
--- a/packages/ui-patterns/Dialogs/ConfirmDialog.tsx
+++ b/packages/ui-patterns/Dialogs/ConfirmDialog.tsx
@@ -17,6 +17,7 @@ interface ConfirmModalProps {
onSelectConfirm: () => void
}
+// @deprecated use ConfirmationModal instead
const ConfirmModal = ({
visible = false,
danger = false,