The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
refactor(studio): extract SQL editor save mechanism + model folder lifecycle (4/9) (#47276)
Charis16526bd6bfbc
diff --git a/apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SQLEditorNav.tsx b/apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SQLEditorNav.tsxindex bdfd2254713..cefdfd1edf9 100644--- a/apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SQLEditorNav.tsx+++ b/apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SQLEditorNav.tsx@@ -39,6 +39,7 @@ import { useLocalStorage } from '@/hooks/misc/useLocalStorage'import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'import { useProfile } from '@/lib/profile'import { useSnippetFolders, useSqlEditorV2StateSnapshot } from '@/state/sql-editor-v2'+import { isNewFolder } from '@/state/sql-editor/sql-editor-lifecycle'import { createTabId, useTabsStateSnapshot } from '@/state/tabs'interface SQLEditorNavProps {@@ -719,10 +720,11 @@ export const SQLEditorNav = ({ sort = 'inserted_at' }: SQLEditorNavProps) => {onSelectShare={() => setSelectedSnippetToShare(element.metadata as Snippet)}onEditSave={(name: string) => {// [Joshen] Inline editing only for folders for now- if (name.length === 0 && element.id === 'new-folder') {- snapV2.removeFolder(element.id as string)+ const folderId = element.id as string+ if (name.length === 0 && isNewFolder(snapV2.folders[folderId]?.status)) {+ snapV2.removeFolder(folderId)} else if (name.length > 0) {- snapV2.saveFolder({ id: element.id as string, name })+ snapV2.saveFolder({ id: folderId, name })}}}hasNextPage={hasNextPage}diff --git a/apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SQLEditorTreeViewItem.tsx b/apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SQLEditorTreeViewItem.tsxindex 30680c5989c..ab9bdc6ea06 100644--- a/apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SQLEditorTreeViewItem.tsx+++ b/apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SQLEditorTreeViewItem.tsx@@ -37,6 +37,11 @@ import useLatest from '@/hooks/misc/useLatest'import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'import { useProfile } from '@/lib/profile'import { useSqlEditorV2StateSnapshot } from '@/state/sql-editor-v2'+import {+ isFolderEditing,+ isFolderSaving,+ type FolderStatus,+} from '@/state/sql-editor/sql-editor-lifecycle'interface SQLEditorTreeViewItemProps extends Omit<ComponentProps<typeof TreeViewItem>,@@ -44,7 +49,7 @@ interface SQLEditorTreeViewItemProps extends Omit<> {element: anyisMultiSelected?: boolean- status?: 'editing' | 'saving' | 'idle'+ status?: FolderStatusgetNodeProps: () => anyonSelectCreate?: () => voidonSelectDelete?: () => void@@ -105,8 +110,8 @@ export const SQLEditorTreeViewItem = ({const isSharedSnippet = element.metadata.visibility === 'project'const isFavorite = element.metadata.favorite- const isEditing = status === 'editing'- const isSaving = status === 'saving'+ const isEditing = isFolderEditing(status)+ const isSaving = isFolderSaving(status)const { can: canCreateSQLSnippet } = useAsyncCheckPermissions(PermissionAction.CREATE,diff --git a/apps/studio/lib/notifier.ts b/apps/studio/lib/notifier.tsnew file mode 100644index 00000000000..8c63ef31837--- /dev/null+++ b/apps/studio/lib/notifier.ts@@ -0,0 +1,10 @@+/**+ * A minimal dependency-injection contract for surfacing user-facing+ * notifications (toasts). It is structurally a subset of sonner's `toast`, so+ * the real `toast` can be passed directly while tests pass a spy — letting+ * modules that need to notify stay free of a hard sonner import.+ */+export interface Notifier {+ success: (message: string) => void+ error: (message: string) => void+}diff --git a/apps/studio/state/sql-editor/sql-editor-lifecycle.test.ts b/apps/studio/state/sql-editor/sql-editor-lifecycle.test.tsindex c48a6d5416c..479a43c706c 100644--- a/apps/studio/state/sql-editor/sql-editor-lifecycle.test.ts+++ b/apps/studio/state/sql-editor/sql-editor-lifecycle.test.ts@@ -1,12 +1,17 @@import { describe, expect, it } from 'vitest'import {+ folderStatusOnSaveStart,+ isFolderEditing,+ isFolderSaving,+ isNewFolder,isSaveFailed,isSaving,statusOnSaveError,statusOnSaveStart,statusOnSaveSuccess,wasNeverPersisted,+ type FolderStatus,} from './sql-editor-lifecycle'import type { SnippetStatus } from '@/data/content/snippet-status'@@ -116,3 +121,53 @@ describe('lifecycle round trips', () => {expect(wasNeverPersisted(status)).toBe(false)})})++const NEW_FOLDER: Array<FolderStatus> = ['new_editing', 'new_saving']+const PERSISTED_FOLDER: Array<FolderStatus> = ['editing', 'saving', 'idle']++describe('isNewFolder', () => {+ it.each(NEW_FOLDER)('is true for not-yet-persisted folder status %s', (status) => {+ expect(isNewFolder(status)).toBe(true)+ })++ it.each(PERSISTED_FOLDER)('is false for persisted folder status %s', (status) => {+ expect(isNewFolder(status)).toBe(false)+ })++ it('treats an absent status as not-new', () => {+ expect(isNewFolder(undefined)).toBe(false)+ })+})++describe('isFolderEditing', () => {+ it('is true only while the name is being edited inline (new or persisted)', () => {+ expect(isFolderEditing('new_editing')).toBe(true)+ expect(isFolderEditing('editing')).toBe(true)+ })++ it.each(['new_saving', 'saving', 'idle', undefined] as const)('is false for %s', (status) => {+ expect(isFolderEditing(status)).toBe(false)+ })+})++describe('isFolderSaving', () => {+ it('is true only while a create/rename is in flight (new or persisted)', () => {+ expect(isFolderSaving('new_saving')).toBe(true)+ expect(isFolderSaving('saving')).toBe(true)+ })++ it.each(['new_editing', 'editing', 'idle', undefined] as const)('is false for %s', (status) => {+ expect(isFolderSaving(status)).toBe(false)+ })+})++describe('folderStatusOnSaveStart', () => {+ it('keeps a new folder in the new family', () => {+ expect(folderStatusOnSaveStart('new_editing')).toBe('new_saving')+ })++ it('moves a persisted folder to saving', () => {+ expect(folderStatusOnSaveStart('editing')).toBe('saving')+ expect(folderStatusOnSaveStart('idle')).toBe('saving')+ })+})diff --git a/apps/studio/state/sql-editor/sql-editor-lifecycle.ts b/apps/studio/state/sql-editor/sql-editor-lifecycle.tsindex e9ce992f8c1..24fc6258e2a 100644--- a/apps/studio/state/sql-editor/sql-editor-lifecycle.ts+++ b/apps/studio/state/sql-editor/sql-editor-lifecycle.ts@@ -38,3 +38,40 @@ export function statusOnSaveSuccess(): SnippetStatus {export function statusOnSaveError(status: SnippetStatus | undefined): SnippetStatus {return wasNeverPersisted(status) ? 'new_save_failed' : 'save_failed'}++/**+ * The lifecycle of a folder in the SQL editor nav, as a single set of+ * mutually-exclusive states. Like SnippetStatus, this collapses two orthogonal+ * axes — persistence (a locally-created placeholder vs a persisted folder) and+ * progress (inline-name editing / save in flight / settled) — into one enum, so+ * a folder can never be in a nonsensical combination (e.g. "new" yet "idle").+ * The predicates below recover each axis.+ */+export type FolderStatus =+ // Never persisted to the database (a locally-created placeholder):+ | 'new_editing' // its name is being entered inline+ | 'new_saving' // its create is in flight+ // Persisted to the database:+ | 'idle' // settled+ | 'editing' // its name is being edited inline (rename)+ | 'saving' // its rename is in flight++/** True for a locally-created placeholder folder that has not been persisted. */+export function isNewFolder(status: FolderStatus | undefined): boolean {+ return status === 'new_editing' || status === 'new_saving'+}++/** True while the folder's name is being edited inline. */+export function isFolderEditing(status: FolderStatus | undefined): boolean {+ return status === 'new_editing' || status === 'editing'+}++/** True while a folder create/rename is in flight. */+export function isFolderSaving(status: FolderStatus | undefined): boolean {+ return status === 'new_saving' || status === 'saving'+}++/** Transition when a folder save begins, preserving the never-persisted axis. */+export function folderStatusOnSaveStart(status: FolderStatus): FolderStatus {+ return isNewFolder(status) ? 'new_saving' : 'saving'+}diff --git a/apps/studio/state/sql-editor/sql-editor-save.test.ts b/apps/studio/state/sql-editor/sql-editor-save.test.tsnew file mode 100644index 00000000000..506dbfcc7ed--- /dev/null+++ b/apps/studio/state/sql-editor/sql-editor-save.test.ts@@ -0,0 +1,285 @@+import { untrustedSql } from '@supabase/pg-meta'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++import { createSaveMechanism, type SaveMechanismStore } from './sql-editor-save'+import type { StateSnippet } from './types'+import type { SnippetFolder } from '@/data/content/sql-folders-query'++function makeStateSnippet(overrides: Partial<StateSnippet['snippet']> = {}): StateSnippet {+ return {+ projectRef: 'ref',+ splitSizes: [50, 50],+ snippet: {+ id: 'snippet-1',+ type: 'sql',+ name: 'Query',+ description: '',+ visibility: 'user',+ project_id: 1,+ owner_id: 1,+ folder_id: null,+ favorite: false,+ inserted_at: '2024-01-01T00:00:00.000Z',+ updated_at: '2024-01-01T00:00:00.000Z',+ status: 'new',+ content: {+ content_id: 'snippet-1',+ schema_version: '1',+ unchecked_sql: untrustedSql('select 1'),+ },+ ...overrides,+ },+ }+}++function makeFolder(id: string, name: string): SnippetFolder {+ return { id, name, owner_id: 1, project_id: 1, parent_id: null }+}++function setup(initial?: Partial<SaveMechanismStore>) {+ const state: SaveMechanismStore = {+ snippets: {},+ folders: {},+ removeFolder: vi.fn((id: string) => {+ delete state.folders[id]+ }),+ ...initial,+ }+ const upsertContent = vi.fn(async () => null)+ const createSQLSnippetFolder = vi.fn(async () => makeFolder('real-id', 'Folder'))+ const updateSQLSnippetFolder = vi.fn(async () => null)+ const invalidate = vi.fn(async () => {})+ const notify = { success: vi.fn(), error: vi.fn() }++ const mechanism = createSaveMechanism({+ state,+ upsertContent,+ createSQLSnippetFolder,+ updateSQLSnippetFolder,+ invalidate,+ notify,+ debounceMs: 1000,+ })++ return {+ state,+ upsertContent,+ createSQLSnippetFolder,+ updateSQLSnippetFolder,+ invalidate,+ notify,+ mechanism,+ }+}++describe('save mechanism — saveSnippet', () => {+ beforeEach(() => vi.useFakeTimers())+ afterEach(() => vi.useRealTimers())++ it('debounces and persists a loaded snippet, transitioning new → saving → saved', async () => {+ const t = setup({ snippets: { 'snippet-1': makeStateSnippet() } })++ t.mechanism.saveSnippet({ id: 'snippet-1', projectRef: 'ref', shouldInvalidate: false })+ expect(t.upsertContent).not.toHaveBeenCalled() // debounced, not yet fired++ await vi.runAllTimersAsync()++ expect(t.upsertContent).toHaveBeenCalledTimes(1)+ expect(t.upsertContent).toHaveBeenCalledWith({+ projectRef: 'ref',+ payload: expect.objectContaining({ id: 'snippet-1', type: 'sql' }),+ })+ expect(t.state.snippets['snippet-1']!.snippet.status).toBe('saved')+ })++ 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 } })++ t.mechanism.saveSnippet({ id: 'snippet-1', projectRef: 'ref', shouldInvalidate: false })+ await vi.runAllTimersAsync()++ expect(t.upsertContent).not.toHaveBeenCalled()+ // status is left untouched — nothing was persisted+ expect(t.state.snippets['snippet-1']!.snippet.status).toBe('new')+ })++ it('invalidates the lists only when shouldInvalidate is true', async () => {+ const t = setup({ snippets: { 'snippet-1': makeStateSnippet() } })++ t.mechanism.saveSnippet({ id: 'snippet-1', projectRef: 'ref', shouldInvalidate: false })+ await vi.runAllTimersAsync()+ expect(t.invalidate).not.toHaveBeenCalled()++ t.mechanism.saveSnippet({ id: 'snippet-1', projectRef: 'ref', shouldInvalidate: true })+ await vi.runAllTimersAsync()+ expect(t.invalidate).toHaveBeenCalledWith('ref')+ })++ it('transitions to save_failed when the upsert rejects', async () => {+ const t = setup({ snippets: { 'snippet-1': makeStateSnippet({ status: 'saved' }) } })+ t.upsertContent.mockRejectedValueOnce(new Error('network'))++ t.mechanism.saveSnippet({ id: 'snippet-1', projectRef: 'ref', shouldInvalidate: false })+ await vi.runAllTimersAsync()++ expect(t.state.snippets['snippet-1']!.snippet.status).toBe('save_failed')+ })++ it('debounces per snippet id — distinct snippets save independently', async () => {+ const t = setup({+ snippets: {+ 'snippet-1': makeStateSnippet({ id: 'snippet-1' }),+ 'snippet-2': makeStateSnippet({ id: 'snippet-2' }),+ },+ })++ t.mechanism.saveSnippet({ id: 'snippet-1', projectRef: 'ref', shouldInvalidate: false })+ t.mechanism.saveSnippet({ id: 'snippet-2', projectRef: 'ref', shouldInvalidate: false })+ await vi.runAllTimersAsync()++ expect(t.upsertContent).toHaveBeenCalledTimes(2)+ })++ it('coalesces rapid saves of the same snippet into one persist', async () => {+ const t = setup({ snippets: { 'snippet-1': makeStateSnippet() } })++ t.mechanism.saveSnippet({ id: 'snippet-1', projectRef: 'ref', shouldInvalidate: false })+ t.mechanism.saveSnippet({ id: 'snippet-1', projectRef: 'ref', shouldInvalidate: false })+ t.mechanism.saveSnippet({ id: 'snippet-1', projectRef: 'ref', shouldInvalidate: false })+ await vi.runAllTimersAsync()++ expect(t.upsertContent).toHaveBeenCalledTimes(1)+ })+})++describe('save mechanism — createFolder', () => {+ it('persists a new folder and swaps the local placeholder for it', async () => {+ const t = setup({+ folders: {+ 'local-1': {+ projectRef: 'ref',+ status: 'new_editing',+ folder: makeFolder('local-1', ''),+ },+ },+ })++ await t.mechanism.createFolder({+ projectRef: 'ref',+ name: 'My Folder',+ placeholderId: 'local-1',+ })++ expect(t.createSQLSnippetFolder).toHaveBeenCalledWith({ projectRef: 'ref', name: 'My Folder' })+ expect(t.state.removeFolder).toHaveBeenCalledWith('local-1')+ expect(t.state.folders['real-id']).toMatchObject({ status: 'idle', folder: { id: 'real-id' } })+ expect(t.notify.success).toHaveBeenCalled()+ })++ it('rolls back the placeholder when creation fails', async () => {+ const t = setup({+ folders: {+ 'local-1': {+ projectRef: 'ref',+ status: 'new_saving',+ folder: makeFolder('local-1', ''),+ },+ },+ })+ t.createSQLSnippetFolder.mockRejectedValueOnce(new Error('boom'))++ await t.mechanism.createFolder({+ projectRef: 'ref',+ name: 'My Folder',+ placeholderId: 'local-1',+ })++ expect(t.state.removeFolder).toHaveBeenCalledWith('local-1')+ expect(t.notify.error).toHaveBeenCalled()+ })+})++describe('save mechanism — updateFolder', () => {+ it('renames an existing folder and resets its status to idle', async () => {+ const t = setup({+ folders: { f1: { projectRef: 'ref', status: 'saving', folder: makeFolder('f1', 'Old') } },+ })++ await t.mechanism.updateFolder({ id: 'f1', projectRef: 'ref', name: 'New' })++ expect(t.updateSQLSnippetFolder).toHaveBeenCalledWith({+ projectRef: 'ref',+ id: 'f1',+ name: 'New',+ })+ expect(t.state.folders['f1']!.status).toBe('idle')+ expect(t.notify.success).toHaveBeenCalled()+ })++ it("rolls the name back to the folder's own previousName when the rename fails", async () => {+ const t = setup({+ folders: {+ f1: {+ projectRef: 'ref',+ status: 'saving',+ folder: makeFolder('f1', 'New'),+ previousName: 'Old',+ },+ },+ })+ t.updateSQLSnippetFolder.mockRejectedValueOnce(new Error('boom'))++ await t.mechanism.updateFolder({ id: 'f1', projectRef: 'ref', name: 'New' })++ expect(t.state.folders['f1']!.folder.name).toBe('Old')+ expect(t.state.folders['f1']!.status).toBe('idle')+ expect(t.state.folders['f1']!.previousName).toBeUndefined()+ })++ it('clears previousName on a successful rename', async () => {+ const t = setup({+ folders: {+ f1: {+ projectRef: 'ref',+ status: 'saving',+ folder: makeFolder('f1', 'New'),+ previousName: 'Old',+ },+ },+ })++ await t.mechanism.updateFolder({ id: 'f1', projectRef: 'ref', name: 'New' })++ expect(t.state.folders['f1']!.previousName).toBeUndefined()+ })++ it('rolls back each folder to its own previousName when concurrent renames fail', async () => {+ const t = setup({+ folders: {+ a: {+ projectRef: 'ref',+ status: 'saving',+ folder: makeFolder('a', 'A-new'),+ previousName: 'A-old',+ },+ b: {+ projectRef: 'ref',+ status: 'saving',+ folder: makeFolder('b', 'B-new'),+ previousName: 'B-old',+ },+ },+ })+ t.updateSQLSnippetFolder.mockRejectedValue(new Error('boom'))++ // Both renames in flight at once; each must restore its own previous name.+ await Promise.all([+ t.mechanism.updateFolder({ id: 'a', projectRef: 'ref', name: 'A-new' }),+ t.mechanism.updateFolder({ id: 'b', projectRef: 'ref', name: 'B-new' }),+ ])++ expect(t.state.folders['a']!.folder.name).toBe('A-old')+ expect(t.state.folders['b']!.folder.name).toBe('B-old')+ })+})diff --git a/apps/studio/state/sql-editor/sql-editor-save.ts b/apps/studio/state/sql-editor/sql-editor-save.tsnew file mode 100644index 00000000000..8de522e9615--- /dev/null+++ b/apps/studio/state/sql-editor/sql-editor-save.ts@@ -0,0 +1,151 @@+import { debounce, memoize } from 'lodash'++import { statusOnSaveError, statusOnSaveStart, statusOnSaveSuccess } from './sql-editor-lifecycle'+import { buildUpsertPayload, isLoadedSnippet } from './sql-editor-rules'+import type { StateSnippet, StateSnippetFolder } from './types'+import type { UpsertContentPayload } from '@/data/content/content-upsert-mutation'+import type { SnippetFolder } from '@/data/content/sql-folders-query'+import { getErrorMessage } from '@/lib/get-error-message'+import type { Notifier } from '@/lib/notifier'++const GENERIC_ERROR_MESSAGE = 'an unexpected error occurred'++/**+ * The slice of the SQL editor store the save mechanism reads from and writes to.+ * Declared structurally (rather than depending on the concrete store) so the+ * mechanism can be exercised in isolation with a plain fake.+ */+export interface SaveMechanismStore {+ snippets: { [id: string]: StateSnippet | undefined }+ folders: { [id: string]: StateSnippetFolder | undefined }+ removeFolder: (id: string) => void+}++export interface SaveMechanismDeps {+ state: SaveMechanismStore+ upsertContent: (vars: { projectRef: string; payload: UpsertContentPayload }) => Promise<unknown>+ createSQLSnippetFolder: (vars: { projectRef: string; name: string }) => Promise<SnippetFolder>+ updateSQLSnippetFolder: (vars: {+ projectRef: string+ id: string+ name: string+ }) => Promise<unknown>+ /** Invalidate the snippet/folder/count lists for a project. */+ invalidate: (projectRef: string) => Promise<void>+ /** Surface success/error toasts. */+ notify: Notifier+ /** Build the upsert payload. Injectable for testing; defaults to buildUpsertPayload. */+ buildPayload?: typeof buildUpsertPayload+ /** Snippet save debounce in ms. Defaults to 1000. */+ debounceMs?: number+}++export interface SaveSnippetArgs {+ id: string+ projectRef: string+ shouldInvalidate: boolean+}++export interface CreateFolderArgs {+ projectRef: string+ name: string+ /** Id of the local placeholder folder to swap for the persisted one. */+ placeholderId: string+}++export interface UpdateFolderArgs {+ id: string+ projectRef: string+ name: string+}++/**+ * The save *mechanism*: it knows how to persist a snippet or folder and how to+ * reflect that in the store (status transitions, list invalidation, folder+ * placeholder swap / rollback). It does NOT decide *when* to save — that policy+ * lives in the store's subscribe today, and moves to a scheduler in a later PR.+ *+ * Dependencies (data-layer calls, query invalidation, notifications, the store,+ * the debounce window) are injected, and the per-snippet debounce cache lives in+ * this factory closure so each instance — and each test — starts clean.+ */+export function createSaveMechanism(deps: SaveMechanismDeps) {+ const {+ state,+ upsertContent,+ createSQLSnippetFolder,+ updateSQLSnippetFolder,+ invalidate,+ notify,+ buildPayload = buildUpsertPayload,+ debounceMs = 1000,+ } = deps++ async function saveSnippet({ id, projectRef, shouldInvalidate }: SaveSnippetArgs) {+ 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++ const payload = buildPayload(snippet, id)+ try {+ snippet.status = statusOnSaveStart(snippet.status)+ await upsertContent({ projectRef, payload })+ if (shouldInvalidate) await invalidate(projectRef)+ snippet.status = statusOnSaveSuccess()+ } catch (error) {+ snippet.status = statusOnSaveError(snippet.status)+ }+ }++ const memoizedSaveSnippet = memoize((_id: string) => debounce(saveSnippet, debounceMs))++ /** Debounced per snippet id; rapid edits to one snippet coalesce to one save. */+ function scheduleSaveSnippet(args: SaveSnippetArgs) {+ memoizedSaveSnippet(args.id)(args)+ }++ async function createFolder({ projectRef, name, placeholderId }: CreateFolderArgs) {+ try {+ const folder = await createSQLSnippetFolder({ projectRef, name })+ notify.success('Successfully created folder')+ // Swap the local placeholder for the persisted folder.+ state.removeFolder(placeholderId)+ state.folders[folder.id] = { projectRef, status: 'idle', folder }+ } catch (error: unknown) {+ notify.error(`Failed to save folder: ${getErrorMessage(error) ?? GENERIC_ERROR_MESSAGE}`)+ // Roll back the placeholder — there is no persisted folder to keep.+ state.removeFolder(placeholderId)+ }+ }++ async function updateFolder({ id, projectRef, name }: UpdateFolderArgs) {+ const storeFolder = state.folders[id]+ if (!storeFolder) return++ try {+ await updateSQLSnippetFolder({ projectRef, id, name })+ notify.success('Successfully updated folder')+ } catch (error: unknown) {+ notify.error(`Failed to save folder: ${getErrorMessage(error) ?? GENERIC_ERROR_MESSAGE}`)+ // Roll back the optimistic rename to this folder's own previous name.+ if (storeFolder.previousName !== undefined) {+ storeFolder.folder.name = storeFolder.previousName+ }+ } finally {+ storeFolder.status = 'idle'+ storeFolder.previousName = undefined+ }+ }++ return {+ /** Schedule a debounced save of the snippet with the given id. */+ saveSnippet: scheduleSaveSnippet,+ /** Persist a new folder, swapping out its local placeholder. */+ createFolder,+ /** Persist a folder rename. */+ updateFolder,+ }+}++export type SaveMechanism = ReturnType<typeof createSaveMechanism>diff --git a/apps/studio/state/sql-editor/sql-editor-state.ts b/apps/studio/state/sql-editor/sql-editor-state.tsindex 4117aa2021a..975b057bc3d 100644--- a/apps/studio/state/sql-editor/sql-editor-state.ts+++ b/apps/studio/state/sql-editor/sql-editor-state.ts@@ -1,16 +1,16 @@import { untrustedSql } from '@supabase/pg-meta'-import { debounce, memoize } from 'lodash'import { useMemo } from 'react'import { toast } from 'sonner'import { proxy, ref, snapshot, subscribe, useSnapshot } from 'valtio'import { devtools, proxyMap } from 'valtio/utils'-import { statusOnSaveError, statusOnSaveStart, statusOnSaveSuccess } from './sql-editor-lifecycle'-import { buildUpsertPayload, isLoadedSnippet, validateMoveToFolder } from './sql-editor-rules'+import { folderStatusOnSaveStart, isNewFolder } from './sql-editor-lifecycle'+import { validateMoveToFolder } from './sql-editor-rules'+import { createSaveMechanism } from './sql-editor-save'import type { StateSnippet, StateSnippetFolder } from './types'import type { QueryPlanRow } from '@/components/interfaces/ExplainVisualizer/ExplainVisualizer.types'import { DiffType } from '@/components/interfaces/SQLEditor/SQLEditor.types'-import { upsertContent, UpsertContentPayload } from '@/data/content/content-upsert-mutation'+import { upsertContent } from '@/data/content/content-upsert-mutation'import { contentKeys } from '@/data/content/keys'import { createSQLSnippetFolder } from '@/data/content/sql-folder-create-mutation'import { updateSQLSnippetFolder } from '@/data/content/sql-folder-update-mutation'@@ -18,8 +18,6 @@ import type { SnippetWithContent } from '@/data/content/sql-folders-query'import { Snippet, SnippetFolder } from '@/data/content/sql-folders-query'import { getQueryClient } from '@/data/query-client'-const NEW_FOLDER_ID = 'new-folder'-export const sqlEditorState = proxy({// ========================================================================// ## Data properties within the store@@ -73,11 +71,6 @@ export const sqlEditorState = proxy({*/limit: 100,- /**- * Used for error handling after optimistical rendering from renaming a folder- */- lastUpdatedFolderName: '',-/*** For Assistant to render diffing into the editor*/@@ -204,18 +197,19 @@ export const sqlEditorState = proxy({*/addFolder: ({ projectRef, folder }: { projectRef: string; folder: SnippetFolder }) => {if (sqlEditorState.folders[folder.id]) return- sqlEditorState.folders[folder.id] = { projectRef, folder }+ sqlEditorState.folders[folder.id] = { projectRef, status: 'idle', folder }},/**- * Adds a new folder placeholder for the UI to render+ * Adds a new folder placeholder for the UI to render. The placeholder gets a+ * unique local id and `status: 'new_editing'` to mark it as not-yet-persisted+ * (the status, not the id, is what tags it as new).*/addNewFolder: ({ projectRef }: { projectRef: string }) => {- // [Joshen] Use this to identify new folders that have yet to be saved- const id = NEW_FOLDER_ID+ const id = crypto.randomUUID()sqlEditorState.folders[id] = {projectRef,- status: 'editing',+ status: 'new_editing',folder: {id,name: '',@@ -227,7 +221,10 @@ export const sqlEditorState = proxy({},editFolder: (id: string) => {- sqlEditorState.folders[id].status = 'editing'+ const storeFolder = sqlEditorState.folders[id]+ if (storeFolder) {+ storeFolder.status = isNewFolder(storeFolder.status) ? 'new_editing' : 'editing'+ }},/**@@ -235,11 +232,11 @@ export const sqlEditorState = proxy({*/saveFolder: ({ id, name }: { id: string; name: string }) => {let storeFolder = sqlEditorState.folders[id]- const isNewFolder = id === 'new-folder'+ const isNew = isNewFolder(storeFolder.status)const hasChanges = storeFolder.folder.name !== nameconst folderNameTaken = sqlEditorState.allFolderNames.includes(name)- if (isNewFolder && folderNameTaken) {+ if (isNew && folderNameTaken) {sqlEditorState.removeFolder(id)return toast.error('Unable to create new folder: This folder name already exists')} else if (hasChanges && folderNameTaken) {@@ -249,12 +246,13 @@ export const sqlEditorState = proxy({const originalFolderName = storeFolder.folder.name.slice()- storeFolder.status = hasChanges ? 'saving' : 'idle'+ storeFolder.status = hasChanges ? folderStatusOnSaveStart(storeFolder.status) : 'idle'storeFolder.folder.id = idstoreFolder.folder.name = nameif (hasChanges) {- sqlEditorState.lastUpdatedFolderName = originalFolderName+ // Remember this folder's own pre-rename name so a failed save can roll back.+ storeFolder.previousName = originalFolderNamesqlEditorState.needsSaving.set(id, true)}},@@ -376,70 +374,24 @@ export const useSnippets = (projectRef: string) => {// ## Below are all the asynchronous saving logic for the SQL Editor// ========================================================================-async function upsertSnippet(- id: string,- projectRef: string,- payload: UpsertContentPayload,- shouldInvalidate = false-) {- const snippet = sqlEditorState.snippets[id]?.snippet- try {- if (snippet) snippet.status = statusOnSaveStart(snippet.status)- await upsertContent({ projectRef, payload })-- if (shouldInvalidate) {- const queryClient = getQueryClient()- await Promise.all([- queryClient.invalidateQueries({ queryKey: contentKeys.count(projectRef, 'sql') }),- queryClient.invalidateQueries({ queryKey: contentKeys.sqlSnippets(projectRef) }),- queryClient.invalidateQueries({ queryKey: contentKeys.folders(projectRef) }),- ])- }-- if (snippet) snippet.status = statusOnSaveSuccess()- } catch (error) {- if (snippet) snippet.status = statusOnSaveError(snippet.status)- }-}--const memoizedUpsertSnippet = memoize((_id: string) => debounce(upsertSnippet, 1000))--const debouncedUpdateSnippet = (- id: string,- projectRef: string,- payload: UpsertContentPayload,- shouldInvalidate = false-) => memoizedUpsertSnippet(id)(id, projectRef, payload, shouldInvalidate)--async function upsertFolder(id: string, projectRef: string, name: string) {- try {- if (id === NEW_FOLDER_ID) {- const res = await createSQLSnippetFolder({ projectRef, name })- toast.success('Successfully created folder')- sqlEditorState.removeFolder(NEW_FOLDER_ID)- sqlEditorState.folders[res.id] = { projectRef, status: 'idle', folder: res }- } else {- await updateSQLSnippetFolder({ projectRef, id, name })- toast.success('Successfully updated folder')- sqlEditorState.folders[id].status = 'idle'- }- } catch (error: any) {- toast.error(`Failed to save folder: ${error.message}`)- if (error.message.includes('create')) {- sqlEditorState.removeFolder(id)- } else if (- error.message.includes('update') &&- sqlEditorState.lastUpdatedFolderName.length > 0- ) {- let storeFolder = sqlEditorState.folders[id]-- storeFolder.status = 'idle'- storeFolder.folder.name = sqlEditorState.lastUpdatedFolderName- }- } finally {- sqlEditorState.lastUpdatedFolderName = ''- }-}+// The save mechanism owns how snippets/folders are persisted. Its data-layer+// collaborators and query invalidation are injected here; the subscribe below+// decides what to enqueue. (The enqueue policy moves to a scheduler in a later PR.)+const saveMechanism = createSaveMechanism({+ state: sqlEditorState,+ upsertContent,+ createSQLSnippetFolder,+ updateSQLSnippetFolder,+ notify: toast,+ invalidate: async (projectRef: string) => {+ const queryClient = getQueryClient()+ await Promise.all([+ queryClient.invalidateQueries({ queryKey: contentKeys.count(projectRef, 'sql') }),+ queryClient.invalidateQueries({ queryKey: contentKeys.sqlSnippets(projectRef) }),+ queryClient.invalidateQueries({ queryKey: contentKeys.folders(projectRef) }),+ ])+ },+})if (typeof window !== 'undefined') {devtools(sqlEditorState, {@@ -461,17 +413,17 @@ if (typeof window !== 'undefined') {if (!result.ok) {toast.error(result.error)- } else if (isLoadedSnippet(snippet.snippet)) {- debouncedUpdateSnippet(- id,- snippet.projectRef,- buildUpsertPayload(snippet.snippet, id),- shouldInvalidate- )+ } else {+ saveMechanism.saveSnippet({ id, projectRef: snippet.projectRef, shouldInvalidate })sqlEditorState.needsSaving.delete(id)}} else if (folder) {- upsertFolder(id, folder.projectRef, folder.folder.name)+ const { projectRef, folder: folderData, status } = folder+ if (isNewFolder(status)) {+ saveMechanism.createFolder({ projectRef, name: folderData.name, placeholderId: id })+ } else {+ saveMechanism.updateFolder({ id, projectRef, name: folderData.name })+ }sqlEditorState.needsSaving.delete(id)}})diff --git a/apps/studio/state/sql-editor/types.ts b/apps/studio/state/sql-editor/types.tsindex 31879c71dce..77b194acaeb 100644--- a/apps/studio/state/sql-editor/types.ts+++ b/apps/studio/state/sql-editor/types.ts@@ -1,9 +1,17 @@+import type { FolderStatus } from './sql-editor-lifecycle'import type { SnippetFolder, SnippetWithContent } from '@/data/content/sql-folders-query'export type StateSnippetFolder = {projectRef: stringfolder: SnippetFolder- status?: 'editing' | 'saving' | 'idle'+ status: FolderStatus+ /**+ * The name to restore if an in-flight rename fails. Set while a rename is+ * saving and cleared once it settles. Stored per-folder (rather than as one+ * shared field) so concurrent renames of different folders can't clobber each+ * other's rollback target.+ */+ previousName?: string}export type StateSnippet = {