Skip to content

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

feat(sql-editor): debug sql errors using ai

Greg Richardson97fa480d4595
diff --git a/studio/components/interfaces/SQLEditor/SQLEditor.tsx b/studio/components/interfaces/SQLEditor/SQLEditor.tsx
index 3ef74a0d503..6863ccaa952 100644
--- a/studio/components/interfaces/SQLEditor/SQLEditor.tsx
+++ b/studio/components/interfaces/SQLEditor/SQLEditor.tsx
@@ -6,7 +6,16 @@ import { m } from 'framer-motion'
import { useLocalStorage, useStore } from 'hooks'
import useLatest from 'hooks/misc/useLatest'
import dynamic from 'next/dynamic'
-import { useCallback, useEffect, useRef, useState } from 'react'
+import {
+ Dispatch,
+ SetStateAction,
+ createContext,
+ useCallback,
+ useContext,
+ useEffect,
+ useRef,
+ useState,
+} from 'react'
import Split from 'react-split'
import { format } from 'sql-formatter'
import { getSqlEditorStateSnapshot, useSqlEditorStateSnapshot } from 'state/sql-editor'
@@ -41,6 +50,27 @@ type ContentDiff = {
modified: string
}
+type SQLEditorContextValues = {
+ aiInput: string
+ setAiInput: Dispatch<SetStateAction<string>>
+ sqlDiff?: ContentDiff
+ setSqlDiff: Dispatch<SetStateAction<ContentDiff | undefined>>
+ debugSolution?: string
+ setDebugSolution: Dispatch<SetStateAction<string | undefined>>
+}
+
+const SQLEditorContext = createContext<SQLEditorContextValues | undefined>(undefined)
+
+export function useSqlEditor() {
+ const values = useContext(SQLEditorContext)
+
+ if (!values) {
+ throw new Error('No SQL editor context. Are you using useSqlEditor() outside of SQLEditor?')
+ }
+
+ return values
+}
+
const SQLEditor = () => {
const { ui } = useStore()
const { ref, id } = useParams()
@@ -48,6 +78,7 @@ const SQLEditor = () => {
const snap = useSqlEditorStateSnapshot()
const { mutateAsync: editSql, isLoading: isEditSqlLoading } = useSqlEditMutation()
const [aiInput, setAiInput] = useState('')
+ const [debugSolution, setDebugSolution] = useState<string>()
const [sqlDiff, setSqlDiff] = useState<ContentDiff>()
const inputRef = useRef<HTMLInputElement>(null)
@@ -130,6 +161,7 @@ const SQLEditor = () => {
])
setAiInput('')
+ setDebugSolution(undefined)
setSqlDiff(undefined)
setTimeout(() => {
inputRef.current?.focus()
@@ -138,6 +170,7 @@ const SQLEditor = () => {
}, [sqlDiff, id])
const discardAiHandler = useCallback(() => {
+ setDebugSolution(undefined)
setSqlDiff(undefined)
setTimeout(() => {
inputRef.current?.focus()
@@ -166,257 +199,274 @@ const SQLEditor = () => {
}, [isDiffOpen, acceptAiHandler, discardAiHandler])
return (
- <div className="flex h-full flex-col">
- {!isEditSqlLoading ? (
- <m.div
- key="ask-ai-input"
- layoutId="ask-ai-input"
- initial={{
- scaleY: 1,
- y: 50,
- borderRadius: 0,
- }}
- animate={{
- scaleY: 1,
- y: 0,
- borderRadius: 0,
- }}
- className="w-full flex justify-center z-[1000] mt-0.5 bg-brand-400"
- >
- <Input
- autoFocus
- size="xlarge"
- value={aiInput}
- onChange={(e) => setAiInput(e.currentTarget.value)}
- disabled={isDiffOpen}
- inputRef={inputRef}
- icon={
- <m.div
- key="ask-ai-input-icon"
- layoutId="ask-ai-input-icon"
- className="ml-1"
- initial={{
- rotate: 0,
- }}
- animate={{
- rotate: 0,
- }}
- >
- <AiIcon className="w-4 h-4" />
- </m.div>
- }
- inputClassName="w-full !border-brand-900 border-none py-4 focus:!ring-0 placeholder:text-scale-900"
- iconContainerClassName="transition text-scale-800 text-brand-900"
- placeholder="Ask Supabase AI to modify your query"
- className="w-full"
- actions={
- <div className="flex flex-row items-center gap-2 space-x-1 mr-6">
- {isDiffOpen ? (
- <>
- <Button
- type="primary"
- size="tiny"
- icon={<IconCheck />}
- iconRight={
- <div className="opacity-30">
- <IconCornerDownLeft size={12} strokeWidth={1.5} />
- </div>
- }
- onClick={acceptAiHandler}
- >
- Accept
- </Button>
- <Button
- type="alternative"
- size="tiny"
- icon={<IconX />}
- iconRight={<span className="opacity-30">ESC</span>}
- onClick={discardAiHandler}
- >
- Discard
- </Button>
- </>
- ) : (
- <IconCornerDownLeft size={16} strokeWidth={1.5} />
- )}
- </div>
- }
- onKeyPress={async (e) => {
- if (e.key === 'Enter') {
- try {
- const prompt = e.currentTarget.value
-
- console.log({ prompt })
+ <SQLEditorContext.Provider
+ value={{
+ aiInput,
+ setAiInput,
+ sqlDiff,
+ setSqlDiff,
+ debugSolution,
+ setDebugSolution,
+ }}
+ >
+ <div className="flex h-full flex-col">
+ {!isEditSqlLoading ? (
+ <m.div
+ key="ask-ai-input"
+ layoutId="ask-ai-input"
+ initial={{
+ scaleY: 1,
+ y: 50,
+ borderRadius: 0,
+ }}
+ animate={{
+ scaleY: 1,
+ y: 0,
+ borderRadius: 0,
+ }}
+ className="w-full flex justify-center z-[1000] mt-0.5 bg-brand-400"
+ >
+ <Input
+ autoFocus
+ size="xlarge"
+ value={aiInput}
+ onChange={(e) => setAiInput(e.currentTarget.value)}
+ disabled={isDiffOpen}
+ inputRef={inputRef}
+ icon={
+ <div className="h-full flex flex-row gap-3 items-center overflow-y-auto">
+ <m.div
+ key="ask-ai-input-icon"
+ layoutId="ask-ai-input-icon"
+ className="ml-1"
+ initial={{
+ rotate: 0,
+ }}
+ animate={{
+ rotate: 0,
+ }}
+ >
+ <AiIcon className="w-4 h-4" />
+ </m.div>
+
+ {debugSolution && (
+ <div className="w-full mr-[16.5rem] text-sm text-white">{debugSolution}</div>
+ )}
+ </div>
+ }
+ inputClassName="w-full !border-brand-900 border-none py-4 focus:!ring-0 placeholder:text-scale-900"
+ iconContainerClassName="transition text-scale-800 text-brand-900"
+ placeholder={!debugSolution ? 'Ask Supabase AI to modify your query' : ''}
+ className="w-full"
+ actions={
+ <div className="flex flex-row items-center gap-2 space-x-1 mr-6">
+ {isDiffOpen ? (
+ <>
+ <Button
+ type="primary"
+ size="tiny"
+ icon={<IconCheck />}
+ iconRight={
+ <div className="opacity-30">
+ <IconCornerDownLeft size={12} strokeWidth={1.5} />
+ </div>
+ }
+ onClick={acceptAiHandler}
+ >
+ Accept
+ </Button>
+ <Button
+ type="alternative"
+ size="tiny"
+ icon={<IconX />}
+ iconRight={<span className="opacity-30">ESC</span>}
+ onClick={discardAiHandler}
+ >
+ Discard
+ </Button>
+ </>
+ ) : (
+ <IconCornerDownLeft size={16} strokeWidth={1.5} />
+ )}
+ </div>
+ }
+ onKeyPress={async (e) => {
+ if (e.key === 'Enter') {
+ try {
+ const prompt = e.currentTarget.value
- if (!prompt) {
- return
- }
+ if (!prompt) {
+ return
+ }
- const sql = editorRef.current?.getValue()
+ const sql = editorRef.current?.getValue()
- if (!sql) {
- return
- }
+ if (!sql) {
+ return
+ }
- const { sql: modifiedSql } = await editSql({
- prompt,
- sql: sql.replace(sqlAiDisclaimerComment, '').trim(),
- })
-
- const formattedSql =
- sqlAiDisclaimerComment +
- '\n\n' +
- format(modifiedSql, {
- language: 'postgresql',
- keywordCase: 'lower',
+ const { sql: modifiedSql } = await editSql({
+ prompt,
+ sql: sql.replace(sqlAiDisclaimerComment, '').trim(),
})
- // TODO: show error
- if (formattedSql.trim() === sql.trim()) {
- return
- }
-
- setSqlDiff({
- original: sql,
- modified: formattedSql,
- })
- } catch (error: unknown) {
- if (
- error &&
- typeof error === 'object' &&
- 'message' in error &&
- typeof error.message === 'string'
- ) {
- ui.setNotification({
- category: 'error',
- message: error.message,
+ const formattedSql =
+ sqlAiDisclaimerComment +
+ '\n\n' +
+ format(modifiedSql, {
+ language: 'postgresql',
+ keywordCase: 'lower',
+ })
+
+ // TODO: show error
+ if (formattedSql.trim() === sql.trim()) {
+ return
+ }
+
+ setSqlDiff({
+ original: sql,
+ modified: formattedSql,
})
+ } catch (error: unknown) {
+ if (
+ error &&
+ typeof error === 'object' &&
+ 'message' in error &&
+ typeof error.message === 'string'
+ ) {
+ ui.setNotification({
+ category: 'error',
+ message: error.message,
+ })
+ }
}
}
- }
- }}
- />
- </m.div>
- ) : (
- <m.div
- key="ask-ai-loading"
- layoutId="ask-ai-input"
- className="w-fit p-5 border border-brand-900 text-brand-900 self-center"
- initial={{
- borderRadius: 50,
- }}
- animate={{
- borderRadius: 50,
- }}
- transition={{
- type: 'spring',
- mass: 0.1,
- stiffness: 200,
- damping: 30,
- }}
- >
+ }}
+ />
+ </m.div>
+ ) : (
<m.div
- key="ask-ai-loading-icon"
- layoutId="ask-ai-input-icon"
+ key="ask-ai-loading"
+ layoutId="ask-ai-input"
+ className="w-fit p-5 border border-brand-900 text-brand-900"
+ initial={{
+ borderRadius: 50,
+ }}
animate={{
- rotate: 360,
- transition: {
- delay: 0.2,
- ease: 'linear',
- duration: 2,
- repeat: Infinity,
- },
+ borderRadius: 50,
+ }}
+ transition={{
+ type: 'spring',
+ mass: 0.1,
+ stiffness: 200,
+ damping: 30,
}}
>
- <AiIcon className="w-4 h-4" />
+ <m.div
+ key="ask-ai-loading-icon"
+ layoutId="ask-ai-input-icon"
+ animate={{
+ rotate: 360,
+ transition: {
+ delay: 0.2,
+ ease: 'linear',
+ duration: 2,
+ repeat: Infinity,
+ },
+ }}
+ >
+ <AiIcon className="w-4 h-4" />
+ </m.div>
</m.div>
- </m.div>
- )}
- <Split
- style={{ height: '100%' }}
- direction="vertical"
- gutterSize={2}
- sizes={(splitSize ? splitSize : (snippet?.splitSizes as number[] | undefined)) ?? [50, 50]}
- minSize={minSize}
- snapOffset={snapOffset}
- expandToMin={true}
- collapsed={isUtilityPanelCollapsed ? 1 : undefined}
- onDragEnd={onDragEnd}
- >
- <m.div
- className="dark:border-dark flex-grow overflow-y-auto border-b"
- initial={{
- opacity: 0,
- filter: 'blur(10px)',
- }}
- animate={{
- opacity: 1,
- filter: 'blur(0px)',
- }}
- transition={{
- duration: 0.3,
- }}
+ )}
+ <Split
+ style={{ height: '100%' }}
+ direction="vertical"
+ gutterSize={2}
+ sizes={
+ (splitSize ? splitSize : (snippet?.splitSizes as number[] | undefined)) ?? [50, 50]
+ }
+ minSize={minSize}
+ snapOffset={snapOffset}
+ expandToMin={true}
+ collapsed={isUtilityPanelCollapsed ? 1 : undefined}
+ onDragEnd={onDragEnd}
>
- {isLoading ? (
- <div className="flex h-full w-full items-center justify-center">Loading...</div>
- ) : (
- <>
- {isDiffOpen && (
+ <m.div
+ className="dark:border-dark flex-grow overflow-y-auto border-b"
+ initial={{
+ opacity: 0,
+ filter: 'blur(10px)',
+ }}
+ animate={{
+ opacity: 1,
+ filter: 'blur(0px)',
+ }}
+ transition={{
+ duration: 0.3,
+ }}
+ >
+ {isLoading ? (
+ <div className="flex h-full w-full items-center justify-center">Loading...</div>
+ ) : (
+ <>
+ {isDiffOpen && (
+ <m.div
+ key="diff-editor"
+ className="w-full h-full"
+ initial={{
+ opacity: 0,
+ filter: 'blur(10px)',
+ }}
+ animate={{
+ opacity: 1,
+ filter: 'blur(0px)',
+ }}
+ >
+ <DiffEditor
+ theme="supabase"
+ language="pgsql"
+ original={sqlDiff.original}
+ modified={sqlDiff.modified}
+ options={{
+ fontSize: 13,
+ }}
+ />
+ </m.div>
+ )}
+
<m.div
- key="diff-editor"
- className="w-full h-full"
- initial={{
- opacity: 0,
- filter: 'blur(10px)',
- }}
- animate={{
- opacity: 1,
- filter: 'blur(0px)',
- }}
+ key="monaco-editor"
+ className={cn('w-full', 'h-full', isDiffOpen && 'invisible')}
>
- <DiffEditor
- theme="supabase"
- language="pgsql"
- original={sqlDiff.original}
- modified={sqlDiff.modified}
- options={{
- fontSize: 13,
- }}
+ <MonacoEditor
+ id={id}
+ editorRef={editorRef}
+ isExecuting={isExecuting}
+ autoFocus={false}
+ executeQuery={executeQuery}
+ // onOpenAiWidget={() => setIsAiWidgetOpen(true)}
+ // onCloseAiWidget={() => setIsAiWidgetOpen(false)}
/>
</m.div>
- )}
-
- <m.div
- key="monaco-editor"
- className={cn('w-full', 'h-full', isDiffOpen && 'invisible')}
- >
- <MonacoEditor
- id={id}
- editorRef={editorRef}
- isExecuting={isExecuting}
- autoFocus={false}
- executeQuery={executeQuery}
- // onOpenAiWidget={() => setIsAiWidgetOpen(true)}
- // onCloseAiWidget={() => setIsAiWidgetOpen(false)}
- />
- </m.div>
- </>
- )}
- </m.div>
- <div className="flex flex-col">
- {isLoading ? (
- <div className="flex h-full w-full items-center justify-center">Loading...</div>
- ) : (
- <UtilityPanel
- id={id}
- isExecuting={isExecuting}
- isDisabled={isDiffOpen}
- executeQuery={executeQuery}
- />
- )}
- </div>
- </Split>
- </div>
+ </>
+ )}
+ </m.div>
+ <div className="flex flex-col">
+ {isLoading ? (
+ <div className="flex h-full w-full items-center justify-center">Loading...</div>
+ ) : (
+ <UtilityPanel
+ id={id}
+ isExecuting={isExecuting}
+ isDisabled={isDiffOpen}
+ executeQuery={executeQuery}
+ />
+ )}
+ </div>
+ </Split>
+ </div>
+ </SQLEditorContext.Provider>
)
}
diff --git a/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityTabResults.tsx b/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityTabResults.tsx
index 5a48d7b80cb..4ab8093e9f9 100644
--- a/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityTabResults.tsx
+++ b/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityTabResults.tsx
@@ -1,4 +1,9 @@
+import { useSqlDebugMutation } from 'data/ai/sql-debug-mutation'
+import { format } from 'sql-formatter'
import { useSqlEditorStateSnapshot } from 'state/sql-editor'
+import { AiIcon, Button, IconLoader } from 'ui'
+import { useSqlEditor } from '../SQLEditor'
+import { sqlAiDisclaimerComment } from '../SQLEditor.constants'
import Results from './Results'
export type UtilityTabResultsProps = {
@@ -8,6 +13,9 @@ export type UtilityTabResultsProps = {
const UtilityTabResults = ({ id, isExecuting }: UtilityTabResultsProps) => {
const snap = useSqlEditorStateSnapshot()
+ const { mutateAsync: debugSql, isLoading: isDebugSqlLoading } = useSqlDebugMutation()
+ const { setDebugSolution, setAiInput, setSqlDiff, sqlDiff } = useSqlEditor()
+
const snippet = snap.snippets[id]
const result = snap.results[id]?.[0]
const isUtilityPanelCollapsed = (snippet?.splitSizes?.[1] ?? 0) === 0
@@ -23,7 +31,41 @@ const UtilityTabResults = ({ id, isExecuting }: UtilityTabResultsProps) => {
} else if (result?.error) {
return (
<div className="bg-table-header-light dark:bg-table-header-dark">
- <p className="m-0 border-0 px-6 py-4 font-mono">{result.error.message ?? result.error}</p>
+ <div className="flex flex-row justify-between items-center pr-8">
+ <p className="m-0 border-0 px-6 py-4 font-mono">{result.error.message ?? result.error}</p>
+ <Button
+ icon={
+ !isDebugSqlLoading ? (
+ <AiIcon className="w-3 h-3" />
+ ) : (
+ <IconLoader className="animate-spin" size={14} />
+ )
+ }
+ disabled={!!sqlDiff}
+ onClick={async () => {
+ const { solution, sql } = await debugSql({
+ sql: snippet.snippet.content.sql.replace(sqlAiDisclaimerComment, '').trim(),
+ errorMessage: result.error.message,
+ })
+
+ const formattedSql =
+ sqlAiDisclaimerComment +
+ '\n\n' +
+ format(sql, {
+ language: 'postgresql',
+ keywordCase: 'lower',
+ })
+ setAiInput('')
+ setDebugSolution(solution)
+ setSqlDiff({
+ original: snippet.snippet.content.sql,
+ modified: formattedSql,
+ })
+ }}
+ >
+ Debug using AI
+ </Button>
+ </div>
{(result.error.message ?? result.error)?.includes(
'canceling statement due to statement timeout'
) && (
diff --git a/studio/data/ai/sql-debug-mutation.ts b/studio/data/ai/sql-debug-mutation.ts
new file mode 100644
index 00000000000..92698c1b483
--- /dev/null
+++ b/studio/data/ai/sql-debug-mutation.ts
@@ -0,0 +1,44 @@
+import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'
+import { post } from 'lib/common/fetch'
+import { ResponseFailure } from 'types'
+import { aiKeys } from './keys'
+
+export type SqlDebugResponse = {
+ solution: string
+ sql: string
+}
+
+export type SqlDebugVariables = {
+ errorMessage: string
+ sql: string
+}
+
+export async function debugSql({ errorMessage, sql }: SqlDebugVariables) {
+ const response = (await post<SqlDebugResponse>('/api/ai/sql/debug', { errorMessage, sql })) as
+ | SqlDebugResponse
+ | ResponseFailure
+
+ if ('error' in response) {
+ throw response.error
+ }
+
+ return response
+}
+
+type SqlDebugData = Awaited<ReturnType<typeof debugSql>>
+
+export const useSqlDebugMutation = ({
+ onSuccess,
+ ...options
+}: Omit<UseMutationOptions<SqlDebugData, unknown, SqlDebugVariables>, 'mutationFn'> = {}) => {
+ const queryClient = useQueryClient()
+
+ return useMutation<SqlDebugData, unknown, SqlDebugVariables>((vars) => debugSql(vars), {
+ async onSuccess(data, variables, context) {
+ await queryClient.invalidateQueries(aiKeys.sql())
+
+ await onSuccess?.(data, variables, context)
+ },
+ ...options,
+ })
+}
diff --git a/studio/pages/api/ai/sql/debug.ts b/studio/pages/api/ai/sql/debug.ts
new file mode 100644
index 00000000000..004d1110168
--- /dev/null
+++ b/studio/pages/api/ai/sql/debug.ts
@@ -0,0 +1,149 @@
+import { SchemaBuilder } from '@serafin/schema-builder'
+import { stripIndent } from 'common-tags'
+import { NextRequest } from 'next/server'
+import type {
+ ChatCompletionRequestMessage,
+ CreateChatCompletionRequest,
+ CreateChatCompletionResponse,
+ ErrorResponse,
+} from 'openai'
+
+export const config = {
+ runtime: 'experimental-edge',
+}
+
+const openAiKey = process.env.OPENAI_KEY
+
+const debugSqlSchema = SchemaBuilder.emptySchema()
+ .addString('solution', {
+ description: 'The suggested solution for the error (as short and concise as possible).',
+ })
+ .addString('sql', {
+ description: 'The SQL rewritten to apply the solution. Includes all the original SQL.',
+ })
+
+type DebugSqlResult = typeof debugSqlSchema.T
+
+const completionFunctions = {
+ debugSql: {
+ name: 'debugSql',
+ description: 'Debugs a Postgres SQL error and modifies the SQL to fix it',
+ parameters: debugSqlSchema.schema,
+ },
+}
+
+export default async function handler(req: NextRequest) {
+ const { errorMessage, sql } = await req.json()
+
+ const model = 'gpt-3.5-turbo-0613'
+ const maxCompletionTokenCount = 2048
+
+ const completionMessages: ChatCompletionRequestMessage[] = [
+ {
+ role: 'user',
+ content: stripIndent`
+ Here is my current SQL:
+ ${sql}
+ `,
+ },
+ {
+ role: 'user',
+ content: stripIndent`
+ Here is the error I am getting:
+ ${errorMessage}
+ `,
+ },
+ ]
+
+ const completionOptions: CreateChatCompletionRequest = {
+ model,
+ messages: completionMessages,
+ max_tokens: maxCompletionTokenCount,
+ temperature: 0,
+ function_call: {
+ name: completionFunctions.debugSql.name,
+ },
+ functions: [completionFunctions.debugSql],
+ stream: false,
+ }
+
+ console.log({ sql, completionMessages })
+
+ const response = await fetch('https://api.openai.com/v1/chat/completions', {
+ headers: {
+ Authorization: `Bearer ${openAiKey}`,
+ 'Content-Type': 'application/json',
+ },
+ method: 'POST',
+ body: JSON.stringify(completionOptions),
+ })
+
+ if (!response.ok) {
+ const errorResponse: ErrorResponse = await response.json()
+ console.error(`AI SQL debugging failed: ${errorResponse.error.message}`)
+
+ return new Response(
+ JSON.stringify({
+ error: 'There was an unknown error debugging the SQL snippet. Please try again.',
+ }),
+ {
+ status: 500,
+ headers: {
+ 'content-type': 'application/json',
+ },
+ }
+ )
+ }
+
+ const completionResponse: CreateChatCompletionResponse = await response.json()
+
+ console.log(completionResponse)
+
+ const [firstChoice] = completionResponse.choices
+
+ const sqlResponseString = firstChoice.message?.function_call?.arguments
+
+ if (!sqlResponseString) {
+ console.error(
+ `AI SQL debugging failed: OpenAI response succeeded, but response format was incorrect`
+ )
+
+ return new Response(
+ JSON.stringify({
+ error: 'There was an unknown error debugging the SQL snippet. Please try again.',
+ }),
+ {
+ status: 500,
+ headers: {
+ 'content-type': 'application/json',
+ },
+ }
+ )
+ }
+
+ console.log({ sqlResponseString })
+
+ const debugSqlResult: DebugSqlResult = JSON.parse(sqlResponseString)
+
+ if (!debugSqlResult.sql) {
+ console.error(`AI SQL debugging failed: Unable to debug SQL for the given prompt`)
+
+ return new Response(
+ JSON.stringify({
+ error: 'Unable to debug SQL. Try adding more details to your prompt.',
+ }),
+ {
+ status: 400,
+ headers: {
+ 'content-type': 'application/json',
+ },
+ }
+ )
+ }
+
+ return new Response(JSON.stringify(debugSqlResult), {
+ headers: {
+ 'content-type': 'application/json',
+ },
+ })
+}