The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
Chore/improved error surfacing in sql editor (#18327)
Joshen Lim651138a88ee0
diff --git a/studio/components/interfaces/SQLEditor/MonacoEditor.tsx b/studio/components/interfaces/SQLEditor/MonacoEditor.tsxindex c56df7f2e45..a11101c3a45 100644--- a/studio/components/interfaces/SQLEditor/MonacoEditor.tsx+++ b/studio/components/interfaces/SQLEditor/MonacoEditor.tsx@@ -16,6 +16,7 @@ import { createSqlSnippetSkeleton } from './SQLEditor.utils'export type MonacoEditorProps = {id: stringeditorRef: MutableRefObject<IStandaloneCodeEditor | null>+ monacoRef: MutableRefObject<Monaco | null>autoFocus?: booleanexecuteQuery: () => voidclassName?: string@@ -24,6 +25,7 @@ export type MonacoEditorProps = {const MonacoEditor = ({id,editorRef,+ monacoRef,autoFocus = true,className,executeQuery,@@ -36,7 +38,6 @@ const MonacoEditor = ({const snap = useSqlEditorStateSnapshot({ sync: true })const snippet = snap.snippets[id]- const monacoRef = useRef<Monaco | null>(null)const executeQueryRef = useRef(executeQuery)executeQueryRef.current = executeQuerydiff --git a/studio/components/interfaces/SQLEditor/SQLEditor.tsx b/studio/components/interfaces/SQLEditor/SQLEditor.tsxindex b22420ec896..96010affed5 100644--- a/studio/components/interfaces/SQLEditor/SQLEditor.tsx+++ b/studio/components/interfaces/SQLEditor/SQLEditor.tsx@@ -63,6 +63,7 @@ import {getDiffTypeDropdownLabel,} from './SQLEditor.utils'import UtilityPanel from './UtilityPanel/UtilityPanel'+import { Monaco } from '@monaco-editor/react'// Load the monaco editor client-side only (does not behave well server-side)const MonacoEditor = dynamic(() => import('./MonacoEditor'), { ssr: false })@@ -137,6 +138,7 @@ const SQLEditor = () => {const [selectedDiffType, setSelectedDiffType] = useState(DiffType.Modification)const [isFirstRender, setIsFirstRender] = useState(true)+ const [lineHighlights, setLineHighlights] = useState<string[]>([])const isAiLoading = isGenerateSqlLoading || isEditSqlLoading@@ -171,8 +173,35 @@ const SQLEditor = () => {// Refetching instead of invalidating since invalidate doesn't work with `enabled` flagrefetchEntityDefinitions()},- onError(error) {- if (id) snap.addResultError(id, error)+ onError(error: any) {+ if (id) {+ if (error.position && monacoRef.current) {+ const editor = editorRef.current+ const monaco = monacoRef.current++ const formattedError = error.formattedError ?? ''+ const lineError = formattedError.slice(formattedError.indexOf('LINE'))+ const line = Number(lineError.slice(0, lineError.indexOf(':')).split(' ')[1])++ if (!isNaN(line)) {+ const decorations = editor?.deltaDecorations(+ [],+ [+ {+ range: new monaco.Range(line, 1, line, 20),+ options: { isWholeLine: true, inlineClassName: 'bg-amber-800' },+ },+ ]+ )+ if (decorations) {+ editor?.revealLineInCenter(line)+ setLineHighlights(decorations)+ }+ }+ }++ snap.addResultError(id, error)+ }},})@@ -191,6 +220,7 @@ const SQLEditor = () => {)const editorRef = useRef<IStandaloneCodeEditor | null>(null)+ const monacoRef = useRef<Monaco | null>(null)const diffEditorRef = useRef<IStandaloneDiffEditor | null>(null)/**@@ -272,6 +302,11 @@ const SQLEditor = () => {setAiTitle(id, sql)}+ if (lineHighlights.length > 0) {+ editor?.deltaDecorations(lineHighlights, [])+ setLineHighlights([])+ }+execute({projectRef: project.ref,connectionString: project.connectionString,@@ -911,6 +946,7 @@ const SQLEditor = () => {autoFocusid={id}editorRef={editorRef}+ monacoRef={monacoRef}executeQuery={executeQuery}/></motion.div>diff --git a/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityTabResults.tsx b/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityTabResults.tsxindex 0661dd7cd4a..6d98ad50a23 100644--- a/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityTabResults.tsx+++ b/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityTabResults.tsx@@ -64,12 +64,24 @@ const UtilityTabResults = ({ id, isExecuting }: UtilityTabResultsProps) => {</div>)} else if (result?.error) {+ const formattedError = (result.error?.formattedError.split('\n') ?? []).filter(+ (x: string) => x.length > 0+ )+return (<div className="bg-table-header-light dark:bg-table-header-dark">- <div className="flex flex-row justify-between items-center pr-8">- <p className="m-0 border-0 px-6 py-4 font-mono text-sm">- Error running SQL: {result.error.message ?? result.error}- </p>+ <div className="flex flex-row justify-between items-start py-4 px-6">+ <div>+ {formattedError.length > 0 ? (+ formattedError.map((x: string, i: number) => (+ <pre key={`error-${i}`} className="font-mono text-sm">+ {x}+ </pre>+ ))+ ) : (+ <p className="font-mono text-sm">{result.error.error}</p>+ )}+ </div>{supabaseAIEnabled && !hasHipaaAddon && (<Buttonicon={diff --git a/studio/data/sql/execute-sql-query.ts b/studio/data/sql/execute-sql-query.tsindex 7d6790ba814..9736d249c59 100644--- a/studio/data/sql/execute-sql-query.ts+++ b/studio/data/sql/execute-sql-query.ts@@ -6,8 +6,7 @@ import {UseQueryOptions,} from '@tanstack/react-query'import md5 from 'blueimp-md5'-import { post } from 'lib/common/fetch'-import { API_URL } from 'lib/constants'+import { post as newPost } from 'data/fetchers'import { useCallback } from 'react'import { sqlKeys } from './keys'@@ -34,33 +33,28 @@ export async function executeSql(>,signal?: AbortSignal) {- if (!projectRef) {- throw new Error('projectRef is required')- }+ if (!projectRef) throw new Error('projectRef is required')let headers = new Headers()+ if (connectionString) headers.set('x-connection-encrypted', connectionString)- if (connectionString) {- headers.set('x-connection-encrypted', connectionString)- }-- const response = await post(- `${API_URL}/pg-meta/${projectRef}/query${- queryKey ? `?key=${queryKey.filter((seg) => typeof seg === 'string').join('-')}` : ''- }`,- { query: sql },- { headers: Object.fromEntries(headers), signal }- )+ const { data, error } = await newPost('/platform/pg-meta/{ref}/query', {+ signal,+ params: {+ header: { 'x-connection-encrypted': connectionString ?? '' },+ path: { ref: projectRef },+ // @ts-ignore: This is just a client side thing to identify queries better+ query: { key: queryKey?.filter((seg) => typeof seg === 'string').join('-') ?? '' },+ },+ body: { query: sql },+ headers: Object.fromEntries(headers),+ })- if (response.error) {- if (handleError !== undefined) {- return handleError(response.error)- } else {- throw response.error- }+ if (error) {+ if (handleError !== undefined) return handleError(error)+ else throw error}-- return { result: response }+ return { result: data }}export type ExecuteSqlData = Awaited<ReturnType<typeof executeSql>>