The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
chore: sql editor upsert
Alaister Young10f564083751
diff --git a/studio/components/interfaces/App/CommandMenuWrapper.tsx b/studio/components/interfaces/App/CommandMenuWrapper.tsxindex e94fe6797d1..bed20fc50a3 100644--- a/studio/components/interfaces/App/CommandMenuWrapper.tsx+++ b/studio/components/interfaces/App/CommandMenuWrapper.tsx@@ -80,7 +80,7 @@ const CommandMenuWrapper = ({ children }: PropsWithChildren<{}>) => {sql: formattedSql,})const data = { ...snippet, id: uuidv4() }- snap.addSnippet(data as SqlSnippet, ref, true)+ snap.addSnippet(data as SqlSnippet, ref)ui.setNotification({category: 'success',message: `Successfully saved snippet!`,diff --git a/studio/components/interfaces/SQLEditor/SQLTemplates/SQLTemplates.tsx b/studio/components/interfaces/SQLEditor/SQLTemplates/SQLTemplates.tsxindex 3c729c690d2..6641f68fa72 100644--- a/studio/components/interfaces/SQLEditor/SQLTemplates/SQLTemplates.tsx+++ b/studio/components/interfaces/SQLEditor/SQLTemplates/SQLTemplates.tsx@@ -42,7 +42,7 @@ const SQLTemplates = observer(() => {try {const snippet = createSqlSnippetSkeleton({ name, sql, owner_id: profile?.id })const data = { ...snippet, id: uuidv4() }- snap.addSnippet(data as SqlSnippet, ref, true)+ snap.addSnippet(data as SqlSnippet, ref)router.push(`/project/${ref}/sql/${data.id}`)} catch (error: any) {ui.setNotification({diff --git a/studio/components/layouts/SQLEditorLayout/SQLEditorMenu.tsx b/studio/components/layouts/SQLEditorLayout/SQLEditorMenu.tsxindex c83802db398..1e527362996 100644--- a/studio/components/layouts/SQLEditorLayout/SQLEditorMenu.tsx+++ b/studio/components/layouts/SQLEditorLayout/SQLEditorMenu.tsx@@ -68,7 +68,7 @@ const SideBarContent = observer(() => {const snippet = createSqlSnippetSkeleton({ name: 'Untitled query', owner_id: profile?.id })const data = { ...snippet, id: uuidv4() }- snap.addSnippet(data as SqlSnippet, ref, true)+ snap.addSnippet(data as SqlSnippet, ref)router.push(`/project/${ref}/sql/${data.id}`)} catch (error: any) {diff --git a/studio/data/content/content-update-mutation.ts b/studio/data/content/content-update-mutation.tsdeleted file mode 100644index a6c4deb843f..00000000000--- a/studio/data/content/content-update-mutation.ts+++ /dev/null@@ -1,53 +0,0 @@-import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'-import { patch } from 'lib/common/fetch'-import { API_URL } from 'lib/constants'-import { UserContent } from 'types'-import { contentKeys } from './keys'--type UpdateContentVariables = {- projectRef: string- id: string- content: Partial<UserContent>-}--export async function updateContent(- { projectRef, id, content }: UpdateContentVariables,- signal?: AbortSignal-) {- const created = await patch<UserContent[]>(- `${API_URL}/projects/${projectRef}/content?id=${id}`,- content,- { signal }- )- if (created.error) {- throw created.error- }-- return { content: created[0] }-}--type UpdateContentData = Awaited<ReturnType<typeof updateContent>>--export const useContentUpdateMutation = ({- onSuccess,- ...options-}: Omit<- UseMutationOptions<UpdateContentData, unknown, UpdateContentVariables>,- 'mutationFn'-> = {}) => {- const queryClient = useQueryClient()-- return useMutation<UpdateContentData, unknown, UpdateContentVariables>(- (args) => updateContent(args),- {- async onSuccess(data, variables, context) {- const { projectRef } = variables-- await Promise.all([queryClient.invalidateQueries(contentKeys.list(projectRef))])-- await onSuccess?.(data, variables, context)- },- ...options,- }- )-}diff --git a/studio/data/content/content-create-mutation.ts b/studio/data/content/content-upsert-mutation.tssimilarity index 56%rename from studio/data/content/content-create-mutation.tsrename to studio/data/content/content-upsert-mutation.tsindex a7235fd70ec..1f498509c47 100644--- a/studio/data/content/content-create-mutation.ts+++ b/studio/data/content/content-upsert-mutation.ts@@ -1,19 +1,20 @@import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'-import { post } from 'lib/common/fetch'+import { put } from 'lib/common/fetch'import { API_URL } from 'lib/constants'import { UserContent } from 'types'import { contentKeys } from './keys'-type CreateContentVariables = {+type UpsertContentVariables = {projectRef: string- payload: UserContent+ id: string+ payload: Partial<UserContent>}-export async function createContent(- { projectRef, payload }: CreateContentVariables,+export async function upsertContent(+ { projectRef, payload }: UpsertContentVariables,signal?: AbortSignal) {- const response = await post<UserContent[]>(`${API_URL}/projects/${projectRef}/content`, payload, {+ const response = await put<UserContent[]>(`${API_URL}/projects/${projectRef}/content`, payload, {signal,})@@ -21,19 +22,19 @@ export async function createContent(return { content: response }}-type CreateContentData = Awaited<ReturnType<typeof createContent>>+type UpsertContentData = Awaited<ReturnType<typeof upsertContent>>-export const useContentCreateMutation = ({+export const useContentUpsertMutation = ({onSuccess,...options}: Omit<- UseMutationOptions<CreateContentData, unknown, CreateContentVariables>,+ UseMutationOptions<UpsertContentData, unknown, UpsertContentVariables>,'mutationFn'> = {}) => {const queryClient = useQueryClient()- return useMutation<CreateContentData, unknown, CreateContentVariables>(- (args) => createContent(args),+ return useMutation<UpsertContentData, unknown, UpsertContentVariables>(+ (args) => upsertContent(args),{async onSuccess(data, variables, context) {const { projectRef } = variablesdiff --git a/studio/state/sql-editor.ts b/studio/state/sql-editor.tsindex 49833b3d8f1..372d5eafae2 100644--- a/studio/state/sql-editor.ts+++ b/studio/state/sql-editor.ts@@ -1,6 +1,5 @@-import { createContent } from 'data/content/content-create-mutation'import { Content } from 'data/content/content-query'-import { updateContent } from 'data/content/content-update-mutation'+import { upsertContent } from 'data/content/content-upsert-mutation'import { SqlSnippet } from 'data/content/sql-snippets-query'import { debounce, memoize } from 'lodash'import { useMemo } from 'react'@@ -31,7 +30,6 @@ export const sqlEditorState = proxy({[key: string]: boolean},- needsCreating: proxySet<string>([]),needsSaving: proxySet<string>([]),savingStates: {} as {[key: string]: 'IDLE' | 'UPDATING' | 'UPDATING_FAILED'@@ -64,7 +62,7 @@ export const sqlEditorState = proxy({sqlEditorState.addSnippet(snippet, projectRef)})},- addSnippet: (snippet: SqlSnippet, projectRef: string, isNew?: boolean) => {+ addSnippet: (snippet: SqlSnippet, projectRef: string) => {if (snippet.id && !sqlEditorState.snippets[snippet.id]) {sqlEditorState.snippets[snippet.id] = {snippet,@@ -80,9 +78,8 @@ export const sqlEditorState = proxy({sqlEditorState.orders[projectRef].unshift(snippet.id)sqlEditorState.reorderSnippets(projectRef)}- if (isNew) {- sqlEditorState.needsCreating.add(snippet.id)- }++ sqlEditorState.needsSaving.add(snippet.id)}sqlEditorState.loaded[projectRef] = true},@@ -98,7 +95,6 @@ export const sqlEditorState = proxy({)sqlEditorState.needsSaving.delete(id)- sqlEditorState.needsCreating.delete(id)},setSplitSizes: (id: string, splitSizes: number[]) => {if (sqlEditorState.snippets[id]) {@@ -174,68 +170,41 @@ export const useSnippets = (projectRef: string | undefined) => {}, [projectRef, snapshot.orders, snapshot.snippets])}-async function update(id: string, projectRef: string, content: Partial<Content>) {+async function upsert(id: string, projectRef: string, content: Partial<Content>) {try {sqlEditorState.savingStates[id] = 'UPDATING'- await updateContent({ projectRef, id, content })+ await upsertContent({ projectRef, id, payload: content })sqlEditorState.savingStates[id] = 'IDLE'} catch (error) {sqlEditorState.savingStates[id] = 'UPDATING_FAILED'}}-const memoizedUpdate = memoize((_id: string) => debounce(update, 1000))+const memoizedUpdate = memoize((_id: string) => debounce(upsert, 1000))const debouncedUpdate = (id: string, projectRef: string, content: Partial<Content>) =>memoizedUpdate(id)(id, projectRef, content)if (typeof window !== 'undefined') {devtools(sqlEditorState, { name: 'sqlEditorState', enabled: true })- subscribe(sqlEditorState.needsCreating, () => {+ subscribe(sqlEditorState.needsSaving, () => {const state = getSqlEditorStateSnapshot()- state.needsCreating.forEach((id) => {+ Array.from(state.needsSaving).forEach((id) => {const snippet = state.snippets[id]if (snippet) {- sqlEditorState.savingStates[id] = 'UPDATING'- createContent({- projectRef: snippet.projectRef,- payload: {- ...snippet.snippet,- type: 'sql',- },+ debouncedUpdate(id, snippet.projectRef, {+ content: { ...snippet.snippet.content, content_id: id },+ type: 'sql',+ id,+ name: snippet.snippet.name,+ description: snippet.snippet.description,+ visibility: snippet.snippet.visibility ?? 'project',})- .then(() => {- sqlEditorState.savingStates[id] = 'IDLE'- sqlEditorState.needsCreating.delete(id)- })- .catch(() => {- sqlEditorState.savingStates[id] = 'UPDATING_FAILED'- })++ sqlEditorState.needsSaving.delete(id)}})})-- subscribe(sqlEditorState.needsSaving, () => {- const state = getSqlEditorStateSnapshot()-- Array.from(state.needsSaving)- .filter((id) => !state.needsCreating.has(id))- .forEach((id) => {- const snippet = state.snippets[id]-- if (snippet) {- debouncedUpdate(id, snippet.projectRef, {- content: { ...snippet.snippet.content, content_id: id },- type: 'sql',- id,- name: snippet.snippet.name,- description: snippet.snippet.description,- })-- sqlEditorState.needsSaving.delete(id)- }- })- })}