The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
Trigger update snippet when toggling favorite (#50121)
Joshen Limc37e756983c5
diff --git a/apps/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityActions.tsx b/apps/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityActions.tsxindex 283832f11b7..f78cf909937 100644--- a/apps/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityActions.tsx+++ b/apps/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityActions.tsx@@ -34,6 +34,7 @@ import { useLocalStorageQuery } from '@/hooks/misc/useLocalStorage'import { IS_PLATFORM } from '@/lib/constants'import { hotkeyToKeys } from '@/state/shortcuts/formatShortcut'import { SHORTCUT_DEFINITIONS, SHORTCUT_IDS } from '@/state/shortcuts/registry'+import { useSqlEditorSaveCoordinator } from '@/state/sql-editor/sql-editor-save-coordinator'import { useSqlEditorSessionSnapshot } from '@/state/sql-editor/sql-editor-session-state'import { useSqlEditorV2StateSnapshot } from '@/state/sql-editor/sql-editor-state'@@ -62,6 +63,7 @@ export const UtilityActions = ({const snapV2 = useSqlEditorV2StateSnapshot()const sessionSnap = useSqlEditorSessionSnapshot()const isManualSaveEnabled = useIsSqlEditorManualSaveEnabled()+ const { saveFavorite } = useSqlEditorSaveCoordinator()const isLogsSourceEnabled = useFlag('sqlEditorLogsSource')const isOtelLogsEnabled = useFlag('otelLegacyLogs')@@ -95,10 +97,6 @@ export const UtilityActions = ({)}- const addFavorite = () => snapV2.addFavorite(id)-- const removeFavorite = () => snapV2.removeFavorite(id)-const onSelectDatabase = (databaseId: string) => {sessionSnap.resetResult(id)setLastSelectedDb(databaseId)@@ -137,13 +135,7 @@ export const UtilityActions = ({{IS_PLATFORM && (<><DropdownMenuSeparator />- <DropdownMenuItem- className="gap-x-2"- onClick={() => {- if (isFavorite) removeFavorite()- else addFavorite()- }}- >+ <DropdownMenuItem className="gap-x-2" onClick={() => saveFavorite(id, !isFavorite)}><Heartsize={14}strokeWidth={2}@@ -205,7 +197,7 @@ export const UtilityActions = ({<Buttonvariant="text"size="tiny"- onClick={removeFavorite}+ onClick={() => saveFavorite(id, false)}className="px-1"icon={<Heart className="fill-brand stroke-none" />}aria-label="Remove from favorites"@@ -214,7 +206,7 @@ export const UtilityActions = ({<Buttonvariant="text"size="tiny"- onClick={addFavorite}+ onClick={() => saveFavorite(id, true)}className="px-1"icon={<Heart className="fill-none stroke-foreground-light" />}aria-label="Add to favorites"diff --git a/apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SQLEditorTreeViewItem.tsx b/apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SQLEditorTreeViewItem.tsxindex 615eecc6aad..978b326dd0f 100644--- a/apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SQLEditorTreeViewItem.tsx+++ b/apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SQLEditorTreeViewItem.tsx@@ -43,6 +43,7 @@ import {isFolderSaving,type FolderStatus,} from '@/state/sql-editor/sql-editor-lifecycle'+import { useSqlEditorSaveCoordinator } from '@/state/sql-editor/sql-editor-save-coordinator'import { useSqlEditorV2StateSnapshot } from '@/state/sql-editor/sql-editor-state'interface SQLEditorTreeViewItemProps extends Omit<@@ -107,6 +108,7 @@ export const SQLEditorTreeViewItem = ({const { data: project } = useSelectedProjectQuery()const { className, onClick } = getNodeProps()const snapV2 = useSqlEditorV2StateSnapshot()+ const { saveFavorite } = useSqlEditorSaveCoordinator()const isOwner = profile?.id === element?.metadata.owner_idconst isSharedSnippet = element.metadata.visibility === 'project'@@ -201,8 +203,7 @@ export const SQLEditorTreeViewItem = ({snapV2.setSnippet(projectRef, snippet)}- if (isFavorite) snapV2.removeFavorite(snippetId)- else snapV2.addFavorite(snippetId)+ saveFavorite(snippetId, !isFavorite)}const onSelectDuplicate = async () => {diff --git a/apps/studio/state/sql-editor/sql-editor-save-coordinator.tsx b/apps/studio/state/sql-editor/sql-editor-save-coordinator.tsxindex b5919477827..7a271da346d 100644--- a/apps/studio/state/sql-editor/sql-editor-save-coordinator.tsx+++ b/apps/studio/state/sql-editor/sql-editor-save-coordinator.tsx@@ -24,7 +24,9 @@ import { createSQLSnippetFolder } from '@/data/content/sql-folder-create-mutatioimport { updateSQLSnippetFolder } from '@/data/content/sql-folder-update-mutation'import { TabsStateContext, type Tab } from '@/state/tabs'-type SaveCoordinator = Pick<SaveScheduler, 'requestSave'>+type SaveCoordinator = Pick<SaveScheduler, 'requestSave'> & {+ saveFavorite: (id: string, favorite: boolean) => void+}const SqlEditorSaveCoordinatorContext = createContext<SaveCoordinator | null>(null)@@ -34,7 +36,8 @@ const SqlEditorSaveCoordinatorContext = createContext<SaveCoordinator | null>(nu* query invalidation uses the React Query client from context, and the* subscription is started/stopped deterministically — and is testable.*- * Exposes `requestSave` (the explicit-save entry, e.g. Cmd+S) via context.+ * Exposes `requestSave` (the explicit-save entry, e.g. Cmd+S) and `saveFavorite`+ * via context.*/export function SqlEditorSaveCoordinatorProvider({ children }: PropsWithChildren) {const queryClient = useQueryClient()@@ -45,7 +48,7 @@ export function SqlEditorSaveCoordinatorProvider({ children }: PropsWithChildrensaveModeRef.current = isManualSaveEnabled ? 'manual' : 'auto'}, [isManualSaveEnabled])- const scheduler = useMemo(() => {+ const coordinator = useMemo(() => {const mechanism = createSaveMechanism({state: sqlEditorState,upsertContent,@@ -63,15 +66,29 @@ export function SqlEditorSaveCoordinatorProvider({ children }: PropsWithChildren// getSaveMode is invoked synchronously from a Valtio `subscribe` callback,// outside React's render cycle, so it can't read reactive state directly.// Route it through a ref that's kept in sync via the effect above instead.- return createSaveScheduler({+ const scheduler = createSaveScheduler({state: sqlEditorState,saveMechanism: mechanism,notify: toast,getSaveMode: () => saveModeRef.current,})++ return {+ ...scheduler,+ saveFavorite: (id: string, favorite: boolean) => {+ const storeSnippet = sqlEditorState.snippets[id]+ if (!storeSnippet) return+ const previousFavorite = storeSnippet.snippet.favorite++ if (favorite) sqlEditorState.addFavorite(id)+ else sqlEditorState.removeFavorite(id)++ mechanism.saveFavorite({ id, projectRef: storeSnippet.projectRef, previousFavorite })+ },+ }}, [queryClient])- useEffect(() => scheduler.start(), [scheduler])+ useEffect(() => coordinator.start(), [coordinator])// Own what a SQL tab means to the tabs layout — how it closes and the// unsaved-changes dot it shows — so the layout doesn't have to know about@@ -133,7 +150,7 @@ export function SqlEditorSaveCoordinatorProvider({ children }: PropsWithChildren}, [])return (- <SqlEditorSaveCoordinatorContext.Provider value={scheduler}>+ <SqlEditorSaveCoordinatorContext.Provider value={coordinator}>{children}</SqlEditorSaveCoordinatorContext.Provider>)diff --git a/apps/studio/state/sql-editor/sql-editor-save.test.ts b/apps/studio/state/sql-editor/sql-editor-save.test.tsindex 30f5a6da77f..23b95683e7a 100644--- a/apps/studio/state/sql-editor/sql-editor-save.test.ts+++ b/apps/studio/state/sql-editor/sql-editor-save.test.ts@@ -158,6 +158,65 @@ describe('save mechanism — saveSnippet', () => {})})+describe('save mechanism — saveFavorite', () => {+ it('persists the snippet immediately, without debouncing', async () => {+ const t = setup({ snippets: { 'snippet-1': makeStateSnippet({ favorite: true }) } })++ await t.mechanism.saveFavorite({ id: 'snippet-1', projectRef: 'ref', previousFavorite: false })++ expect(t.upsertContent).toHaveBeenCalledTimes(1)+ expect(t.upsertContent).toHaveBeenCalledWith({+ projectRef: 'ref',+ payload: expect.objectContaining({ id: 'snippet-1', favorite: true }),+ })+ expect(t.state.snippets['snippet-1']!.snippet.status).toBe('saved')+ })++ it('cancels a pending debounced content save for the same id', async () => {+ vi.useFakeTimers()+ const t = setup({ snippets: { 'snippet-1': makeStateSnippet({ favorite: true }) } })++ t.mechanism.saveSnippet({ id: 'snippet-1', projectRef: 'ref', shouldInvalidate: false })+ await t.mechanism.saveFavorite({ id: 'snippet-1', projectRef: 'ref', previousFavorite: false })+ await vi.runAllTimersAsync()++ // Only the immediate favorite save fired — the debounced one never ran.+ expect(t.upsertContent).toHaveBeenCalledTimes(1)+ vi.useRealTimers()+ })++ it('invalidates the lists on a successful save, so the Favorites nav section refetches', async () => {+ const t = setup({ snippets: { 'snippet-1': makeStateSnippet({ favorite: true }) } })++ await t.mechanism.saveFavorite({ id: 'snippet-1', projectRef: 'ref', previousFavorite: false })++ expect(t.invalidate).toHaveBeenCalledWith('ref')+ })++ it('rolls back to previousFavorite, notifies, and does NOT invalidate when the save fails', async () => {+ const t = setup({+ snippets: { 'snippet-1': makeStateSnippet({ favorite: true, status: 'saved' }) },+ })+ t.upsertContent.mockRejectedValueOnce(new Error('network'))++ await t.mechanism.saveFavorite({ id: 'snippet-1', projectRef: 'ref', previousFavorite: false })++ expect(t.state.snippets['snippet-1']!.snippet.favorite).toBe(false)+ expect(t.state.snippets['snippet-1']!.snippet.status).toBe('save_failed')+ expect(t.notify.error).toHaveBeenCalled()+ expect(t.invalidate).not.toHaveBeenCalled()+ })++ it('does NOT call upsertContent for a snippet whose content is not loaded', async () => {+ const snippet = makeStateSnippet({ content: undefined })+ const t = setup({ snippets: { 'snippet-1': snippet } })++ await t.mechanism.saveFavorite({ id: 'snippet-1', projectRef: 'ref', previousFavorite: false })++ expect(t.upsertContent).not.toHaveBeenCalled()+ })+})+describe('save mechanism — createFolder', () => {it('persists a new folder and swaps the local placeholder for it', async () => {const t = setup({diff --git a/apps/studio/state/sql-editor/sql-editor-save.ts b/apps/studio/state/sql-editor/sql-editor-save.tsindex 8de522e9615..c652a7ffb23 100644--- a/apps/studio/state/sql-editor/sql-editor-save.ts+++ b/apps/studio/state/sql-editor/sql-editor-save.ts@@ -81,23 +81,36 @@ export function createSaveMechanism(deps: SaveMechanismDeps) {debounceMs = 1000,} = deps- async function saveSnippet({ id, projectRef, shouldInvalidate }: SaveSnippetArgs) {+ type PersistResult = { status: 'skipped' | 'success' } | { status: 'error'; error: unknown }++ /**+ * Upsert a snippet's full current state and reflect the outcome in its+ * `status`. Shared by the debounced content save and the immediate favorite+ * save — the endpoint has no partial update, so both send the whole snippet.+ */+ async function persistSnippet(id: string, projectRef: string): Promise<PersistResult> {const snippet = state.snippets[id]?.snippet// Only persist a snippet whose content has been loaded — otherwise we would// PUT an empty content body and clobber the stored SQL.- if (snippet === undefined || !isLoadedSnippet(snippet)) return+ if (snippet === undefined || !isLoadedSnippet(snippet)) return { status: 'skipped' }const payload = buildPayload(snippet, id)try {snippet.status = statusOnSaveStart(snippet.status)await upsertContent({ projectRef, payload })- if (shouldInvalidate) await invalidate(projectRef)snippet.status = statusOnSaveSuccess()+ return { status: 'success' }} catch (error) {snippet.status = statusOnSaveError(snippet.status)+ return { status: 'error', error }}}+ async function saveSnippet({ id, projectRef, shouldInvalidate }: SaveSnippetArgs) {+ const result = await persistSnippet(id, projectRef)+ if (result.status === 'success' && shouldInvalidate) await invalidate(projectRef)+ }+const memoizedSaveSnippet = memoize((_id: string) => debounce(saveSnippet, debounceMs))/** Debounced per snippet id; rapid edits to one snippet coalesce to one save. */@@ -105,6 +118,41 @@ export function createSaveMechanism(deps: SaveMechanismDeps) {memoizedSaveSnippet(args.id)(args)}+ /**+ * Persist a snippet's favorite flag immediately, bypassing the debounce and+ * save-mode policy that content edits go through. Any pending debounced+ * content save for this id is cancelled since it would otherwise duplicate+ * this request. `previousFavorite` is the value the caller applied the+ * optimistic change over, so a failed save can roll back to exactly that —+ * rather than inverting whatever the field happens to hold once the request+ * settles, which could be wrong if the flag was toggled again in the meantime.+ * Always invalidates on success — the Favorites nav section is backed by its+ * own `favorite: true` query, not a live filter over this store, so it won't+ * otherwise notice the flag changed.+ */+ async function saveFavorite({+ id,+ projectRef,+ previousFavorite,+ }: {+ id: string+ projectRef: string+ previousFavorite: boolean+ }) {+ memoizedSaveSnippet(id).cancel()++ const result = await persistSnippet(id, projectRef)+ if (result.status === 'success') {+ await invalidate(projectRef)+ } else if (result.status === 'error') {+ notify.error(+ `Failed to update favorite: ${getErrorMessage(result.error) ?? GENERIC_ERROR_MESSAGE}`+ )+ const snippet = state.snippets[id]?.snippet+ if (snippet) snippet.favorite = previousFavorite+ }+ }+async function createFolder({ projectRef, name, placeholderId }: CreateFolderArgs) {try {const folder = await createSQLSnippetFolder({ projectRef, name })@@ -141,6 +189,8 @@ export function createSaveMechanism(deps: SaveMechanismDeps) {return {/** Schedule a debounced save of the snippet with the given id. */saveSnippet: scheduleSaveSnippet,+ /** Persist a snippet's favorite flag immediately. */+ saveFavorite,/** Persist a new folder, swapping out its local placeholder. */createFolder,/** Persist a folder rename. */diff --git a/apps/studio/state/sql-editor/sql-editor-state.test.ts b/apps/studio/state/sql-editor/sql-editor-state.test.tsindex 3bceae2105a..0b65fe69cf3 100644--- a/apps/studio/state/sql-editor/sql-editor-state.test.ts+++ b/apps/studio/state/sql-editor/sql-editor-state.test.ts@@ -62,16 +62,17 @@ describe('addFavorite / removeFavorite', () => {sqlEditorState.needsSaving.clear()})- it('marks a loaded snippet as favorite and queues it for saving', () => {+ it('marks a loaded snippet as favorite without queueing it for saving', () => {sqlEditorState.addSnippet({ projectRef: 'ref', snippet: makeSnippet('snippet-1') })sqlEditorState.addFavorite('snippet-1')expect(sqlEditorState.snippets['snippet-1'].snippet.favorite).toBe(true)- expect(sqlEditorState.needsSaving.get('snippet-1')).toBe(true)+ // Favorites persist immediately via the save coordinator, not the queue.+ expect(sqlEditorState.needsSaving.has('snippet-1')).toBe(false)})- it('unmarks a favorited snippet and queues it for saving', () => {+ it('unmarks a favorited snippet without queueing it for saving', () => {sqlEditorState.addSnippet({projectRef: 'ref',snippet: makeSnippet('snippet-1', { favorite: true }),@@ -80,7 +81,7 @@ describe('addFavorite / removeFavorite', () => {sqlEditorState.removeFavorite('snippet-1')expect(sqlEditorState.snippets['snippet-1'].snippet.favorite).toBe(false)- expect(sqlEditorState.needsSaving.get('snippet-1')).toBe(true)+ expect(sqlEditorState.needsSaving.has('snippet-1')).toBe(false)})it('ignores addFavorite for a snippet that is not in the store', () => {diff --git a/apps/studio/state/sql-editor/sql-editor-state.ts b/apps/studio/state/sql-editor/sql-editor-state.tsindex c3519a75ea8..c35c1912003 100644--- a/apps/studio/state/sql-editor/sql-editor-state.ts+++ b/apps/studio/state/sql-editor/sql-editor-state.ts@@ -252,11 +252,14 @@ export const sqlEditorState = proxy({addNeedsSaving: (id: string) => sqlEditorState.needsSaving.set(id, true),+ /**+ * Mark a snippet as favorite. Favoriting persists immediately regardless of+ * save mode (see `SqlEditorSaveCoordinatorProvider.saveFavorite`)+ */addFavorite: (id: string) => {const storeSnippet = sqlEditorState.snippets[id]if (storeSnippet) {storeSnippet.snippet.favorite = true- sqlEditorState.needsSaving.set(id, true)}},@@ -264,7 +267,6 @@ export const sqlEditorState = proxy({const storeSnippet = sqlEditorState.snippets[id]if (storeSnippet) {storeSnippet.snippet.favorite = false- sqlEditorState.needsSaving.set(id, true)}},})