The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
fix(studio): keep the new SQL editor tab from being pruned on first keystroke (#48956)
Charis4ca17a23cee3
diff --git a/apps/studio/components/interfaces/SQLEditor/useSnippetEditor.test.tsx b/apps/studio/components/interfaces/SQLEditor/useSnippetEditor.test.tsxnew file mode 100644index 00000000000..bda651b7312--- /dev/null+++ b/apps/studio/components/interfaces/SQLEditor/useSnippetEditor.test.tsx@@ -0,0 +1,56 @@+import { act, waitFor } from '@testing-library/react'+import { beforeEach, describe, expect, it } from 'vitest'++import { useSnippetEditor } from './useSnippetEditor'+import { sqlEditorState } from '@/state/sql-editor/sql-editor-state'+import { createMockProfileContext } from '@/tests/lib/profile-helpers'+import {+ renderSqlEditorHook,+ resetSqlEditorStores,+ seedSnippet,+ setupSqlEditorMocks,+} from '@/tests/lib/sql-editor-test-utils'++const PROFILE_CONTEXT = createMockProfileContext()++describe('useSnippetEditor', () => {+ beforeEach(() => {+ resetSqlEditorStores()+ setupSqlEditorMocks()+ })++ it('writing in a newly opened tab does not overwrite an already-open tab', async () => {+ seedSnippet({ id: 'existing-tab', sql: 'select existing;' })++ // Mount the editor for the already-open tab, mirroring the keyed+ // MonacoEditor mount for that snippet id, then unmount it the way opening+ // a new tab would (the `key={id}` wrapper swaps to a brand new instance).+ const first = renderSqlEditorHook(useSnippetEditor, {+ initialProps: { id: 'existing-tab', snippetName: 'Existing tab' },+ profileContext: PROFILE_CONTEXT,+ })+ await waitFor(() => expect(first.result.current.snippet).toBeDefined())+ first.unmount()++ // Mount a fresh instance for a brand new tab, as clicking "+" would.+ const second = renderSqlEditorHook(useSnippetEditor, {+ initialProps: { id: 'new-tab-id', snippetName: 'New query' },+ profileContext: PROFILE_CONTEXT,+ })++ // `handleEditorChange` only creates the new snippet once the project has+ // loaded, so retry the keystroke until that happens.+ await waitFor(() => {+ act(() => {+ second.result.current.handleEditorChange('select typed content;')+ })+ expect(sqlEditorState.snippets['new-tab-id']?.snippet.content?.unchecked_sql).toContain(+ 'typed content'+ )+ })++ expect(sqlEditorState.snippets['existing-tab'].snippet.content?.unchecked_sql).toContain(+ 'select existing'+ )+ })+})diff --git a/apps/studio/components/interfaces/SQLEditor/useSnippetIdentity.route-change.test.tsx b/apps/studio/components/interfaces/SQLEditor/useSnippetIdentity.route-change.test.tsxnew file mode 100644index 00000000000..a428fdbe633--- /dev/null+++ b/apps/studio/components/interfaces/SQLEditor/useSnippetIdentity.route-change.test.tsx@@ -0,0 +1,59 @@+import { act, waitFor } from '@testing-library/react'+import mockRouter from 'next-router-mock'+import { beforeEach, describe, expect, it, vi } from 'vitest'++import { useSnippetIdentity } from './useSnippetIdentity'+import {+ renderSqlEditorHook,+ resetSqlEditorStores,+ seedSnippet,+} from '@/tests/lib/sql-editor-test-utils'++// `common`'s `useParams` is globally stubbed (see tests/vitestSetup.ts) to a+// constant `{ ref: 'default' }` so most tests don't have to think about+// routing. This suite is specifically about behavior across route changes, so+// it swaps in the real implementation (still backed by the `next-router-mock`+// router the rest of the app is wired to in tests).+vi.mock('common', async (importOriginal) => {+ const actual = (await importOriginal()) as object+ return { ...actual }+})++describe('useSnippetIdentity across route changes', () => {+ beforeEach(() => {+ resetSqlEditorStores()+ mockRouter.setCurrentUrl('/project/default/sql/existing-tab')+ })++ it('generates a fresh id for each new tab, never reusing the previous one', async () => {+ seedSnippet({ id: 'existing-tab', sql: 'select existing;' })++ const { result } = renderSqlEditorHook(useSnippetIdentity)++ await waitFor(() => expect(result.current.id).toEqual('existing-tab'))++ // Click "+" to open a new tab.+ await act(async () => {+ await mockRouter.push('/project/default/sql/new?skip=true')+ })+ const firstNewTabId = result.current.id+ expect(firstNewTabId).not.toEqual('existing-tab')++ // Typing in the new tab creates its snippet and shallow-navigates to it+ // (mirrors the `router.push` inside `useSnippetEditor.handleEditorChange`).+ seedSnippet({ id: firstNewTabId, sql: 'select typed content;' })+ await act(async () => {+ await mockRouter.push(`/project/default/sql/${firstNewTabId}`)+ })+ await waitFor(() => expect(result.current.id).toEqual(firstNewTabId))++ // Click "+" again to open a second new tab.+ await act(async () => {+ await mockRouter.push('/project/default/sql/new?skip=true')+ })+ const secondNewTabId = result.current.id++ expect(secondNewTabId).not.toEqual(firstNewTabId)+ expect(secondNewTabId).not.toEqual('existing-tab')+ })+})diff --git a/apps/studio/components/layouts/Tabs/Tabs.utils.test.tsx b/apps/studio/components/layouts/Tabs/Tabs.utils.test.tsxindex 8bb69423320..a89fd1bdfb0 100644--- a/apps/studio/components/layouts/Tabs/Tabs.utils.test.tsx+++ b/apps/studio/components/layouts/Tabs/Tabs.utils.test.tsx@@ -1,9 +1,11 @@import { act, renderHook } from '@testing-library/react'import type { ReactNode } from 'react'-import { describe, expect, it } from 'vitest'+import { afterEach, describe, expect, it } from 'vitest'import { useSqlEditorTabsCleanup } from './Tabs.utils'+import { sqlEditorState } from '@/state/sql-editor/sql-editor-state'import { createTabsState, TabsStateContext, type Tab } from '@/state/tabs'+import { seedSnippet } from '@/tests/lib/sql-editor-test-utils'const dbTab = (id: string): Tab => ({id: `sql-${id}`,@@ -29,6 +31,28 @@ function renderCleanup(store: ReturnType<typeof createTabsState>) {}describe('useSqlEditorTabsCleanup', () => {+ afterEach(() => {+ for (const key of Object.keys(sqlEditorState.snippets)) delete sqlEditorState.snippets[key]+ })++ it('keeps the tab of a locally-created snippet that has not been persisted yet', () => {+ const store = createTabsState('default')+ store.addTab(dbTab('existing'))+ store.addTab(dbTab('brand-new'))++ // A snippet created by typing in a new tab: it lives in the local store with+ // a never-persisted status, but the server-fetched snippet list can't know+ // about it yet.+ seedSnippet({ id: 'brand-new', name: 'Untitled query', sql: 'select 1;' })++ const cleanup = renderCleanup(store)+ act(() => cleanup({ snippets: [{ id: 'existing', type: 'sql', name: 'existing' }] }))++ expect(store.tabsMap['sql-brand-new']).toBeDefined()+ expect(store.openTabs).toContain('sql-brand-new')+ expect(store.activeTab).toEqual('sql-brand-new')+ })+it('prunes tabs for deleted snippets (database and logs) while keeping live ones', () => {const store = createTabsState('default')store.addTab(dbTab('db-stale'))diff --git a/apps/studio/components/layouts/Tabs/Tabs.utils.ts b/apps/studio/components/layouts/Tabs/Tabs.utils.tsindex ad95bf40784..4cfec12f325 100644--- a/apps/studio/components/layouts/Tabs/Tabs.utils.ts+++ b/apps/studio/components/layouts/Tabs/Tabs.utils.ts@@ -2,6 +2,8 @@ import { useCallback, useEffect, useRef } from 'react'import { Entity } from '@/data/entity-types/entity-types-infinite-query'import { useLatest } from '@/hooks/misc/useLatest'+import { wasNeverPersisted } from '@/state/sql-editor/sql-editor-lifecycle'+import { getSqlEditorV2StateSnapshot } from '@/state/sql-editor/sql-editor-state'import { createTabId, editorEntityTypes, useTabsStateSnapshot } from '@/state/tabs'export function useTableEditorTabsCleanUp() {@@ -91,9 +93,20 @@ export function useSqlEditorTabsCleanup() {...IGNORED_TAB_IDS,]+ // A snippet created during this session (by typing in a new tab) exists only+ // in the local store until its first save lands, so the server-fetched list+ // legitimately doesn't contain it yet. Without this, invalidating the snippet+ // lists on that first keystroke prunes the tab that was just opened — the URL+ // and editor stay on the new snippet while the tab bar falls back to whichever+ // tab was open before, making it look like the previous tab is being edited.+ const localSnippets = getSqlEditorV2StateSnapshot().snippets+ const isUnpersistedLocalSnippet = (sqlId: string | undefined) =>+ sqlId !== undefined && wasNeverPersisted(localSnippets[sqlId]?.snippet.status)+const isPrunable = (id: string) =>id.startsWith('sql') &&!currentContentIds.includes(id) &&+ !isUnpersistedLocalSnippet(tabMapRef.current[id]?.metadata?.sqlId) &&(canPruneLogsTabs || tabMapRef.current[id]?.metadata?.sqlSource !== 'logs')// Remove any snippet tabs that might no longer be existing (removed outside of the dashboard session)@@ -108,6 +121,7 @@ export function useSqlEditorTabsCleanup() {.filter((item) =>!currentContentIds.includes(item.id) &&+ !isUnpersistedLocalSnippet(item.metadata?.sqlId) &&(canPruneLogsTabs || item.metadata?.sqlSource !== 'logs')).map((item) => item.id)