Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

refactor(studio): extract notebook cache eviction helper (#49414)

Charis48cc37f0d254
diff --git a/apps/studio/components/interfaces/Explorer/ExplorerNotebookTabCoordinator.tsx b/apps/studio/components/interfaces/Explorer/ExplorerNotebookTabCoordinator.tsx
index ee7337f0889..63a15562aa8 100644
--- a/apps/studio/components/interfaces/Explorer/ExplorerNotebookTabCoordinator.tsx
+++ b/apps/studio/components/interfaces/Explorer/ExplorerNotebookTabCoordinator.tsx
@@ -2,21 +2,18 @@ import { useQueryClient } from '@tanstack/react-query'
import { useParams } from 'common'
import { useContext, useEffect } from 'react'
-import { contentKeys } from '@/data/content/keys'
+import {
+ evictNotebookFromCaches,
+ hasDiscardableChanges,
+} from '@/data/content/notebooks/notebook-cache'
import { notebooksState, useNotebooksStateSnapshot } from '@/state/notebooks/notebooks-state'
-import { hasUnsavedChanges } from '@/state/sql-editor/sql-editor-lifecycle'
import { TabsStateContext, type Tab } from '@/state/tabs'
const NotebookTabStatusIndicator = ({ tab }: { tab: Tab }) => {
const notebooksSnap = useNotebooksStateSnapshot()
const notebookId = tab.metadata?.notebookId
const stateNotebook = notebookId ? notebooksSnap.notebooks[notebookId] : undefined
- if (!hasUnsavedChanges(stateNotebook?.status)) return null
-
- // A never-persisted notebook with no cells has nothing worth flagging as unsaved.
- const isEmptyNewNotebook =
- stateNotebook?.status === 'new' && (stateNotebook.notebook.content?.cells.length ?? 0) === 0
- if (isEmptyNewNotebook) return null
+ if (!hasDiscardableChanges(stateNotebook)) return null
return (
<span
@@ -44,26 +41,14 @@ export const ExplorerNotebookTabCoordinator = () => {
const notebookId = tab.metadata?.notebookId
if (!ref || !notebookId) return
- if (notebooksState.notebooks[notebookId]) {
- notebooksState.removeNotebook({ id: notebookId })
- }
-
- notebooksState.removeNotebook({ id: notebookId })
- queryClient.removeQueries({ queryKey: contentKeys.resource(ref, notebookId) })
+ evictNotebookFromCaches({ queryClient, projectRef: ref, id: notebookId, mode: 'remove' })
},
confirmClose: (notebookTabs) => {
const dirtyCount = notebookTabs.filter((tab) => {
const notebookId = tab.metadata?.notebookId
if (!notebookId) return false
- const stateNotebook = notebooksState.notebooks[notebookId]
- if (!hasUnsavedChanges(stateNotebook?.status)) return false
-
- // A never-persisted notebook with no cells has nothing worth confirming before discarding.
- const isEmptyNewNotebook =
- stateNotebook?.status === 'new' &&
- (stateNotebook.notebook.content?.cells.length ?? 0) === 0
- return !isEmptyNewNotebook
+ return hasDiscardableChanges(notebooksState.notebooks[notebookId])
}).length
if (dirtyCount === 0) return null
diff --git a/apps/studio/data/content/notebooks/notebook-cache.test.ts b/apps/studio/data/content/notebooks/notebook-cache.test.ts
new file mode 100644
index 00000000000..6e95ffbdd84
--- /dev/null
+++ b/apps/studio/data/content/notebooks/notebook-cache.test.ts
@@ -0,0 +1,112 @@
+import { QueryClient } from '@tanstack/react-query'
+import { afterEach, describe, expect, it } from 'vitest'
+
+import { evictNotebookFromCaches } from './notebook-cache'
+import { contentKeys } from '@/data/content/keys'
+import { notebooksState } from '@/state/notebooks/notebooks-state'
+import type { Notebook } from '@/state/notebooks/types'
+
+const PROJECT_REF = 'default'
+const NOTEBOOK_ID = 'notebook-cache-test'
+
+const NOTEBOOK: Notebook = {
+ id: NOTEBOOK_ID,
+ type: 'notebook',
+ name: 'Test notebook',
+ visibility: 'project',
+ favorite: false,
+ owner_id: 1,
+ project_id: 1,
+ content: { schema_version: 1, cells: [] },
+}
+
+const seedNotebook = (status: 'new' | 'saved') => {
+ delete notebooksState.notebooks[NOTEBOOK_ID]
+ if (status === 'new') {
+ notebooksState.addNotebook({ projectRef: PROJECT_REF, notebook: NOTEBOOK })
+ } else {
+ notebooksState.setNotebook({ projectRef: PROJECT_REF, notebook: NOTEBOOK })
+ }
+}
+
+const seedQueryData = (queryClient: QueryClient) =>
+ queryClient.setQueryData(contentKeys.resource(PROJECT_REF, NOTEBOOK_ID), { id: NOTEBOOK_ID })
+
+afterEach(() => {
+ delete notebooksState.notebooks[NOTEBOOK_ID]
+ notebooksState.needsSaving.clear()
+})
+
+describe('evictNotebookFromCaches', () => {
+ it('removes a saved notebook from the store and invalidates its cache entry in "refresh" mode', async () => {
+ seedNotebook('saved')
+ const queryClient = new QueryClient()
+ seedQueryData(queryClient)
+
+ const evicted = await evictNotebookFromCaches({
+ queryClient,
+ projectRef: PROJECT_REF,
+ id: NOTEBOOK_ID,
+ mode: 'refresh',
+ })
+
+ expect(evicted).toBe(true)
+ expect(notebooksState.notebooks[NOTEBOOK_ID]).toBeUndefined()
+ expect(
+ queryClient.getQueryState(contentKeys.resource(PROJECT_REF, NOTEBOOK_ID))?.isInvalidated
+ ).toBe(true)
+ })
+
+ it('removes a saved notebook from the store and drops its cache entry in "remove" mode', async () => {
+ seedNotebook('saved')
+ const queryClient = new QueryClient()
+ seedQueryData(queryClient)
+
+ const evicted = await evictNotebookFromCaches({
+ queryClient,
+ projectRef: PROJECT_REF,
+ id: NOTEBOOK_ID,
+ mode: 'remove',
+ })
+
+ expect(evicted).toBe(true)
+ expect(notebooksState.notebooks[NOTEBOOK_ID]).toBeUndefined()
+ expect(queryClient.getQueryData(contentKeys.resource(PROJECT_REF, NOTEBOOK_ID))).toBeUndefined()
+ })
+
+ it('leaves an unsaved notebook and its cache entry untouched', async () => {
+ seedNotebook('new')
+ const queryClient = new QueryClient()
+ seedQueryData(queryClient)
+
+ const evicted = await evictNotebookFromCaches({
+ queryClient,
+ projectRef: PROJECT_REF,
+ id: NOTEBOOK_ID,
+ mode: 'remove',
+ })
+
+ expect(evicted).toBe(false)
+ expect(notebooksState.notebooks[NOTEBOOK_ID]).toBeDefined()
+ expect(queryClient.getQueryData(contentKeys.resource(PROJECT_REF, NOTEBOOK_ID))).toEqual({
+ id: NOTEBOOK_ID,
+ })
+ })
+
+ it('no-ops for an id not present in the store', async () => {
+ const queryClient = new QueryClient()
+ seedQueryData(queryClient)
+
+ const evicted = await evictNotebookFromCaches({
+ queryClient,
+ projectRef: PROJECT_REF,
+ id: NOTEBOOK_ID,
+ mode: 'remove',
+ })
+
+ expect(evicted).toBe(false)
+ expect(queryClient.getQueryData(contentKeys.resource(PROJECT_REF, NOTEBOOK_ID))).toEqual({
+ id: NOTEBOOK_ID,
+ })
+ })
+})
diff --git a/apps/studio/data/content/notebooks/notebook-cache.ts b/apps/studio/data/content/notebooks/notebook-cache.ts
new file mode 100644
index 00000000000..3ad97128b15
--- /dev/null
+++ b/apps/studio/data/content/notebooks/notebook-cache.ts
@@ -0,0 +1,59 @@
+import type { QueryClient } from '@tanstack/react-query'
+import type { Snapshot } from 'valtio'
+
+import { contentKeys } from '@/data/content/keys'
+import { notebooksState } from '@/state/notebooks/notebooks-state'
+import type { StateNotebook } from '@/state/notebooks/types'
+import { hasUnsavedChanges } from '@/state/sql-editor/sql-editor-lifecycle'
+
+export type NotebookCacheEvictionMode = 'refresh' | 'remove'
+
+/**
+ * Whether a notebook has edits worth discarding on close: anything not yet
+ * saved, except a never-persisted notebook that's still empty (nothing to
+ * lose by closing it).
+ */
+export function hasDiscardableChanges(
+ stateNotebook: StateNotebook | Snapshot<StateNotebook> | undefined
+): boolean {
+ if (!hasUnsavedChanges(stateNotebook?.status)) return false
+
+ const isEmptyNewNotebook =
+ stateNotebook?.status === 'new' && (stateNotebook.notebook.content?.cells.length ?? 0) === 0
+ return !isEmptyNewNotebook
+}
+
+/**
+ * Evicts a notebook from the React Query cache and the Valtio store together.
+ * Applies to a persisted notebook (always safe to refetch) and to a dirty
+ * unsaved notebook (safe once the caller has confirmed discarding it).
+ *
+ * @returns A boolean indicating whether the notebook was successfully evicted
+ * from the cache.
+ */
+export async function evictNotebookFromCaches({
+ queryClient,
+ projectRef,
+ id,
+ mode,
+}: {
+ queryClient: QueryClient
+ projectRef: string
+ id: string
+ mode: NotebookCacheEvictionMode
+}): Promise<boolean> {
+ const stateNotebook = notebooksState.notebooks[id]
+ const canEvict = stateNotebook?.status === 'saved' || hasDiscardableChanges(stateNotebook)
+ if (!canEvict) return false
+
+ notebooksState.removeNotebook({ id })
+
+ const queryKey = contentKeys.resource(projectRef, id)
+ if (mode === 'remove') {
+ queryClient.removeQueries({ queryKey })
+ } else {
+ await queryClient.invalidateQueries({ queryKey })
+ }
+
+ return true
+}