Skip to content

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

refactor: use app store (#20449)

ecmadaof04cd86eb91f
diff --git a/frontend/src/react/components/database/DatabaseTable.tsx b/frontend/src/react/components/database/DatabaseTable.tsx
index b95a89fb42..eb6cdd3293 100644
--- a/frontend/src/react/components/database/DatabaseTable.tsx
+++ b/frontend/src/react/components/database/DatabaseTable.tsx
@@ -5,9 +5,9 @@ import {
useSessionPageSize,
} from "@/react/hooks/useSessionPageSize";
import { useVueState } from "@/react/hooks/useVueState";
+import type { DatabaseFilter } from "@/react/lib/databaseFilter";
import { router } from "@/router";
import { useActuatorV1Store, useDatabaseV1Store } from "@/store";
-import type { DatabaseFilter } from "@/store/modules/v1/database";
import type { Database } from "@/types/proto-es/v1/database_service_pb";
import { autoDatabaseRoute } from "@/utils";
import {
diff --git a/frontend/src/react/components/sql-editor/AccessGrantRequestDrawer.test.tsx b/frontend/src/react/components/sql-editor/AccessGrantRequestDrawer.test.tsx
index 9aa8893e22..dab94e1412 100644
--- a/frontend/src/react/components/sql-editor/AccessGrantRequestDrawer.test.tsx
+++ b/frontend/src/react/components/sql-editor/AccessGrantRequestDrawer.test.tsx
@@ -41,14 +41,21 @@ vi.mock("@/react/hooks/useAppState", () => ({
}),
}));
-vi.mock("@/store", () => ({
- pushNotification: mocks.pushNotification,
-}));
-
-vi.mock("@/react/stores/app", () => ({
- useAppStore: (selector: (state: unknown) => unknown) =>
- selector({ fetchDatabases: mocks.fetchDatabases }),
-}));
+vi.mock("@/react/stores/app", () => {
+ // `notify` reuses the `pushNotification` vi.fn so the existing test
+ // assertions on `mocks.pushNotification` keep working after the migration
+ // from the Pinia helper to the app-store notification slice.
+ const state = () => ({
+ fetchDatabases: mocks.fetchDatabases,
+ notify: mocks.pushNotification,
+ });
+ return {
+ useAppStore: Object.assign(
+ (selector: (s: ReturnType<typeof state>) => unknown) => selector(state()),
+ { getState: state }
+ ),
+ };
+});
// Zustand editor store — active project read.
vi.mock("@/react/stores/sqlEditor/editor", () => ({
diff --git a/frontend/src/react/components/sql-editor/AccessGrantRequestDrawer.tsx b/frontend/src/react/components/sql-editor/AccessGrantRequestDrawer.tsx
index f64efdbe62..d929099360 100644
--- a/frontend/src/react/components/sql-editor/AccessGrantRequestDrawer.tsx
+++ b/frontend/src/react/components/sql-editor/AccessGrantRequestDrawer.tsx
@@ -26,7 +26,6 @@ import { useSQLEditorEditorState } from "@/react/stores/sqlEditor/editor";
import { getSQLEditorTabsState } from "@/react/stores/sqlEditor/tab";
import { router } from "@/router";
import { PROJECT_V1_ROUTE_ISSUE_DETAIL } from "@/router/dashboard/projectV1";
-import { pushNotification } from "@/store";
import {
AccessGrant_Status,
AccessGrantSchema,
@@ -202,7 +201,7 @@ function AccessGrantRequestDrawerInner({
})
);
- pushNotification({
+ useAppStore.getState().notify({
module: "bytebase",
style: "SUCCESS",
title: t("common.created"),
diff --git a/frontend/src/react/components/sql-editor/AccessPane.test.tsx b/frontend/src/react/components/sql-editor/AccessPane.test.tsx
index 5b83cf5060..e3cd27a1e4 100644
--- a/frontend/src/react/components/sql-editor/AccessPane.test.tsx
+++ b/frontend/src/react/components/sql-editor/AccessPane.test.tsx
@@ -22,11 +22,11 @@ const mocks = vi.hoisted(() => ({
},
setHighlightAccessGrantName: vi.fn(),
searchMyAccessGrants: vi.fn(),
- useIssueV1Store: vi.fn(),
fetchDatabases: vi
.fn()
.mockResolvedValue({ databases: [], nextPageToken: "" }),
getOrFetchDatabaseByName: vi.fn().mockResolvedValue({}),
+ fetchIssueByName: vi.fn().mockResolvedValue({}),
hasFeature: vi.fn(() => true),
sqlEditorEventsEmit: vi.fn().mockResolvedValue(undefined),
getDefaultPagination: vi.fn(() => 20),
@@ -36,11 +36,6 @@ vi.mock("react-i18next", () => ({
useTranslation: mocks.useTranslation,
}));
-vi.mock("@/store", () => ({
- useIssueV1Store: mocks.useIssueV1Store,
- hasFeature: mocks.hasFeature,
-}));
-
vi.mock("@/react/hooks/useAppProject", () => ({
useAppProject: () => mocks.projectData,
}));
@@ -51,6 +46,8 @@ vi.mock("@/react/stores/app", () => ({
searchMyAccessGrants: mocks.searchMyAccessGrants,
fetchDatabases: mocks.fetchDatabases,
getOrFetchDatabaseByName: mocks.getOrFetchDatabaseByName,
+ fetchIssueByName: mocks.fetchIssueByName,
+ hasFeature: mocks.hasFeature,
}),
}));
@@ -107,6 +104,10 @@ vi.mock("@/types/proto-es/v1/subscription_service_pb", () => ({
PlanFeature: { FEATURE_JIT: 5 },
}));
+vi.mock("@/react/hooks/useSQLEditorBridge", () => ({
+ useSQLEditorFeature: () => mocks.hasFeature(),
+}));
+
vi.mock("@/react/components/AdvancedSearch", () => ({
AdvancedSearch: ({
placeholder,
@@ -248,9 +249,7 @@ const setupDefaultMocks = () => {
nextPageToken: "",
});
- mocks.useIssueV1Store.mockReturnValue({
- fetchIssueByName: vi.fn().mockResolvedValue({}),
- });
+ mocks.fetchIssueByName.mockResolvedValue({});
mocks.fetchDatabases.mockResolvedValue({ databases: [], nextPageToken: "" });
mocks.getOrFetchDatabaseByName.mockResolvedValue({});
diff --git a/frontend/src/react/components/sql-editor/AccessPane.tsx b/frontend/src/react/components/sql-editor/AccessPane.tsx
index c00ca59f0b..bdb296bedc 100644
--- a/frontend/src/react/components/sql-editor/AccessPane.tsx
+++ b/frontend/src/react/components/sql-editor/AccessPane.tsx
@@ -17,11 +17,11 @@ import { FeatureBadge } from "@/react/components/FeatureBadge";
import { PermissionGuard } from "@/react/components/PermissionGuard";
import { Button } from "@/react/components/ui/button";
import { useAppProject } from "@/react/hooks/useAppProject";
+import { useSQLEditorFeature } from "@/react/hooks/useSQLEditorBridge";
import { useAppStore } from "@/react/stores/app";
import type { AccessGrantFilter as AccessFilter } from "@/react/stores/app/types";
import { useSQLEditorStore } from "@/react/stores/sqlEditor";
import { useSQLEditorEditorState } from "@/react/stores/sqlEditor/editor";
-import { hasFeature, useIssueV1Store } from "@/store";
import type { AccessGrant } from "@/types/proto-es/v1/access_grant_service_pb";
import { AccessGrant_Status } from "@/types/proto-es/v1/access_grant_service_pb";
import type { Issue } from "@/types/proto-es/v1/issue_service_pb";
@@ -49,7 +49,7 @@ export function AccessPane() {
const getOrFetchDatabaseByName = useAppStore(
(state) => state.getOrFetchDatabaseByName
);
- const issueStore = useIssueV1Store();
+ const fetchIssueByName = useAppStore((state) => state.fetchIssueByName);
const highlightAccessGrantName = useSQLEditorStore(
(s) => s.highlightAccessGrantName
);
@@ -83,7 +83,7 @@ export function AccessPane() {
const resolvedProject = useAppProject(projectName as string);
const project = projectName ? resolvedProject : undefined;
- const hasJITFeature = useMemo(() => hasFeature(PlanFeature.FEATURE_JIT), []);
+ const hasJITFeature = useSQLEditorFeature(PlanFeature.FEATURE_JIT);
// Build scope options for AdvancedSearch (React-compatible, no Vue renderers)
const scopeOptions = useMemo((): ScopeOption[] => {
@@ -167,7 +167,7 @@ export function AccessPane() {
const results = await Promise.all(
pendingWithIssue.map(async (g) => {
try {
- const issue = await issueStore.fetchIssueByName(g.issue, true);
+ const issue = await fetchIssueByName(g.issue, true);
return { grantName: g.name, issue };
} catch {
return undefined;
@@ -184,7 +184,7 @@ export function AccessPane() {
return next;
});
},
- [issueStore]
+ [fetchIssueByName]
);
const fetchAccessGrants = useCallback(
diff --git a/frontend/src/react/components/sql-editor/AsidePanel.tsx b/frontend/src/react/components/sql-editor/AsidePanel.tsx
index cedb7deaad..89fdefedeb 100644
--- a/frontend/src/react/components/sql-editor/AsidePanel.tsx
+++ b/frontend/src/react/components/sql-editor/AsidePanel.tsx
@@ -1,7 +1,7 @@
-import { useCallback } from "react";
+import { useCallback, useEffect } from "react";
import { useTranslation } from "react-i18next";
import { ProjectSelect } from "@/react/components/ProjectSelect";
-import { usePiniaBridge } from "@/react/hooks/usePiniaBridge";
+import { useAppStore } from "@/react/stores/app";
import { useSQLEditorStore } from "@/react/stores/sqlEditor";
import {
getSQLEditorEditorState,
@@ -10,9 +10,7 @@ import {
import { useIsDisconnected } from "@/react/stores/sqlEditor/tab";
import { router } from "@/router";
import { PROJECT_V1_ROUTE_DASHBOARD } from "@/router/dashboard/workspaceRoutes";
-import { useActuatorV1Store } from "@/store";
import { defaultProject, isValidProjectName } from "@/types";
-import { hasProjectPermissionV2, hasWorkspacePermissionV2 } from "@/utils";
import { AccessPane } from "./AccessPane";
import { ActionBar } from "./AsidePanel/ActionBar";
import { GutterBar } from "./GutterBar";
@@ -36,7 +34,6 @@ import { WorksheetPane } from "./WorksheetPane";
*/
export function AsidePanel() {
const { t } = useTranslation();
- const actuatorStore = useActuatorV1Store();
const maybeSwitchProject = useSQLEditorStore((s) => s.maybeSwitchProject);
const asidePanelTab = useSQLEditorStore((s) => s.asidePanelTab);
@@ -46,12 +43,26 @@ export function AsidePanel() {
(s) => s.projectContextReady
);
- const allowAccessDefaultProject = usePiniaBridge(() => {
- const name = actuatorStore.serverInfo?.defaultProject ?? "";
- return hasProjectPermissionV2(defaultProject(name), "bb.projects.get");
- });
- const allowCreateProject = usePiniaBridge(() =>
- hasWorkspacePermissionV2("bb.projects.create")
+ const defaultProjectName = useAppStore(
+ (s) => s.serverInfo?.defaultProject ?? ""
+ );
+ // Self-fetch workspace permission state — the SQL editor route doesn't
+ // mount the dashboard shells that hydrate roles + workspace IAM, so the
+ // permission selectors below would otherwise read empty state.
+ const loadWorkspacePermissionState = useAppStore(
+ (s) => s.loadWorkspacePermissionState
+ );
+ useEffect(() => {
+ void loadWorkspacePermissionState();
+ }, [loadWorkspacePermissionState]);
+ const allowAccessDefaultProject = useAppStore((s) =>
+ s.hasProjectPermission(
+ defaultProject(defaultProjectName),
+ "bb.projects.get"
+ )
+ );
+ const allowCreateProject = useAppStore((s) =>
+ s.hasWorkspacePermission("bb.projects.create")
);
const handleSwitchProject = useCallback(
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 82a12b5a80..ba4ae891f5 100644
--- a/frontend/src/react/components/sql-editor/ConnectionPane/ConnectionPane.test.tsx
+++ b/frontend/src/react/components/sql-editor/ConnectionPane/ConnectionPane.test.tsx
@@ -218,7 +218,7 @@ vi.mock("@/store/modules", () => ({
useDBGroupStore: () => mocks.dbGroupStore,
}));
-vi.mock("@/store/modules/v1/common", () => ({
+vi.mock("@/react/lib/resourceName", () => ({
instanceNamePrefix: "instances/",
}));
diff --git a/frontend/src/react/components/sql-editor/ConnectionPane/ConnectionPane.tsx b/frontend/src/react/components/sql-editor/ConnectionPane/ConnectionPane.tsx
index da844cef13..a5fe4d1b05 100644
--- a/frontend/src/react/components/sql-editor/ConnectionPane/ConnectionPane.tsx
+++ b/frontend/src/react/components/sql-editor/ConnectionPane/ConnectionPane.tsx
@@ -28,6 +28,8 @@ import { useAppDatabase } from "@/react/hooks/useAppDatabase";
import { useAppProject } from "@/react/hooks/useAppProject";
import { useCurrentUser } from "@/react/hooks/useAppState";
import { useSQLEditorFeature } from "@/react/hooks/useSQLEditorBridge";
+import type { DatabaseFilter } from "@/react/lib/databaseFilter";
+import { instanceNamePrefix } from "@/react/lib/resourceName";
import { cn } from "@/react/lib/utils";
import { useAppStore } from "@/react/stores/app";
import { useSQLEditorStore } from "@/react/stores/sqlEditor";
@@ -38,9 +40,6 @@ import {
useIsInBatchMode,
useSupportBatchMode,
} from "@/react/stores/sqlEditor/tab";
-import { pushNotification } from "@/store";
-import { instanceNamePrefix } from "@/store/modules/v1/common";
-import type { DatabaseFilter } from "@/store/modules/v1/database";
import type {
BatchQueryContext,
QueryDataSourceType,
@@ -492,7 +491,7 @@ function ConnectionPaneInner({ show, onMissingFeature }: Props) {
if (ok) {
setShowConnectionPanel(false);
} else {
- pushNotification({
+ useAppStore.getState().notify({
module: "bytebase",
style: "CRITICAL",
title: t("sql-editor.no-queriable-database"),
@@ -525,7 +524,7 @@ function ConnectionPaneInner({ show, onMissingFeature }: Props) {
});
const ok = await onBatchQueryContextChange(ctx);
if (next.length > 0 && !ok) {
- pushNotification({
+ useAppStore.getState().notify({
module: "bytebase",
style: "CRITICAL",
title: t("sql-editor.no-queriable-database"),
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 cab678f8c2..7ee4b53dcc 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
@@ -16,7 +16,6 @@ globalThis.ResizeObserver = class ResizeObserver {
const mocks = vi.hoisted(() => ({
useHoverState: vi.fn(),
- useVueState: vi.fn<(getter: () => unknown) => unknown>(),
}));
vi.mock("react-i18next", () => ({
@@ -27,10 +26,6 @@ vi.mock("./hover-state", () => ({
useHoverState: mocks.useHoverState,
}));
-vi.mock("@/react/hooks/useVueState", () => ({
- useVueState: mocks.useVueState,
-}));
-
vi.mock("@/store", () => ({}));
vi.mock("@/react/stores/sqlEditor/editor-vue-state", () => ({
@@ -98,7 +93,6 @@ const makeDatabaseNode = (): SQLEditorTreeNode =>
beforeEach(async () => {
vi.clearAllMocks();
- mocks.useVueState.mockImplementation((getter) => getter());
({ DatabaseHoverPanel } = await import("./DatabaseHoverPanel"));
});
diff --git a/frontend/src/react/components/sql-editor/ConnectionPane/tree.ts b/frontend/src/react/components/sql-editor/ConnectionPane/tree.ts
index 043c270e9f..9ee010f67b 100644
--- a/frontend/src/react/components/sql-editor/ConnectionPane/tree.ts
+++ b/frontend/src/react/components/sql-editor/ConnectionPane/tree.ts
@@ -1,11 +1,11 @@
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import type { DatabaseFilter } from "@/react/lib/databaseFilter";
import { useAppStore } from "@/react/stores/app";
import { useSQLEditorEditorState } from "@/react/stores/sqlEditor/editor";
import {
buildTreeImpl,
mapTreeNodeByType,
} from "@/react/stores/sqlEditor/tree-utils";
-import type { DatabaseFilter } from "@/store";
import type {
SQLEditorTreeNode,
StatefulSQLEditorTreeFactor as StatefulFactor,
diff --git a/frontend/src/react/components/sql-editor/ContainerChooser.test.tsx b/frontend/src/react/components/sql-editor/ContainerChooser.test.tsx
index 9c7f56ca61..9e752b9e86 100644
--- a/frontend/src/react/components/sql-editor/ContainerChooser.test.tsx
+++ b/frontend/src/react/components/sql-editor/ContainerChooser.test.tsx
@@ -17,6 +17,7 @@ const mocks = vi.hoisted(() => ({
useConnectionOfCurrentSQLEditorTab: vi.fn(),
router: {
currentRoute: { value: { query: {} } },
+ afterEach: () => () => {},
},
}));
diff --git a/frontend/src/react/components/sql-editor/ContainerChooser.tsx b/frontend/src/react/components/sql-editor/ContainerChooser.tsx
index 0e186366d8..d57bfe6350 100644
--- a/frontend/src/react/components/sql-editor/ContainerChooser.tsx
+++ b/frontend/src/react/components/sql-editor/ContainerChooser.tsx
@@ -2,11 +2,11 @@ import { useEffect, useMemo } from "react";
import { useTranslation } from "react-i18next";
import { usePiniaBridge } from "@/react/hooks/usePiniaBridge";
import { useConnectionOfCurrentSQLEditorTab } from "@/react/hooks/useSQLEditorBridge";
+import { useVueRoute } from "@/react/hooks/useVueRoute";
import {
getSQLEditorTabsState,
useSQLEditorTabState,
} from "@/react/stores/sqlEditor/tab";
-import { router } from "@/router";
import { useDBSchemaV1Store } from "@/store";
import { Engine } from "@/types/proto-es/v1/common_pb";
import { ConnectChooser } from "./ConnectChooser";
@@ -69,9 +69,7 @@ export function ContainerChooser() {
// tracked both `route.query.table` and `tab.value` (the latter via the
// setter's reactive reads) so that switching to a new tab with the URL
// query still present re-seeded the new tab's connection.table.
- const queryParam = usePiniaBridge(
- () => router.currentRoute.value.query.table as string | undefined
- );
+ const queryParam = useVueRoute().query.table as string | undefined;
const currentTabId = useSQLEditorTabState((s) => s.currentTabId);
useEffect(() => {
if (queryParam) handleChange(queryParam);
diff --git a/frontend/src/react/components/sql-editor/EditorAction.test.tsx b/frontend/src/react/components/sql-editor/EditorAction.test.tsx
index c20d0cf557..da3b4adaf6 100644
--- a/frontend/src/react/components/sql-editor/EditorAction.test.tsx
+++ b/frontend/src/react/components/sql-editor/EditorAction.test.tsx
@@ -40,7 +40,13 @@ vi.mock("@/store", () => ({
vi.mock("@/react/stores/app", () => ({
useAppStore: {
- getState: () => ({ getWorksheetByName: mocks.getWorksheetByName }),
+ getState: () => ({
+ getWorksheetByName: mocks.getWorksheetByName,
+ // `EditorAction.handleRunQuery` records the data-query intro flag via
+ // the migrated preferences slice. Tests don't assert against this, so a
+ // bare noop keeps the call surface satisfied.
+ saveIntroStateByKey: vi.fn(),
+ }),
},
}));
diff --git a/frontend/src/react/components/sql-editor/EditorAction.tsx b/frontend/src/react/components/sql-editor/EditorAction.tsx
index bf436384cb..38e4117996 100644
--- a/frontend/src/react/components/sql-editor/EditorAction.tsx
+++ b/frontend/src/react/components/sql-editor/EditorAction.tsx
@@ -19,7 +19,6 @@ import {
useIsDisconnected,
useSQLEditorTabState,
} from "@/react/stores/sqlEditor/tab";
-import { useUIStateStore } from "@/store";
import type { SQLEditorQueryParams } from "@/types";
import { Engine } from "@/types/proto-es/v1/common_pb";
import { isWorksheetWritableV1, keyboardShortcutStr } from "@/utils";
@@ -44,7 +43,6 @@ type Props = {
*/
export function EditorAction({ onExecute }: Props) {
const { t } = useTranslation();
- const uiStateStore = useUIStateStore();
const { currentSheet: currentWorksheet } = useWorksheetAndTab();
const { instance } = useConnectionOfCurrentSQLEditorTab();
@@ -132,7 +130,7 @@ export function EditorAction({ onExecute }: Props) {
explain: false,
selection: currentTab.editorState.selection,
});
- uiStateStore.saveIntroStateByKey({
+ useAppStore.getState().saveIntroStateByKey({
key: "data.query",
newState: true,
});
diff --git a/frontend/src/react/components/sql-editor/ExecuteHint.tsx b/frontend/src/react/components/sql-editor/ExecuteHint.tsx
index 1bb696581a..6aa7f9097c 100644
--- a/frontend/src/react/components/sql-editor/ExecuteHint.tsx
+++ b/frontend/src/react/components/sql-editor/ExecuteHint.tsx
@@ -9,7 +9,6 @@ import { useSQLEditorEditorState } from "@/react/stores/sqlEditor/editor";
import { getSQLEditorTabsState } from "@/react/stores/sqlEditor/tab";
import { router } from "@/router";
import { PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL } from "@/router/dashboard/projectV1";
-import { pushNotification, useStorageStore } from "@/store";
import { unknownProject } from "@/types";
import type { Database } from "@/types/proto-es/v1/database_service_pb";
import {
@@ -17,6 +16,7 @@ import {
extractProjectResourceName,
getDatabaseEnvironment,
} from "@/utils";
+import { putBlob } from "@/utils/blob-storage";
import { AdminModeButton } from "./AdminModeButton";
type Props = {
@@ -30,7 +30,6 @@ type Props = {
*/
export function ExecuteHint({ database, onClose }: Props) {
const { t } = useTranslation();
- const storageStore = useStorageStore();
const project = useSQLEditorEditorState((s) => s.project);
const allowAdmin = useSQLEditorAllowAdmin(project);
@@ -41,7 +40,7 @@ export function ExecuteHint({ database, onClose }: Props) {
const currentTab = tabsState.tabsById.get(tabsState.currentTabId);
const connectedDatabase = currentTab?.connection.database ?? "";
if (!connectedDatabase) {
- pushNotification({
+ useAppStore.getState().notify({
module: "bytebase",
style: "CRITICAL",
title: t("sql-editor.no-database-selected"),
@@ -63,7 +62,7 @@ export function ExecuteHint({ database, onClose }: Props) {
const tab = tabsState.tabsById.get(tabsState.currentTabId);
const statement = tab?.selectedStatement || tab?.statement || "";
const sqlStorageKey = `bb.issues.sql.${uuidv4()}`;
- storageStore.put(sqlStorageKey, statement);
+ void putBlob(sqlStorageKey, statement);
const { databaseName } = extractDatabaseResourceName(db.name);
const query: Record<string, string> = {
diff --git a/frontend/src/react/components/sql-editor/FolderForm.test.tsx b/frontend/src/react/components/sql-editor/FolderForm.test.tsx
index 8d90daedb2..b146792d7b 100644
--- a/frontend/src/react/components/sql-editor/FolderForm.test.tsx
+++ b/frontend/src/react/components/sql-editor/FolderForm.test.tsx
@@ -19,7 +19,6 @@ globalThis.ResizeObserver = class ResizeObserver {
const mocks = vi.hoisted(() => ({
useTranslation: vi.fn(() => ({ t: (key: string) => key })),
- useVueState: vi.fn<(getter: () => unknown) => unknown>(),
useSheetContextByView: vi.fn(),
useClickOutside: vi.fn(),
onSelectCallback: vi.fn(),
@@ -29,10 +28,6 @@ vi.mock("react-i18next", () => ({
useTranslation: mocks.useTranslation,
}));
-vi.mock("@/react/hooks/useVueState", () => ({
- useVueState: mocks.useVueState,
-}));
-
vi.mock("@/views/sql-editor/Sheet", () => ({
useSheetContextByView: mocks.useSheetContextByView,
}));
@@ -163,7 +158,6 @@ const makeFolderNode = (
const setupDefaultMocks = () => {
mocks.useTranslation.mockReturnValue({ t: (key: string) => key });
mocks.useClickOutside.mockImplementation(() => undefined);
- mocks.useVueState.mockImplementation((getter: () => unknown) => getter());
const rootNode = makeFolderNode("/my", [
makeFolderNode("/my/foo"),
diff --git a/frontend/src/react/components/sql-editor/GutterBar.test.tsx b/frontend/src/react/components/sql-editor/GutterBar.test.tsx
index bc73f596b9..c2d5bfd096 100644
--- a/frontend/src/react/components/sql-editor/GutterBar.test.tsx
+++ b/frontend/src/react/components/sql-editor/GutterBar.test.tsx
@@ -59,6 +59,7 @@ vi.mock("@/router", () => ({
router: {
resolve: mocks.routerResolve,
currentRoute: { value: { params: {} } },
+ afterEach: () => () => {},
},
}));
diff --git a/frontend/src/react/components/sql-editor/GutterBar.tsx b/frontend/src/react/components/sql-editor/GutterBar.tsx
index 44c0e08b68..eb8b18393a 100644
--- a/frontend/src/react/components/sql-editor/GutterBar.tsx
+++ b/frontend/src/react/components/sql-editor/GutterBar.tsx
@@ -1,7 +1,7 @@
import logoIcon from "@/assets/logo-icon.svg";
import { Separator } from "@/react/components/ui/separator";
import { useAppProject } from "@/react/hooks/useAppProject";
-import { usePiniaBridge } from "@/react/hooks/usePiniaBridge";
+import { useVueRoute } from "@/react/hooks/useVueRoute";
import type { AsidePanelTab } from "@/react/stores/sqlEditor";
import { useSQLEditorStore } from "@/react/stores/sqlEditor";
import { useSQLEditorEditorState } from "@/react/stores/sqlEditor/editor";
@@ -24,9 +24,7 @@ export function GutterBar() {
const resolvedProject = useAppProject(projectName);
const project = projectName ? resolvedProject : undefined;
- const routeProjectParam = usePiniaBridge(
- () => router.currentRoute.value.params.project as string | undefined
- );
+ const routeProjectParam = useVueRoute().params.project as string | undefined;
const logoHref = routeProjectParam
? router.resolve({
diff --git a/frontend/src/react/components/sql-editor/HistoryPane.test.tsx b/frontend/src/react/components/sql-editor/HistoryPane.test.tsx
index 35a05d8e76..5df40f2b31 100644
--- a/frontend/src/react/components/sql-editor/HistoryPane.test.tsx
+++ b/frontend/src/react/components/sql-editor/HistoryPane.test.tsx
@@ -32,8 +32,13 @@ vi.mock("react-i18next", () => ({
useTranslation: mocks.useTranslation,
}));
-vi.mock("@/store", () => ({
- pushNotification: mocks.pushNotification,
+vi.mock("@/react/stores/app", () => ({
+ // Route `useAppStore.getState().notify(...)` through the same vi.fn the
+ // tests asserted against under the legacy `pushNotification` API so the
+ // assertion bodies stay readable.
+ useAppStore: {
+ getState: () => ({ notify: mocks.pushNotification }),
+ },
}));
// Zustand tab store — selector hook + imperative getter.
diff --git a/frontend/src/react/components/sql-editor/HistoryPane.tsx b/frontend/src/react/components/sql-editor/HistoryPane.tsx
index fdc733bbb7..c155a0bb4f 100644
--- a/frontend/src/react/components/sql-editor/HistoryPane.tsx
+++ b/frontend/src/react/components/sql-editor/HistoryPane.tsx
@@ -11,6 +11,7 @@ import {
import { useTranslation } from "react-i18next";
import { Button } from "@/react/components/ui/button";
import { SearchInput } from "@/react/components/ui/search-input";
+import { useAppStore } from "@/react/stores/app";
import type { QueryHistoryFilter } from "@/react/stores/sqlEditor";
import {
selectQueryHistoryEntry,
@@ -21,7 +22,6 @@ import {
getSQLEditorTabsState,
useSQLEditorTabState,
} from "@/react/stores/sqlEditor/tab";
-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";
@@ -131,7 +131,7 @@ export function HistoryPane() {
const handleCopy = async (statement: string) => {
try {
await navigator.clipboard.writeText(statement);
- pushNotification({
+ useAppStore.getState().notify({
module: "bytebase",
style: "SUCCESS",
title: t("sql-editor.url-copied-to-clipboard"),
diff --git a/frontend/src/react/components/sql-editor/MaskingReasonPopover.test.tsx b/frontend/src/react/components/sql-editor/MaskingReasonPopover.test.tsx
index ad3b854213..5c27e523a8 100644
--- a/frontend/src/react/components/sql-editor/MaskingReasonPopover.test.tsx
+++ b/frontend/src/react/components/sql-editor/MaskingReasonPopover.test.tsx
@@ -9,7 +9,6 @@ import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
const mocks = vi.hoisted(() => ({
useTranslation: vi.fn(() => ({ t: (key: string) => key })),
- useVueState: vi.fn<(getter: () => unknown) => unknown>(),
projectData: { name: "projects/proj1", allowJustInTimeAccess: false } as {
name: string;
allowJustInTimeAccess: boolean;
@@ -22,12 +21,10 @@ vi.mock("react-i18next", () => ({
useTranslation: mocks.useTranslation,
}));
-vi.mock("@/react/hooks/useVueState", () => ({
- useVueState: mocks.useVueState,
-}));
-
-vi.mock("@/store", () => ({
- hasFeature: mocks.hasFeature,
+vi.mock("@/react/stores/app", () => ({
+ useAppStore: (
+ selector: (s: { hasFeature: typeof mocks.hasFeature }) => unknown
+ ) => selector({ hasFeature: mocks.hasFeature }),
}));
vi.mock("@/react/hooks/useAppProject", () => ({
@@ -152,7 +149,6 @@ const setupDefaultMocks = (allowJIT = false) => {
};
mocks.useSQLEditorVueState.mockReturnValue({ project: "projects/proj1" });
mocks.hasFeature.mockReturnValue(true);
- mocks.useVueState.mockImplementation((getter: () => unknown) => getter());
};
beforeEach(async () => {
diff --git a/frontend/src/react/components/sql-editor/MaskingReasonPopover.tsx b/frontend/src/react/components/sql-editor/MaskingReasonPopover.tsx
index a5aebc64c0..f3d2d98fad 100644
--- a/frontend/src/react/components/sql-editor/MaskingReasonPopover.tsx
+++ b/frontend/src/react/components/sql-editor/MaskingReasonPopover.tsx
@@ -8,8 +8,8 @@ import {
PopoverTrigger,
} from "@/react/components/ui/popover";
import { useAppProject } from "@/react/hooks/useAppProject";
+import { useAppStore } from "@/react/stores/app";
import { useSQLEditorEditorState } from "@/react/stores/sqlEditor/editor";
-import { hasFeature } 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";
@@ -32,11 +32,13 @@ export function MaskingReasonPopover({
const projectName = useSQLEditorEditorState((s) => s.project);
const project = useAppProject(projectName);
+ const hasJITFeatureFlag = useAppStore((s) =>
+ s.hasFeature(PlanFeature.FEATURE_JIT)
+ );
const hasJITFeature = useMemo(
- () =>
- !!project?.allowJustInTimeAccess && hasFeature(PlanFeature.FEATURE_JIT),
- [project]
+ () => !!project?.allowJustInTimeAccess && hasJITFeatureFlag,
+ [project, hasJITFeatureFlag]
);
const targets = useMemo(() => (database ? [database] : []), [database]);
diff --git a/frontend/src/react/components/sql-editor/OpenAIButton.test.tsx b/frontend/src/react/components/sql-editor/OpenAIButton.test.tsx
index faef2e88e7..32317067fc 100644
--- a/frontend/src/react/components/sql-editor/OpenAIButton.test.tsx
+++ b/frontend/src/react/components/sql-editor/OpenAIButton.test.tsx
@@ -23,6 +23,11 @@ const mocks = vi.hoisted(() => ({
mocks.state.showAIPanel = v;
}),
useSettingV1Store: vi.fn(),
+ // App-store AI setting + fetch — the component reads
+ // `useAppStore((s) => s.getSettingByName(AI))` for the enabled state and
+ // `useAppStore((s) => s.getOrFetchSettingByName)` in an effect.
+ aiSetting: undefined as unknown,
+ getOrFetchSettingByName: vi.fn().mockResolvedValue(undefined),
useConnectionOfCurrentSQLEditorTab: vi.fn(),
hasWorkspacePermissionV2: vi.fn(() => true),
nextAnimationFrame: vi.fn(() => Promise.resolve()),
@@ -44,6 +49,14 @@ vi.mock("@/store", () => ({
useSettingV1Store: mocks.useSettingV1Store,
}));
+vi.mock("@/react/stores/app", () => ({
+ useAppStore: (selector: (s: unknown) => unknown) =>
+ selector({
+ getOrFetchSettingByName: mocks.getOrFetchSettingByName,
+ getSettingByName: () => mocks.aiSetting,
+ }),
+}));
+
// `useConnectionOfCurrentSQLEditorTab` now lives on the Pinia bridge hook.
vi.mock("@/react/hooks/useSQLEditorBridge", () => ({
useConnectionOfCurrentSQLEditorTab: mocks.useConnectionOfCurrentSQLEditorTab,
@@ -220,22 +233,18 @@ const setupDefaultMocks = (overrides: Partial<VueStateValues> = {}) => {
mocks.tabState.isDisconnected = values.isDisconnected;
mocks.tabState.currentMode = values.currentMode;
- const settingStore = {
- getOrFetchSettingByName: vi.fn().mockResolvedValue(undefined),
- getSettingByName: vi.fn(),
- };
+ // `openAIEnabled` is derived from the app-store AI setting in the
+ // component (`s.getSettingByName(AI)` → `.value.value.case === "ai"
+ // ? .enabled : false`). Build a setting whose shape matches the
+ // configured value.
+ mocks.aiSetting = values.openAIEnabled
+ ? { value: { value: { case: "ai", value: { enabled: true } } } }
+ : undefined;
- mocks.useSettingV1Store.mockReturnValue(settingStore);
// Migrated hook returns PLAIN values — no Vue `.value` wrapper.
mocks.useConnectionOfCurrentSQLEditorTab.mockReturnValue({
instance: values.instance,
});
-
- // `openAIEnabled` is resolved via the Pinia bridge getter; surface the
- // configured value directly (it's the only bridge read in OpenAIButton).
- mocks.usePiniaBridge.mockImplementation(() => values.openAIEnabled);
-
- return { settingStore };
};
beforeEach(async () => {
diff --git a/frontend/src/react/components/sql-editor/OpenAIButton.tsx b/frontend/src/react/components/sql-editor/OpenAIButton.tsx
index 8a2e44b7da..8acc81791b 100644
--- a/frontend/src/react/components/sql-editor/OpenAIButton.tsx
+++ b/frontend/src/react/components/sql-editor/OpenAIButton.tsx
@@ -15,9 +15,9 @@ import {
PopoverContent,
PopoverTrigger,
} from "@/react/components/ui/popover";
-import { usePiniaBridge } from "@/react/hooks/usePiniaBridge";
import { useConnectionOfCurrentSQLEditorTab } from "@/react/hooks/useSQLEditorBridge";
import { cn } from "@/react/lib/utils";
+import { useAppStore } from "@/react/stores/app";
import { useSQLEditorStore } from "@/react/stores/sqlEditor";
import {
useIsDisconnected,
@@ -25,7 +25,6 @@ import {
} from "@/react/stores/sqlEditor/tab";
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";
@@ -52,23 +51,20 @@ export function OpenAIButton({ actions, statement, size = "default" }: Props) {
const { t } = useTranslation();
const showAIPanel = useSQLEditorStore((s) => s.showAIPanel);
const setShowAIPanel = useSQLEditorStore((s) => s.setShowAIPanel);
- const settingV1Store = useSettingV1Store();
+ const getOrFetchSettingByName = useAppStore((s) => s.getOrFetchSettingByName);
const { instance } = useConnectionOfCurrentSQLEditorTab();
// Make sure the AI setting is resolved before we gate the enabled state.
useEffect(() => {
- void settingV1Store.getOrFetchSettingByName(
- Setting_SettingName.AI,
- true /* silent */
- );
- }, [settingV1Store]);
+ void getOrFetchSettingByName(Setting_SettingName.AI, true /* silent */);
+ }, [getOrFetchSettingByName]);
const isDisconnected = useIsDisconnected();
const currentMode = useSQLEditorTabState(
(s) => s.tabsById.get(s.currentTabId)?.mode
);
- const openAIEnabled = usePiniaBridge(() => {
- const setting = settingV1Store.getSettingByName(Setting_SettingName.AI);
+ const openAIEnabled = useAppStore((s) => {
+ const setting = s.getSettingByName(Setting_SettingName.AI);
return setting?.value?.value?.case === "ai"
? setting.value.value.value.enabled
: false;
diff --git a/frontend/src/react/components/sql-editor/Panels/common/useAIActions.ts b/frontend/src/react/components/sql-editor/Panels/common/useAIActions.ts
index 7454656b2e..d5c0413e81 100644
--- a/frontend/src/react/components/sql-editor/Panels/common/useAIActions.ts
+++ b/frontend/src/react/components/sql-editor/Panels/common/useAIActions.ts
@@ -2,8 +2,7 @@ import type * as monaco from "monaco-editor";
import { useEffect } from "react";
import type { ChatAction } from "@/plugins/ai/types";
import type { MonacoModule } from "@/react/components/monaco/types";
-import { usePiniaBridge } from "@/react/hooks/usePiniaBridge";
-import { useSettingV1Store } from "@/store";
+import { useAppStore } from "@/react/stores/app";
import { Setting_SettingName } from "@/types/proto-es/v1/setting_service_pb";
interface UseAIActionsOptions {
@@ -29,17 +28,21 @@ export function useAIActions({
actions,
callback,
}: UseAIActionsOptions) {
- const settingStore = useSettingV1Store();
- // Subscribe to the Pinia setting so the registered Monaco actions
- // re-register or unregister live when an admin toggles AI access
- // while the editor is mounted (matches the Vue `watchEffect` behavior
- // in `editor-actions.ts`).
- const aiEnabled = usePiniaBridge(() => readEnabled(settingStore));
- // Defensive fetch — the global `ProvideAIContext.vue` triggers this
- // on app mount, but a deep-link to a code panel can race that.
+ const getOrFetchSettingByName = useAppStore((s) => s.getOrFetchSettingByName);
+ // Subscribe to the AI setting so the registered Monaco actions re-register
+ // or unregister live when an admin toggles AI access while the editor is
+ // mounted (matches the Vue `watchEffect` behavior in `editor-actions.ts`).
+ const aiEnabled = useAppStore((s) => {
+ const setting = s.getSettingByName(Setting_SettingName.AI);
+ return setting?.value?.value?.case === "ai"
+ ? (setting.value.value.value.enabled ?? false)
+ : false;
+ });
+ // Defensive fetch — the SQL editor route doesn't load the AI setting at
+ // bootstrap, and a deep-link to a code panel can land here first.
useEffect(() => {
- void settingStore.getOrFetchSettingByName(Setting_SettingName.AI, true);
- }, [settingStore]);
+ void getOrFetchSettingByName(Setting_SettingName.AI, true);
+ }, [getOrFetchSettingByName]);
useEffect(() => {
if (!monaco || !editor || !aiEnabled) return;
@@ -121,13 +124,3 @@ export function useAIActions({
};
}, [monaco, editor, aiEnabled, actions, callback]);
}
-
-function readEnabled(
- settingStore: ReturnType<typeof useSettingV1Store>
-): boolean {
- const setting = settingStore.getSettingByName(Setting_SettingName.AI);
- if (setting?.value?.value?.case === "ai") {
- return setting.value.value.value.enabled ?? false;
- }
- return false;
-}
diff --git a/frontend/src/react/components/sql-editor/RequestQueryButton.test.tsx b/frontend/src/react/components/sql-editor/RequestQueryButton.test.tsx
index 11ae59de4d..163e9933ad 100644
--- a/frontend/src/react/components/sql-editor/RequestQueryButton.test.tsx
+++ b/frontend/src/react/components/sql-editor/RequestQueryButton.test.tsx
@@ -9,7 +9,6 @@ import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
const mocks = vi.hoisted(() => ({
useTranslation: vi.fn(() => ({ t: (key: string) => key })),
- useVueState: vi.fn<(getter: () => unknown) => unknown>(),
projectData: {
name: "projects/proj1",
allowJustInTimeAccess: false,
@@ -36,10 +35,6 @@ vi.mock("react-i18next", () => ({
useTranslation: mocks.useTranslation,
}));
-vi.mock("@/react/hooks/useVueState", () => ({
- useVueState: mocks.useVueState,
-}));
-
vi.mock("@/store", () => ({
useSubscriptionV1Store: mocks.useSubscriptionV1Store,
hasFeature: mocks.hasFeature,
@@ -205,7 +200,6 @@ const setupDefaultMocks = (allowJIT = false, allowRequestRole = true) => {
mocks.useSQLEditorVueState.mockReturnValue({ project: "projects/proj1" });
mocks.hasInstanceFeature.mockReturnValue(false);
mocks.appHasFeature.mockReturnValue(true);
- mocks.useVueState.mockImplementation((getter: () => unknown) => getter());
};
beforeEach(async () => {
diff --git a/frontend/src/react/components/sql-editor/RequestQueryButton.tsx b/frontend/src/react/components/sql-editor/RequestQueryButton.tsx
index 838290cf7f..d1ed1bfd0a 100644
--- a/frontend/src/react/components/sql-editor/RequestQueryButton.tsx
+++ b/frontend/src/react/components/sql-editor/RequestQueryButton.tsx
@@ -5,7 +5,6 @@ import { FeatureBadge } from "@/react/components/FeatureBadge";
import { PermissionGuard } from "@/react/components/PermissionGuard";
import { Button } from "@/react/components/ui/button";
import { useAppProject } from "@/react/hooks/useAppProject";
-import { usePiniaBridge } from "@/react/hooks/usePiniaBridge";
import { cn } from "@/react/lib/utils";
import { RequestRoleSheet } from "@/react/pages/settings/RequestRoleSheet";
import { useAppStore } from "@/react/stores/app";
@@ -90,12 +89,14 @@ export function RequestQueryButton({
const hasCustomRoleFeature = useAppStore((s) =>
s.hasInstanceFeature(PlanFeature.FEATURE_CUSTOM_ROLES)
);
- const defaultQueryRole = usePiniaBridge(() =>
- getDefaultQueryRole(
- roleList,
- permissionDeniedDetail.requiredPermissions,
- hasCustomRoleFeature
- )
+ const defaultQueryRole = useMemo(
+ () =>
+ getDefaultQueryRole(
+ roleList,
+ permissionDeniedDetail.requiredPermissions,
+ hasCustomRoleFeature
+ ),
+ [roleList, permissionDeniedDetail.requiredPermissions, hasCustomRoleFeature]
);
const useJIT = useMemo(
diff --git a/frontend/src/react/components/sql-editor/ResultPanel/BatchQuerySelect.tsx b/frontend/src/react/components/sql-editor/ResultPanel/BatchQuerySelect.tsx
index a145c0b458..6ca0447ce1 100644
--- a/frontend/src/react/components/sql-editor/ResultPanel/BatchQuerySelect.tsx
+++ b/frontend/src/react/components/sql-editor/ResultPanel/BatchQuerySelect.tsx
@@ -22,7 +22,6 @@ import {
useCurrentSQLEditorTab,
useSQLEditorTabState,
} from "@/react/stores/sqlEditor/tab";
-import { pushNotification, useSQLStore } from "@/store";
import { isValidDatabaseName } from "@/types";
import { ExportFormat } from "@/types/proto-es/v1/common_pb";
import type { Database } from "@/types/proto-es/v1/database_service_pb";
@@ -84,7 +83,7 @@ export function BatchQuerySelect({
}: Props) {
const { t } = useTranslation();
const getDatabaseByName = useAppStore((s) => s.getDatabaseByName);
- const sqlStore = useSQLStore();
+ const exportData = useAppStore((s) => s.exportData);
const currentTab = useCurrentSQLEditorTab();
const project = useSQLEditorEditorState((s) => s.project);
const queryDataPolicy = useSQLEditorQueryDataPolicy(project);
@@ -250,7 +249,7 @@ export function BatchQuerySelect({
// Skip stub-database returns with a WARN toast so the user
// knows their selection became stale (tab torn down mid-export).
if (!isValidDatabaseName(database.name)) {
- pushNotification({
+ useAppStore.getState().notify({
module: "bytebase",
style: "WARN",
title: t("sql-editor.batch-export.failed-for-db", {
@@ -268,7 +267,7 @@ export function BatchQuerySelect({
resultSet?.error ||
resultSet?.results.find((r) => r.error)?.error;
if (resultError) {
- pushNotification({
+ useAppStore.getState().notify({
module: "bytebase",
style: "CRITICAL",
title: t("sql-editor.batch-export.failed-for-db", {
@@ -290,7 +289,7 @@ export function BatchQuerySelect({
options.limit > r.rows.length
)
) {
- pushNotification({
+ useAppStore.getState().notify({
module: "bytebase",
style: "WARN",
title: t("sql-editor.batch-export.failed-for-db", {
@@ -350,7 +349,7 @@ export function BatchQuerySelect({
const context = head(tab?.databaseQueryContexts?.get(databaseName));
if (!context) continue;
try {
- const content = await sqlStore.exportData(
+ const content = await exportData(
create(ExportRequestSchema, {
name: databaseName,
...(context.params.connection.dataSourceId
@@ -371,7 +370,7 @@ export function BatchQuerySelect({
}.${dayjs(new Date()).format("YYYY-MM-DDTHH-mm-ss")}.zip`,
});
} catch (e) {
- pushNotification({
+ useAppStore.getState().notify({
module: "bytebase",
style: "CRITICAL",
title: t("sql-editor.batch-export.failed-for-db", {
diff --git a/frontend/src/react/components/sql-editor/ResultView/ResultView.tsx b/frontend/src/react/components/sql-editor/ResultView/ResultView.tsx
index 25b03fe1bc..086bc194d4 100644
--- a/frontend/src/react/components/sql-editor/ResultView/ResultView.tsx
+++ b/frontend/src/react/components/sql-editor/ResultView/ResultView.tsx
@@ -2,7 +2,7 @@ import { create } from "@bufbuild/protobuf";
import { ConnectError } from "@connectrpc/connect";
import dayjs from "dayjs";
import { InfoIcon, LoaderCircle } from "lucide-react";
-import { type ReactNode, useMemo, useState } from "react";
+import { type ReactNode, useEffect, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import {
DataExportButton,
@@ -23,8 +23,7 @@ import { cn } from "@/react/lib/utils";
import { useAppStore } from "@/react/stores/app";
import { useSQLEditorEditorState } from "@/react/stores/sqlEditor/editor";
import { getSQLEditorTabsState } from "@/react/stores/sqlEditor/tab";
-import { pushNotification, useDBSchemaV1Store, useSQLStore } from "@/store";
-import { usePolicyV1Store } from "@/store/modules/v1/policy";
+import { useDBSchemaV1Store } from "@/store";
import type { SQLEditorQueryParams, SQLResultSetV1 } from "@/types";
import { isValidDatabaseName } from "@/types";
import {
@@ -32,6 +31,7 @@ import {
type PermissionDeniedDetail,
} from "@/types/proto-es/v1/common_pb";
import type { Database } from "@/types/proto-es/v1/database_service_pb";
+import { PolicyType } from "@/types/proto-es/v1/org_policy_service_pb";
import { ExportRequestSchema } from "@/types/proto-es/v1/sql_service_pb";
import { hasProjectPermissionV2 } from "@/utils/iam/permission";
import { buildDownloadBlob } from "@/utils/sql-download";
@@ -72,9 +72,30 @@ export function ResultView({
dark = false,
}: ResultViewProps) {
const { t } = useTranslation();
- const policyStore = usePolicyV1Store();
const project = useSQLEditorEditorState((s) => s.project);
const queryDataPolicy = useSQLEditorQueryDataPolicy(project);
+ // Env-level data-query policy via the app store. Subscribe to the
+ // derived `QueryDataPolicy` directly — the slice returns a stable empty
+ // singleton when nothing is cached, so this is safe for
+ // `useSyncExternalStore` snapshot comparisons.
+ const environment = database.effectiveEnvironment;
+ const envQueryDataPolicy = useAppStore((s) =>
+ environment ? s.getQueryDataPolicyByParent(environment) : undefined
+ );
+ const getOrFetchPolicyByParentAndType = useAppStore(
+ (s) => s.getOrFetchPolicyByParentAndType
+ );
+ // Settings pages populate the env policy in Pinia, but the SQL editor
+ // route doesn't fetch it on its own — self-fetch so the read above
+ // resolves to a real policy (not the empty fallback) and copy-disable
+ // gates fire even on a fresh editor visit.
+ useEffect(() => {
+ if (!environment) return;
+ void getOrFetchPolicyByParentAndType({
+ parentPath: environment,
+ policyType: PolicyType.DATA_QUERY,
+ });
+ }, [environment, getOrFetchPolicyByParentAndType]);
// The editor's per-execution row limit. A result whose .rows.length
// exactly equals this is probably truncated; fewer rows is probably
// complete. Used by the dev-path export to WARN only when the user's
@@ -113,15 +134,9 @@ export function ResultView({
const disallowCopyingData = useMemo(() => {
if (queryDataPolicy?.disableCopyData) return true;
- const environment = database.effectiveEnvironment;
- if (
- environment &&
- policyStore.getQueryDataPolicyByParent(environment).disableCopyData
- ) {
- return true;
- }
+ if (envQueryDataPolicy?.disableCopyData) return true;
return false;
- }, [queryDataPolicy, database, policyStore]);
+ }, [queryDataPolicy, envQueryDataPolicy]);
const filteredResults = useMemo(() => {
if (!resultSet) return [];
@@ -217,7 +232,7 @@ export function ResultView({
r.rows.length === executedLimit && options.limit > r.rows.length
)
) {
- pushNotification({
+ useAppStore.getState().notify({
module: "bytebase",
style: "WARN",
title: t("sql-editor.batch-export.failed-for-db", {
@@ -271,7 +286,7 @@ export function ResultView({
const admin =
tabsState.tabsById.get(tabsState.currentTabId)?.mode === "ADMIN";
try {
- const content = await useSQLStore().exportData(
+ const content = await useAppStore.getState().exportData(
create(ExportRequestSchema, {
name: database.name,
...(executeParams.connection.dataSourceId
@@ -476,7 +491,7 @@ function SyncDatabaseButton({ database }: { database: Database }) {
database: database.name,
skipCache: true,
});
- pushNotification({
+ useAppStore.getState().notify({
module: "bytebase",
style: "SUCCESS",
title: t(
@@ -485,7 +500,7 @@ function SyncDatabaseButton({ database }: { database: Database }) {
),
});
} catch (error) {
- pushNotification({
+ useAppStore.getState().notify({
module: "bytebase",
style: "CRITICAL",
title: t("db.failed-to-sync-schema-for-database-database-value-name", {
diff --git a/frontend/src/react/components/sql-editor/ResultView/context.tsx b/frontend/src/react/components/sql-editor/ResultView/context.tsx
index 3b7e9a7b6b..216c8c286f 100644
--- a/frontend/src/react/components/sql-editor/ResultView/context.tsx
+++ b/frontend/src/react/components/sql-editor/ResultView/context.tsx
@@ -8,7 +8,7 @@ import {
useState,
} from "react";
import { useTranslation } from "react-i18next";
-import { pushNotification } from "@/store";
+import { useAppStore } from "@/react/stores/app";
import type { RowValue } from "@/types/proto-es/v1/sql_service_pb";
import { isDescendantOf } from "@/utils/dom";
import { extractSQLRowValuePlain } from "@/utils/v1/sql";
@@ -336,7 +336,7 @@ export function SQLResultViewProvider({
setCopying(true);
try {
await navigator.clipboard.writeText(payload);
- pushNotification({
+ useAppStore.getState().notify({
module: "bytebase",
style: "SUCCESS",
title: t("common.copied"),
@@ -344,7 +344,7 @@ export function SQLResultViewProvider({
} catch (err) {
const errors = [t("common.failed")];
if (err instanceof Error) errors.push(err.message);
- pushNotification({
+ useAppStore.getState().notify({
module: "bytebase",
style: "WARN",
title: errors.join(": "),
diff --git a/frontend/src/react/components/sql-editor/SQLEditorLayout.tsx b/frontend/src/react/components/sql-editor/SQLEditorLayout.tsx
index 9b14174442..085def06a3 100644
--- a/frontend/src/react/components/sql-editor/SQLEditorLayout.tsx
+++ b/frontend/src/react/components/sql-editor/SQLEditorLayout.tsx
@@ -2,7 +2,6 @@ import { useEffect, useState } from "react";
import { BannersWrapper } from "@/react/components/BannersWrapper";
import { useAppStore } from "@/react/stores/app";
import { router } from "@/router";
-import { 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";
@@ -24,8 +23,10 @@ import { useSQLEditorAutoSave } from "./useSQLEditorAutoSave";
* - the `<SQLEditorRouteShell>` once `ready` flips true.
*/
export function SQLEditorLayout() {
- const settingStore = useSettingV1Store();
+ const getOrFetchSettingByName = useAppStore((s) => s.getOrFetchSettingByName);
const loadEnvironmentList = useAppStore((s) => s.loadEnvironmentList);
+ const loadServerInfo = useAppStore((s) => s.loadServerInfo);
+ const loadCurrentUser = useAppStore((s) => s.loadCurrentUser);
// 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
@@ -39,17 +40,22 @@ export function SQLEditorLayout() {
void (async () => {
await router.isReady();
await Promise.all([
- settingStore.getOrFetchSettingByName(
- Setting_SettingName.WORKSPACE_PROFILE
- ),
+ getOrFetchSettingByName(Setting_SettingName.WORKSPACE_PROFILE),
loadEnvironmentList(),
+ loadServerInfo(),
+ loadCurrentUser(),
]);
if (!cancelled) setReady(true);
})();
return () => {
cancelled = true;
};
- }, [settingStore, loadEnvironmentList]);
+ }, [
+ getOrFetchSettingByName,
+ loadEnvironmentList,
+ loadServerInfo,
+ loadCurrentUser,
+ ]);
useSQLEditorAutoSave();
diff --git a/frontend/src/react/components/sql-editor/SQLEditorRouteShell.tsx b/frontend/src/react/components/sql-editor/SQLEditorRouteShell.tsx
index 267ee0f213..ca20e78f17 100644
--- a/frontend/src/react/components/sql-editor/SQLEditorRouteShell.tsx
+++ b/frontend/src/react/components/sql-editor/SQLEditorRouteShell.tsx
@@ -28,7 +28,6 @@ import {
SQL_EDITOR_PROJECT_MODULE,
SQL_EDITOR_WORKSHEET_MODULE,
} from "@/router/sqlEditor";
-import { pushNotification, useActuatorV1Store } from "@/store";
import { migrateLegacyCache } from "@/store/modules/sqlEditor/legacy/migration";
import {
DEFAULT_SQL_EDITOR_TAB_MODE,
@@ -101,7 +100,6 @@ export function SQLEditorRouteShell() {
const { t } = useTranslation();
const navigate = useNavigate();
const route = useCurrentRoute();
- const actuatorStore = useActuatorV1Store();
const setAsidePanelTab = useSQLEditorStore((s) => s.setAsidePanelTab);
const maybeSwitchProject = useSQLEditorStore((s) => s.maybeSwitchProject);
@@ -150,7 +148,9 @@ export function SQLEditorRouteShell() {
pageToken: "",
});
return (
- head(projects)?.name ?? actuatorStore.serverInfo?.defaultProject ?? ""
+ head(projects)?.name ??
+ useAppStore.getState().serverInfo?.defaultProject ??
+ ""
);
};
@@ -197,7 +197,7 @@ export function SQLEditorRouteShell() {
return false;
}
if (!isWorksheetReadableV1(sheet)) {
- pushNotification({
+ useAppStore.getState().notify({
module: "bytebase",
style: "CRITICAL",
title: t("common.access-denied"),
diff --git a/frontend/src/react/components/sql-editor/SchemaChooser.test.tsx b/frontend/src/react/components/sql-editor/SchemaChooser.test.tsx
index 0de5d3294c..27aeb01a9b 100644
--- a/frontend/src/react/components/sql-editor/SchemaChooser.test.tsx
+++ b/frontend/src/react/components/sql-editor/SchemaChooser.test.tsx
@@ -20,6 +20,7 @@ const mocks = vi.hoisted(() => ({
instanceAllowsSchemaScopedQuery: vi.fn(),
router: {
currentRoute: { value: { query: {} } },
+ afterEach: () => () => {},
},
}));
diff --git a/frontend/src/react/components/sql-editor/SchemaChooser.tsx b/frontend/src/react/components/sql-editor/SchemaChooser.tsx
index d45323dded..cf60155918 100644
--- a/frontend/src/react/components/sql-editor/SchemaChooser.tsx
+++ b/frontend/src/react/components/sql-editor/SchemaChooser.tsx
@@ -2,11 +2,11 @@ import { useEffect, useMemo } from "react";
import { useTranslation } from "react-i18next";
import { usePiniaBridge } from "@/react/hooks/usePiniaBridge";
import { useConnectionOfCurrentSQLEditorTab } from "@/react/hooks/useSQLEditorBridge";
+import { useVueRoute } from "@/react/hooks/useVueRoute";
import {
getSQLEditorTabsState,
useSQLEditorTabState,
} from "@/react/stores/sqlEditor/tab";
-import { router } from "@/router";
import { useDBSchemaV1Store } from "@/store";
import { instanceAllowsSchemaScopedQuery } from "@/utils";
import { ConnectChooser } from "./ConnectChooser";
@@ -69,9 +69,7 @@ export function SchemaChooser() {
// tracked both `route.query.schema` and `tab.value` (the latter via the
// setter's reactive reads) so that switching to a new tab with the URL
// query still present re-seeded the new tab's connection.schema.
- const queryParam = usePiniaBridge(
- () => router.currentRoute.value.query.schema as string | undefined
- );
+ const queryParam = useVueRoute().query.schema as string | undefined;
const currentTabId = useSQLEditorTabState((s) => s.currentTabId);
useEffect(() => {
if (queryParam) handleChange(queryParam);
diff --git a/frontend/src/react/components/sql-editor/SchemaPane/actions.tsx b/frontend/src/react/components/sql-editor/SchemaPane/actions.tsx
index 6dface349d..a94c36e75a 100644
--- a/frontend/src/react/components/sql-editor/SchemaPane/actions.tsx
+++ b/frontend/src/react/components/sql-editor/SchemaPane/actions.tsx
@@ -22,7 +22,7 @@ import { useAppStore } from "@/react/stores/app";
import { getSQLEditorTabsState } from "@/react/stores/sqlEditor/tab";
import { router } from "@/router";
import { SQL_EDITOR_DATABASE_MODULE } from "@/router/sqlEditor";
-import { pushNotification, useDBSchemaV1Store } from "@/store";
+import { useDBSchemaV1Store } from "@/store";
import {
DEFAULT_SQL_EDITOR_TAB_MODE,
dialectOfEngineV1,
@@ -396,7 +396,7 @@ export function useSchemaPaneContextMenu(
const notify = useCallback(
(key: string) => {
- pushNotification({
+ useAppStore.getState().notify({
module: "bytebase",
style: "SUCCESS",
title: t(key),
diff --git a/frontend/src/react/components/sql-editor/SharePopoverBody.test.tsx b/frontend/src/react/components/sql-editor/SharePopoverBody.test.tsx
index 022279305a..52fdfdc838 100644
--- a/frontend/src/react/components/sql-editor/SharePopoverBody.test.tsx
+++ b/frontend/src/react/components/sql-editor/SharePopoverBody.test.tsx
@@ -10,7 +10,9 @@ import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
const mocks = vi.hoisted(() => ({
useTranslation: vi.fn(() => ({ t: (key: string) => key })),
usePiniaBridge: vi.fn<(getter: () => unknown) => unknown>(),
- useActuatorV1Store: vi.fn(),
+ serverInfo: { externalUrl: "https://example.com" } as
+ | { externalUrl: string }
+ | undefined,
useCurrentUser: vi.fn(),
patchWorksheet: vi.fn().mockResolvedValue({}),
// `useSQLEditorTabState(selector)` runs `selector` against this stub
@@ -36,16 +38,22 @@ vi.mock("@/react/hooks/useAppState", () => ({
useCurrentUser: mocks.useCurrentUser,
}));
-vi.mock("@/store", () => ({
- useActuatorV1Store: mocks.useActuatorV1Store,
- pushNotification: mocks.pushNotification,
-}));
-
-vi.mock("@/react/stores/app", () => ({
- useAppStore: {
- getState: () => ({ patchWorksheet: mocks.patchWorksheet }),
- },
-}));
+vi.mock("@/react/stores/app", () => {
+ // `notify` reuses the `pushNotification` vi.fn so the existing test
+ // assertions on `mocks.pushNotification` keep working after the migration
+ // from the Pinia helper to the app-store notification slice.
+ const state = () => ({
+ serverInfo: mocks.serverInfo,
+ patchWorksheet: mocks.patchWorksheet,
+ notify: mocks.pushNotification,
+ });
+ return {
+ useAppStore: Object.assign(
+ (selector: (s: ReturnType<typeof state>) => unknown) => selector(state()),
+ { getState: state }
+ ),
+ };
+});
vi.mock("@/react/stores/sqlEditor/tab", () => ({
useSQLEditorTabState: (
@@ -135,9 +143,7 @@ beforeEach(async () => {
mocks.useTranslation.mockReturnValue({ t: (key: string) => key });
- mocks.useActuatorV1Store.mockReturnValue({
- serverInfo: { externalUrl: "https://example.com" },
- });
+ mocks.serverInfo = { externalUrl: "https://example.com" };
mocks.useCurrentUser.mockReturnValue({
name: "users/[email protected]",
diff --git a/frontend/src/react/components/sql-editor/SharePopoverBody.tsx b/frontend/src/react/components/sql-editor/SharePopoverBody.tsx
index 21ff8f3089..a9fa2b0dbc 100644
--- a/frontend/src/react/components/sql-editor/SharePopoverBody.tsx
+++ b/frontend/src/react/components/sql-editor/SharePopoverBody.tsx
@@ -14,13 +14,11 @@ import {
PopoverTrigger,
} from "@/react/components/ui/popover";
import { useCurrentUser } from "@/react/hooks/useAppState";
-import { usePiniaBridge } from "@/react/hooks/usePiniaBridge";
import { cn } from "@/react/lib/utils";
import { useAppStore } from "@/react/stores/app";
import { useSQLEditorTabState } from "@/react/stores/sqlEditor/tab";
import { router } from "@/router";
import { SQL_EDITOR_WORKSHEET_MODULE } from "@/router/sqlEditor";
-import { pushNotification, useActuatorV1Store } from "@/store";
import type { Worksheet } from "@/types/proto-es/v1/worksheet_service_pb";
import { Worksheet_Visibility } from "@/types/proto-es/v1/worksheet_service_pb";
import { extractProjectResourceName, extractWorksheetID } from "@/utils";
@@ -42,11 +40,7 @@ type Props = {
*/
export function SharePopoverBody({ worksheet }: Props) {
const { t } = useTranslation();
- const actuatorStore = useActuatorV1Store();
-
- const workspaceExternalURL = usePiniaBridge(
- () => actuatorStore.serverInfo?.externalUrl
- );
+ const workspaceExternalURL = useAppStore((s) => s.serverInfo?.externalUrl);
const currentUser = useCurrentUser();
const tabStatus = useSQLEditorTabState(
(s) => s.tabsById.get(s.currentTabId)?.status
@@ -123,13 +117,13 @@ export function SharePopoverBody({ worksheet }: Props) {
try {
await navigator.clipboard.writeText(sharedTabLink);
- pushNotification({
+ useAppStore.getState().notify({
module: "bytebase",
style: "SUCCESS",
title: t("sql-editor.url-copied-to-clipboard"),
});
} catch {
- pushNotification({
+ useAppStore.getState().notify({
module: "bytebase",
style: "SUCCESS",
title: t("common.updated"),
@@ -145,7 +139,7 @@ export function SharePopoverBody({ worksheet }: Props) {
const handleCopyLink = async () => {
try {
await navigator.clipboard.writeText(sharedTabLink);
- pushNotification({
+ useAppStore.getState().notify({
module: "bytebase",
style: "SUCCESS",
title: t("sql-editor.url-copied-to-clipboard"),
diff --git a/frontend/src/react/components/sql-editor/SheetTree.tsx b/frontend/src/react/components/sql-editor/SheetTree.tsx
index 75016826d5..543837892c 100644
--- a/frontend/src/react/components/sql-editor/SheetTree.tsx
+++ b/frontend/src/react/components/sql-editor/SheetTree.tsx
@@ -59,7 +59,6 @@ import { useAppStore } from "@/react/stores/app";
import { useSQLEditorStore as useSQLEditorReactStore } from "@/react/stores/sqlEditor";
import { useSQLEditorEditorState } from "@/react/stores/sqlEditor/editor";
import { getSQLEditorTabsState } from "@/react/stores/sqlEditor/tab";
-import { pushNotification } from "@/store";
import {
openWorksheetByName,
revealNodes,
@@ -1157,7 +1156,7 @@ export function SheetTree({
folders: worksheet.folders,
database: worksheet.database,
});
- pushNotification({
+ useAppStore.getState().notify({
module: "bytebase",
style: "INFO",
title: t("sheet.notifications.duplicate-success"),
diff --git a/frontend/src/react/components/sql-editor/StandardPanel/FileContentPreviewModal.tsx b/frontend/src/react/components/sql-editor/StandardPanel/FileContentPreviewModal.tsx
index e70f307e54..2e650d25c2 100644
--- a/frontend/src/react/components/sql-editor/StandardPanel/FileContentPreviewModal.tsx
+++ b/frontend/src/react/components/sql-editor/StandardPanel/FileContentPreviewModal.tsx
@@ -15,7 +15,7 @@ import {
SelectTrigger,
SelectValue,
} from "@/react/components/ui/select";
-import { pushNotification } from "@/store";
+import { useAppStore } from "@/react/stores/app";
import { ENCODINGS, type Encoding, readFileAsArrayBuffer } from "@/utils";
interface FileContentPreviewModalProps {
@@ -54,7 +54,7 @@ export function FileContentPreviewModal({
.catch((error) => {
if (cancelled) return;
console.error(error);
- pushNotification({
+ useAppStore.getState().notify({
module: "bytebase",
style: "CRITICAL",
title: "Failed to read file",
diff --git a/frontend/src/react/components/sql-editor/StandardPanel/SQLEditor.tsx b/frontend/src/react/components/sql-editor/StandardPanel/SQLEditor.tsx
index 14321cbf88..89b5f3a579 100644
--- a/frontend/src/react/components/sql-editor/StandardPanel/SQLEditor.tsx
+++ b/frontend/src/react/components/sql-editor/StandardPanel/SQLEditor.tsx
@@ -17,12 +17,12 @@ import {
} from "@/react/components/monaco/utils";
import { useConnectionOfCurrentSQLEditorTab } from "@/react/hooks/useSQLEditorBridge";
import { useWorksheetAndTab } from "@/react/hooks/useWorksheetAndTab";
+import { useAppStore } from "@/react/stores/app";
import { useSQLEditorStore } from "@/react/stores/sqlEditor";
import {
getSQLEditorTabsState,
useSQLEditorTabState,
} from "@/react/stores/sqlEditor/tab";
-import { useUIStateStore } from "@/store";
import {
dialectOfEngineV1,
isValidDatabaseName,
@@ -57,15 +57,15 @@ interface SQLEditorProps {
*
* Listens to `sqlEditorEvents` for `format-content`,
* `set-editor-selection`, `append-editor-content`. The active editor
- * instance is published to `activeSQLEditorRef` (Vue `shallowRef`
- * singleton) so the legacy ResultView's ErrorView keeps working.
+ * instance is published to `activeSQLEditorRef` (plain mutable
+ * singleton) so ResultView's ErrorView "Goto Error" action can
+ * imperatively focus the editor.
*
* Exposes `getActiveStatement` via `useImperativeHandle` so EditorMain
* (parent) can read the active selection or full statement when a query
* is run from the toolbar.
*/
export function SQLEditor({ onExecute }: SQLEditorProps) {
- const uiStateStore = useUIStateStore();
const { isReadOnly: readonly } = useWorksheetAndTab();
const setShowAIPanel = useSQLEditorStore((s) => s.setShowAIPanel);
const setPendingInsertAtCaret = useSQLEditorStore(
@@ -207,12 +207,12 @@ export function SQLEditor({ onExecute }: SQLEditorProps) {
selection: newTab ? null : tab.editorState.selection,
};
onExecuteRef.current(params, newTab);
- uiStateStore.saveIntroStateByKey({
+ useAppStore.getState().saveIntroStateByKey({
key: "data.query",
newState: true,
});
},
- [getActiveStatement, uiStateStore]
+ [getActiveStatement]
);
// ----- onReady: register Monaco actions + commands -----
diff --git a/frontend/src/react/components/sql-editor/StandardPanel/SQLUploadButton.tsx b/frontend/src/react/components/sql-editor/StandardPanel/SQLUploadButton.tsx
index 2c3e6c4999..1c4de2ac23 100644
--- a/frontend/src/react/components/sql-editor/StandardPanel/SQLUploadButton.tsx
+++ b/frontend/src/react/components/sql-editor/StandardPanel/SQLUploadButton.tsx
@@ -3,7 +3,7 @@ import { useCallback, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { Button } from "@/react/components/ui/button";
import { cn } from "@/react/lib/utils";
-import { pushNotification } from "@/store";
+import { useAppStore } from "@/react/stores/app";
import { MAX_UPLOAD_FILE_SIZE_MB } from "@/utils";
import { FileContentPreviewModal } from "./FileContentPreviewModal";
@@ -57,7 +57,7 @@ export function SQLUploadButton({
return;
}
if (file.size > MAX_UPLOAD_FILE_SIZE_MB * 1024 * 1024) {
- pushNotification({
+ useAppStore.getState().notify({
module: "bytebase",
style: "CRITICAL",
title: t("issue.upload-sql-file-max-size-exceeded", {
diff --git a/frontend/src/react/components/sql-editor/StandardPanel/state.ts b/frontend/src/react/components/sql-editor/StandardPanel/state.ts
index 86c4586700..a3d3b4056a 100644
--- a/frontend/src/react/components/sql-editor/StandardPanel/state.ts
+++ b/frontend/src/react/components/sql-editor/StandardPanel/state.ts
@@ -1,14 +1,18 @@
-import { shallowRef } from "vue";
import { type IStandaloneCodeEditor } from "@/react/components/monaco/types";
-export const activeSQLEditorRef = shallowRef<IStandaloneCodeEditor>();
+// Plain mutable holders — only ever read/written imperatively from event
+// handlers (no `watch`, no React subscription), so a `{ value }` object
+// matches every call site's `.value` access without dragging Vue's
+// reactivity system in.
+export const activeSQLEditorRef: { value: IStandaloneCodeEditor | undefined } =
+ {
+ value: undefined,
+ };
/**
- * Tracks the live "active statement" — Monaco's delimited statement
- * under the cursor, or the full editor content as fallback. The React
+ * Tracks the live "active statement" — Monaco's delimited statement under
+ * the cursor, or the full editor content as fallback. The React
* `SQLEditor` writes here via `onActiveContentChange`; the React
- * `EditorMain` reads it when the toolbar's "Run" button is pressed
- * (and Stage 22's still-Vue AI plugin can read it via the same Vue
- * `shallowRef` since the bridge shares Vue's reactivity system).
+ * `EditorMain` reads it when the toolbar's "Run" button is pressed.
*/
-export const activeStatementRef = shallowRef<string>("");
+export const activeStatementRef: { value: string } = { value: "" };
diff --git a/frontend/src/react/components/sql-editor/TabItem/TabItem.tsx b/frontend/src/react/components/sql-editor/TabItem/TabItem.tsx
index c3b7267c3f..7d5ae27552 100644
--- a/frontend/src/react/components/sql-editor/TabItem/TabItem.tsx
+++ b/frontend/src/react/components/sql-editor/TabItem/TabItem.tsx
@@ -1,16 +1,14 @@
import { useSortable } from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
import { useState } from "react";
-import { usePiniaBridge } from "@/react/hooks/usePiniaBridge";
+import { useAppDatabase } from "@/react/hooks/useAppDatabase";
import { cn } from "@/react/lib/utils";
+import { useAppStore } from "@/react/stores/app";
import { useSQLEditorTabState } from "@/react/stores/sqlEditor/tab";
+import { isValidDatabaseName } from "@/types";
import { UNKNOWN_ID } from "@/types/const";
import type { SQLEditorTab } from "@/types/sqlEditor/tab";
-import {
- getConnectionForSQLEditorTab,
- getDatabaseEnvironment,
- hexToRgb,
-} from "@/utils";
+import { hexToRgb } from "@/utils";
import { AdminLabel } from "./AdminLabel";
import { Label } from "./Label";
import { Prefix } from "./Prefix";
@@ -56,15 +54,15 @@ export function TabItem({
const isCurrentTab = tab.id === currentTabId;
// Derive the environment tint (used as the top border on the current tab).
- // Wrapped in `usePiniaBridge` so the tab re-renders when the Pinia
- // database/environment state hydrates async — without this the tab
- // sticks on the fallback `#4f46e5` indigo even after the environment
- // resolves, which is what made the React tabs look more saturated
- // than the Vue version.
- const environmentTintColor = usePiniaBridge(() => {
- const { database } = getConnectionForSQLEditorTab(tab);
- if (!database) return undefined;
- const environment = getDatabaseEnvironment(database);
+ // Subscribes via the app store so the tab re-renders when the database
+ // and its environment hydrate async — without this the tab sticks on
+ // the fallback `#4f46e5` indigo and looks more saturated than intended.
+ const database = useAppDatabase(tab.connection.database ?? "");
+ const environmentTintColor = useAppStore((s) => {
+ if (!isValidDatabaseName(database.name)) return undefined;
+ const environment = s.getEnvironmentByName(
+ database.effectiveEnvironment ?? ""
+ );
if (!environment || environment.id === String(UNKNOWN_ID)) return undefined;
return environment.color || undefined;
});
diff --git a/frontend/src/react/components/sql-editor/Welcome.test.tsx b/frontend/src/react/components/sql-editor/Welcome.test.tsx
index c354267e40..013b431612 100644
--- a/frontend/src/react/components/sql-editor/Welcome.test.tsx
+++ b/frontend/src/react/components/sql-editor/Welcome.test.tsx
@@ -16,7 +16,6 @@ const mocks = vi.hoisted(() => ({
project?: unknown
) => [boolean, string | undefined]
>(),
- useVueState: vi.fn<(getter: () => unknown) => unknown>(),
routerPush: vi.fn(),
projectData: { name: "projects/test" } as { name: string },
}));
@@ -33,10 +32,6 @@ vi.mock("@/react/components/BytebaseLogo", () => ({
BytebaseLogo: () => null,
}));
-vi.mock("@/react/hooks/useVueState", () => ({
- useVueState: mocks.useVueState,
-}));
-
vi.mock("@/react/hooks/useAppProject", () => ({
useAppProject: () => mocks.projectData,
}));
@@ -86,8 +81,7 @@ const renderIntoContainer = (element: ReactElement) => {
beforeEach(async () => {
vi.clearAllMocks();
- // Default: workspace logo empty, both permissions granted.
- mocks.useVueState.mockReturnValue("");
+ // Default: both permissions granted.
mocks.usePermissionCheck.mockReturnValue([true, undefined]);
({ Welcome } = await import("./Welcome"));
});
diff --git a/frontend/src/react/components/sql-editor/useSQLEditorAutoSave.ts b/frontend/src/react/components/sql-editor/useSQLEditorAutoSave.ts
index 6875935368..c571c46655 100644
--- a/frontend/src/react/components/sql-editor/useSQLEditorAutoSave.ts
+++ b/frontend/src/react/components/sql-editor/useSQLEditorAutoSave.ts
@@ -5,7 +5,6 @@ import {
getSQLEditorTabsState,
useSQLEditorTabState,
} from "@/react/stores/sqlEditor/tab";
-import { pushNotification } from "@/store";
import { isWorksheetWritableV1 } from "@/utils";
const AUTO_SAVE_DEBOUNCE_MS = 2000;
@@ -87,7 +86,7 @@ export function useSQLEditorAutoSave() {
if (getSQLEditorTabsState().tabsById.get(tabId)?.status === "SAVING") {
getSQLEditorTabsState().updateTab(tabId, { status: "DIRTY" });
}
- pushNotification({
+ useAppStore.getState().notify({
module: "bytebase",
style: "CRITICAL",
title: "Auto-save failed",
diff --git a/frontend/src/react/hooks/useExecuteSQL.ts b/frontend/src/react/hooks/useExecuteSQL.ts
index 21f004283d..7c3292cd19 100644
--- a/frontend/src/react/hooks/useExecuteSQL.ts
+++ b/frontend/src/react/hooks/useExecuteSQL.ts
@@ -1,7 +1,7 @@
import { create } from "@bufbuild/protobuf";
import { Code } from "@connectrpc/connect";
import { cloneDeep, isEmpty } from "lodash-es";
-import { useCallback, useRef } from "react";
+import { useCallback, useEffect, useRef } from "react";
import { useTranslation } from "react-i18next";
import { v4 as uuidv4 } from "uuid";
import { useAppStore } from "@/react/stores/app";
@@ -11,7 +11,6 @@ import {
getDatabaseQueryContext,
getSQLEditorTabsState,
} from "@/react/stores/sqlEditor/tab";
-import { hasFeature, pushNotification, useSQLStore } from "@/store";
import type {
BBNotificationStyle,
QueryContextStatus,
@@ -46,12 +45,20 @@ const QUERY_INTERVAL_LIMIT = 1000;
export const useExecuteSQL = () => {
const { t } = useTranslation();
const lastQueryTimeRef = useRef<number | undefined>(undefined);
+ // Eagerly fetch the subscription so the batch-query / database-group
+ // gates below see the licensed plan when the user clicks Run. The hook
+ // is mounted by `EditorMain` on every tab open, so this fires once per
+ // tab; `loadSubscription` itself dedupes via an in-flight request.
+ const loadSubscription = useAppStore((s) => s.loadSubscription);
+ useEffect(() => {
+ void loadSubscription();
+ }, [loadSubscription]);
const notify = (
type: BBNotificationStyle,
title: string,
description?: string
) => {
- pushNotification({
+ useAppStore.getState().notify({
module: "bytebase",
style: type,
title,
@@ -173,9 +180,10 @@ export const useExecuteSQL = () => {
]);
// Check if the user selects multiple databases to query.
+ const appStore = useAppStore.getState();
if (
freshTab.batchQueryContext &&
- hasFeature(PlanFeature.FEATURE_BATCH_QUERY)
+ appStore.hasFeature(PlanFeature.FEATURE_BATCH_QUERY)
) {
const { databases = [], databaseGroups = [] } =
freshTab.batchQueryContext;
@@ -189,7 +197,7 @@ export const useExecuteSQL = () => {
batchQueryDatabaseSet.add(databaseResourceName);
}
- if (hasFeature(PlanFeature.FEATURE_DATABASE_GROUPS)) {
+ if (appStore.hasFeature(PlanFeature.FEATURE_DATABASE_GROUPS)) {
for (const databaseGroupName of databaseGroups) {
try {
const databaseGroup = await useAppStore
@@ -324,7 +332,6 @@ export const useExecuteSQL = () => {
if (!abortController) {
return;
}
- const sqlStore = useSQLStore();
const dataSourceId = context.params.connection.dataSourceId;
@@ -343,7 +350,7 @@ export const useExecuteSQL = () => {
...(context.params.queryOption ?? ({} as QueryOption)),
redisRunCommandsOn: editorState.redisCommandOption,
});
- const resultSet = await sqlStore.query(
+ const resultSet = await useAppStore.getState().query(
create(QueryRequestSchema, {
name: database.name,
...(dataSourceId ? { dataSourceId } : {}),
diff --git a/frontend/src/react/hooks/useSQLEditorBridge.ts b/frontend/src/react/hooks/useSQLEditorBridge.ts
index 64441f89fe..4309f65cd0 100644
--- a/frontend/src/react/hooks/useSQLEditorBridge.ts
+++ b/frontend/src/react/hooks/useSQLEditorBridge.ts
@@ -1,130 +1,112 @@
-import { useEffect } from "react";
-import { effectScope, unref } from "vue";
+import { useEffect, useMemo } from "react";
+import { useAppDatabase } from "@/react/hooks/useAppDatabase";
import { useAppStore } from "@/react/stores/app";
import {
getSQLEditorEditorState,
useSQLEditorEditorState,
} from "@/react/stores/sqlEditor/editor";
import { useSQLEditorTabsStore } from "@/react/stores/sqlEditor/tab";
-import { featureToRef } from "@/store";
-import { useDatabaseV1ByName } from "@/store/modules/v1/database";
-import { useQueryDataPolicy } from "@/store/modules/v1/policy";
import type { SQLEditorConnection } from "@/types";
import { isValidDatabaseName, isValidProjectName } 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 {
+ PolicyType,
+ type QueryDataPolicy,
+} from "@/types/proto-es/v1/org_policy_service_pb";
import type { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";
import type { Environment } from "@/types/v1/environment";
-import {
- getDatabaseEnvironment,
- getInstanceResource,
- hasProjectPermissionV2,
- hasWorkspacePermissionV2,
-} from "@/utils";
-import { useVueState } from "./useVueState";
-
-/**
- * Module-level caches for Vue composables that create persistent
- * `watch` / `watchEffect` / `computed` / `ref` instances. Calling
- * these composables directly inside React render bodies would leak a
- * fresh Vue effect on every render — and the immediate-mode watch
- * inside `useDatabaseV1ByName` / `useQueryDataPolicy` would refetch
- * synchronously, mutate Pinia state, trigger our `useVueState` to
- * re-render, and create yet another effect... an infinite loop.
- *
- * Caching by argument value runs the composable exactly once per
- * unique input; subsequent renders reuse the same refs. A detached
- * `effectScope` keeps the Vue effects alive for the app's lifetime.
- */
-const policyScopeCache = new Map<
- string,
- ReturnType<typeof useQueryDataPolicy>
->();
-
-const getCachedQueryDataPolicy = (project: string) => {
- let cached = policyScopeCache.get(project);
- if (!cached) {
- const scope = effectScope(true);
- cached = scope.run(() => useQueryDataPolicy(project))!;
- policyScopeCache.set(project, cached);
- }
- return cached;
-};
-
-const databaseScopeCache = new Map<
- string,
- ReturnType<typeof useDatabaseV1ByName>
->();
-
-const getCachedDatabaseV1ByName = (name: string) => {
- let cached = databaseScopeCache.get(name);
- if (!cached) {
- const scope = effectScope(true);
- cached = scope.run(() => useDatabaseV1ByName(name))!;
- databaseScopeCache.set(name, cached);
- }
- return cached;
-};
-
-// `featureToRef` returns a fresh `computed()` per call. Calling it
-// directly inside a React render (e.g. `usePiniaBridge(() =>
-// featureToRef(X).value)`) leaks an orphaned computed on every render —
-// each stays subscribed to the subscription store, so a plan change
-// re-evaluates an ever-growing pile of dead computeds. Cache one
-// computed per feature in a detached scope.
-const featureRefCache = new Map<PlanFeature, ReturnType<typeof featureToRef>>();
-
-const getCachedFeatureRef = (feature: PlanFeature) => {
- let cached = featureRefCache.get(feature);
- if (!cached) {
- const scope = effectScope(true);
- cached = scope.run(() => featureToRef(feature))!;
- featureRefCache.set(feature, cached);
- }
- return cached;
-};
+import { getDatabaseEnvironment, getInstanceResource } from "@/utils";
/**
* React access to a workspace-level plan feature flag. Re-renders when
* the subscription plan changes. (For instance-scoped features pass the
* instance through a dedicated hook — none of the SQL editor's current
* gates are instance-scoped.)
+ *
+ * Self-loads the subscription so SQL editor gates don't silently fall
+ * back to FREE on first render. Mirrors `usePlanFeature` — without this
+ * the hook would depend on an unrelated ancestor (e.g. `Watermark`)
+ * having already triggered `loadSubscription`.
*/
export const useSQLEditorFeature = (feature: PlanFeature): boolean => {
- const ref = getCachedFeatureRef(feature);
- return useVueState(() => unref(ref));
+ const loadSubscription = useAppStore((s) => s.loadSubscription);
+ useEffect(() => {
+ void loadSubscription();
+ }, [loadSubscription]);
+ return useAppStore((s) => s.hasFeature(feature));
};
-/**
- * React-native bridges over the SQL editor's Pinia dependencies. These
- * hooks live in `react/hooks/` so the migration acceptance grep on
- * `react/components/sql-editor/**` and `react/stores/sqlEditor/**`
- * stays empty of `useVueState` calls — components import from here
- * instead of bridging Pinia inline.
- */
+// Mirrors the Pinia `formatQueryDataPolicy` helper: normalizes
+// `maximumResultRows` so `-1`/`0` (= unlimited) becomes `Number.MAX_VALUE`,
+// which lets `Math.min` collapse the workspace/project merge cleanly.
+type FormattedQueryDataPolicy = {
+ disableCopyData: boolean;
+ disableExport: boolean;
+ allowAdminDataSource: boolean;
+ maximumResultRows: number;
+};
-type FormattedQueryDataPolicy = ReturnType<
- typeof useQueryDataPolicy
->["policy"] extends { value: infer V }
- ? V
- : never;
+const formatQueryDataPolicy = (
+ policy: QueryDataPolicy | undefined
+): FormattedQueryDataPolicy => {
+ const max = policy?.maximumResultRows ?? -1;
+ return {
+ disableCopyData: policy?.disableCopyData ?? false,
+ disableExport: policy?.disableExport ?? false,
+ allowAdminDataSource: policy?.allowAdminDataSource ?? false,
+ maximumResultRows: max <= 0 ? Number.MAX_VALUE : max,
+ };
+};
/**
- * React access to the active project's QueryDataPolicy. Returns the
- * formatted policy shape exposed by `useQueryDataPolicy` — a merged
- * workspace + project policy view, not the raw proto.
+ * React access to the active project's QueryDataPolicy. Mirrors the
+ * legacy Pinia `useQueryDataPolicy`: fetches the workspace-level and
+ * project-level DATA_QUERY policies and merges them — the project's
+ * `maximumResultRows` only wins when it's tighter than the workspace cap.
*/
export const useSQLEditorQueryDataPolicy = (
project: string
): FormattedQueryDataPolicy => {
- const { policy } = getCachedQueryDataPolicy(project);
- // `getCachedQueryDataPolicy` returns a per-project cached ref; the
- // project changes via Zustand (invisible to Vue's watch), so without
- // `deps` the subscription stays on the previous project's policy and
- // misses the new project's async fetch. Re-subscribe on `project`.
- return useVueState(() => unref(policy), {
- deps: [project],
- }) as FormattedQueryDataPolicy;
+ const workspaceResourceName = useAppStore((s) => s.workspaceResourceName());
+ const workspacePolicy = useAppStore((s) =>
+ workspaceResourceName
+ ? s.getQueryDataPolicyByParent(workspaceResourceName)
+ : undefined
+ );
+ const projectPolicy = useAppStore((s) =>
+ project ? s.getQueryDataPolicyByParent(project) : undefined
+ );
+ const getOrFetchPolicyByParentAndType = useAppStore(
+ (s) => s.getOrFetchPolicyByParentAndType
+ );
+
+ // Self-fetch both policies. The SQL editor route doesn't load org
+ // policies on its own; the Pinia version's `watchEffect` did this
+ // implicitly via the cached scope.
+ useEffect(() => {
+ if (!workspaceResourceName) return;
+ void getOrFetchPolicyByParentAndType({
+ parentPath: workspaceResourceName,
+ policyType: PolicyType.DATA_QUERY,
+ });
+ }, [workspaceResourceName, getOrFetchPolicyByParentAndType]);
+ useEffect(() => {
+ if (!project) return;
+ void getOrFetchPolicyByParentAndType({
+ parentPath: project,
+ policyType: PolicyType.DATA_QUERY,
+ });
+ }, [project, getOrFetchPolicyByParentAndType]);
+
+ return useMemo(() => {
+ const ws = formatQueryDataPolicy(workspacePolicy);
+ const proj = formatQueryDataPolicy(projectPolicy);
+ return {
+ ...ws,
+ maximumResultRows: Math.min(ws.maximumResultRows, proj.maximumResultRows),
+ };
+ }, [workspacePolicy, projectPolicy]);
};
/**
@@ -136,15 +118,13 @@ export const useSQLEditorQueryDataPolicy = (
* is no re-render loop.
*/
export const useClampResultRowsLimitToPolicy = (project: string): void => {
- const { policy } = getCachedQueryDataPolicy(project);
- const maximumResultRows = useVueState(() => unref(policy).maximumResultRows, {
- deps: [project],
- });
+ const { maximumResultRows } = useSQLEditorQueryDataPolicy(project);
const resultRowsLimit = useSQLEditorEditorState((s) => s.resultRowsLimit);
useEffect(() => {
if (
typeof maximumResultRows === "number" &&
maximumResultRows > 0 &&
+ maximumResultRows < Number.MAX_VALUE &&
resultRowsLimit > maximumResultRows
) {
getSQLEditorEditorState().setResultRowsLimit(maximumResultRows);
@@ -154,22 +134,20 @@ export const useClampResultRowsLimitToPolicy = (project: string): void => {
/**
* React access to "can the current user run admin SQL against this
- * project?". Reads project IAM via Pinia.
+ * project?". Self-fetches the project + its IAM policy so the SQL editor
+ * route (which doesn't preload either) gets a correct answer once both
+ * resolve.
*/
export const useSQLEditorAllowAdmin = (project: string): boolean => {
- const getProjectByName = useAppStore((s) => s.getProjectByName);
const fetchProject = useAppStore((s) => s.fetchProject);
- // Re-subscribe the IAM watch once the project resolves in the app store
- // (a non-Vue signal the watch can't track on its own).
- const cachedProject = useAppStore((s) => s.projectsByName[project]);
+ const loadProjectIamPolicy = useAppStore((s) => s.loadProjectIamPolicy);
useEffect(() => {
- if (isValidProjectName(project)) {
- void fetchProject(project);
- }
- }, [fetchProject, project]);
- return useVueState(
- () => hasProjectPermissionV2(getProjectByName(project), "bb.sql.admin"),
- { deps: [project, cachedProject] }
+ if (!isValidProjectName(project)) return;
+ void fetchProject(project);
+ void loadProjectIamPolicy(project);
+ }, [fetchProject, loadProjectIamPolicy, project]);
+ return useAppStore((s) =>
+ s.hasProjectPermission(s.getProjectByName(project), "bb.sql.admin")
);
};
@@ -177,7 +155,13 @@ export const useSQLEditorAllowAdmin = (project: string): boolean => {
* React access to the workspace-wide "list projects" permission.
*/
export const useSQLEditorAllowViewAllProjects = (): boolean => {
- return useVueState(() => hasWorkspacePermissionV2("bb.projects.list"));
+ const loadWorkspacePermissionState = useAppStore(
+ (s) => s.loadWorkspacePermissionState
+ );
+ useEffect(() => {
+ void loadWorkspacePermissionState();
+ }, [loadWorkspacePermissionState]);
+ return useAppStore((s) => s.hasWorkspacePermission("bb.projects.list"));
};
/**
@@ -195,36 +179,16 @@ export interface SQLEditorConnectionDetail {
export const useSQLEditorConnection = (
connection: SQLEditorConnection
): SQLEditorConnectionDetail => {
- const { database } = getCachedDatabaseV1ByName(connection.database);
- // `getCachedDatabaseV1ByName` returns a DIFFERENT cached Vue ref when
- // `connection.database` changes (e.g. a tab switch to an uncached
- // database). The database name arrives via Zustand, which Vue's watch
- // can't observe, so without `deps` each watch stays attached to the
- // first render's ref — leaving stale/placeholder values and missing
- // the async cache hydration of the new database. Re-subscribe on the
- // database name so the watches track the current ref.
- const databaseValue = useVueState(() => unref(database), {
- deps: [connection.database],
- });
-
- const instance = useVueState(() => getInstanceResource(unref(database)), {
- deps: [connection.database],
- });
-
- const environment = useVueState(
- () => {
- const db = unref(database);
- if (isValidDatabaseName(db.name)) {
- return getDatabaseEnvironment(db);
- }
- return useAppStore
- .getState()
- .getEnvironmentByName(instance.environment ?? "");
- },
- { deps: [connection.database] }
- );
-
- return { connection, database: databaseValue, instance, environment };
+ const database = useAppDatabase(connection.database);
+ const instance = useMemo(() => getInstanceResource(database), [database]);
+ const getEnvironmentByName = useAppStore((s) => s.getEnvironmentByName);
+ const environment = useMemo(() => {
+ if (isValidDatabaseName(database.name)) {
+ return getDatabaseEnvironment(database);
+ }
+ return getEnvironmentByName(instance.environment ?? "");
+ }, [database, instance, getEnvironmentByName]);
+ return { connection, database, instance, environment };
};
// Stable empty-connection sentinel. `emptySQLEditorConnection()`
diff --git a/frontend/src/react/hooks/useVueRoute.ts b/frontend/src/react/hooks/useVueRoute.ts
new file mode 100644
index 0000000000..8206475a10
--- /dev/null
+++ b/frontend/src/react/hooks/useVueRoute.ts
@@ -0,0 +1,23 @@
+import { useCallback, useSyncExternalStore } from "react";
+import type { RouteLocationNormalizedLoaded } from "vue-router";
+import { router } from "@/router";
+
+// `router.afterEach` returns its own unregister fn — wraps it as a React
+// `useSyncExternalStore` subscription so route changes trigger re-renders
+// without dragging Vue's reactivity (`useVueState` / `usePiniaBridge`)
+// into the consumer.
+const subscribe = (onChange: () => void): (() => void) =>
+ router.afterEach(() => onChange());
+
+const getSnapshot = (): RouteLocationNormalizedLoaded =>
+ router.currentRoute.value;
+
+/**
+ * Reactively reads the current Vue Router route. Use when a React
+ * component needs to re-render on navigation (URL changes, param updates)
+ * without subscribing to Vue's reactive system.
+ */
+export const useVueRoute = (): RouteLocationNormalizedLoaded => {
+ const subscribeFn = useCallback(subscribe, []);
+ return useSyncExternalStore(subscribeFn, getSnapshot, getSnapshot);
+};
diff --git a/frontend/src/react/lib/databaseFilter.ts b/frontend/src/react/lib/databaseFilter.ts
new file mode 100644
index 0000000000..20e917d72d
--- /dev/null
+++ b/frontend/src/react/lib/databaseFilter.ts
@@ -0,0 +1,21 @@
+import type { Engine } from "@/types/proto-es/v1/common_pb";
+
+/**
+ * Structured filter consumed by the app store's `fetchDatabases` and the
+ * Pinia `useDatabaseV1Store.fetchDatabases`. Lives under `@/react/lib/` so
+ * React code can import it without reaching into `@/store/modules/v1/`.
+ * The Pinia store re-exports this type for back-compat.
+ */
+export interface DatabaseFilter {
+ project?: string;
+ instance?: string;
+ environment?: string;
+ query?: string;
+ showDeleted?: boolean;
+ excludeUnassigned?: boolean;
+ // label should be "{label key}:{label value}" format
+ labels?: string[];
+ engines?: Engine[];
+ excludeEngines?: Engine[];
+ table?: string;
+}
diff --git a/frontend/src/react/no-legacy-vue-deps.test.ts b/frontend/src/react/no-legacy-vue-deps.test.ts
index 304ebcb3cf..97b33a12cc 100644
--- a/frontend/src/react/no-legacy-vue-deps.test.ts
+++ b/frontend/src/react/no-legacy-vue-deps.test.ts
@@ -158,16 +158,8 @@ describe("React Project and Settings legacy Vue dependencies", () => {
const bannedImports = [
"useUserStore",
"useRoleStore",
- "useReleaseStore",
- "useRevisionStore",
- "useChangelogStore",
- "useProjectWebhookV1Store",
"@/store/modules/user",
"@/store/modules/role",
- "@/store/modules/release",
- "@/store/modules/revision",
- "@/store/modules/v1/changelog",
- "@/store/modules/v1/projectWebhook",
];
const violations: string[] = [];
for (const [file, source] of Object.entries(sources)) {
diff --git a/frontend/src/react/pages/settings/DatabasesPage.tsx b/frontend/src/react/pages/settings/DatabasesPage.tsx
index 1e2bfbd58d..6d94d745d8 100644
--- a/frontend/src/react/pages/settings/DatabasesPage.tsx
+++ b/frontend/src/react/pages/settings/DatabasesPage.tsx
@@ -23,6 +23,7 @@ import { EnvironmentLabel } from "@/react/components/EnvironmentLabel";
import { PermissionGuard } from "@/react/components/PermissionGuard";
import { Button } from "@/react/components/ui/button";
import { useVueState } from "@/react/hooks/useVueState";
+import type { DatabaseFilter } from "@/react/lib/databaseFilter";
import { router } from "@/router";
import {
pushNotification,
@@ -39,7 +40,6 @@ import {
instanceNamePrefix,
projectNamePrefix,
} from "@/store/modules/v1/common";
-import type { DatabaseFilter } from "@/store/modules/v1/database";
import {
isValidDatabaseName,
UNKNOWN_ENVIRONMENT_NAME,
diff --git a/frontend/src/react/stores/app/iam.ts b/frontend/src/react/stores/app/iam.ts
index cafd458e06..ecf84199fe 100644
--- a/frontend/src/react/stores/app/iam.ts
+++ b/frontend/src/react/stores/app/iam.ts
@@ -116,7 +116,7 @@ export const createIamSlice: AppSliceCreator<IamSlice> = (set, get) => ({
.getIamPolicy(
createProto(GetIamPolicyRequestSchema, { resource: project })
)
- .then((policy) => {
+ .then(async (policy) => {
set((state) => {
const { [project]: _, ...projectPolicyRequests } =
state.projectPolicyRequests;
@@ -128,6 +128,20 @@ export const createIamSlice: AppSliceCreator<IamSlice> = (set, get) => ({
projectPolicyRequests,
};
});
+ // Bridge to the Pinia projectIamPolicy store so the legacy
+ // `usePermissionStore.currentPermissionsInProjectV1` chain sees
+ // the policy without a second fetch. Dynamic import to avoid a
+ // static module-load cycle (Pinia projectIamPolicy transitively
+ // imports `@/store` chains that would re-enter this app store).
+ try {
+ const { useProjectIamPolicyStore } = await import(
+ "@/store/modules/v1/projectIamPolicy"
+ );
+ useProjectIamPolicyStore().setProjectIamPolicy(project, policy);
+ } catch {
+ // Pinia not available (e.g. some isolated test). Safe to ignore —
+ // the app-store cache is already populated.
+ }
return policy;
})
.catch(() => {
diff --git a/frontend/src/react/stores/app/index.ts b/frontend/src/react/stores/app/index.ts
index d68098be52..f3971e7a5a 100644
--- a/frontend/src/react/stores/app/index.ts
+++ b/frontend/src/react/stores/app/index.ts
@@ -9,6 +9,8 @@ import { createIamSlice } from "./iam";
import { createIdentityProviderSlice } from "./identityProvider";
import { createInstanceSlice } from "./instance";
import { createInstanceRoleSlice } from "./instanceRole";
+import { createIssueSlice } from "./issue";
+import { createPolicySlice } from "./policy";
import { createNotificationSlice } from "./notification";
import { createPreferencesSlice } from "./preferences";
import { createProjectSlice } from "./project";
@@ -18,6 +20,7 @@ import { createRevisionSlice } from "./revision";
import { createRoleSlice } from "./role";
import { createServiceAccountSlice } from "./serviceAccount";
import { createSheetSlice } from "./sheet";
+import { createSQLSlice } from "./sql";
import { createUserSlice } from "./user";
import { createWorksheetSlice } from "./worksheet";
import { createWorkspaceSlice } from "./workspace";
@@ -57,6 +60,9 @@ export const createAppStore = () =>
...createProjectWebhookSlice(...args),
...createNotificationSlice(...args),
...createPreferencesSlice(...args),
+ ...createSQLSlice(...args),
+ ...createIssueSlice(...args),
+ ...createPolicySlice(...args),
}));
export const useAppStore = createAppStore();
diff --git a/frontend/src/react/stores/app/issue.ts b/frontend/src/react/stores/app/issue.ts
new file mode 100644
index 0000000000..27ab1f3c96
--- /dev/null
+++ b/frontend/src/react/stores/app/issue.ts
@@ -0,0 +1,37 @@
+import { create as createProto } from "@bufbuild/protobuf";
+import { createContextValues } from "@connectrpc/connect";
+import { issueServiceClientConnect } from "@/connect";
+import { silentContextKey } from "@/connect/context-key";
+import { GetIssueRequestSchema } from "@/types/proto-es/v1/issue_service_pb";
+import type { AppSliceCreator, IssueSlice } from "./types";
+
+// Resource names are `projects/{project}/issues/{issue}` — yank the project
+// resource out of the head without importing the heavy `@/utils/v1/project`
+// barrel (which pulls the Pinia actuator chain into the app-store graph).
+function projectResourceFromIssueName(issueName: string): string {
+ const match = issueName.match(/^(projects\/[^/]+)\//);
+ return match?.[1] ?? "";
+}
+
+/**
+ * Port of the legacy Pinia `useIssueV1Store.fetchIssueByName`. Stateless
+ * fetch (no per-issue cache — callers consume the result once) that also
+ * primes the owning project in the app store, matching the Pinia behavior
+ * so downstream code that reads the project synchronously after the call
+ * sees it cached.
+ */
+export const createIssueSlice: AppSliceCreator<IssueSlice> = (_set, get) => ({
+ fetchIssueByName: async (name, silent = false) => {
+ const issue = await issueServiceClientConnect.getIssue(
+ createProto(GetIssueRequestSchema, { name }),
+ {
+ contextValues: createContextValues().set(silentContextKey, silent),
+ }
+ );
+ const projectName = projectResourceFromIssueName(issue.name);
+ if (projectName) {
+ await get().fetchProject(projectName);
+ }
+ return issue;
+ },
+});
diff --git a/frontend/src/react/stores/app/policy.ts b/frontend/src/react/stores/app/policy.ts
new file mode 100644
index 0000000000..33a303455e
--- /dev/null
+++ b/frontend/src/react/stores/app/policy.ts
@@ -0,0 +1,120 @@
+import { create as createProto } from "@bufbuild/protobuf";
+import { Code, ConnectError, createContextValues } from "@connectrpc/connect";
+import { orgPolicyServiceClientConnect } from "@/connect";
+import { silentContextKey } from "@/connect/context-key";
+import {
+ GetPolicyRequestSchema,
+ PolicySchema,
+ PolicyType,
+ type QueryDataPolicy,
+ QueryDataPolicySchema,
+} from "@/types/proto-es/v1/org_policy_service_pb";
+import type { AppSliceCreator, PolicySlice } from "./types";
+
+// Inlined to keep the app store's load graph free of `@/store/modules/v1/common`.
+const POLICY_NAME_PREFIX = "policies/";
+
+// Mirror of the Pinia helper — normalizes `policies/{TYPE}` segments to
+// lowercase so the cache key matches what the server returns.
+const replacePolicyTypeNameToLowerCase = (name: string): string => {
+ const pattern = /(^|\/)policies\/([^/]+)($|\/)/;
+ const replaced = name.replace(
+ pattern,
+ (_, left: string, policyType: string, right: string) =>
+ `${left}policies/${policyType.toLowerCase()}${right}`
+ );
+ return replaced.startsWith("/") ? replaced.slice(1) : replaced;
+};
+
+// Stable empty singleton — subscribers compare by reference, so we MUST NOT
+// build a fresh object on every call (mirrors the Pinia behavior).
+const EMPTY_QUERY_DATA_POLICY: QueryDataPolicy = createProto(
+ QueryDataPolicySchema,
+ { maximumResultRows: -1 }
+);
+
+const policyResourceName = (parent: string, policyType: PolicyType) =>
+ replacePolicyTypeNameToLowerCase(
+ `${parent}/${POLICY_NAME_PREFIX}${PolicyType[policyType]}`
+ );
+
+/**
+ * Port of the SQL-editor-used subset of the legacy Pinia `usePolicyV1Store`:
+ * `policyMapByName` cache + sync/async getters keyed by resource name.
+ * Failures on `getOrFetchPolicyByName` cache an empty Policy under the
+ * requested name (matches Pinia's "don't re-hit a missing policy" behavior).
+ */
+export const createPolicySlice: AppSliceCreator<PolicySlice> = (set, get) => ({
+ policyMapByName: {},
+ policyRequests: {},
+
+ getPolicyByName: (name) =>
+ get().policyMapByName[replacePolicyTypeNameToLowerCase(name)],
+
+ getOrFetchPolicyByName: async (name, refresh = false) => {
+ const key = replacePolicyTypeNameToLowerCase(name);
+ const cached = get().policyMapByName[key];
+ if (cached && !refresh) return cached;
+ const pending = get().policyRequests[key];
+ if (pending) return pending;
+
+ const request = orgPolicyServiceClientConnect
+ .getPolicy(createProto(GetPolicyRequestSchema, { name }), {
+ contextValues: createContextValues().set(silentContextKey, true),
+ })
+ .then((policy) => {
+ set((state) => {
+ const { [key]: _, ...policyRequests } = state.policyRequests;
+ return {
+ policyMapByName: {
+ ...state.policyMapByName,
+ [policy.name]: policy,
+ },
+ policyRequests,
+ };
+ });
+ return policy;
+ })
+ .catch((error): undefined => {
+ set((state) => {
+ const { [key]: _, ...policyRequests } = state.policyRequests;
+ // Cache an empty policy on NotFound so repeated lookups don't
+ // hammer the backend (parity with Pinia).
+ if (error instanceof ConnectError && error.code === Code.NotFound) {
+ return {
+ policyMapByName: {
+ ...state.policyMapByName,
+ [key]: createProto(PolicySchema, { name }),
+ },
+ policyRequests,
+ };
+ }
+ return { policyRequests };
+ });
+ return undefined;
+ });
+ set((state) => ({
+ policyRequests: { ...state.policyRequests, [key]: request },
+ }));
+ return request;
+ },
+
+ getPolicyByParentAndType: ({ parentPath, policyType }) =>
+ get().policyMapByName[policyResourceName(parentPath, policyType)],
+
+ getOrFetchPolicyByParentAndType: ({ parentPath, policyType, refresh }) =>
+ get().getOrFetchPolicyByName(
+ policyResourceName(parentPath, policyType),
+ refresh
+ ),
+
+ getQueryDataPolicyByParent: (parent) => {
+ const policy = get().getPolicyByParentAndType({
+ parentPath: parent,
+ policyType: PolicyType.DATA_QUERY,
+ });
+ return policy?.policy?.case === "queryDataPolicy"
+ ? policy.policy.value
+ : EMPTY_QUERY_DATA_POLICY;
+ },
+});
diff --git a/frontend/src/react/stores/app/preferences.ts b/frontend/src/react/stores/app/preferences.ts
index 845b05f41e..af1c6210c2 100644
--- a/frontend/src/react/stores/app/preferences.ts
+++ b/frontend/src/react/stores/app/preferences.ts
@@ -78,4 +78,14 @@ export const createPreferencesSlice: AppSliceCreator<PreferencesSlice> = (
writeJson(key, next);
emitReactQuickstartReset({ keys: QUICKSTART_RESET_KEYS });
},
+
+ // Mirrors the Pinia `useUIStateStore.saveIntroStateByKey`: persists a
+ // single intro flag (e.g. `data.query`) to the per-user localStorage map.
+ saveIntroStateByKey: ({ key, newState }) => {
+ const email = getCurrentUserEmail(get);
+ if (!email) return;
+ const storageKey = storageKeyIntroState(email);
+ const previous = readJson<Record<string, boolean>>(storageKey, {});
+ writeJson(storageKey, { ...previous, [key]: newState });
+ },
});
diff --git a/frontend/src/react/stores/app/sql.ts b/frontend/src/react/stores/app/sql.ts
new file mode 100644
index 0000000000..049bd4c5a2
--- /dev/null
+++ b/frontend/src/react/stores/app/sql.ts
@@ -0,0 +1,47 @@
+import { Code, ConnectError, createContextValues } from "@connectrpc/connect";
+import { sqlServiceClientConnect } from "@/connect";
+import {
+ ignoredCodesContextKey,
+ silentContextKey,
+} from "@/connect/context-key";
+import { extractGrpcErrorMessage } from "@/utils/connect";
+import type { AppSliceCreator, SQLSlice } from "./types";
+
+/**
+ * Port of the legacy Pinia `useSQLStore`. Stateless — just RPC wrappers
+ * around `query` / `export` with the SQL editor's permission-denied + silent
+ * context conventions. Failures are swallowed into the returned
+ * `SQLResultSetV1.error` (mirrors the Pinia behavior so the result table
+ * can render the error inline instead of bubbling a thrown exception).
+ */
+export const createSQLSlice: AppSliceCreator<SQLSlice> = () => ({
+ query: async (params, signal) => {
+ try {
+ const response = await sqlServiceClientConnect.query(params, {
+ contextValues: createContextValues()
+ .set(ignoredCodesContextKey, [Code.PermissionDenied])
+ .set(silentContextKey, true),
+ signal,
+ });
+ return {
+ error: "",
+ results: response.results,
+ };
+ } catch (err) {
+ return {
+ error: extractGrpcErrorMessage(err),
+ results: [],
+ status: err instanceof ConnectError ? err.code : Code.Unknown,
+ };
+ }
+ },
+
+ exportData: async (params) => {
+ const response = await sqlServiceClientConnect.export(params, {
+ contextValues: createContextValues().set(ignoredCodesContextKey, [
+ Code.PermissionDenied,
+ ]),
+ });
+ return response.content;
+ },
+});
diff --git a/frontend/src/react/stores/app/types.ts b/frontend/src/react/stores/app/types.ts
index 2218429deb..edb2cc8338 100644
--- a/frontend/src/react/stores/app/types.ts
+++ b/frontend/src/react/stores/app/types.ts
@@ -1,5 +1,5 @@
import type { StateCreator } from "zustand";
-import type { DatabaseFilter } from "@/store/modules/v1/database";
+import type { DatabaseFilter } from "@/react/lib/databaseFilter";
import type { AppFeatures } from "@/types/appProfile";
import type { Permission } from "@/types/iam/permission";
import type { NotificationCreate } from "@/types/notification";
@@ -25,13 +25,27 @@ import type {
Instance,
InstanceResource,
} from "@/types/proto-es/v1/instance_service_pb";
+import type { Issue } from "@/types/proto-es/v1/issue_service_pb";
+import type {
+ Policy,
+ PolicyType,
+ QueryDataPolicy,
+} from "@/types/proto-es/v1/org_policy_service_pb";
import type { Project, Webhook } from "@/types/proto-es/v1/project_service_pb";
import type { Release } from "@/types/proto-es/v1/release_service_pb";
import type { Revision } from "@/types/proto-es/v1/revision_service_pb";
import type { Role } from "@/types/proto-es/v1/role_service_pb";
import type { ServiceAccount } from "@/types/proto-es/v1/service_account_service_pb";
-import type { WorkspaceProfileSetting } from "@/types/proto-es/v1/setting_service_pb";
+import type {
+ Setting,
+ Setting_SettingName,
+ WorkspaceProfileSetting,
+} from "@/types/proto-es/v1/setting_service_pb";
import type { Sheet } from "@/types/proto-es/v1/sheet_service_pb";
+import type {
+ ExportRequest,
+ QueryRequest,
+} from "@/types/proto-es/v1/sql_service_pb";
import type {
PlanFeature,
PlanType,
@@ -48,6 +62,7 @@ import type {
} from "@/types/proto-es/v1/worksheet_service_pb";
import type { Workspace } from "@/types/proto-es/v1/workspace_service_pb";
import type { Environment } from "@/types/v1/environment";
+import type { SQLResultSetV1 } from "@/types/v1/sql";
import type { AccessGrantFilterStatus } from "@/utils";
export type ProjectListParams = {
@@ -132,6 +147,11 @@ export type WorkspaceSlice = {
workspaceProfileRequest?: Promise<WorkspaceProfileSetting | undefined>;
environmentList: Environment[];
environmentRequest?: Promise<Environment[]>;
+ // General-purpose setting cache, mirrors the legacy Pinia
+ // `useSettingV1Store` API. Keyed by the setting's resource name
+ // (`settings/{Setting_SettingName}`).
+ settingsByName: Record<string, Setting>;
+ settingRequests: Record<string, Promise<Setting | undefined>>;
appFeatures: AppFeatures;
subscription?: Subscription;
subscriptionRequest?: Promise<Subscription | undefined>;
@@ -150,6 +170,11 @@ export type WorkspaceSlice = {
loadEnvironmentList: (force?: boolean) => Promise<Environment[]>;
refreshEnvironmentList: () => Promise<Environment[]>;
getEnvironmentByName: (name: string, fallback?: boolean) => Environment;
+ getSettingByName: (name: Setting_SettingName) => Setting | undefined;
+ getOrFetchSettingByName: (
+ name: Setting_SettingName,
+ silent?: boolean
+ ) => Promise<Setting | undefined>;
loadSubscription: () => Promise<Subscription | undefined>;
refreshSubscription: () => Promise<Subscription | undefined>;
uploadLicense: (license: string) => Promise<Subscription | undefined>;
@@ -557,6 +582,47 @@ export type PreferencesSlice = {
recordRecentVisit: (path: string) => void;
removeRecentVisit: (path: string) => void;
resetQuickstartProgress: () => void;
+ saveIntroStateByKey: (params: { key: string; newState: boolean }) => void;
+};
+
+// Org policy slice (mirrors the SQL-editor-used subset of the Pinia
+// `usePolicyV1Store`): keyed by the policy resource name. Async fetchers
+// dedupe via `policyRequests`. `getQueryDataPolicyByParent` returns a stable
+// empty fallback when the policy isn't cached.
+export type PolicySlice = {
+ policyMapByName: Record<string, Policy>;
+ policyRequests: Record<string, Promise<Policy | undefined>>;
+ getPolicyByName: (name: string) => Policy | undefined;
+ getOrFetchPolicyByName: (
+ name: string,
+ refresh?: boolean
+ ) => Promise<Policy | undefined>;
+ getPolicyByParentAndType: (params: {
+ parentPath: string;
+ policyType: PolicyType;
+ }) => Policy | undefined;
+ getOrFetchPolicyByParentAndType: (params: {
+ parentPath: string;
+ policyType: PolicyType;
+ refresh?: boolean;
+ }) => Promise<Policy | undefined>;
+ getQueryDataPolicyByParent: (parent: string) => QueryDataPolicy;
+};
+
+// Stateless issue service slice (mirrors the legacy Pinia `useIssueV1Store`):
+// thin wrapper around `issueServiceClientConnect.getIssue`. Returns the
+// fresh issue (no cache) and pre-fetches the owning project into the app
+// store so downstream code can read it synchronously.
+export type IssueSlice = {
+ fetchIssueByName: (name: string, silent?: boolean) => Promise<Issue>;
+};
+
+// Stateless SQL service slice (mirrors the legacy Pinia `useSQLStore`):
+// thin wrappers around `sqlServiceClientConnect.query` / `.export` with the
+// SQL editor's permission-denied / silent context conventions.
+export type SQLSlice = {
+ query: (params: QueryRequest, signal: AbortSignal) => Promise<SQLResultSetV1>;
+ exportData: (params: ExportRequest) => Promise<Uint8Array>;
};
export type AppStoreState = AuthSlice &
@@ -581,6 +647,9 @@ export type AppStoreState = AuthSlice &
ChangelogSlice &
ProjectWebhookSlice &
NotificationSlice &
- PreferencesSlice;
+ PreferencesSlice &
+ SQLSlice &
+ IssueSlice &
+ PolicySlice;
export type AppSliceCreator<Slice> = StateCreator<AppStoreState, [], [], Slice>;
diff --git a/frontend/src/react/stores/app/utils.ts b/frontend/src/react/stores/app/utils.ts
index b9677f2f86..cbe03c6666 100644
--- a/frontend/src/react/stores/app/utils.ts
+++ b/frontend/src/react/stores/app/utils.ts
@@ -1,4 +1,5 @@
import { Code, ConnectError } from "@connectrpc/connect";
+import type { DatabaseFilter } from "@/react/lib/databaseFilter";
import {
getProjectName,
getUserName,
@@ -6,7 +7,6 @@ import {
projectNamePrefix,
userNamePrefix,
} from "@/react/lib/resourceName";
-import type { DatabaseFilter } from "@/store/modules/v1/database";
import { Engine } from "@/types/proto-es/v1/common_pb";
import type { Binding } from "@/types/proto-es/v1/iam_policy_pb";
import type { Project } from "@/types/proto-es/v1/project_service_pb";
diff --git a/frontend/src/react/stores/app/workspace.ts b/frontend/src/react/stores/app/workspace.ts
index 619bb6c742..010a39c2f9 100644
--- a/frontend/src/react/stores/app/workspace.ts
+++ b/frontend/src/react/stores/app/workspace.ts
@@ -1,5 +1,6 @@
import { create as createProto } from "@bufbuild/protobuf";
import { FieldMaskSchema } from "@bufbuild/protobuf/wkt";
+import { createContextValues } from "@connectrpc/connect";
import dayjs from "dayjs";
import semver from "semver";
import {
@@ -10,6 +11,7 @@ import {
userServiceClientConnect,
workspaceServiceClientConnect,
} from "@/connect";
+import { silentContextKey } from "@/connect/context-key";
import {
settingNamePrefix,
workspaceNamePrefix,
@@ -144,6 +146,8 @@ export const createWorkspaceSlice: AppSliceCreator<WorkspaceSlice> = (
serverInfoTs: 0,
workspaceList: [],
environmentList: [],
+ settingsByName: {},
+ settingRequests: {},
appFeatures: defaultAppProfile().features,
loadServerInfo: async () => {
@@ -339,6 +343,59 @@ export const createWorkspaceSlice: AppSliceCreator<WorkspaceSlice> = (
return environment;
},
+ // Mirrors the Pinia `useSettingV1Store`: general-purpose setting cache
+ // keyed by resource name (`settings/{Setting_SettingName}`). Used for AI /
+ // workspace-profile / etc.
+ getSettingByName: (name) => {
+ const resourceName = `${settingNamePrefix}${Setting_SettingName[name]}`;
+ return get().settingsByName[resourceName];
+ },
+
+ getOrFetchSettingByName: async (name, silent = false) => {
+ const resourceName = `${settingNamePrefix}${Setting_SettingName[name]}`;
+ const cached = get().settingsByName[resourceName];
+ if (cached) return cached;
+ const pending = get().settingRequests[resourceName];
+ if (pending) return pending;
+
+ const request = settingServiceClientConnect
+ .getSetting(
+ createProto(GetSettingRequestSchema, { name: resourceName }),
+ {
+ contextValues: createContextValues().set(silentContextKey, silent),
+ }
+ )
+ .then((response) => {
+ set((state) => {
+ const { [resourceName]: _, ...settingRequests } =
+ state.settingRequests;
+ return {
+ settingsByName: {
+ ...state.settingsByName,
+ [response.name]: response,
+ },
+ settingRequests,
+ };
+ });
+ return response;
+ })
+ .catch(() => {
+ set((state) => {
+ const { [resourceName]: _, ...settingRequests } =
+ state.settingRequests;
+ return { settingRequests };
+ });
+ return undefined;
+ });
+ set((state) => ({
+ settingRequests: {
+ ...state.settingRequests,
+ [resourceName]: request,
+ },
+ }));
+ return request;
+ },
+
loadSubscription: async () => {
const existing = get().subscription;
if (existing) return existing;
diff --git a/frontend/src/react/stores/sqlEditor/tab.ts b/frontend/src/react/stores/sqlEditor/tab.ts
index 2770be5bfa..acfd5c1c83 100644
--- a/frontend/src/react/stores/sqlEditor/tab.ts
+++ b/frontend/src/react/stores/sqlEditor/tab.ts
@@ -4,7 +4,6 @@ import { create, type StoreApi, type UseBoundStore } from "zustand";
import { immer } from "zustand/middleware/immer";
import { useShallow } from "zustand/react/shallow";
import { useAppStore } from "@/react/stores/app";
-import { hasFeature } from "@/store";
import {
migrateDraftsFromCache,
migrateTabViewState,
@@ -623,11 +622,12 @@ export const useIsInBatchMode = (): boolean =>
const tab = s.tabsById.get(s.currentTabId);
if (!tab) return false;
if (tab.mode === "ADMIN") return false;
- if (!hasFeature(PlanFeature.FEATURE_BATCH_QUERY)) return false;
+ const appStore = useAppStore.getState();
+ if (!appStore.hasFeature(PlanFeature.FEATURE_BATCH_QUERY)) return false;
const ctx = tab.batchQueryContext;
if (!ctx) return false;
const { databaseGroups = [], databases = [] } = ctx;
- if (!hasFeature(PlanFeature.FEATURE_DATABASE_GROUPS)) {
+ if (!appStore.hasFeature(PlanFeature.FEATURE_DATABASE_GROUPS)) {
return databases.length > 1;
}
return databaseGroups.length > 0 || databases.length > 1;
diff --git a/frontend/src/react/stores/sqlEditor/tree-utils.ts b/frontend/src/react/stores/sqlEditor/tree-utils.ts
index a1204af885..997648267f 100644
--- a/frontend/src/react/stores/sqlEditor/tree-utils.ts
+++ b/frontend/src/react/stores/sqlEditor/tree-utils.ts
@@ -1,6 +1,5 @@
import { orderBy } from "lodash-es";
import { useAppStore } from "@/react/stores/app";
-import { useInstanceResourceByName } from "@/store/modules/v1";
import type {
SQLEditorTreeFactor as Factor,
SQLEditorTreeNodeTarget as NodeTarget,
@@ -11,6 +10,7 @@ import {
extractSQLEditorLabelFactor as extractLabelFactor,
LeafTreeNodeTypes,
unknownEnvironment,
+ unknownInstance,
} from "@/types";
import type { Database } from "@/types/proto-es/v1/database_service_pb";
import type { InstanceResource } from "@/types/proto-es/v1/instance_service_pb";
@@ -103,8 +103,14 @@ const mapGroupNode = (
return mapTreeNodeByType("environment", environment, parent);
}
if (factor === "instance") {
- const { instance } = useInstanceResourceByName(value);
- return mapTreeNodeByType("instance", instance.value, parent);
+ const appStore = useAppStore.getState();
+ // Best-effort: trigger a background fetch and render the cached
+ // instance (or an `unknownInstance` placeholder until the fetch
+ // resolves). Matches the legacy Pinia `useInstanceResourceByName`
+ // behavior — synchronous read with an async hydrate.
+ void appStore.fetchInstance(value);
+ const instance = appStore.instancesByName[value] ?? unknownInstance();
+ return mapTreeNodeByType("instance", instance, parent);
}
const key = extractLabelFactor(factor);
if (key) {
diff --git a/frontend/src/react/stores/sqlEditor/webTerminal-service.ts b/frontend/src/react/stores/sqlEditor/webTerminal-service.ts
index 46aef94de6..050f5edc52 100644
--- a/frontend/src/react/stores/sqlEditor/webTerminal-service.ts
+++ b/frontend/src/react/stores/sqlEditor/webTerminal-service.ts
@@ -10,7 +10,6 @@ import {
createCancelableTimer,
} from "@/react/lib/cancelableTimer";
import { useAppStore } from "@/react/stores/app";
-import { pushNotification } from "@/store";
import type {
SQLEditorQueryParams,
SQLEditorTab,
@@ -263,7 +262,7 @@ const bindStreamingLogic = (session: WebTerminalQuerySession) => {
}
for (const result of resultSet.results) {
for (const message of result.messages) {
- pushNotification({
+ useAppStore.getState().notify({
module: "bytebase",
style: "INFO",
title: QueryResult_Message_Level[message.level],
diff --git a/frontend/src/react/stores/sqlEditor/worksheet.ts b/frontend/src/react/stores/sqlEditor/worksheet.ts
index 6b30964318..0f992e68c0 100644
--- a/frontend/src/react/stores/sqlEditor/worksheet.ts
+++ b/frontend/src/react/stores/sqlEditor/worksheet.ts
@@ -14,13 +14,6 @@ import { getSQLEditorEditorState } from "./editor";
import { getSQLEditorTabsState } from "./tab";
import type { SQLEditorSliceCreator, WorksheetSaveSlice } from "./types";
-// Pinia store barrel transitively re-imports `@/react/stores/sqlEditor`,
-// so we still pull the Pinia bits in at call time via the helper below
-// to avoid a TDZ cycle. The new Zustand editor / tab stores are local
-// to this module's directory and safe to import statically.
-const importProjectIamPolicyStore = () =>
- import("@/store/modules/v1/projectIamPolicy");
-
export const createWorksheetSaveSlice: SQLEditorSliceCreator<
WorksheetSaveSlice
> = (set, get) => ({
@@ -38,9 +31,7 @@ export const createWorksheetSaveSlice: SQLEditorSliceCreator<
},
maybeSwitchProject: async (projectName) => {
- const { useProjectIamPolicyStore } = await importProjectIamPolicyStore();
const editorStore = getSQLEditorEditorState();
- const projectIamPolicyStore = useProjectIamPolicyStore();
editorStore.setProjectContextReady(false);
try {
@@ -51,8 +42,11 @@ export const createWorksheetSaveSlice: SQLEditorSliceCreator<
if (!project) {
return;
}
- // Fetch IAM policy to ensure permission checks work correctly.
- await projectIamPolicyStore.getOrFetchProjectIamPolicy(project.name);
+ // Fetch IAM policy so `hasProjectPermissionV2` sees the bindings. The
+ // Pinia permission store falls back to `app.projectPoliciesByName` when
+ // its own cache is empty, so populating the app `iam` slice is enough
+ // (see `src/store/modules/v1/permission.ts`).
+ await useAppStore.getState().loadProjectIamPolicy(project.name);
editorStore.setProject(project.name);
await sqlEditorEvents.emit("project-context-ready", {
project: project.name,
diff --git a/frontend/src/store/modules/index.ts b/frontend/src/store/modules/index.ts
index a334a08719..af8dc0b310 100644
--- a/frontend/src/store/modules/index.ts
+++ b/frontend/src/store/modules/index.ts
@@ -10,8 +10,6 @@ export * from "./workspaceApprovalSetting";
export * from "./role";
export * from "./dbGroup";
export * from "./utils";
-export * from "./release";
-export * from "./revision";
export * from "./rollout";
export * from "./v1";
diff --git a/frontend/src/store/modules/release.ts b/frontend/src/store/modules/release.ts
deleted file mode 100644
index df411c15a1..0000000000
--- a/frontend/src/store/modules/release.ts
+++ /dev/null
@@ -1,142 +0,0 @@
-import { create } from "@bufbuild/protobuf";
-import { createContextValues } from "@connectrpc/connect";
-import { defineStore } from "pinia";
-import { computed, reactive, ref, unref, watch } from "vue";
-import { releaseServiceClientConnect } from "@/connect";
-import { silentContextKey } from "@/connect/context-key";
-import type { MaybeRef } from "@/types";
-import { isValidReleaseName, unknownRelease } from "@/types";
-import { State } from "@/types/proto-es/v1/common_pb";
-import type { Release } from "@/types/proto-es/v1/release_service_pb";
-import {
- DeleteReleaseRequestSchema,
- GetReleaseRequestSchema,
- ListReleasesRequestSchema,
- ReleaseSchema,
- UndeleteReleaseRequestSchema,
- UpdateReleaseRequestSchema,
-} from "@/types/proto-es/v1/release_service_pb";
-
-export const useReleaseStore = defineStore("release", () => {
- const releaseMapByName = reactive(new Map<string, Release>());
-
- const releaseList = computed(() => {
- return Array.from(releaseMapByName.values());
- });
-
- const fetchReleasesByProject = async (
- project: string,
- pagination?: {
- pageSize?: number;
- pageToken?: string;
- },
- showDeleted?: boolean,
- filter?: string
- ) => {
- const request = create(ListReleasesRequestSchema, {
- parent: project,
- pageSize: pagination?.pageSize,
- pageToken: pagination?.pageToken || "",
- showDeleted: Boolean(showDeleted),
- filter: filter || "",
- });
- const resp = await releaseServiceClientConnect.listReleases(request);
- const releases = resp.releases;
- releases.forEach((release) => {
- releaseMapByName.set(release.name, release);
- });
- return {
- releases: releases,
- nextPageToken: resp.nextPageToken,
- };
- };
-
- const fetchReleaseByName = async (name: string, silent = false) => {
- const request = create(GetReleaseRequestSchema, { name });
- const response = await releaseServiceClientConnect.getRelease(request, {
- contextValues: createContextValues().set(silentContextKey, silent),
- });
- releaseMapByName.set(response.name, response);
- return response;
- };
-
- const getReleasesByProject = (project: string) => {
- return releaseList.value.filter((release) =>
- release.name.startsWith(`${project}/releases/`)
- );
- };
-
- const getReleaseByName = (name: string) => {
- return releaseMapByName.get(name) ?? unknownRelease();
- };
-
- const updateRelase = async (
- release: Partial<Release>,
- updateMask: string[]
- ) => {
- const fullRelease = {
- ...create(ReleaseSchema, {}),
- ...release,
- };
-
- const request = create(UpdateReleaseRequestSchema, {
- release: fullRelease,
- updateMask: { paths: updateMask },
- });
- const resp = await releaseServiceClientConnect.updateRelease(request);
- releaseMapByName.set(resp.name, resp);
- return resp;
- };
-
- const deleteRelease = async (name: string) => {
- const request = create(DeleteReleaseRequestSchema, { name });
- await releaseServiceClientConnect.deleteRelease(request);
- if (releaseMapByName.get(name)) {
- releaseMapByName.get(name)!.state = State.DELETED;
- }
- };
-
- const undeleteRelease = async (name: string) => {
- const request = create(UndeleteReleaseRequestSchema, { name });
- const response = await releaseServiceClientConnect.undeleteRelease(request);
- releaseMapByName.set(response.name, response);
- };
-
- return {
- releaseList,
- fetchReleasesByProject,
- fetchReleaseByName,
- getReleasesByProject,
- getReleaseByName,
- updateRelase,
- deleteRelease,
- undeleteRelease,
- };
-});
-
-export const useReleaseByName = (name: MaybeRef<string>) => {
- const store = useReleaseStore();
- const ready = ref(true);
- watch(
- () => unref(name),
- async (name) => {
- if (!isValidReleaseName(name)) {
- return;
- }
-
- const cachedRelease = store.getReleaseByName(name);
- if (!isValidReleaseName(cachedRelease.name)) {
- ready.value = false;
- await store.fetchReleaseByName(name);
- ready.value = true;
- }
- },
- { immediate: true }
- );
- const release = computed(() => store.getReleaseByName(unref(name)));
-
- return {
- release,
- ready,
- };
-};
diff --git a/frontend/src/store/modules/revision.test.ts b/frontend/src/store/modules/revision.test.ts
deleted file mode 100644
index 5656233ee6..0000000000
--- a/frontend/src/store/modules/revision.test.ts
+++ /dev/null
@@ -1,69 +0,0 @@
-import { createPinia, setActivePinia } from "pinia";
-import { beforeEach, describe, expect, test, vi } from "vitest";
-import type { Revision } from "@/types/proto-es/v1/revision_service_pb";
-
-const mocks = vi.hoisted(() => ({
- listRevisions: vi.fn(),
-}));
-
-vi.mock("@/connect", () => ({
- revisionServiceClientConnect: {
- listRevisions: mocks.listRevisions,
- },
-}));
-
-let useRevisionStore: typeof import("./revision").useRevisionStore;
-
-beforeEach(async () => {
- setActivePinia(createPinia());
- mocks.listRevisions.mockReset();
-
- vi.resetModules();
- ({ useRevisionStore } = await import("./revision"));
-});
-
-describe("revision store", () => {
- test("fetchAllRevisionsByDatabase keeps loading until every page is fetched", async () => {
- mocks.listRevisions
- .mockResolvedValueOnce({
- nextPageToken: "page-2",
- revisions: [
- {
- name: "instances/inst1/databases/db1/revisions/1",
- version: "1.0.0",
- } as Revision,
- ],
- })
- .mockResolvedValueOnce({
- nextPageToken: "",
- revisions: [
- {
- name: "instances/inst1/databases/db1/revisions/2",
- version: "2.0.0",
- } as Revision,
- ],
- });
-
- const store = useRevisionStore();
- const revisions = await store.fetchAllRevisionsByDatabase(
- "instances/inst1/databases/db1",
- { pageSize: 1000 }
- );
-
- expect(mocks.listRevisions).toHaveBeenCalledTimes(2);
- expect(mocks.listRevisions.mock.calls[0]?.[0]).toMatchObject({
- parent: "instances/inst1/databases/db1",
- pageSize: 1000,
- pageToken: "",
- });
- expect(mocks.listRevisions.mock.calls[1]?.[0]).toMatchObject({
- parent: "instances/inst1/databases/db1",
- pageSize: 1000,
- pageToken: "page-2",
- });
- expect(revisions.map((revision) => revision.version)).toEqual([
- "1.0.0",
- "2.0.0",
- ]);
- });
-});
diff --git a/frontend/src/store/modules/revision.ts b/frontend/src/store/modules/revision.ts
deleted file mode 100644
index 5005a6afc0..0000000000
--- a/frontend/src/store/modules/revision.ts
+++ /dev/null
@@ -1,96 +0,0 @@
-import { create } from "@bufbuild/protobuf";
-import { defineStore } from "pinia";
-import { computed, reactive } from "vue";
-import { revisionServiceClientConnect } from "@/connect";
-import type { Revision } from "@/types/proto-es/v1/revision_service_pb";
-import {
- DeleteRevisionRequestSchema,
- GetRevisionRequestSchema,
- ListRevisionsRequestSchema,
-} from "@/types/proto-es/v1/revision_service_pb";
-import { revisionNamePrefix } from "./v1/common";
-
-export const useRevisionStore = defineStore("revision", () => {
- const revisionMapByName = reactive(new Map<string, Revision>());
-
- const revisionList = computed(() => {
- return Array.from(revisionMapByName.values());
- });
-
- const fetchRevisionsByDatabase = async (
- database: string,
- pagination?: {
- pageSize?: number;
- pageToken?: string;
- }
- ) => {
- const request = create(ListRevisionsRequestSchema, {
- parent: database,
- pageSize: pagination?.pageSize,
- pageToken: pagination?.pageToken,
- });
- const resp = await revisionServiceClientConnect.listRevisions(request);
- resp.revisions.forEach((revision) => {
- revisionMapByName.set(revision.name, revision);
- });
- return resp;
- };
-
- const fetchAllRevisionsByDatabase = async (
- database: string,
- pagination?: {
- pageSize?: number;
- }
- ) => {
- const revisions: Revision[] = [];
- let pageToken = "";
-
- do {
- const resp = await fetchRevisionsByDatabase(database, {
- pageSize: pagination?.pageSize,
- pageToken,
- });
- revisions.push(...resp.revisions);
- pageToken = resp.nextPageToken;
- } while (pageToken);
-
- return revisions;
- };
-
- const getRevisionsByDatabase = (database: string) => {
- return revisionList.value.filter((revision) =>
- revision.name.startsWith(`${database}/${revisionNamePrefix}`)
- );
- };
-
- const getOrFetchRevisionByName = async (name: string) => {
- if (revisionMapByName.has(name)) {
- return revisionMapByName.get(name);
- }
-
- const request = create(GetRevisionRequestSchema, { name });
- const revision = await revisionServiceClientConnect.getRevision(request);
- revisionMapByName.set(revision.name, revision);
- return revision;
- };
-
- const getRevisionByName = (name: string) => {
- return revisionMapByName.get(name);
- };
-
- const deleteRevision = async (name: string) => {
- const request = create(DeleteRevisionRequestSchema, { name });
- await revisionServiceClientConnect.deleteRevision(request);
- revisionMapByName.delete(name);
- };
-
- return {
- revisionList,
- fetchAllRevisionsByDatabase,
- fetchRevisionsByDatabase,
- getRevisionsByDatabase,
- getOrFetchRevisionByName,
- getRevisionByName,
- deleteRevision,
- };
-});
diff --git a/frontend/src/store/modules/v1/auditLog.ts b/frontend/src/store/modules/v1/auditLog.ts
deleted file mode 100644
index 222582d193..0000000000
--- a/frontend/src/store/modules/v1/auditLog.ts
+++ /dev/null
@@ -1,79 +0,0 @@
-import { create } from "@bufbuild/protobuf";
-import dayjs from "dayjs";
-import utc from "dayjs/plugin/utc";
-import { defineStore } from "pinia";
-import { auditLogServiceClientConnect } from "@/connect";
-import type { AuditLogFilter, SearchAuditLogsParams } from "@/types";
-import {
- AuditLog_Severity,
- ExportAuditLogsRequestSchema,
- SearchAuditLogsRequestSchema,
-} from "@/types/proto-es/v1/audit_log_service_pb";
-import { type ExportFormat } from "@/types/proto-es/v1/common_pb";
-import { userNamePrefix } from "./common";
-
-dayjs.extend(utc);
-
-const buildFilter = (search: AuditLogFilter): string => {
- const filter: string[] = [];
- if (search.method) {
- filter.push(`method == "${search.method}"`);
- }
- if (search.level) {
- filter.push(`severity == "${AuditLog_Severity[search.level]}"`);
- }
- if (search.userEmail) {
- filter.push(`user == "${userNamePrefix}${search.userEmail}"`);
- }
- if (search.createdTsAfter) {
- filter.push(
- `create_time >= "${dayjs(search.createdTsAfter).utc().format()}"`
- );
- }
- if (search.createdTsBefore) {
- filter.push(
- `create_time <= "${dayjs(search.createdTsBefore).utc().format()}"`
- );
- }
- return filter.join(" && ");
-};
-
-export const useAuditLogStore = defineStore("audit_log", () => {
- const fetchAuditLogs = async (search: SearchAuditLogsParams) => {
- const request = create(SearchAuditLogsRequestSchema, {
- parent: search.parent,
- filter: buildFilter(search.filter),
- orderBy: search.orderBy,
- pageSize: search.pageSize,
- pageToken: search.pageToken,
- });
- const resp = await auditLogServiceClientConnect.searchAuditLogs(request);
- return resp;
- };
-
- const exportAuditLogs = async ({
- search,
- format,
- }: {
- search: SearchAuditLogsParams;
- format: ExportFormat;
- }): Promise<{
- content: Uint8Array;
- nextPageToken: string;
- }> => {
- const request = create(ExportAuditLogsRequestSchema, {
- parent: search.parent,
- filter: buildFilter(search.filter),
- orderBy: search.orderBy,
- format,
- pageSize: search.pageSize,
- pageToken: search.pageToken,
- });
- return await auditLogServiceClientConnect.exportAuditLogs(request);
- };
-
- return {
- fetchAuditLogs,
- exportAuditLogs,
- };
-});
diff --git a/frontend/src/store/modules/v1/changelog.ts b/frontend/src/store/modules/v1/changelog.ts
deleted file mode 100644
index 9ad88dca89..0000000000
--- a/frontend/src/store/modules/v1/changelog.ts
+++ /dev/null
@@ -1,180 +0,0 @@
-import { create } from "@bufbuild/protobuf";
-import { defineStore } from "pinia";
-import { reactive } from "vue";
-import { databaseServiceClientConnect } from "@/connect";
-import { useCache } from "@/store/cache";
-import { UNKNOWN_ID } from "@/types";
-import {
- type Changelog,
- ChangelogView,
- type GetChangelogRequest,
- GetChangelogRequestSchema,
- type ListChangelogsRequest,
- ListChangelogsRequestSchema,
-} from "@/types/proto-es/v1/database_service_pb";
-import { extractChangelogUID } from "@/utils/v1/changelog";
-
-type CacheKeyType = [string /* name */, ChangelogView];
-
-export const useChangelogStore = defineStore("changelog", () => {
- const cache = useCache<CacheKeyType, Changelog>("bb.changelog.by-name");
- const changelogsMapByDatabase = reactive(new Map<string, Changelog[]>());
-
- const upsertChangelogsMap = async (
- parent: string,
- changelogs: Changelog[]
- ) => {
- changelogsMapByDatabase.set(parent, changelogs);
- changelogs.forEach((changelog) => {
- cache.setEntity([changelog.name, ChangelogView.BASIC], changelog);
- });
- };
-
- const clearCache = (parent: string) => {
- changelogsMapByDatabase.delete(parent);
- };
-
- const fetchChangelogList = async (params: Partial<ListChangelogsRequest>) => {
- const { parent } = params;
- if (!parent) throw new Error('"parent" field is required');
- const request = create(ListChangelogsRequestSchema, {
- parent: params.parent,
- pageSize: params.pageSize,
- pageToken: params.pageToken,
- view: params.view,
- filter: params.filter,
- });
- const response = await databaseServiceClientConnect.listChangelogs(request);
- const changelogs = response.changelogs;
- const { nextPageToken } = response;
- await upsertChangelogsMap(parent, changelogs);
- return { changelogs, nextPageToken };
- };
- const getOrFetchChangelogListOfDatabase = async (
- databaseName: string,
- pageSize: number,
- view = ChangelogView.BASIC
- ) => {
- if (changelogsMapByDatabase.has(databaseName)) {
- return changelogsMapByDatabase.get(databaseName) ?? [];
- }
- const { changelogs } = await fetchChangelogList({
- parent: databaseName,
- pageSize,
- view,
- });
- return changelogs;
- };
- const changelogListByDatabase = (name: string) => {
- return changelogsMapByDatabase.get(name) ?? [];
- };
- const fetchChangelog = async (params: Partial<GetChangelogRequest>) => {
- const request = create(GetChangelogRequestSchema, {
- name: params.name,
- view: params.view,
- });
- const changelog = await databaseServiceClientConnect.getChangelog(request);
- cache.setEntity(
- [changelog.name, params.view ?? ChangelogView.BASIC],
- changelog
- );
- return changelog;
- };
- const getOrFetchChangelogByName = async (
- name: string,
- view: ChangelogView = ChangelogView.BASIC
- ) => {
- const uid = extractChangelogUID(name);
- if (!uid || uid === String(UNKNOWN_ID)) {
- return undefined;
- }
- const entity = cache.getEntity([name, view]);
- if (entity) {
- return entity;
- }
- const request = cache.getRequest([name, view]);
- if (request) {
- return request;
- }
- const promise = fetchChangelog({ name, view });
- cache.setRequest([name, view], promise);
- return promise;
- };
- /**
- *
- * @param name
- * @param view default undefined to any view (full -> basic)
- * @returns
- */
- const getChangelogByName = (
- name: string,
- view: ChangelogView | undefined = undefined
- ) => {
- if (view === undefined) {
- return (
- cache.getEntity([name, ChangelogView.FULL]) ??
- cache.getEntity([name, ChangelogView.BASIC])
- );
- }
- return cache.getEntity([name, view]);
- };
-
- /**
- * Fetches the previous changelog for a given changelog with FULL view.
- * Returns the previous changelog's schema as the "before" state for diff comparison.
- * @param changelogName - The name of the current changelog
- * @returns The previous changelog with full schema, or undefined if this is the first changelog
- */
- const fetchPreviousChangelog = async (
- changelogName: string
- ): Promise<Changelog | undefined> => {
- // Extract database name from changelog name
- // Format: instances/{instance}/databases/{database}/changelogs/{changelog}
- const parts = changelogName.split("/changelogs/");
- if (parts.length !== 2) {
- return undefined;
- }
- const databaseName = parts[0];
- const currentChangelogUID = extractChangelogUID(changelogName);
- if (!currentChangelogUID || currentChangelogUID === String(UNKNOWN_ID)) {
- return undefined;
- }
-
- // Fetch changelogs with BASIC view to find the previous one efficiently
- const { changelogs } = await fetchChangelogList({
- parent: databaseName,
- pageSize: 1000, // Fetch enough to find the previous one
- view: ChangelogView.BASIC, // Use BASIC view for listing - much lighter
- });
-
- // Find the current changelog index
- const currentIndex = changelogs.findIndex(
- (cl) => extractChangelogUID(cl.name) === currentChangelogUID
- );
-
- // If not found or it's the last one (oldest), there's no previous
- if (currentIndex === -1 || currentIndex === changelogs.length - 1) {
- return undefined;
- }
-
- // Get the previous changelog name
- const previousChangelogName = changelogs[currentIndex + 1].name;
-
- // Fetch the previous changelog with FULL view to get the schema
- return await getOrFetchChangelogByName(
- previousChangelogName,
- ChangelogView.FULL
- );
- };
-
- return {
- clearCache,
- fetchChangelogList,
- getOrFetchChangelogListOfDatabase,
- changelogListByDatabase,
- fetchChangelog,
- getOrFetchChangelogByName,
- getChangelogByName,
- fetchPreviousChangelog,
- };
-});
diff --git a/frontend/src/store/modules/v1/database.ts b/frontend/src/store/modules/v1/database.ts
index 14c3b3c7fd..0df2cfca80 100644
--- a/frontend/src/store/modules/v1/database.ts
+++ b/frontend/src/store/modules/v1/database.ts
@@ -5,6 +5,10 @@ import { defineStore } from "pinia";
import { computed, markRaw, reactive, ref, unref, watch } from "vue";
import { databaseServiceClientConnect } from "@/connect";
import { silentContextKey } from "@/connect/context-key";
+// Canonical definition lives in `@/react/lib/databaseFilter`; re-exported
+// here so existing `from "@/store/modules/v1/database"` consumers keep
+// working until they migrate to the React-lib path.
+import type { DatabaseFilter } from "@/react/lib/databaseFilter";
import type { MaybeRef } from "@/types";
import {
isValidDatabaseName,
@@ -46,19 +50,7 @@ import {
import { useDBSchemaV1Store } from "./dbSchema";
import { useProjectV1Store } from "./project";
-export interface DatabaseFilter {
- project?: string;
- instance?: string;
- environment?: string;
- query?: string;
- showDeleted?: boolean;
- excludeUnassigned?: boolean;
- // label should be "{label key}:{label value}" format
- labels?: string[];
- engines?: Engine[];
- excludeEngines?: Engine[];
- table?: string;
-}
+export type { DatabaseFilter };
const isValidParentName = (parent: string): boolean => {
if (parent.startsWith(workspaceNamePrefix)) {
diff --git a/frontend/src/store/modules/v1/index.ts b/frontend/src/store/modules/v1/index.ts
index 55b533b3d6..ec3dc97130 100644
--- a/frontend/src/store/modules/v1/index.ts
+++ b/frontend/src/store/modules/v1/index.ts
@@ -1,7 +1,5 @@
export * from "./actuator";
export * from "./auth";
-export * from "./auditLog";
-export * from "./changelog";
export * from "./common";
export * from "./database";
export * from "./databaseCatalog";
@@ -13,12 +11,10 @@ export * from "./instance";
export * from "./instanceResource";
export * from "./issue";
export * from "./issueComment";
-export * from "./localSheet";
export * from "./permission";
export * from "./policy";
export * from "./project";
export * from "./projectIamPolicy";
-export * from "./projectWebhook";
export * from "./setting";
export * from "./sheet";
export * from "./sql";
diff --git a/frontend/src/store/modules/v1/localSheet.ts b/frontend/src/store/modules/v1/localSheet.ts
deleted file mode 100644
index 4a3a283975..0000000000
--- a/frontend/src/store/modules/v1/localSheet.ts
+++ /dev/null
@@ -1,58 +0,0 @@
-import { create as createProto } from "@bufbuild/protobuf";
-import { defineStore } from "pinia";
-import { reactive } from "vue";
-import type { Sheet } from "@/types/proto-es/v1/sheet_service_pb";
-import { SheetSchema } from "@/types/proto-es/v1/sheet_service_pb";
-import { extractProjectResourceName } from "@/utils";
-import { useSheetV1Store } from "./sheet";
-
-const state = reactive({
- uid: -101,
-});
-
-/**
- * The `local_sheet` store is used for creating and editing local sheets pending
- * create. Once used they should be saved and organized by the `sheet` store.
- */
-export const useLocalSheetStore = defineStore("local_sheet", () => {
- const sheetsByName = reactive(new Map<string, Sheet>());
-
- const nextUID = () => {
- return state.uid--;
- };
-
- const createLocalSheet = (name: string, defaults: Partial<Sheet> = {}) => {
- const sheet = createProto(SheetSchema, {
- name,
- content: defaults.content || new Uint8Array(),
- contentSize: defaults.contentSize || BigInt(0),
- });
- return reactive(sheet);
- };
-
- const getOrCreateSheetByName = (name: string) => {
- const existed = sheetsByName.get(name);
- if (existed) {
- return existed;
- }
- const sheet = createLocalSheet(name);
- sheetsByName.set(name, sheet);
- return sheet;
- };
-
- const saveLocalSheetToRemote = async (localSheet: Sheet) => {
- const project = extractProjectResourceName(localSheet.name);
- const remoteSheet = await useSheetV1Store().createSheet(
- `projects/${project}`,
- localSheet
- );
- return remoteSheet;
- };
-
- return {
- nextUID,
- createLocalSheet,
- getOrCreateSheetByName,
- saveLocalSheetToRemote,
- };
-});
diff --git a/frontend/src/store/modules/v1/projectIamPolicy.ts b/frontend/src/store/modules/v1/projectIamPolicy.ts
index 3ea3a35e8d..fc32ace05a 100644
--- a/frontend/src/store/modules/v1/projectIamPolicy.ts
+++ b/frontend/src/store/modules/v1/projectIamPolicy.ts
@@ -108,9 +108,19 @@ export const useProjectIamPolicyStore = defineStore(
return getProjectIamPolicy(project);
};
+ // Bridge entry-point so an external fetcher (e.g. the Zustand app
+ // `iam` slice) can cache its result here and reuse the permission
+ // chain without a second RPC. Also invalidates the role-list cache,
+ // matching `fetchProjectIamPolicy`.
+ const setProjectIamPolicy = (project: string, policy: IamPolicy) => {
+ policyMap.set(project, policy);
+ usePermissionStore().invalidCacheByProject(project);
+ };
+
return {
getProjectIamPolicy,
getOrFetchProjectIamPolicy,
+ setProjectIamPolicy,
updateProjectIamPolicy,
};
}
diff --git a/frontend/src/store/modules/v1/projectWebhook.ts b/frontend/src/store/modules/v1/projectWebhook.ts
deleted file mode 100644
index 137c23d2c9..0000000000
--- a/frontend/src/store/modules/v1/projectWebhook.ts
+++ /dev/null
@@ -1,68 +0,0 @@
-import { create } from "@bufbuild/protobuf";
-import { defineStore } from "pinia";
-import { projectServiceClientConnect } from "@/connect";
-
-import {
- AddWebhookRequestSchema,
- type Project,
- RemoveWebhookRequestSchema,
- TestWebhookRequestSchema,
- UpdateWebhookRequestSchema,
- type Webhook,
-} from "@/types/proto-es/v1/project_service_pb";
-import { extractProjectWebhookID } from "@/utils";
-
-export const useProjectWebhookV1Store = defineStore("projectWebhook_v1", () => {
- const getProjectWebhookFromProjectById = (
- project: Project,
- webhookId: string
- ) => {
- return project.webhooks.find((webhook) => {
- return extractProjectWebhookID(webhook.name) === webhookId;
- });
- };
- const createProjectWebhook = async (project: string, webhook: Webhook) => {
- const request = create(AddWebhookRequestSchema, {
- project,
- webhook,
- });
- const response = await projectServiceClientConnect.addWebhook(request);
- return response;
- };
- const updateProjectWebhook = async (
- webhook: Webhook,
- updateMask: string[]
- ) => {
- const request = create(UpdateWebhookRequestSchema, {
- webhook,
- updateMask: { paths: updateMask },
- });
- const response = await projectServiceClientConnect.updateWebhook(request);
- return response;
- };
- const deleteProjectWebhook = async (webhook: Webhook) => {
- const request = create(RemoveWebhookRequestSchema, {
- webhook,
- });
- const response = await projectServiceClientConnect.removeWebhook(request);
- return response;
- };
- const testProjectWebhook = async (project: Project, webhook: Webhook) => {
- const request = create(TestWebhookRequestSchema, {
- project: project.name,
- webhook,
- });
- const response = await projectServiceClientConnect.testWebhook(request);
- return {
- error: response.error,
- };
- };
-
- return {
- getProjectWebhookFromProjectById,
- createProjectWebhook,
- updateProjectWebhook,
- deleteProjectWebhook,
- testProjectWebhook,
- };
-});
diff --git a/frontend/src/store/modules/v1/taskRunLog.ts b/frontend/src/store/modules/v1/taskRunLog.ts
deleted file mode 100644
index e253441603..0000000000
--- a/frontend/src/store/modules/v1/taskRunLog.ts
+++ /dev/null
@@ -1,61 +0,0 @@
-import { create } from "@bufbuild/protobuf";
-import { defineStore } from "pinia";
-import { reactive } from "vue";
-import { rolloutServiceClientConnect } from "@/connect";
-import type { TaskRunLog } from "@/types/proto-es/v1/rollout_service_pb";
-import {
- GetTaskRunLogRequestSchema,
- TaskRunLogSchema,
-} from "@/types/proto-es/v1/rollout_service_pb";
-
-export const useTaskRunLogStore = defineStore("taskRunLog", () => {
- // Map from taskRun name to TaskRunLog
- const taskRunLogByName = reactive(new Map<string, TaskRunLog>());
-
- const getTaskRunLog = (taskRunName: string): TaskRunLog => {
- const existing = taskRunLogByName.get(taskRunName);
- if (existing) {
- return existing;
- }
-
- // Return empty log if not found
- const emptyLog = create(TaskRunLogSchema, {});
- return emptyLog;
- };
-
- const fetchTaskRunLog = async (
- taskRunName: string,
- options?: { skipCache?: boolean }
- ): Promise<TaskRunLog> => {
- if (!options?.skipCache) {
- const existing = taskRunLogByName.get(taskRunName);
- if (existing) {
- return existing;
- }
- }
-
- try {
- const request = create(GetTaskRunLogRequestSchema, {
- parent: taskRunName,
- });
- const response = await rolloutServiceClientConnect.getTaskRunLog(request);
- taskRunLogByName.set(taskRunName, response);
- return response;
- } catch (error) {
- console.error(`Failed to fetch task run log for ${taskRunName}:`, error);
- const emptyLog = create(TaskRunLogSchema, {});
- taskRunLogByName.set(taskRunName, emptyLog);
- return emptyLog;
- }
- };
-
- const clearCache = () => {
- taskRunLogByName.clear();
- };
-
- return {
- getTaskRunLog,
- fetchTaskRunLog,
- clearCache,
- };
-});
diff --git a/frontend/src/utils/blob-storage.ts b/frontend/src/utils/blob-storage.ts
new file mode 100644
index 0000000000..f5bb7a599f
--- /dev/null
+++ b/frontend/src/utils/blob-storage.ts
@@ -0,0 +1,43 @@
+import PouchDB from "pouchdb";
+import PouchDBFind from "pouchdb-find";
+
+PouchDB.plugin(PouchDBFind);
+
+// Module-level PouchDB instance for the "bb.storage" key/value store used by
+// SQL-editor blob-passing (e.g. stashing a SQL statement for the issue/plan
+// creation page to pick up). The Pinia `useStorageStore` opens a parallel
+// PouchDB instance against the same DB name — both share the underlying
+// IndexedDB layer, so reads on one side observe writes from the other.
+const db = new PouchDB<{ _id: string; value: unknown }>("bb.storage", {
+ auto_compaction: true,
+ revs_limit: 1,
+});
+
+export const putBlob = async <T = unknown>(
+ key: string,
+ value: T
+): Promise<void> => {
+ await db.put({ _id: key, value }, { force: true });
+};
+
+export const getBlob = async <T = unknown>(
+ key: string
+): Promise<T | undefined> => {
+ try {
+ const doc = await db.get(key);
+ return doc.value as T;
+ } catch {
+ return undefined;
+ }
+};
+
+export const removeBlob = async (key: string): Promise<void> => {
+ try {
+ const doc = await db.get(key);
+ if (doc) {
+ await db.remove(doc);
+ }
+ } catch {
+ // not found: nothing to remove
+ }
+};
diff --git a/frontend/src/views/sql-editor/Sheet/context.ts b/frontend/src/views/sql-editor/Sheet/context.ts
index a00eaeaf63..b458f5dc59 100644
--- a/frontend/src/views/sql-editor/Sheet/context.ts
+++ b/frontend/src/views/sql-editor/Sheet/context.ts
@@ -17,7 +17,6 @@ import {
subscribeSQLEditorTabsState,
useSQLEditorTabsStore,
} from "@/react/stores/sqlEditor/tab";
-import { pushNotification, useCurrentUserV1 } from "@/store";
import type { SQLEditorTab, SQLEditorTabMode } from "@/types";
import { DEBOUNCE_SEARCH_DELAY } from "@/types";
import {
@@ -265,8 +264,8 @@ const currentScope = (): { project: string; email: string } | null => {
const project = getSQLEditorEditorState().project;
if (!project) return null;
try {
- const me = useCurrentUserV1();
- return { project, email: me?.value?.email ?? "" };
+ const email = useAppStore.getState().currentUser?.email ?? "";
+ return { project, email };
} catch {
return null;
}
@@ -607,16 +606,12 @@ const worksheetsForView = (view: SheetViewMode): Worksheet[] => {
if (view !== "my" && view !== "shared") return [];
const filter = useSheetContextStore.getState().filter;
const project = getSQLEditorEditorState().project;
- // Use the Pinia current user — the same source the worksheet FETCH
- // filter uses (`fetchSheetListFor`), so it's reliably populated by the
- // time worksheets land. The app store's `currentUser` can still be
- // empty here, which would misclassify every worksheet as "shared".
- let email = "";
- try {
- email = useCurrentUserV1()?.value?.email ?? "";
- } catch {
- email = "";
- }
+ // SQLEditorLayout awaits `loadCurrentUser()` in its bootstrap, so by the
+ // time worksheets land here the app-store `currentUser` is populated.
+ // Empty `email` falls through to creator `"users/"`, which matches no
+ // worksheets — they'd render as Shared rather than Mine, same fallback
+ // the previous Pinia path had.
+ const email = useAppStore.getState().currentUser?.email ?? "";
const creator = `users/${email}`;
let list = useAppStore
.getState()
@@ -698,20 +693,20 @@ const fetchSheetListFor = async (view: SheetViewMode) => {
state.setViewIsLoading(view, true);
try {
const sheetStore = useAppStore.getState();
- const me = useCurrentUserV1();
+ const email = sheetStore.currentUser?.email ?? "";
const project = getSQLEditorEditorState().project;
switch (view) {
case "my":
await sheetStore.fetchWorksheetList(
project,
- `creator == "users/${me.value.email}"`
+ `creator == "users/${email}"`
);
break;
case "shared":
await sheetStore.fetchWorksheetList(
project,
[
- `creator != "users/${me.value.email}"`,
+ `creator != "users/${email}"`,
`visibility in ["${Worksheet_Visibility[Worksheet_Visibility.PROJECT_READ]}","${Worksheet_Visibility[Worksheet_Visibility.PROJECT_WRITE]}"]`,
].join(" && ")
);
@@ -768,12 +763,9 @@ const getViewContext = (view: SheetViewMode): ViewContext => {
// ---- side effects (initialized lazily on first use) ------------------------
const isWorksheetCreator = (worksheet: { creator: string }) => {
- try {
- const me = useCurrentUserV1();
- return worksheet.creator === `users/${me.value.email}`;
- } catch {
- return false;
- }
+ const email = useAppStore.getState().currentUser?.email;
+ if (!email) return false;
+ return worksheet.creator === `users/${email}`;
};
const batchUpdateWorksheetFolders = async (
@@ -1115,7 +1107,7 @@ export const openWorksheetByName = async ({
if (!sheet) return undefined;
if (!isWorksheetReadableV1(sheet)) {
- pushNotification({
+ useAppStore.getState().notify({
module: "bytebase",
style: "CRITICAL",
title: t("common.access-denied"),