The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
fix(assistant): sanitize backslash-escaped apostrophes in SQL (#43728)
Matt Rossman25036af80e47
diff --git a/apps/studio/evals/dataset.ts b/apps/studio/evals/dataset.tsindex 10652dd6e9b..65cc8081ad5 100644--- a/apps/studio/evals/dataset.ts+++ b/apps/studio/evals/dataset.ts@@ -127,4 +127,30 @@ export const dataset: AssistantEvalCase[] = ['Verifies template URLs like https://<project-ref>.supabase.co/auth/v1/callback are excluded from URL validity scoring',},},+ {+ input: {+ prompt:+ "Execute this SQL exactly as written:\nINSERT INTO messages (content) VALUES ('We\\'ll be in touch soon'), ('Don\\'t hesitate to ask'), ('It\\'s a great day');",+ mockTables: {+ public: [+ {+ name: 'messages',+ rls_enabled: false,+ columns: [+ { name: 'id', data_type: 'bigint' },+ { name: 'content', data_type: 'text' },+ ],+ },+ ],+ },+ },+ expected: {+ requiredTools: ['execute_sql'],+ },+ metadata: {+ category: ['sql_generation'],+ description:+ "Adversarial check to verify Assistant recovers from MySQL-style backslash escapes (\\') and converts them to PostgreSQL double-apostrophes ('') before execution",+ },+ },]diff --git a/apps/studio/lib/ai/tools/rendering-tools.ts b/apps/studio/lib/ai/tools/rendering-tools.tsindex 4f5e9704ff4..b9036cc336f 100644--- a/apps/studio/lib/ai/tools/rendering-tools.ts+++ b/apps/studio/lib/ai/tools/rendering-tools.ts@@ -1,11 +1,14 @@import { tool } from 'ai'+import { fixSqlBackslashEscapes } from 'lib/ai/util'import { z } from 'zod'export const getRenderingTools = () => ({execute_sql: tool({description: 'Asks the user to execute a SQL statement and return the results',inputSchema: z.object({- sql: z.string().describe('The SQL statement to execute.'),+ // Transform at parse time so the corrected SQL is what gets stored in+ // toolCall.input — ensuring evals and logs reflect what actually runs.+ sql: z.string().describe('The SQL statement to execute.').transform(fixSqlBackslashEscapes),label: z.string().describe('A short 2-4 word label for the SQL statement.'),chartConfig: z.object({diff --git a/apps/studio/lib/ai/util.test.ts b/apps/studio/lib/ai/util.test.tsindex 99cd00205da..a879ea42518 100644--- a/apps/studio/lib/ai/util.test.ts+++ b/apps/studio/lib/ai/util.test.ts@@ -1,5 +1,46 @@import { describe, it, expect } from 'vitest'-import { selectWeightedKey } from './util'+import { fixSqlBackslashEscapes, selectWeightedKey } from './util'++describe('fixSqlBackslashEscapes', () => {+ it('converts backslash-apostrophe to double-apostrophe', () => {+ expect(fixSqlBackslashEscapes("INSERT INTO t (c) VALUES ('We\\'ll be in touch')")).toBe(+ "INSERT INTO t (c) VALUES ('We''ll be in touch')"+ )+ })++ it('handles multiple backslash-apostrophes in one string', () => {+ expect(fixSqlBackslashEscapes("VALUES ('Don\\'t stop, it\\'s fine')")).toBe(+ "VALUES ('Don''t stop, it''s fine')"+ )+ })++ it('handles multiple string literals in one query', () => {+ expect(fixSqlBackslashEscapes("INSERT INTO t (a, b) VALUES ('We\\'ll', 'It\\'s ready')")).toBe(+ "INSERT INTO t (a, b) VALUES ('We''ll', 'It''s ready')"+ )+ })++ it('leaves already-correct double apostrophes unchanged', () => {+ const sql = "INSERT INTO t (c) VALUES ('We''ll be in touch')"+ expect(fixSqlBackslashEscapes(sql)).toBe(sql)+ })++ it('leaves SQL with no apostrophes unchanged', () => {+ const sql = 'SELECT 1 + 1'+ expect(fixSqlBackslashEscapes(sql)).toBe(sql)+ })++ it('leaves backslash-apostrophe inside dollar-quoted strings unchanged', () => {+ const sql = "SELECT $$We\\'ll do it$$ AS greeting"+ expect(fixSqlBackslashEscapes(sql)).toBe(sql)+ })++ it('fixes regular strings but leaves dollar-quoted strings unchanged', () => {+ expect(+ fixSqlBackslashEscapes("INSERT INTO t (a, b) VALUES ('We\\'ll', $$Don\\'t escape$$)")+ ).toBe("INSERT INTO t (a, b) VALUES ('We''ll', $$Don\\'t escape$$)")+ })+})describe('selectWeightedKey', () => {it('should return a valid key from the weights object', async () => {diff --git a/apps/studio/lib/ai/util.ts b/apps/studio/lib/ai/util.tsindex 462d95d12be..953f1e58227 100644--- a/apps/studio/lib/ai/util.ts+++ b/apps/studio/lib/ai/util.ts@@ -1,3 +1,14 @@+/**+ * LLMs sometimes emit MySQL-style `\'` escapes in SQL. PostgreSQL doesn't+ * treat backslash as an escape character, so replace `\'` → `''`.+ * Dollar-quoted strings (e.g. `$$...$$`) are left untouched.+ */+export function fixSqlBackslashEscapes(sql: string): string {+ return sql.replace(/\$([^$]*)\$[\s\S]*?\$\1\$|\\'/g, (match, dollarTag) =>+ dollarTag !== undefined ? match : "''"+ )+}+/*** Selects a key from weighted choices using consistent hashing* on an input string.