Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

refactor: migrate sql editor pinia store (#20363)

ecmadao3f600bbada3f
diff --git a/frontend/src/composables/useExecuteSQL.ts b/frontend/src/composables/useExecuteSQL.ts
index 964a266cc2..9eccd29f49 100644
--- a/frontend/src/composables/useExecuteSQL.ts
+++ b/frontend/src/composables/useExecuteSQL.ts
@@ -4,14 +4,14 @@ import { cloneDeep, isEmpty } from "lodash-es";
import { v4 as uuidv4 } from "uuid";
import { markRaw, reactive } from "vue";
import { t } from "@/plugins/i18n";
+import { useSQLEditorStore as useSQLEditorReactStore } from "@/react/stores/sqlEditor";
+import { useSQLEditorVueState } from "@/react/stores/sqlEditor/editor-vue-state";
+import { useSQLEditorTabStore } from "@/react/stores/sqlEditor/tab-vue-state";
import {
hasFeature,
pushNotification,
useDatabaseV1Store,
useDBGroupStore,
- useSQLEditorQueryHistoryStore,
- useSQLEditorStore,
- useSQLEditorTabStore,
useSQLStore,
} from "@/store";
import type {
@@ -51,8 +51,7 @@ const useExecuteSQL = () => {
const dbGroupStore = useDBGroupStore();
const dbStore = useDatabaseV1Store();
const tabStore = useSQLEditorTabStore();
- const sqlEditorStore = useSQLEditorStore();
- const queryHistoryStore = useSQLEditorQueryHistoryStore();
+ const sqlEditorStore = useSQLEditorVueState();
const notify = (
type: BBNotificationStyle,
@@ -296,7 +295,8 @@ const useExecuteSQL = () => {
// the HistoryPane re-renders from it (store reactivity alone
// doesn't reliably propagate into the React `useVueState`
// subscriber, so we trigger the re-render explicitly).
- queryHistoryStore
+ useSQLEditorReactStore
+ .getState()
.mergeLatest({
project: sqlEditorStore.project,
database: database.name,
diff --git a/frontend/src/plugins/ai/logic/useChatByTab.ts b/frontend/src/plugins/ai/logic/useChatByTab.ts
index f98030bee6..a179583c58 100644
--- a/frontend/src/plugins/ai/logic/useChatByTab.ts
+++ b/frontend/src/plugins/ai/logic/useChatByTab.ts
@@ -1,6 +1,6 @@
import { last } from "lodash-es";
import { computed, ref, watch } from "vue";
-import { useSQLEditorTabStore } from "@/store";
+import { useSQLEditorTabStore } from "@/react/stores/sqlEditor/tab-vue-state";
import type { SQLEditorTab } from "@/types";
import { useConversationStore } from "../store";
import type { AIChatInfo, Conversation } from "../types";
diff --git a/frontend/src/plugins/ai/react/ChatPanel.tsx b/frontend/src/plugins/ai/react/ChatPanel.tsx
index 7f4a18c4bf..b3806f59f1 100644
--- a/frontend/src/plugins/ai/react/ChatPanel.tsx
+++ b/frontend/src/plugins/ai/react/ChatPanel.tsx
@@ -4,7 +4,7 @@ import { Loader2 } from "lucide-react";
import { useCallback, useEffect, useRef, useState } from "react";
import { sqlServiceClientConnect } from "@/connect";
import { useVueState } from "@/react/hooks/useVueState";
-import { useSQLEditorTabStore } from "@/store";
+import { useSQLEditorTabStore } from "@/react/stores/sqlEditor/tab-vue-state";
import {
type AICompletionRequest_Message,
AICompletionRequest_MessageSchema,
diff --git a/frontend/src/plugins/ai/react/HistoryPanel/ConversationList.tsx b/frontend/src/plugins/ai/react/HistoryPanel/ConversationList.tsx
index 9749b78cdf..f519cffb9b 100644
--- a/frontend/src/plugins/ai/react/HistoryPanel/ConversationList.tsx
+++ b/frontend/src/plugins/ai/react/HistoryPanel/ConversationList.tsx
@@ -14,7 +14,7 @@ import {
import { Button } from "@/react/components/ui/button";
import { useVueState } from "@/react/hooks/useVueState";
import { cn } from "@/react/lib/utils";
-import { useSQLEditorTabStore } from "@/store";
+import { useSQLEditorTabStore } from "@/react/stores/sqlEditor/tab-vue-state";
import { useConversationStore } from "../../store";
import type { Conversation } from "../../types";
import { useAIContext } from "../context";
diff --git a/frontend/src/plugins/ai/react/context.tsx b/frontend/src/plugins/ai/react/context.tsx
index 07d4ac7d9f..b67dd09eeb 100644
--- a/frontend/src/plugins/ai/react/context.tsx
+++ b/frontend/src/plugins/ai/react/context.tsx
@@ -11,10 +11,9 @@ import {
import { useVueState } from "@/react/hooks/useVueState";
import {
useConnectionOfCurrentSQLEditorTab,
- useDBSchemaV1Store,
- useSettingV1Store,
useSQLEditorTabStore,
-} from "@/store";
+} from "@/react/stores/sqlEditor/tab-vue-state";
+import { useDBSchemaV1Store, useSettingV1Store } from "@/store";
import { Engine } from "@/types/proto-es/v1/common_pb";
import type { DatabaseMetadata } from "@/types/proto-es/v1/database_service_pb";
import type { AISetting } from "@/types/proto-es/v1/setting_service_pb";
diff --git a/frontend/src/react/components/sql-editor/AccessGrantRequestDrawer.test.tsx b/frontend/src/react/components/sql-editor/AccessGrantRequestDrawer.test.tsx
index 59746d0cc5..d66e855ab4 100644
--- a/frontend/src/react/components/sql-editor/AccessGrantRequestDrawer.test.tsx
+++ b/frontend/src/react/components/sql-editor/AccessGrantRequestDrawer.test.tsx
@@ -12,7 +12,7 @@ const mocks = vi.hoisted(() => ({
useVueState: vi.fn<(getter: () => unknown) => unknown>(),
useCurrentUserV1: vi.fn(),
// Legacy Pinia editor store.
- useSQLEditorPiniaStore: vi.fn(),
+ useSQLEditorVueState: vi.fn(),
useSQLEditorTabStore: vi.fn(),
// New zustand setters.
setAsidePanelTab: vi.fn(),
@@ -33,12 +33,18 @@ vi.mock("@/react/hooks/useVueState", () => ({
vi.mock("@/store", () => ({
useCurrentUserV1: mocks.useCurrentUserV1,
- useSQLEditorStore: mocks.useSQLEditorPiniaStore,
- useSQLEditorTabStore: mocks.useSQLEditorTabStore,
pushNotification: mocks.pushNotification,
useDatabaseV1Store: mocks.useDatabaseV1Store,
}));
+vi.mock("@/react/stores/sqlEditor/tab-vue-state", () => ({
+ useSQLEditorTabStore: mocks.useSQLEditorTabStore,
+}));
+
+vi.mock("@/react/stores/sqlEditor/editor-vue-state", () => ({
+ useSQLEditorVueState: mocks.useSQLEditorVueState,
+}));
+
vi.mock("@/react/stores/sqlEditor", () => ({
useSQLEditorStore: (
selector: (s: {
@@ -293,7 +299,7 @@ const setupMocks = () => {
value: { email: "[email protected]" },
});
- mocks.useSQLEditorPiniaStore.mockReturnValue({ project: "projects/proj1" });
+ mocks.useSQLEditorVueState.mockReturnValue({ project: "projects/proj1" });
mocks.useSQLEditorTabStore.mockReturnValue({
currentTab: {
diff --git a/frontend/src/react/components/sql-editor/AccessGrantRequestDrawer.tsx b/frontend/src/react/components/sql-editor/AccessGrantRequestDrawer.tsx
index 96be47e26c..45523cb645 100644
--- a/frontend/src/react/components/sql-editor/AccessGrantRequestDrawer.tsx
+++ b/frontend/src/react/components/sql-editor/AccessGrantRequestDrawer.tsx
@@ -21,14 +21,14 @@ import {
import { Textarea } from "@/react/components/ui/textarea";
import { useVueState } from "@/react/hooks/useVueState";
import { useSQLEditorStore } from "@/react/stores/sqlEditor";
+import { useSQLEditorVueState } from "@/react/stores/sqlEditor/editor-vue-state";
+import { useSQLEditorTabStore } from "@/react/stores/sqlEditor/tab-vue-state";
import { router } from "@/router";
import { PROJECT_V1_ROUTE_ISSUE_DETAIL } from "@/router/dashboard/projectV1";
import {
pushNotification,
useCurrentUserV1,
useDatabaseV1Store,
- useSQLEditorStore as useSQLEditorPiniaStore,
- useSQLEditorTabStore,
} from "@/store";
import {
AccessGrant_Status,
@@ -111,7 +111,7 @@ function AccessGrantRequestDrawerInner({
}: AccessGrantRequestDrawerInnerProps) {
const { t } = useTranslation();
const currentUser = useCurrentUserV1();
- const editorStore = useSQLEditorPiniaStore();
+ const editorStore = useSQLEditorVueState();
const tabStore = useSQLEditorTabStore();
const setAsidePanelTab = useSQLEditorStore((s) => s.setAsidePanelTab);
const setHighlightAccessGrantName = useSQLEditorStore(
diff --git a/frontend/src/react/components/sql-editor/AccessPane.test.tsx b/frontend/src/react/components/sql-editor/AccessPane.test.tsx
index da45bd4b9a..b61cadc9cd 100644
--- a/frontend/src/react/components/sql-editor/AccessPane.test.tsx
+++ b/frontend/src/react/components/sql-editor/AccessPane.test.tsx
@@ -12,7 +12,7 @@ const mocks = vi.hoisted(() => ({
useVueState: vi.fn<(getter: () => unknown) => unknown>(),
useProjectV1Store: vi.fn(),
// Legacy Pinia editor store.
- useSQLEditorPiniaStore: vi.fn(),
+ useSQLEditorVueState: vi.fn(),
useSQLEditorTabStore: vi.fn(),
// New zustand store state + setter.
state: {
@@ -37,14 +37,20 @@ vi.mock("@/react/hooks/useVueState", () => ({
vi.mock("@/store", () => ({
useProjectV1Store: mocks.useProjectV1Store,
- useSQLEditorStore: mocks.useSQLEditorPiniaStore,
- useSQLEditorTabStore: mocks.useSQLEditorTabStore,
useAccessGrantStore: mocks.useAccessGrantStore,
useIssueV1Store: mocks.useIssueV1Store,
useDatabaseV1Store: mocks.useDatabaseV1Store,
hasFeature: mocks.hasFeature,
}));
+vi.mock("@/react/stores/sqlEditor/tab-vue-state", () => ({
+ useSQLEditorTabStore: mocks.useSQLEditorTabStore,
+}));
+
+vi.mock("@/react/stores/sqlEditor/editor-vue-state", () => ({
+ useSQLEditorVueState: mocks.useSQLEditorVueState,
+}));
+
vi.mock("@/react/stores/sqlEditor", () => ({
useSQLEditorStore: Object.assign(
(
@@ -231,7 +237,7 @@ const setupDefaultMocks = () => {
})),
});
- mocks.useSQLEditorPiniaStore.mockReturnValue({ project: "projects/proj1" });
+ mocks.useSQLEditorVueState.mockReturnValue({ project: "projects/proj1" });
mocks.useSQLEditorTabStore.mockReturnValue({
currentTab: { connection: { database: "instances/inst1/databases/db1" } },
});
diff --git a/frontend/src/react/components/sql-editor/AccessPane.tsx b/frontend/src/react/components/sql-editor/AccessPane.tsx
index 8353982dc9..73706d8c13 100644
--- a/frontend/src/react/components/sql-editor/AccessPane.tsx
+++ b/frontend/src/react/components/sql-editor/AccessPane.tsx
@@ -18,13 +18,13 @@ import { PermissionGuard } from "@/react/components/PermissionGuard";
import { Button } from "@/react/components/ui/button";
import { useVueState } from "@/react/hooks/useVueState";
import { useSQLEditorStore } from "@/react/stores/sqlEditor";
+import { useSQLEditorVueState } from "@/react/stores/sqlEditor/editor-vue-state";
import {
hasFeature,
useAccessGrantStore,
useDatabaseV1Store,
useIssueV1Store,
useProjectV1Store,
- useSQLEditorStore as useSQLEditorPiniaStore,
} from "@/store";
import type { AccessFilter } from "@/store/modules/accessGrant";
import type { AccessGrant } from "@/types/proto-es/v1/access_grant_service_pb";
@@ -48,7 +48,7 @@ export function AccessPane() {
const { t } = useTranslation();
const projectStore = useProjectV1Store();
- const editorStore = useSQLEditorPiniaStore();
+ const editorStore = useSQLEditorVueState();
const accessGrantStore = useAccessGrantStore();
const issueStore = useIssueV1Store();
const databaseStore = useDatabaseV1Store();
diff --git a/frontend/src/react/components/sql-editor/AdminModeButton.test.tsx b/frontend/src/react/components/sql-editor/AdminModeButton.test.tsx
index 7615b3057a..a04fe10de5 100644
--- a/frontend/src/react/components/sql-editor/AdminModeButton.test.tsx
+++ b/frontend/src/react/components/sql-editor/AdminModeButton.test.tsx
@@ -10,7 +10,7 @@ import { beforeEach, describe, expect, test, vi } from "vitest";
const mocks = vi.hoisted(() => ({
useTranslation: vi.fn(() => ({ t: (key: string) => key })),
useVueState: vi.fn<(getter: () => unknown) => unknown>(),
- useSQLEditorStore: vi.fn(),
+ useSQLEditorVueState: vi.fn(),
useSQLEditorTabStore: vi.fn(),
}));
@@ -22,11 +22,16 @@ vi.mock("@/react/hooks/useVueState", () => ({
useVueState: mocks.useVueState,
}));
-vi.mock("@/store", () => ({
- useSQLEditorStore: mocks.useSQLEditorStore,
+vi.mock("@/store", () => ({}));
+
+vi.mock("@/react/stores/sqlEditor/tab-vue-state", () => ({
useSQLEditorTabStore: mocks.useSQLEditorTabStore,
}));
+vi.mock("@/react/stores/sqlEditor/editor-vue-state", () => ({
+ useSQLEditorVueState: mocks.useSQLEditorVueState,
+}));
+
vi.mock("@/react/components/ui/tooltip", () => ({
Tooltip: ({ children }: { children: React.ReactNode }) => <>{children}</>,
}));
@@ -56,7 +61,7 @@ const renderIntoContainer = (element: ReactElement) => {
beforeEach(async () => {
vi.clearAllMocks();
// Default: allow admin, WORKSHEET mode, connected
- mocks.useSQLEditorStore.mockReturnValue({ allowAdmin: true });
+ mocks.useSQLEditorVueState.mockReturnValue({ allowAdmin: true });
mocks.useSQLEditorTabStore.mockReturnValue({
updateCurrentTab: vi.fn(),
});
@@ -66,7 +71,7 @@ beforeEach(async () => {
describe("AdminModeButton", () => {
test("renders nothing when allowAdmin is false", () => {
- mocks.useSQLEditorStore.mockReturnValue({ allowAdmin: false });
+ mocks.useSQLEditorVueState.mockReturnValue({ allowAdmin: false });
mocks.useVueState.mockImplementation((getter) => getter());
// Need to also mock the tab state reads. Configure useVueState to return
// appropriate values per call: allowAdmin=false, mode="WORKSHEET", isDisconnected=false
diff --git a/frontend/src/react/components/sql-editor/AdminModeButton.tsx b/frontend/src/react/components/sql-editor/AdminModeButton.tsx
index 9fd7ef3619..954e6c7ca8 100644
--- a/frontend/src/react/components/sql-editor/AdminModeButton.tsx
+++ b/frontend/src/react/components/sql-editor/AdminModeButton.tsx
@@ -4,7 +4,8 @@ import { Button } from "@/react/components/ui/button";
import { Tooltip } from "@/react/components/ui/tooltip";
import { useVueState } from "@/react/hooks/useVueState";
import { cn } from "@/react/lib/utils";
-import { useSQLEditorStore, useSQLEditorTabStore } from "@/store";
+import { useSQLEditorVueState } from "@/react/stores/sqlEditor/editor-vue-state";
+import { useSQLEditorTabStore } from "@/react/stores/sqlEditor/tab-vue-state";
type AdminModeButtonProps = {
readonly size?: "sm" | "default";
@@ -23,7 +24,7 @@ export function AdminModeButton({
onEnter,
}: AdminModeButtonProps) {
const { t } = useTranslation();
- const editorStore = useSQLEditorStore();
+ const editorStore = useSQLEditorVueState();
const tabStore = useSQLEditorTabStore();
const allowAdmin = useVueState(() => editorStore.allowAdmin);
diff --git a/frontend/src/react/components/sql-editor/AsidePanel.tsx b/frontend/src/react/components/sql-editor/AsidePanel.tsx
index c68abc4004..e7af4d5aa4 100644
--- a/frontend/src/react/components/sql-editor/AsidePanel.tsx
+++ b/frontend/src/react/components/sql-editor/AsidePanel.tsx
@@ -3,14 +3,11 @@ import { useTranslation } from "react-i18next";
import { ProjectSelect } from "@/react/components/ProjectSelect";
import { useVueState } from "@/react/hooks/useVueState";
import { useSQLEditorStore } from "@/react/stores/sqlEditor";
+import { useSQLEditorVueState } from "@/react/stores/sqlEditor/editor-vue-state";
+import { useSQLEditorTabStore } from "@/react/stores/sqlEditor/tab-vue-state";
import { router } from "@/router";
import { PROJECT_V1_ROUTE_DASHBOARD } from "@/router/dashboard/workspaceRoutes";
-import {
- useActuatorV1Store,
- useSQLEditorStore as useSQLEditorPiniaStore,
- useSQLEditorTabStore,
- useSQLEditorWorksheetStore,
-} from "@/store";
+import { useActuatorV1Store } from "@/store";
import { defaultProject, isValidProjectName } from "@/types";
import { hasProjectPermissionV2, hasWorkspacePermissionV2 } from "@/utils";
import { AccessPane } from "./AccessPane";
@@ -36,10 +33,10 @@ import { WorksheetPane } from "./WorksheetPane";
*/
export function AsidePanel() {
const { t } = useTranslation();
- const editorStore = useSQLEditorPiniaStore();
+ const editorStore = useSQLEditorVueState();
const actuatorStore = useActuatorV1Store();
const tabStore = useSQLEditorTabStore();
- const worksheetStore = useSQLEditorWorksheetStore();
+ const maybeSwitchProject = useSQLEditorStore((s) => s.maybeSwitchProject);
const asidePanelTab = useSQLEditorStore((s) => s.asidePanelTab);
const isDisconnected = useVueState(() => tabStore.isDisconnected);
@@ -61,10 +58,10 @@ export function AsidePanel() {
if (!name || !isValidProjectName(name)) {
editorStore.setProject("");
} else {
- void worksheetStore.maybeSwitchProject(name);
+ void maybeSwitchProject(name);
}
},
- [editorStore, worksheetStore]
+ [editorStore, maybeSwitchProject]
);
// Vue's `<template #empty>` — rich empty state when the user is not
diff --git a/frontend/src/react/components/sql-editor/AsidePanel/ActionBarTabItem.tsx b/frontend/src/react/components/sql-editor/AsidePanel/ActionBarTabItem.tsx
index 5c919bb375..4f91f07d39 100644
--- a/frontend/src/react/components/sql-editor/AsidePanel/ActionBarTabItem.tsx
+++ b/frontend/src/react/components/sql-editor/AsidePanel/ActionBarTabItem.tsx
@@ -5,7 +5,7 @@ import { cn } from "@/react/lib/utils";
import {
useConnectionOfCurrentSQLEditorTab,
useSQLEditorTabStore,
-} from "@/store";
+} from "@/react/stores/sqlEditor/tab-vue-state";
import { extractDatabaseResourceName } from "@/utils";
import type { AvailableAction } from "../SchemaPane/actions";
import { useSchemaPaneActions } from "../SchemaPane/actions";
diff --git a/frontend/src/react/components/sql-editor/ConnectionPane/ConnectionPane.test.tsx b/frontend/src/react/components/sql-editor/ConnectionPane/ConnectionPane.test.tsx
index d8f95ebe3a..66de6d5756 100644
--- a/frontend/src/react/components/sql-editor/ConnectionPane/ConnectionPane.test.tsx
+++ b/frontend/src/react/components/sql-editor/ConnectionPane/ConnectionPane.test.tsx
@@ -118,19 +118,34 @@ vi.mock("@/store", () => ({
useEnvironmentV1Store: () => mocks.environmentStore,
useInstanceV1Store: () => mocks.instanceStore,
useProjectV1Store: () => mocks.projectStore,
- useSQLEditorStore: () => mocks.editorStore,
+}));
+
+vi.mock("@/react/stores/sqlEditor/tab-vue-state", () => ({
useSQLEditorTabStore: () => mocks.tabStore,
- useSQLEditorTreeStore: () => mocks.treeStore,
+}));
+
+vi.mock("@/react/stores/sqlEditor/editor-vue-state", () => ({
+ useSQLEditorVueState: () => mocks.editorStore,
}));
vi.mock("@/react/stores/sqlEditor", () => ({
useSQLEditorStore: (
- selector: (s: { setShowConnectionPanel: (v: boolean) => void }) => unknown
+ selector: (s: {
+ setShowConnectionPanel: (v: boolean) => void;
+ treeState: string;
+ setTreeState: (state: string) => void;
+ treeNodeKeysByTarget: () => string[];
+ }) => unknown
) =>
selector({
setShowConnectionPanel: (next: boolean) => {
mocks.uiStore.showConnectionPanel = next;
},
+ treeState: mocks.treeStore.state,
+ setTreeState: (state: string) => {
+ mocks.treeStore.state = state as typeof mocks.treeStore.state;
+ },
+ treeNodeKeysByTarget: mocks.treeStore.nodeKeysByTarget,
}),
}));
@@ -192,7 +207,7 @@ vi.mock("@/utils", () => ({
instanceV1Name: (i: { title: string }) => i.title,
}));
-vi.mock("@/react/components/instance/constants", () => ({
+vi.mock("@/components/InstanceForm/constants", () => ({
EngineIconPath: { MYSQL: "/mysql.svg" },
}));
diff --git a/frontend/src/react/components/sql-editor/ConnectionPane/ConnectionPane.tsx b/frontend/src/react/components/sql-editor/ConnectionPane/ConnectionPane.tsx
index cb52bb7394..576b740417 100644
--- a/frontend/src/react/components/sql-editor/ConnectionPane/ConnectionPane.tsx
+++ b/frontend/src/react/components/sql-editor/ConnectionPane/ConnectionPane.tsx
@@ -26,6 +26,8 @@ import { useCommonSearchScopeOptions } from "@/react/components/useCommonSearchS
import { useVueState } from "@/react/hooks/useVueState";
import { cn } from "@/react/lib/utils";
import { useSQLEditorStore } from "@/react/stores/sqlEditor";
+import { useSQLEditorVueState } from "@/react/stores/sqlEditor/editor-vue-state";
+import { useSQLEditorTabStore } from "@/react/stores/sqlEditor/tab-vue-state";
import {
featureToRef,
pushNotification,
@@ -35,9 +37,6 @@ import {
useEnvironmentV1Store,
useInstanceV1Store,
useProjectV1Store,
- useSQLEditorStore as useSQLEditorPiniaStore,
- useSQLEditorTabStore,
- useSQLEditorTreeStore,
} from "@/store";
import { instanceNamePrefix } from "@/store/modules/v1/common";
import type { DatabaseFilter } from "@/store/modules/v1/database";
@@ -140,7 +139,7 @@ function ConnectionPaneWithHoverState(props: Props) {
function ConnectionPaneInner({ show, onMissingFeature }: Props) {
const { t } = useTranslation();
const tabStore = useSQLEditorTabStore();
- const editorStore = useSQLEditorPiniaStore();
+ const editorStore = useSQLEditorVueState();
const setShowConnectionPanel = useSQLEditorStore(
(s) => s.setShowConnectionPanel
);
@@ -149,12 +148,13 @@ function ConnectionPaneInner({ show, onMissingFeature }: Props) {
const environmentStore = useEnvironmentV1Store();
const projectStore = useProjectV1Store();
const instanceStore = useInstanceV1Store();
- const treeStore = useSQLEditorTreeStore();
+ const setTreeState = useSQLEditorStore((s) => s.setTreeState);
+ const treeNodeKeysByTarget = useSQLEditorStore((s) => s.treeNodeKeysByTarget);
const currentUser = useCurrentUserV1();
const supportBatchMode = useVueState(() => tabStore.supportBatchMode);
const isInBatchMode = useVueState(() => tabStore.isInBatchMode);
- const treeStoreState = useVueState(() => treeStore.state);
+ const treeStoreState = useSQLEditorStore((s) => s.treeState);
const currentTab = useVueState(() => tabStore.currentTab);
const currentUserEmail = useVueState(() => currentUser.value.email);
const projectName = useVueState(() => editorStore.project);
@@ -340,11 +340,11 @@ function ConnectionPaneInner({ show, onMissingFeature }: Props) {
useEffect(() => {
if (!isValidProjectName(projectName)) return;
if (!projectContextReady) {
- treeStore.state = "LOADING";
+ setTreeState("LOADING");
return;
}
- treeStore.state = "READY";
- }, [projectName, projectContextReady, treeStore]);
+ setTreeState("READY");
+ }, [projectName, projectContextReady, setTreeState]);
// Highlight the current tab's connection node in the tree. Mirrors
// Vue's `getSelectedKeys` + `tree-ready` event listener: when the tree
@@ -365,13 +365,13 @@ function ConnectionPaneInner({ show, onMissingFeature }: Props) {
connection.database
);
if (cancelled) return;
- setSelectedKeys(treeStore.nodeKeysByTarget("database", database));
+ setSelectedKeys(treeNodeKeysByTarget("database", database));
return;
}
if (connection.instance) {
const instance = instanceStore.getInstanceByName(connection.instance);
if (cancelled) return;
- setSelectedKeys(treeStore.nodeKeysByTarget("instance", instance));
+ setSelectedKeys(treeNodeKeysByTarget("instance", instance));
return;
}
if (!cancelled) setSelectedKeys([]);
@@ -386,7 +386,7 @@ function ConnectionPaneInner({ show, onMissingFeature }: Props) {
cancelled = true;
unsubscribe();
};
- }, [tabStore, databaseStore, instanceStore, treeStore]);
+ }, [tabStore, databaseStore, instanceStore, treeNodeKeysByTarget]);
// Context-menu imperative handle.
const contextMenuRef = useRef<ConnectionContextMenuHandle>(null);
diff --git a/frontend/src/react/components/sql-editor/ConnectionPane/DatabaseHoverPanel/DatabaseHoverPanel.test.tsx b/frontend/src/react/components/sql-editor/ConnectionPane/DatabaseHoverPanel/DatabaseHoverPanel.test.tsx
index c80cbcdb39..cab678f8c2 100644
--- a/frontend/src/react/components/sql-editor/ConnectionPane/DatabaseHoverPanel/DatabaseHoverPanel.test.tsx
+++ b/frontend/src/react/components/sql-editor/ConnectionPane/DatabaseHoverPanel/DatabaseHoverPanel.test.tsx
@@ -31,8 +31,10 @@ vi.mock("@/react/hooks/useVueState", () => ({
useVueState: mocks.useVueState,
}));
-vi.mock("@/store", () => ({
- useSQLEditorStore: () => ({ project: "" }),
+vi.mock("@/store", () => ({}));
+
+vi.mock("@/react/stores/sqlEditor/editor-vue-state", () => ({
+ useSQLEditorVueState: () => ({ project: "" }),
}));
vi.mock("@/utils", () => ({
diff --git a/frontend/src/react/components/sql-editor/ConnectionPane/DatabaseHoverPanel/DatabaseHoverPanel.tsx b/frontend/src/react/components/sql-editor/ConnectionPane/DatabaseHoverPanel/DatabaseHoverPanel.tsx
index 8f69092e10..3eecc9ddea 100644
--- a/frontend/src/react/components/sql-editor/ConnectionPane/DatabaseHoverPanel/DatabaseHoverPanel.tsx
+++ b/frontend/src/react/components/sql-editor/ConnectionPane/DatabaseHoverPanel/DatabaseHoverPanel.tsx
@@ -5,7 +5,7 @@ import { EnvironmentLabel } from "@/react/components/EnvironmentLabel";
import { getLayerRoot, LAYER_SURFACE_CLASS } from "@/react/components/ui/layer";
import { useVueState } from "@/react/hooks/useVueState";
import { cn } from "@/react/lib/utils";
-import { useSQLEditorStore } from "@/store";
+import { useSQLEditorVueState } from "@/react/stores/sqlEditor/editor-vue-state";
import type { Position, SQLEditorTreeNode } from "@/types";
import {
getDatabaseProject,
@@ -36,7 +36,7 @@ export function DatabaseHoverPanel({
onClickOutside,
}: Props) {
const { t } = useTranslation();
- const editorStore = useSQLEditorStore();
+ const editorStore = useSQLEditorVueState();
const { state, position, update } = useHoverState();
const hasProjectContext = useVueState(() => !!editorStore.project);
diff --git a/frontend/src/react/components/sql-editor/ConnectionPane/TreeNode/DatabaseNode.test.tsx b/frontend/src/react/components/sql-editor/ConnectionPane/TreeNode/DatabaseNode.test.tsx
index 27587ae237..9c34769b29 100644
--- a/frontend/src/react/components/sql-editor/ConnectionPane/TreeNode/DatabaseNode.test.tsx
+++ b/frontend/src/react/components/sql-editor/ConnectionPane/TreeNode/DatabaseNode.test.tsx
@@ -17,7 +17,9 @@ vi.mock("react-i18next", () => ({
useTranslation: () => ({ t: (key: string) => key }),
}));
-vi.mock("@/store", () => ({
+vi.mock("@/store", () => ({}));
+
+vi.mock("@/react/stores/sqlEditor/tab-vue-state", () => ({
useSQLEditorTabStore: mocks.useSQLEditorTabStore,
}));
diff --git a/frontend/src/react/components/sql-editor/ConnectionPane/TreeNode/DatabaseNode.tsx b/frontend/src/react/components/sql-editor/ConnectionPane/TreeNode/DatabaseNode.tsx
index 5474bd5681..b837daedc6 100644
--- a/frontend/src/react/components/sql-editor/ConnectionPane/TreeNode/DatabaseNode.tsx
+++ b/frontend/src/react/components/sql-editor/ConnectionPane/TreeNode/DatabaseNode.tsx
@@ -7,7 +7,7 @@ import { Checkbox } from "@/react/components/ui/checkbox";
import { Tooltip } from "@/react/components/ui/tooltip";
import { useVueState } from "@/react/hooks/useVueState";
import { cn } from "@/react/lib/utils";
-import { useSQLEditorTabStore } from "@/store";
+import { useSQLEditorTabStore } from "@/react/stores/sqlEditor/tab-vue-state";
import type { SQLEditorTreeNode } from "@/types";
import { PermissionDeniedDetailSchema } from "@/types/proto-es/v1/common_pb";
import {
diff --git a/frontend/src/react/components/sql-editor/ConnectionPane/TreeNode/Label.tsx b/frontend/src/react/components/sql-editor/ConnectionPane/TreeNode/Label.tsx
index d00f33ed77..93b6036732 100644
--- a/frontend/src/react/components/sql-editor/ConnectionPane/TreeNode/Label.tsx
+++ b/frontend/src/react/components/sql-editor/ConnectionPane/TreeNode/Label.tsx
@@ -1,4 +1,5 @@
import { ShieldAlert } from "lucide-react";
+import { useTranslation } from "react-i18next";
import { HighlightLabelText } from "@/react/components/HighlightLabelText";
import { useVueState } from "@/react/hooks/useVueState";
import { cn } from "@/react/lib/utils";
@@ -65,6 +66,7 @@ function EnvironmentLabel({
node: SQLEditorTreeNode;
keyword: string;
}) {
+ const { t } = useTranslation();
const environment = (node as SQLEditorTreeNode<"environment">).meta.target;
const isUnset =
environment.name === UNKNOWN_ENVIRONMENT_NAME ||
@@ -92,8 +94,18 @@ function EnvironmentLabel({
: undefined
}
>
- <HighlightLabelText text={environment.title} keyword={keyword} />
- {isProtected && (
+ {isUnset ? (
+ // Matches the shared <EnvironmentLabel> treatment: the store's
+ // getEnvironmentByName fallback sets `title = id` for unknown envs,
+ // so rendering `environment.title` would surface raw "-1" in the
+ // tree. Show a localized italic placeholder instead.
+ <span className="text-control-light italic">
+ {t("common.unassigned")}
+ </span>
+ ) : (
+ <HighlightLabelText text={environment.title} keyword={keyword} />
+ )}
+ {isProtected && !isUnset && (
<ShieldAlert className="size-3.5 shrink-0 text-current" />
)}
</span>
diff --git a/frontend/src/react/components/sql-editor/ConnectionPane/actions.test.tsx b/frontend/src/react/components/sql-editor/ConnectionPane/actions.test.tsx
index ab8729ca2a..9d14b95237 100644
--- a/frontend/src/react/components/sql-editor/ConnectionPane/actions.test.tsx
+++ b/frontend/src/react/components/sql-editor/ConnectionPane/actions.test.tsx
@@ -23,13 +23,14 @@ vi.mock("@/react/hooks/useVueState", () => ({
useVueState: mocks.useVueState,
}));
-vi.mock("@/store", () => ({
- useSQLEditorStore: () => ({ allowAdmin: mocks.allowAdmin }),
+vi.mock("@/store", () => ({}));
+
+vi.mock("@/react/stores/sqlEditor/tab-vue-state", () => ({
useSQLEditorTabStore: () => ({ currentTab: null }),
- useSQLEditorWorksheetStore: () => ({
- createWorksheet: vi.fn().mockResolvedValue(undefined),
- maybeUpdateWorksheet: vi.fn().mockResolvedValue(undefined),
- }),
+}));
+
+vi.mock("@/react/stores/sqlEditor/editor-vue-state", () => ({
+ useSQLEditorVueState: () => ({ allowAdmin: mocks.allowAdmin }),
}));
vi.mock("@/react/stores/sqlEditor", () => ({
@@ -43,6 +44,8 @@ vi.mock("@/react/stores/sqlEditor", () => ({
{
getState: () => ({
setAsidePanelTab: mocks.setAsidePanelTab,
+ createWorksheet: vi.fn().mockResolvedValue(undefined),
+ maybeUpdateWorksheet: vi.fn().mockResolvedValue(undefined),
}),
}
),
diff --git a/frontend/src/react/components/sql-editor/ConnectionPane/actions.tsx b/frontend/src/react/components/sql-editor/ConnectionPane/actions.tsx
index fa278a9049..335c50bc5e 100644
--- a/frontend/src/react/components/sql-editor/ConnectionPane/actions.tsx
+++ b/frontend/src/react/components/sql-editor/ConnectionPane/actions.tsx
@@ -8,13 +8,10 @@ import { useCallback, useMemo } from "react";
import { useTranslation } from "react-i18next";
import { useVueState } from "@/react/hooks/useVueState";
import { useSQLEditorStore } from "@/react/stores/sqlEditor";
+import { useSQLEditorVueState } from "@/react/stores/sqlEditor/editor-vue-state";
+import { useSQLEditorTabStore } from "@/react/stores/sqlEditor/tab-vue-state";
import { router } from "@/router";
import { PROJECT_V1_ROUTE_DATABASE_DETAIL } from "@/router/dashboard/projectV1";
-import {
- useSQLEditorStore as useSQLEditorPiniaStore,
- useSQLEditorTabStore,
- useSQLEditorWorksheetStore,
-} from "@/store";
import type {
BatchQueryContext,
SQLEditorConnection,
@@ -72,7 +69,8 @@ export function setConnection(options: {
};
const tabStore = useSQLEditorTabStore();
- const worksheetStore = useSQLEditorWorksheetStore();
+ const { maybeUpdateWorksheet, createWorksheet } =
+ useSQLEditorStore.getState();
const batchQueryContext: BatchQueryContext = Object.assign(
{ databases: [] } as BatchQueryContext,
@@ -82,7 +80,7 @@ export function setConnection(options: {
const createOrUpdate = () => {
if (!newTab && tabStore.currentTab) {
- return worksheetStore.maybeUpdateWorksheet({
+ return maybeUpdateWorksheet({
tabId: tabStore.currentTab.id,
worksheet: tabStore.currentTab.worksheet,
title: tabStore.currentTab.title,
@@ -90,7 +88,7 @@ export function setConnection(options: {
statement: tabStore.currentTab.statement,
});
}
- return worksheetStore.createWorksheet({
+ return createWorksheet({
database: connection.database,
});
};
@@ -110,7 +108,7 @@ export function setConnection(options: {
*/
export function useConnectionMenu(node: SQLEditorTreeNode | null) {
const { t } = useTranslation();
- const editorStore = useSQLEditorPiniaStore();
+ const editorStore = useSQLEditorVueState();
const setShowConnectionPanel = useSQLEditorStore(
(s) => s.setShowConnectionPanel
);
diff --git a/frontend/src/react/components/sql-editor/ConnectionPane/tree.ts b/frontend/src/react/components/sql-editor/ConnectionPane/tree.ts
index 4f546afede..b2bc380027 100644
--- a/frontend/src/react/components/sql-editor/ConnectionPane/tree.ts
+++ b/frontend/src/react/components/sql-editor/ConnectionPane/tree.ts
@@ -1,11 +1,13 @@
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { useSQLEditorVueState } from "@/react/stores/sqlEditor/editor-vue-state";
import {
buildTreeImpl,
- type DatabaseFilter,
mapTreeNodeByType,
+} from "@/react/stores/sqlEditor/tree-utils";
+import {
+ type DatabaseFilter,
useDatabaseV1Store,
useEnvironmentV1Store,
- useSQLEditorStore,
} from "@/store";
import type {
SQLEditorTreeNode,
@@ -89,7 +91,7 @@ export function useSQLEditorTreeByEnvironment(
{ email }: Options
): TreeByEnvironment {
const databaseStore = useDatabaseV1Store();
- const editorStore = useSQLEditorStore();
+ const editorStore = useSQLEditorVueState();
const environmentStore = useEnvironmentV1Store();
const storageKey = useMemo(
diff --git a/frontend/src/react/components/sql-editor/ContainerChooser.test.tsx b/frontend/src/react/components/sql-editor/ContainerChooser.test.tsx
index ff04d8c005..e774746ca8 100644
--- a/frontend/src/react/components/sql-editor/ContainerChooser.test.tsx
+++ b/frontend/src/react/components/sql-editor/ContainerChooser.test.tsx
@@ -27,9 +27,12 @@ vi.mock("@/react/hooks/useVueState", () => ({
}));
vi.mock("@/store", () => ({
- useSQLEditorTabStore: mocks.useSQLEditorTabStore,
useDBSchemaV1Store: mocks.useDBSchemaV1Store,
+}));
+
+vi.mock("@/react/stores/sqlEditor/tab-vue-state", () => ({
useConnectionOfCurrentSQLEditorTab: mocks.useConnectionOfCurrentSQLEditorTab,
+ useSQLEditorTabStore: mocks.useSQLEditorTabStore,
}));
vi.mock("@/router", () => ({
diff --git a/frontend/src/react/components/sql-editor/ContainerChooser.tsx b/frontend/src/react/components/sql-editor/ContainerChooser.tsx
index 1b091a7e45..09041c671b 100644
--- a/frontend/src/react/components/sql-editor/ContainerChooser.tsx
+++ b/frontend/src/react/components/sql-editor/ContainerChooser.tsx
@@ -1,12 +1,12 @@
import { useEffect, useMemo } from "react";
import { useTranslation } from "react-i18next";
import { useVueState } from "@/react/hooks/useVueState";
-import { router } from "@/router";
import {
useConnectionOfCurrentSQLEditorTab,
- useDBSchemaV1Store,
useSQLEditorTabStore,
-} from "@/store";
+} from "@/react/stores/sqlEditor/tab-vue-state";
+import { router } from "@/router";
+import { useDBSchemaV1Store } from "@/store";
import { Engine } from "@/types/proto-es/v1/common_pb";
import { ConnectChooser } from "./ConnectChooser";
diff --git a/frontend/src/react/components/sql-editor/DatabaseChooser.test.tsx b/frontend/src/react/components/sql-editor/DatabaseChooser.test.tsx
index 602fd2f4db..3bfd7e8009 100644
--- a/frontend/src/react/components/sql-editor/DatabaseChooser.test.tsx
+++ b/frontend/src/react/components/sql-editor/DatabaseChooser.test.tsx
@@ -11,8 +11,8 @@ const mocks = vi.hoisted(() => ({
useTranslation: vi.fn(() => ({ t: (key: string) => key })),
useVueState: vi.fn<(getter: () => unknown) => unknown>(),
useSQLEditorTabStore: vi.fn(),
- // Legacy Pinia useSQLEditorStore (editor.ts).
- useSQLEditorPiniaStore: vi.fn(),
+ // Legacy Pinia useSQLEditorVueState (editor.ts).
+ useSQLEditorVueState: vi.fn(),
useConnectionOfCurrentSQLEditorTab: vi.fn(),
// New zustand store setter.
setShowConnectionPanel: vi.fn(),
@@ -32,10 +32,15 @@ vi.mock("@/react/hooks/useVueState", () => ({
useVueState: mocks.useVueState,
}));
-vi.mock("@/store", () => ({
- useSQLEditorTabStore: mocks.useSQLEditorTabStore,
- useSQLEditorStore: mocks.useSQLEditorPiniaStore,
+vi.mock("@/store", () => ({}));
+
+vi.mock("@/react/stores/sqlEditor/tab-vue-state", () => ({
useConnectionOfCurrentSQLEditorTab: mocks.useConnectionOfCurrentSQLEditorTab,
+ useSQLEditorTabStore: mocks.useSQLEditorTabStore,
+}));
+
+vi.mock("@/react/stores/sqlEditor/editor-vue-state", () => ({
+ useSQLEditorVueState: mocks.useSQLEditorVueState,
}));
vi.mock("@/react/stores/sqlEditor", () => ({
@@ -58,7 +63,7 @@ vi.mock("@/utils", () => ({
getInstanceResource: mocks.getInstanceResource,
}));
-vi.mock("@/react/components/instance/constants", () => ({
+vi.mock("@/components/InstanceForm/constants", () => ({
EngineIconPath: mocks.EngineIconPath,
}));
@@ -112,7 +117,7 @@ beforeEach(async () => {
currentTab: { id: "tab1" },
isInBatchMode: false,
});
- mocks.useSQLEditorPiniaStore.mockReturnValue({ projectContextReady: true });
+ mocks.useSQLEditorVueState.mockReturnValue({ projectContextReady: true });
mocks.isValidInstanceName.mockReturnValue(true);
mocks.isValidDatabaseName.mockReturnValue(true);
mocks.getInstanceResource.mockReturnValue(mockInstance);
@@ -158,7 +163,7 @@ describe("DatabaseChooser", () => {
});
test("button is disabled when projectContextReady is false", () => {
- mocks.useSQLEditorPiniaStore.mockReturnValue({
+ mocks.useSQLEditorVueState.mockReturnValue({
projectContextReady: false,
});
const { container, render, unmount } = renderIntoContainer(
diff --git a/frontend/src/react/components/sql-editor/DatabaseChooser.tsx b/frontend/src/react/components/sql-editor/DatabaseChooser.tsx
index 5a86e37e51..0669733bd2 100644
--- a/frontend/src/react/components/sql-editor/DatabaseChooser.tsx
+++ b/frontend/src/react/components/sql-editor/DatabaseChooser.tsx
@@ -6,11 +6,11 @@ import { Tooltip } from "@/react/components/ui/tooltip";
import { useVueState } from "@/react/hooks/useVueState";
import { cn } from "@/react/lib/utils";
import { useSQLEditorStore } from "@/react/stores/sqlEditor";
+import { useSQLEditorVueState } from "@/react/stores/sqlEditor/editor-vue-state";
import {
useConnectionOfCurrentSQLEditorTab,
- useSQLEditorStore as useSQLEditorPiniaStore,
useSQLEditorTabStore,
-} from "@/store";
+} from "@/react/stores/sqlEditor/tab-vue-state";
import { isValidDatabaseName, isValidInstanceName } from "@/types";
import {
extractDatabaseResourceName,
@@ -30,7 +30,7 @@ type DatabaseChooserProps = {
export function DatabaseChooser({ disabled = false }: DatabaseChooserProps) {
const { t } = useTranslation();
const tabStore = useSQLEditorTabStore();
- const editorStore = useSQLEditorPiniaStore();
+ const editorStore = useSQLEditorVueState();
const setShowConnectionPanel = useSQLEditorStore(
(s) => s.setShowConnectionPanel
);
diff --git a/frontend/src/react/components/sql-editor/DiagramPanel.tsx b/frontend/src/react/components/sql-editor/DiagramPanel.tsx
index 6407cef254..fa42b174cf 100644
--- a/frontend/src/react/components/sql-editor/DiagramPanel.tsx
+++ b/frontend/src/react/components/sql-editor/DiagramPanel.tsx
@@ -1,9 +1,7 @@
import { SchemaDiagram } from "@/react/components/SchemaDiagram";
import { useVueState } from "@/react/hooks/useVueState";
-import {
- useConnectionOfCurrentSQLEditorTab,
- useDBSchemaV1Store,
-} from "@/store";
+import { useConnectionOfCurrentSQLEditorTab } from "@/react/stores/sqlEditor/tab-vue-state";
+import { useDBSchemaV1Store } from "@/store";
/**
* React port of `frontend/src/views/sql-editor/EditorPanel/Panels/DiagramPanel/DiagramPanel.vue`.
diff --git a/frontend/src/react/components/sql-editor/EditorAction.test.tsx b/frontend/src/react/components/sql-editor/EditorAction.test.tsx
index 77bda7919f..559070d6cb 100644
--- a/frontend/src/react/components/sql-editor/EditorAction.test.tsx
+++ b/frontend/src/react/components/sql-editor/EditorAction.test.tsx
@@ -14,7 +14,7 @@ const mocks = vi.hoisted(() => ({
})),
useVueState: vi.fn<(getter: () => unknown) => unknown>(),
useSQLEditorTabStore: vi.fn(),
- useSQLEditorStore: vi.fn(),
+ useSQLEditorVueState: vi.fn(),
useUIStateStore: vi.fn(),
useWorkSheetStore: vi.fn(),
useWorkSheetAndTabStore: vi.fn(),
@@ -33,12 +33,18 @@ vi.mock("@/react/hooks/useVueState", () => ({
}));
vi.mock("@/store", () => ({
- useSQLEditorTabStore: mocks.useSQLEditorTabStore,
- useSQLEditorStore: mocks.useSQLEditorStore,
useUIStateStore: mocks.useUIStateStore,
useWorkSheetStore: mocks.useWorkSheetStore,
useWorkSheetAndTabStore: mocks.useWorkSheetAndTabStore,
+}));
+
+vi.mock("@/react/stores/sqlEditor/tab-vue-state", () => ({
useConnectionOfCurrentSQLEditorTab: mocks.useConnectionOfCurrentSQLEditorTab,
+ useSQLEditorTabStore: mocks.useSQLEditorTabStore,
+}));
+
+vi.mock("@/react/stores/sqlEditor/editor-vue-state", () => ({
+ useSQLEditorVueState: mocks.useSQLEditorVueState,
}));
vi.mock("@/utils", () => ({
@@ -174,7 +180,7 @@ const setup = (options: SetupOptions = {}) => {
isDisconnected,
updateCurrentTab,
});
- mocks.useSQLEditorStore.mockReturnValue({ resultRowsLimit: 500 });
+ mocks.useSQLEditorVueState.mockReturnValue({ resultRowsLimit: 500 });
mocks.useUIStateStore.mockReturnValue({ saveIntroStateByKey });
mocks.useWorkSheetStore.mockReturnValue({
getWorksheetByName: vi.fn(() => ({
diff --git a/frontend/src/react/components/sql-editor/EditorAction.tsx b/frontend/src/react/components/sql-editor/EditorAction.tsx
index 996092fced..74795d97cc 100644
--- a/frontend/src/react/components/sql-editor/EditorAction.tsx
+++ b/frontend/src/react/components/sql-editor/EditorAction.tsx
@@ -10,10 +10,12 @@ import {
import { Tooltip } from "@/react/components/ui/tooltip";
import { useVueState } from "@/react/hooks/useVueState";
import { cn } from "@/react/lib/utils";
+import { useSQLEditorVueState } from "@/react/stores/sqlEditor/editor-vue-state";
import {
useConnectionOfCurrentSQLEditorTab,
- useSQLEditorStore,
useSQLEditorTabStore,
+} from "@/react/stores/sqlEditor/tab-vue-state";
+import {
useUIStateStore,
useWorkSheetAndTabStore,
useWorkSheetStore,
@@ -43,7 +45,7 @@ type Props = {
export function EditorAction({ onExecute }: Props) {
const { t } = useTranslation();
const tabStore = useSQLEditorTabStore();
- const editorStore = useSQLEditorStore();
+ const editorStore = useSQLEditorVueState();
const uiStateStore = useUIStateStore();
const worksheetStore = useWorkSheetStore();
const sheetAndTabStore = useWorkSheetAndTabStore();
@@ -236,10 +238,7 @@ export function EditorAction({ onExecute }: Props) {
/>
</Tooltip>
<PopoverContent align="end" sideOffset={4}>
- <SharePopoverBody
- worksheet={currentWorksheet}
- onUpdated={() => setShareOpen(false)}
- />
+ <SharePopoverBody worksheet={currentWorksheet} />
</PopoverContent>
</Popover>
</>
diff --git a/frontend/src/react/components/sql-editor/ExecuteHint.tsx b/frontend/src/react/components/sql-editor/ExecuteHint.tsx
index af3bedb2dd..0abc8ff323 100644
--- a/frontend/src/react/components/sql-editor/ExecuteHint.tsx
+++ b/frontend/src/react/components/sql-editor/ExecuteHint.tsx
@@ -4,14 +4,14 @@ import { Alert } from "@/react/components/ui/alert";
import { Button } from "@/react/components/ui/button";
import { useVueState } from "@/react/hooks/useVueState";
import { applyPlanTitleToQuery } from "@/react/lib/plan/title";
+import { useSQLEditorVueState } from "@/react/stores/sqlEditor/editor-vue-state";
+import { useSQLEditorTabStore } from "@/react/stores/sqlEditor/tab-vue-state";
import { router } from "@/router";
import { PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL } from "@/router/dashboard/projectV1";
import {
pushNotification,
useDatabaseV1Store,
useProjectV1Store,
- useSQLEditorStore,
- useSQLEditorTabStore,
useStorageStore,
} from "@/store";
import { unknownProject } from "@/types";
@@ -35,7 +35,7 @@ type Props = {
export function ExecuteHint({ database, onClose }: Props) {
const { t } = useTranslation();
const tabStore = useSQLEditorTabStore();
- const editorStore = useSQLEditorStore();
+ const editorStore = useSQLEditorVueState();
const databaseStore = useDatabaseV1Store();
const projectStore = useProjectV1Store();
const storageStore = useStorageStore();
diff --git a/frontend/src/react/components/sql-editor/ExecutingHintModal.test.tsx b/frontend/src/react/components/sql-editor/ExecutingHintModal.test.tsx
index f95639d8aa..74c19cac9c 100644
--- a/frontend/src/react/components/sql-editor/ExecutingHintModal.test.tsx
+++ b/frontend/src/react/components/sql-editor/ExecutingHintModal.test.tsx
@@ -10,7 +10,7 @@ import { beforeEach, describe, expect, test, vi } from "vitest";
const mocks = vi.hoisted(() => ({
useTranslation: vi.fn(() => ({ t: (key: string) => key })),
useVueState: vi.fn<(getter: () => unknown) => unknown>(),
- useSQLEditorStore: vi.fn(),
+ useSQLEditorVueState: vi.fn(),
}));
vi.mock("react-i18next", () => ({
@@ -21,8 +21,10 @@ vi.mock("@/react/hooks/useVueState", () => ({
useVueState: mocks.useVueState,
}));
-vi.mock("@/store", () => ({
- useSQLEditorStore: mocks.useSQLEditorStore,
+vi.mock("@/store", () => ({}));
+
+vi.mock("@/react/stores/sqlEditor/editor-vue-state", () => ({
+ useSQLEditorVueState: mocks.useSQLEditorVueState,
}));
vi.mock("@/react/components/ui/dialog", () => ({
@@ -99,7 +101,7 @@ const setup = (
isShowExecutingHint: options.show ?? false,
executingHintDatabase: options.database,
};
- mocks.useSQLEditorStore.mockReturnValue(store);
+ mocks.useSQLEditorVueState.mockReturnValue(store);
mocks.useVueState.mockImplementation((getter) => getter());
return store;
};
diff --git a/frontend/src/react/components/sql-editor/ExecutingHintModal.tsx b/frontend/src/react/components/sql-editor/ExecutingHintModal.tsx
index 40c0a51015..87e5444e95 100644
--- a/frontend/src/react/components/sql-editor/ExecutingHintModal.tsx
+++ b/frontend/src/react/components/sql-editor/ExecutingHintModal.tsx
@@ -5,7 +5,7 @@ import {
DialogTitle,
} from "@/react/components/ui/dialog";
import { useVueState } from "@/react/hooks/useVueState";
-import { useSQLEditorStore } from "@/store";
+import { useSQLEditorVueState } from "@/react/stores/sqlEditor/editor-vue-state";
import { ExecuteHint } from "./ExecuteHint";
/**
@@ -15,7 +15,7 @@ import { ExecuteHint } from "./ExecuteHint";
*/
export function ExecutingHintModal() {
const { t } = useTranslation();
- const editorStore = useSQLEditorStore();
+ const editorStore = useSQLEditorVueState();
const show = useVueState(() => editorStore.isShowExecutingHint);
const database = useVueState(() => editorStore.executingHintDatabase);
diff --git a/frontend/src/react/components/sql-editor/FolderForm.test.tsx b/frontend/src/react/components/sql-editor/FolderForm.test.tsx
index 5e3ce654ba..0010ada622 100644
--- a/frontend/src/react/components/sql-editor/FolderForm.test.tsx
+++ b/frontend/src/react/components/sql-editor/FolderForm.test.tsx
@@ -20,7 +20,7 @@ globalThis.ResizeObserver = class ResizeObserver {
const mocks = vi.hoisted(() => ({
useTranslation: vi.fn(() => ({ t: (key: string) => key })),
useVueState: vi.fn<(getter: () => unknown) => unknown>(),
- useSQLEditorWorksheetStore: vi.fn(),
+ useSheetContextByView: vi.fn(),
useClickOutside: vi.fn(),
onSelectCallback: vi.fn(),
}));
@@ -33,8 +33,8 @@ vi.mock("@/react/hooks/useVueState", () => ({
useVueState: mocks.useVueState,
}));
-vi.mock("@/store", () => ({
- useSQLEditorWorksheetStore: mocks.useSQLEditorWorksheetStore,
+vi.mock("@/views/sql-editor/Sheet", () => ({
+ useSheetContextByView: mocks.useSheetContextByView,
}));
vi.mock("@/react/hooks/useClickOutside", () => ({
@@ -177,9 +177,7 @@ const setupDefaultMocks = () => {
},
};
- mocks.useSQLEditorWorksheetStore.mockReturnValue({
- getContextByView: vi.fn(() => viewContext),
- });
+ mocks.useSheetContextByView.mockReturnValue(viewContext);
};
const renderIntoContainer = (element: ReactElement) => {
diff --git a/frontend/src/react/components/sql-editor/FolderForm.tsx b/frontend/src/react/components/sql-editor/FolderForm.tsx
index a5d85c0633..bcba9e6085 100644
--- a/frontend/src/react/components/sql-editor/FolderForm.tsx
+++ b/frontend/src/react/components/sql-editor/FolderForm.tsx
@@ -8,8 +8,8 @@ import type { TreeDataNode } from "@/react/components/ui/tree";
import { Tree } from "@/react/components/ui/tree";
import { useVueState } from "@/react/hooks/useVueState";
import { cn } from "@/react/lib/utils";
-import { useSQLEditorWorksheetStore } from "@/store";
import type { WorksheetFolderNode } from "@/views/sql-editor/Sheet";
+import { useSheetContextByView } from "@/views/sql-editor/Sheet";
import { TreeNodePrefix } from "./TreeNodePrefix";
type Props = {
@@ -30,8 +30,7 @@ function toTreeData(
export function FolderForm({ folder, onFolderChange }: Props) {
const { t } = useTranslation();
- const sheetStore = useSQLEditorWorksheetStore();
- const viewContext = sheetStore.getContextByView("my");
+ const viewContext = useSheetContextByView("my");
const folderTree = useVueState(() => viewContext.folderTree.value);
const rootPath = useVueState(() => viewContext.folderContext.rootPath.value);
diff --git a/frontend/src/react/components/sql-editor/GutterBar.test.tsx b/frontend/src/react/components/sql-editor/GutterBar.test.tsx
index 6d86b6ef66..a9e9c38082 100644
--- a/frontend/src/react/components/sql-editor/GutterBar.test.tsx
+++ b/frontend/src/react/components/sql-editor/GutterBar.test.tsx
@@ -10,9 +10,9 @@ import { beforeEach, describe, expect, test, vi } from "vitest";
const mocks = vi.hoisted(() => ({
useTranslation: vi.fn(() => ({ t: (key: string) => key })),
useVueState: vi.fn<(getter: () => unknown) => unknown>(),
- // Pinia legacy useSQLEditorStore (editor.ts) — still imported by GutterBar
+ // Pinia legacy useSQLEditorVueState (editor.ts) — still imported by GutterBar
// until that store is migrated.
- useSQLEditorPiniaStore: vi.fn(),
+ useSQLEditorVueState: vi.fn(),
useProjectV1Store: vi.fn(),
// New zustand store.
state: {
@@ -31,10 +31,13 @@ vi.mock("@/react/hooks/useVueState", () => ({
}));
vi.mock("@/store", () => ({
- useSQLEditorStore: mocks.useSQLEditorPiniaStore,
useProjectV1Store: mocks.useProjectV1Store,
}));
+vi.mock("@/react/stores/sqlEditor/editor-vue-state", () => ({
+ useSQLEditorVueState: mocks.useSQLEditorVueState,
+}));
+
vi.mock("@/react/stores/sqlEditor", () => ({
useSQLEditorStore: (
selector: (s: {
@@ -95,7 +98,7 @@ const renderIntoContainer = (element: ReactElement) => {
beforeEach(async () => {
vi.clearAllMocks();
- mocks.useSQLEditorPiniaStore.mockReturnValue({ project: "projects/test" });
+ mocks.useSQLEditorVueState.mockReturnValue({ project: "projects/test" });
mocks.useProjectV1Store.mockReturnValue({
getProjectByName: () => ({ allowJustInTimeAccess: false }),
});
diff --git a/frontend/src/react/components/sql-editor/GutterBar.tsx b/frontend/src/react/components/sql-editor/GutterBar.tsx
index 76dbfb10ac..e9db4c257b 100644
--- a/frontend/src/react/components/sql-editor/GutterBar.tsx
+++ b/frontend/src/react/components/sql-editor/GutterBar.tsx
@@ -3,13 +3,11 @@ import { Separator } from "@/react/components/ui/separator";
import { useVueState } from "@/react/hooks/useVueState";
import type { AsidePanelTab } from "@/react/stores/sqlEditor";
import { useSQLEditorStore } from "@/react/stores/sqlEditor";
+import { useSQLEditorVueState } from "@/react/stores/sqlEditor/editor-vue-state";
import { router } from "@/router";
import { PROJECT_V1_ROUTE_DETAIL } from "@/router/dashboard/projectV1";
import { WORKSPACE_ROUTE_LANDING } from "@/router/dashboard/workspaceRoutes";
-import {
- useProjectV1Store,
- useSQLEditorStore as useSQLEditorPiniaStore,
-} from "@/store";
+import { useProjectV1Store } from "@/store";
import { TabItem } from "./TabItem";
/**
@@ -20,7 +18,7 @@ import { TabItem } from "./TabItem";
* Replaces frontend/src/views/sql-editor/AsidePanel/GutterBar/GutterBar.vue.
*/
export function GutterBar() {
- const editorStore = useSQLEditorPiniaStore();
+ const editorStore = useSQLEditorVueState();
const projectStore = useProjectV1Store();
const setAsidePanelTab = useSQLEditorStore((s) => s.setAsidePanelTab);
diff --git a/frontend/src/react/components/sql-editor/HistoryPane.test.tsx b/frontend/src/react/components/sql-editor/HistoryPane.test.tsx
index 5e54477efc..3a747d5658 100644
--- a/frontend/src/react/components/sql-editor/HistoryPane.test.tsx
+++ b/frontend/src/react/components/sql-editor/HistoryPane.test.tsx
@@ -11,8 +11,19 @@ const mocks = vi.hoisted(() => ({
useTranslation: vi.fn(() => ({ t: (key: string) => key })),
useVueState: vi.fn<(getter: () => unknown) => unknown>(),
useSQLEditorTabStore: vi.fn(),
- useSQLEditorStore: vi.fn(),
- useSQLEditorQueryHistoryStore: vi.fn(),
+ // Legacy Pinia editor store.
+ useSQLEditorVueState: vi.fn(),
+ // Mutable per-test state for the zustand mock.
+ historyEntry: {
+ queryHistories: [] as Array<{
+ name: string;
+ statement: string;
+ createTime: { seconds: bigint; nanos: number } | undefined;
+ }>,
+ nextPageToken: "" as string | undefined,
+ },
+ fetchQueryHistoryList: vi.fn().mockResolvedValue({ queryHistories: [] }),
+ resetPageToken: vi.fn(),
pushNotification: vi.fn(),
sqlEditorEventsEmit: vi.fn().mockResolvedValue(undefined),
}));
@@ -26,12 +37,31 @@ vi.mock("@/react/hooks/useVueState", () => ({
}));
vi.mock("@/store", () => ({
- useSQLEditorTabStore: mocks.useSQLEditorTabStore,
- useSQLEditorStore: mocks.useSQLEditorStore,
- useSQLEditorQueryHistoryStore: mocks.useSQLEditorQueryHistoryStore,
pushNotification: mocks.pushNotification,
}));
+vi.mock("@/react/stores/sqlEditor/tab-vue-state", () => ({
+ useSQLEditorTabStore: mocks.useSQLEditorTabStore,
+}));
+
+vi.mock("@/react/stores/sqlEditor/editor-vue-state", () => ({
+ useSQLEditorVueState: mocks.useSQLEditorVueState,
+}));
+
+vi.mock("@/react/stores/sqlEditor", () => ({
+ selectQueryHistoryEntry: () => () => mocks.historyEntry,
+ useSQLEditorStore: (
+ selector: (s: {
+ fetchQueryHistoryList: typeof mocks.fetchQueryHistoryList;
+ resetPageToken: typeof mocks.resetPageToken;
+ }) => unknown
+ ) =>
+ selector({
+ fetchQueryHistoryList: mocks.fetchQueryHistoryList,
+ resetPageToken: mocks.resetPageToken,
+ }),
+}));
+
vi.mock("@/views/sql-editor/events", () => ({
sqlEditorEvents: {
emit: mocks.sqlEditorEventsEmit,
@@ -124,18 +154,12 @@ beforeEach(async () => {
addTab: vi.fn(),
});
- mocks.useSQLEditorStore.mockReturnValue({
+ mocks.useSQLEditorVueState.mockReturnValue({
project: "projects/proj1",
});
- mocks.useSQLEditorQueryHistoryStore.mockReturnValue({
- getQueryHistoryList: vi.fn(() => ({
- queryHistories: [],
- nextPageToken: "",
- })),
- fetchQueryHistoryList: vi.fn().mockResolvedValue({ queryHistories: [] }),
- resetPageToken: vi.fn(),
- });
+ mocks.historyEntry = { queryHistories: [], nextPageToken: "" };
+ mocks.fetchQueryHistoryList.mockResolvedValue({ queryHistories: [] });
mocks.useVueState.mockImplementation((getter: () => unknown) => getter());
@@ -155,17 +179,6 @@ afterEach(() => {
describe("HistoryPane", () => {
test("empty state — shows no-history-found when empty list and not loading", () => {
- const queryHistoryStore = {
- getQueryHistoryList: vi.fn(() => ({
- queryHistories: [],
- nextPageToken: "",
- })),
- fetchQueryHistoryList: vi.fn().mockResolvedValue({ queryHistories: [] }),
- resetPageToken: vi.fn(),
- };
- mocks.useSQLEditorQueryHistoryStore.mockReturnValue(queryHistoryStore);
- mocks.useVueState.mockImplementation((getter: () => unknown) => getter());
-
const { container, render, unmount } = renderIntoContainer(<HistoryPane />);
render();
@@ -174,22 +187,13 @@ describe("HistoryPane", () => {
});
test("rendered history list — both entries visible via statement text", () => {
- const histories = [
- makeHistory("histories/h1", "SELECT * FROM users"),
- makeHistory("histories/h2", "SELECT id FROM orders"),
- ];
- const queryHistoryStore = {
- getQueryHistoryList: vi.fn(() => ({
- queryHistories: histories,
- nextPageToken: "",
- })),
- fetchQueryHistoryList: vi
- .fn()
- .mockResolvedValue({ queryHistories: histories }),
- resetPageToken: vi.fn(),
+ mocks.historyEntry = {
+ queryHistories: [
+ makeHistory("histories/h1", "SELECT * FROM users"),
+ makeHistory("histories/h2", "SELECT id FROM orders"),
+ ],
+ nextPageToken: "",
};
- mocks.useSQLEditorQueryHistoryStore.mockReturnValue(queryHistoryStore);
- mocks.useVueState.mockImplementation((getter: () => unknown) => getter());
const { container, render, unmount } = renderIntoContainer(<HistoryPane />);
render();
@@ -202,30 +206,14 @@ describe("HistoryPane", () => {
test("debounced search — fetchQueryHistoryList called with statement after timer", async () => {
vi.useFakeTimers();
- const fetchQueryHistoryList = vi
- .fn()
- .mockResolvedValue({ queryHistories: [] });
- const queryHistoryStore = {
- getQueryHistoryList: vi.fn(() => ({
- queryHistories: [],
- nextPageToken: "",
- })),
- fetchQueryHistoryList,
- resetPageToken: vi.fn(),
- };
- mocks.useSQLEditorQueryHistoryStore.mockReturnValue(queryHistoryStore);
- mocks.useVueState.mockImplementation((getter: () => unknown) => getter());
-
const { container, render, unmount } = renderIntoContainer(<HistoryPane />);
render();
- // Find the search input and type
const searchInput = container.querySelector(
"[data-testid='search-input']"
) as HTMLInputElement;
expect(searchInput).not.toBeNull();
- // Type into the search input by directly setting value and firing input event
act(() => {
Object.defineProperty(searchInput, "value", {
writable: true,
@@ -239,35 +227,23 @@ describe("HistoryPane", () => {
searchInput.dispatchEvent(inputEvent);
});
- // Advance timers to trigger debounce
await act(async () => {
vi.advanceTimersByTime(300);
});
- // fetchQueryHistoryList should have been called (initial load + after search)
- expect(fetchQueryHistoryList).toHaveBeenCalled();
+ expect(mocks.fetchQueryHistoryList).toHaveBeenCalled();
unmount();
});
test("click history row → emits append-editor-content event", async () => {
- const histories = [makeHistory("histories/h1", "SELECT * FROM users")];
- const queryHistoryStore = {
- getQueryHistoryList: vi.fn(() => ({
- queryHistories: histories,
- nextPageToken: "",
- })),
- fetchQueryHistoryList: vi
- .fn()
- .mockResolvedValue({ queryHistories: histories }),
- resetPageToken: vi.fn(),
+ mocks.historyEntry = {
+ queryHistories: [makeHistory("histories/h1", "SELECT * FROM users")],
+ nextPageToken: "",
};
- mocks.useSQLEditorQueryHistoryStore.mockReturnValue(queryHistoryStore);
- mocks.useVueState.mockImplementation((getter: () => unknown) => getter());
const { container, render, unmount } = renderIntoContainer(<HistoryPane />);
render();
- // Find history row (first div in the history list)
const historyRow = container.querySelector(
"[data-history-row]"
) as HTMLElement;
@@ -285,19 +261,10 @@ describe("HistoryPane", () => {
});
test("click copy button → clipboard writeText and pushNotification called", async () => {
- const histories = [makeHistory("histories/h1", "SELECT * FROM users")];
- const queryHistoryStore = {
- getQueryHistoryList: vi.fn(() => ({
- queryHistories: histories,
- nextPageToken: "",
- })),
- fetchQueryHistoryList: vi
- .fn()
- .mockResolvedValue({ queryHistories: histories }),
- resetPageToken: vi.fn(),
+ mocks.historyEntry = {
+ queryHistories: [makeHistory("histories/h1", "SELECT * FROM users")],
+ nextPageToken: "",
};
- mocks.useSQLEditorQueryHistoryStore.mockReturnValue(queryHistoryStore);
- mocks.useVueState.mockImplementation((getter: () => unknown) => getter());
const { container, render, unmount } = renderIntoContainer(<HistoryPane />);
render();
diff --git a/frontend/src/react/components/sql-editor/HistoryPane.tsx b/frontend/src/react/components/sql-editor/HistoryPane.tsx
index c05aa4fbc4..e15780ff4a 100644
--- a/frontend/src/react/components/sql-editor/HistoryPane.tsx
+++ b/frontend/src/react/components/sql-editor/HistoryPane.tsx
@@ -12,13 +12,14 @@ import { useTranslation } from "react-i18next";
import { Button } from "@/react/components/ui/button";
import { SearchInput } from "@/react/components/ui/search-input";
import { useVueState } from "@/react/hooks/useVueState";
-import type { QueryHistoryFilter } from "@/store";
+import type { QueryHistoryFilter } from "@/react/stores/sqlEditor";
import {
- pushNotification,
- useSQLEditorQueryHistoryStore,
+ selectQueryHistoryEntry,
useSQLEditorStore,
- useSQLEditorTabStore,
-} from "@/store";
+} from "@/react/stores/sqlEditor";
+import { useSQLEditorVueState } from "@/react/stores/sqlEditor/editor-vue-state";
+import { useSQLEditorTabStore } from "@/react/stores/sqlEditor/tab-vue-state";
+import { pushNotification } from "@/store";
import { DEBOUNCE_SEARCH_DELAY, getDateForPbTimestampProtoEs } from "@/types";
import type { QueryHistory } from "@/types/proto-es/v1/sql_service_pb";
import { getHighlightHTMLByKeyWords } from "@/utils";
@@ -32,8 +33,11 @@ export function HistoryPane() {
const { t } = useTranslation();
const tabStore = useSQLEditorTabStore();
- const editorStore = useSQLEditorStore();
- const queryHistoryStore = useSQLEditorQueryHistoryStore();
+ const editorStore = useSQLEditorVueState();
+ const fetchQueryHistoryList = useSQLEditorStore(
+ (s) => s.fetchQueryHistoryList
+ );
+ const resetPageToken = useSQLEditorStore((s) => s.resetPageToken);
const [searchText, setSearchText] = useState("");
const [loading, setLoading] = useState(false);
@@ -57,18 +61,16 @@ export function HistoryPane() {
[currentTabDatabase, project, searchText]
);
- const historyData = useVueState(() =>
- queryHistoryStore.getQueryHistoryList(historyQuery)
- );
+ const historyData = useSQLEditorStore(selectQueryHistoryEntry(historyQuery));
const fetchHistory = useCallback(async () => {
setLoading(true);
try {
- await queryHistoryStore.fetchQueryHistoryList(historyQuery);
+ await fetchQueryHistoryList(historyQuery);
} finally {
setLoading(false);
}
- }, [queryHistoryStore, historyQuery]);
+ }, [fetchQueryHistoryList, historyQuery]);
// Debounced fetch on query change — only when list is empty (initial load / filter change)
useEffect(() => {
@@ -96,10 +98,10 @@ export function HistoryPane() {
const onSearchUpdate = useCallback(
(next: string) => {
- queryHistoryStore.resetPageToken({ ...historyQuery, statement: next });
+ resetPageToken({ ...historyQuery, statement: next });
setSearchText(next);
},
- [queryHistoryStore, historyQuery]
+ [resetPageToken, historyQuery]
);
const titleOfQueryHistory = (h: QueryHistory) =>
diff --git a/frontend/src/react/components/sql-editor/MaskingReasonPopover.test.tsx b/frontend/src/react/components/sql-editor/MaskingReasonPopover.test.tsx
index 2066e85b5f..b137ca8da8 100644
--- a/frontend/src/react/components/sql-editor/MaskingReasonPopover.test.tsx
+++ b/frontend/src/react/components/sql-editor/MaskingReasonPopover.test.tsx
@@ -11,7 +11,7 @@ const mocks = vi.hoisted(() => ({
useTranslation: vi.fn(() => ({ t: (key: string) => key })),
useVueState: vi.fn<(getter: () => unknown) => unknown>(),
useProjectV1Store: vi.fn(),
- useSQLEditorStore: vi.fn(),
+ useSQLEditorVueState: vi.fn(),
hasFeature: vi.fn(() => true),
}));
@@ -25,10 +25,13 @@ vi.mock("@/react/hooks/useVueState", () => ({
vi.mock("@/store", () => ({
useProjectV1Store: mocks.useProjectV1Store,
- useSQLEditorStore: mocks.useSQLEditorStore,
hasFeature: mocks.hasFeature,
}));
+vi.mock("@/react/stores/sqlEditor/editor-vue-state", () => ({
+ useSQLEditorVueState: mocks.useSQLEditorVueState,
+}));
+
vi.mock("@/types/proto-es/v1/subscription_service_pb", () => ({
PlanFeature: { FEATURE_JIT: 5 },
}));
@@ -143,7 +146,7 @@ const setupDefaultMocks = (allowJIT = false) => {
allowJustInTimeAccess: allowJIT,
})),
});
- mocks.useSQLEditorStore.mockReturnValue({ project: "projects/proj1" });
+ mocks.useSQLEditorVueState.mockReturnValue({ project: "projects/proj1" });
mocks.hasFeature.mockReturnValue(true);
mocks.useVueState.mockImplementation((getter: () => unknown) => getter());
};
diff --git a/frontend/src/react/components/sql-editor/MaskingReasonPopover.tsx b/frontend/src/react/components/sql-editor/MaskingReasonPopover.tsx
index 3b36a7c3f3..114645769b 100644
--- a/frontend/src/react/components/sql-editor/MaskingReasonPopover.tsx
+++ b/frontend/src/react/components/sql-editor/MaskingReasonPopover.tsx
@@ -8,7 +8,8 @@ import {
PopoverTrigger,
} from "@/react/components/ui/popover";
import { useVueState } from "@/react/hooks/useVueState";
-import { hasFeature, useProjectV1Store, useSQLEditorStore } from "@/store";
+import { useSQLEditorVueState } from "@/react/stores/sqlEditor/editor-vue-state";
+import { hasFeature, useProjectV1Store } from "@/store";
import type { MaskingReason } from "@/types/proto-es/v1/sql_service_pb";
import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";
import { AccessGrantRequestDrawer } from "./AccessGrantRequestDrawer";
@@ -30,7 +31,7 @@ export function MaskingReasonPopover({
const [showDrawer, setShowDrawer] = useState(false);
const projectStore = useProjectV1Store();
- const editorStore = useSQLEditorStore();
+ const editorStore = useSQLEditorVueState();
const projectName = useVueState(() => editorStore.project);
const project = useVueState(() => projectStore.getProjectByName(projectName));
diff --git a/frontend/src/react/components/sql-editor/OpenAIButton.test.tsx b/frontend/src/react/components/sql-editor/OpenAIButton.test.tsx
index 0fd7c14701..dd562a9446 100644
--- a/frontend/src/react/components/sql-editor/OpenAIButton.test.tsx
+++ b/frontend/src/react/components/sql-editor/OpenAIButton.test.tsx
@@ -36,9 +36,12 @@ vi.mock("@/react/hooks/useVueState", () => ({
}));
vi.mock("@/store", () => ({
- useSQLEditorTabStore: mocks.useSQLEditorTabStore,
useSettingV1Store: mocks.useSettingV1Store,
+}));
+
+vi.mock("@/react/stores/sqlEditor/tab-vue-state", () => ({
useConnectionOfCurrentSQLEditorTab: mocks.useConnectionOfCurrentSQLEditorTab,
+ useSQLEditorTabStore: mocks.useSQLEditorTabStore,
}));
vi.mock("@/react/stores/sqlEditor", () => ({
diff --git a/frontend/src/react/components/sql-editor/OpenAIButton.tsx b/frontend/src/react/components/sql-editor/OpenAIButton.tsx
index bfafdf28e2..7ec98a27d5 100644
--- a/frontend/src/react/components/sql-editor/OpenAIButton.tsx
+++ b/frontend/src/react/components/sql-editor/OpenAIButton.tsx
@@ -18,13 +18,13 @@ import {
import { useVueState } from "@/react/hooks/useVueState";
import { cn } from "@/react/lib/utils";
import { useSQLEditorStore } from "@/react/stores/sqlEditor";
-import { router } from "@/router";
-import { SETTING_ROUTE_WORKSPACE_GENERAL } from "@/router/dashboard/workspaceSetting";
import {
useConnectionOfCurrentSQLEditorTab,
- useSettingV1Store,
useSQLEditorTabStore,
-} from "@/store";
+} from "@/react/stores/sqlEditor/tab-vue-state";
+import { router } from "@/router";
+import { SETTING_ROUTE_WORKSPACE_GENERAL } from "@/router/dashboard/workspaceSetting";
+import { useSettingV1Store } from "@/store";
import { Setting_SettingName } from "@/types/proto-es/v1/setting_service_pb";
import { hasWorkspacePermissionV2, nextAnimationFrame } from "@/utils";
diff --git a/frontend/src/react/components/sql-editor/Panels/ExternalTablesPanel/ExternalTablesPanel.tsx b/frontend/src/react/components/sql-editor/Panels/ExternalTablesPanel/ExternalTablesPanel.tsx
index 946894a4e8..c629564d70 100644
--- a/frontend/src/react/components/sql-editor/Panels/ExternalTablesPanel/ExternalTablesPanel.tsx
+++ b/frontend/src/react/components/sql-editor/Panels/ExternalTablesPanel/ExternalTablesPanel.tsx
@@ -2,10 +2,8 @@ import { ChevronLeft, Table as TableIcon } from "lucide-react";
import { useState } from "react";
import { Button } from "@/react/components/ui/button";
import { useVueState } from "@/react/hooks/useVueState";
-import {
- useConnectionOfCurrentSQLEditorTab,
- useDBSchemaV1Store,
-} from "@/store";
+import { useConnectionOfCurrentSQLEditorTab } from "@/react/stores/sqlEditor/tab-vue-state";
+import { useDBSchemaV1Store } from "@/store";
import { PanelSearchBox } from "../common/PanelSearchBox";
import { ColumnsTable } from "../common/tables/ColumnsTable";
import { useViewStateNav } from "../common/useViewStateNav";
diff --git a/frontend/src/react/components/sql-editor/Panels/FunctionsPanel/FunctionsPanel.tsx b/frontend/src/react/components/sql-editor/Panels/FunctionsPanel/FunctionsPanel.tsx
index c17e8eac2d..216d61d789 100644
--- a/frontend/src/react/components/sql-editor/Panels/FunctionsPanel/FunctionsPanel.tsx
+++ b/frontend/src/react/components/sql-editor/Panels/FunctionsPanel/FunctionsPanel.tsx
@@ -2,10 +2,8 @@ import { ChevronLeft, FunctionSquare } from "lucide-react";
import { useState } from "react";
import { Button } from "@/react/components/ui/button";
import { useVueState } from "@/react/hooks/useVueState";
-import {
- useConnectionOfCurrentSQLEditorTab,
- useDBSchemaV1Store,
-} from "@/store";
+import { useConnectionOfCurrentSQLEditorTab } from "@/react/stores/sqlEditor/tab-vue-state";
+import { useDBSchemaV1Store } from "@/store";
import {
extractKeyWithPosition,
keyWithPosition,
diff --git a/frontend/src/react/components/sql-editor/Panels/InfoPanel/InfoPanel.tsx b/frontend/src/react/components/sql-editor/Panels/InfoPanel/InfoPanel.tsx
index 54e1b675a4..b2fd33c49a 100644
--- a/frontend/src/react/components/sql-editor/Panels/InfoPanel/InfoPanel.tsx
+++ b/frontend/src/react/components/sql-editor/Panels/InfoPanel/InfoPanel.tsx
@@ -2,10 +2,8 @@ import { useState } from "react";
import { useTranslation } from "react-i18next";
import { useVueState } from "@/react/hooks/useVueState";
import { DatabaseOverviewInfo } from "@/react/pages/project/database-detail/overview/DatabaseOverviewInfo";
-import {
- useConnectionOfCurrentSQLEditorTab,
- useDBSchemaV1Store,
-} from "@/store";
+import { useConnectionOfCurrentSQLEditorTab } from "@/react/stores/sqlEditor/tab-vue-state";
+import { useDBSchemaV1Store } from "@/store";
import {
getInstanceResource,
instanceV1SupportsExternalTable,
diff --git a/frontend/src/react/components/sql-editor/Panels/PackagesPanel/PackagesPanel.tsx b/frontend/src/react/components/sql-editor/Panels/PackagesPanel/PackagesPanel.tsx
index ea4b036552..4931563ad1 100644
--- a/frontend/src/react/components/sql-editor/Panels/PackagesPanel/PackagesPanel.tsx
+++ b/frontend/src/react/components/sql-editor/Panels/PackagesPanel/PackagesPanel.tsx
@@ -2,10 +2,8 @@ import { ChevronLeft, Package } from "lucide-react";
import { useState } from "react";
import { Button } from "@/react/components/ui/button";
import { useVueState } from "@/react/hooks/useVueState";
-import {
- useConnectionOfCurrentSQLEditorTab,
- useDBSchemaV1Store,
-} from "@/store";
+import { useConnectionOfCurrentSQLEditorTab } from "@/react/stores/sqlEditor/tab-vue-state";
+import { useDBSchemaV1Store } from "@/store";
import {
extractKeyWithPosition,
keyWithPosition,
diff --git a/frontend/src/react/components/sql-editor/Panels/Panels.tsx b/frontend/src/react/components/sql-editor/Panels/Panels.tsx
index 95c01cfccf..2635c81dc0 100644
--- a/frontend/src/react/components/sql-editor/Panels/Panels.tsx
+++ b/frontend/src/react/components/sql-editor/Panels/Panels.tsx
@@ -33,10 +33,9 @@ import {
} from "@/react/stores/sqlEditor";
import {
useConnectionOfCurrentSQLEditorTab,
- useDatabaseV1Store,
- useDBSchemaV1Store,
useSQLEditorTabStore,
-} from "@/store";
+} from "@/react/stores/sqlEditor/tab-vue-state";
+import { useDatabaseV1Store, useDBSchemaV1Store } from "@/store";
import { isValidDatabaseName } from "@/types";
import {
extractDatabaseResourceName,
diff --git a/frontend/src/react/components/sql-editor/Panels/ProceduresPanel/ProceduresPanel.tsx b/frontend/src/react/components/sql-editor/Panels/ProceduresPanel/ProceduresPanel.tsx
index ed8fb0c60a..24ddb7d42c 100644
--- a/frontend/src/react/components/sql-editor/Panels/ProceduresPanel/ProceduresPanel.tsx
+++ b/frontend/src/react/components/sql-editor/Panels/ProceduresPanel/ProceduresPanel.tsx
@@ -2,10 +2,8 @@ import { ChevronLeft, FileCode } from "lucide-react";
import { useState } from "react";
import { Button } from "@/react/components/ui/button";
import { useVueState } from "@/react/hooks/useVueState";
-import {
- useConnectionOfCurrentSQLEditorTab,
- useDBSchemaV1Store,
-} from "@/store";
+import { useConnectionOfCurrentSQLEditorTab } from "@/react/stores/sqlEditor/tab-vue-state";
+import { useDBSchemaV1Store } from "@/store";
import {
extractKeyWithPosition,
keyWithPosition,
diff --git a/frontend/src/react/components/sql-editor/Panels/SequencesPanel/SequencesPanel.tsx b/frontend/src/react/components/sql-editor/Panels/SequencesPanel/SequencesPanel.tsx
index 21498567bd..1cb53e2886 100644
--- a/frontend/src/react/components/sql-editor/Panels/SequencesPanel/SequencesPanel.tsx
+++ b/frontend/src/react/components/sql-editor/Panels/SequencesPanel/SequencesPanel.tsx
@@ -1,9 +1,7 @@
import { useState } from "react";
import { useVueState } from "@/react/hooks/useVueState";
-import {
- useConnectionOfCurrentSQLEditorTab,
- useDBSchemaV1Store,
-} from "@/store";
+import { useConnectionOfCurrentSQLEditorTab } from "@/react/stores/sqlEditor/tab-vue-state";
+import { useDBSchemaV1Store } from "@/store";
import { keyWithPosition } from "@/views/sql-editor/EditorCommon/utils";
import { PanelSearchBox } from "../common/PanelSearchBox";
import { useViewStateNav } from "../common/useViewStateNav";
diff --git a/frontend/src/react/components/sql-editor/Panels/TablesPanel/TablesPanel.tsx b/frontend/src/react/components/sql-editor/Panels/TablesPanel/TablesPanel.tsx
index 6f27be073b..f15c8ebeb0 100644
--- a/frontend/src/react/components/sql-editor/Panels/TablesPanel/TablesPanel.tsx
+++ b/frontend/src/react/components/sql-editor/Panels/TablesPanel/TablesPanel.tsx
@@ -1,9 +1,7 @@
import { useState } from "react";
import { useVueState } from "@/react/hooks/useVueState";
-import {
- useConnectionOfCurrentSQLEditorTab,
- useDBSchemaV1Store,
-} from "@/store";
+import { useConnectionOfCurrentSQLEditorTab } from "@/react/stores/sqlEditor/tab-vue-state";
+import { useDBSchemaV1Store } from "@/store";
import { PanelSearchBox } from "../common/PanelSearchBox";
import { useViewStateNav } from "../common/useViewStateNav";
import { TableDetail } from "./TableDetail";
diff --git a/frontend/src/react/components/sql-editor/Panels/TriggersPanel/TriggersPanel.tsx b/frontend/src/react/components/sql-editor/Panels/TriggersPanel/TriggersPanel.tsx
index 441804e199..c5cabd6a0c 100644
--- a/frontend/src/react/components/sql-editor/Panels/TriggersPanel/TriggersPanel.tsx
+++ b/frontend/src/react/components/sql-editor/Panels/TriggersPanel/TriggersPanel.tsx
@@ -2,10 +2,8 @@ import { ChevronLeft, Zap } from "lucide-react";
import { useState } from "react";
import { Button } from "@/react/components/ui/button";
import { useVueState } from "@/react/hooks/useVueState";
-import {
- useConnectionOfCurrentSQLEditorTab,
- useDBSchemaV1Store,
-} from "@/store";
+import { useConnectionOfCurrentSQLEditorTab } from "@/react/stores/sqlEditor/tab-vue-state";
+import { useDBSchemaV1Store } from "@/store";
import {
extractKeyWithPosition,
keyWithPosition,
diff --git a/frontend/src/react/components/sql-editor/Panels/ViewsPanel/ViewsPanel.tsx b/frontend/src/react/components/sql-editor/Panels/ViewsPanel/ViewsPanel.tsx
index 18ec0470c8..911ba18510 100644
--- a/frontend/src/react/components/sql-editor/Panels/ViewsPanel/ViewsPanel.tsx
+++ b/frontend/src/react/components/sql-editor/Panels/ViewsPanel/ViewsPanel.tsx
@@ -1,9 +1,7 @@
import { useState } from "react";
import { useVueState } from "@/react/hooks/useVueState";
-import {
- useConnectionOfCurrentSQLEditorTab,
- useDBSchemaV1Store,
-} from "@/store";
+import { useConnectionOfCurrentSQLEditorTab } from "@/react/stores/sqlEditor/tab-vue-state";
+import { useDBSchemaV1Store } from "@/store";
import { PanelSearchBox } from "../common/PanelSearchBox";
import { useViewStateNav } from "../common/useViewStateNav";
import { ViewDetail } from "./ViewDetail";
diff --git a/frontend/src/react/components/sql-editor/Panels/common/SchemaSelectToolbar.tsx b/frontend/src/react/components/sql-editor/Panels/common/SchemaSelectToolbar.tsx
index cb56d391d8..e4059c1296 100644
--- a/frontend/src/react/components/sql-editor/Panels/common/SchemaSelectToolbar.tsx
+++ b/frontend/src/react/components/sql-editor/Panels/common/SchemaSelectToolbar.tsx
@@ -7,10 +7,8 @@ import {
SelectValue,
} from "@/react/components/ui/select";
import { useVueState } from "@/react/hooks/useVueState";
-import {
- useConnectionOfCurrentSQLEditorTab,
- useDBSchemaV1Store,
-} from "@/store";
+import { useConnectionOfCurrentSQLEditorTab } from "@/react/stores/sqlEditor/tab-vue-state";
+import { useDBSchemaV1Store } from "@/store";
import { hasSchemaProperty } from "@/utils";
import { useViewStateNav } from "./useViewStateNav";
diff --git a/frontend/src/react/components/sql-editor/Panels/common/useViewStateNav.test.tsx b/frontend/src/react/components/sql-editor/Panels/common/useViewStateNav.test.tsx
index 480e11f3fb..77c84e7649 100644
--- a/frontend/src/react/components/sql-editor/Panels/common/useViewStateNav.test.tsx
+++ b/frontend/src/react/components/sql-editor/Panels/common/useViewStateNav.test.tsx
@@ -38,7 +38,9 @@ const mocks = vi.hoisted(() => ({
},
}));
-vi.mock("@/store", () => ({
+vi.mock("@/store", () => ({}));
+
+vi.mock("@/react/stores/sqlEditor/tab-vue-state", () => ({
useSQLEditorTabStore: () => ({
updateTab: mocks.updateTab,
get currentTab() {
diff --git a/frontend/src/react/components/sql-editor/Panels/common/useViewStateNav.ts b/frontend/src/react/components/sql-editor/Panels/common/useViewStateNav.ts
index 2cdfb62d73..53606c47ba 100644
--- a/frontend/src/react/components/sql-editor/Panels/common/useViewStateNav.ts
+++ b/frontend/src/react/components/sql-editor/Panels/common/useViewStateNav.ts
@@ -1,6 +1,6 @@
import { useCallback } from "react";
import { useVueState } from "@/react/hooks/useVueState";
-import { useSQLEditorTabStore } from "@/store";
+import { useSQLEditorTabStore } from "@/react/stores/sqlEditor/tab-vue-state";
import { defaultViewState } from "@/types";
import type { EditorPanelViewState } from "@/types/sqlEditor/tabViewState";
diff --git a/frontend/src/react/components/sql-editor/QueryContextSettingPopover.test.tsx b/frontend/src/react/components/sql-editor/QueryContextSettingPopover.test.tsx
index 5fff8facaf..50acf87a5d 100644
--- a/frontend/src/react/components/sql-editor/QueryContextSettingPopover.test.tsx
+++ b/frontend/src/react/components/sql-editor/QueryContextSettingPopover.test.tsx
@@ -11,7 +11,7 @@ const mocks = vi.hoisted(() => ({
useTranslation: vi.fn(() => ({ t: (key: string) => key })),
useVueState: vi.fn<(getter: () => unknown) => unknown>(),
useSQLEditorTabStore: vi.fn(),
- useSQLEditorStore: vi.fn(),
+ useSQLEditorVueState: vi.fn(),
useConnectionOfCurrentSQLEditorTab: vi.fn(),
getInstanceResource: vi.fn(),
readableDataSourceType: vi.fn((type: number) => `type-${type}`),
@@ -26,10 +26,15 @@ vi.mock("@/react/hooks/useVueState", () => ({
useVueState: mocks.useVueState,
}));
-vi.mock("@/store", () => ({
- useSQLEditorTabStore: mocks.useSQLEditorTabStore,
- useSQLEditorStore: mocks.useSQLEditorStore,
+vi.mock("@/store", () => ({}));
+
+vi.mock("@/react/stores/sqlEditor/tab-vue-state", () => ({
useConnectionOfCurrentSQLEditorTab: mocks.useConnectionOfCurrentSQLEditorTab,
+ useSQLEditorTabStore: mocks.useSQLEditorTabStore,
+}));
+
+vi.mock("@/react/stores/sqlEditor/editor-vue-state", () => ({
+ useSQLEditorVueState: mocks.useSQLEditorVueState,
}));
vi.mock("@/utils", () => ({
@@ -134,7 +139,7 @@ beforeEach(async () => {
currentTab: { mode: "WORKSHEET" },
updateCurrentTab: vi.fn(),
});
- mocks.useSQLEditorStore.mockReturnValue({
+ mocks.useSQLEditorVueState.mockReturnValue({
resultRowsLimit: 1000,
redisCommandOption: 0,
queryDataPolicy: {
diff --git a/frontend/src/react/components/sql-editor/QueryContextSettingPopover.tsx b/frontend/src/react/components/sql-editor/QueryContextSettingPopover.tsx
index 2c3f485150..4bb162b3c2 100644
--- a/frontend/src/react/components/sql-editor/QueryContextSettingPopover.tsx
+++ b/frontend/src/react/components/sql-editor/QueryContextSettingPopover.tsx
@@ -12,11 +12,11 @@ import {
import { Tooltip } from "@/react/components/ui/tooltip";
import { useVueState } from "@/react/hooks/useVueState";
import { cn } from "@/react/lib/utils";
+import { useSQLEditorVueState } from "@/react/stores/sqlEditor/editor-vue-state";
import {
useConnectionOfCurrentSQLEditorTab,
- useSQLEditorStore,
useSQLEditorTabStore,
-} from "@/store";
+} from "@/react/stores/sqlEditor/tab-vue-state";
import { Engine } from "@/types/proto-es/v1/common_pb";
import type { DataSource } from "@/types/proto-es/v1/instance_service_pb";
import {
@@ -37,7 +37,7 @@ type Props = {
export function QueryContextSettingPopover({ disabled = false }: Props) {
const { t } = useTranslation();
const tabStore = useSQLEditorTabStore();
- const editorStore = useSQLEditorStore();
+ const editorStore = useSQLEditorVueState();
const connection = useConnectionOfCurrentSQLEditorTab();
const currentTabMode = useVueState(() => tabStore.currentTab?.mode);
diff --git a/frontend/src/react/components/sql-editor/ReadonlyModeNotSupported.test.tsx b/frontend/src/react/components/sql-editor/ReadonlyModeNotSupported.test.tsx
index 27d5c9a498..7347ced7ab 100644
--- a/frontend/src/react/components/sql-editor/ReadonlyModeNotSupported.test.tsx
+++ b/frontend/src/react/components/sql-editor/ReadonlyModeNotSupported.test.tsx
@@ -35,9 +35,11 @@ vi.mock("@/react/hooks/useVueState", () => ({
}));
vi.mock("@/store", () => ({
- useConnectionOfCurrentSQLEditorTab: mocks.useConnectionOfCurrentSQLEditorTab,
// Transitive imports from AdminModeButton — provide stubs.
- useSQLEditorStore: vi.fn(() => ({ allowAdmin: false })),
+}));
+
+vi.mock("@/react/stores/sqlEditor/tab-vue-state", () => ({
+ useConnectionOfCurrentSQLEditorTab: mocks.useConnectionOfCurrentSQLEditorTab,
useSQLEditorTabStore: vi.fn(() => ({
currentTab: undefined,
isDisconnected: true,
@@ -45,6 +47,10 @@ vi.mock("@/store", () => ({
})),
}));
+vi.mock("@/react/stores/sqlEditor/editor-vue-state", () => ({
+ useSQLEditorVueState: vi.fn(() => ({ allowAdmin: false })),
+}));
+
vi.mock("@/react/components/instance/constants", () => ({
EngineIconPath: {
[Engine.POSTGRES]: "/icons/postgres.svg",
diff --git a/frontend/src/react/components/sql-editor/ReadonlyModeNotSupported.tsx b/frontend/src/react/components/sql-editor/ReadonlyModeNotSupported.tsx
index 3f9bb8f3c7..b459534d86 100644
--- a/frontend/src/react/components/sql-editor/ReadonlyModeNotSupported.tsx
+++ b/frontend/src/react/components/sql-editor/ReadonlyModeNotSupported.tsx
@@ -2,7 +2,7 @@ import { ShieldAlert } from "lucide-react";
import { Trans, useTranslation } from "react-i18next";
import { EngineIcon } from "@/react/components/EngineIcon";
import { useVueState } from "@/react/hooks/useVueState";
-import { useConnectionOfCurrentSQLEditorTab } from "@/store";
+import { useConnectionOfCurrentSQLEditorTab } from "@/react/stores/sqlEditor/tab-vue-state";
import { AdminModeButton } from "./AdminModeButton";
/**
diff --git a/frontend/src/react/components/sql-editor/RequestQueryButton.test.tsx b/frontend/src/react/components/sql-editor/RequestQueryButton.test.tsx
index ae38501bf1..f13ec9420b 100644
--- a/frontend/src/react/components/sql-editor/RequestQueryButton.test.tsx
+++ b/frontend/src/react/components/sql-editor/RequestQueryButton.test.tsx
@@ -12,7 +12,7 @@ const mocks = vi.hoisted(() => ({
useVueState: vi.fn<(getter: () => unknown) => unknown>(),
useProjectV1Store: vi.fn(),
useRoleStore: vi.fn(),
- useSQLEditorStore: vi.fn(),
+ useSQLEditorVueState: vi.fn(),
useSubscriptionV1Store: vi.fn(),
hasFeature: vi.fn(() => true),
parseStringToResource: vi.fn((s: string) => ({
@@ -32,11 +32,14 @@ vi.mock("@/react/hooks/useVueState", () => ({
vi.mock("@/store", () => ({
useProjectV1Store: mocks.useProjectV1Store,
useRoleStore: mocks.useRoleStore,
- useSQLEditorStore: mocks.useSQLEditorStore,
useSubscriptionV1Store: mocks.useSubscriptionV1Store,
hasFeature: mocks.hasFeature,
}));
+vi.mock("@/react/stores/sqlEditor/editor-vue-state", () => ({
+ useSQLEditorVueState: mocks.useSQLEditorVueState,
+}));
+
vi.mock("@/utils/v1/databaseResource", () => ({
parseStringToResource: mocks.parseStringToResource,
}));
@@ -180,7 +183,7 @@ const setupDefaultMocks = (allowJIT = false, allowRequestRole = true) => {
},
],
});
- mocks.useSQLEditorStore.mockReturnValue({ project: "projects/proj1" });
+ mocks.useSQLEditorVueState.mockReturnValue({ project: "projects/proj1" });
mocks.useSubscriptionV1Store.mockReturnValue({
hasInstanceFeature: vi.fn(() => false),
});
diff --git a/frontend/src/react/components/sql-editor/RequestQueryButton.tsx b/frontend/src/react/components/sql-editor/RequestQueryButton.tsx
index 8c6a42b136..e2ddca77d6 100644
--- a/frontend/src/react/components/sql-editor/RequestQueryButton.tsx
+++ b/frontend/src/react/components/sql-editor/RequestQueryButton.tsx
@@ -7,11 +7,11 @@ import { Button } from "@/react/components/ui/button";
import { useVueState } from "@/react/hooks/useVueState";
import { cn } from "@/react/lib/utils";
import { RequestRoleSheet } from "@/react/pages/settings/RequestRoleSheet";
+import { useSQLEditorVueState } from "@/react/stores/sqlEditor/editor-vue-state";
import {
hasFeature,
useProjectV1Store,
useRoleStore,
- useSQLEditorStore,
useSubscriptionV1Store,
} from "@/store";
import type { DatabaseResource, Permission } from "@/types";
@@ -81,7 +81,7 @@ export function RequestQueryButton({
const [showJITDrawer, setShowJITDrawer] = useState(false);
const projectStore = useProjectV1Store();
- const editorStore = useSQLEditorStore();
+ const editorStore = useSQLEditorVueState();
const roleStore = useRoleStore();
const subscriptionStore = useSubscriptionV1Store();
diff --git a/frontend/src/react/components/sql-editor/ResultPanel/BatchQuerySelect.tsx b/frontend/src/react/components/sql-editor/ResultPanel/BatchQuerySelect.tsx
index b54b6dc4fe..99e6be42e8 100644
--- a/frontend/src/react/components/sql-editor/ResultPanel/BatchQuerySelect.tsx
+++ b/frontend/src/react/components/sql-editor/ResultPanel/BatchQuerySelect.tsx
@@ -15,13 +15,9 @@ import { Button } from "@/react/components/ui/button";
import { Tooltip } from "@/react/components/ui/tooltip";
import { useVueState } from "@/react/hooks/useVueState";
import { cn } from "@/react/lib/utils";
-import {
- pushNotification,
- useDatabaseV1Store,
- useSQLEditorStore,
- useSQLEditorTabStore,
- useSQLStore,
-} from "@/store";
+import { useSQLEditorVueState } from "@/react/stores/sqlEditor/editor-vue-state";
+import { useSQLEditorTabStore } from "@/react/stores/sqlEditor/tab-vue-state";
+import { pushNotification, useDatabaseV1Store, useSQLStore } from "@/store";
import { ExportFormat } from "@/types/proto-es/v1/common_pb";
import type { Database } from "@/types/proto-es/v1/database_service_pb";
import { ExportRequestSchema } from "@/types/proto-es/v1/sql_service_pb";
@@ -80,7 +76,7 @@ export function BatchQuerySelect({
const tabStore = useSQLEditorTabStore();
const databaseStore = useDatabaseV1Store();
const sqlStore = useSQLStore();
- const editorStore = useSQLEditorStore();
+ const editorStore = useSQLEditorVueState();
const [showEmpty, setShowEmpty] = useState(true);
const [selectedDatabaseNames, setSelectedDatabaseNames] = useState<
diff --git a/frontend/src/react/components/sql-editor/ResultPanel/DatabaseQueryContext.tsx b/frontend/src/react/components/sql-editor/ResultPanel/DatabaseQueryContext.tsx
index c3dc65938f..c3ce9e00a0 100644
--- a/frontend/src/react/components/sql-editor/ResultPanel/DatabaseQueryContext.tsx
+++ b/frontend/src/react/components/sql-editor/ResultPanel/DatabaseQueryContext.tsx
@@ -4,7 +4,7 @@ import { useTranslation } from "react-i18next";
import { useExecuteSQL } from "@/composables/useExecuteSQL";
import { ResultView } from "@/react/components/sql-editor/ResultView";
import { Button } from "@/react/components/ui/button";
-import { useSQLEditorTabStore } from "@/store";
+import { useSQLEditorTabStore } from "@/react/stores/sqlEditor/tab-vue-state";
import type {
SQLEditorDatabaseQueryContext,
SQLEditorQueryParams,
diff --git a/frontend/src/react/components/sql-editor/ResultPanel/ResultPanel.tsx b/frontend/src/react/components/sql-editor/ResultPanel/ResultPanel.tsx
index b6f9123fb0..7cb7d51fa2 100644
--- a/frontend/src/react/components/sql-editor/ResultPanel/ResultPanel.tsx
+++ b/frontend/src/react/components/sql-editor/ResultPanel/ResultPanel.tsx
@@ -18,7 +18,7 @@ import {
import { Tooltip } from "@/react/components/ui/tooltip";
import { useVueState } from "@/react/hooks/useVueState";
import { cn } from "@/react/lib/utils";
-import { useSQLEditorTabStore } from "@/store";
+import { useSQLEditorTabStore } from "@/react/stores/sqlEditor/tab-vue-state";
import type { SQLEditorDatabaseQueryContext } from "@/types";
import { getDataSourceTypeI18n } from "@/types";
import type { Database } from "@/types/proto-es/v1/database_service_pb";
diff --git a/frontend/src/react/components/sql-editor/ResultView/ResultView.tsx b/frontend/src/react/components/sql-editor/ResultView/ResultView.tsx
index 3b865b0895..26bad27102 100644
--- a/frontend/src/react/components/sql-editor/ResultView/ResultView.tsx
+++ b/frontend/src/react/components/sql-editor/ResultView/ResultView.tsx
@@ -20,12 +20,12 @@ import {
import { Tooltip } from "@/react/components/ui/tooltip";
import { useVueState } from "@/react/hooks/useVueState";
import { cn } from "@/react/lib/utils";
+import { useSQLEditorVueState } from "@/react/stores/sqlEditor/editor-vue-state";
+import { useSQLEditorTabStore } from "@/react/stores/sqlEditor/tab-vue-state";
import {
pushNotification,
useDatabaseV1Store,
useDBSchemaV1Store,
- useSQLEditorStore,
- useSQLEditorTabStore,
useSQLStore,
} from "@/store";
import { usePolicyV1Store } from "@/store/modules/v1/policy";
@@ -73,7 +73,7 @@ export function ResultView({
const { t } = useTranslation();
const policyStore = usePolicyV1Store();
const queryDataPolicy = useVueState(
- () => useSQLEditorStore().queryDataPolicy
+ () => useSQLEditorVueState().queryDataPolicy
);
const tabStore = useSQLEditorTabStore();
diff --git a/frontend/src/react/components/sql-editor/ResultView/SingleResultView.tsx b/frontend/src/react/components/sql-editor/ResultView/SingleResultView.tsx
index e8e74045d2..0c182c0b78 100644
--- a/frontend/src/react/components/sql-editor/ResultView/SingleResultView.tsx
+++ b/frontend/src/react/components/sql-editor/ResultView/SingleResultView.tsx
@@ -33,7 +33,8 @@ import { Switch } from "@/react/components/ui/switch";
import { Tooltip } from "@/react/components/ui/tooltip";
import { useVueState } from "@/react/hooks/useVueState";
import { cn } from "@/react/lib/utils";
-import { useSQLEditorStore, useSQLEditorTabStore } from "@/store";
+import { useSQLEditorVueState } from "@/react/stores/sqlEditor/editor-vue-state";
+import { useSQLEditorTabStore } from "@/react/stores/sqlEditor/tab-vue-state";
import type {
SQLEditorDatabaseQueryContext,
SQLEditorQueryParams,
@@ -228,7 +229,7 @@ function SingleResultViewInner({
}: SingleResultViewInnerProps) {
const { t } = useTranslation();
const tabStore = useSQLEditorTabStore();
- const editorStore = useSQLEditorStore();
+ const editorStore = useSQLEditorVueState();
const currentTabMode = useVueState(() => tabStore.currentTab?.mode);
const resultRowsLimit = useVueState(() => editorStore.resultRowsLimit);
const policyMaxRows = useVueState(
diff --git a/frontend/src/react/components/sql-editor/SQLEditorHomePage.tsx b/frontend/src/react/components/sql-editor/SQLEditorHomePage.tsx
index 683bd7d754..0c2ac22871 100644
--- a/frontend/src/react/components/sql-editor/SQLEditorHomePage.tsx
+++ b/frontend/src/react/components/sql-editor/SQLEditorHomePage.tsx
@@ -24,13 +24,10 @@ import { applyPlanTitleToQuery } from "@/react/lib/plan/title";
import { cn } from "@/react/lib/utils";
import { useNavigate } from "@/react/router";
import { useSQLEditorStore } from "@/react/stores/sqlEditor";
+import { useSQLEditorVueState } from "@/react/stores/sqlEditor/editor-vue-state";
+import { useSQLEditorTabStore } from "@/react/stores/sqlEditor/tab-vue-state";
import { PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL } from "@/router/dashboard/projectV1";
-import {
- useDatabaseV1Store,
- useProjectV1Store,
- useSQLEditorStore as useSQLEditorPiniaStore,
- useSQLEditorTabStore,
-} from "@/store";
+import { useDatabaseV1Store, useProjectV1Store } from "@/store";
import { unknownProject } from "@/types";
import {
extractDatabaseResourceName,
@@ -68,7 +65,7 @@ export function SQLEditorHomePage() {
);
const databaseStore = useDatabaseV1Store();
const projectStore = useProjectV1Store();
- const editorStore = useSQLEditorPiniaStore();
+ const editorStore = useSQLEditorVueState();
const projectContextReady = useVueState(
() => editorStore.projectContextReady
diff --git a/frontend/src/react/components/sql-editor/SQLEditorLayout.tsx b/frontend/src/react/components/sql-editor/SQLEditorLayout.tsx
index 2f299c62e7..0cfa6a5374 100644
--- a/frontend/src/react/components/sql-editor/SQLEditorLayout.tsx
+++ b/frontend/src/react/components/sql-editor/SQLEditorLayout.tsx
@@ -1,12 +1,9 @@
import { useEffect, useState } from "react";
import { BannersWrapper } from "@/react/components/BannersWrapper";
import { router } from "@/router";
-import {
- useEnvironmentV1Store,
- useSettingV1Store,
- useSQLEditorWorksheetStore,
-} from "@/store";
+import { useEnvironmentV1Store, useSettingV1Store } from "@/store";
import { Setting_SettingName } from "@/types/proto-es/v1/setting_service_pb";
+import { provideSheetContext } from "@/views/sql-editor/Sheet";
import { RequestDrawerHost } from "./RequestDrawerHost";
import { SQLEditorRouteShell } from "./SQLEditorRouteShell";
import { useSQLEditorAutoSave } from "./useSQLEditorAutoSave";
@@ -28,10 +25,11 @@ import { useSQLEditorAutoSave } from "./useSQLEditorAutoSave";
export function SQLEditorLayout() {
const settingStore = useSettingV1Store();
const environmentStore = useEnvironmentV1Store();
- // Mounting the worksheet store eagerly mirrors the legacy
- // `provideSheetContext()` call — it boots the per-view watchers
- // (selectedKeys ↔ active tab) the moment the layout appears.
- useSQLEditorWorksheetStore();
+ // Boots the per-view watchers (selectedKeys ↔ active tab) the moment
+ // the layout appears. The sheet-context singleton is module-level and
+ // lazy — calling it here ensures the watchers are wired before any
+ // child component reads from it.
+ provideSheetContext();
const [ready, setReady] = useState(false);
diff --git a/frontend/src/react/components/sql-editor/SQLEditorRouteShell.tsx b/frontend/src/react/components/sql-editor/SQLEditorRouteShell.tsx
index b187cc6803..cbbe54af1b 100644
--- a/frontend/src/react/components/sql-editor/SQLEditorRouteShell.tsx
+++ b/frontend/src/react/components/sql-editor/SQLEditorRouteShell.tsx
@@ -10,6 +10,8 @@ import { useVueState } from "@/react/hooks/useVueState";
import { useCurrentRoute, useNavigate } from "@/react/router";
import type { AsidePanelTab } from "@/react/stores/sqlEditor";
import { useSQLEditorStore } from "@/react/stores/sqlEditor";
+import { useSQLEditorVueState } from "@/react/stores/sqlEditor/editor-vue-state";
+import { useSQLEditorTabStore } from "@/react/stores/sqlEditor/tab-vue-state";
import { router } from "@/router";
import {
SQL_EDITOR_DATABASE_MODULE,
@@ -23,9 +25,6 @@ import {
useActuatorV1Store,
useDatabaseV1Store,
useProjectV1Store,
- useSQLEditorStore as useSQLEditorPiniaStore,
- useSQLEditorTabStore,
- useSQLEditorWorksheetStore,
useWorkSheetStore,
} from "@/store";
import { migrateLegacyCache } from "@/store/modules/sqlEditor/legacy/migration";
@@ -103,11 +102,11 @@ export function SQLEditorRouteShell() {
const actuatorStore = useActuatorV1Store();
const projectStore = useProjectV1Store();
const databaseStore = useDatabaseV1Store();
- const editorStore = useSQLEditorPiniaStore();
+ const editorStore = useSQLEditorVueState();
const tabStore = useSQLEditorTabStore();
const setAsidePanelTab = useSQLEditorStore((s) => s.setAsidePanelTab);
+ const maybeSwitchProject = useSQLEditorStore((s) => s.maybeSwitchProject);
const worksheetStore = useWorkSheetStore();
- const sqlEditorWorksheetStore = useSQLEditorWorksheetStore();
const projectContextReady = useVueState(
() => editorStore.projectContextReady
@@ -167,12 +166,10 @@ export function SQLEditorRouteShell() {
project = editorStore.storedLastViewedProject;
}
- let initializeSuccess =
- !!(await sqlEditorWorksheetStore.maybeSwitchProject(project));
+ let initializeSuccess = !!(await maybeSwitchProject(project));
if (!initializeSuccess) {
project = await fallbackToFirstProject();
- initializeSuccess =
- !!(await sqlEditorWorksheetStore.maybeSwitchProject(project));
+ initializeSuccess = !!(await maybeSwitchProject(project));
}
if (!initializeSuccess) {
editorStore.setProject("");
@@ -217,7 +214,7 @@ export function SQLEditorRouteShell() {
const sheetId = route.params.sheet;
if (typeof projectId !== "string" || !projectId) return false;
if (typeof sheetId !== "string" || !sheetId) return false;
- await sqlEditorWorksheetStore.maybeSwitchProject(`projects/${projectId}`);
+ await maybeSwitchProject(`projects/${projectId}`);
return await switchWorksheet(`projects/${projectId}/worksheets/${sheetId}`);
};
@@ -232,7 +229,7 @@ export function SQLEditorRouteShell() {
const databaseName = `instances/${route.params.instance}/databases/${route.params.database}`;
if (!isValidDatabaseName(databaseName)) return false;
const database = await databaseStore.getOrFetchDatabaseByName(databaseName);
- await sqlEditorWorksheetStore.maybeSwitchProject(database.project);
+ await maybeSwitchProject(database.project);
const { instance } = extractDatabaseResourceName(database.name);
const connection = { instance, database: database.name };
tabStore.addTab({
diff --git a/frontend/src/react/components/sql-editor/SaveSheetModal.test.tsx b/frontend/src/react/components/sql-editor/SaveSheetModal.test.tsx
index 48be7bbf05..20696bf8de 100644
--- a/frontend/src/react/components/sql-editor/SaveSheetModal.test.tsx
+++ b/frontend/src/react/components/sql-editor/SaveSheetModal.test.tsx
@@ -41,7 +41,12 @@ vi.mock("@/react/hooks/useSQLEditorEvent", () => ({
vi.mock("@/store", () => ({
useWorkSheetStore: vi.fn(() => mocks.worksheetStore),
- useSQLEditorWorksheetStore: vi.fn(() => mocks.editorWorksheetStore),
+}));
+
+vi.mock("@/react/stores/sqlEditor", () => ({
+ useSQLEditorStore: (
+ selector: (s: typeof mocks.editorWorksheetStore) => unknown
+ ) => selector(mocks.editorWorksheetStore),
}));
vi.mock("@/views/sql-editor/Sheet", () => ({
diff --git a/frontend/src/react/components/sql-editor/SaveSheetModal.tsx b/frontend/src/react/components/sql-editor/SaveSheetModal.tsx
index 2327a01d4c..02aa77ba91 100644
--- a/frontend/src/react/components/sql-editor/SaveSheetModal.tsx
+++ b/frontend/src/react/components/sql-editor/SaveSheetModal.tsx
@@ -8,7 +8,8 @@ import {
} from "@/react/components/ui/dialog";
import { Input } from "@/react/components/ui/input";
import { useSQLEditorEvent } from "@/react/hooks/useSQLEditorEvent";
-import { useSQLEditorWorksheetStore, useWorkSheetStore } from "@/store";
+import { useSQLEditorStore } from "@/react/stores/sqlEditor";
+import { useWorkSheetStore } from "@/store";
import type { SQLEditorTab } from "@/types";
import { UNKNOWN_ID } from "@/types";
import { extractWorksheetID } from "@/utils";
@@ -18,7 +19,9 @@ import { FolderForm } from "./FolderForm";
export function SaveSheetModal() {
const { t } = useTranslation();
const worksheetStore = useWorkSheetStore();
- const editorWorksheetStore = useSQLEditorWorksheetStore();
+ const abortAutoSave = useSQLEditorStore((s) => s.abortAutoSave);
+ const maybeUpdateWorksheet = useSQLEditorStore((s) => s.maybeUpdateWorksheet);
+ const createWorksheet = useSQLEditorStore((s) => s.createWorksheet);
const sheetContext = useSheetContextByView("my");
const [open, setOpen] = useState(false);
@@ -44,14 +47,14 @@ export function SaveSheetModal() {
const effectiveTitle = tabTitle ?? title;
const effectiveFolder = tabFolder ?? folder;
- editorWorksheetStore.abortAutoSave();
+ abortAutoSave();
const { worksheet, connection, statement, id: tabId } = effectiveTab;
const folders = sheetContext.getFoldersForWorksheet(effectiveFolder);
const sheetId = extractWorksheetID(worksheet ?? "");
if (sheetId !== String(UNKNOWN_ID)) {
- await editorWorksheetStore.maybeUpdateWorksheet({
+ await maybeUpdateWorksheet({
tabId,
worksheet,
title: effectiveTitle,
@@ -60,7 +63,7 @@ export function SaveSheetModal() {
folders,
});
} else {
- await editorWorksheetStore.createWorksheet({
+ await createWorksheet({
tabId,
title: effectiveTitle,
statement,
diff --git a/frontend/src/react/components/sql-editor/SchemaChooser.test.tsx b/frontend/src/react/components/sql-editor/SchemaChooser.test.tsx
index a904c03a75..6a7819eb83 100644
--- a/frontend/src/react/components/sql-editor/SchemaChooser.test.tsx
+++ b/frontend/src/react/components/sql-editor/SchemaChooser.test.tsx
@@ -28,9 +28,12 @@ vi.mock("@/react/hooks/useVueState", () => ({
}));
vi.mock("@/store", () => ({
- useSQLEditorTabStore: mocks.useSQLEditorTabStore,
useDBSchemaV1Store: mocks.useDBSchemaV1Store,
+}));
+
+vi.mock("@/react/stores/sqlEditor/tab-vue-state", () => ({
useConnectionOfCurrentSQLEditorTab: mocks.useConnectionOfCurrentSQLEditorTab,
+ useSQLEditorTabStore: mocks.useSQLEditorTabStore,
}));
vi.mock("@/utils", () => ({
diff --git a/frontend/src/react/components/sql-editor/SchemaChooser.tsx b/frontend/src/react/components/sql-editor/SchemaChooser.tsx
index 163998c572..5dc2aaed8e 100644
--- a/frontend/src/react/components/sql-editor/SchemaChooser.tsx
+++ b/frontend/src/react/components/sql-editor/SchemaChooser.tsx
@@ -1,12 +1,12 @@
import { useEffect, useMemo } from "react";
import { useTranslation } from "react-i18next";
import { useVueState } from "@/react/hooks/useVueState";
-import { router } from "@/router";
import {
useConnectionOfCurrentSQLEditorTab,
- useDBSchemaV1Store,
useSQLEditorTabStore,
-} from "@/store";
+} from "@/react/stores/sqlEditor/tab-vue-state";
+import { router } from "@/router";
+import { useDBSchemaV1Store } from "@/store";
import { instanceAllowsSchemaScopedQuery } from "@/utils";
import { ConnectChooser } from "./ConnectChooser";
diff --git a/frontend/src/react/components/sql-editor/SchemaPane/SchemaPane.test.tsx b/frontend/src/react/components/sql-editor/SchemaPane/SchemaPane.test.tsx
index b04cc98495..58cd779603 100644
--- a/frontend/src/react/components/sql-editor/SchemaPane/SchemaPane.test.tsx
+++ b/frontend/src/react/components/sql-editor/SchemaPane/SchemaPane.test.tsx
@@ -40,25 +40,28 @@ vi.mock("@/react/i18n", () => ({
}));
vi.mock("@/store", () => ({
- useSQLEditorTabStore: () => ({
- currentTab: mocks.currentTab,
- openTabList: [],
- addTab: vi.fn(),
- setCurrentTabId: vi.fn(),
- updateCurrentTab: vi.fn(),
- updateTab: vi.fn(),
- }),
useDBSchemaV1Store: () => ({
getOrFetchDatabaseMetadata: mocks.getOrFetchDatabaseMetadata,
syncDatabase: vi.fn(),
getTableMetadata: vi.fn(),
}),
useDatabaseV1Store: () => ({ getDatabaseByName: vi.fn() }),
+ pushNotification: vi.fn(),
+}));
+
+vi.mock("@/react/stores/sqlEditor/tab-vue-state", () => ({
useConnectionOfCurrentSQLEditorTab: () => ({
database: { value: mocks.databaseRefValue },
instance: { value: mocks.instanceRefValue },
}),
- pushNotification: vi.fn(),
+ useSQLEditorTabStore: () => ({
+ currentTab: mocks.currentTab,
+ openTabList: [],
+ addTab: vi.fn(),
+ setCurrentTabId: vi.fn(),
+ updateCurrentTab: vi.fn(),
+ updateTab: vi.fn(),
+ }),
}));
vi.mock("@/types", () => ({
diff --git a/frontend/src/react/components/sql-editor/SchemaPane/SchemaPane.tsx b/frontend/src/react/components/sql-editor/SchemaPane/SchemaPane.tsx
index 9e8e7f8199..328222da31 100644
--- a/frontend/src/react/components/sql-editor/SchemaPane/SchemaPane.tsx
+++ b/frontend/src/react/components/sql-editor/SchemaPane/SchemaPane.tsx
@@ -23,9 +23,9 @@ import { useVueState } from "@/react/hooks/useVueState";
import { cn } from "@/react/lib/utils";
import {
useConnectionOfCurrentSQLEditorTab,
- useDBSchemaV1Store,
useSQLEditorTabStore,
-} from "@/store";
+} from "@/react/stores/sqlEditor/tab-vue-state";
+import { useDBSchemaV1Store } from "@/store";
import { isValidDatabaseName } from "@/types";
import type {
DatabaseMetadata,
diff --git a/frontend/src/react/components/sql-editor/SchemaPane/SyncSchemaButton.test.tsx b/frontend/src/react/components/sql-editor/SchemaPane/SyncSchemaButton.test.tsx
index 5ca61f965e..997cabd057 100644
--- a/frontend/src/react/components/sql-editor/SchemaPane/SyncSchemaButton.test.tsx
+++ b/frontend/src/react/components/sql-editor/SchemaPane/SyncSchemaButton.test.tsx
@@ -69,15 +69,18 @@ vi.mock("@/react/hooks/useVueState", () => ({
}));
vi.mock("@/store", () => ({
- useConnectionOfCurrentSQLEditorTab: () => ({
- database: { value: mocks.databaseRefValue },
- }),
useDatabaseV1Store: () => ({ syncDatabase: mocks.syncDatabase }),
useDBSchemaV1Store: () => ({
getOrFetchDatabaseMetadata: mocks.getOrFetchDatabaseMetadata,
}),
}));
+vi.mock("@/react/stores/sqlEditor/tab-vue-state", () => ({
+ useConnectionOfCurrentSQLEditorTab: () => ({
+ database: { value: mocks.databaseRefValue },
+ }),
+}));
+
vi.mock("@/types", () => ({
getDateForPbTimestampProtoEs: () => undefined,
isValidDatabaseName: mocks.isValidDatabaseName,
diff --git a/frontend/src/react/components/sql-editor/SchemaPane/SyncSchemaButton.tsx b/frontend/src/react/components/sql-editor/SchemaPane/SyncSchemaButton.tsx
index dcccc30cf6..ef122ef4c6 100644
--- a/frontend/src/react/components/sql-editor/SchemaPane/SyncSchemaButton.tsx
+++ b/frontend/src/react/components/sql-editor/SchemaPane/SyncSchemaButton.tsx
@@ -6,11 +6,8 @@ import { Button } from "@/react/components/ui/button";
import { Tooltip } from "@/react/components/ui/tooltip";
import { useVueState } from "@/react/hooks/useVueState";
import { cn } from "@/react/lib/utils";
-import {
- useConnectionOfCurrentSQLEditorTab,
- useDatabaseV1Store,
- useDBSchemaV1Store,
-} from "@/store";
+import { useConnectionOfCurrentSQLEditorTab } from "@/react/stores/sqlEditor/tab-vue-state";
+import { useDatabaseV1Store, useDBSchemaV1Store } from "@/store";
import { getDateForPbTimestampProtoEs, isValidDatabaseName } from "@/types";
/**
diff --git a/frontend/src/react/components/sql-editor/SchemaPane/actions.test.tsx b/frontend/src/react/components/sql-editor/SchemaPane/actions.test.tsx
index f788a3aa35..7a57803acb 100644
--- a/frontend/src/react/components/sql-editor/SchemaPane/actions.test.tsx
+++ b/frontend/src/react/components/sql-editor/SchemaPane/actions.test.tsx
@@ -54,6 +54,9 @@ vi.mock("@/store", () => ({
pushNotification: vi.fn(),
useDatabaseV1Store: () => ({ getDatabaseByName: mocks.getDatabaseByName }),
useDBSchemaV1Store: () => ({ getTableMetadata: mocks.getTableMetadata }),
+}));
+
+vi.mock("@/react/stores/sqlEditor/tab-vue-state", () => ({
useSQLEditorTabStore: () => ({
currentTab: { id: "t1", viewState: { schema: "" } },
openTabList: [],
diff --git a/frontend/src/react/components/sql-editor/SchemaPane/actions.tsx b/frontend/src/react/components/sql-editor/SchemaPane/actions.tsx
index dc9a90be8c..46c8245b4e 100644
--- a/frontend/src/react/components/sql-editor/SchemaPane/actions.tsx
+++ b/frontend/src/react/components/sql-editor/SchemaPane/actions.tsx
@@ -17,13 +17,13 @@ import { useCallback, useMemo } from "react";
import { useTranslation } from "react-i18next";
import { useExecuteSQL } from "@/composables/useExecuteSQL";
import { formatSQL } from "@/react/components/monaco/sqlFormatter";
+import { useSQLEditorTabStore } from "@/react/stores/sqlEditor/tab-vue-state";
import { router } from "@/router";
import { SQL_EDITOR_DATABASE_MODULE } from "@/router/sqlEditor";
import {
pushNotification,
useDatabaseV1Store,
useDBSchemaV1Store,
- useSQLEditorTabStore,
} from "@/store";
import {
DEFAULT_SQL_EDITOR_TAB_MODE,
diff --git a/frontend/src/react/components/sql-editor/SchemaPane/availableActions.tsx b/frontend/src/react/components/sql-editor/SchemaPane/availableActions.tsx
index 86eeb49b63..791d17c403 100644
--- a/frontend/src/react/components/sql-editor/SchemaPane/availableActions.tsx
+++ b/frontend/src/react/components/sql-editor/SchemaPane/availableActions.tsx
@@ -2,7 +2,7 @@ import { Box, Info } from "lucide-react";
import { useMemo } from "react";
import { useTranslation } from "react-i18next";
import { useVueState } from "@/react/hooks/useVueState";
-import { useConnectionOfCurrentSQLEditorTab } from "@/store";
+import { useConnectionOfCurrentSQLEditorTab } from "@/react/stores/sqlEditor/tab-vue-state";
import {
instanceV1SupportsExternalTable,
instanceV1SupportsPackage,
diff --git a/frontend/src/react/components/sql-editor/SharePopoverBody.test.tsx b/frontend/src/react/components/sql-editor/SharePopoverBody.test.tsx
index 1df3d1b26c..5d93948db3 100644
--- a/frontend/src/react/components/sql-editor/SharePopoverBody.test.tsx
+++ b/frontend/src/react/components/sql-editor/SharePopoverBody.test.tsx
@@ -34,10 +34,13 @@ vi.mock("@/store", () => ({
useActuatorV1Store: mocks.useActuatorV1Store,
useCurrentUserV1: mocks.useCurrentUserV1,
useWorkSheetStore: mocks.useWorkSheetStore,
- useSQLEditorTabStore: mocks.useSQLEditorTabStore,
pushNotification: mocks.pushNotification,
}));
+vi.mock("@/react/stores/sqlEditor/tab-vue-state", () => ({
+ useSQLEditorTabStore: mocks.useSQLEditorTabStore,
+}));
+
vi.mock("@/utils", () => ({
extractProjectResourceName: mocks.extractProjectResourceName,
extractWorksheetID: mocks.extractWorksheetID,
@@ -187,16 +190,12 @@ describe("SharePopoverBody", () => {
unmount();
});
- test("handleChangeAccess calls patchWorksheet and pushNotification and onUpdated", async () => {
- const onUpdated = vi.fn();
+ test("handleChangeAccess calls patchWorksheet and pushNotification but does NOT close the outer popover", async () => {
const patchWorksheet = vi.fn().mockResolvedValue({});
mocks.useWorkSheetStore.mockReturnValue({ patchWorksheet });
const { container, render, unmount } = renderIntoContainer(
- <SharePopoverBody
- worksheet={mockWorksheet as never}
- onUpdated={onUpdated}
- />
+ <SharePopoverBody worksheet={mockWorksheet as never} />
);
render();
@@ -206,14 +205,16 @@ describe("SharePopoverBody", () => {
const optionRows = popoverContent?.querySelectorAll("[data-option-row]");
expect(optionRows?.length).toBeGreaterThanOrEqual(1);
- // Click second option (Project Read)
+ // Click second option (Project Read).
await act(async () => {
(optionRows?.[1] as HTMLElement)?.click();
});
expect(patchWorksheet).toHaveBeenCalledTimes(1);
expect(mocks.pushNotification).toHaveBeenCalledTimes(1);
- expect(onUpdated).toHaveBeenCalledTimes(1);
+ // The SharePopoverBody no longer signals "close me" on access
+ // change — the outer share popover stays open so the user can copy
+ // the just-updated link.
unmount();
});
diff --git a/frontend/src/react/components/sql-editor/SharePopoverBody.tsx b/frontend/src/react/components/sql-editor/SharePopoverBody.tsx
index 8f5a3b33bc..8357b627a7 100644
--- a/frontend/src/react/components/sql-editor/SharePopoverBody.tsx
+++ b/frontend/src/react/components/sql-editor/SharePopoverBody.tsx
@@ -15,13 +15,13 @@ import {
} from "@/react/components/ui/popover";
import { useVueState } from "@/react/hooks/useVueState";
import { cn } from "@/react/lib/utils";
+import { useSQLEditorTabStore } from "@/react/stores/sqlEditor/tab-vue-state";
import { router } from "@/router";
import { SQL_EDITOR_WORKSHEET_MODULE } from "@/router/sqlEditor";
import {
pushNotification,
useActuatorV1Store,
useCurrentUserV1,
- useSQLEditorTabStore,
useWorkSheetStore,
} from "@/store";
import type { Worksheet } from "@/types/proto-es/v1/worksheet_service_pb";
@@ -37,14 +37,13 @@ type AccessOption = {
type Props = {
readonly worksheet?: Worksheet;
- readonly onUpdated?: () => void;
};
/**
* Replaces frontend/src/views/sql-editor/EditorCommon/SharePopover.vue.
* Renders the share popover body content: visibility selector + shareable link.
*/
-export function SharePopoverBody({ worksheet, onUpdated }: Props) {
+export function SharePopoverBody({ worksheet }: Props) {
const { t } = useTranslation();
const actuatorStore = useActuatorV1Store();
const currentUserStore = useCurrentUserV1();
@@ -140,7 +139,9 @@ export function SharePopoverBody({ worksheet, onUpdated }: Props) {
});
}
- onUpdated?.();
+ // Close only the inner access selector — keep the outer share
+ // popover open so the user can still copy the just-updated link
+ // (or change the access again).
setSelectorOpen(false);
};
diff --git a/frontend/src/react/components/sql-editor/SheetTree.test.tsx b/frontend/src/react/components/sql-editor/SheetTree.test.tsx
index fb1f1f2fd6..f06835b738 100644
--- a/frontend/src/react/components/sql-editor/SheetTree.test.tsx
+++ b/frontend/src/react/components/sql-editor/SheetTree.test.tsx
@@ -22,8 +22,9 @@ const mocks = vi.hoisted(() => ({
useVueState: vi.fn<(getter: () => unknown) => unknown>(),
useWorkSheetStore: vi.fn(),
useSQLEditorTabStore: vi.fn(),
- useSQLEditorStore: vi.fn(),
- useSQLEditorWorksheetStore: vi.fn(),
+ useSQLEditorVueState: vi.fn(),
+ // The new zustand store mock — only `createWorksheet` is used by SheetTree.
+ createWorksheet: vi.fn().mockResolvedValue({}),
useSheetContext: vi.fn(),
useSheetContextByView: vi.fn(),
useDropdown: vi.fn(),
@@ -41,12 +42,23 @@ vi.mock("@/react/hooks/useVueState", () => ({
vi.mock("@/store", () => ({
useWorkSheetStore: mocks.useWorkSheetStore,
- useSQLEditorTabStore: mocks.useSQLEditorTabStore,
- useSQLEditorStore: mocks.useSQLEditorStore,
- useSQLEditorWorksheetStore: mocks.useSQLEditorWorksheetStore,
pushNotification: mocks.pushNotification,
}));
+vi.mock("@/react/stores/sqlEditor/tab-vue-state", () => ({
+ useSQLEditorTabStore: mocks.useSQLEditorTabStore,
+}));
+
+vi.mock("@/react/stores/sqlEditor/editor-vue-state", () => ({
+ useSQLEditorVueState: mocks.useSQLEditorVueState,
+}));
+
+vi.mock("@/react/stores/sqlEditor", () => ({
+ useSQLEditorStore: (
+ selector: (s: { createWorksheet: typeof mocks.createWorksheet }) => unknown
+ ) => selector({ createWorksheet: mocks.createWorksheet }),
+}));
+
vi.mock("@/views/sql-editor/Sheet", () => ({
useSheetContext: mocks.useSheetContext,
useSheetContextByView: mocks.useSheetContextByView,
@@ -384,7 +396,7 @@ const setupDefaultMocks = () => {
mocks.useSheetContext.mockReturnValue(sheetContext);
mocks.useSheetContextByView.mockReturnValue(viewContext);
- mocks.useSQLEditorStore.mockReturnValue({
+ mocks.useSQLEditorVueState.mockReturnValue({
project: "projects/proj1",
});
mocks.useWorkSheetStore.mockReturnValue({
@@ -406,9 +418,7 @@ const setupDefaultMocks = () => {
updateTab: vi.fn(),
setCurrentTabId: vi.fn(),
});
- mocks.useSQLEditorWorksheetStore.mockReturnValue({
- createWorksheet: vi.fn().mockResolvedValue({}),
- });
+ mocks.createWorksheet.mockResolvedValue({});
mocks.useDropdown.mockReturnValue({
currentNode: undefined,
options: [],
diff --git a/frontend/src/react/components/sql-editor/SheetTree.tsx b/frontend/src/react/components/sql-editor/SheetTree.tsx
index 74c2cf4751..dba0745b00 100644
--- a/frontend/src/react/components/sql-editor/SheetTree.tsx
+++ b/frontend/src/react/components/sql-editor/SheetTree.tsx
@@ -56,13 +56,10 @@ import { Tree } from "@/react/components/ui/tree";
import { countVisibleRows } from "@/react/components/ui/tree-utils";
import { useVueState } from "@/react/hooks/useVueState";
import { cn } from "@/react/lib/utils";
-import {
- pushNotification,
- useSQLEditorStore,
- useSQLEditorTabStore,
- useSQLEditorWorksheetStore,
- useWorkSheetStore,
-} from "@/store";
+import { useSQLEditorStore as useSQLEditorReactStore } from "@/react/stores/sqlEditor";
+import { useSQLEditorVueState } from "@/react/stores/sqlEditor/editor-vue-state";
+import { useSQLEditorTabStore } from "@/react/stores/sqlEditor/tab-vue-state";
+import { pushNotification, useWorkSheetStore } from "@/store";
import {
openWorksheetByName,
revealNodes,
@@ -182,8 +179,8 @@ export function SheetTree({
// ---- Pinia stores (called at top level, not inside useVueState) ----------
const worksheetV1Store = useWorkSheetStore();
const tabStore = useSQLEditorTabStore();
- const editorStore = useSQLEditorStore();
- const editorWorksheetStore = useSQLEditorWorksheetStore();
+ const editorStore = useSQLEditorVueState();
+ const createWorksheet = useSQLEditorReactStore((s) => s.createWorksheet);
// ---- Sheet contexts -------------------------------------------------------
const sheetContext = useSheetContext();
@@ -736,7 +733,7 @@ export function SheetTree({
break;
}
case "add-worksheet":
- await editorWorksheetStore.createWorksheet({
+ await createWorksheet({
folders: getFoldersForWorksheet(contextMenuNode.key),
});
break;
@@ -761,7 +758,7 @@ export function SheetTree({
expandedKeysRef,
folderContext,
getFoldersForWorksheet,
- editorWorksheetStore,
+ createWorksheet,
handleDeleteFolders,
handleDuplicateSheet,
handleSharePanelShow,
@@ -1159,7 +1156,7 @@ export function SheetTree({
const worksheet =
worksheetV1Store.getWorksheetByName(worksheetName);
if (!worksheet) return;
- await editorWorksheetStore.createWorksheet({
+ await createWorksheet({
title: worksheet.title,
folders: worksheet.folders,
database: worksheet.database,
@@ -1358,12 +1355,7 @@ export function SheetTree({
}
/>
<PopoverContent align="start" sideOffset={4}>
- {worksheetEntity && (
- <SharePopoverBody
- worksheet={worksheetEntity}
- onUpdated={handleContextMenuClickOutside}
- />
- )}
+ {worksheetEntity && <SharePopoverBody worksheet={worksheetEntity} />}
</PopoverContent>
</Popover>
diff --git a/frontend/src/react/components/sql-editor/StandardPanel/EditorMain.tsx b/frontend/src/react/components/sql-editor/StandardPanel/EditorMain.tsx
index dde0c480ee..3b841b50d7 100644
--- a/frontend/src/react/components/sql-editor/StandardPanel/EditorMain.tsx
+++ b/frontend/src/react/components/sql-editor/StandardPanel/EditorMain.tsx
@@ -4,9 +4,9 @@ import { ReadonlyModeNotSupported } from "@/react/components/sql-editor/Readonly
import { useVueState } from "@/react/hooks/useVueState";
import {
useConnectionOfCurrentSQLEditorTab,
- useDatabaseV1Store,
useSQLEditorTabStore,
-} from "@/store";
+} from "@/react/stores/sqlEditor/tab-vue-state";
+import { useDatabaseV1Store } from "@/store";
import type { SQLEditorQueryParams } from "@/types";
import { Engine } from "@/types/proto-es/v1/common_pb";
import { getInstanceResource, instanceV1HasReadonlyMode } from "@/utils";
diff --git a/frontend/src/react/components/sql-editor/StandardPanel/SQLEditor.tsx b/frontend/src/react/components/sql-editor/StandardPanel/SQLEditor.tsx
index 4ea9c7d22a..eb3ca2b1fb 100644
--- a/frontend/src/react/components/sql-editor/StandardPanel/SQLEditor.tsx
+++ b/frontend/src/react/components/sql-editor/StandardPanel/SQLEditor.tsx
@@ -20,9 +20,8 @@ import { useSQLEditorStore } from "@/react/stores/sqlEditor";
import {
useConnectionOfCurrentSQLEditorTab,
useSQLEditorTabStore,
- useUIStateStore,
- useWorkSheetAndTabStore,
-} from "@/store";
+} from "@/react/stores/sqlEditor/tab-vue-state";
+import { useUIStateStore, useWorkSheetAndTabStore } from "@/store";
import {
dialectOfEngineV1,
isValidDatabaseName,
diff --git a/frontend/src/react/components/sql-editor/StandardPanel/StandardPanel.tsx b/frontend/src/react/components/sql-editor/StandardPanel/StandardPanel.tsx
index fd1a4ab33e..a9755b6d80 100644
--- a/frontend/src/react/components/sql-editor/StandardPanel/StandardPanel.tsx
+++ b/frontend/src/react/components/sql-editor/StandardPanel/StandardPanel.tsx
@@ -17,7 +17,7 @@ import {
import {
useConnectionOfCurrentSQLEditorTab,
useSQLEditorTabStore,
-} from "@/store";
+} from "@/react/stores/sqlEditor/tab-vue-state";
import { instanceV1HasReadonlyMode } from "@/utils";
import { EditorMain } from "./EditorMain";
diff --git a/frontend/src/react/components/sql-editor/StandardPanel/UploadFileButton.tsx b/frontend/src/react/components/sql-editor/StandardPanel/UploadFileButton.tsx
index 7058e73186..0d8a359061 100644
--- a/frontend/src/react/components/sql-editor/StandardPanel/UploadFileButton.tsx
+++ b/frontend/src/react/components/sql-editor/StandardPanel/UploadFileButton.tsx
@@ -3,7 +3,7 @@ import { useCallback } from "react";
import { useTranslation } from "react-i18next";
import { Tooltip } from "@/react/components/ui/tooltip";
import { useVueState } from "@/react/hooks/useVueState";
-import { useSQLEditorTabStore } from "@/store";
+import { useSQLEditorTabStore } from "@/react/stores/sqlEditor/tab-vue-state";
import { SQLUploadButton } from "./SQLUploadButton";
interface UploadFileButtonProps {
diff --git a/frontend/src/react/components/sql-editor/TabItem/Label.test.tsx b/frontend/src/react/components/sql-editor/TabItem/Label.test.tsx
index d116454eae..219df8a5c5 100644
--- a/frontend/src/react/components/sql-editor/TabItem/Label.test.tsx
+++ b/frontend/src/react/components/sql-editor/TabItem/Label.test.tsx
@@ -20,10 +20,13 @@ const mocks = vi.hoisted(() => ({
}));
vi.mock("@/store", () => ({
- useSQLEditorTabStore: mocks.useSQLEditorTabStore,
useWorkSheetStore: mocks.useWorkSheetStore,
}));
+vi.mock("@/react/stores/sqlEditor/tab-vue-state", () => ({
+ useSQLEditorTabStore: mocks.useSQLEditorTabStore,
+}));
+
vi.mock("@/views/sql-editor/TabList/events", () => ({
tabListEvents: mocks.tabListEvents,
}));
diff --git a/frontend/src/react/components/sql-editor/TabItem/Label.tsx b/frontend/src/react/components/sql-editor/TabItem/Label.tsx
index b6f1b47422..3416870b19 100644
--- a/frontend/src/react/components/sql-editor/TabItem/Label.tsx
+++ b/frontend/src/react/components/sql-editor/TabItem/Label.tsx
@@ -3,7 +3,8 @@ import { useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { EllipsisText } from "@/react/components/ui/ellipsis-text";
import { cn } from "@/react/lib/utils";
-import { useSQLEditorTabStore, useWorkSheetStore } from "@/store";
+import { useSQLEditorTabStore } from "@/react/stores/sqlEditor/tab-vue-state";
+import { useWorkSheetStore } from "@/store";
import { WorksheetSchema } from "@/types/proto-es/v1/worksheet_service_pb";
import type { SQLEditorTab } from "@/types/sqlEditor/tab";
import { tabListEvents } from "@/views/sql-editor/TabList/events";
diff --git a/frontend/src/react/components/sql-editor/TabItem/TabItem.tsx b/frontend/src/react/components/sql-editor/TabItem/TabItem.tsx
index 2881ba35fa..0108bc819b 100644
--- a/frontend/src/react/components/sql-editor/TabItem/TabItem.tsx
+++ b/frontend/src/react/components/sql-editor/TabItem/TabItem.tsx
@@ -3,7 +3,7 @@ import { CSS } from "@dnd-kit/utilities";
import { useState } from "react";
import { useVueState } from "@/react/hooks/useVueState";
import { cn } from "@/react/lib/utils";
-import { useSQLEditorTabStore } from "@/store";
+import { useSQLEditorTabStore } from "@/react/stores/sqlEditor/tab-vue-state";
import { UNKNOWN_ID } from "@/types/const";
import type { SQLEditorTab } from "@/types/sqlEditor/tab";
import {
diff --git a/frontend/src/react/components/sql-editor/TabList.test.tsx b/frontend/src/react/components/sql-editor/TabList.test.tsx
index 96f295b7fc..55ede86005 100644
--- a/frontend/src/react/components/sql-editor/TabList.test.tsx
+++ b/frontend/src/react/components/sql-editor/TabList.test.tsx
@@ -18,7 +18,6 @@ const mocks = vi.hoisted(() => ({
useTranslation: vi.fn(() => ({ t: (key: string) => key })),
useVueState: vi.fn<(getter: () => unknown) => unknown>(),
useSQLEditorTabStore: vi.fn(),
- useSQLEditorWorksheetStore: vi.fn(),
closeTab: vi.fn(),
setCurrentTabId: vi.fn(),
createWorksheet: vi.fn().mockResolvedValue(undefined),
@@ -34,9 +33,19 @@ vi.mock("@/react/hooks/useVueState", () => ({
useVueState: mocks.useVueState,
}));
-vi.mock("@/store", () => ({
+vi.mock("@/store", () => ({}));
+
+vi.mock("@/react/stores/sqlEditor/tab-vue-state", () => ({
useSQLEditorTabStore: mocks.useSQLEditorTabStore,
- useSQLEditorWorksheetStore: mocks.useSQLEditorWorksheetStore,
+}));
+
+vi.mock("@/react/stores/sqlEditor", () => ({
+ useSQLEditorStore: (
+ selector: (s: { createWorksheet: typeof mocks.createWorksheet }) => unknown
+ ) =>
+ selector({
+ createWorksheet: mocks.createWorksheet,
+ }),
}));
vi.mock("@/views/sql-editor/TabList/events", () => ({
@@ -206,9 +215,6 @@ const setup = (tabs: SQLEditorTab[], currentTabId = tabs[0]?.id ?? "") => {
closeTab: mocks.closeTab,
};
mocks.useSQLEditorTabStore.mockReturnValue(tabStore);
- mocks.useSQLEditorWorksheetStore.mockReturnValue({
- createWorksheet: mocks.createWorksheet,
- });
mocks.useVueState.mockImplementation((getter) => getter());
mocks.tabListEventsOn.mockReturnValue(() => {});
return { tabStore };
diff --git a/frontend/src/react/components/sql-editor/TabList.tsx b/frontend/src/react/components/sql-editor/TabList.tsx
index 31c5b5b8cd..9458759e04 100644
--- a/frontend/src/react/components/sql-editor/TabList.tsx
+++ b/frontend/src/react/components/sql-editor/TabList.tsx
@@ -31,7 +31,8 @@ import {
import { Button } from "@/react/components/ui/button";
import { useVueState } from "@/react/hooks/useVueState";
import { cn } from "@/react/lib/utils";
-import { useSQLEditorTabStore, useSQLEditorWorksheetStore } from "@/store";
+import { useSQLEditorStore } from "@/react/stores/sqlEditor";
+import { useSQLEditorTabStore } from "@/react/stores/sqlEditor/tab-vue-state";
import type { SQLEditorTab } from "@/types/sqlEditor/tab";
import { tabListEvents } from "@/views/sql-editor/TabList/events";
import { TabContextMenu, type TabContextMenuHandle } from "./TabContextMenu";
@@ -58,7 +59,7 @@ type PendingClose = {
export function TabList() {
const { t } = useTranslation();
const tabStore = useSQLEditorTabStore();
- const worksheetStore = useSQLEditorWorksheetStore();
+ const createWorksheet = useSQLEditorStore((s) => s.createWorksheet);
// `deep: true` so React re-renders when a tab's nested fields change
// (e.g. `tab.connection` after setConnection, or `tab.status` after
@@ -160,7 +161,7 @@ export function TabList() {
if (loading) return;
setLoading(true);
try {
- await worksheetStore.createWorksheet({});
+ await createWorksheet({});
requestAnimationFrame(() => {
const el = scrollRef.current;
if (el) el.scrollTo(el.scrollWidth, 0);
diff --git a/frontend/src/react/components/sql-editor/TerminalPanel/CompactSQLEditor.tsx b/frontend/src/react/components/sql-editor/TerminalPanel/CompactSQLEditor.tsx
index 8b5c3a1987..c9b36c9905 100644
--- a/frontend/src/react/components/sql-editor/TerminalPanel/CompactSQLEditor.tsx
+++ b/frontend/src/react/components/sql-editor/TerminalPanel/CompactSQLEditor.tsx
@@ -12,7 +12,7 @@ import { useVueState } from "@/react/hooks/useVueState";
import {
useConnectionOfCurrentSQLEditorTab,
useSQLEditorTabStore,
-} from "@/store";
+} from "@/react/stores/sqlEditor/tab-vue-state";
import type { SQLEditorQueryParams } from "@/types";
import { dialectOfEngineV1 } from "@/types";
import { Engine } from "@/types/proto-es/v1/common_pb";
diff --git a/frontend/src/react/components/sql-editor/TerminalPanel/TerminalPanel.tsx b/frontend/src/react/components/sql-editor/TerminalPanel/TerminalPanel.tsx
index a4744684ec..0d38f060ff 100644
--- a/frontend/src/react/components/sql-editor/TerminalPanel/TerminalPanel.tsx
+++ b/frontend/src/react/components/sql-editor/TerminalPanel/TerminalPanel.tsx
@@ -1,17 +1,15 @@
import { Loader2 } from "lucide-react";
-import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { useCallback, useEffect, useMemo, useRef } from "react";
import { useTranslation } from "react-i18next";
-import { watch } from "vue";
import type { IStandaloneCodeEditor } from "@/react/components/monaco/types";
import { ConnectionHolder } from "@/react/components/sql-editor/ConnectionHolder";
import { EditorAction } from "@/react/components/sql-editor/EditorAction";
import { ResultView } from "@/react/components/sql-editor/ResultView";
import { useVueState } from "@/react/hooks/useVueState";
-import {
- useDatabaseV1Store,
- useSQLEditorTabStore,
- useWebTerminalStore,
-} from "@/store";
+import { useSQLEditorStore } from "@/react/stores/sqlEditor";
+import { useSQLEditorTabStore } from "@/react/stores/sqlEditor/tab-vue-state";
+import { getWebTerminalQuerySession } from "@/react/stores/sqlEditor/webTerminal-service";
+import { useDatabaseV1Store } from "@/store";
import type { SQLEditorQueryParams, WebTerminalQueryItemV1 } from "@/types";
import { CompactSQLEditor } from "./CompactSQLEditor";
import { useHistory } from "./useHistory";
@@ -37,52 +35,43 @@ import { useHistory } from "./useHistory";
export function TerminalPanel() {
const { t } = useTranslation();
const tabStore = useSQLEditorTabStore();
- const webTerminalStore = useWebTerminalStore();
const databaseStore = useDatabaseV1Store();
+ const updateWebTerminalQueryItem = useSQLEditorStore(
+ (s) => s.updateWebTerminalQueryItem
+ );
+ const replaceWebTerminalQueryItems = useSQLEditorStore(
+ (s) => s.replaceWebTerminalQueryItems
+ );
const isDisconnected = useVueState(() => tabStore.isDisconnected);
const currentTabId = useVueState(() => tabStore.currentTab?.id);
- // Force a React re-render on every mutation of the active tab's
- // `queryItemList` (push, shift, per-item field flips). Watching the
- // ref's `.value` keeps the watch alive even when no tab is loaded
- // initially — re-arming on `currentTabId` change picks up the new
- // tab's query list. A plain `useVueState` getter wouldn't work here
- // because the store mutates the array in place, so the getter would
- // keep returning the same reference and `useSyncExternalStore` would
- // skip the re-render.
- const [, forceRender] = useState(0);
+ // Lazily create the per-tab session (WebSocket + timer + event bus)
+ // when this panel mounts for a new tab. The zustand selector below
+ // does its own subscription for re-renders; the session is only set
+ // up here so the controller and timer exist by the time the user
+ // hits Enter.
useEffect(() => {
const tab = tabStore.currentTab;
if (!tab) return;
- const qs = webTerminalStore.getQueryStateByTab(tab);
- const stop = watch(
- () => qs.queryItemList.value,
- () => forceRender((v) => v + 1),
- { deep: true, flush: "sync" }
- );
- return () => {
- stop();
- };
- }, [tabStore, webTerminalStore, currentTabId]);
+ getWebTerminalQuerySession(tab);
+ }, [tabStore, currentTabId]);
- // Re-spread on every render so the JSX iteration sees the latest
- // array. Items are still the same Vue reactive proxies; mutating
- // `item.statement` etc. flows back to the store via Pinia. Operations
- // that need to mutate the **list shape** (e.g. clear-screen
- // `.shift()`) must reach the live `queryItemList.value` directly.
- const queryList: WebTerminalQueryItemV1[] = (() => {
- const tab = tabStore.currentTab;
- if (!tab) return [];
- const qs = webTerminalStore.getQueryStateByTab(tab);
- return [...qs.queryItemList.value];
- })();
+ // Subscribe to the per-tab query items from the zustand slice — every
+ // mutation (push, status flip, resultSet attach) produces a new array
+ // reference, so the component re-renders without any Vue `watch`.
+ const queryList = useSQLEditorStore(
+ (s) =>
+ (currentTabId
+ ? s.webTerminalQueryItemsByTabId[currentTabId]
+ : undefined) ?? EMPTY_QUERY_LIST
+ );
const expired = useVueState(() => {
const tab = tabStore.currentTab;
if (!tab) return false;
- const qs = webTerminalStore.getQueryStateByTab(tab);
- return qs.timer.expired.value;
+ const session = getWebTerminalQuerySession(tab);
+ return session.timer.expired.value;
});
// Pre-fetch any database referenced by an existing query item so the
@@ -108,23 +97,23 @@ export function TerminalPanel() {
}
const tab = tabStore.currentTab;
if (!tab) return;
- const qs = webTerminalStore.getQueryStateByTab(tab);
- void qs.controller.events.emit("query", params);
+ const session = getWebTerminalQuerySession(tab);
+ void session.controller.events.emit("query", params);
},
- [currentQuery, tabStore, webTerminalStore]
+ [currentQuery, tabStore]
);
const handleClearScreen = useCallback(() => {
- // Mutate the live Vue array, not our shallow copy — the store's
- // reactivity is tracked on the source and React re-renders via the
- // tick-bumped `queryList` snapshot.
const tab = tabStore.currentTab;
if (!tab) return;
- const list = webTerminalStore.getQueryStateByTab(tab).queryItemList.value;
- while (list.length > 1) {
- list.shift();
- }
- }, [tabStore, webTerminalStore]);
+ // Keep only the live (tail) query item; the slice replaces the
+ // whole array, so React re-renders via the existing selector.
+ const items =
+ useSQLEditorStore.getState().webTerminalQueryItemsByTabId[tab.id] ??
+ EMPTY_QUERY_LIST;
+ if (items.length <= 1) return;
+ replaceWebTerminalQueryItems(tab.id, items.slice(-1));
+ }, [tabStore, replaceWebTerminalQueryItems]);
const handleHistory = useCallback(
(direction: "up" | "down", editor: IStandaloneCodeEditor) => {
@@ -144,7 +133,7 @@ export function TerminalPanel() {
const handleCancelQuery = () => {
const tab = tabStore.currentTab;
if (!tab) return;
- webTerminalStore.getQueryStateByTab(tab).controller.abort();
+ getWebTerminalQuerySession(tab).controller.abort();
};
// Auto-scroll the outer container to the bottom whenever the inner
@@ -170,18 +159,23 @@ export function TerminalPanel() {
// Build a stable handler list per-query for the editor onChange callback,
// since the editor inside `<CompactSQLEditor>` re-registers actions on
- // identity change of these props.
+ // identity change of these props. Each handler patches the item via
+ // the zustand slice — direct mutation is not safe with immutable items.
const handleChangeFor = useMemo(
() =>
new Map(
- queryList.map((q) => [
- q.id,
- (value: string) => {
- q.statement = value;
- },
- ])
+ queryList.map((q) => {
+ const tabId = currentTabId;
+ return [
+ q.id,
+ (value: string) => {
+ if (!tabId) return;
+ updateWebTerminalQueryItem(tabId, q.id, { statement: value });
+ },
+ ];
+ })
),
- [queryList]
+ [queryList, currentTabId, updateWebTerminalQueryItem]
);
return (
@@ -255,3 +249,8 @@ export function TerminalPanel() {
}
const noop = () => {};
+
+// Stable empty array reference so the zustand selector doesn't return a
+// fresh `[]` on every store change for unconnected tabs (would trigger
+// spurious re-renders).
+const EMPTY_QUERY_LIST: WebTerminalQueryItemV1[] = [];
diff --git a/frontend/src/react/components/sql-editor/TerminalPanel/useHistory.ts b/frontend/src/react/components/sql-editor/TerminalPanel/useHistory.ts
index 3e4c1166c9..e83823af80 100644
--- a/frontend/src/react/components/sql-editor/TerminalPanel/useHistory.ts
+++ b/frontend/src/react/components/sql-editor/TerminalPanel/useHistory.ts
@@ -1,6 +1,7 @@
import { useEffect, useRef } from "react";
import { useVueState } from "@/react/hooks/useVueState";
-import { useSQLEditorTabStore, useWebTerminalStore } from "@/store";
+import { useSQLEditorStore } from "@/react/stores/sqlEditor";
+import { useSQLEditorTabStore } from "@/react/stores/sqlEditor/tab-vue-state";
import type { WebTerminalQueryItemV1 } from "@/types";
import { minmax } from "@/utils";
@@ -21,14 +22,18 @@ interface HistoryState {
*/
export function useHistory() {
const tabStore = useSQLEditorTabStore();
- const webTerminalStore = useWebTerminalStore();
+ const updateWebTerminalQueryItem = useSQLEditorStore(
+ (s) => s.updateWebTerminalQueryItem
+ );
const historyByTabIdRef = useRef(new Map<string, HistoryState>());
- const currentQuery = useVueState((): WebTerminalQueryItemV1 | undefined => {
- const tab = tabStore.currentTab;
- if (!tab) return undefined;
- const list = webTerminalStore.getQueryStateByTab(tab).queryItemList.value;
- return list[list.length - 1];
+ // The selector returns the (immutable) tail item from zustand; React
+ // re-renders whenever the underlying array changes.
+ const currentTabId = useVueState(() => tabStore.currentTab?.id);
+ const currentQuery = useSQLEditorStore((s) => {
+ if (!currentTabId) return undefined;
+ const list = s.webTerminalQueryItemsByTabId[currentTabId];
+ return list && list.length > 0 ? list[list.length - 1] : undefined;
});
const currentStack = (): HistoryState | undefined => {
@@ -53,12 +58,20 @@ export function useHistory() {
stack.index = stack.list.length - 1;
};
- // Push the new query item onto the per-tab history whenever the tail
- // changes. Mirrors Vue's `watch(currentQuery, push, { immediate: true })`.
- // `push` reads through refs and store getters, so it doesn't need to be
- // a dependency.
+ // Push the new query item onto the per-tab history only when a new
+ // command row is created — not on every keystroke. The Vue original
+ // got this for free because `updateWebTerminalQueryItem` mutated the
+ // tail in place, so the `computed(() => list[length-1])` kept the
+ // same reference across edits. The zustand slice replaces the tail
+ // immutably (`{...item, ...patch}`), so the selector returns a new
+ // identity on every statement edit; gate on `id` to recover the
+ // original semantics.
+ const lastPushedIdRef = useRef<string | undefined>(undefined);
useEffect(() => {
- if (currentQuery) push(currentQuery);
+ if (!currentQuery) return;
+ if (currentQuery.id === lastPushedIdRef.current) return;
+ lastPushedIdRef.current = currentQuery.id;
+ push(currentQuery);
}, [currentQuery]);
const move = (direction: "up" | "down") => {
@@ -71,15 +84,19 @@ export function useHistory() {
const tab = tabStore.currentTab;
if (!tab) return;
- const head = webTerminalStore.getQueryStateByTab(tab).queryItemList.value;
- const tail = head[head.length - 1];
+ const tabItems =
+ useSQLEditorStore.getState().webTerminalQueryItemsByTabId[tab.id];
+ const tail = tabItems?.[tabItems.length - 1];
if (!tail) return;
if (nextIndex === list.length - 1) {
- tail.statement = "";
+ updateWebTerminalQueryItem(tab.id, tail.id, { statement: "" });
} else {
const historyQuery = list[nextIndex];
- if (historyQuery) tail.statement = historyQuery.statement;
+ if (historyQuery)
+ updateWebTerminalQueryItem(tab.id, tail.id, {
+ statement: historyQuery.statement,
+ });
}
stack.index = nextIndex;
};
diff --git a/frontend/src/react/components/sql-editor/TreeNodeSuffix.test.tsx b/frontend/src/react/components/sql-editor/TreeNodeSuffix.test.tsx
index 6fa5000c08..d336a335b7 100644
--- a/frontend/src/react/components/sql-editor/TreeNodeSuffix.test.tsx
+++ b/frontend/src/react/components/sql-editor/TreeNodeSuffix.test.tsx
@@ -35,10 +35,13 @@ vi.mock("@/react/hooks/useVueState", () => ({
vi.mock("@/store", () => ({
useWorkSheetStore: mocks.useWorkSheetStore,
- useSQLEditorTabStore: mocks.useSQLEditorTabStore,
useUserStore: mocks.useUserStore,
}));
+vi.mock("@/react/stores/sqlEditor/tab-vue-state", () => ({
+ useSQLEditorTabStore: mocks.useSQLEditorTabStore,
+}));
+
vi.mock("@/views/sql-editor/Sheet", () => ({
useSheetContext: mocks.useSheetContext,
}));
diff --git a/frontend/src/react/components/sql-editor/TreeNodeSuffix.tsx b/frontend/src/react/components/sql-editor/TreeNodeSuffix.tsx
index 53d018a891..0750fcdb16 100644
--- a/frontend/src/react/components/sql-editor/TreeNodeSuffix.tsx
+++ b/frontend/src/react/components/sql-editor/TreeNodeSuffix.tsx
@@ -3,7 +3,8 @@ import { useTranslation } from "react-i18next";
import { Tooltip } from "@/react/components/ui/tooltip";
import { useVueState } from "@/react/hooks/useVueState";
import { cn } from "@/react/lib/utils";
-import { useSQLEditorTabStore, useUserStore, useWorkSheetStore } from "@/store";
+import { useSQLEditorTabStore } from "@/react/stores/sqlEditor/tab-vue-state";
+import { useUserStore, useWorkSheetStore } from "@/store";
import { Worksheet_Visibility } from "@/types/proto-es/v1/worksheet_service_pb";
import type {
SheetViewMode,
diff --git a/frontend/src/react/components/sql-editor/Welcome.test.tsx b/frontend/src/react/components/sql-editor/Welcome.test.tsx
index 3871d6f642..c5dc80580b 100644
--- a/frontend/src/react/components/sql-editor/Welcome.test.tsx
+++ b/frontend/src/react/components/sql-editor/Welcome.test.tsx
@@ -46,11 +46,14 @@ vi.mock("@/router/dashboard/workspaceRoutes", () => ({
}));
vi.mock("@/store", () => ({
- useSQLEditorStore: vi.fn(),
useProjectV1Store: vi.fn(),
useWorkspaceV1Store: vi.fn(),
}));
+vi.mock("@/react/stores/sqlEditor/editor-vue-state", () => ({
+ useSQLEditorVueState: vi.fn(),
+}));
+
vi.mock("@/assets/logo-full.svg", () => ({
default: "/assets/logo-full.svg",
}));
diff --git a/frontend/src/react/components/sql-editor/Welcome.tsx b/frontend/src/react/components/sql-editor/Welcome.tsx
index 4b66aad028..11cc46b4c6 100644
--- a/frontend/src/react/components/sql-editor/Welcome.tsx
+++ b/frontend/src/react/components/sql-editor/Welcome.tsx
@@ -3,9 +3,10 @@ import { useTranslation } from "react-i18next";
import { BytebaseLogo } from "@/react/components/BytebaseLogo";
import { usePermissionCheck } from "@/react/components/PermissionGuard";
import { useVueState } from "@/react/hooks/useVueState";
+import { useSQLEditorVueState } from "@/react/stores/sqlEditor/editor-vue-state";
import { router } from "@/router";
import { INSTANCE_ROUTE_DASHBOARD } from "@/router/dashboard/workspaceRoutes";
-import { useProjectV1Store, useSQLEditorStore } from "@/store";
+import { useProjectV1Store } from "@/store";
import { WelcomeButton } from "./WelcomeButton";
export type WelcomeProps = {
@@ -19,7 +20,7 @@ export type WelcomeProps = {
export function Welcome({ onChangeConnection }: WelcomeProps) {
const { t } = useTranslation();
- const sqlEditorStore = useSQLEditorStore();
+ const sqlEditorStore = useSQLEditorVueState();
const projectV1Store = useProjectV1Store();
const project = useVueState(() => {
diff --git a/frontend/src/react/components/sql-editor/useSQLEditorAutoSave.ts b/frontend/src/react/components/sql-editor/useSQLEditorAutoSave.ts
index d227c8fdef..d563352f18 100644
--- a/frontend/src/react/components/sql-editor/useSQLEditorAutoSave.ts
+++ b/frontend/src/react/components/sql-editor/useSQLEditorAutoSave.ts
@@ -1,11 +1,8 @@
import { useEffect, useRef } from "react";
import { useVueState } from "@/react/hooks/useVueState";
-import {
- pushNotification,
- useSQLEditorTabStore,
- useSQLEditorWorksheetStore,
- useWorkSheetStore,
-} from "@/store";
+import { useSQLEditorStore } from "@/react/stores/sqlEditor";
+import { useSQLEditorTabStore } from "@/react/stores/sqlEditor/tab-vue-state";
+import { pushNotification, useWorkSheetStore } from "@/store";
import { isWorksheetWritableV1 } from "@/utils";
const AUTO_SAVE_DEBOUNCE_MS = 2000;
@@ -26,7 +23,11 @@ const AUTO_SAVE_DEBOUNCE_MS = 2000;
export function useSQLEditorAutoSave() {
const tabStore = useSQLEditorTabStore();
const worksheetStore = useWorkSheetStore();
- const sqlEditorWorksheetStore = useSQLEditorWorksheetStore();
+ const abortAutoSave = useSQLEditorStore((s) => s.abortAutoSave);
+ const setAutoSaveController = useSQLEditorStore(
+ (s) => s.setAutoSaveController
+ );
+ const maybeUpdateWorksheet = useSQLEditorStore((s) => s.maybeUpdateWorksheet);
const statement = useVueState(() => tabStore.currentTab?.statement);
const debounceTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
@@ -56,18 +57,18 @@ export function useSQLEditorAutoSave() {
const worksheet = worksheetStore.getWorksheetByName(tab.worksheet);
if (!worksheet || !isWorksheetWritableV1(worksheet)) return;
- sqlEditorWorksheetStore.abortAutoSave();
+ abortAutoSave();
const statementToSave = tab.statement;
const tabId = tab.id;
const controller = new AbortController();
- sqlEditorWorksheetStore.autoSaveController = controller;
+ setAutoSaveController(controller);
tabStore.updateTab(tabId, { status: "SAVING" });
let wasAborted = false;
try {
- await sqlEditorWorksheetStore.maybeUpdateWorksheet({
+ await maybeUpdateWorksheet({
tabId,
worksheet: tab.worksheet,
database: tab.connection.database,
@@ -89,7 +90,7 @@ export function useSQLEditorAutoSave() {
description: error instanceof Error ? error.message : "Unknown error",
});
} finally {
- sqlEditorWorksheetStore.autoSaveController = null;
+ setAutoSaveController(null);
if (!wasAborted) {
const currentStatement = tabStore.getTabById(tabId)?.statement;
if (currentStatement !== statementToSave) {
diff --git a/frontend/src/store/modules/sqlEditor/editor.ts b/frontend/src/react/stores/sqlEditor/editor-vue-state.ts
similarity index 64%
rename from frontend/src/store/modules/sqlEditor/editor.ts
rename to frontend/src/react/stores/sqlEditor/editor-vue-state.ts
index e61659d86d..ef496ddd42 100644
--- a/frontend/src/store/modules/sqlEditor/editor.ts
+++ b/frontend/src/react/stores/sqlEditor/editor-vue-state.ts
@@ -1,7 +1,6 @@
import { useLocalStorage } from "@vueuse/core";
import { includes } from "lodash-es";
-import { defineStore } from "pinia";
-import { computed, ref, watchEffect } from "vue";
+import { computed, reactive, ref, watchEffect } from "vue";
import { useProjectV1Store } from "@/store";
import { useQueryDataPolicy } from "@/store/modules/v1/policy";
import type { Database } from "@/types/proto-es/v1/database_service_pb";
@@ -14,7 +13,21 @@ import {
STORAGE_KEY_SQL_EDITOR_RESULT_LIMIT,
} from "@/utils";
-export const useSQLEditorStore = defineStore("sqlEditor", () => {
+/**
+ * Vue-reactive SQL Editor app state. Replaces the Pinia
+ * `useSQLEditorStore` (`store/modules/sqlEditor/editor.ts`) — same
+ * shape and field semantics, but lives as a module-level lazy
+ * singleton instead of a Pinia store. Several fields are derived
+ * computeds whose dependencies (project IAM policy, workspace
+ * permissions) sit in other Pinia stores, so keeping the Vue
+ * reactivity here lets consumers continue to use `useVueState(() =>
+ * editorState.X)` without churning that pattern across ~40 files.
+ *
+ * When SheetTree / other consumers eventually move off `useVueState`,
+ * this is the obvious thing to port to zustand (or selectors over the
+ * zustand store).
+ */
+const buildSQLEditorVueState = () => {
const projectStore = useProjectV1Store();
const resultRowsLimit = useLocalStorage(
@@ -38,14 +51,13 @@ export const useSQLEditorStore = defineStore("sqlEditor", () => {
) {
return defaults;
}
- // Otherwise, return the storage value
return storageValue;
},
}
);
- // `false` if we are preparing project-scoped resources
- // we should render a skeleton layout with spinner placeholders
+ // `false` while project-scoped resources are loading — consumers
+ // render a skeleton layout with spinner placeholders.
const projectContextReady = ref<boolean>(false);
const storedLastViewedProject = useLocalStorage<string>(
@@ -83,7 +95,11 @@ export const useSQLEditorStore = defineStore("sqlEditor", () => {
return hasProjectPermissionV2(project, "bb.sql.admin");
});
- return {
+ // Wrap with `reactive()` so consumers see the same auto-unwrap /
+ // auto-wrap-on-assign ergonomics they had with the Pinia store. Use
+ // Vue's `toRefs()` (not Pinia's `storeToRefs`) to extract individual
+ // refs when needed.
+ return reactive({
resultRowsLimit,
queryDataPolicy,
project: computed(() => storedLastViewedProject.value),
@@ -95,5 +111,13 @@ export const useSQLEditorStore = defineStore("sqlEditor", () => {
executingHintDatabase,
redisCommandOption,
allowAdmin,
- };
-});
+ });
+};
+
+let _state: ReturnType<typeof buildSQLEditorVueState> | undefined;
+export const useSQLEditorVueState = () => {
+ if (!_state) _state = buildSQLEditorVueState();
+ return _state;
+};
+
+export type SQLEditorVueState = ReturnType<typeof useSQLEditorVueState>;
diff --git a/frontend/src/store/modules/sqlEditor/folder.ts b/frontend/src/react/stores/sqlEditor/folder.ts
similarity index 82%
rename from frontend/src/store/modules/sqlEditor/folder.ts
rename to frontend/src/react/stores/sqlEditor/folder.ts
index 3af4dd7ada..97a179fb7d 100644
--- a/frontend/src/store/modules/sqlEditor/folder.ts
+++ b/frontend/src/react/stores/sqlEditor/folder.ts
@@ -1,16 +1,24 @@
import { sortBy } from "lodash-es";
-import { storeToRefs } from "pinia";
-import { computed } from "vue";
-import { useCurrentUserV1, useSQLEditorStore } from "@/store";
+import { computed, toRefs } from "vue";
+import { useSQLEditorVueState } from "@/react/stores/sqlEditor/editor-vue-state";
+import { useCurrentUserV1 } from "@/store";
import {
storageKeySqlEditorWorksheetFolder,
useDynamicLocalStorage,
} from "@/utils";
import type { SheetViewMode } from "@/views/sql-editor/Sheet/types";
+/**
+ * Vue-reactive folder-tree helper used by the worksheet sheet context.
+ * The only consumer today is the Vue-side singleton at
+ * `views/sql-editor/Sheet/context.ts`, but the file lives under the
+ * React store tree because the whole sqlEditor state surface is
+ * homing there as the Pinia layer is dismantled. The Vue refs and
+ * `storeToRefs` calls stay — the consumer is still Vue-reactive.
+ */
export const buildFolderContext = (viewMode: SheetViewMode) => {
const me = useCurrentUserV1();
- const { project } = storeToRefs(useSQLEditorStore());
+ const { project } = toRefs(useSQLEditorVueState());
const rootPath = computed(() => `/${viewMode}`);
const localCacheKey = computed(() =>
diff --git a/frontend/src/react/stores/sqlEditor/index.ts b/frontend/src/react/stores/sqlEditor/index.ts
index 2a23ef59e1..c566d213e8 100644
--- a/frontend/src/react/stores/sqlEditor/index.ts
+++ b/frontend/src/react/stores/sqlEditor/index.ts
@@ -1,10 +1,29 @@
import { create } from "zustand";
+import { createQueryHistorySlice } from "./queryHistory";
+import { createTreeSlice } from "./tree";
import type { SQLEditorStoreState } from "./types";
import { createUIStateSlice } from "./uiState";
+import { createWebTerminalSlice } from "./webTerminal";
+import { createWorksheetSaveSlice } from "./worksheet";
-export type { AsidePanelTab, SQLEditorStoreState } from "./types";
+export type {
+ AsidePanelTab,
+ QueryHistoryEntry,
+ QueryHistoryFilter,
+ SQLEditorStoreState,
+} from "./types";
+export {
+ getQueryHistoryCacheKey,
+ selectQueryHistoryEntry,
+} from "./queryHistory";
+export { idForSQLEditorTreeNodeTarget, selectAllTreeNodeKeys } from "./tree";
export { selectEditorPanelSize } from "./uiState";
+export { createWebTerminalQueryItemV1 } from "./webTerminal";
export const useSQLEditorStore = create<SQLEditorStoreState>()((...args) => ({
...createUIStateSlice(...args),
+ ...createQueryHistorySlice(...args),
+ ...createTreeSlice(...args),
+ ...createWebTerminalSlice(...args),
+ ...createWorksheetSaveSlice(...args),
}));
diff --git a/frontend/src/react/stores/sqlEditor/queryHistory.test.ts b/frontend/src/react/stores/sqlEditor/queryHistory.test.ts
new file mode 100644
index 0000000000..b65fd3cdd3
--- /dev/null
+++ b/frontend/src/react/stores/sqlEditor/queryHistory.test.ts
@@ -0,0 +1,209 @@
+import { beforeEach, describe, expect, test, vi } from "vitest";
+import { create, type StoreApi } from "zustand";
+import {
+ createQueryHistorySlice,
+ getQueryHistoryCacheKey,
+ selectQueryHistoryEntry,
+} from "./queryHistory";
+import type {
+ QueryHistoryFilter,
+ SQLEditorStoreState,
+ TreeSlice,
+ UIStateSlice,
+ WebTerminalSlice,
+ WorksheetSaveSlice,
+} from "./types";
+
+const searchQueryHistoriesMock = vi.fn();
+
+// Stub the connect client so the slice's `mergeLatest` /
+// `fetchQueryHistoryList` calls hit a deterministic in-memory fake.
+vi.mock("@/connect", () => ({
+ sqlServiceClientConnect: {
+ searchQueryHistories: (...args: unknown[]) =>
+ searchQueryHistoriesMock(...args),
+ },
+}));
+
+// Stub the UIState half so the composed store satisfies the
+// `SQLEditorStoreState` shape without dragging in the real uiState
+// slice (which reads localStorage on creation).
+const stubUIStateSlice = (): UIStateSlice => ({
+ asidePanelTab: "WORKSHEET",
+ showConnectionPanel: false,
+ showAIPanel: false,
+ pendingInsertAtCaret: undefined,
+ highlightAccessGrantName: undefined,
+ isShowingCode: false,
+ aiPanelSize: 0.3,
+ setAsidePanelTab: vi.fn(),
+ setShowConnectionPanel: vi.fn(),
+ setShowAIPanel: vi.fn(),
+ setPendingInsertAtCaret: vi.fn(),
+ setHighlightAccessGrantName: vi.fn(),
+ setIsShowingCode: vi.fn(),
+ handleEditorPanelResize: vi.fn(),
+});
+
+const stubTreeSlice = (): TreeSlice => ({
+ treeState: "UNSET",
+ treeNodeKeysById: {},
+ setTreeState: vi.fn(),
+ collectTreeNode: vi.fn(),
+ treeNodeKeysByTarget: vi.fn(() => []),
+});
+
+const stubWebTerminalSlice = (): WebTerminalSlice => ({
+ webTerminalQueryItemsByTabId: {},
+ ensureWebTerminalQueryState: vi.fn(),
+ clearWebTerminalQueryState: vi.fn(),
+ replaceWebTerminalQueryItems: vi.fn(),
+ pushWebTerminalQueryItem: vi.fn(),
+ updateWebTerminalQueryItem: vi.fn(),
+});
+
+const stubWorksheetSaveSlice = (): WorksheetSaveSlice => ({
+ autoSaveController: null,
+ setAutoSaveController: vi.fn(),
+ abortAutoSave: vi.fn(),
+ maybeSwitchProject: vi.fn(async () => undefined),
+ maybeUpdateWorksheet: vi.fn(async () => undefined),
+ createWorksheet: vi.fn(async () => undefined),
+});
+
+const makeStore = (): StoreApi<SQLEditorStoreState> =>
+ create<SQLEditorStoreState>()((...args) => ({
+ ...stubUIStateSlice(),
+ ...stubTreeSlice(),
+ ...stubWebTerminalSlice(),
+ ...stubWorksheetSaveSlice(),
+ ...createQueryHistorySlice(...args),
+ }));
+
+const filter: QueryHistoryFilter = {
+ project: "projects/p1",
+ database: "instances/inst1/databases/db1",
+};
+
+const history = (name: string) => ({
+ name,
+ statement: `-- ${name}`,
+ createTime: undefined,
+});
+
+beforeEach(() => {
+ searchQueryHistoriesMock.mockReset();
+});
+
+describe("getQueryHistoryCacheKey", () => {
+ test("composes project + database when both are valid", () => {
+ expect(
+ getQueryHistoryCacheKey({
+ project: "projects/p1",
+ database: "instances/i/databases/d",
+ })
+ ).toBe("projects/p1.instances/i/databases/d");
+ });
+
+ test("omits invalid resource segments", () => {
+ expect(getQueryHistoryCacheKey({ project: "p1", database: "" })).toBe("");
+ });
+});
+
+describe("queryHistory slice — fetchQueryHistoryList", () => {
+ test("replaces the list on first page (no pageToken)", async () => {
+ searchQueryHistoriesMock.mockResolvedValue({
+ queryHistories: [history("a"), history("b")],
+ nextPageToken: "tok-1",
+ });
+ const store = makeStore();
+ await store.getState().fetchQueryHistoryList(filter);
+ const entry = selectQueryHistoryEntry(filter)(store.getState());
+ expect(entry.queryHistories.map((h) => h.name)).toEqual(["a", "b"]);
+ expect(entry.nextPageToken).toBe("tok-1");
+ });
+
+ test("appends + dedupes by `name` on subsequent pages", async () => {
+ searchQueryHistoriesMock.mockResolvedValueOnce({
+ queryHistories: [history("a"), history("b")],
+ nextPageToken: "tok-2",
+ });
+ const store = makeStore();
+ await store.getState().fetchQueryHistoryList(filter);
+
+ searchQueryHistoriesMock.mockResolvedValueOnce({
+ // `b` is a duplicate (cursor drift) and must be filtered.
+ queryHistories: [history("b"), history("c")],
+ nextPageToken: "tok-3",
+ });
+ await store.getState().fetchQueryHistoryList(filter);
+
+ const entry = selectQueryHistoryEntry(filter)(store.getState());
+ expect(entry.queryHistories.map((h) => h.name)).toEqual(["a", "b", "c"]);
+ expect(entry.nextPageToken).toBe("tok-3");
+ });
+});
+
+describe("queryHistory slice — mergeLatest", () => {
+ test("prepends fresh entries and preserves the existing nextPageToken", async () => {
+ // Seed page 1.
+ searchQueryHistoriesMock.mockResolvedValueOnce({
+ queryHistories: [history("a"), history("b")],
+ nextPageToken: "tok-1",
+ });
+ const store = makeStore();
+ await store.getState().fetchQueryHistoryList(filter);
+
+ // mergeLatest returns the just-executed query at the top.
+ searchQueryHistoriesMock.mockResolvedValueOnce({
+ queryHistories: [history("z"), history("a")],
+ nextPageToken: "tok-fresh",
+ });
+ await store.getState().mergeLatest(filter);
+
+ const entry = selectQueryHistoryEntry(filter)(store.getState());
+ // `z` is new and prepended; `a` is deduped.
+ expect(entry.queryHistories.map((h) => h.name)).toEqual(["z", "a", "b"]);
+ // Cursor is preserved (existing wins).
+ expect(entry.nextPageToken).toBe("tok-1");
+ });
+
+ test("falls back to the response cursor when no cached entry exists yet", async () => {
+ searchQueryHistoriesMock.mockResolvedValue({
+ queryHistories: [history("z")],
+ nextPageToken: "tok-from-resp",
+ });
+ const store = makeStore();
+ await store.getState().mergeLatest(filter);
+ const entry = selectQueryHistoryEntry(filter)(store.getState());
+ expect(entry.nextPageToken).toBe("tok-from-resp");
+ });
+});
+
+describe("queryHistory slice — resetPageToken", () => {
+ test("clears the entry for the given filter only", async () => {
+ searchQueryHistoriesMock.mockResolvedValueOnce({
+ queryHistories: [history("a")],
+ nextPageToken: "tok-1",
+ });
+ const store = makeStore();
+ await store.getState().fetchQueryHistoryList(filter);
+
+ store.getState().resetPageToken(filter);
+ const entry = selectQueryHistoryEntry(filter)(store.getState());
+ expect(entry.queryHistories).toEqual([]);
+ expect(entry.nextPageToken).toBeUndefined();
+ });
+});
+
+describe("selectQueryHistoryEntry", () => {
+ test("returns the same stable empty reference when the entry is missing", () => {
+ const store = makeStore();
+ const a = selectQueryHistoryEntry(filter)(store.getState());
+ const b = selectQueryHistoryEntry(filter)(store.getState());
+ // Reference equality — a stable empty default keeps zustand selectors
+ // from re-rendering on every store change for unseen filters.
+ expect(a).toBe(b);
+ expect(a.queryHistories).toEqual([]);
+ });
+});
diff --git a/frontend/src/react/stores/sqlEditor/queryHistory.ts b/frontend/src/react/stores/sqlEditor/queryHistory.ts
new file mode 100644
index 0000000000..7865bf993c
--- /dev/null
+++ b/frontend/src/react/stores/sqlEditor/queryHistory.ts
@@ -0,0 +1,146 @@
+import { create } from "@bufbuild/protobuf";
+import { sqlServiceClientConnect } from "@/connect";
+import type { QueryHistory } from "@/types/proto-es/v1/sql_service_pb";
+import { SearchQueryHistoriesRequestSchema } from "@/types/proto-es/v1/sql_service_pb";
+import { isValidDatabaseName } from "@/types/v1/database";
+import { isValidProjectName } from "@/types/v1/project";
+import type {
+ QueryHistoryEntry,
+ QueryHistoryFilter,
+ QueryHistorySlice,
+ SQLEditorSliceCreator,
+ SQLEditorStoreState,
+} from "./types";
+
+const EMPTY_ENTRY: QueryHistoryEntry = { queryHistories: [] };
+
+const getListQueryHistoryFilter = (filter: QueryHistoryFilter) => {
+ const params = [`type == "QUERY"`];
+ if (isValidProjectName(filter.project)) {
+ params.push(`project == "${filter.project}"`);
+ }
+ if (isValidDatabaseName(filter.database)) {
+ params.push(`database == "${filter.database}"`);
+ }
+ if (filter.statement) {
+ params.push(`statement.contains("${filter.statement}")`);
+ }
+ return params.join(" && ");
+};
+
+export const getQueryHistoryCacheKey = (filter: QueryHistoryFilter): string => {
+ const params: string[] = [];
+ if (isValidProjectName(filter.project)) {
+ params.push(filter.project as string);
+ }
+ if (isValidDatabaseName(filter.database)) {
+ params.push(filter.database as string);
+ }
+ return params.join(".");
+};
+
+export const createQueryHistorySlice: SQLEditorSliceCreator<
+ QueryHistorySlice
+> = (set, get) => ({
+ queryHistoryByKey: {},
+
+ fetchQueryHistoryList: async (filter) => {
+ const key = getQueryHistoryCacheKey(filter);
+ const existing = get().queryHistoryByKey[key] ?? EMPTY_ENTRY;
+ const pageToken = existing.nextPageToken;
+
+ const request = create(SearchQueryHistoriesRequestSchema, {
+ pageSize: 5,
+ pageToken,
+ filter: getListQueryHistoryFilter(filter),
+ });
+ const resp = await sqlServiceClientConnect.searchQueryHistories(request);
+
+ set((s) => {
+ const prev = s.queryHistoryByKey[key] ?? EMPTY_ENTRY;
+ let queryHistories: QueryHistory[];
+ if (pageToken) {
+ // Dedupe by `name` on the append path. The backend uses
+ // offset-based page tokens, so when `mergeLatest` prepends a
+ // freshly-executed query the cached cursor is now off by one
+ // (the new entry shifted every server position). The next
+ // "Load more" call may return rows that already live in the
+ // cache; filtering by `name` prevents visible duplicates.
+ const cachedNames = new Set(prev.queryHistories.map((h) => h.name));
+ const fresh = resp.queryHistories.filter(
+ (h) => !cachedNames.has(h.name)
+ );
+ queryHistories = [...prev.queryHistories, ...fresh];
+ } else {
+ queryHistories = resp.queryHistories;
+ }
+ return {
+ queryHistoryByKey: {
+ ...s.queryHistoryByKey,
+ [key]: { nextPageToken: resp.nextPageToken, queryHistories },
+ },
+ };
+ });
+ return resp;
+ },
+
+ resetPageToken: (filter) => {
+ const key = getQueryHistoryCacheKey(filter);
+ set((s) => ({
+ queryHistoryByKey: {
+ ...s.queryHistoryByKey,
+ [key]: { queryHistories: [] },
+ },
+ }));
+ },
+
+ /**
+ * Post-execute refresh that preserves pagination state. Fetches
+ * page 1 (no cursor) and prepends entries whose `name` isn't already
+ * cached. Keeps the existing `nextPageToken`, so a user who has
+ * loaded pages 1–3 stays at pages 1–3 after running a new query —
+ * the just-executed statement appears at the top without resetting
+ * the list.
+ */
+ mergeLatest: async (filter) => {
+ const key = getQueryHistoryCacheKey(filter);
+ const resp = await sqlServiceClientConnect.searchQueryHistories(
+ create(SearchQueryHistoriesRequestSchema, {
+ pageSize: 5,
+ filter: getListQueryHistoryFilter(filter),
+ })
+ );
+ set((s) => {
+ const existing = s.queryHistoryByKey[key];
+ const existingNames = new Set(
+ (existing?.queryHistories ?? []).map((h) => h.name)
+ );
+ const fresh = resp.queryHistories.filter(
+ (h) => !existingNames.has(h.name)
+ );
+ return {
+ queryHistoryByKey: {
+ ...s.queryHistoryByKey,
+ [key]: {
+ nextPageToken: existing?.nextPageToken ?? resp.nextPageToken,
+ queryHistories: [...fresh, ...(existing?.queryHistories ?? [])],
+ },
+ },
+ };
+ });
+ return resp;
+ },
+});
+
+/**
+ * Curried selector for the query-history entry under a specific filter.
+ * Returns a stable `EMPTY_ENTRY` reference when no entry exists yet, so
+ * subscribers don't see infinite re-renders from default-object identity
+ * changes.
+ */
+export const selectQueryHistoryEntry =
+ (filter: QueryHistoryFilter) =>
+ (state: SQLEditorStoreState): QueryHistoryEntry => {
+ const key = getQueryHistoryCacheKey(filter);
+ return state.queryHistoryByKey[key] ?? EMPTY_ENTRY;
+ };
diff --git a/frontend/src/store/modules/sqlEditor/tab.ts b/frontend/src/react/stores/sqlEditor/tab-vue-state.ts
similarity index 87%
rename from frontend/src/store/modules/sqlEditor/tab.ts
rename to frontend/src/react/stores/sqlEditor/tab-vue-state.ts
index bbc2ca1fc3..1720f0bfa5 100644
--- a/frontend/src/store/modules/sqlEditor/tab.ts
+++ b/frontend/src/react/stores/sqlEditor/tab-vue-state.ts
@@ -1,6 +1,17 @@
import { cloneDeep, head, isUndefined, omitBy, pick } from "lodash-es";
-import { defineStore, storeToRefs } from "pinia";
-import { computed, type MaybeRef, reactive, unref, watch } from "vue";
+import { computed, type MaybeRef, reactive, toRefs, unref, watch } from "vue";
+import { useSQLEditorVueState } from "@/react/stores/sqlEditor/editor-vue-state";
+import {
+ hasFeature,
+ useCurrentUserV1,
+ useDatabaseV1ByName,
+ useEnvironmentV1Store,
+ useWorkSheetStore,
+} from "@/store";
+import {
+ migrateDraftsFromCache,
+ migrateTabViewState,
+} from "@/store/modules/sqlEditor/legacy/migration";
import type {
BatchQueryContext,
SQLEditorConnection,
@@ -22,20 +33,16 @@ import {
storageKeySqlEditorTabs,
useDynamicLocalStorage,
} from "@/utils";
-import {
- hasFeature,
- useDatabaseV1ByName,
- useEnvironmentV1Store,
- useWorkSheetStore,
-} from "../v1";
-import { useCurrentUserV1 } from "../v1/auth";
-import { useSQLEditorStore } from "./editor";
-import {
- migrateDraftsFromCache,
- migrateTabViewState,
-} from "./legacy/migration";
-import { useWebTerminalStore } from "./webTerminal";
+/**
+ * Vue-reactive SQL Editor tab state. Replaces the Pinia
+ * `useSQLEditorTabStore` (`store/modules/sqlEditor/tab.ts`) — same
+ * shape and field semantics, but lives as a module-level lazy
+ * singleton instead of a Pinia store. The store is still heavily
+ * Vue-reactive (`reactive(new Map())`, `computed`, `watch`,
+ * `useDynamicLocalStorage`), so consumers continue to use
+ * `useVueState(() => tabStore.X)` for cross-framework reads.
+ */
const PERSISTENT_TAB_FIELDS = [
"id",
"worksheet",
@@ -46,9 +53,9 @@ const PERSISTENT_TAB_FIELDS = [
] as const;
type PersistentTab = Pick<SQLEditorTab, (typeof PERSISTENT_TAB_FIELDS)[number]>;
-export const useSQLEditorTabStore = defineStore("sqlEditorTab", () => {
+const buildSQLEditorTabState = () => {
// re-expose selected project in sqlEditorStore for shortcut
- const { project } = storeToRefs(useSQLEditorStore());
+ const { project } = toRefs(useSQLEditorVueState());
const tabsById = reactive(new Map<string, SQLEditorTab>());
const worksheetStore = useWorkSheetStore();
@@ -170,7 +177,6 @@ export const useSQLEditorTabStore = defineStore("sqlEditorTab", () => {
return databaseGroups.length > 0 || databases.length > 1;
});
- // actions
/**
* Create or update the tab, and ensure the tab is open.
* @param payload
@@ -228,7 +234,13 @@ export const useSQLEditorTabStore = defineStore("sqlEditorTab", () => {
}
openTmpTabList.value.splice(position, 1);
tabsById.delete(tabId);
- useWebTerminalStore().clearQueryStateByTab(tabId);
+ // Dynamic import avoids a static cycle with the zustand store
+ // (which transitively re-imports this module via `@/store`).
+ void import("@/react/stores/sqlEditor/webTerminal-service").then(
+ ({ disposeWebTerminalQuerySession }) => {
+ disposeWebTerminalQuerySession(tabId);
+ }
+ );
if (tabId === currentTabId.value) {
const nextIndex = Math.min(position, openTmpTabList.value.length - 1);
@@ -327,7 +339,6 @@ export const useSQLEditorTabStore = defineStore("sqlEditorTab", () => {
if (!tab.databaseQueryContexts.has(database)) {
return;
}
- // Early exit if no contexts to remove
if (contextIds.length === 0) {
return;
}
@@ -336,7 +347,6 @@ export const useSQLEditorTabStore = defineStore("sqlEditorTab", () => {
const contexts = tab.databaseQueryContexts.get(database)!;
const newContexts = contexts.filter((ctx) => !target.has(ctx.id));
- // Only update if something actually changed
if (newContexts.length !== contexts.length) {
tab.databaseQueryContexts.set(database, newContexts);
}
@@ -387,14 +397,17 @@ export const useSQLEditorTabStore = defineStore("sqlEditorTab", () => {
}
);
- // some shortcuts
const isDisconnected = computed(() => {
const tab = currentTab.value;
if (!tab) return true;
return !isConnectedSQLEditorTab(tab);
});
- return {
+ // Wrap with `reactive()` so consumers see the same auto-unwrap /
+ // auto-wrap-on-assign ergonomics they had with the Pinia store. Use
+ // Vue's `toRefs()` (not Pinia's `storeToRefs`) to extract individual
+ // refs when needed.
+ return reactive({
project,
initProject,
getTabById,
@@ -416,22 +429,28 @@ export const useSQLEditorTabStore = defineStore("sqlEditorTab", () => {
isDisconnected,
isInBatchMode,
supportBatchMode,
- };
-});
+ });
+};
+
+let _state: ReturnType<typeof buildSQLEditorTabState> | undefined;
+export const useSQLEditorTabStore = () => {
+ if (!_state) _state = buildSQLEditorTabState();
+ return _state;
+};
+
+export type SQLEditorTabState = ReturnType<typeof useSQLEditorTabStore>;
export const useCurrentSQLEditorTab = () => {
- return storeToRefs(useSQLEditorTabStore()).currentTab;
+ return toRefs(useSQLEditorTabStore()).currentTab;
};
export const isSQLEditorTabClosable = (tab: SQLEditorTab) => {
const { openTabList } = useSQLEditorTabStore();
if (openTabList.length > 1) {
- // Not the only one tab
return true;
}
if (openTabList.length === 1) {
- // It's the only one tab, and it's closable if it's a sheet tab
return !!tab.worksheet;
}
return false;
diff --git a/frontend/src/store/modules/sqlEditor/tree.ts b/frontend/src/react/stores/sqlEditor/tree-utils.ts
similarity index 58%
rename from frontend/src/store/modules/sqlEditor/tree.ts
rename to frontend/src/react/stores/sqlEditor/tree-utils.ts
index 40294a0318..0183c44d6a 100644
--- a/frontend/src/store/modules/sqlEditor/tree.ts
+++ b/frontend/src/react/stores/sqlEditor/tree-utils.ts
@@ -1,67 +1,29 @@
-import { flatten, orderBy, uniq } from "lodash-es";
-import { defineStore } from "pinia";
-import { computed, reactive, ref } from "vue";
+import { orderBy } from "lodash-es";
+import {
+ useEnvironmentV1Store,
+ useInstanceResourceByName,
+} from "@/store/modules/v1";
import type {
SQLEditorTreeFactor as Factor,
SQLEditorTreeNodeTarget as NodeTarget,
SQLEditorTreeNodeType as NodeType,
SQLEditorTreeNode as TreeNode,
- SQLEditorTreeState as TreeState,
} from "@/types";
import {
extractSQLEditorLabelFactor as extractLabelFactor,
- formatEnvironmentName,
LeafTreeNodeTypes,
unknownEnvironment,
} from "@/types";
import type { Database } from "@/types/proto-es/v1/database_service_pb";
import type { InstanceResource } from "@/types/proto-es/v1/instance_service_pb";
-import type { Project } from "@/types/proto-es/v1/project_service_pb";
import type { Environment } from "@/types/v1/environment";
import {
extractDatabaseResourceName,
getSemanticLabelValue,
groupBy,
} from "@/utils";
-import { useEnvironmentV1Store, useInstanceResourceByName } from "../v1";
-
-export const useSQLEditorTreeStore = defineStore("sqlEditorTree", () => {
- const nodeListMapById = reactive(
- new Map<
- string /* node id by type and target */,
- string[] /* node key list */
- >()
- );
- // states
- const allNodeKeys = computed(() => {
- return uniq(flatten([...nodeListMapById.values()]));
- });
-
- const state = ref<TreeState>("UNSET");
-
- const collectNode = <T extends NodeType>(node: TreeNode<T>) => {
- const { type, target } = node.meta;
- const id = idForSQLEditorTreeNodeTarget(type, target);
- const nodeList = nodeListMapById.get(id) ?? [];
- nodeList.push(node.key);
- nodeListMapById.set(id, nodeList);
- };
-
- const nodeKeysByTarget = <T extends NodeType>(
- type: T,
- target: NodeTarget<T>
- ) => {
- const id = idForSQLEditorTreeNodeTarget(type, target);
- return nodeListMapById.get(id) ?? [];
- };
-
- return {
- state,
- collectNode,
- nodeKeysByTarget,
- allNodeKeys,
- };
-});
+import { useSQLEditorStore } from "./index";
+import { idForSQLEditorTreeNodeTarget } from "./tree";
const keyForSQLEditorTreeNodeTarget = <T extends NodeType>(
type: T,
@@ -76,26 +38,6 @@ const keyForSQLEditorTreeNodeTarget = <T extends NodeType>(
return parts.join("/");
};
-export const idForSQLEditorTreeNodeTarget = <T extends NodeType>(
- type: T,
- target: NodeTarget<T>
-) => {
- if (type === "instance" || type === "database") {
- return (target as Project | InstanceResource | Database).name;
- }
- if (type === "environment") {
- return formatEnvironmentName((target as Environment).id);
- }
- if (type === "label") {
- const kv = target as NodeTarget<"label">;
- return `labels/${kv.key}:${kv.value}`;
- }
-
- throw new Error(
- `should never reach this line, type=${type}, target=${target}, parent=${parent}`
- );
-};
-
const buildSubTree = (
databaseList: Database[],
parent: TreeNode | undefined,
@@ -103,14 +45,9 @@ const buildSubTree = (
factorIndex: number
): TreeNode[] => {
if (factorIndex === factorList.length) {
- // the last dimension is database nodes
- return databaseList.map((db) => {
- const node = mapTreeNodeByType("database", db, parent);
- return node;
- });
+ return databaseList.map((db) => mapTreeNodeByType("database", db, parent));
}
- // group (project, instance, environment, label) nodes
const nodes: TreeNode[] = [];
const factor = factorList[factorIndex];
@@ -132,7 +69,6 @@ const buildSubTree = (
const sortNodesIfNeeded = (nodes: TreeNode[], factor: Factor) => {
if (factor === "environment") {
- // Sort by environment order DESC. Put production envs to the first.
return orderBy(
nodes as TreeNode<"environment">[],
[(node) => node.meta.target.order],
@@ -140,31 +76,22 @@ const sortNodesIfNeeded = (nodes: TreeNode[], factor: Factor) => {
);
}
if (factor.startsWith("label:")) {
- // Sort in lexicographical order, and put <empty value> to the last
return orderBy(
nodes as TreeNode<"label">[],
[
- (node) => (node.meta.target.value ? -1 : 1), // Empty value to the last,
- (node) => node.meta.target.value, // lexicographical order then
+ (node) => (node.meta.target.value ? -1 : 1),
+ (node) => node.meta.target.value,
],
["asc", "asc"]
);
}
-
return nodes;
};
export const buildTreeImpl = (
databaseList: Database[],
factorList: Factor[]
-): TreeNode[] => {
- return buildSubTree(
- databaseList,
- undefined /* parent */,
- factorList,
- 0 /* factorIndex */
- );
-};
+): TreeNode[] => buildSubTree(databaseList, undefined, factorList, 0);
const mapGroupNode = (
factor: Factor,
@@ -181,19 +108,10 @@ const mapGroupNode = (
const { instance } = useInstanceResourceByName(value);
return mapTreeNodeByType("instance", instance.value, parent);
}
- // factor is label
const key = extractLabelFactor(factor);
if (key) {
- return mapTreeNodeByType(
- "label",
- {
- key,
- value,
- },
- parent
- );
+ return mapTreeNodeByType("label", { key, value }, parent);
}
-
throw new Error(
`mapGroupNode: should never reach this line. factor=${factor}, factorValue=${value}`
);
@@ -214,8 +132,7 @@ export const mapTreeNodeByType = <T extends NodeType>(
...overrides,
};
- useSQLEditorTreeStore().collectNode(node);
-
+ useSQLEditorStore.getState().collectTreeNode(node);
return node;
};
@@ -235,9 +152,7 @@ const readableTargetByType = <T extends NodeType>(
return (target as NodeTarget<"label">).value;
};
-const isLeafNodeType = (type: NodeType) => {
- return LeafTreeNodeTypes.includes(type);
-};
+const isLeafNodeType = (type: NodeType) => LeafTreeNodeTypes.includes(type);
const getSemanticFactorValue = (db: Database, factor: Factor) => {
switch (factor) {
@@ -246,7 +161,6 @@ const getSemanticFactorValue = (db: Database, factor: Factor) => {
case "instance":
return extractDatabaseResourceName(db.name).instance;
}
-
const key = extractLabelFactor(factor);
if (key) {
return getSemanticLabelValue(db, key);
diff --git a/frontend/src/react/stores/sqlEditor/tree.ts b/frontend/src/react/stores/sqlEditor/tree.ts
new file mode 100644
index 0000000000..d6f67ff896
--- /dev/null
+++ b/frontend/src/react/stores/sqlEditor/tree.ts
@@ -0,0 +1,67 @@
+import { flatten, uniq } from "lodash-es";
+import type {
+ SQLEditorTreeNodeTarget as NodeTarget,
+ SQLEditorTreeNodeType as NodeType,
+ SQLEditorTreeState as TreeState,
+} from "@/types";
+import { formatEnvironmentName } from "@/types";
+import type { Database } from "@/types/proto-es/v1/database_service_pb";
+import type { InstanceResource } from "@/types/proto-es/v1/instance_service_pb";
+import type { Project } from "@/types/proto-es/v1/project_service_pb";
+import type { Environment } from "@/types/v1/environment";
+import type {
+ SQLEditorSliceCreator,
+ SQLEditorStoreState,
+ TreeSlice,
+} from "./types";
+
+export const idForSQLEditorTreeNodeTarget = <T extends NodeType>(
+ type: T,
+ target: NodeTarget<T>
+): string => {
+ if (type === "instance" || type === "database") {
+ return (target as Project | InstanceResource | Database).name;
+ }
+ if (type === "environment") {
+ return formatEnvironmentName((target as Environment).id);
+ }
+ if (type === "label") {
+ const kv = target as NodeTarget<"label">;
+ return `labels/${kv.key}:${kv.value}`;
+ }
+ throw new Error(
+ `should never reach this line, type=${type}, target=${target}`
+ );
+};
+
+export const createTreeSlice: SQLEditorSliceCreator<TreeSlice> = (
+ set,
+ get
+) => ({
+ treeState: "UNSET",
+ treeNodeKeysById: {},
+
+ setTreeState: (state: TreeState) => set({ treeState: state }),
+
+ collectTreeNode: (node) => {
+ const { type, target } = node.meta;
+ const id = idForSQLEditorTreeNodeTarget(type, target);
+ set((s) => {
+ const prev = s.treeNodeKeysById[id] ?? [];
+ return {
+ treeNodeKeysById: {
+ ...s.treeNodeKeysById,
+ [id]: [...prev, node.key],
+ },
+ };
+ });
+ },
+
+ treeNodeKeysByTarget: (type, target) => {
+ const id = idForSQLEditorTreeNodeTarget(type, target);
+ return get().treeNodeKeysById[id] ?? [];
+ },
+});
+
+export const selectAllTreeNodeKeys = (state: SQLEditorStoreState): string[] =>
+ uniq(flatten(Object.values(state.treeNodeKeysById)));
diff --git a/frontend/src/react/stores/sqlEditor/types.ts b/frontend/src/react/stores/sqlEditor/types.ts
index 0c8e78de5c..9ddc4f4888 100644
--- a/frontend/src/react/stores/sqlEditor/types.ts
+++ b/frontend/src/react/stores/sqlEditor/types.ts
@@ -1,4 +1,16 @@
import type { StateCreator } from "zustand";
+import type {
+ SQLEditorTreeNodeTarget as NodeTarget,
+ SQLEditorTreeNodeType as NodeType,
+ SQLEditorTab,
+ SQLEditorTreeNode as TreeNode,
+ SQLEditorTreeState as TreeState,
+ WebTerminalQueryItemV1,
+} from "@/types";
+import type {
+ QueryHistory,
+ SearchQueryHistoriesResponse,
+} from "@/types/proto-es/v1/sql_service_pb";
export type AsidePanelTab = "SCHEMA" | "WORKSHEET" | "HISTORY" | "ACCESS";
@@ -25,7 +37,91 @@ export interface UIStateSlice {
handleEditorPanelResize: (size: number) => void;
}
-export type SQLEditorStoreState = UIStateSlice;
+export interface QueryHistoryFilter {
+ statement?: string;
+ project?: string;
+ database?: string;
+}
+
+export interface QueryHistoryEntry {
+ nextPageToken?: string;
+ queryHistories: QueryHistory[];
+}
+
+export interface QueryHistorySlice {
+ queryHistoryByKey: Record<string, QueryHistoryEntry>;
+ fetchQueryHistoryList: (
+ filter: QueryHistoryFilter
+ ) => Promise<SearchQueryHistoriesResponse>;
+ resetPageToken: (filter: QueryHistoryFilter) => void;
+ mergeLatest: (
+ filter: QueryHistoryFilter
+ ) => Promise<SearchQueryHistoriesResponse>;
+}
+
+export interface TreeSlice {
+ treeState: TreeState;
+ // Index of node-target id → registered node keys.
+ treeNodeKeysById: Record<string, string[]>;
+
+ setTreeState: (state: TreeState) => void;
+ collectTreeNode: <T extends NodeType>(node: TreeNode<T>) => void;
+ treeNodeKeysByTarget: <T extends NodeType>(
+ type: T,
+ target: NodeTarget<T>
+ ) => string[];
+}
+
+export interface WebTerminalSlice {
+ // Per-tab admin-mode query items. The WebSocket / RxJS / timer
+ // services live module-side (see `webTerminal-service.ts`); only the
+ // React-visible state is in the slice.
+ webTerminalQueryItemsByTabId: Record<string, WebTerminalQueryItemV1[]>;
+ ensureWebTerminalQueryState: (tabId: string) => void;
+ clearWebTerminalQueryState: (tabId: string) => void;
+ replaceWebTerminalQueryItems: (
+ tabId: string,
+ items: WebTerminalQueryItemV1[]
+ ) => void;
+ pushWebTerminalQueryItem: (tabId: string) => void;
+ updateWebTerminalQueryItem: (
+ tabId: string,
+ itemId: string,
+ patch: Partial<WebTerminalQueryItemV1>
+ ) => void;
+}
+
+export interface WorksheetSaveSlice {
+ // Live AbortController for the active auto-save request. Set by the
+ // auto-save composable so a subsequent edit can cancel the in-flight
+ // PATCH. `null` between saves.
+ autoSaveController: AbortController | null;
+ setAutoSaveController: (controller: AbortController | null) => void;
+ abortAutoSave: () => void;
+ maybeSwitchProject: (projectName: string) => Promise<string | undefined>;
+ maybeUpdateWorksheet: (opts: {
+ tabId: string;
+ worksheet?: string;
+ title?: string;
+ database: string;
+ statement: string;
+ folders?: string[];
+ signal?: AbortSignal;
+ }) => Promise<SQLEditorTab | undefined>;
+ createWorksheet: (opts: {
+ tabId?: string;
+ title?: string;
+ statement?: string;
+ folders?: string[];
+ database?: string;
+ }) => Promise<SQLEditorTab | undefined>;
+}
+
+export type SQLEditorStoreState = UIStateSlice &
+ QueryHistorySlice &
+ TreeSlice &
+ WebTerminalSlice &
+ WorksheetSaveSlice;
export type SQLEditorSliceCreator<Slice> = StateCreator<
SQLEditorStoreState,
diff --git a/frontend/src/react/stores/sqlEditor/uiState.test.ts b/frontend/src/react/stores/sqlEditor/uiState.test.ts
index fe4d3d8217..0439d6c8ff 100644
--- a/frontend/src/react/stores/sqlEditor/uiState.test.ts
+++ b/frontend/src/react/stores/sqlEditor/uiState.test.ts
@@ -1,7 +1,13 @@
-import { afterEach, beforeEach, describe, expect, test } from "vitest";
+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
import { create, type StoreApi } from "zustand";
import { STORAGE_KEY_SQL_EDITOR_AI_PANEL_SIZE } from "@/utils/storage-keys";
-import type { SQLEditorStoreState } from "./types";
+import type {
+ QueryHistorySlice,
+ SQLEditorStoreState,
+ TreeSlice,
+ WebTerminalSlice,
+ WorksheetSaveSlice,
+} from "./types";
const originalLocalStorage = globalThis.localStorage;
const storage = new Map<string, string>();
@@ -22,16 +28,59 @@ const localStorageMock = {
},
};
+// Inline stub for the queryHistory slice so this test stays decoupled
+// from the real `./queryHistory` module — that module pulls in
+// `@/connect` and (transitively) the Pinia store layout, which can
+// create circular-import issues during test load and isn't relevant
+// to validating uiState behavior.
+const stubQueryHistorySlice = (): QueryHistorySlice => ({
+ queryHistoryByKey: {},
+ fetchQueryHistoryList: vi.fn().mockResolvedValue(undefined),
+ resetPageToken: vi.fn(),
+ mergeLatest: vi.fn().mockResolvedValue(undefined),
+});
+
+const stubTreeSlice = (): TreeSlice => ({
+ treeState: "UNSET",
+ treeNodeKeysById: {},
+ setTreeState: vi.fn(),
+ collectTreeNode: vi.fn(),
+ treeNodeKeysByTarget: vi.fn(() => []),
+});
+
+const stubWebTerminalSlice = (): WebTerminalSlice => ({
+ webTerminalQueryItemsByTabId: {},
+ ensureWebTerminalQueryState: vi.fn(),
+ clearWebTerminalQueryState: vi.fn(),
+ replaceWebTerminalQueryItems: vi.fn(),
+ pushWebTerminalQueryItem: vi.fn(),
+ updateWebTerminalQueryItem: vi.fn(),
+});
+
+const stubWorksheetSaveSlice = (): WorksheetSaveSlice => ({
+ autoSaveController: null,
+ setAutoSaveController: vi.fn(),
+ abortAutoSave: vi.fn(),
+ maybeSwitchProject: vi.fn(async () => undefined),
+ maybeUpdateWorksheet: vi.fn(async () => undefined),
+ createWorksheet: vi.fn(async () => undefined),
+});
+
// Build a fresh store for each test so the slice's `aiPanelSize`
-// initialiser re-reads the (mocked) localStorage and we don't leak state
-// between tests. The slice module is dynamically imported with a query
-// string so Vitest doesn't cache the module-level read of localStorage.
+// initialiser re-reads the (mocked) localStorage and we don't leak
+// state between tests. The slice module is dynamically re-imported
+// with a query string so the module-level localStorage read in
+// `createUIStateSlice` runs again under the mock.
const makeStore = async (): Promise<StoreApi<SQLEditorStoreState>> => {
const mod = (await import(
`./uiState?t=${Date.now()}`
)) as typeof import("./uiState");
return create<SQLEditorStoreState>()((...args) => ({
...mod.createUIStateSlice(...args),
+ ...stubQueryHistorySlice(),
+ ...stubTreeSlice(),
+ ...stubWebTerminalSlice(),
+ ...stubWorksheetSaveSlice(),
}));
};
diff --git a/frontend/src/react/stores/sqlEditor/uiState.ts b/frontend/src/react/stores/sqlEditor/uiState.ts
index 6d3dfbe20b..ce78c8142e 100644
--- a/frontend/src/react/stores/sqlEditor/uiState.ts
+++ b/frontend/src/react/stores/sqlEditor/uiState.ts
@@ -1,9 +1,5 @@
import { STORAGE_KEY_SQL_EDITOR_AI_PANEL_SIZE } from "@/utils/storage-keys";
-import type {
- SQLEditorSliceCreator,
- SQLEditorStoreState,
- UIStateSlice,
-} from "./types";
+import type { SQLEditorSliceCreator, UIStateSlice } from "./types";
const MINIMUM_EDITOR_PANEL_SIZE = 0.5;
const DEFAULT_AI_PANEL_SIZE = 0.3;
@@ -58,7 +54,7 @@ export const createUIStateSlice: SQLEditorSliceCreator<UIStateSlice> = (
});
export const selectEditorPanelSize = (
- state: SQLEditorStoreState
+ state: UIStateSlice
): { size: number; max: number; min: number } => {
if (!state.showAIPanel) {
return { size: 1, max: 1, min: 1 };
diff --git a/frontend/src/store/modules/sqlEditor/webTerminal.ts b/frontend/src/react/stores/sqlEditor/webTerminal-service.ts
similarity index 69%
rename from frontend/src/store/modules/sqlEditor/webTerminal.ts
rename to frontend/src/react/stores/sqlEditor/webTerminal-service.ts
index 80a31538ed..65c0ecb42a 100644
--- a/frontend/src/store/modules/sqlEditor/webTerminal.ts
+++ b/frontend/src/react/stores/sqlEditor/webTerminal-service.ts
@@ -1,26 +1,19 @@
import { create, fromJson, toJson } from "@bufbuild/protobuf";
import { Code, ConnectError } from "@connectrpc/connect";
import Emittery from "emittery";
-import { cloneDeep, uniqueId } from "lodash-es";
-import { defineStore } from "pinia";
+import { cloneDeep } from "lodash-es";
import type { Subscription } from "rxjs";
import { fromEventPattern, Observable } from "rxjs";
-import { markRaw, ref, shallowRef } from "vue";
+import { markRaw, ref } from "vue";
import { useCancelableTimeout } from "@/composables/useCancelableTimeout";
import { refreshTokens } from "@/connect/refreshToken";
-import {
- pushNotification,
- useDatabaseV1Store,
- useSQLEditorQueryHistoryStore,
- useSQLEditorStore,
-} from "@/store";
+import { useSQLEditorVueState } from "@/react/stores/sqlEditor/editor-vue-state";
+import { pushNotification, useDatabaseV1Store } from "@/store";
import type {
SQLEditorQueryParams,
SQLEditorTab,
SQLResultSetV1,
StreamingQueryController,
- WebTerminalQueryItemV1,
- WebTerminalQueryState,
} from "@/types";
import type {
AdminExecuteRequest,
@@ -38,56 +31,48 @@ import {
getErrorCode as extractGrpcStatusCode,
} from "@/utils/connect";
import { sqlEditorEvents } from "@/views/sql-editor/events";
+import { useSQLEditorStore as useSQLEditorReactStore } from "./index";
const ENDPOINT = "/v1:adminExecute";
const SIG_ABORT = 3000 + Code.Aborted;
const QUERY_TIMEOUT_MS = 5000;
-const MAX_QUERY_ITEM_COUNT = 20;
-
-export const useWebTerminalStore = defineStore("webTerminal", () => {
- const map = shallowRef(new Map<string, WebTerminalQueryState>());
-
- const getQueryStateByTab = (tab: SQLEditorTab) => {
- const existed = map.value.get(tab.id);
- if (existed) return existed;
-
- const qs = createQueryState(tab);
- map.value.set(tab.id, qs);
- useQueryStateLogic(qs);
- return qs;
- };
- const clearQueryStateByTab = (id: string) => {
- map.value.delete(id);
- };
-
- return { getQueryStateByTab, clearQueryStateByTab };
-});
-
-const createQueryState = (tab: SQLEditorTab): WebTerminalQueryState => {
- return {
+/**
+ * Per-tab admin-mode streaming session. The `tab` + `timer` + `controller`
+ * fields are framework-agnostic mutable services (Emittery / RxJS /
+ * `useCancelableTimeout`); the query items themselves live in the zustand
+ * `webTerminalQueryItemsByTabId` slice so React consumers re-render via
+ * selectors instead of `useVueState` on a Vue ref.
+ */
+export interface WebTerminalQuerySession {
+ tab: SQLEditorTab;
+ timer: ReturnType<typeof useCancelableTimeout>;
+ controller: StreamingQueryController;
+}
+
+const sessions = new Map<string, WebTerminalQuerySession>();
+
+export const getWebTerminalQuerySession = (
+ tab: SQLEditorTab
+): WebTerminalQuerySession => {
+ const existed = sessions.get(tab.id);
+ if (existed) return existed;
+ const session: WebTerminalQuerySession = {
tab,
- queryItemList: ref([createInitialQueryItemByTab(tab)]),
timer: markRaw(useCancelableTimeout(QUERY_TIMEOUT_MS)),
controller: createStreamingQueryController(),
};
+ sessions.set(tab.id, session);
+ useSQLEditorReactStore.getState().ensureWebTerminalQueryState(tab.id);
+ bindStreamingLogic(session);
+ return session;
};
-const createInitialQueryItemByTab = (
- _tab: SQLEditorTab
-): WebTerminalQueryItemV1 => {
- return createQueryItemV1("");
+export const disposeWebTerminalQuerySession = (tabId: string): void => {
+ sessions.delete(tabId);
+ useSQLEditorReactStore.getState().clearWebTerminalQueryState(tabId);
};
-export const createQueryItemV1 = (
- statement = "",
- status: WebTerminalQueryItemV1["status"] = "IDLE"
-): WebTerminalQueryItemV1 => ({
- id: uniqueId(),
- statement,
- status,
-});
-
const createStreamingQueryController = () => {
const status: StreamingQueryController["status"] = ref("DISCONNECTED");
const events: StreamingQueryController["events"] = markRaw(new Emittery());
@@ -231,36 +216,41 @@ const createStreamingQueryController = () => {
return controller;
};
-const useQueryStateLogic = (qs: WebTerminalQueryState) => {
- const activeQuery = () => {
- return qs.queryItemList.value[qs.queryItemList.value.length - 1];
- };
+const bindStreamingLogic = (session: WebTerminalQuerySession) => {
+ const tabId = session.tab.id;
- const pushQueryItem = () => {
- const list = qs.queryItemList.value;
- list.push(createQueryItemV1());
-
- if (list.length > MAX_QUERY_ITEM_COUNT) {
- list.shift();
- }
- };
-
- const cleanup = () => {
- activeQuery().status = "FINISHED";
- qs.timer.stop();
-
- pushQueryItem();
+ const activeItem = () => {
+ const list =
+ useSQLEditorReactStore.getState().webTerminalQueryItemsByTabId[tabId] ??
+ [];
+ return list[list.length - 1];
};
- qs.controller.events.on("query", (input) => {
- qs.timer.start();
- activeQuery().params = cloneDeep(input);
- activeQuery().status = "RUNNING";
+ session.controller.events.on("query", (input) => {
+ session.timer.start();
+ const tail = activeItem();
+ if (!tail) return;
+ useSQLEditorReactStore
+ .getState()
+ .updateWebTerminalQueryItem(tabId, tail.id, {
+ params: cloneDeep(input),
+ status: "RUNNING",
+ });
});
- qs.controller.events.on("result", (resultSet) => {
+ session.controller.events.on("result", (resultSet) => {
+ // The tab may have been closed mid-flight; disposeWebTerminalQuerySession
+ // dropped our session entry, but the WebSocket is still bound and this
+ // handler is still subscribed. Bail before pushing a new query item,
+ // which would resurrect store state for a tab that no longer exists.
+ if (!sessions.has(tabId)) return;
console.debug("event resultSet", resultSet);
- activeQuery().resultSet = resultSet;
+ const tail = activeItem();
+ if (tail) {
+ useSQLEditorReactStore
+ .getState()
+ .updateWebTerminalQueryItem(tabId, tail.id, { resultSet });
+ }
for (const result of resultSet.results) {
for (const message of result.messages) {
pushNotification({
@@ -271,14 +261,15 @@ const useQueryStateLogic = (qs: WebTerminalQueryState) => {
});
}
}
- // Admin-mode queries don't go through `useExecuteSQL`, so mirror
- // its post-exec history refresh here. `mergeLatest` prepends the
+ // Admin-mode queries don't go through `useExecuteSQL`, so mirror its
+ // post-exec history refresh here. `mergeLatest` prepends the
// just-run statement without resetting the user's pagination.
- const database = activeQuery().params?.connection.database;
+ const database = tail?.params?.connection.database;
if (database) {
- useSQLEditorQueryHistoryStore()
+ useSQLEditorReactStore
+ .getState()
.mergeLatest({
- project: useSQLEditorStore().project,
+ project: useSQLEditorVueState().project,
database,
})
.catch(() => {
@@ -290,7 +281,17 @@ const useQueryStateLogic = (qs: WebTerminalQueryState) => {
} else {
void sqlEditorEvents.emit("query-executed");
}
- cleanup();
+ // Finish the current item and append a fresh one for the next prompt.
+ const finishedTail = activeItem();
+ if (finishedTail) {
+ useSQLEditorReactStore
+ .getState()
+ .updateWebTerminalQueryItem(tabId, finishedTail.id, {
+ status: "FINISHED",
+ });
+ }
+ session.timer.stop();
+ useSQLEditorReactStore.getState().pushWebTerminalQueryItem(tabId);
});
};
diff --git a/frontend/src/react/stores/sqlEditor/webTerminal.ts b/frontend/src/react/stores/sqlEditor/webTerminal.ts
new file mode 100644
index 0000000000..b3a977c1a9
--- /dev/null
+++ b/frontend/src/react/stores/sqlEditor/webTerminal.ts
@@ -0,0 +1,84 @@
+import type { WebTerminalQueryItemV1 } from "@/types";
+import type { SQLEditorSliceCreator, WebTerminalSlice } from "./types";
+
+const MAX_QUERY_ITEM_COUNT = 20;
+
+let nextItemId = 0;
+const generateItemId = () => `wt-${++nextItemId}`;
+
+export const createWebTerminalQueryItemV1 = (
+ statement = "",
+ status: WebTerminalQueryItemV1["status"] = "IDLE"
+): WebTerminalQueryItemV1 => ({
+ id: generateItemId(),
+ statement,
+ status,
+});
+
+const EMPTY_ITEMS: WebTerminalQueryItemV1[] = [];
+
+export const createWebTerminalSlice: SQLEditorSliceCreator<WebTerminalSlice> = (
+ set,
+ get
+) => ({
+ webTerminalQueryItemsByTabId: {},
+
+ ensureWebTerminalQueryState: (tabId) => {
+ if (get().webTerminalQueryItemsByTabId[tabId]) return;
+ set((s) => ({
+ webTerminalQueryItemsByTabId: {
+ ...s.webTerminalQueryItemsByTabId,
+ [tabId]: [createWebTerminalQueryItemV1()],
+ },
+ }));
+ },
+
+ clearWebTerminalQueryState: (tabId) => {
+ set((s) => {
+ if (!(tabId in s.webTerminalQueryItemsByTabId)) return s;
+ const next = { ...s.webTerminalQueryItemsByTabId };
+ delete next[tabId];
+ return { webTerminalQueryItemsByTabId: next };
+ });
+ },
+
+ replaceWebTerminalQueryItems: (tabId, items) => {
+ set((s) => ({
+ webTerminalQueryItemsByTabId: {
+ ...s.webTerminalQueryItemsByTabId,
+ [tabId]: items,
+ },
+ }));
+ },
+
+ pushWebTerminalQueryItem: (tabId) => {
+ set((s) => {
+ const prev = s.webTerminalQueryItemsByTabId[tabId] ?? EMPTY_ITEMS;
+ const next = [...prev, createWebTerminalQueryItemV1()];
+ // Trim oldest items above the per-tab cap so memory stays bounded.
+ while (next.length > MAX_QUERY_ITEM_COUNT) next.shift();
+ return {
+ webTerminalQueryItemsByTabId: {
+ ...s.webTerminalQueryItemsByTabId,
+ [tabId]: next,
+ },
+ };
+ });
+ },
+
+ updateWebTerminalQueryItem: (tabId, itemId, patch) => {
+ set((s) => {
+ const prev = s.webTerminalQueryItemsByTabId[tabId];
+ if (!prev) return s;
+ const next = prev.map((item) =>
+ item.id === itemId ? { ...item, ...patch } : item
+ );
+ return {
+ webTerminalQueryItemsByTabId: {
+ ...s.webTerminalQueryItemsByTabId,
+ [tabId]: next,
+ },
+ };
+ });
+ },
+});
diff --git a/frontend/src/react/stores/sqlEditor/worksheet.test.ts b/frontend/src/react/stores/sqlEditor/worksheet.test.ts
new file mode 100644
index 0000000000..9d487d1643
--- /dev/null
+++ b/frontend/src/react/stores/sqlEditor/worksheet.test.ts
@@ -0,0 +1,176 @@
+import { beforeEach, describe, expect, test, vi } from "vitest";
+import { create, type StoreApi } from "zustand";
+import type {
+ QueryHistorySlice,
+ SQLEditorStoreState,
+ TreeSlice,
+ UIStateSlice,
+ WebTerminalSlice,
+} from "./types";
+import { createWorksheetSaveSlice } from "./worksheet";
+
+// Stub all the other slices so the composed store satisfies
+// `SQLEditorStoreState` without dragging in real implementations
+// (the worksheet slice itself dynamic-imports the Pinia stores it
+// needs, so we only have to mock those via vi.mock below).
+const stubUIStateSlice = (): UIStateSlice => ({
+ asidePanelTab: "WORKSHEET",
+ showConnectionPanel: false,
+ showAIPanel: false,
+ pendingInsertAtCaret: undefined,
+ highlightAccessGrantName: undefined,
+ isShowingCode: false,
+ aiPanelSize: 0.3,
+ setAsidePanelTab: vi.fn(),
+ setShowConnectionPanel: vi.fn(),
+ setShowAIPanel: vi.fn(),
+ setPendingInsertAtCaret: vi.fn(),
+ setHighlightAccessGrantName: vi.fn(),
+ setIsShowingCode: vi.fn(),
+ handleEditorPanelResize: vi.fn(),
+});
+
+const stubQueryHistorySlice = (): QueryHistorySlice => ({
+ queryHistoryByKey: {},
+ fetchQueryHistoryList: vi.fn(async () => undefined as never),
+ resetPageToken: vi.fn(),
+ mergeLatest: vi.fn(async () => undefined as never),
+});
+
+const stubTreeSlice = (): TreeSlice => ({
+ treeState: "UNSET",
+ treeNodeKeysById: {},
+ setTreeState: vi.fn(),
+ collectTreeNode: vi.fn(),
+ treeNodeKeysByTarget: vi.fn(() => []),
+});
+
+const stubWebTerminalSlice = (): WebTerminalSlice => ({
+ webTerminalQueryItemsByTabId: {},
+ ensureWebTerminalQueryState: vi.fn(),
+ clearWebTerminalQueryState: vi.fn(),
+ replaceWebTerminalQueryItems: vi.fn(),
+ pushWebTerminalQueryItem: vi.fn(),
+ updateWebTerminalQueryItem: vi.fn(),
+});
+
+const piniaMocks = vi.hoisted(() => ({
+ editorStore: {
+ project: "projects/default",
+ projectContextReady: true,
+ setProject: vi.fn(),
+ },
+ projectStore: {
+ getOrFetchProjectByName: vi.fn(),
+ },
+ projectIamPolicyStore: {
+ getOrFetchProjectIamPolicy: vi.fn(),
+ },
+ tabStore: {
+ updateTab: vi.fn(),
+ },
+ worksheetStore: {
+ getWorksheetByName: vi.fn(),
+ patchWorksheet: vi.fn(),
+ upsertWorksheetOrganizer: vi.fn(),
+ createWorksheet: vi.fn(),
+ },
+}));
+
+vi.mock("@/store", () => ({
+ useProjectV1Store: () => piniaMocks.projectStore,
+ useWorkSheetStore: () => piniaMocks.worksheetStore,
+}));
+
+vi.mock("@/react/stores/sqlEditor/tab-vue-state", () => ({
+ useSQLEditorTabStore: () => piniaMocks.tabStore,
+}));
+
+vi.mock("./editor-vue-state", () => ({
+ useSQLEditorVueState: () => piniaMocks.editorStore,
+}));
+
+vi.mock("@/store/modules/v1/projectIamPolicy", () => ({
+ useProjectIamPolicyStore: () => piniaMocks.projectIamPolicyStore,
+}));
+
+vi.mock("@/views/sql-editor/events", () => ({
+ sqlEditorEvents: { emit: vi.fn() },
+}));
+
+vi.mock("@/views/sql-editor/Sheet", () => ({
+ openWorksheetByName: vi.fn(),
+}));
+
+vi.mock("@/utils", async (importOriginal) => {
+ const actual = (await importOriginal()) as Record<string, unknown>;
+ return {
+ ...actual,
+ extractWorksheetConnection: vi.fn(
+ async ({ database }: { database: string }) => ({
+ database,
+ instance: "",
+ })
+ ),
+ };
+});
+
+const makeStore = (): StoreApi<SQLEditorStoreState> =>
+ create<SQLEditorStoreState>()((...args) => ({
+ ...stubUIStateSlice(),
+ ...stubQueryHistorySlice(),
+ ...stubTreeSlice(),
+ ...stubWebTerminalSlice(),
+ ...createWorksheetSaveSlice(...args),
+ }));
+
+beforeEach(() => {
+ Object.values(piniaMocks).forEach((store) => {
+ Object.values(store).forEach((v) => {
+ if (typeof v === "function" && "mockReset" in v) {
+ (v as { mockReset: () => void }).mockReset();
+ }
+ });
+ });
+ piniaMocks.editorStore.project = "projects/default";
+ piniaMocks.editorStore.projectContextReady = true;
+});
+
+describe("worksheet save slice — autoSaveController", () => {
+ test("initial value is null", () => {
+ const store = makeStore();
+ expect(store.getState().autoSaveController).toBeNull();
+ });
+
+ test("setAutoSaveController writes the new value", () => {
+ const store = makeStore();
+ const controller = new AbortController();
+ store.getState().setAutoSaveController(controller);
+ expect(store.getState().autoSaveController).toBe(controller);
+ });
+
+ test("abortAutoSave with no controller is a no-op", () => {
+ const store = makeStore();
+ expect(() => store.getState().abortAutoSave()).not.toThrow();
+ expect(store.getState().autoSaveController).toBeNull();
+ });
+
+ test("abortAutoSave with a controller aborts and clears it", () => {
+ const store = makeStore();
+ const controller = new AbortController();
+ const abortSpy = vi.spyOn(controller, "abort");
+ store.getState().setAutoSaveController(controller);
+ store.getState().abortAutoSave();
+ expect(abortSpy).toHaveBeenCalledTimes(1);
+ expect(store.getState().autoSaveController).toBeNull();
+ });
+});
+
+describe("worksheet save slice — maybeSwitchProject", () => {
+ test("with an invalid project name returns undefined without setting project", async () => {
+ const store = makeStore();
+ const result = await store.getState().maybeSwitchProject("not-a-project");
+ expect(result).toBeUndefined();
+ expect(piniaMocks.editorStore.setProject).not.toHaveBeenCalled();
+ });
+});
diff --git a/frontend/src/react/stores/sqlEditor/worksheet.ts b/frontend/src/react/stores/sqlEditor/worksheet.ts
new file mode 100644
index 0000000000..e36fb8c012
--- /dev/null
+++ b/frontend/src/react/stores/sqlEditor/worksheet.ts
@@ -0,0 +1,194 @@
+import { create } from "@bufbuild/protobuf";
+import { isUndefined } from "lodash-es";
+import { nextTick } from "vue";
+import { isValidProjectName } from "@/types";
+import {
+ type Worksheet,
+ Worksheet_Visibility,
+ WorksheetSchema,
+} from "@/types/proto-es/v1/worksheet_service_pb";
+import { extractWorksheetConnection } from "@/utils";
+import { sqlEditorEvents } from "@/views/sql-editor/events";
+import { openWorksheetByName } from "@/views/sql-editor/Sheet";
+import type { SQLEditorSliceCreator, WorksheetSaveSlice } from "./types";
+
+// Avoid static imports of Pinia stores (`useSQLEditorVueState`,
+// `useSQLEditorTabStore`, `useProjectV1Store`, ...) because the Pinia
+// store barrel transitively re-imports `@/react/stores/sqlEditor` —
+// loading them at module evaluation creates a TDZ cycle. The slice
+// pulls them in at call time via the helper below.
+const importStores = () => import("@/store");
+const importProjectIamPolicyStore = () =>
+ import("@/store/modules/v1/projectIamPolicy");
+
+export const createWorksheetSaveSlice: SQLEditorSliceCreator<
+ WorksheetSaveSlice
+> = (set, get) => ({
+ autoSaveController: null,
+
+ setAutoSaveController: (controller) =>
+ set({ autoSaveController: controller }),
+
+ abortAutoSave: () => {
+ const controller = get().autoSaveController;
+ if (controller) {
+ controller.abort();
+ set({ autoSaveController: null });
+ }
+ },
+
+ maybeSwitchProject: async (projectName) => {
+ const { useProjectV1Store } = await importStores();
+ const { useProjectIamPolicyStore } = await importProjectIamPolicyStore();
+ const { useSQLEditorVueState } = await import("./editor-vue-state");
+ const editorStore = useSQLEditorVueState();
+ const projectStore = useProjectV1Store();
+ const projectIamPolicyStore = useProjectIamPolicyStore();
+
+ editorStore.projectContextReady = false;
+ try {
+ if (!isValidProjectName(projectName)) {
+ return;
+ }
+ const project = await projectStore.getOrFetchProjectByName(projectName);
+ // Fetch IAM policy to ensure permission checks work correctly.
+ await projectIamPolicyStore.getOrFetchProjectIamPolicy(project.name);
+ editorStore.setProject(project.name);
+ await sqlEditorEvents.emit("project-context-ready", {
+ project: project.name,
+ });
+ return project.name;
+ } catch {
+ // ignore
+ } finally {
+ editorStore.projectContextReady = true;
+ }
+ },
+
+ maybeUpdateWorksheet: async ({
+ tabId,
+ worksheet,
+ title,
+ database,
+ statement,
+ folders,
+ signal,
+ }) => {
+ const { useWorkSheetStore } = await importStores();
+ const { useSQLEditorTabStore } = await import("./tab-vue-state");
+ const tabStore = useSQLEditorTabStore();
+ const worksheetStore = useWorkSheetStore();
+
+ const connection = await extractWorksheetConnection({ database });
+
+ // `title === undefined` means "don't change the title" — preserves
+ // the current title on auto-save calls that never pass one.
+ // `title === ""` is a real, explicit empty title that should be
+ // persisted (renders as the Untitled placeholder elsewhere).
+ const currentSheet = worksheet
+ ? worksheetStore.getWorksheetByName(worksheet)
+ : undefined;
+ if (worksheet && !currentSheet) {
+ return;
+ }
+ const worksheetTitle = title ?? currentSheet?.title ?? "";
+
+ if (worksheet && currentSheet) {
+ const updated = await worksheetStore.patchWorksheet(
+ {
+ ...currentSheet,
+ title: worksheetTitle,
+ database,
+ content: new TextEncoder().encode(statement),
+ },
+ ["title", "database", "content"],
+ signal
+ );
+ if (!updated) {
+ return;
+ }
+ if (!isUndefined(folders)) {
+ await worksheetStore.upsertWorksheetOrganizer(
+ {
+ worksheet: updated.name,
+ folders: folders,
+ },
+ ["folders"]
+ );
+ }
+ }
+
+ return tabStore.updateTab(tabId, {
+ status: "CLEAN",
+ connection,
+ title: worksheetTitle,
+ worksheet,
+ });
+ },
+
+ createWorksheet: async ({
+ tabId,
+ title,
+ statement = "",
+ folders = [],
+ database = "",
+ }) => {
+ const { useWorkSheetStore } = await importStores();
+ const { useSQLEditorVueState } = await import("./editor-vue-state");
+ const { useSQLEditorTabStore } = await import("./tab-vue-state");
+ const editorStore = useSQLEditorVueState();
+ const tabStore = useSQLEditorTabStore();
+ const worksheetStore = useWorkSheetStore();
+
+ const worksheetTitle = title ?? "";
+ const connection = await extractWorksheetConnection({ database });
+
+ const newWorksheet = await worksheetStore.createWorksheet(
+ create(WorksheetSchema, {
+ title: worksheetTitle,
+ database,
+ content: new TextEncoder().encode(statement),
+ project: editorStore.project,
+ visibility: Worksheet_Visibility.PRIVATE,
+ })
+ );
+
+ if (folders.length > 0) {
+ await worksheetStore.upsertWorksheetOrganizer(
+ {
+ worksheet: newWorksheet.name,
+ folders: folders,
+ },
+ ["folders"]
+ );
+ }
+
+ if (tabId) {
+ return tabStore.updateTab(tabId, {
+ status: "CLEAN",
+ title: worksheetTitle,
+ statement,
+ connection,
+ worksheet: newWorksheet.name,
+ });
+ }
+
+ const tab = await openWorksheetByName({
+ worksheet: newWorksheet.name,
+ forceNewTab: true,
+ });
+ nextTick(() => {
+ if (tab && !tab.connection?.database) {
+ // The zustand store itself owns the UI-state slice, so we can
+ // call the action directly through `get()` (avoids the
+ // dynamic-import dance we use for cross-store calls).
+ get().setShowConnectionPanel(true);
+ }
+ });
+ return tab;
+ },
+});
+
+// Re-export the Worksheet proto type so callers don't have to plumb the
+// proto path themselves.
+export type { Worksheet };
diff --git a/frontend/src/store/modules/index.ts b/frontend/src/store/modules/index.ts
index dd9b58dd9c..46c8ca2dd3 100644
--- a/frontend/src/store/modules/index.ts
+++ b/frontend/src/store/modules/index.ts
@@ -2,7 +2,6 @@ export * from "./accessGrant";
export * from "./v1/auth";
export * from "./notification";
export * from "./router";
-export * from "./sqlEditor";
export * from "./uistate";
export * from "./sqlReview";
export * from "./idp";
diff --git a/frontend/src/store/modules/sqlEditor/index.ts b/frontend/src/store/modules/sqlEditor/index.ts
deleted file mode 100644
index 790c0ad1b5..0000000000
--- a/frontend/src/store/modules/sqlEditor/index.ts
+++ /dev/null
@@ -1,7 +0,0 @@
-export * from "./editor";
-export * from "./tab";
-export * from "./tree";
-export * from "./queryHistory";
-export * from "./webTerminal";
-export * from "./folder";
-export * from "./worksheet";
diff --git a/frontend/src/store/modules/sqlEditor/queryHistory.ts b/frontend/src/store/modules/sqlEditor/queryHistory.ts
deleted file mode 100644
index 8a12a0d7cd..0000000000
--- a/frontend/src/store/modules/sqlEditor/queryHistory.ts
+++ /dev/null
@@ -1,137 +0,0 @@
-import { create } from "@bufbuild/protobuf";
-import { defineStore } from "pinia";
-import { reactive } from "vue";
-import { sqlServiceClientConnect } from "@/connect";
-import { isValidDatabaseName, isValidProjectName } from "@/types";
-import type { QueryHistory } from "@/types/proto-es/v1/sql_service_pb";
-import { SearchQueryHistoriesRequestSchema } from "@/types/proto-es/v1/sql_service_pb";
-
-export interface QueryHistoryFilter {
- statement?: string;
- project?: string;
- database?: string;
-}
-
-const getListQueryHistoryFilter = (filter: QueryHistoryFilter) => {
- const params = [`type == "QUERY"`];
- if (isValidProjectName(filter.project)) {
- params.push(`project == "${filter.project}"`);
- }
- if (isValidDatabaseName(filter.database)) {
- params.push(`database == "${filter.database}"`);
- }
- if (filter.statement) {
- params.push(`statement.contains("${filter.statement}")`);
- }
- return params.join(" && ");
-};
-
-const getCacheKey = (filter: QueryHistoryFilter) => {
- const params = [];
- if (isValidProjectName(filter.project)) {
- params.push(filter.project);
- }
- if (isValidDatabaseName(filter.database)) {
- params.push(filter.database);
- }
- return params.join(".");
-};
-
-export const useSQLEditorQueryHistoryStore = defineStore(
- "sqlEditorQueryHistory",
- () => {
- const queryHistoryMap = reactive(
- new Map<
- string,
- { nextPageToken?: string; queryHistories: QueryHistory[] }
- >()
- );
-
- const fetchQueryHistoryList = async (
- filter: QueryHistoryFilter
- ): Promise<{
- queryHistories: QueryHistory[];
- nextPageToken?: string;
- }> => {
- const key = getCacheKey(filter);
- if (!queryHistoryMap.has(key)) {
- queryHistoryMap.set(key, { queryHistories: [] });
- }
- const pageToken = queryHistoryMap.get(key)?.nextPageToken;
-
- const request = create(SearchQueryHistoriesRequestSchema, {
- pageSize: 5,
- pageToken,
- filter: getListQueryHistoryFilter(filter),
- });
- const resp = await sqlServiceClientConnect.searchQueryHistories(request);
-
- queryHistoryMap.get(key)!.nextPageToken = resp.nextPageToken;
- if (pageToken) {
- // Dedupe by `name` on the append path. The backend uses
- // offset-based page tokens, so when `mergeLatest` prepends a
- // freshly-executed query the cached cursor is now off by one
- // (the new entry shifted every server position). The next
- // "Load more" call may return rows that already live in the
- // cache; filtering by `name` prevents visible duplicates.
- const cachedNames = new Set(
- queryHistoryMap.get(key)!.queryHistories.map((h) => h.name)
- );
- const fresh = resp.queryHistories.filter(
- (h) => !cachedNames.has(h.name)
- );
- queryHistoryMap.get(key)!.queryHistories.push(...fresh);
- } else {
- queryHistoryMap.get(key)!.queryHistories = resp.queryHistories;
- }
- return resp;
- };
-
- const getQueryHistoryList = (filter: QueryHistoryFilter) => {
- const key = getCacheKey(filter);
- return queryHistoryMap.get(key) ?? { queryHistories: [] };
- };
-
- const resetPageToken = (filter: QueryHistoryFilter) => {
- const key = getCacheKey(filter);
- queryHistoryMap.set(key, { queryHistories: [] });
- };
-
- /**
- * Post-execute refresh that preserves pagination state. Fetches
- * page 1 (no cursor) and prepends entries whose `name` isn't
- * already cached. Keeps the existing `nextPageToken`, so a user
- * who has loaded pages 1–3 stays at pages 1–3 after running a new
- * query — the just-executed statement appears at the top without
- * resetting the list.
- */
- const mergeLatest = async (filter: QueryHistoryFilter) => {
- const key = getCacheKey(filter);
- const resp = await sqlServiceClientConnect.searchQueryHistories(
- create(SearchQueryHistoriesRequestSchema, {
- pageSize: 5,
- filter: getListQueryHistoryFilter(filter),
- })
- );
- const existing = queryHistoryMap.get(key);
- const existingNames = new Set(
- (existing?.queryHistories ?? []).map((h) => h.name)
- );
- const fresh = resp.queryHistories.filter(
- (h) => !existingNames.has(h.name)
- );
- queryHistoryMap.set(key, {
- nextPageToken: existing?.nextPageToken ?? resp.nextPageToken,
- queryHistories: [...fresh, ...(existing?.queryHistories ?? [])],
- });
- return resp;
- };
-
- return {
- resetPageToken,
- fetchQueryHistoryList,
- getQueryHistoryList,
- mergeLatest,
- };
- }
-);
diff --git a/frontend/src/store/modules/sqlEditor/worksheet.test.ts b/frontend/src/store/modules/sqlEditor/worksheet.test.ts
deleted file mode 100644
index c5b683c902..0000000000
--- a/frontend/src/store/modules/sqlEditor/worksheet.test.ts
+++ /dev/null
@@ -1,136 +0,0 @@
-import { createPinia, setActivePinia } from "pinia";
-import { beforeEach, describe, expect, test, vi } from "vitest";
-
-// Mock @/store to stub sub-stores (mirrors uiState.test.ts pattern)
-vi.mock("@/store", async () => {
- const { ref } = await import("vue");
- return {
- pushNotification: vi.fn(),
- useCurrentUserV1: vi.fn(() => ({
- value: { email: "[email protected]" },
- })),
- useProjectIamPolicyStore: vi.fn(() => ({
- getOrFetchProjectIamPolicy: vi.fn(),
- })),
- useProjectV1Store: vi.fn(() => ({
- getOrFetchProjectByName: vi.fn(),
- })),
- useSQLEditorStore: vi.fn(() => ({
- project: ref("projects/default"),
- projectContextReady: true,
- setProject: vi.fn(),
- })),
- useSQLEditorTabStore: vi.fn(() => ({
- updateTab: vi.fn(),
- getTabById: vi.fn(),
- currentTab: undefined,
- openTabList: [],
- })),
- useSQLEditorUIStore: vi.fn(() => ({
- showConnectionPanel: ref(false),
- })),
- useWorkSheetStore: vi.fn(() => ({
- getWorksheetByName: vi.fn(),
- patchWorksheet: vi.fn(),
- upsertWorksheetOrganizer: vi.fn(),
- batchUpsertWorksheetOrganizers: vi.fn(),
- createWorksheet: vi.fn(),
- fetchWorksheetList: vi.fn(),
- myWorksheetList: [],
- sharedWorksheetList: [],
- })),
- };
-});
-
-// Mock @/utils completely to avoid native binary dependencies
-vi.mock("@/utils", async () => {
- const { ref } = await import("vue");
- return {
- extractWorksheetConnection: vi.fn(
- async ({ database }: { database: string }) => ({
- database,
- instance: "",
- })
- ),
- isWorksheetWritableV1: vi.fn(() => true),
- isValidProjectName: vi.fn((name: string) => name.startsWith("projects/")),
- storageKeySqlEditorWorksheetFilter: vi.fn(() => "filter-key"),
- storageKeySqlEditorWorksheetTree: vi.fn(() => "tree-key"),
- storageKeySqlEditorWorksheetFolder: vi.fn(() => "folder-key"),
- useDynamicLocalStorage: vi.fn((_: unknown, defaultValue: unknown) =>
- ref(defaultValue)
- ),
- };
-});
-
-// Mock @/types to avoid importing native modules transitively
-vi.mock("@/types", () => ({
- isValidProjectName: vi.fn((name: string) => name.startsWith("projects/")),
- DEBOUNCE_SEARCH_DELAY: 300,
-}));
-
-// Mock @/views/sql-editor/Sheet
-vi.mock("@/views/sql-editor/Sheet", () => ({
- openWorksheetByName: vi.fn(),
-}));
-
-// Mock @/views/sql-editor/events
-vi.mock("@/views/sql-editor/events", () => ({
- sqlEditorEvents: {
- emit: vi.fn(),
- },
-}));
-
-// Mock protobuf and worksheet_service_pb
-vi.mock("@bufbuild/protobuf", () => ({
- create: vi.fn(),
-}));
-
-vi.mock("@/types/proto-es/v1/worksheet_service_pb", () => ({
- Worksheet_Visibility: { PRIVATE: 0 },
- WorksheetSchema: {},
-}));
-
-let useSQLEditorWorksheetStore: typeof import("./worksheet").useSQLEditorWorksheetStore;
-
-beforeEach(async () => {
- vi.clearAllMocks();
- setActivePinia(createPinia());
- ({ useSQLEditorWorksheetStore } = await import("./worksheet"));
-});
-
-describe("useSQLEditorWorksheetStore", () => {
- test("store initializes with autoSaveController === null", () => {
- const store = useSQLEditorWorksheetStore();
- expect(store.autoSaveController).toBeNull();
- });
-
- test("abortAutoSave() with no controller is a no-op (doesn't throw)", () => {
- const store = useSQLEditorWorksheetStore();
- expect(() => store.abortAutoSave()).not.toThrow();
- expect(store.autoSaveController).toBeNull();
- });
-
- test("abortAutoSave() with a controller calls abort and clears it", () => {
- const store = useSQLEditorWorksheetStore();
- const controller = new AbortController();
- const abortSpy = vi.spyOn(controller, "abort");
- store.autoSaveController = controller;
-
- store.abortAutoSave();
-
- expect(abortSpy).toHaveBeenCalledTimes(1);
- expect(store.autoSaveController).toBeNull();
- });
-
- test("maybeSwitchProject with an invalid project name returns undefined without setting project", async () => {
- const store = useSQLEditorWorksheetStore();
- const { useSQLEditorStore } = await import("@/store");
- const editorStore = useSQLEditorStore();
-
- const result = await store.maybeSwitchProject("not-a-valid-project-name");
-
- expect(result).toBeUndefined();
- expect(editorStore.setProject).not.toHaveBeenCalled();
- });
-});
diff --git a/frontend/src/store/modules/sqlEditor/worksheet.ts b/frontend/src/store/modules/sqlEditor/worksheet.ts
deleted file mode 100644
index af3aac2e3e..0000000000
--- a/frontend/src/store/modules/sqlEditor/worksheet.ts
+++ /dev/null
@@ -1,673 +0,0 @@
-import { create } from "@bufbuild/protobuf";
-import { useDebounceFn } from "@vueuse/core";
-import Emittery from "emittery";
-import { isEqual, isUndefined, orderBy } from "lodash-es";
-import { defineStore, storeToRefs } from "pinia";
-import scrollIntoView from "scroll-into-view-if-needed";
-import type { Ref } from "vue";
-import { computed, nextTick, ref, watch } from "vue";
-import { t } from "@/plugins/i18n";
-import { useSQLEditorStore as useSQLEditorReactStore } from "@/react/stores/sqlEditor";
-import {
- useCurrentUserV1,
- useProjectIamPolicyStore,
- useProjectV1Store,
- useSQLEditorStore,
- useSQLEditorTabStore,
- useWorkSheetStore,
-} from "@/store";
-import type { SQLEditorTab } from "@/types";
-import { DEBOUNCE_SEARCH_DELAY, isValidProjectName } from "@/types";
-import {
- type Worksheet,
- Worksheet_Visibility,
- WorksheetSchema,
-} from "@/types/proto-es/v1/worksheet_service_pb";
-import {
- extractWorksheetConnection,
- storageKeySqlEditorWorksheetFilter,
- storageKeySqlEditorWorksheetTree,
- useDynamicLocalStorage,
-} from "@/utils";
-import { sqlEditorEvents } from "@/views/sql-editor/events";
-import { openWorksheetByName } from "@/views/sql-editor/Sheet";
-import type { SheetViewMode } from "@/views/sql-editor/Sheet/types";
-import { buildFolderContext } from "./folder";
-
-export type { FolderContext } from "./folder";
-
-// ---- types ------------------------------------------------------------------
-
-type SheetTreeEvents = Emittery<{
- "on-built": { viewMode: SheetViewMode };
-}>;
-
-export interface WorksheetLikeItem {
- name: string;
- title: string;
- folders: string[];
- type: "worksheet" | "draft";
-}
-
-export interface WorksheetFolderNode {
- key: string;
- label: string;
- editable: boolean;
- isLeaf?: boolean;
- empty?: boolean;
- worksheet?: WorksheetLikeItem;
- children: WorksheetFolderNode[];
- [key: string]: unknown;
-}
-
-export interface WorksheetFilter {
- keyword: string;
- onlyShowStarred: boolean;
- showMine: boolean;
- showShared: boolean;
- showDraft: boolean;
-}
-
-// ---- per-view tree context --------------------------------------------------
-
-const convertToWorksheetLikeItem = (
- worksheet: Worksheet
-): WorksheetLikeItem => ({
- name: worksheet.name,
- title: worksheet.title,
- folders: worksheet.folders,
- type: "worksheet",
-});
-
-const buildViewContext = (
- viewMode: SheetViewMode,
- filterRef: Ref<WorksheetFilter>
-) => {
- const sheetStore = useWorkSheetStore();
- const folderContext = buildFolderContext(viewMode);
- const me = useCurrentUserV1();
- const events: SheetTreeEvents = new Emittery();
- const tabStore = useSQLEditorTabStore();
- const { project } = storeToRefs(useSQLEditorStore());
-
- const isInitialized = ref(false);
- const isLoading = ref(false);
-
- const rootNodeLabel = computed(() => {
- switch (viewMode) {
- case "my":
- return t("sheet.mine");
- case "shared":
- return t("sheet.shared");
- case "draft":
- return t("common.draft");
- default:
- return "";
- }
- });
-
- const getRootTreeNode = (): WorksheetFolderNode => ({
- isLeaf: false,
- children: [],
- key: folderContext.rootPath.value,
- label: rootNodeLabel.value,
- editable: false,
- });
-
- const sheetTree = ref<WorksheetFolderNode>(getRootTreeNode());
-
- const worksheetList = computed((): Worksheet[] => {
- let list: Worksheet[] = [];
- switch (viewMode) {
- case "my":
- list = sheetStore.myWorksheetList;
- break;
- case "shared":
- list = sheetStore.sharedWorksheetList;
- break;
- default:
- break;
- }
- list = list.filter((sheet) => sheet.project === project.value);
- if (filterRef.value.onlyShowStarred) {
- return list.filter((sheet) => sheet.starred);
- }
- return list;
- });
-
- const sheetLikeItemList = computed((): WorksheetLikeItem[] => {
- switch (viewMode) {
- case "my":
- case "shared":
- return worksheetList.value.map(convertToWorksheetLikeItem);
- case "draft":
- return tabStore.openTabList
- .filter((tab) => !tab.worksheet)
- .map((tab) => ({
- name: tab.id,
- title: tab.title,
- folders: [],
- type: "draft" as const,
- }));
- default:
- return [];
- }
- });
-
- const getPathesForWorksheet = (worksheet: {
- folders: string[];
- }): string[] => {
- const pathes = [folderContext.rootPath.value];
- let currentPath = folderContext.rootPath.value;
- for (const folder of worksheet.folders) {
- currentPath = folderContext.ensureFolderPath(`${currentPath}/${folder}`);
- pathes.push(currentPath);
- }
- return pathes;
- };
-
- const getPwdForWorksheet = (worksheet: { folders: string[] }): string => {
- return folderContext.ensureFolderPath(worksheet.folders.join("/"));
- };
-
- const getKeyForWorksheet = (worksheet: WorksheetLikeItem): string => {
- return [
- getPwdForWorksheet(worksheet),
- `bytebase-${worksheet.type}-${worksheet.name.split("/").slice(-1)[0]}.sql`,
- ].join("/");
- };
-
- const getFoldersForWorksheet = (path: string): string[] => {
- const pathes = path.replace(folderContext.rootPath.value, "").split("/");
- if (pathes.slice(-1)[0].endsWith(".sql")) {
- pathes.pop();
- }
- return pathes.map((p) => p.trim()).filter((p) => p);
- };
-
- const buildTree = (
- parent: WorksheetFolderNode,
- worksheetsByFolder: Map<string, WorksheetLikeItem[]>,
- hideEmpty: boolean
- ) => {
- const subfolders = folderContext
- .listSubFolders(parent.key)
- .map((folder) => ({
- isLeaf: false,
- children: [],
- key: folder,
- label: folder.split("/").slice(-1)[0],
- editable: true,
- }));
-
- let empty = true;
- for (const childNode of subfolders) {
- const subtree = buildTree(childNode, worksheetsByFolder, hideEmpty);
- if (!subtree.empty || !hideEmpty) {
- parent.children.push(subtree);
- }
- if (!subtree.empty) {
- empty = false;
- }
- }
-
- const sheets = orderBy(
- worksheetsByFolder.get(parent.key) || [],
- (item) => item.title
- ).map((worksheet) => ({
- isLeaf: true,
- key: getKeyForWorksheet(worksheet),
- label: worksheet.title,
- worksheet,
- editable: true,
- children: [],
- }));
-
- parent.children.push(...sheets);
- parent.empty = sheets.length === 0 && empty;
- if (parent.key !== folderContext.rootPath.value) {
- parent.isLeaf = parent.children.length === 0;
- }
-
- return parent;
- };
-
- const folderTree = computed(() =>
- buildTree(getRootTreeNode(), new Map(), false)
- );
-
- const rebuildTree = useDebounceFn(() => {
- const folderPaths = new Set<string>([]);
- const worksheetsByFolder = new Map<string, WorksheetLikeItem[]>();
-
- for (const worksheet of sheetLikeItemList.value) {
- for (const path of getPathesForWorksheet(worksheet)) {
- folderPaths.add(path);
- }
- const pwd = getPwdForWorksheet(worksheet);
- if (!worksheetsByFolder.has(pwd)) {
- worksheetsByFolder.set(pwd, []);
- }
- worksheetsByFolder.get(pwd)!.push(worksheet);
- }
-
- folderContext.mergeFolders(folderPaths);
- sheetTree.value = buildTree(
- getRootTreeNode(),
- worksheetsByFolder,
- filterRef.value.onlyShowStarred
- );
- events.emit("on-built", { viewMode });
- }, DEBOUNCE_SEARCH_DELAY);
-
- watch(
- [() => folderContext.folders.value, () => sheetLikeItemList.value],
- ([newFolders, newSheetList], [oldFolders, oldSheetList]) => {
- if (
- isEqual(newFolders, oldFolders) &&
- isEqual(newSheetList, oldSheetList)
- ) {
- return;
- }
- rebuildTree();
- }
- );
-
- const fetchSheetList = async () => {
- isLoading.value = true;
- try {
- switch (viewMode) {
- case "my":
- await sheetStore.fetchWorksheetList(
- project.value,
- `creator == "users/${me.value.email}"`
- );
- break;
- case "shared":
- await sheetStore.fetchWorksheetList(
- project.value,
- [
- `creator != "users/${me.value.email}"`,
- `visibility in ["${Worksheet_Visibility[Worksheet_Visibility.PROJECT_READ]}","${Worksheet_Visibility[Worksheet_Visibility.PROJECT_WRITE]}"]`,
- ].join(" && ")
- );
- break;
- default:
- break;
- }
- rebuildTree();
- isInitialized.value = true;
- } finally {
- isLoading.value = false;
- }
- };
-
- return {
- events,
- isInitialized,
- isLoading,
- sheetTree,
- folderTree,
- fetchSheetList,
- folderContext,
- getKeyForWorksheet,
- getFoldersForWorksheet,
- getPathesForWorksheet,
- getPwdForWorksheet,
- };
-};
-
-export type ViewContext = ReturnType<typeof buildViewContext>;
-
-// ---- constants --------------------------------------------------------------
-
-const INITIAL_FILTER: WorksheetFilter = {
- keyword: "",
- showShared: true,
- showMine: true,
- showDraft: true,
- onlyShowStarred: false,
-};
-
-// ---- Pinia store ------------------------------------------------------------
-
-export const useSQLEditorWorksheetStore = defineStore(
- "sqlEditorWorksheet",
- () => {
- const editorStore = useSQLEditorStore();
- const tabStore = useSQLEditorTabStore();
- const projectStore = useProjectV1Store();
- const projectIamPolicyStore = useProjectIamPolicyStore();
- const worksheetStore = useWorkSheetStore();
- const me = useCurrentUserV1();
- const worksheetV1Store = useWorkSheetStore();
- const { project } = storeToRefs(useSQLEditorStore());
-
- // ---- save-flow actions --------------------------------------------------
-
- const autoSaveController = ref<AbortController | null>(null);
-
- const abortAutoSave = () => {
- if (autoSaveController.value) {
- autoSaveController.value.abort();
- autoSaveController.value = null;
- }
- };
-
- const maybeSwitchProject = async (
- projectName: string
- ): Promise<string | undefined> => {
- editorStore.projectContextReady = false;
- try {
- if (!isValidProjectName(projectName)) {
- return;
- }
- const project = await projectStore.getOrFetchProjectByName(projectName);
- // Fetch IAM policy to ensure permission checks work correctly
- await projectIamPolicyStore.getOrFetchProjectIamPolicy(project.name);
- editorStore.setProject(project.name);
- await sqlEditorEvents.emit("project-context-ready", {
- project: project.name,
- });
- return project.name;
- } catch {
- // Nothing
- } finally {
- editorStore.projectContextReady = true;
- }
- };
-
- const maybeUpdateWorksheet = async ({
- tabId,
- worksheet,
- title,
- database,
- statement,
- folders,
- signal,
- }: {
- tabId: string;
- worksheet?: string;
- title?: string;
- database: string;
- statement: string;
- folders?: string[];
- signal?: AbortSignal;
- }): Promise<SQLEditorTab | undefined> => {
- const connection = await extractWorksheetConnection({ database });
-
- // `title === undefined` means "don't change the title" — preserves the
- // current title on auto-save calls from useSQLEditorAutoSave which
- // never pass one. `title === ""` is a real, explicit empty title that
- // should be persisted (renders as the Untitled placeholder elsewhere).
- const currentSheet = worksheet
- ? worksheetStore.getWorksheetByName(worksheet)
- : undefined;
- if (worksheet && !currentSheet) {
- return;
- }
- const worksheetTitle = title ?? currentSheet?.title ?? "";
-
- if (worksheet && currentSheet) {
- const updated = await worksheetStore.patchWorksheet(
- {
- ...currentSheet,
- title: worksheetTitle,
- database,
- content: new TextEncoder().encode(statement),
- },
- ["title", "database", "content"],
- signal
- );
- if (!updated) {
- return;
- }
- if (!isUndefined(folders)) {
- await worksheetStore.upsertWorksheetOrganizer(
- {
- worksheet: updated.name,
- folders: folders,
- },
- ["folders"]
- );
- }
- }
-
- return tabStore.updateTab(tabId, {
- status: "CLEAN",
- connection,
- title: worksheetTitle,
- worksheet,
- });
- };
-
- const createWorksheet = async ({
- tabId,
- title,
- statement = "",
- folders = [],
- database = "",
- }: {
- tabId?: string;
- title?: string;
- statement?: string;
- folders?: string[];
- database?: string;
- }): Promise<SQLEditorTab | undefined> => {
- const worksheetTitle = title ?? "";
- const connection = await extractWorksheetConnection({ database });
-
- const newWorksheet = await worksheetStore.createWorksheet(
- create(WorksheetSchema, {
- title: worksheetTitle,
- database,
- content: new TextEncoder().encode(statement),
- project: editorStore.project,
- visibility: Worksheet_Visibility.PRIVATE,
- })
- );
-
- if (folders.length > 0) {
- await worksheetStore.upsertWorksheetOrganizer(
- {
- worksheet: newWorksheet.name,
- folders: folders,
- },
- ["folders"]
- );
- }
-
- if (tabId) {
- return tabStore.updateTab(tabId, {
- status: "CLEAN",
- title: worksheetTitle,
- statement,
- connection,
- worksheet: newWorksheet.name,
- });
- } else {
- const tab = await openWorksheetByName({
- worksheet: newWorksheet.name,
- forceNewTab: true,
- });
- nextTick(() => {
- if (tab && !tab.connection?.database) {
- useSQLEditorReactStore.getState().setShowConnectionPanel(true);
- }
- });
- return tab;
- }
- };
-
- // ---- shared filter ------------------------------------------------------
-
- const filter = useDynamicLocalStorage<WorksheetFilter>(
- computed(() =>
- storageKeySqlEditorWorksheetFilter(project.value, me.value.email)
- ),
- { ...INITIAL_FILTER }
- );
- const filterChanged = computed(
- () => !isEqual(filter.value, INITIAL_FILTER)
- );
-
- // Safe computed ref — useDynamicLocalStorage can yield null during SSR
- // or on first boot; fall back to INITIAL_FILTER so consumers always get
- // a non-null WorksheetFilter.
- const safeFilter = computed<WorksheetFilter>(
- () => filter.value ?? { ...INITIAL_FILTER }
- );
-
- // ---- per-view contexts (lazily initialised) -----------------------------
- // Use a plain Map (not reactive) — the ViewContext objects have their own
- // internal reactive state. Wrapping in reactive() would auto-unwrap refs.
-
- const contexts = new Map<SheetViewMode, ViewContext>();
-
- const ensureContext = (view: SheetViewMode): ViewContext => {
- if (!contexts.has(view)) {
- contexts.set(view, buildViewContext(view, safeFilter));
- }
- return contexts.get(view)!;
- };
-
- const getContextByView = (view: SheetViewMode) => ensureContext(view);
-
- // Eagerly build all three so watchers/selection logic works on startup.
- const viewContexts = {
- get my() {
- return ensureContext("my");
- },
- get shared() {
- return ensureContext("shared");
- },
- get draft() {
- return ensureContext("draft");
- },
- };
-
- // ---- shared tree-selection state ----------------------------------------
-
- const expandedKeys = useDynamicLocalStorage<Set<string>>(
- computed(() =>
- storageKeySqlEditorWorksheetTree(project.value, me.value.email)
- ),
- new Set([
- ensureContext("my").folderContext.rootPath.value,
- ensureContext("shared").folderContext.rootPath.value,
- ensureContext("draft").folderContext.rootPath.value,
- ])
- );
- const selectedKeys = ref<string[]>([]);
-
- const isWorksheetCreator = (worksheet: { creator: string }) =>
- worksheet.creator === `users/${me.value.email}`;
-
- watch(
- () => ({
- tabId: tabStore.currentTab?.id,
- worksheetName: tabStore.currentTab?.worksheet,
- }),
- async ({ tabId, worksheetName }) => {
- selectedKeys.value = [];
- if (!tabId) {
- return;
- }
-
- let viewMode: SheetViewMode = "draft";
- let worksheetLikeItem: WorksheetLikeItem | undefined;
-
- if (worksheetName) {
- const worksheet = worksheetV1Store.getWorksheetByName(worksheetName);
- if (!worksheet) {
- return;
- }
- worksheetLikeItem = {
- name: worksheet.name,
- title: worksheet.title,
- folders: worksheet.folders,
- type: "worksheet",
- };
- viewMode = isWorksheetCreator(worksheet) ? "my" : "shared";
- } else {
- worksheetLikeItem = {
- name: tabId,
- folders: [],
- title: "",
- type: "draft",
- };
- }
-
- const viewContext = ensureContext(viewMode);
- const key = viewContext.getKeyForWorksheet(worksheetLikeItem);
- selectedKeys.value = [key];
-
- for (const path of viewContext.getPathesForWorksheet(
- worksheetLikeItem
- )) {
- expandedKeys.value.add(path);
- }
-
- await nextTick();
- const dom = document.querySelector(`[data-item-key="${key}"]`);
- if (dom) {
- scrollIntoView(dom, {
- scrollMode: "if-needed",
- block: "nearest",
- });
- }
- },
- { immediate: true }
- );
-
- // ---- editing node -------------------------------------------------------
-
- const editingNode = ref<
- { node: WorksheetFolderNode; rawLabel: string } | undefined
- >();
-
- // ---- batch operations ---------------------------------------------------
-
- const batchUpdateWorksheetFolders = async (
- worksheets: { name: string; folders: string[] }[]
- ) => {
- if (worksheets.length === 0) {
- return;
- }
- await worksheetV1Store.batchUpsertWorksheetOrganizers(
- worksheets.map((worksheet) => ({
- organizer: {
- worksheet: worksheet.name,
- folders: worksheet.folders,
- },
- updateMask: ["folders"],
- }))
- );
- };
-
- // ---- view ref (preserved for SheetContext compat) -----------------------
-
- const view = ref<SheetViewMode>("my");
-
- return {
- // Save-flow actions
- autoSaveController,
- abortAutoSave,
- maybeSwitchProject,
- maybeUpdateWorksheet,
- createWorksheet,
- // SheetContext-compatible fields
- view,
- viewContexts,
- filter,
- filterChanged,
- expandedKeys,
- selectedKeys,
- editingNode,
- isWorksheetCreator,
- batchUpdateWorksheetFolders,
- // view context accessor
- getContextByView,
- };
- }
-);
diff --git a/frontend/src/store/modules/v1/worksheet.ts b/frontend/src/store/modules/v1/worksheet.ts
index 360e178485..9fec1e3f00 100644
--- a/frontend/src/store/modules/v1/worksheet.ts
+++ b/frontend/src/store/modules/v1/worksheet.ts
@@ -5,6 +5,7 @@ import { defineStore } from "pinia";
import { computed } from "vue";
import { worksheetServiceClientConnect } from "@/connect";
import { silentContextKey } from "@/connect/context-key";
+import { useSQLEditorTabStore } from "@/react/stores/sqlEditor/tab-vue-state";
import { useCache } from "@/store/cache";
import { UNKNOWN_ID } from "@/types";
import type {
@@ -28,7 +29,6 @@ import {
getStatementSize,
isWorksheetWritableV1,
} from "@/utils";
-import { useSQLEditorTabStore } from "../sqlEditor";
import { useUserStore } from "../user";
import { useCurrentUserV1 } from "./auth";
import { extractUserEmail } from "./common";
diff --git a/frontend/src/views/sql-editor/Sheet/context.ts b/frontend/src/views/sql-editor/Sheet/context.ts
index 4a99fc92a8..ee3edcfc44 100644
--- a/frontend/src/views/sql-editor/Sheet/context.ts
+++ b/frontend/src/views/sql-editor/Sheet/context.ts
@@ -1,56 +1,516 @@
-import { storeToRefs } from "pinia";
-import type { InjectionKey } from "vue";
+import { useDebounceFn } from "@vueuse/core";
+import Emittery from "emittery";
+import { isEqual, orderBy } from "lodash-es";
+import scrollIntoView from "scroll-into-view-if-needed";
+import type { InjectionKey, Ref } from "vue";
+import { computed, nextTick, ref, toRefs, watch } from "vue";
import { t } from "@/plugins/i18n";
-import {
- pushNotification,
- useSQLEditorTabStore,
- useSQLEditorWorksheetStore,
- useWorkSheetStore,
-} from "@/store";
-import type {
- FolderContext,
- ViewContext,
- WorksheetFilter,
- WorksheetFolderNode,
- WorksheetLikeItem,
-} from "@/store/modules/sqlEditor/worksheet";
+import { useSQLEditorVueState } from "@/react/stores/sqlEditor/editor-vue-state";
+import type { FolderContext } from "@/react/stores/sqlEditor/folder";
+import { buildFolderContext } from "@/react/stores/sqlEditor/folder";
+import { useSQLEditorTabStore } from "@/react/stores/sqlEditor/tab-vue-state";
+import { pushNotification, useCurrentUserV1, useWorkSheetStore } from "@/store";
import type { SQLEditorTab, SQLEditorTabMode } from "@/types";
+import { DEBOUNCE_SEARCH_DELAY } from "@/types";
+import {
+ type Worksheet,
+ Worksheet_Visibility,
+} from "@/types/proto-es/v1/worksheet_service_pb";
import {
extractWorksheetConnection,
getSheetStatement,
isWorksheetReadableV1,
+ storageKeySqlEditorWorksheetFilter,
+ storageKeySqlEditorWorksheetTree,
+ useDynamicLocalStorage,
} from "@/utils";
import type { SheetViewMode } from "./types";
-// ---- re-export types that consumers import from this module ----------------
+// ---- public types -----------------------------------------------------------
+
+export type { FolderContext };
+
+export interface WorksheetLikeItem {
+ name: string;
+ title: string;
+ folders: string[];
+ type: "worksheet" | "draft";
+}
+
+export interface WorksheetFolderNode {
+ key: string;
+ label: string;
+ editable: boolean;
+ isLeaf?: boolean;
+ empty?: boolean;
+ worksheet?: WorksheetLikeItem;
+ children: WorksheetFolderNode[];
+ [key: string]: unknown;
+}
+
+export interface WorksheetFilter {
+ keyword: string;
+ onlyShowStarred: boolean;
+ showMine: boolean;
+ showShared: boolean;
+ showDraft: boolean;
+}
+
+type SheetTreeEvents = Emittery<{
+ "on-built": { viewMode: SheetViewMode };
+}>;
+
+// ---- per-view tree context --------------------------------------------------
+
+const convertToWorksheetLikeItem = (
+ worksheet: Worksheet
+): WorksheetLikeItem => ({
+ name: worksheet.name,
+ title: worksheet.title,
+ folders: worksheet.folders,
+ type: "worksheet",
+});
+
+const buildViewContext = (
+ viewMode: SheetViewMode,
+ filterRef: Ref<WorksheetFilter>
+) => {
+ const sheetStore = useWorkSheetStore();
+ const folderContext = buildFolderContext(viewMode);
+ const me = useCurrentUserV1();
+ const events: SheetTreeEvents = new Emittery();
+ const tabStore = useSQLEditorTabStore();
+ const { project } = toRefs(useSQLEditorVueState());
+
+ const isInitialized = ref(false);
+ const isLoading = ref(false);
+
+ const rootNodeLabel = computed(() => {
+ switch (viewMode) {
+ case "my":
+ return t("sheet.mine");
+ case "shared":
+ return t("sheet.shared");
+ case "draft":
+ return t("common.draft");
+ default:
+ return "";
+ }
+ });
+
+ const getRootTreeNode = (): WorksheetFolderNode => ({
+ isLeaf: false,
+ children: [],
+ key: folderContext.rootPath.value,
+ label: rootNodeLabel.value,
+ editable: false,
+ });
+
+ const sheetTree = ref<WorksheetFolderNode>(getRootTreeNode());
+
+ const worksheetList = computed((): Worksheet[] => {
+ let list: Worksheet[] = [];
+ switch (viewMode) {
+ case "my":
+ list = sheetStore.myWorksheetList;
+ break;
+ case "shared":
+ list = sheetStore.sharedWorksheetList;
+ break;
+ default:
+ break;
+ }
+ list = list.filter((sheet) => sheet.project === project.value);
+ if (filterRef.value.onlyShowStarred) {
+ return list.filter((sheet) => sheet.starred);
+ }
+ return list;
+ });
+
+ const sheetLikeItemList = computed((): WorksheetLikeItem[] => {
+ switch (viewMode) {
+ case "my":
+ case "shared":
+ return worksheetList.value.map(convertToWorksheetLikeItem);
+ case "draft":
+ return tabStore.openTabList
+ .filter((tab) => !tab.worksheet)
+ .map((tab) => ({
+ name: tab.id,
+ title: tab.title,
+ folders: [],
+ type: "draft" as const,
+ }));
+ default:
+ return [];
+ }
+ });
+
+ const getPathesForWorksheet = (worksheet: {
+ folders: string[];
+ }): string[] => {
+ const pathes = [folderContext.rootPath.value];
+ let currentPath = folderContext.rootPath.value;
+ for (const folder of worksheet.folders) {
+ currentPath = folderContext.ensureFolderPath(`${currentPath}/${folder}`);
+ pathes.push(currentPath);
+ }
+ return pathes;
+ };
+
+ const getPwdForWorksheet = (worksheet: { folders: string[] }): string => {
+ return folderContext.ensureFolderPath(worksheet.folders.join("/"));
+ };
+
+ const getKeyForWorksheet = (worksheet: WorksheetLikeItem): string => {
+ return [
+ getPwdForWorksheet(worksheet),
+ `bytebase-${worksheet.type}-${worksheet.name.split("/").slice(-1)[0]}.sql`,
+ ].join("/");
+ };
+
+ const getFoldersForWorksheet = (path: string): string[] => {
+ const pathes = path.replace(folderContext.rootPath.value, "").split("/");
+ if (pathes.slice(-1)[0].endsWith(".sql")) {
+ pathes.pop();
+ }
+ return pathes.map((p) => p.trim()).filter((p) => p);
+ };
+
+ const buildTree = (
+ parent: WorksheetFolderNode,
+ worksheetsByFolder: Map<string, WorksheetLikeItem[]>,
+ hideEmpty: boolean
+ ) => {
+ const subfolders = folderContext
+ .listSubFolders(parent.key)
+ .map((folder) => ({
+ isLeaf: false,
+ children: [],
+ key: folder,
+ label: folder.split("/").slice(-1)[0],
+ editable: true,
+ }));
+
+ let empty = true;
+ for (const childNode of subfolders) {
+ const subtree = buildTree(childNode, worksheetsByFolder, hideEmpty);
+ if (!subtree.empty || !hideEmpty) {
+ parent.children.push(subtree);
+ }
+ if (!subtree.empty) {
+ empty = false;
+ }
+ }
+
+ const sheets = orderBy(
+ worksheetsByFolder.get(parent.key) || [],
+ (item) => item.title
+ ).map((worksheet) => ({
+ isLeaf: true,
+ key: getKeyForWorksheet(worksheet),
+ label: worksheet.title,
+ worksheet,
+ editable: true,
+ children: [],
+ }));
+
+ parent.children.push(...sheets);
+ parent.empty = sheets.length === 0 && empty;
+ if (parent.key !== folderContext.rootPath.value) {
+ parent.isLeaf = parent.children.length === 0;
+ }
+
+ return parent;
+ };
+
+ const folderTree = computed(() =>
+ buildTree(getRootTreeNode(), new Map(), false)
+ );
+
+ const rebuildTree = useDebounceFn(() => {
+ const folderPaths = new Set<string>([]);
+ const worksheetsByFolder = new Map<string, WorksheetLikeItem[]>();
+
+ for (const worksheet of sheetLikeItemList.value) {
+ for (const path of getPathesForWorksheet(worksheet)) {
+ folderPaths.add(path);
+ }
+ const pwd = getPwdForWorksheet(worksheet);
+ if (!worksheetsByFolder.has(pwd)) {
+ worksheetsByFolder.set(pwd, []);
+ }
+ worksheetsByFolder.get(pwd)!.push(worksheet);
+ }
+
+ folderContext.mergeFolders(folderPaths);
+ sheetTree.value = buildTree(
+ getRootTreeNode(),
+ worksheetsByFolder,
+ filterRef.value.onlyShowStarred
+ );
+ events.emit("on-built", { viewMode });
+ }, DEBOUNCE_SEARCH_DELAY);
+
+ watch(
+ [() => folderContext.folders.value, () => sheetLikeItemList.value],
+ ([newFolders, newSheetList], [oldFolders, oldSheetList]) => {
+ if (
+ isEqual(newFolders, oldFolders) &&
+ isEqual(newSheetList, oldSheetList)
+ ) {
+ return;
+ }
+ rebuildTree();
+ }
+ );
+
+ const fetchSheetList = async () => {
+ isLoading.value = true;
+ try {
+ switch (viewMode) {
+ case "my":
+ await sheetStore.fetchWorksheetList(
+ project.value,
+ `creator == "users/${me.value.email}"`
+ );
+ break;
+ case "shared":
+ await sheetStore.fetchWorksheetList(
+ project.value,
+ [
+ `creator != "users/${me.value.email}"`,
+ `visibility in ["${Worksheet_Visibility[Worksheet_Visibility.PROJECT_READ]}","${Worksheet_Visibility[Worksheet_Visibility.PROJECT_WRITE]}"]`,
+ ].join(" && ")
+ );
+ break;
+ default:
+ break;
+ }
+ rebuildTree();
+ isInitialized.value = true;
+ } finally {
+ isLoading.value = false;
+ }
+ };
-export type {
- FolderContext,
- ViewContext,
- WorksheetFilter,
- WorksheetFolderNode,
- WorksheetLikeItem,
+ return {
+ events,
+ isInitialized,
+ isLoading,
+ sheetTree,
+ folderTree,
+ fetchSheetList,
+ folderContext,
+ getKeyForWorksheet,
+ getFoldersForWorksheet,
+ getPathesForWorksheet,
+ getPwdForWorksheet,
+ };
};
-// ---- public API ------------------------------------------------------------
+export type ViewContext = ReturnType<typeof buildViewContext>;
+
+// ---- top-level singleton ----------------------------------------------------
+
+const INITIAL_FILTER: WorksheetFilter = {
+ keyword: "",
+ showShared: true,
+ showMine: true,
+ showDraft: true,
+ onlyShowStarred: false,
+};
/**
- * Returns the full sheet context (filter, expandedKeys, selectedKeys, etc.).
- * Previously backed by Vue provide/inject; now delegates to Pinia store.
- * Returns storeToRefs() merged with non-ref methods so destructuring behaves
- * the same as the original inject pattern (refs preserved as Ref<T>).
+ * The shared sheet-context state. Pulled out of Pinia's `defineStore`
+ * into a module-level lazy singleton because none of this state is
+ * actually shared with Vue components (all live consumers are React)
+ * — dropping Pinia removes the cross-framework store layer without
+ * needing to rewrite the Vue-reactive pipeline. The lazy singleton
+ * preserves "set up once, watchers stay alive" semantics that Pinia
+ * gave us for free.
*/
-export const useSheetContext = () => {
- const store = useSQLEditorWorksheetStore();
- const refs = storeToRefs(store);
+const buildSheetState = () => {
+ const tabStore = useSQLEditorTabStore();
+ const me = useCurrentUserV1();
+ const worksheetV1Store = useWorkSheetStore();
+ const { project } = toRefs(useSQLEditorVueState());
+
+ // ---- shared filter ------------------------------------------------------
+
+ const filter = useDynamicLocalStorage<WorksheetFilter>(
+ computed(() =>
+ storageKeySqlEditorWorksheetFilter(project.value, me.value.email)
+ ),
+ { ...INITIAL_FILTER }
+ );
+ const filterChanged = computed(() => !isEqual(filter.value, INITIAL_FILTER));
+
+ // Safe computed ref — useDynamicLocalStorage can yield null during SSR
+ // or on first boot; fall back to INITIAL_FILTER so consumers always get
+ // a non-null WorksheetFilter.
+ const safeFilter = computed<WorksheetFilter>(
+ () => filter.value ?? { ...INITIAL_FILTER }
+ );
+
+ // ---- per-view contexts (lazily initialised) -----------------------------
+ // Use a plain Map (not reactive) — the ViewContext objects have their own
+ // internal reactive state. Wrapping in reactive() would auto-unwrap refs.
+
+ const contexts = new Map<SheetViewMode, ViewContext>();
+
+ const ensureContext = (view: SheetViewMode): ViewContext => {
+ if (!contexts.has(view)) {
+ contexts.set(view, buildViewContext(view, safeFilter));
+ }
+ return contexts.get(view)!;
+ };
+
+ const getContextByView = (view: SheetViewMode) => ensureContext(view);
+
+ // Eagerly build all three so watchers/selection logic works on startup.
+ const viewContexts = {
+ get my() {
+ return ensureContext("my");
+ },
+ get shared() {
+ return ensureContext("shared");
+ },
+ get draft() {
+ return ensureContext("draft");
+ },
+ };
+
+ // ---- shared tree-selection state ----------------------------------------
+
+ const expandedKeys = useDynamicLocalStorage<Set<string>>(
+ computed(() =>
+ storageKeySqlEditorWorksheetTree(project.value, me.value.email)
+ ),
+ new Set([
+ ensureContext("my").folderContext.rootPath.value,
+ ensureContext("shared").folderContext.rootPath.value,
+ ensureContext("draft").folderContext.rootPath.value,
+ ])
+ );
+ const selectedKeys = ref<string[]>([]);
+
+ const isWorksheetCreator = (worksheet: { creator: string }) =>
+ worksheet.creator === `users/${me.value.email}`;
+
+ watch(
+ () => ({
+ tabId: tabStore.currentTab?.id,
+ worksheetName: tabStore.currentTab?.worksheet,
+ }),
+ async ({ tabId, worksheetName }) => {
+ selectedKeys.value = [];
+ if (!tabId) {
+ return;
+ }
+
+ let viewMode: SheetViewMode = "draft";
+ let worksheetLikeItem: WorksheetLikeItem | undefined;
+
+ if (worksheetName) {
+ const worksheet = worksheetV1Store.getWorksheetByName(worksheetName);
+ if (!worksheet) {
+ return;
+ }
+ worksheetLikeItem = {
+ name: worksheet.name,
+ title: worksheet.title,
+ folders: worksheet.folders,
+ type: "worksheet",
+ };
+ viewMode = isWorksheetCreator(worksheet) ? "my" : "shared";
+ } else {
+ worksheetLikeItem = {
+ name: tabId,
+ folders: [],
+ title: "",
+ type: "draft",
+ };
+ }
+
+ const viewContext = ensureContext(viewMode);
+ const key = viewContext.getKeyForWorksheet(worksheetLikeItem);
+ selectedKeys.value = [key];
+
+ for (const path of viewContext.getPathesForWorksheet(worksheetLikeItem)) {
+ expandedKeys.value.add(path);
+ }
+
+ await nextTick();
+ const dom = document.querySelector(`[data-item-key="${key}"]`);
+ if (dom) {
+ scrollIntoView(dom, {
+ scrollMode: "if-needed",
+ block: "nearest",
+ });
+ }
+ },
+ { immediate: true }
+ );
+
+ // ---- editing node -------------------------------------------------------
+
+ const editingNode = ref<
+ { node: WorksheetFolderNode; rawLabel: string } | undefined
+ >();
+
+ // ---- batch operations ---------------------------------------------------
+
+ const batchUpdateWorksheetFolders = async (
+ worksheets: { name: string; folders: string[] }[]
+ ) => {
+ if (worksheets.length === 0) {
+ return;
+ }
+ await worksheetV1Store.batchUpsertWorksheetOrganizers(
+ worksheets.map((worksheet) => ({
+ organizer: {
+ worksheet: worksheet.name,
+ folders: worksheet.folders,
+ },
+ updateMask: ["folders"],
+ }))
+ );
+ };
+
+ // ---- view ref -----------------------------------------------------------
+
+ const view = ref<SheetViewMode>("my");
+
return {
- ...refs,
- isWorksheetCreator: store.isWorksheetCreator,
- batchUpdateWorksheetFolders: store.batchUpdateWorksheetFolders,
- getContextByView: store.getContextByView,
+ view,
+ viewContexts,
+ filter,
+ filterChanged,
+ expandedKeys,
+ selectedKeys,
+ editingNode,
+ isWorksheetCreator,
+ batchUpdateWorksheetFolders,
+ getContextByView,
};
};
+let _sheetState: ReturnType<typeof buildSheetState> | undefined;
+const getSheetState = () => {
+ if (!_sheetState) _sheetState = buildSheetState();
+ return _sheetState;
+};
+
+// ---- public API ------------------------------------------------------------
+
+/**
+ * Returns the full sheet context (filter, expandedKeys, selectedKeys, etc.).
+ * Previously delegated to a Pinia store; now reads directly from a
+ * module-level Vue-reactive singleton built by `buildSheetState()`.
+ */
+export const useSheetContext = () => getSheetState();
+
export type SheetContext = ReturnType<typeof useSheetContext>;
// ---- InjectionKey kept for source-compat (no longer used) ------------------
@@ -59,10 +519,9 @@ export const KEY = Symbol("bb.sql-editor.sheet") as InjectionKey<SheetContext>;
/**
* Returns the per-view context for `view`.
- * Previously backed by Vue inject; now delegates to Pinia store.
*/
export const useSheetContextByView = (view: SheetViewMode) =>
- useSQLEditorWorksheetStore().getContextByView(view);
+ getSheetState().getContextByView(view);
// ---- tree helpers ----------------------------------------------------------
@@ -93,13 +552,12 @@ export const revealWorksheets = <T>(
});
};
-// ---- provideSheetContext: kept for backward compat (no-op) -----------------
-
-// Called from SQLEditorLayout.vue to eagerly boot the store so watchers
-// (tab-selection → selectedKeys) start immediately on app mount.
-export const provideSheetContext = () => {
- return useSQLEditorWorksheetStore();
-};
+/**
+ * Eagerly boot the sheet-state singleton so its watchers start firing on
+ * app mount. Kept as a no-op-shaped function so call sites match the
+ * Pinia-era `useSQLEditorWorksheetStore()` boot call.
+ */
+export const provideSheetContext = () => getSheetState();
// ---- openWorksheetByName (unchanged) ----------------------------------------