Skip to content

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

feat(assistant): score and improve SQL identifier quoting (#42122)

Matt Rossmaneb259f136415
diff --git a/apps/studio/evals/assistant.eval.ts b/apps/studio/evals/assistant.eval.ts
index da25f794b35..650dbe2e525 100644
--- a/apps/studio/evals/assistant.eval.ts
+++ b/apps/studio/evals/assistant.eval.ts
@@ -10,6 +10,7 @@ import {
correctnessScorer,
docsFaithfulnessScorer,
goalCompletionScorer,
+ sqlIdentifierQuotingScorer,
sqlSyntaxScorer,
toolUsageScorer,
} from './scorer'
@@ -24,8 +25,8 @@ Eval('Assistant', {
task: async (input) => {
const result = await generateAssistantResponse({
model: openai('gpt-5-mini'),
- messages: [{ id: '1', role: 'user', parts: [{ type: 'text', text: input }] }],
- tools: await getMockTools(),
+ messages: [{ id: '1', role: 'user', parts: [{ type: 'text', text: input.prompt }] }],
+ tools: await getMockTools(input.mockTables ? { list_tables: input.mockTables } : undefined),
})
const finishReason = await result.finishReason
@@ -76,6 +77,7 @@ Eval('Assistant', {
scores: [
toolUsageScorer,
sqlSyntaxScorer,
+ sqlIdentifierQuotingScorer,
goalCompletionScorer,
concisenessScorer,
completenessScorer,
diff --git a/apps/studio/evals/dataset.ts b/apps/studio/evals/dataset.ts
index 16ce4af0437..6e5d73bb273 100644
--- a/apps/studio/evals/dataset.ts
+++ b/apps/studio/evals/dataset.ts
@@ -2,41 +2,45 @@ import { AssistantEvalCase } from './scorer'
export const dataset: AssistantEvalCase[] = [
{
- input: 'How do I run WASM in edge functions? Use `search_docs`.',
+ input: { prompt: 'How do I run WASM in edge functions? Use `search_docs`.' },
expected: { requiredTools: ['search_docs'] },
metadata: { category: ['general_help'] },
},
{
- input: 'Check if my project is having issues right now and tell me what to fix first.',
+ input: {
+ prompt: 'Check if my project is having issues right now and tell me what to fix first.',
+ },
expected: {
requiredTools: ['get_advisors', 'get_logs'],
},
metadata: { category: ['debugging', 'rls_policies'] },
},
{
- input: 'Create a new table "foods" with columns for "name" and "color"',
+ input: { prompt: 'Create a new table "foods" with columns for "name" and "color"' },
expected: {
requiredTools: ['execute_sql'],
},
metadata: { category: ['sql_generation', 'schema_design'] },
},
{
- input:
- 'Write a SQL query to select all products from the products table where the price is greater than 100',
+ input: {
+ prompt:
+ 'Write a SQL query to select all projects from the projects table where the name is not null',
+ },
expected: {
requiredTools: ['execute_sql'],
},
metadata: { category: ['sql_generation'] },
},
{
- input: 'Create an index on the products table for the name column',
+ input: { prompt: 'Create an index on the projects table for the name column' },
expected: {
requiredTools: ['execute_sql'],
},
metadata: { category: ['sql_generation', 'database_optimization'] },
},
{
- input: 'How many projects are included in the free tier?',
+ input: { prompt: 'How many projects are included in the free tier?' },
expected: {
requiredTools: ['search_docs'],
correctAnswer: '2',
@@ -44,7 +48,7 @@ export const dataset: AssistantEvalCase[] = [
metadata: { category: ['general_help'] },
},
{
- input: 'Restore my Supabase Storage files to the state from 3 days ago',
+ input: { prompt: 'Restore my Supabase Storage files to the state from 3 days ago' },
expected: {
requiredTools: ['search_docs'],
correctAnswer:
@@ -53,11 +57,41 @@ export const dataset: AssistantEvalCase[] = [
metadata: { category: ['general_help'] },
},
{
- input: 'How do I enable S3 versioning in Supabase Storage?',
+ input: { prompt: 'How do I enable S3 versioning in Supabase Storage?' },
expected: {
requiredTools: ['search_docs'],
correctAnswer: 'S3 versioning is not supported in Supabase Storage.',
},
metadata: { category: ['general_help'] },
},
+ {
+ input: {
+ prompt:
+ 'Show me customer name, order date, order, and user from the order history table in MySchema where order is not null',
+ mockTables: {
+ MySchema: [
+ {
+ name: 'order-history',
+ rls_enabled: false,
+ columns: [
+ { name: 'id', data_type: 'bigint' },
+ { name: 'customerName', data_type: 'text' },
+ { name: 'order-date', data_type: 'timestamp with time zone' },
+ { name: 'order', data_type: 'uuid' },
+ { name: 'user', data_type: 'text' },
+ { name: 'total', data_type: 'numeric' },
+ ],
+ },
+ ],
+ },
+ },
+ expected: {
+ requiredTools: ['execute_sql'],
+ },
+ metadata: {
+ category: ['sql_generation'],
+ description:
+ 'Uses quotes around schema/table/columns with capital letters, special characters, and reserved keywords.',
+ },
+ },
]
diff --git a/apps/studio/evals/scorer.ts b/apps/studio/evals/scorer.ts
index 718f712ec60..6a9a0e1ac48 100644
--- a/apps/studio/evals/scorer.ts
+++ b/apps/studio/evals/scorer.ts
@@ -3,10 +3,23 @@ import { LLMClassifierFromTemplate } from 'autoevals'
import { EvalCase, EvalScorer } from 'braintrust'
import { stripIndent } from 'common-tags'
import { parse } from 'libpg-query'
+import { MOCK_TABLES_DATA } from 'lib/ai/tools/mock-tools'
+import { extractIdentifiers } from 'lib/sql-identifier-quoting'
+import { isQuotedInSql, needsQuoting } from 'lib/sql-identifier-quoting'
const LLM_AS_A_JUDGE_MODEL = 'gpt-5.2-2025-12-11'
-type Input = string
+type Input = {
+ prompt: string
+ mockTables?: Record<
+ string,
+ Array<{
+ name: string
+ rls_enabled: boolean
+ columns: Array<{ name: string; data_type: string }>
+ }>
+ >
+}
type Output = {
finishReason: FinishReason
@@ -34,6 +47,7 @@ export type AssistantEvalCaseCategory =
export type AssistantEvalCaseMetadata = {
category?: AssistantEvalCaseCategory[]
+ description?: string
}
export type AssistantEvalCase = EvalCase<Input, Expected, AssistantEvalCaseMetadata>
@@ -125,7 +139,7 @@ const concisenessEvaluator = LLMClassifierFromTemplate<{ input: string }>({
export const concisenessScorer: EvalScorer<Input, Output, Expected> = async ({ input, output }) => {
return await concisenessEvaluator({
- input,
+ input: input.prompt,
output: serializeSteps(output.steps),
})
}
@@ -152,7 +166,7 @@ export const completenessScorer: EvalScorer<Input, Output, Expected> = async ({
output,
}) => {
return await completenessEvaluator({
- input,
+ input: input.prompt,
output: serializeSteps(output.steps),
})
}
@@ -180,7 +194,7 @@ export const goalCompletionScorer: EvalScorer<Input, Output, Expected> = async (
output,
}) => {
return await goalCompletionEvaluator({
- input,
+ input: input.prompt,
output: serializeSteps(output.steps),
})
}
@@ -258,8 +272,54 @@ export const correctnessScorer: EvalScorer<Input, Output, Expected> = async ({
}
return await correctnessEvaluator({
- input,
+ input: input.prompt,
expected: expected.correctAnswer,
output: extractTextOnly(output.steps),
})
}
+
+export const sqlIdentifierQuotingScorer: EvalScorer<Input, Output, Expected> = async ({
+ input,
+ output,
+}) => {
+ // Skip if no SQL queries
+ if (!output.sqlQueries?.length) {
+ return null
+ }
+
+ const errors: string[] = []
+ let totalNeedingQuotes = 0
+ let properlyQuoted = 0
+
+ for (const sql of output.sqlQueries) {
+ try {
+ const ast = await parse(sql)
+ const identifiers = extractIdentifiers(ast)
+
+ for (const identifier of identifiers) {
+ if (needsQuoting(identifier)) {
+ totalNeedingQuotes++
+ if (isQuotedInSql(sql, identifier)) {
+ properlyQuoted++
+ } else {
+ const sqlPreview = sql.length > 100 ? `${sql.substring(0, 100)}...` : sql
+ errors.push(
+ `Identifier "${identifier}" needs quoting but is not quoted in: ${sqlPreview}`
+ )
+ }
+ }
+ }
+ } catch (error) {
+ // Skip invalid SQL - already handled by sqlSyntaxScorer
+ continue
+ }
+ }
+
+ const score = totalNeedingQuotes === 0 ? 1 : properlyQuoted / totalNeedingQuotes
+
+ return {
+ name: 'SQL Identifier Quoting',
+ score,
+ metadata: errors.length > 0 ? { errors } : undefined,
+ }
+}
diff --git a/apps/studio/lib/ai/prompts.ts b/apps/studio/lib/ai/prompts.ts
index 5f52d254789..9c719bca9ec 100644
--- a/apps/studio/lib/ai/prompts.ts
+++ b/apps/studio/lib/ai/prompts.ts
@@ -235,6 +235,7 @@ export const PG_BEST_PRACTICES = `
## SQL Style Guidelines
- Ensure all generated SQL is valid for Postgres.
- Always escape single quotes within strings using double apostrophes (e.g., \`'Night''s watch'\`).
+- Always quote identifiers (table names, column names) with double quotes when they contain uppercase letters (e.g., \`SELECT "locationType" FROM "Locations"\`), are PostgreSQL reserved words (e.g., \`"order"\`, \`"select"\`, \`"table"\`), or have special characters like dashes or spaces (e.g., \`"user-name"\`, \`"created at"\`). PostgreSQL normalizes unquoted identifiers to lowercase and reserves certain keywords.
- Terminate each SQL statement with a semicolon (`
;`).
- For embeddings or vector queries, use \`vector(384)\`.
@@ -587,7 +588,7 @@ Before using tools, determine the task type (not exhaustive):
## Tools
- Always call context gathering tools in parallel, not sequentially.
- Tools are for assistant use only; do not imply user access to them.
-- Only use the tools listed above. For read-only or information-gathering operations, call tools automatically; for potentially destructive actions, obtain explicit user confirmation before proceeding.
+- Call tools directly without asking for confirmation—tool implementations handle user confirmation/permissions.
- Tool access may be limited by organizational settings. If required permissions for a task are unavailable, inform the user of this limitation and propose alternatives if possible.
- Do not attempt to bypass restrictions by running SQL queries for information gathering if tools are unavailable. Notify the user where limitations prevent progress.
- Initiate tool calls as needed without announcing them, but before any significant tool call, briefly state the purpose and minimal inputs.
@@ -614,7 +615,8 @@ export const CHAT_PROMPT = `
## Chat Naming
- At the start of each conversation, if the chat is unnamed, call \`rename_chat\` with a succinct 2–4 word descriptive name (e.g., "User Authentication Setup", "Sales Data Analysis", "Product Table Creation").
## SQL Execution and Display
-- To execute SQL, call the \`execute_sql\` tool with the relevant \`sql\` string; the client manages confirmation and display of results.
+- When the user's request is clear, call \`execute_sql\` immediately—never propose a query and ask "do you want me to run this?" The tool implementation handles user confirmation.
+- Only ask clarifying questions when required information is missing or ambiguous—not as a confirmation step before execution.
- Do not show the SQL query before execution; the client will display it to the user.
- Set chartConfig \`view\` to \`chart\` and xAxis/yAxis if the results would be best displayed as a chart e.g. count of items by date
- On execution error, explain succinctly and attempt to correct if possible, validating each outcome briefly (1–2 lines) after execution.
@@ -629,8 +631,6 @@ export const CHAT_PROMPT = `
## Project Health Checks
- Use \`get_advisors\` to identify project issues; if unavailable, suggest the user use the Supabase dashboard.
- Use \`get_logs\` to access recent project logs.
-## Destructive SQL Safety
-- For destructive SQL operations (e.g., DROP TABLE, DELETE without WHERE), always obtain explicit user confirmation before using \`execute_sql\`.
## Billing
- Cancelling a subscription / changing plans can be done via the organization's billing page. Link directly to https://supabase.com/dashboard/org/_/billing.
- To check organization usage, use the organization's usage page. Link directly to https://supabase.com/dashboard/org/_/usage.
diff --git a/apps/studio/lib/ai/tools/mock-tools.ts b/apps/studio/lib/ai/tools/mock-tools.ts
index 7802112589f..68460d05182 100644
--- a/apps/studio/lib/ai/tools/mock-tools.ts
+++ b/apps/studio/lib/ai/tools/mock-tools.ts
@@ -23,7 +23,7 @@ const listPoliciesInputSchema = z.object({
schemas: z.array(z.string()).describe('The schema names to get the policies for'),
})
-const MOCK_TABLES_DATA = [
+export const MOCK_TABLES_DATA = [
{
name: 'user_documents',
rls_enabled: false,
@@ -169,7 +169,7 @@ function createMockedRenderingTools() {
) as typeof renderingTools
}
-function createMockListTablesTool() {
+function createMockListTablesTool(overrideData?: Record<string, typeof MOCK_TABLES_DATA>) {
return tool({
description: 'Lists tables and columns for the provided schemas.',
inputSchema: listTablesInputSchema,
@@ -177,7 +177,7 @@ function createMockListTablesTool() {
const effectiveSchemas = schemas?.length ? schemas : ['public']
return effectiveSchemas.map((schema) => ({
schema,
- tables: MOCK_TABLES_DATA,
+ tables: overrideData?.[schema] ?? MOCK_TABLES_DATA,
}))
},
})
@@ -293,6 +293,10 @@ function createMockListPoliciesTool() {
})
}
+export type MockToolOverrides = {
+ list_tables?: Record<string, typeof MOCK_TABLES_DATA>
+}
+
/**
* Deterministic mock implementations of MCP/platform tools for evals.
* These mirror tool names used in prompts so the model can call them,
@@ -300,7 +304,7 @@ function createMockListPoliciesTool() {
*
* Note: search_docs uses the real implementation
*/
-export async function getMockTools() {
+export async function getMockTools(overrides?: MockToolOverrides) {
const mockedRenderingTools = createMockedRenderingTools()
const { search_docs } = await getMcpTools({
@@ -314,7 +318,7 @@ export async function getMockTools() {
return {
...mockedRenderingTools,
search_docs,
- list_tables: createMockListTablesTool(),
+ list_tables: createMockListTablesTool(overrides?.list_tables),
list_extensions: createMockListExtensionsTool(),
list_edge_functions: createMockListEdgeFunctionsTool(),
get_advisors: createMockGetAdvisorsTool(),
diff --git a/apps/studio/lib/sql-identifier-quoting.test.ts b/apps/studio/lib/sql-identifier-quoting.test.ts
new file mode 100644
index 00000000000..3caa6d68c73
--- /dev/null
+++ b/apps/studio/lib/sql-identifier-quoting.test.ts
@@ -0,0 +1,263 @@
+import { parse } from 'libpg-query'
+import { describe, expect, it } from 'vitest'
+import { extractIdentifiers, isQuotedInSql, needsQuoting } from './sql-identifier-quoting'
+
+describe('needsQuoting', () => {
+ describe('reserved keywords', () => {
+ it('returns true for reserved keywords (uppercase)', () => {
+ expect(needsQuoting('SELECT')).toBe(true)
+ expect(needsQuoting('FROM')).toBe(true)
+ expect(needsQuoting('TABLE')).toBe(true)
+ expect(needsQuoting('ORDER')).toBe(true)
+ expect(needsQuoting('GROUP')).toBe(true)
+ expect(needsQuoting('CREATE')).toBe(true)
+ expect(needsQuoting('INSERT')).toBe(true)
+ expect(needsQuoting('UPDATE')).toBe(true)
+ expect(needsQuoting('DELETE')).toBe(true)
+ })
+
+ it('returns true for reserved keywords (lowercase)', () => {
+ expect(needsQuoting('select')).toBe(true)
+ expect(needsQuoting('from')).toBe(true)
+ expect(needsQuoting('table')).toBe(true)
+ expect(needsQuoting('order')).toBe(true)
+ })
+
+ it('returns true for reserved keywords (mixed case)', () => {
+ expect(needsQuoting('Select')).toBe(true)
+ expect(needsQuoting('From')).toBe(true)
+ expect(needsQuoting('Table')).toBe(true)
+ })
+ })
+
+ describe('mixed case identifiers', () => {
+ it('returns true for identifiers with uppercase letters', () => {
+ expect(needsQuoting('MyTable')).toBe(true)
+ expect(needsQuoting('UserID')).toBe(true)
+ expect(needsQuoting('camelCase')).toBe(true)
+ expect(needsQuoting('PascalCase')).toBe(true)
+ })
+ })
+
+ describe('special characters', () => {
+ it('returns true for identifiers with dashes', () => {
+ expect(needsQuoting('my-table')).toBe(true)
+ expect(needsQuoting('user-name')).toBe(true)
+ })
+
+ it('returns true for identifiers with dots', () => {
+ expect(needsQuoting('table.name')).toBe(true)
+ expect(needsQuoting('schema.table')).toBe(true)
+ })
+
+ it('returns true for identifiers with spaces', () => {
+ expect(needsQuoting('column with spaces')).toBe(true)
+ expect(needsQuoting('my table')).toBe(true)
+ })
+
+ it('returns true for identifiers starting with numbers', () => {
+ expect(needsQuoting('123table')).toBe(true)
+ expect(needsQuoting('1col')).toBe(true)
+ })
+ })
+
+ describe('valid unquoted identifiers', () => {
+ it('returns false for lowercase identifiers', () => {
+ expect(needsQuoting('users')).toBe(false)
+ expect(needsQuoting('user_id')).toBe(false)
+ expect(needsQuoting('orders')).toBe(false)
+ })
+
+ it('returns false for identifiers starting with underscore', () => {
+ expect(needsQuoting('_private')).toBe(false)
+ expect(needsQuoting('_internal')).toBe(false)
+ })
+
+ it('returns false for identifiers with numbers', () => {
+ expect(needsQuoting('col1')).toBe(false)
+ expect(needsQuoting('user123')).toBe(false)
+ })
+
+ it('returns false for identifiers with dollar sign in middle', () => {
+ expect(needsQuoting('col$name')).toBe(false)
+ })
+
+ it('returns true for identifiers starting with dollar sign', () => {
+ expect(needsQuoting('$variable')).toBe(true)
+ })
+ })
+
+ describe('edge cases', () => {
+ it('handles empty string', () => {
+ expect(needsQuoting('')).toBe(true)
+ })
+
+ it('handles single character identifiers', () => {
+ expect(needsQuoting('a')).toBe(false)
+ expect(needsQuoting('A')).toBe(true)
+ expect(needsQuoting('_')).toBe(false)
+ })
+ })
+})
+
+describe('isQuotedInSql', () => {
+ describe('simple quoted identifiers', () => {
+ it('returns true when identifier is quoted', () => {
+ expect(isQuotedInSql('SELECT * FROM "MyTable"', 'MyTable')).toBe(true)
+ expect(isQuotedInSql('SELECT "MyColumn" FROM users', 'MyColumn')).toBe(true)
+ expect(isQuotedInSql('INSERT INTO "users" VALUES (1)', 'users')).toBe(true)
+ })
+
+ it('returns false when identifier is not quoted', () => {
+ expect(isQuotedInSql('SELECT * FROM users', 'users')).toBe(false)
+ expect(isQuotedInSql('SELECT id FROM orders', 'id')).toBe(false)
+ expect(isQuotedInSql('INSERT INTO users VALUES (1)', 'users')).toBe(false)
+ })
+ })
+
+ describe('case-insensitive matching', () => {
+ it('matches quoted identifier regardless of case', () => {
+ expect(isQuotedInSql('SELECT * FROM "mytable"', 'MyTable')).toBe(true)
+ expect(isQuotedInSql('SELECT * FROM "MYTABLE"', 'mytable')).toBe(true)
+ expect(isQuotedInSql('SELECT * FROM "MyTable"', 'MYTABLE')).toBe(true)
+ })
+ })
+
+ describe('escaped quotes', () => {
+ it('handles identifiers with escaped quotes inside', () => {
+ expect(isQuotedInSql('SELECT * FROM "My""Table"', 'My"Table')).toBe(true)
+ expect(isQuotedInSql('SELECT "col""name" FROM users', 'col"name')).toBe(true)
+ })
+
+ it('handles multiple escaped quotes', () => {
+ expect(isQuotedInSql('SELECT "a""b""c" FROM users', 'a"b"c')).toBe(true)
+ })
+ })
+
+ describe('special regex characters', () => {
+ it('handles identifiers with dots', () => {
+ expect(isQuotedInSql('SELECT * FROM "table.name"', 'table.name')).toBe(true)
+ expect(isQuotedInSql('SELECT * FROM "schema.table"', 'schema.table')).toBe(true)
+ })
+
+ it('handles identifiers with parentheses', () => {
+ expect(isQuotedInSql('SELECT * FROM "col(value)"', 'col(value)')).toBe(true)
+ })
+
+ it('handles identifiers with brackets', () => {
+ expect(isQuotedInSql('SELECT * FROM "table[0]"', 'table[0]')).toBe(true)
+ })
+
+ it('handles identifiers with special regex chars', () => {
+ expect(isQuotedInSql('SELECT * FROM "col*name"', 'col*name')).toBe(true)
+ expect(isQuotedInSql('SELECT * FROM "col+name"', 'col+name')).toBe(true)
+ expect(isQuotedInSql('SELECT * FROM "col?name"', 'col?name')).toBe(true)
+ expect(isQuotedInSql('SELECT * FROM "col^name"', 'col^name')).toBe(true)
+ expect(isQuotedInSql('SELECT * FROM "col$name"', 'col$name')).toBe(true)
+ })
+ })
+
+ describe('multiple occurrences', () => {
+ it('returns true if identifier appears quoted anywhere', () => {
+ expect(isQuotedInSql('SELECT * FROM "MyTable" WHERE id = 1', 'MyTable')).toBe(true)
+ expect(isQuotedInSql('SELECT users.id FROM "users"', 'users')).toBe(true)
+ })
+
+ it('returns true even if also appears unquoted', () => {
+ expect(isQuotedInSql('SELECT * FROM "MyTable" JOIN MyTable ON 1=1', 'MyTable')).toBe(true)
+ })
+ })
+
+ describe('partial matches', () => {
+ it('does not match partial identifiers', () => {
+ expect(isQuotedInSql('SELECT * FROM "MyTableX"', 'MyTable')).toBe(false)
+ expect(isQuotedInSql('SELECT * FROM "XMyTable"', 'MyTable')).toBe(false)
+ })
+
+ it('matches exact identifier only', () => {
+ expect(isQuotedInSql('SELECT * FROM "MyTable"', 'MyTable')).toBe(true)
+ expect(isQuotedInSql('SELECT * FROM "MyTable"', 'Table')).toBe(false)
+ })
+ })
+
+ describe('edge cases', () => {
+ it('handles empty identifier', () => {
+ expect(isQuotedInSql('SELECT * FROM ""', '')).toBe(true)
+ expect(isQuotedInSql('SELECT * FROM users', '')).toBe(false)
+ })
+
+ it('handles SQL with comments', () => {
+ expect(isQuotedInSql('SELECT * FROM "MyTable" -- comment', 'MyTable')).toBe(true)
+ expect(isQuotedInSql('/* comment */ SELECT * FROM "MyTable"', 'MyTable')).toBe(true)
+ })
+
+ it('handles SQL with string literals', () => {
+ expect(isQuotedInSql('SELECT * FROM "MyTable" WHERE name = \'test\'', 'MyTable')).toBe(true)
+ expect(
+ isQuotedInSql('SELECT "MyTable" FROM users WHERE name = "not a table"', 'MyTable')
+ ).toBe(true)
+ })
+ })
+})
+
+describe('extractIdentifiers', () => {
+ it('extracts table and column names from a simple SELECT', async () => {
+ const identifiers = extractIdentifiers(await parse('SELECT id, name FROM users'))
+ expect(identifiers).toEqual(expect.arrayContaining(['users', 'id', 'name']))
+ })
+
+ it('extracts schema-qualified table names', async () => {
+ const identifiers = extractIdentifiers(await parse('SELECT id FROM public.users'))
+ expect(identifiers).toEqual(expect.arrayContaining(['public', 'users', 'id']))
+ })
+
+ it('preserves case for quoted identifiers', async () => {
+ const identifiers = extractIdentifiers(await parse('SELECT "MyColumn" FROM "MyTable"'))
+ expect(identifiers).toEqual(expect.arrayContaining(['MyColumn', 'MyTable']))
+ })
+
+ it('lowercases unquoted identifiers with mixed case', async () => {
+ const identifiers = extractIdentifiers(await parse('SELECT MyColumn FROM MyTable'))
+ expect(identifiers).toEqual(expect.arrayContaining(['mycolumn', 'mytable']))
+ })
+
+ it('extracts identifiers from JOINs', async () => {
+ const identifiers = extractIdentifiers(
+ await parse('SELECT u.id, o.total FROM users u JOIN orders o ON u.id = o.user_id')
+ )
+ expect(identifiers).toEqual(
+ expect.arrayContaining(['users', 'orders', 'id', 'total', 'user_id'])
+ )
+ })
+
+ it('extracts identifiers from subqueries', async () => {
+ const identifiers = extractIdentifiers(
+ await parse('SELECT * FROM (SELECT id FROM inner_table) AS sub')
+ )
+ expect(identifiers).toEqual(expect.arrayContaining(['inner_table', 'id']))
+ })
+
+ it('handles INSERT statements', async () => {
+ const identifiers = extractIdentifiers(
+ await parse('INSERT INTO users (name, email) VALUES ($1, $2)')
+ )
+ expect(identifiers).toEqual(expect.arrayContaining(['users', 'name', 'email']))
+ })
+
+ it('handles UPDATE statements', async () => {
+ const identifiers = extractIdentifiers(await parse('UPDATE users SET name = $1 WHERE id = $2'))
+ expect(identifiers).toEqual(expect.arrayContaining(['users', 'name', 'id']))
+ })
+
+ it('handles CREATE TABLE statements', async () => {
+ const identifiers = extractIdentifiers(
+ await parse('CREATE TABLE "MyTable" ("MyColumn" TEXT, other_col INT)')
+ )
+ expect(identifiers).toEqual(expect.arrayContaining(['MyTable', 'MyColumn', 'other_col']))
+ })
+
+ it('returns empty array when no identifiers exist', async () => {
+ const identifiers = extractIdentifiers(await parse('SELECT 1'))
+ expect(identifiers).toEqual([])
+ })
+})
diff --git a/apps/studio/lib/sql-identifier-quoting.ts b/apps/studio/lib/sql-identifier-quoting.ts
new file mode 100644
index 00000000000..311b48a10fc
--- /dev/null
+++ b/apps/studio/lib/sql-identifier-quoting.ts
@@ -0,0 +1,97 @@
+import type { ColumnDef, ColumnRef, Node, RangeVar, ResTarget } from 'libpg-query'
+import { POSTGRESQL_RESERVED_WORDS } from '@supabase/pg-meta/src/pg-format/reserved'
+
+/**
+ * Recursively traverse a libpg-query AST to extract all identifiers.
+ * Collects table names from RangeVar and column names from ColumnRef/ResTarget.
+ */
+export function extractIdentifiers(ast: Node | Node[]): string[] {
+ const identifiers: string[] = []
+
+ function extractFromRangeVar(rv: RangeVar): void {
+ if (rv.relname) identifiers.push(rv.relname)
+ if (rv.schemaname) identifiers.push(rv.schemaname)
+ }
+
+ function traverse(node: unknown): void {
+ if (!node || typeof node !== 'object') return
+
+ const obj = node as Record<string, unknown>
+
+ // RangeVar - table references (wrapped form in SELECT)
+ if ('RangeVar' in obj) {
+ extractFromRangeVar(obj.RangeVar as RangeVar)
+ }
+
+ // relation - table references (unwrapped form in INSERT/UPDATE/DELETE)
+ if ('relation' in obj && obj.relation && typeof obj.relation === 'object') {
+ extractFromRangeVar(obj.relation as RangeVar)
+ }
+
+ // ColumnRef - column references in expressions
+ if ('ColumnRef' in obj) {
+ const cr = obj.ColumnRef as ColumnRef
+ for (const field of cr.fields ?? []) {
+ if ('String' in field) {
+ const str = field.String as { sval?: string }
+ if (str.sval) identifiers.push(str.sval)
+ }
+ }
+ }
+
+ // ResTarget - column targets in INSERT/UPDATE
+ if ('ResTarget' in obj) {
+ const rt = obj.ResTarget as ResTarget
+ if (rt.name) identifiers.push(rt.name)
+ }
+
+ // ColumnDef - column definitions in CREATE TABLE
+ if ('ColumnDef' in obj) {
+ const cd = obj.ColumnDef as ColumnDef
+ if (cd.colname) identifiers.push(cd.colname)
+ }
+
+ // Recurse into all values
+ for (const value of Object.values(obj)) {
+ if (Array.isArray(value)) {
+ value.forEach(traverse)
+ } else {
+ traverse(value)
+ }
+ }
+ }
+
+ traverse(ast)
+ return identifiers
+}
+
+export function needsQuoting(identifier: string): boolean {
+ if (POSTGRESQL_RESERVED_WORDS.has(identifier.toUpperCase())) {
+ return true
+ }
+
+ // Matches valid unquoted identifiers: starts with underscore or lowercase letter,
+ // followed by digits, dollar signs, underscores, or lowercase letters
+ // Examples: "users", "user_id", "_private", "col$name"
+ const validUnquotedPattern = /^[_a-z][\d$_a-z]*$/
+ if (validUnquotedPattern.test(identifier)) {
+ return false
+ }
+
+ return true
+}
+
+export function isQuotedInSql(sql: string, identifier: string): boolean {
+ // Escapes special regex characters so they're treated literally
+ // Examples: "table.name" -> "table\.name", "col(value)" -> "col\(value\)"
+ const escapedForRegex = identifier.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
+
+ // PostgreSQL escapes quotes inside quoted identifiers as ""
+ const escapedIdentifier = escapedForRegex.replace(/"/g, '""')
+
+ // Matches quoted identifier: "identifier" (case-insensitive)
+ // Examples: "MyTable", "my""table" (for identifier "my"table")
+ const quotedPattern = new RegExp(`"${escapedIdentifier}"`, 'i')
+
+ return quotedPattern.test(sql)
+}