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 pure SQL helpers + tighten safe-SQL boundary (decompose 2/6) (#47831)

Charisb6cdd5cce329
diff --git a/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx b/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx
index 304389598bf..10785b69a3d 100644
--- a/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx
+++ b/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx
@@ -1,12 +1,10 @@
import type { Monaco } from '@monaco-editor/react'
import {
acceptUntrustedSql,
- rawSql,
- safeSql,
+ untrustedSql,
type SafeSqlFragment,
type UntrustedSqlFragment,
} from '@supabase/pg-meta'
-import { wrapWithRollback } from '@supabase/pg-meta/src/query'
import { useQueryClient } from '@tanstack/react-query'
import { IS_PLATFORM, LOCAL_STORAGE_KEYS, useFlag, useParams } from 'common'
import { Loader2 } from 'lucide-react'
@@ -31,12 +29,17 @@ import {
} from './SQLEditor.types'
import {
appendEnableRLSStatements,
+ assembleCompletionDiff,
+ buildDebugPromptText,
+ buildExplainSql,
checkAlterDatabaseConnection,
checkDestructiveQuery,
checkIfAppendLimitRequired,
+ computeErrorHighlightLine,
createSqlSnippetSkeletonV2,
filterTablesCoveredByEnsureRLSTrigger,
getCreateTablesMissingRLS,
+ getEditorSql,
hasActiveEnsureRLSTrigger,
isUpdateWithoutWhere,
suffixWithLimit,
@@ -46,7 +49,6 @@ import { UtilityActions } from './UtilityPanel/UtilityActions'
import { UtilityPanel } from './UtilityPanel/UtilityPanel'
import {
isExplainQuery,
- isExplainSql,
splitSqlStatements,
} from '@/components/interfaces/ExplainVisualizer/ExplainVisualizer.utils'
import { SIDEBAR_KEYS } from '@/components/layouts/ProjectLayout/LayoutSidebar/LayoutSidebarProvider'
@@ -243,10 +245,7 @@ export const SQLEditor = () => {
const startLineNumber = hasSelection ? (editor?.getSelection()?.startLineNumber ?? 0) : 0
- const formattedError = error.formattedError ?? ''
- const lineError = formattedError.slice(formattedError.indexOf('LINE'))
- const line =
- startLineNumber + Number(lineError.slice(0, lineError.indexOf(':')).split(' ')[1])
+ const line = computeErrorHighlightLine(error, startLineNumber)
if (!isNaN(line)) {
const decorations = editor?.deltaDecorations(
@@ -314,12 +313,7 @@ export const SQLEditor = () => {
if (editorRef.current && project) {
const editor = editorRef.current
- const selection = editor.getSelection()
- const selectedValue = selection ? editor.getModel()?.getValueInRange(selection) : undefined
- const sql = snippet
- ? ((selectedValue || editorRef.current?.getValue()) ??
- snippet.snippet.content?.unchecked_sql)
- : selectedValue || editorRef.current?.getValue()
+ const sql = getEditorSql(editor, snippet?.snippet.content?.unchecked_sql)
const formattedSql = formatSql(sql)
const editorModel = editorRef?.current?.getModel()
@@ -339,32 +333,29 @@ export const SQLEditor = () => {
registerInCommandMenu: true,
})
+ // Reads the SQL to run from the editor as an UntrustedSqlFragment. The
+ // untrusted→safe promotion (acceptUntrustedSql) happens in the small run /
+ // explain gesture handlers below — never inside the longer execute* helpers,
+ // which by construction only accept already-reviewed SafeSqlFragments.
+ const readEditorSql = useCallback((): UntrustedSqlFragment | undefined => {
+ const editor = editorRef.current
+ if (!editor) return undefined
+ const snippet = getSqlEditorV2StateSnapshot().snippets[id]
+ return getEditorSql(editor, snippet?.snippet.content?.unchecked_sql)
+ }, [id])
+
const executeQuery = useCallback(
- async (force: boolean = false, sqlOverride?: SafeSqlFragment) => {
+ async (sql: SafeSqlFragment, force: boolean = false) => {
if (isDiffOpen) {
clearPendingRunRefocus()
return
}
- // use the latest state
- const state = getSqlEditorV2StateSnapshot()
- const snippet = state.snippets[id]
-
if (editorRef.current === null || isExecuting || project === undefined) {
clearPendingRunRefocus()
return
}
- const editor = editorRef.current
- const selection = editor.getSelection()
- const selectedValue = selection ? editor.getModel()?.getValueInRange(selection) : undefined
-
- const editorSql = snippet
- ? ((selectedValue || editorRef.current?.getValue()) ??
- snippet.snippet.content?.unchecked_sql)
- : selectedValue || editorRef.current?.getValue()
- const sql = sqlOverride ?? editorSql
-
const hasDestructiveOperations = checkDestructiveQuery(sql)
const hasUpdateWithoutWhere = isUpdateWithoutWhere(sql)
const hasAlterDatabasePreventConnection = checkAlterDatabaseConnection(sql)
@@ -390,6 +381,8 @@ export const SQLEditor = () => {
return
}
+ // use the latest state for the title-generation check
+ const snippet = getSqlEditorV2StateSnapshot().snippets[id]
if (
// Don't auto-generate a title when the org has disabled AI or is a HIPAA project,
// as that would silently forward the query to the AI provider without consent
@@ -402,7 +395,7 @@ export const SQLEditor = () => {
}
if (lineHighlights.length > 0) {
- editor?.deltaDecorations(lineHighlights, [])
+ editorRef.current?.deltaDecorations(lineHighlights, [])
setLineHighlights([])
}
@@ -415,9 +408,8 @@ export const SQLEditor = () => {
return toast.error('Unable to run query: Connection string is missing')
}
- const userSql = rawSql(sql)
- const { appendAutoLimit } = checkIfAppendLimitRequired(userSql, limit)
- const formattedSql = suffixWithLimit(userSql, limit)
+ const { appendAutoLimit } = checkIfAppendLimitRequired(sql, limit)
+ const formattedSql = suffixWithLimit(sql, limit)
execute({
projectRef: project.ref,
@@ -453,87 +445,87 @@ export const SQLEditor = () => {
]
)
+ // Run gesture from the toolbar button: promote here, then run.
const executeQueryFromButton = useCallback(() => {
shouldRefocusAfterRunRef.current = true
refocusEditor()
- void executeQuery()
- }, [executeQuery, refocusEditor])
+ const sql = readEditorSql()
+ if (sql === undefined) return clearPendingRunRefocus()
+ void executeQuery(acceptUntrustedSql(sql))
+ }, [clearPendingRunRefocus, executeQuery, readEditorSql, refocusEditor])
+
+ // Run gesture from the editor (Cmd/Ctrl+Enter): promote here, then run.
+ const handleRunShortcut = useCallback(() => {
+ const sql = readEditorSql()
+ if (sql !== undefined) void executeQuery(acceptUntrustedSql(sql))
+ }, [executeQuery, readEditorSql])
+
+ const executeExplainQuery = useCallback(
+ async (sql: SafeSqlFragment) => {
+ if (isDiffOpen) return
+
+ if (editorRef.current !== null && !isExplainExecuting && project !== undefined) {
+ // Check for multiple statements - EXPLAIN only works on a single statement
+ const statements = splitSqlStatements(sql)
+ if (statements.length > 1) {
+ sessionSnap.addExplainResultError(id, {
+ message:
+ 'EXPLAIN only works on a single SQL statement. Please select just one query to analyze.',
+ })
+ setActiveUtilityTab('explain')
+ return
+ }
- const executeExplainQuery = useCallback(async () => {
- if (isDiffOpen) return
+ if (lineHighlights.length > 0) {
+ editorRef.current?.deltaDecorations(lineHighlights, [])
+ setLineHighlights([])
+ }
- // use the latest state
- const state = getSqlEditorV2StateSnapshot()
- const snippet = state.snippets[id]
+ const impersonatedRoleState = getImpersonatedRoleState()
+ const connectionString = databases?.find(
+ (db) => db.identifier === databaseSelectorState.selectedDatabaseId
+ )?.connectionString
+ if (!isValidConnString(connectionString)) {
+ return toast.error('Unable to run query: Connection string is missing')
+ }
- if (editorRef.current !== null && !isExplainExecuting && project !== undefined) {
- const editor = editorRef.current
- const selection = editor.getSelection()
- const selectedValue = selection ? editor.getModel()?.getValueInRange(selection) : undefined
-
- const sql = snippet
- ? ((selectedValue || editorRef.current?.getValue()) ??
- snippet.snippet.content?.unchecked_sql)
- : selectedValue || editorRef.current?.getValue()
-
- // Check for multiple statements - EXPLAIN only works on a single statement
- const statements = splitSqlStatements(sql)
- if (statements.length > 1) {
- sessionSnap.addExplainResultError(id, {
- message:
- 'EXPLAIN only works on a single SQL statement. Please select just one query to analyze.',
+ // Wrap in EXPLAIN ANALYZE (unless already an EXPLAIN), apply role
+ // impersonation, and wrap in a rollback transaction so EXPLAIN ANALYZE
+ // INSERT/UPDATE/DELETE queries don't actually modify data.
+ const explainSqlWithTransaction = buildExplainSql(sql, impersonatedRoleState)
+
+ executeExplain({
+ projectRef: project.ref,
+ connectionString: connectionString,
+ sql: explainSqlWithTransaction,
+ isRoleImpersonationEnabled: isRoleImpersonationEnabled(impersonatedRoleState.role),
+ handleError: (error) => {
+ throw error
+ },
})
- setActiveUtilityTab('explain')
- return
}
+ },
+ [
+ isDiffOpen,
+ id,
+ isExplainExecuting,
+ project,
+ executeExplain,
+ getImpersonatedRoleState,
+ databaseSelectorState.selectedDatabaseId,
+ databases,
+ lineHighlights,
+ sessionSnap,
+ ]
+ )
- if (lineHighlights.length > 0) {
- editor?.deltaDecorations(lineHighlights, [])
- setLineHighlights([])
- }
-
- const impersonatedRoleState = getImpersonatedRoleState()
- const connectionString = databases?.find(
- (db) => db.identifier === databaseSelectorState.selectedDatabaseId
- )?.connectionString
- if (!isValidConnString(connectionString)) {
- return toast.error('Unable to run query: Connection string is missing')
- }
-
- // Wrap the query with EXPLAIN ANALYZE only if it's not already an EXPLAIN query
- const userSql = rawSql(sql ?? '')
- const explainSql = isExplainSql(sql) ? userSql : safeSql`EXPLAIN ANALYZE ${userSql}`
-
- // Wrap EXPLAIN queries in a transaction with rollback to prevent data modifications
- // This ensures EXPLAIN ANALYZE INSERT/UPDATE/DELETE queries don't actually modify data
- const explainSqlWithTransaction = wrapWithRollback(
- wrapWithRoleImpersonation(explainSql, impersonatedRoleState)
- )
+ // Explain gesture (editor action, toolbar, shortcut): promote here, then run.
+ const handleRunExplain = useCallback(() => {
+ const sql = readEditorSql()
+ if (sql !== undefined) void executeExplainQuery(acceptUntrustedSql(sql))
+ }, [executeExplainQuery, readEditorSql])
- executeExplain({
- projectRef: project.ref,
- connectionString: connectionString,
- sql: explainSqlWithTransaction,
- isRoleImpersonationEnabled: isRoleImpersonationEnabled(impersonatedRoleState.role),
- handleError: (error) => {
- throw error
- },
- })
- }
- }, [
- isDiffOpen,
- id,
- isExplainExecuting,
- project,
- executeExplain,
- getImpersonatedRoleState,
- databaseSelectorState.selectedDatabaseId,
- databases,
- lineHighlights,
- sessionSnap,
- ])
-
- useShortcut(SHORTCUT_IDS.SQL_EDITOR_EXPLAIN, executeExplainQuery, {
+ useShortcut(SHORTCUT_IDS.SQL_EDITOR_EXPLAIN, handleRunExplain, {
enabled: !disablePrettyExplain,
registerInCommandMenu: true,
})
@@ -584,9 +576,8 @@ export const SQLEditor = () => {
.replace(sqlAiDisclaimerComment, '')
.trim()
const errorMessage = result?.error?.message ?? 'Unknown error'
- const prompt = `Help me to debug the attached sql snippet which gives the following error: \n\n${errorMessage}`
- return `${prompt}\n\nSQL Query:\n\`\`\`sql\n${sql}\n\`\`\``
+ return buildDebugPromptText(sql, errorMessage)
}, [id, sessionSnap.results, snapV2.snippets])
const onDebug = useCallback(async () => {
@@ -694,12 +685,7 @@ export const SQLEditor = () => {
const text: string = await response.json()
const meta = options?.body?.completionMetadata ?? {}
- const beforeSelection: string = meta.textBeforeCursor ?? ''
- const afterSelection: string = meta.textAfterCursor ?? ''
- const selection: string = meta.selection ?? ''
-
- const original = beforeSelection + selection + afterSelection
- const modified = beforeSelection + text + afterSelection
+ const { original, modified } = assembleCompletionDiff(meta, text)
const formattedModified = formatSql(modified)
setSourceSqlDiff({ original, modified: formattedModified })
@@ -881,22 +867,21 @@ export const SQLEditor = () => {
shouldRefocusAfterRunRef.current = true
setPotentialIssues(undefined)
refocusEditor()
- void executeQuery(true)
+ // The user has reviewed the warning and confirmed — promote here.
+ const sql = readEditorSql()
+ if (sql === undefined) return clearPendingRunRefocus()
+ void executeQuery(acceptUntrustedSql(sql), true)
}}
onConfirmWithRLS={() => {
const tables = potentialIssues?.createTablesMissingRLS ?? []
if (tables.length === 0) return
- const editor = editorRef.current
- const selection = editor?.getSelection()
- const selectedValue = selection
- ? editor?.getModel()?.getValueInRange(selection)
- : undefined
- const baseSql = selectedValue || editor?.getValue() || ''
+ const baseSql = readEditorSql() ?? untrustedSql('')
const rewrittenSql = appendEnableRLSStatements(baseSql, tables)
shouldRefocusAfterRunRef.current = true
setPotentialIssues(undefined)
refocusEditor()
- void executeQuery(true, acceptUntrustedSql(rewrittenSql as UntrustedSqlFragment))
+ // The user has reviewed the warning and confirmed — promote here.
+ void executeQuery(acceptUntrustedSql(untrustedSql(rewrittenSql)), true)
}}
/>
@@ -977,8 +962,8 @@ export const SQLEditor = () => {
className={cn(isDiffOpen && 'hidden')}
editorRef={editorRef}
monacoRef={monacoRef}
- executeQuery={executeQuery}
- executeExplainQuery={executeExplainQuery}
+ executeQuery={handleRunShortcut}
+ executeExplainQuery={handleRunExplain}
showExplainAction={!disablePrettyExplain}
prettifyQuery={prettifyQuery}
onHasSelection={setHasSelection}
@@ -1040,7 +1025,7 @@ export const SQLEditor = () => {
isExecuting={isExecuting}
isExplainExecuting={isExplainExecuting}
isDisabled={isDiffOpen}
- executeExplainQuery={executeExplainQuery}
+ executeExplainQuery={handleRunExplain}
showExplainTab={!disablePrettyExplain}
onDebug={onDebug}
buildDebugPrompt={buildDebugPrompt}
diff --git a/apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.test.ts b/apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.test.ts
index 51b01338b15..73e51811ea8 100644
--- a/apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.test.ts
+++ b/apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.test.ts
@@ -1,14 +1,20 @@
-import { safeSql } from '@supabase/pg-meta'
+import { safeSql, untrustedSql } from '@supabase/pg-meta'
import { stripIndent } from 'common-tags'
import { describe, expect, it, test } from 'vitest'
+import type { IStandaloneCodeEditor } from './SQLEditor.types'
import {
appendEnableRLSStatements,
+ assembleCompletionDiff,
+ buildDebugPromptText,
+ buildExplainSql,
checkAlterDatabaseConnection,
checkDestructiveQuery,
checkIfAppendLimitRequired,
+ computeErrorHighlightLine,
filterTablesCoveredByEnsureRLSTrigger,
getCreateTablesMissingRLS,
+ getEditorSql,
hasActiveEnsureRLSTrigger,
isUpdateWithoutWhere,
suffixWithLimit,
@@ -962,3 +968,97 @@ describe('SQLEditor.utils:checkAlterDatabaseConnection', () => {
expect(match).toBe(true)
})
})
+
+// Minimal fake editor for exercising getEditorSql's selection/value logic.
+const makeEditor = ({
+ value,
+ selectionValue,
+ hasSelection = selectionValue !== undefined,
+}: {
+ value: string | undefined
+ selectionValue?: string
+ hasSelection?: boolean
+}): IStandaloneCodeEditor =>
+ ({
+ getValue: () => value,
+ getSelection: () => (hasSelection ? ({ startLineNumber: 1 } as any) : null),
+ getModel: () => ({ getValueInRange: () => selectionValue }) as any,
+ }) as unknown as IStandaloneCodeEditor
+
+describe('SQLEditor.utils:getEditorSql', () => {
+ it('returns the selected text when there is a selection', () => {
+ const editor = makeEditor({ value: 'select 1;', selectionValue: 'select 2;' })
+ expect(getEditorSql(editor)).toBe('select 2;')
+ })
+
+ it('returns the full editor value when there is no selection', () => {
+ const editor = makeEditor({ value: 'select 1;', hasSelection: false })
+ expect(getEditorSql(editor)).toBe('select 1;')
+ })
+
+ it('falls back to the full value when the selection is empty', () => {
+ const editor = makeEditor({ value: 'select 1;', selectionValue: '' })
+ expect(getEditorSql(editor)).toBe('select 1;')
+ })
+
+ it('falls back to snippet content only when there is no editor value', () => {
+ // Real Monaco always returns a string from getValue(); this guards the
+ // last-resort snippet-content fallback contract.
+ const editor = makeEditor({ value: undefined, hasSelection: false })
+ expect(getEditorSql(editor, untrustedSql('stored sql'))).toBe('stored sql')
+ })
+})
+
+describe('SQLEditor.utils:computeErrorHighlightLine', () => {
+ it('parses the LINE marker and offsets by the selection start line', () => {
+ const error = { formattedError: 'ERROR: syntax error\nLINE 3: slect 1;\n ^' }
+ expect(computeErrorHighlightLine(error, 0)).toBe(3)
+ expect(computeErrorHighlightLine(error, 5)).toBe(8)
+ })
+
+ it('returns NaN when there is no LINE marker', () => {
+ expect(computeErrorHighlightLine({ formattedError: 'boom' }, 0)).toBeNaN()
+ })
+
+ it('returns NaN when formattedError is missing', () => {
+ expect(computeErrorHighlightLine({}, 2)).toBeNaN()
+ })
+})
+
+describe('SQLEditor.utils:assembleCompletionDiff', () => {
+ it('assembles original and modified from before/selection/after', () => {
+ const result = assembleCompletionDiff(
+ { textBeforeCursor: 'a ', selection: 'b', textAfterCursor: ' c' },
+ 'X'
+ )
+ expect(result).toEqual({ original: 'a b c', modified: 'a X c' })
+ })
+
+ it('treats missing metadata fields as empty strings', () => {
+ expect(assembleCompletionDiff({}, 'X')).toEqual({ original: '', modified: 'X' })
+ })
+})
+
+describe('SQLEditor.utils:buildExplainSql', () => {
+ it('wraps a non-EXPLAIN query in EXPLAIN ANALYZE and a rollback transaction', () => {
+ const result = buildExplainSql(safeSql`select 1`)
+ expect(result).toMatch(/begin;/i)
+ expect(result).toMatch(/explain analyze select 1/i)
+ expect(result).toMatch(/rollback;/i)
+ })
+
+ it('does not double-wrap a query that is already an EXPLAIN', () => {
+ const result = buildExplainSql(safeSql`explain select 1`)
+ expect(result).toMatch(/explain select 1/i)
+ expect(result).not.toMatch(/analyze/i)
+ expect(result).toMatch(/rollback;/i)
+ })
+})
+
+describe('SQLEditor.utils:buildDebugPromptText', () => {
+ it('builds the debug prompt with the error message and SQL block', () => {
+ const result = buildDebugPromptText('select 1;', 'relation does not exist')
+ expect(result).toContain('relation does not exist')
+ expect(result).toContain('```sql\nselect 1;\n```')
+ })
+})
diff --git a/apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.ts b/apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.ts
index d662302048d..de40b63f8eb 100644
--- a/apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.ts
+++ b/apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.ts
@@ -1,4 +1,10 @@
-import { untrustedSql, type SafeSqlFragment } from '@supabase/pg-meta'
+import {
+ safeSql,
+ untrustedSql,
+ type SafeSqlFragment,
+ type UntrustedSqlFragment,
+} from '@supabase/pg-meta'
+import { wrapWithRollback } from '@supabase/pg-meta/src/query'
import { TABLE_EVENT_ACTIONS } from 'common/telemetry-constants'
import {
@@ -8,12 +14,15 @@ import {
sqlAiDisclaimerComment,
updateWithoutWhereRegex,
} from './SQLEditor.constants'
-import { ContentDiff } from './SQLEditor.types'
+import { ContentDiff, type IStandaloneCodeEditor } from './SQLEditor.types'
+import { isExplainSql } from '@/components/interfaces/ExplainVisualizer/ExplainVisualizer.utils'
import type { SnippetWithContent } from '@/data/content/sql-folders-query'
import type { DatabaseEventTrigger } from '@/data/database-event-triggers/database-event-triggers-query'
import { generateUuid } from '@/lib/api/snippets.browser'
import { removeCommentsFromSql } from '@/lib/helpers'
+import { wrapWithRoleImpersonation } from '@/lib/role-impersonation'
import { sqlEventParser } from '@/lib/sql-event-parser'
+import type { RoleImpersonationState } from '@/state/role-impersonation-state'
export type CreateTableWithoutRLS = {
schema?: string
@@ -261,3 +270,79 @@ export const suffixWithLimit = (sql: SafeSqlFragment, limit: number = 0): SafeSq
cleanedSql.endsWith(';') ? sql.replace(/[;]+$/, ` limit ${limit};`) : `${sql} limit ${limit};`
) as SafeSqlFragment
}
+
+/**
+ * Resolves the SQL to act on from the editor: the current selection if there is
+ * one, otherwise the full editor contents, falling back to the snippet's stored
+ * SQL. Mirrors the logic that used to be duplicated inline across the run,
+ * prettify and explain flows.
+ *
+ * Returns an `UntrustedSqlFragment`: editor contents (and snippet
+ * `unchecked_sql`) can be influenced by third parties (e.g. URL-prefilled
+ * snippets), so the value must only be promoted to executable via
+ * `acceptUntrustedSql` inside an explicit run/explain user action.
+ */
+export function getEditorSql(
+ editor: IStandaloneCodeEditor,
+ snippetContent?: UntrustedSqlFragment
+): UntrustedSqlFragment {
+ const selection = editor.getSelection()
+ const selectedValue = selection ? editor.getModel()?.getValueInRange(selection) : undefined
+ return untrustedSql((selectedValue || editor.getValue()) ?? snippetContent)
+}
+
+/**
+ * Parses a Postgres `formattedError` (e.g. `... LINE 3: ...`) into the 1-based
+ * editor line to highlight, offset by the selection's start line. Returns `NaN`
+ * when the error carries no parseable `LINE` marker; callers guard on that.
+ */
+export function computeErrorHighlightLine(
+ error: { formattedError?: string },
+ startLineNumber: number
+): number {
+ const formattedError = error.formattedError ?? ''
+ const lineError = formattedError.slice(formattedError.indexOf('LINE'))
+ return startLineNumber + Number(lineError.slice(0, lineError.indexOf(':')).split(' ')[1])
+}
+
+/**
+ * Reassembles the original vs. modified SQL for an AI completion diff from the
+ * completion metadata (text before/after the cursor + selection) and the
+ * generated replacement text.
+ */
+export function assembleCompletionDiff(
+ meta: { textBeforeCursor?: string; textAfterCursor?: string; selection?: string },
+ text: string
+): ContentDiff {
+ const beforeSelection = meta.textBeforeCursor ?? ''
+ const afterSelection = meta.textAfterCursor ?? ''
+ const selection = meta.selection ?? ''
+ return {
+ original: beforeSelection + selection + afterSelection,
+ modified: beforeSelection + text + afterSelection,
+ }
+}
+
+/**
+ * Builds the SQL sent for an EXPLAIN run: wraps the query in `EXPLAIN ANALYZE`
+ * (unless it is already an EXPLAIN), applies role impersonation, and wraps the
+ * whole thing in a rollback transaction so EXPLAIN ANALYZE never mutates data.
+ *
+ * Takes an already-safe fragment — the untrusted→safe promotion happens at the
+ * caller's user-action boundary (see `acceptUntrustedSql`), not in here.
+ */
+export function buildExplainSql(
+ sql: SafeSqlFragment,
+ impersonatedRoleState?: RoleImpersonationState
+): SafeSqlFragment {
+ const explainSql = isExplainSql(sql) ? sql : safeSql`EXPLAIN ANALYZE ${sql}`
+ return wrapWithRollback(wrapWithRoleImpersonation(explainSql, impersonatedRoleState))
+}
+
+/**
+ * Builds the prompt text used to ask the assistant to debug a failing snippet.
+ */
+export function buildDebugPromptText(sql: string, errorMessage: string): string {
+ const prompt = `Help me to debug the attached sql snippet which gives the following error: \n\n${errorMessage}`
+ return `${prompt}\n\nSQL Query:\n\`\`\`sql\n${sql}\n\`\`\``
+}