Skip to content

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

refactor(sql-editor): extract query-issue analysis + connection string resolution (#47980)

Charis11fb71514905
diff --git a/apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.test.ts b/apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.test.ts
index 389a06b9ff0..63f45bc3a11 100644
--- a/apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.test.ts
+++ b/apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.test.ts
@@ -4,6 +4,7 @@ import { describe, expect, it, test } from 'vitest'
import type { IStandaloneCodeEditor } from './SQLEditor.types'
import {
+ analyzeQueryIssues,
appendEnableRLSStatements,
assembleCompletionDiff,
buildDebugPromptText,
@@ -15,10 +16,13 @@ import {
getCreateTablesMissingRLS,
getEditorSql,
hasActiveEnsureRLSTrigger,
+ hasBlockingIssues,
isUpdateWithoutWhere,
+ resolveConnectionString,
suffixWithLimit,
} from './SQLEditor.utils'
import type { DatabaseEventTrigger } from '@/data/database-event-triggers/database-event-triggers-query'
+import type { Database } from '@/data/read-replicas/replicas-query'
const buildTrigger = (overrides: Partial<DatabaseEventTrigger> = {}): DatabaseEventTrigger => ({
oid: 1,
@@ -1045,3 +1049,109 @@ describe('SQLEditor.utils:buildDebugPromptText', () => {
expect(result).toContain('```sql\nselect 1;\n```')
})
})
+
+describe('SQLEditor.utils:analyzeQueryIssues', () => {
+ it('flags a destructive query with no event triggers', () => {
+ expect(analyzeQueryIssues('drop table countries;', undefined)).toEqual({
+ hasDestructiveOperations: true,
+ hasUpdateWithoutWhere: false,
+ hasAlterDatabasePreventConnection: false,
+ createTablesMissingRLS: [],
+ })
+ })
+
+ it('filters out a CREATE TABLE covered by an active ensure_rls trigger', () => {
+ const result = analyzeQueryIssues('create table foo (id int);', [buildTrigger()])
+ expect(result.createTablesMissingRLS).toEqual([])
+ })
+
+ it('reports no issues for a clean select query', () => {
+ expect(analyzeQueryIssues('select * from countries;', undefined)).toEqual({
+ hasDestructiveOperations: false,
+ hasUpdateWithoutWhere: false,
+ hasAlterDatabasePreventConnection: false,
+ createTablesMissingRLS: [],
+ })
+ })
+})
+
+describe('SQLEditor.utils:hasBlockingIssues', () => {
+ const noIssues = {
+ hasDestructiveOperations: false,
+ hasUpdateWithoutWhere: false,
+ hasAlterDatabasePreventConnection: false,
+ createTablesMissingRLS: [],
+ }
+
+ it('returns false when there are no issues', () => {
+ expect(hasBlockingIssues(noIssues, false)).toBe(false)
+ })
+
+ it('returns true when hasDestructiveOperations is set', () => {
+ expect(hasBlockingIssues({ ...noIssues, hasDestructiveOperations: true }, false)).toBe(true)
+ })
+
+ it('returns true when hasUpdateWithoutWhere is set', () => {
+ expect(hasBlockingIssues({ ...noIssues, hasUpdateWithoutWhere: true }, false)).toBe(true)
+ })
+
+ it('returns true when hasAlterDatabasePreventConnection is set', () => {
+ expect(hasBlockingIssues({ ...noIssues, hasAlterDatabasePreventConnection: true }, false)).toBe(
+ true
+ )
+ })
+
+ it('returns true when createTablesMissingRLS is non-empty', () => {
+ expect(
+ hasBlockingIssues({ ...noIssues, createTablesMissingRLS: [{ tableName: 'foo' }] }, false)
+ ).toBe(true)
+ })
+
+ it('returns false when force is true, even with issues present', () => {
+ expect(hasBlockingIssues({ ...noIssues, hasDestructiveOperations: true }, true)).toBe(false)
+ })
+
+ it('returns false when force is true and there are no issues', () => {
+ expect(hasBlockingIssues(noIssues, true)).toBe(false)
+ })
+})
+
+const buildDatabase = (overrides: Partial<Database> = {}): Database => ({
+ cloud_provider: 'AWS',
+ connectionString: 'postgres://primary',
+ db_host: 'db.example.com',
+ db_name: 'postgres',
+ db_port: 5432,
+ db_user: 'postgres',
+ identifier: 'primary',
+ inserted_at: '2024-01-01T00:00:00Z',
+ region: 'us-east-1',
+ restUrl: 'https://example.com',
+ size: 'micro',
+ status: 'ACTIVE_HEALTHY',
+ ...overrides,
+})
+
+describe('SQLEditor.utils:resolveConnectionString', () => {
+ it('returns the matching database connection string', () => {
+ const databases = [
+ buildDatabase({ identifier: 'primary', connectionString: 'postgres://primary' }),
+ buildDatabase({ identifier: 'replica-1', connectionString: 'postgres://replica-1' }),
+ ]
+ expect(resolveConnectionString(databases, 'replica-1')).toBe('postgres://replica-1')
+ })
+
+ it('returns undefined when no database matches', () => {
+ const databases = [buildDatabase({ identifier: 'primary' })]
+ expect(resolveConnectionString(databases, 'unknown')).toBeUndefined()
+ })
+
+ it('returns undefined when databases is undefined', () => {
+ expect(resolveConnectionString(undefined, 'primary')).toBeUndefined()
+ })
+
+ it('normalizes a null connectionString to undefined', () => {
+ const databases = [buildDatabase({ identifier: 'primary', connectionString: null })]
+ expect(resolveConnectionString(databases, 'primary')).toBeUndefined()
+ })
+})
diff --git a/apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.ts b/apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.ts
index 88a89a18d3e..27454efa19a 100644
--- a/apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.ts
+++ b/apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.ts
@@ -8,9 +8,10 @@ import {
sqlAiDisclaimerComment,
updateWithoutWhereRegex,
} from './SQLEditor.constants'
-import { ContentDiff, type IStandaloneCodeEditor } from './SQLEditor.types'
+import { ContentDiff, type IStandaloneCodeEditor, type PotentialIssues } from './SQLEditor.types'
import type { SnippetWithContent } from '@/data/content/sql-folders-query'
import type { DatabaseEventTrigger } from '@/data/database-event-triggers/database-event-triggers-query'
+import type { Database } from '@/data/read-replicas/replicas-query'
import { generateUuid } from '@/lib/api/snippets.browser'
import { removeCommentsFromSql } from '@/lib/helpers'
import { sqlEventParser } from '@/lib/sql-event-parser'
@@ -177,6 +178,53 @@ export function checkAlterDatabaseConnection(sql: string): boolean {
)
}
+/**
+ * Runs every pre-execution safety check on a query and packages the results as
+ * `PotentialIssues`, used both to decide whether to show the warning modal and
+ * to render its content.
+ */
+export function analyzeQueryIssues(
+ sql: string,
+ eventTriggers: DatabaseEventTrigger[] | undefined
+): PotentialIssues {
+ return {
+ hasDestructiveOperations: checkDestructiveQuery(sql),
+ hasUpdateWithoutWhere: isUpdateWithoutWhere(sql),
+ hasAlterDatabasePreventConnection: checkAlterDatabaseConnection(sql),
+ createTablesMissingRLS: filterTablesCoveredByEnsureRLSTrigger(
+ getCreateTablesMissingRLS(sql),
+ hasActiveEnsureRLSTrigger(eventTriggers)
+ ),
+ }
+}
+
+/**
+ * Whether `issues` should block an unforced run behind the warning modal.
+ */
+export function hasBlockingIssues(issues: PotentialIssues, force: boolean): boolean {
+ return (
+ !force &&
+ (!!issues.hasDestructiveOperations ||
+ !!issues.hasUpdateWithoutWhere ||
+ !!issues.hasAlterDatabasePreventConnection ||
+ (issues.createTablesMissingRLS?.length ?? 0) > 0)
+ )
+}
+
+/**
+ * Resolves the connection string for the currently selected database (primary
+ * or read replica) from the read-replicas list. Shared by the run and explain
+ * flows so the lookup isn't duplicated.
+ */
+export function resolveConnectionString(
+ databases: Database[] | undefined,
+ selectedDatabaseId: string | undefined
+): string | undefined {
+ return (
+ databases?.find((db) => db.identifier === selectedDatabaseId)?.connectionString ?? undefined
+ )
+}
+
export const generateMigrationCliCommand = (id: string, name: string, isNpx = false) =>
`
${isNpx ? 'npx ' : ''}supabase snippets download ${id} |
diff --git a/apps/studio/components/interfaces/SQLEditor/useSqlEditorExecution.ts b/apps/studio/components/interfaces/SQLEditor/useSqlEditorExecution.ts
index 7b926512e0b..85d76becfe4 100644
--- a/apps/studio/components/interfaces/SQLEditor/useSqlEditorExecution.ts
+++ b/apps/studio/components/interfaces/SQLEditor/useSqlEditorExecution.ts
@@ -7,13 +7,10 @@ import { toast } from 'sonner'
import { untitledSnippetTitle } from './SQLEditor.constants'
import type { PotentialIssues } from './SQLEditor.types'
import {
- checkAlterDatabaseConnection,
- checkDestructiveQuery,
+ analyzeQueryIssues,
checkIfAppendLimitRequired,
- filterTablesCoveredByEnsureRLSTrigger,
- getCreateTablesMissingRLS,
- hasActiveEnsureRLSTrigger,
- isUpdateWithoutWhere,
+ hasBlockingIssues,
+ resolveConnectionString,
suffixWithLimit,
} from './SQLEditor.utils'
import { useSQLEditorContext } from './SQLEditorContext'
@@ -108,28 +105,10 @@ export function useSqlEditorExecution({
return
}
- const hasDestructiveOperations = checkDestructiveQuery(sql)
- const hasUpdateWithoutWhere = isUpdateWithoutWhere(sql)
- const hasAlterDatabasePreventConnection = checkAlterDatabaseConnection(sql)
- const createTablesMissingRLS = filterTablesCoveredByEnsureRLSTrigger(
- getCreateTablesMissingRLS(sql),
- hasActiveEnsureRLSTrigger(eventTriggers)
- )
+ const issues = analyzeQueryIssues(sql, eventTriggers)
- const queryHasIssues =
- !force &&
- (hasDestructiveOperations ||
- hasUpdateWithoutWhere ||
- hasAlterDatabasePreventConnection ||
- createTablesMissingRLS.length > 0)
-
- if (queryHasIssues) {
- setPotentialIssues({
- hasDestructiveOperations,
- hasUpdateWithoutWhere,
- hasAlterDatabasePreventConnection,
- createTablesMissingRLS,
- })
+ if (hasBlockingIssues(issues, force)) {
+ setPotentialIssues(issues)
return
}
@@ -149,9 +128,10 @@ export function useSqlEditorExecution({
clearHighlights()
const impersonatedRoleState = getImpersonatedRoleState()
- const connectionString = databases?.find(
- (db) => db.identifier === databaseSelectorState.selectedDatabaseId
- )?.connectionString
+ const connectionString = resolveConnectionString(
+ databases,
+ databaseSelectorState.selectedDatabaseId
+ )
if (!isValidConnString(connectionString)) {
clearPendingRunRefocus()
return toast.error('Unable to run query: Connection string is missing')