Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
chore: persist explore mode tab in local storage (#21218)
ecmadao8bc24d06dbc1
diff --git a/frontend/src/hooks/useExecuteSQL.ts b/frontend/src/hooks/useExecuteSQL.tsindex 9134dbb31b..5059b00dff 100644--- a/frontend/src/hooks/useExecuteSQL.ts+++ b/frontend/src/hooks/useExecuteSQL.ts@@ -64,7 +64,7 @@ export const useExecuteSQL = () => {};const preflight = useCallback(- async (params: SQLEditorQueryParams) => {+ (params: SQLEditorQueryParams) => {lastQueryTimeRef.current = Date.now();const tabsState = getSQLEditorTabsState();@@ -136,31 +136,31 @@ export const useExecuteSQL = () => {};const preExecute = useCallback(- async (params: SQLEditorQueryParams) => {+ async (params: SQLEditorQueryParams): Promise<boolean> => {const now = Date.now();if (lastQueryTimeRef.current &&now - lastQueryTimeRef.current < QUERY_INTERVAL_LIMIT) {- return;+ return false;}const tabsState = getSQLEditorTabsState();const tab = tabsState.tabsById.get(tabsState.currentTabId);if (!tab) {- return;+ return false;}const { mode } = tab;if (mode === "ADMIN") {- return;+ return false;}if (!preflight(params)) {- return;+ return false;}if (!isValidDatabaseName(params.connection.database)) {- return;+ return false;}// Re-read the tab after preflight, which may have initialized@@ -168,7 +168,7 @@ export const useExecuteSQL = () => {const freshState = getSQLEditorTabsState();const freshTab = freshState.tabsById.get(freshState.currentTabId);if (!freshTab) {- return;+ return false;}const existingContexts: Map<string, SQLEditorDatabaseQueryContext[]> =freshTab.databaseQueryContexts ?? new Map();@@ -235,6 +235,7 @@ export const useExecuteSQL = () => {.getState().batchGetOrFetchDatabases([...batchQueryDatabaseSet.keys()]);+ let accepted = false;for (const databaseName of batchQueryDatabaseSet.values()) {// Re-read the latest tab snapshot inside the loop so each// iteration sees the prior iteration's writes.@@ -281,7 +282,9 @@ export const useExecuteSQL = () => {const nextMap = new Map(currentMap);nextMap.set(databaseName, [context, ...trimmedList]);loopState.updateTab(loopTab.id, { databaseQueryContexts: nextMap });+ accepted = true;}+ return accepted;},[preflight]);diff --git a/frontend/src/modules/sql-editor/components/DataExplorer/DataExplorerPanel.test.tsx b/frontend/src/modules/sql-editor/components/DataExplorer/DataExplorerPanel.test.tsxindex fc7d2b1837..23fc53e5df 100644--- a/frontend/src/modules/sql-editor/components/DataExplorer/DataExplorerPanel.test.tsx+++ b/frontend/src/modules/sql-editor/components/DataExplorer/DataExplorerPanel.test.tsx@@ -14,19 +14,28 @@ const mocks = vi.hoisted(() => {table: "users",},editorState: { selection: null },- dataExplorer: { filter: "", initialized: false },+ dataExplorer: {+ filter: "",+ initialized: false,+ selectedRowKey: undefined,+ } as {+ filter: string;+ initialized: boolean;+ selectedRowKey?: number;+ },databaseQueryContexts: new Map(),};return {tab,engine: 23 as Engine,resultRowsLimit: 500,- execute: vi.fn().mockResolvedValue(undefined),+ execute: vi.fn().mockResolvedValue(true),updateTab: vi.fn((_: string, patch: Record<string, unknown>) => {Object.assign(tab, patch);return tab;}),deleteDatabaseQueryContext: vi.fn(),+ batchRemoveDatabaseQueryContext: vi.fn(),};});@@ -64,6 +73,7 @@ vi.mock("@/modules/sql-editor/store/tab", () => {...state,updateTab: mocks.updateTab,deleteDatabaseQueryContext: mocks.deleteDatabaseQueryContext,+ batchRemoveDatabaseQueryContext: mocks.batchRemoveDatabaseQueryContext,}),};});@@ -131,6 +141,70 @@ describe("DataExplorerPanel", () => {});});+ test("keeps the current result when execution is not accepted", async () => {+ const previousContext = { id: "previous", status: "DONE" };+ mocks.tab.dataExplorer = {+ filter: "",+ initialized: true,+ selectedRowKey: 7,+ };+ mocks.tab.databaseQueryContexts = new Map([+ [mocks.tab.connection.database, [previousContext]],+ ]);+ mocks.execute.mockResolvedValueOnce(false);+ render(<DataExplorerPanel />);++ fireEvent.click(+ screen.getByRole("button", { name: /\(limit\s*500\)/ })+ );++ await waitFor(() => {+ expect(mocks.execute).toHaveBeenCalledOnce();+ });+ expect(mocks.deleteDatabaseQueryContext).not.toHaveBeenCalled();+ expect(mocks.batchRemoveDatabaseQueryContext).not.toHaveBeenCalled();+ expect(mocks.tab.dataExplorer.selectedRowKey).toBe(7);+ });++ test("removes the previous result after execution is accepted", async () => {+ let acceptExecution!: (accepted: boolean) => void;+ const previousContext = { id: "previous", status: "DONE" };+ mocks.tab.dataExplorer = {+ filter: "",+ initialized: true,+ selectedRowKey: 7,+ };+ mocks.tab.databaseQueryContexts = new Map([+ [mocks.tab.connection.database, [previousContext]],+ ]);+ mocks.execute.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ acceptExecution = resolve;+ })+ );+ render(<DataExplorerPanel />);++ fireEvent.click(+ screen.getByRole("button", { name: /\(limit\s*500\)/ })+ );++ await waitFor(() => {+ expect(mocks.execute).toHaveBeenCalledOnce();+ });+ expect(mocks.batchRemoveDatabaseQueryContext).not.toHaveBeenCalled();++ acceptExecution(true);+ await waitFor(() => {+ expect(mocks.batchRemoveDatabaseQueryContext).toHaveBeenCalledWith({+ database: mocks.tab.connection.database,+ contextIds: ["previous"],+ });+ });+ expect(mocks.deleteDatabaseQueryContext).not.toHaveBeenCalled();+ expect(mocks.tab.dataExplorer.selectedRowKey).toBeUndefined();+ });+test("builds a qualified relational preview query", async () => {mocks.engine = Engine.POSTGRES;mocks.tab.connection.schema = "public";diff --git a/frontend/src/modules/sql-editor/components/DataExplorer/DataExplorerPanel.tsx b/frontend/src/modules/sql-editor/components/DataExplorer/DataExplorerPanel.tsxindex 216cde8eec..872dc5f911 100644--- a/frontend/src/modules/sql-editor/components/DataExplorer/DataExplorerPanel.tsx+++ b/frontend/src/modules/sql-editor/components/DataExplorer/DataExplorerPanel.tsx@@ -80,17 +80,9 @@ export function DataExplorerPanel() {if (!tab || !statement) return;const tabsState = getSQLEditorTabsState();- for (const existing of tab.databaseQueryContexts?.get(database.name) ??- []) {- existing.abortController?.abort();- }- tabsState.deleteDatabaseQueryContext(database.name);- updateExplorerState({- filter: suffix,- initialized: true,- resetRow: true,- });- await execute({+ const previousContexts =+ tab.databaseQueryContexts?.get(database.name) ?? [];+ const accepted = await execute({connection,statement,engine: instance.engine,@@ -98,6 +90,22 @@ export function DataExplorerPanel() {limit: resultRowsLimit,selection: tab.editorState.selection,});+ if (!accepted) return;++ for (const context of previousContexts) {+ context.abortController?.abort();+ }+ if (previousContexts.length > 0) {+ tabsState.batchRemoveDatabaseQueryContext({+ database: database.name,+ contextIds: previousContexts.map((context) => context.id),+ });+ }+ updateExplorerState({+ filter: suffix,+ initialized: true,+ resetRow: true,+ });},[connection,diff --git a/frontend/src/modules/sql-editor/components/ResultView/CopyAllButton.tsx b/frontend/src/modules/sql-editor/components/ResultView/CopyAllButton.tsxindex bafad27e25..b15f65921a 100644--- a/frontend/src/modules/sql-editor/components/ResultView/CopyAllButton.tsx+++ b/frontend/src/modules/sql-editor/components/ResultView/CopyAllButton.tsx@@ -7,19 +7,24 @@ import {DropdownMenuItem,DropdownMenuTrigger,} from "@/components/ui/dropdown-menu";+import { cn } from "@/lib/utils";import { useSelectionContext } from "./context";import { formatAsCSV, formatAsSQL, formatAsText } from "./copy-formats";-export function CopyAllButton() {+interface CopyAllButtonProps {+ size?: "sm" | "md";+}++export function CopyAllButton({ size = "sm" }: CopyAllButtonProps) {const { t } = useTranslation();const { copy, canCopyAsInsert } = useSelectionContext();return (<div className="flex items-center"><Button- size="sm"+ size={size}appearance="outline"- className="h-7 px-2 rounded-r-none border-r-0 text-control border-control-border hover:bg-control-bg-hover"+ className="px-2 rounded-r-none border-r-0 text-control border-control-border hover:bg-control-bg-hover"onClick={() => copy("all", formatAsText)}><CopyIcon className="size-4" />@@ -31,10 +36,13 @@ export function CopyAllButton() {delay={100}render={<Button- size="sm"+ size={size}appearance="outline"aria-label={t("common.copy")}- className="h-7 w-6 px-0 rounded-l-none text-control border-control-border hover:bg-control-bg-hover"+ className={cn(+ "px-0 rounded-l-none text-control border-control-border hover:bg-control-bg-hover",+ size === "md" ? "w-8" : "w-6"+ )}><ChevronDownIcon className="size-4" /></Button>diff --git a/frontend/src/modules/sql-editor/components/ResultView/DataExplorerResultView.test.tsx b/frontend/src/modules/sql-editor/components/ResultView/DataExplorerResultView.test.tsxindex 3e83520274..4cbe8825a7 100644--- a/frontend/src/modules/sql-editor/components/ResultView/DataExplorerResultView.test.tsx+++ b/frontend/src/modules/sql-editor/components/ResultView/DataExplorerResultView.test.tsx@@ -201,10 +201,14 @@ describe("DataExplorerResultView", () => {expect(screen.getByTestId("search-placeholder")).toHaveTextContent("common.search-results");- expect(- screen.getByRole("button", { name: "common.copy-all" })- ).toBeVisible();- fireEvent.click(screen.getByRole("button", { name: "common.copy-all" }));+ const copyAllButton = screen.getByRole("button", {+ name: "common.copy-all",+ });+ expect(copyAllButton).toHaveClass("h-9");+ expect(screen.getByRole("button", { name: "common.copy" })).toHaveClass(+ "h-9"+ );+ fireEvent.click(copyAllButton);await waitFor(() => {expect(mocks.writeTextToClipboard).toHaveBeenCalledWith("index\tid\n0\t1\n1\t2"diff --git a/frontend/src/modules/sql-editor/components/ResultView/DataExplorerResultView.tsx b/frontend/src/modules/sql-editor/components/ResultView/DataExplorerResultView.tsxindex 34fe2cd2bc..46164c09a4 100644--- a/frontend/src/modules/sql-editor/components/ResultView/DataExplorerResultView.tsx+++ b/frontend/src/modules/sql-editor/components/ResultView/DataExplorerResultView.tsx@@ -119,7 +119,7 @@ export function DataExplorerResultView({</div>{!disallowCopyingData && rows.length > 0 && (<div className="shrink-0">- <CopyAllButton />+ <CopyAllButton size="md" /></div>)}</div>diff --git a/frontend/src/modules/sql-editor/components/ResultView/VirtualDataTable.test.tsx b/frontend/src/modules/sql-editor/components/ResultView/VirtualDataTable.test.tsxindex bd8f2c9b55..46ff032527 100644--- a/frontend/src/modules/sql-editor/components/ResultView/VirtualDataTable.test.tsx+++ b/frontend/src/modules/sql-editor/components/ResultView/VirtualDataTable.test.tsx@@ -312,6 +312,9 @@ describe("VirtualDataTable row detail action", () => {expect(container.querySelector('[data-col-index="1"] > div')).not.toHaveClass("cursor-pointer");+ expect(container.querySelector('[data-row-index="0"]')).toHaveClass(+ "cursor-pointer"+ );expect(container.querySelector('[data-col-index="1"]')).toHaveClass("bg-accent/20!");diff --git a/frontend/src/modules/sql-editor/components/ResultView/VirtualDataTable.tsx b/frontend/src/modules/sql-editor/components/ResultView/VirtualDataTable.tsxindex d0ed9301bf..d650a6bc55 100644--- a/frontend/src/modules/sql-editor/components/ResultView/VirtualDataTable.tsx+++ b/frontend/src/modules/sql-editor/components/ResultView/VirtualDataTable.tsx@@ -411,7 +411,10 @@ export const VirtualDataTable = forwardRef<<divkey={virtualRow.key}data-row-index={rowIndex}- className="flex absolute inset-x-0 group"+ className={cn(+ "flex absolute inset-x-0 group",+ onRowClick && "cursor-pointer"+ )}onClickCapture={onRowClick ? () => onRowClick(rowIndex) : undefined}diff --git a/frontend/src/modules/sql-editor/components/SQLEditorRouteShell.test.tsx b/frontend/src/modules/sql-editor/components/SQLEditorRouteShell.test.tsxindex 1eb9f202f5..25cd209fcb 100644--- a/frontend/src/modules/sql-editor/components/SQLEditorRouteShell.test.tsx+++ b/frontend/src/modules/sql-editor/components/SQLEditorRouteShell.test.tsx@@ -285,6 +285,41 @@ beforeEach(() => {});describe("SQLEditorRouteShell", () => {+ test("keeps a restored data explorer tab that matches the database route", async () => {+ mocks.tabsState.initProject.mockImplementationOnce(async () => {+ const tab = {+ id: "explorer",+ savedQuery: "",+ mode: "DATA_EXPLORER",+ connection: {+ instance: "instances/inst1",+ database: "instances/inst1/databases/db1",+ schema: "public",+ table: "users",+ },+ dataExplorer: {+ filter: "WHERE active = true",+ initialized: false,+ },+ } as SQLEditorTab;+ mocks.tabsState.tabsById.set(tab.id, tab);+ mocks.tabsState.currentTabId = tab.id;+ });++ const { unmount } = renderShell();++ await act(async () => {+ await Promise.resolve();+ await Promise.resolve();+ await Promise.resolve();+ });++ expect(mocks.tabsState.addTab).not.toHaveBeenCalled();+ expect(mocks.tabsState.currentTabId).toBe("explorer");++ unmount();+ });+test("seeds database route tabs with schema and table from the URL", async () => {const { unmount } = renderShell();diff --git a/frontend/src/modules/sql-editor/components/SQLEditorRouteShell.tsx b/frontend/src/modules/sql-editor/components/SQLEditorRouteShell.tsxindex 4e972047e6..427103b799 100644--- a/frontend/src/modules/sql-editor/components/SQLEditorRouteShell.tsx+++ b/frontend/src/modules/sql-editor/components/SQLEditorRouteShell.tsx@@ -321,7 +321,18 @@ export function SQLEditorRouteShell() {connection.table = table;connection.schema ??= "";}- getSQLEditorTabsState().addTab({+ const tabsState = getSQLEditorTabsState();+ const currentTab = tabsState.tabsById.get(tabsState.currentTabId);+ if (+ currentTab?.mode === "DATA_EXPLORER" &&+ currentTab.connection.instance === connection.instance &&+ currentTab.connection.database === connection.database &&+ (currentTab.connection.schema ?? "") === (connection.schema ?? "") &&+ currentTab.connection.table === connection.table+ ) {+ return true;+ }+ tabsState.addTab({connection,mode: DEFAULT_SQL_EDITOR_TAB_MODE,});diff --git a/frontend/src/modules/sql-editor/components/SheetTree.test.tsx b/frontend/src/modules/sql-editor/components/SheetTree.test.tsxindex 6810276312..7bcb384550 100644--- a/frontend/src/modules/sql-editor/components/SheetTree.test.tsx+++ b/frontend/src/modules/sql-editor/components/SheetTree.test.tsx@@ -903,6 +903,48 @@ describe("SheetTree", () => {unmount();});+ test("does not open the context menu for draft rows", () => {+ const defaultMocks = setupDefaultMocks();+ const draftNode = makeSavedQueryNode(+ "/draft/explorer",+ "data-explorer-tab"+ );+ if (draftNode.savedQuery) {+ draftNode.savedQuery.type = "draft";+ }+ defaultMocks.viewContext._sheetTree.value = makeFolderNode("/draft", [+ draftNode,+ ]);++ const handleContextMenu = vi.fn();+ mocks.useDropdown.mockReturnValue({+ currentNode: undefined,+ options: [],+ savedQueryEntity: undefined,+ showSharePanel: false,+ handleContextMenu,+ handleSharePanelShow: vi.fn(),+ handleClickOutside: vi.fn(),+ });++ const { container, render, unmount } = renderIntoContainer(+ <SheetTree view="draft" />+ );+ render();++ const row = container.querySelector(+ `[data-item-key="/draft/explorer"]`+ );+ expect(row).not.toBeNull();+ act(() => {+ row?.dispatchEvent(new MouseEvent("contextmenu", { bubbles: true }));+ });++ expect(handleContextMenu).not.toHaveBeenCalled();++ unmount();+ });+test("6. Delete confirm → fires savedQueryV1Store.deleteSavedQueryByName", async () => {const defaultMocks = setupDefaultMocks();const wsNode = makeSavedQueryNode("/my/ws2", "savedQueries/ws2");diff --git a/frontend/src/modules/sql-editor/components/SheetTree.tsx b/frontend/src/modules/sql-editor/components/SheetTree.tsxindex d0706fabf7..1b0fc1941b 100644--- a/frontend/src/modules/sql-editor/components/SheetTree.tsx+++ b/frontend/src/modules/sql-editor/components/SheetTree.tsx@@ -1176,7 +1176,7 @@ export function SheetTree({onContextMenu={(e) => {e.preventDefault();e.stopPropagation();- if (folderNode.loadMore) return;+ if (view === "draft" || folderNode.loadMore) return;openMenuAtPoint(e.clientX, e.clientY, folderNode);}}>diff --git a/frontend/src/modules/sql-editor/components/TabList.tsx b/frontend/src/modules/sql-editor/components/TabList.tsxindex d9b88e63f6..55322296fc 100644--- a/frontend/src/modules/sql-editor/components/TabList.tsx+++ b/frontend/src/modules/sql-editor/components/TabList.tsx@@ -212,16 +212,7 @@ export function TabList() {const [moved] = next.splice(oldIndex, 1);next.splice(newIndex, 0, moved);// Rewrite the persisted tab order without touching individual tabs.- getSQLEditorTabsState().setOpenTabListOrder(- next.map((tab) => ({- id: tab.id,- savedQuery: tab.savedQuery,- mode: tab.mode,- batchQueryContext: tab.batchQueryContext,- treeState: tab.treeState,- viewState: tab.viewState,- }))- );+ getSQLEditorTabsState().setOpenTabListOrder(next.map((tab) => tab.id));};// Listen for close-tab events from the context menu (batch actions).diff --git a/frontend/src/modules/sql-editor/store/tab.test.ts b/frontend/src/modules/sql-editor/store/tab.test.tsindex d1e6af728a..b3c0dc183c 100644--- a/frontend/src/modules/sql-editor/store/tab.test.ts+++ b/frontend/src/modules/sql-editor/store/tab.test.ts@@ -1,5 +1,8 @@import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";-import { storageKeySqlEditorTabs } from "@/utils";+import {+ storageKeySqlEditorCurrentTab,+ storageKeySqlEditorTabs,+} from "@/utils";import {__resetTabStoreProjectCursor,getSQLEditorTabsState,@@ -9,8 +12,15 @@ import {} from "./tab";const mocks = vi.hoisted(() => ({+ project: "projects/aaa",loadCurrentUser: vi.fn(async () => undefined),getOrFetchSavedQueryByName: vi.fn(),+ getOrFetchDatabaseByName: vi.fn(),+}));++vi.mock("./editor", () => ({+ getSQLEditorEditorState: () => ({ project: mocks.project }),+ subscribeSQLEditorEditorState: vi.fn(() => vi.fn()),}));vi.mock("@/lib/sqlEditorConnection", () => ({@@ -31,6 +41,7 @@ vi.mock("@/stores/app", () => ({isSaaSMode: () => false,loadCurrentUser: mocks.loadCurrentUser,getOrFetchSavedQueryByName: mocks.getOrFetchSavedQueryByName,+ getOrFetchDatabaseByName: mocks.getOrFetchDatabaseByName,}),},}));@@ -79,6 +90,10 @@ beforeEach(() => {content: new TextEncoder().encode("SELECT 1"),contentSize: BigInt(new TextEncoder().encode("SELECT 1").length),}));+ mocks.getOrFetchDatabaseByName.mockImplementation(async (name: string) => ({+ name,+ project: "projects/aaa",+ }));});afterEach(() => {@@ -159,19 +174,78 @@ describe("useSQLEditorTabsStore", () => {expect(isSQLEditorTabClosable(tab)).toBe(true);});- test("setOpenTabListOrder rewrites the persisted order without losing tabs", () => {+ test("persists the data explorer target and filter without runtime state", () => {+ const tab = getSQLEditorTabsState().addTab({+ id: "explorer",+ title: "users",+ mode: "DATA_EXPLORER",+ connection: {+ instance: "instances/mysql-instance",+ database: "instances/mysql-instance/databases/bytebase",+ schema: "public",+ table: "users",+ },+ dataExplorer: {+ filter: "",+ initialized: false,+ },+ });+ getSQLEditorTabsState().updateTab(tab.id, {+ dataExplorer: {+ filter: "WHERE active = true",+ initialized: true,+ selectedRowKey: 7,+ },+ });++ const persisted = JSON.parse(+ storage.get(+ storageKeySqlEditorTabs("", "projects/aaa", "[email protected]")+ ) ?? "[]"+ );+ expect(persisted).toEqual([+ expect.objectContaining({+ id: "explorer",+ mode: "DATA_EXPLORER",+ connection: {+ instance: "instances/mysql-instance",+ database: "instances/mysql-instance/databases/bytebase",+ schema: "public",+ table: "users",+ },+ dataExplorer: { filter: "WHERE active = true" },+ }),+ ]);+ });++ test("setOpenTabListOrder preserves data explorer metadata", () => {const a = getSQLEditorTabsState().addTab({ title: "a" });- const b = getSQLEditorTabsState().addTab({ title: "b" });+ const b = getSQLEditorTabsState().addTab({+ title: "users",+ mode: "DATA_EXPLORER",+ connection: {+ instance: "instances/mysql-instance",+ database: "instances/mysql-instance/databases/bytebase",+ table: "users",+ },+ dataExplorer: {+ filter: "WHERE active = true",+ initialized: false,+ },+ });- const reordered = [- ...useSQLEditorTabsStore.getState().openTmpTabList,- ].reverse();- getSQLEditorTabsState().setOpenTabListOrder(reordered);+ getSQLEditorTabsState().setOpenTabListOrder([b.id, a.id]);const order = useSQLEditorTabsStore.getState().openTmpTabList.map((t) => t.id);expect(order).toEqual([b.id, a.id]);+ expect(useSQLEditorTabsStore.getState().openTmpTabList[0]).toEqual(+ expect.objectContaining({+ connection: b.connection,+ dataExplorer: { filter: "WHERE active = true" },+ })+ );// Live tab map unchanged.expect(useSQLEditorTabsStore.getState().tabsById.size).toBe(2);});@@ -331,4 +405,93 @@ describe("useSQLEditorTabsStore", () => {state.openTmpTabList.find((t) => t.id === "legacy-tab")).not.toHaveProperty("worksheet");});++ test("initProject restores the current data explorer tab and its filter", async () => {+ const tabsKey = storageKeySqlEditorTabs(+ "",+ "projects/aaa",+ );+ storage.set(+ tabsKey,+ JSON.stringify([+ {+ id: "saved-query",+ savedQuery: "projects/aaa/savedQueries/aaa-sheet",+ mode: "SAVED_QUERY",+ },+ {+ id: "explorer",+ savedQuery: "",+ mode: "DATA_EXPLORER",+ connection: {+ instance: "instances/mysql-instance",+ database: "instances/mysql-instance/databases/bytebase",+ schema: "public",+ table: "users",+ },+ dataExplorer: { filter: "WHERE active = true" },+ },+ ])+ );+ storage.set(+ storageKeySqlEditorCurrentTab("", "projects/aaa", "[email protected]"),+ JSON.stringify("explorer")+ );++ await getSQLEditorTabsState().initProject("projects/aaa");++ const state = useSQLEditorTabsStore.getState();+ expect(state.currentTabId).toBe("explorer");+ expect(state.openTmpTabList.map((tab) => tab.id)).toEqual([+ "saved-query",+ "explorer",+ ]);+ expect(state.tabsById.get("explorer")).toEqual(+ expect.objectContaining({+ title: "users",+ mode: "DATA_EXPLORER",+ connection: {+ instance: "instances/mysql-instance",+ database: "instances/mysql-instance/databases/bytebase",+ schema: "public",+ table: "users",+ },+ dataExplorer: {+ filter: "WHERE active = true",+ initialized: false,+ },+ databaseQueryContexts: undefined,+ })+ );+ });++ test("initProject drops data explorer tabs from another project", async () => {+ storage.set(+ storageKeySqlEditorTabs("", "projects/aaa", "[email protected]"),+ JSON.stringify([+ {+ id: "explorer",+ savedQuery: "",+ mode: "DATA_EXPLORER",+ connection: {+ instance: "instances/mysql-instance",+ database: "instances/mysql-instance/databases/bytebase",+ table: "users",+ },+ dataExplorer: { filter: "" },+ },+ ])+ );+ mocks.getOrFetchDatabaseByName.mockResolvedValueOnce({+ name: "instances/mysql-instance/databases/bytebase",+ project: "projects/other",+ });++ await getSQLEditorTabsState().initProject("projects/aaa");++ const state = useSQLEditorTabsStore.getState();+ expect(state.tabsById.has("explorer")).toBe(false);+ expect(state.openTmpTabList).toEqual([]);+ });});diff --git a/frontend/src/modules/sql-editor/store/tab.ts b/frontend/src/modules/sql-editor/store/tab.tsindex 147b779865..3a265baf76 100644--- a/frontend/src/modules/sql-editor/store/tab.ts+++ b/frontend/src/modules/sql-editor/store/tab.ts@@ -47,7 +47,10 @@ const PERSISTENT_TAB_FIELDS = [export type PersistentTab = Pick<SQLEditorTab,(typeof PERSISTENT_TAB_FIELDS)[number]->;+> & {+ connection?: SQLEditorTab["connection"];+ dataExplorer?: Pick<NonNullable<SQLEditorTab["dataExplorer"]>, "filter">;+};export interface SQLEditorTabsState {/** Authoritative live tab objects keyed by id. */@@ -59,7 +62,7 @@ export interface SQLEditorTabsState {setCurrentTabId: (id: string) => void;/** Rewrites the persisted tab order without touching individual tabs. */- setOpenTabListOrder: (order: PersistentTab[]) => void;+ setOpenTabListOrder: (order: string[]) => void;addTab: (payload?: Partial<SQLEditorTab>, beside?: boolean) => SQLEditorTab;cloneTab: (targetId: string, payload?: Partial<SQLEditorTab>) => SQLEditorTab;closeTab: (tabId: string) => void;@@ -133,6 +136,19 @@ const normalizePersistedTab = (const mode =(persisted.mode as string) === "WORKSHEET" ? "SAVED_QUERY" : persisted.mode;const { worksheet: _legacy, ...rest } = persisted;+ if (mode === "DATA_EXPLORER") {+ return {+ ...rest,+ savedQuery: "",+ mode,+ dataExplorer: {+ filter:+ typeof persisted.dataExplorer?.filter === "string"+ ? persisted.dataExplorer.filter+ : "",+ },+ };+ }return { ...rest, savedQuery, mode };};@@ -160,7 +176,7 @@ const persistOpenTabs = (openTabs: PersistentTab[]) => {if (!scope) return;safeWrite(storageKeySqlEditorTabs(scope.wsScope, scope.project, scope.email),- openTabs.filter((tab) => tab.mode !== "DATA_EXPLORER")+ openTabs);};@@ -184,6 +200,17 @@ const readOpenTabs = ([]);+const readCurrentTabId = (+ wsScope: string,+ project: string,+ email: string+): string =>+ safeRead<string>(+ storageKeySqlEditorCurrentTab(wsScope, project, email),+ (v) => (typeof v === "string" ? v : undefined),+ ""+ );+export const useSQLEditorTabsStore: UseBoundStore<StoreApi<SQLEditorTabsState>> = create<SQLEditorTabsState>()(@@ -201,9 +228,13 @@ export const useSQLEditorTabsStore: UseBoundStore<setOpenTabListOrder(order) {set((s) => {- s.openTmpTabList = order;+ const byId = new Map(s.openTmpTabList.map((tab) => [tab.id, tab]));+ s.openTmpTabList = order.flatMap((id) => {+ const tab = byId.get(id);+ return tab ? [tab] : [];+ });});- persistOpenTabs(order);+ persistOpenTabs(get().openTmpTabList);},addTab(payload, beside = false) {@@ -439,6 +470,7 @@ const hydrateProjectTabs = async (project: string): Promise<void> => {);const storedTabs = readOpenTabs(wsScope, project, email);+ const storedCurrentTabId = readCurrentTabId(wsScope, project, email);const hydratedTabs: SQLEditorTab[] = [];const validPersistent: PersistentTab[] = [];@@ -446,6 +478,39 @@ const hydrateProjectTabs = async (project: string): Promise<void> => {for (const persisted of storedTabs) {if (seen.has(persisted.id)) continue;++ if (persisted.mode === "DATA_EXPLORER") {+ const connection = persisted.connection;+ if (!connection?.instance || !connection.database || !connection.table) {+ continue;+ }+ const database = await useAppStore+ .getState()+ .getOrFetchDatabaseByName(connection.database);+ if (database.project !== project) continue;++ const fullTab: SQLEditorTab = {+ ...defaultSQLEditorTab(),+ ...omitBy(persisted, isUndefined),+ title: connection.table,+ status: "CLEAN",+ connection,+ dataExplorer: {+ filter:+ typeof persisted.dataExplorer?.filter === "string"+ ? persisted.dataExplorer.filter+ : "",+ initialized: false,+ },+ databaseQueryContexts: undefined,+ };++ seen.add(persisted.id);+ validPersistent.push(persisted);+ hydratedTabs.push(fullTab);+ continue;+ }+if (!persisted.savedQuery) continue;const savedQuery = await useAppStore@@ -473,10 +538,16 @@ const hydrateProjectTabs = async (project: string): Promise<void> => {hydratedTabs.push(fullTab);}+ const currentTabId = validPersistent.some(+ (tab) => tab.id === storedCurrentTabId+ )+ ? storedCurrentTabId+ : (head(validPersistent)?.id ?? "");+useSQLEditorTabsStore.setState({tabsById: new Map(hydratedTabs.map((t) => [t.id, t])),openTmpTabList: validPersistent,- currentTabId: head(validPersistent)?.id ?? "",+ currentTabId,});persistOpenTabs(validPersistent);@@ -507,9 +578,15 @@ const upsertOpenTabDraft = (beside: boolean) => {const persistent = pick(tab, ...PERSISTENT_TAB_FIELDS) as PersistentTab;+ if (tab.mode === "DATA_EXPLORER") {+ persistent.connection = tab.connection;+ persistent.dataExplorer = {+ filter: tab.dataExplorer?.filter ?? "",+ };+ }const position = state.openTmpTabList.findIndex((item) => item.id === tab.id);if (position >= 0) {- Object.assign(state.openTmpTabList[position], persistent);+ state.openTmpTabList[position] = persistent;return;}const currentPosition = state.openTmpTabList.findIndex(