Skip to content

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

refactor(react): decouple dbGroup store from React (Vue→React migration) (#20460)

boojack8fa90b2c0611
diff --git a/docs/superpowers/plans/2026-06-01-react-store-decoupling-dbgroup.md b/docs/superpowers/plans/2026-06-01-react-store-decoupling-dbgroup.md
new file mode 100644
index 0000000000..312a31b54c
--- /dev/null
+++ b/docs/superpowers/plans/2026-06-01-react-store-decoupling-dbgroup.md
@@ -0,0 +1,709 @@
+# DBGroup Store Decoupling Implementation Plan
+
+> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
+
+**Goal:** Remove every React dependency on the Pinia `useDBGroupStore` by porting its API to the existing Zustand `createDBGroupSlice`, then cutting all 17 React consumers over to `useAppStore`.
+
+**Architecture:** The Zustand `useAppStore` already has a partial `DBGroupSlice` (`fetchDBGroup`, `listDBGroupsForProject`). This plan extends that slice to full parity with the Pinia store's public method surface (`getDBGroupByName`, `getOrFetchDBGroupByName`, `fetchDBGroupListByProjectName`, `createDatabaseGroup`, `updateDatabaseGroup`, `deleteDatabaseGroup`, `fetchDatabaseGroupMatchList`), then mechanically replaces `const dbGroupStore = useDBGroupStore()` + `dbGroupStore.X(...)` with `useAppStore.getState().X(...)`. The Pinia `dbGroup.ts` file stays — it still has Vue-side consumers (deleted later, in the routing phase).
+
+**Tech Stack:** Zustand 5 (slice pattern), Connect-ES clients, Vitest, TypeScript.
+
+**Scope note:** This is PR #1 of the React store decoupling effort described in `docs/superpowers/specs/2026-06-01-react-store-decoupling-design.md`. The Vue composables `useDBGroupListByProject` / `useDatabaseGroupByName` exported from `store/modules/dbGroup.ts` have **no React consumers** (verified) and are out of scope.
+
+---
+
+## File Structure
+
+**Modified:**
+- `frontend/src/react/stores/app/types.ts` — extend `DBGroupSlice` type (one responsibility: app store type surface).
+- `frontend/src/react/stores/app/dbGroup.ts` — implement the new slice methods (one responsibility: dbGroup data access).
+- `frontend/src/react/stores/app/index.test.ts` — add tests for the new methods.
+- 11 React **source** consumers — swap Pinia store for `useAppStore`.
+- 4 React **test** consumers — relocate the dbGroup mock from `@/store` to `@/react/stores/app`.
+
+**Not modified:**
+- `frontend/src/store/modules/dbGroup.ts` — Pinia store stays (Vue consumers remain).
+
+**Consumer inventory (source):**
+
+| File | Methods used |
+|---|---|
+| `react/components/MatchedDatabaseView.tsx` | `fetchDatabaseGroupMatchList` |
+| `react/components/DatabaseGroupTable.tsx` | (declares store; verify usage) |
+| `react/components/DatabaseGroupForm.tsx` | `getOrFetchDBGroupByName`, `createDatabaseGroup`, `updateDatabaseGroup` |
+| `react/lib/plan/issue.ts` | `getDBGroupByName` |
+| `react/pages/project/ProjectGitOpsPage.tsx` | (declares store; verify usage) |
+| `react/pages/project/ProjectPlanDashboardPage.tsx` | (declares store; verify usage) |
+| `react/pages/project/ProjectDatabaseGroupDetailPage.tsx` | `getDBGroupByName`, `getOrFetchDBGroupByName`, `deleteDatabaseGroup` |
+| `react/pages/project/ProjectDatabaseGroupsPage.tsx` | `fetchDBGroupListByProjectName`, `deleteDatabaseGroup` |
+| `react/pages/project/issue-detail/components/IssueDetailDatabaseChangeView.tsx` | `getDBGroupByName`, `getOrFetchDBGroupByName` (+ threaded param) |
+| `react/pages/project/issue-detail/components/IssueDetailDatabaseExportView.tsx` | `getDBGroupByName`, `getOrFetchDBGroupByName` |
+| `react/pages/project/plan-detail/utils/rolloutPreview.ts` | `getOrFetchDBGroupByName` |
+| `react/pages/project/plan-detail/components/PlanDetailChangesBranch.tsx` | `getDBGroupByName`, `getOrFetchDBGroupByName` (+ threaded param) |
+| `react/pages/project/export-center/DataExportPrepSheet.tsx` | `getOrFetchDBGroupByName` |
+
+**Consumer inventory (test):** `ConnectionPane.test.tsx`, `IssueDetailDatabaseChangeView.test.tsx`, `PlanDetailChangesBranch.test.tsx`, `DataExportPrepSheet.test.tsx`.
+
+---
+
+## Task 1: Extend the DBGroupSlice type
+
+**Files:**
+- Modify: `frontend/src/react/stores/app/types.ts:296-309` (the `DBGroupSlice` type)
+
+- [ ] **Step 1: Add `ConditionGroupExpr` import**
+
+At the top of `types.ts`, add (grouped with other `@/plugins` / type imports, sorted by path):
+
+```typescript
+import type { ConditionGroupExpr } from "@/plugins/cel";
+```
+
+- [ ] **Step 2: Extend the `DBGroupSlice` type**
+
+Replace the existing `DBGroupSlice` type body (currently ending after `listDBGroupsForProject`) with:
+
+```typescript
+export type DBGroupSlice = {
+ dbGroupsByName: Record<string, DatabaseGroup>;
+ // Tracks which view (BASIC/FULL) the cached entry was fetched with, so a
+ // FULL request (needs `matchedDatabases`) refetches when only BASIC is
+ // cached.
+ dbGroupViewByName: Record<string, DatabaseGroupView>;
+ dbGroupRequests: Record<string, Promise<DatabaseGroup | undefined>>;
+ dbGroupErrorsByName: Record<string, Error | undefined>;
+ fetchDBGroup: (
+ name: string,
+ view?: DatabaseGroupView
+ ) => Promise<DatabaseGroup | undefined>;
+ listDBGroupsForProject: (project: string) => Promise<DatabaseGroup[]>;
+ // Synchronous cache read. Returns `unknownDatabaseGroup()` when absent or
+ // when a FULL view is requested but only BASIC is cached.
+ getDBGroupByName: (name: string, view?: DatabaseGroupView) => DatabaseGroup;
+ getOrFetchDBGroupByName: (
+ name: string,
+ options?: {
+ skipCache?: boolean;
+ silent?: boolean;
+ view?: DatabaseGroupView;
+ }
+ ) => Promise<DatabaseGroup>;
+ fetchDBGroupListByProjectName: (
+ projectName: string,
+ view: DatabaseGroupView
+ ) => Promise<DatabaseGroup[]>;
+ createDatabaseGroup: (params: {
+ projectName: string;
+ databaseGroup: Pick<
+ DatabaseGroup,
+ "$typeName" | "name" | "title" | "databaseExpr"
+ >;
+ databaseGroupId: string;
+ validateOnly?: boolean;
+ }) => Promise<DatabaseGroup>;
+ updateDatabaseGroup: (
+ databaseGroup: DatabaseGroup,
+ updateMask: string[]
+ ) => Promise<DatabaseGroup>;
+ deleteDatabaseGroup: (name: string) => Promise<void>;
+ fetchDatabaseGroupMatchList: (params: {
+ projectName: string;
+ expr: ConditionGroupExpr;
+ }) => Promise<string[]>;
+};
+```
+
+- [ ] **Step 3: Verify it type-checks (will fail on missing impls — expected)**
+
+Run: `pnpm --dir frontend type-check`
+Expected: errors in `dbGroup.ts` — "Property 'getDBGroupByName' is missing in type". This confirms the type is wired; Task 2 implements the methods.
+
+- [ ] **Step 4: Commit**
+
+```bash
+git add frontend/src/react/stores/app/types.ts
+git commit -m "feat(react/stores): extend DBGroupSlice type to Pinia parity"
+```
+
+---
+
+## Task 2: Implement the new slice methods
+
+**Files:**
+- Modify: `frontend/src/react/stores/app/dbGroup.ts`
+- Test: `frontend/src/react/stores/app/index.test.ts`
+
+- [ ] **Step 1: Write failing tests**
+
+Append to `frontend/src/react/stores/app/index.test.ts` (inside the existing top-level `describe` block, alongside the existing `fetchDBGroup` tests near line 1734). These exercise the sync getter's view-fallback and the cache-on-fetch behavior:
+
+```typescript
+describe("dbGroup parity methods", () => {
+ it("getDBGroupByName returns unknownDatabaseGroup when absent", () => {
+ const store = createAppStore();
+ const group = store.getState().getDBGroupByName("projects/p/databaseGroups/x");
+ expect(isValidDatabaseGroupName(group.name)).toBe(false);
+ });
+
+ it("getDBGroupByName with FULL view misses a BASIC-only cache entry", () => {
+ const store = createAppStore();
+ const name = "projects/p/databaseGroups/g";
+ store.setState({
+ dbGroupsByName: {
+ [name]: create(DatabaseGroupSchema, { name, title: "g" }),
+ },
+ dbGroupViewByName: { [name]: DatabaseGroupView.BASIC },
+ });
+ // BASIC request is satisfied:
+ expect(store.getState().getDBGroupByName(name).name).toBe(name);
+ // FULL request is not satisfied by a BASIC entry:
+ const full = store
+ .getState()
+ .getDBGroupByName(name, DatabaseGroupView.FULL);
+ expect(isValidDatabaseGroupName(full.name)).toBe(false);
+ });
+
+ it("getOrFetchDBGroupByName returns cached entry without a request", async () => {
+ const store = createAppStore();
+ const name = "projects/p/databaseGroups/g";
+ store.setState({
+ dbGroupsByName: {
+ [name]: create(DatabaseGroupSchema, { name, title: "g" }),
+ },
+ dbGroupViewByName: { [name]: DatabaseGroupView.BASIC },
+ });
+ const group = await store.getState().getOrFetchDBGroupByName(name);
+ expect(group.name).toBe(name);
+ });
+});
+```
+
+Ensure the test file imports `create` from `@bufbuild/protobuf`, `DatabaseGroupSchema` + `DatabaseGroupView` from `@/types/proto-es/v1/database_group_service_pb`, and `isValidDatabaseGroupName` from `@/types/dbGroup` (add any that are missing to the existing import block).
+
+- [ ] **Step 2: Run tests to verify they fail**
+
+Run: `pnpm --dir frontend test -- src/react/stores/app/index.test.ts`
+Expected: FAIL — `getDBGroupByName is not a function` / `getOrFetchDBGroupByName is not a function`.
+
+- [ ] **Step 3: Implement the methods**
+
+Replace the entire body of `frontend/src/react/stores/app/dbGroup.ts` with:
+
+```typescript
+import { create as createProto } from "@bufbuild/protobuf";
+import { createContextValues } from "@connectrpc/connect";
+import { head } from "lodash-es";
+import { databaseGroupServiceClientConnect } from "@/connect";
+import { silentContextKey } from "@/connect/context-key";
+import { buildCELExpr } from "@/plugins/cel";
+import { isValidDatabaseGroupName, unknownDatabaseGroup } from "@/types/dbGroup";
+import { ExprSchema } from "@/types/proto-es/google/type/expr_pb";
+import {
+ type DatabaseGroup,
+ CreateDatabaseGroupRequestSchema,
+ DatabaseGroupSchema,
+ DatabaseGroupView,
+ DeleteDatabaseGroupRequestSchema,
+ GetDatabaseGroupRequestSchema,
+ ListDatabaseGroupsRequestSchema,
+ UpdateDatabaseGroupRequestSchema,
+} from "@/types/proto-es/v1/database_group_service_pb";
+import { batchConvertParsedExprToCELString } from "@/utils";
+import { databaseGroupNamePrefix } from "@/store/modules/v1/common";
+import type { AppSliceCreator, DBGroupSlice } from "./types";
+import { toError } from "./utils";
+
+export const createDBGroupSlice: AppSliceCreator<DBGroupSlice> = (set, get) => {
+ // Immutable cache write. A name maps to a single group + the view it was
+ // fetched with; overwriting is sufficient (no per-view keying needed).
+ const setCache = (group: DatabaseGroup, view: DatabaseGroupView) => {
+ set((state) => ({
+ dbGroupsByName: { ...state.dbGroupsByName, [group.name]: group },
+ dbGroupViewByName: { ...state.dbGroupViewByName, [group.name]: view },
+ }));
+ };
+ const removeCache = (name: string) => {
+ set((state) => {
+ const { [name]: _g, ...dbGroupsByName } = state.dbGroupsByName;
+ const { [name]: _v, ...dbGroupViewByName } = state.dbGroupViewByName;
+ return { dbGroupsByName, dbGroupViewByName };
+ });
+ };
+
+ return {
+ dbGroupsByName: {},
+ dbGroupViewByName: {},
+ dbGroupRequests: {},
+ dbGroupErrorsByName: {},
+
+ fetchDBGroup: async (name, view = DatabaseGroupView.BASIC) => {
+ if (!isValidDatabaseGroupName(name)) return undefined;
+ const existing = get().dbGroupsByName[name];
+ if (
+ existing &&
+ (view !== DatabaseGroupView.FULL ||
+ get().dbGroupViewByName[name] === DatabaseGroupView.FULL)
+ ) {
+ return existing;
+ }
+ const pending = get().dbGroupRequests[name];
+ if (pending) return pending;
+
+ const request = databaseGroupServiceClientConnect
+ .getDatabaseGroup(
+ createProto(GetDatabaseGroupRequestSchema, { name, view })
+ )
+ .then((group: DatabaseGroup) => {
+ set((state) => {
+ const { [name]: _, ...dbGroupRequests } = state.dbGroupRequests;
+ return {
+ dbGroupsByName: { ...state.dbGroupsByName, [group.name]: group },
+ dbGroupViewByName: {
+ ...state.dbGroupViewByName,
+ [group.name]: view,
+ },
+ dbGroupErrorsByName: {
+ ...state.dbGroupErrorsByName,
+ [name]: undefined,
+ },
+ dbGroupRequests,
+ };
+ });
+ return group;
+ })
+ .catch((error) => {
+ set((state) => {
+ const { [name]: _, ...dbGroupRequests } = state.dbGroupRequests;
+ return {
+ dbGroupErrorsByName: {
+ ...state.dbGroupErrorsByName,
+ [name]: toError(error),
+ },
+ dbGroupRequests,
+ };
+ });
+ return undefined;
+ });
+ set((state) => ({
+ dbGroupRequests: { ...state.dbGroupRequests, [name]: request },
+ }));
+ return request;
+ },
+
+ listDBGroupsForProject: async (project) => {
+ const response =
+ await databaseGroupServiceClientConnect.listDatabaseGroups(
+ createProto(ListDatabaseGroupsRequestSchema, { parent: project })
+ );
+ for (const group of response.databaseGroups) {
+ setCache(group, DatabaseGroupView.BASIC);
+ }
+ return response.databaseGroups;
+ },
+
+ getDBGroupByName: (name, view = DatabaseGroupView.UNSPECIFIED) => {
+ const group = get().dbGroupsByName[name];
+ if (group) {
+ const cachedView = get().dbGroupViewByName[name];
+ const satisfied =
+ view === DatabaseGroupView.FULL
+ ? cachedView === DatabaseGroupView.FULL
+ : true; // UNSPECIFIED / BASIC are satisfied by either view
+ if (satisfied) return group;
+ }
+ return unknownDatabaseGroup();
+ },
+
+ getOrFetchDBGroupByName: async (name, options) => {
+ const {
+ skipCache = false,
+ silent = false,
+ view = DatabaseGroupView.BASIC,
+ } = options ?? {};
+ if (!skipCache) {
+ const cached = get().getDBGroupByName(name, view);
+ if (isValidDatabaseGroupName(cached.name)) {
+ return cached;
+ }
+ }
+ const group = await databaseGroupServiceClientConnect.getDatabaseGroup(
+ createProto(GetDatabaseGroupRequestSchema, { name, view }),
+ { contextValues: createContextValues().set(silentContextKey, silent) }
+ );
+ setCache(group, view);
+ return group;
+ },
+
+ fetchDBGroupListByProjectName: async (projectName, view) => {
+ const response =
+ await databaseGroupServiceClientConnect.listDatabaseGroups(
+ createProto(ListDatabaseGroupsRequestSchema, {
+ parent: projectName,
+ view,
+ })
+ );
+ for (const group of response.databaseGroups) {
+ setCache(group, view);
+ }
+ return response.databaseGroups;
+ },
+
+ createDatabaseGroup: async ({
+ projectName,
+ databaseGroup,
+ databaseGroupId,
+ validateOnly = false,
+ }) => {
+ const newDatabaseGroup = createProto(DatabaseGroupSchema, {
+ name: databaseGroup.name,
+ title: databaseGroup.title,
+ databaseExpr: databaseGroup.databaseExpr,
+ matchedDatabases: [],
+ });
+ const created =
+ await databaseGroupServiceClientConnect.createDatabaseGroup(
+ createProto(CreateDatabaseGroupRequestSchema, {
+ parent: projectName,
+ databaseGroup: newDatabaseGroup,
+ databaseGroupId,
+ validateOnly,
+ }),
+ {
+ contextValues: createContextValues().set(
+ silentContextKey,
+ validateOnly
+ ),
+ }
+ );
+ if (!validateOnly) {
+ setCache(created, DatabaseGroupView.FULL);
+ }
+ return created;
+ },
+
+ updateDatabaseGroup: async (databaseGroup, updateMask) => {
+ const updated =
+ await databaseGroupServiceClientConnect.updateDatabaseGroup(
+ createProto(UpdateDatabaseGroupRequestSchema, {
+ databaseGroup,
+ updateMask: { paths: updateMask },
+ })
+ );
+ setCache(updated, DatabaseGroupView.FULL);
+ return updated;
+ },
+
+ deleteDatabaseGroup: async (name) => {
+ await databaseGroupServiceClientConnect.deleteDatabaseGroup(
+ createProto(DeleteDatabaseGroupRequestSchema, { name })
+ );
+ removeCache(name);
+ },
+
+ fetchDatabaseGroupMatchList: async ({ projectName, expr }) => {
+ const celexpr = await buildCELExpr(expr);
+ if (!celexpr) {
+ return [];
+ }
+ const celStrings = await batchConvertParsedExprToCELString([celexpr]);
+ const expression = head(celStrings) || "true";
+ const validateOnlyResourceId = `creating-database-group-${Date.now()}`;
+ const result = await get().createDatabaseGroup({
+ projectName,
+ databaseGroup: createProto(DatabaseGroupSchema, {
+ name: `${projectName}/${databaseGroupNamePrefix}${validateOnlyResourceId}`,
+ title: validateOnlyResourceId,
+ databaseExpr: createProto(ExprSchema, { expression }),
+ }),
+ databaseGroupId: validateOnlyResourceId,
+ validateOnly: true,
+ });
+ return result.matchedDatabases.map((item) => item.name);
+ },
+ };
+};
+```
+
+- [ ] **Step 4: Run tests to verify they pass**
+
+Run: `pnpm --dir frontend test -- src/react/stores/app/index.test.ts`
+Expected: PASS (new `dbGroup parity methods` block + the pre-existing `fetchDBGroup` tests).
+
+- [ ] **Step 5: Lint + type-check the store layer**
+
+Run: `pnpm --dir frontend type-check`
+Expected: PASS for `dbGroup.ts` and `types.ts` (consumer files still reference Pinia — they are migrated in later tasks and remain valid until then).
+
+- [ ] **Step 6: Commit**
+
+```bash
+git add frontend/src/react/stores/app/dbGroup.ts frontend/src/react/stores/app/index.test.ts
+git commit -m "feat(react/stores): port dbGroup methods to Zustand slice"
+```
+
+---
+
+## Consumer migration — transformation rule (applies to Tasks 3–6)
+
+For every **source** consumer:
+
+1. Remove `useDBGroupStore` from the `@/store` (or `@/store/modules` / `@/store/modules/dbGroup`) import. If that import only provided `useDBGroupStore`, delete the whole import line; otherwise keep the other names.
+2. Add (or extend an existing) `import { useAppStore } from "@/react/stores/app";`.
+3. Delete the `const dbGroupStore = useDBGroupStore();` line.
+4. Replace each `dbGroupStore.METHOD(...)` with `useAppStore.getState().METHOD(...)`. Signatures are identical, so arguments are unchanged.
+5. Remove `dbGroupStore` from any `useCallback` / `useMemo` / `useEffect` dependency arrays — `useAppStore.getState()` is a stable module-level reference and must not be a dep.
+6. For helpers that receive the store as a parameter typed `ReturnType<typeof useDBGroupStore>` (see Task 5): delete that parameter and call `useAppStore.getState()` inside the helper instead; update all call sites.
+
+**Concrete example** (from `ProjectDatabaseGroupsPage.tsx`):
+
+```diff
+-import { useVueState } from "@/react/hooks/useVueState";
+-import { useDBGroupStore, useProjectV1Store } from "@/store";
++import { useVueState } from "@/react/hooks/useVueState";
++import { useProjectV1Store } from "@/store";
++import { useAppStore } from "@/react/stores/app";
+ ...
+- const dbGroupStore = useDBGroupStore();
+ ...
+- dbGroupStore
+- .fetchDBGroupListByProjectName(projectName, DatabaseGroupView.BASIC)
++ useAppStore
++ .getState()
++ .fetchDBGroupListByProjectName(projectName, DatabaseGroupView.BASIC)
+ .then(...)
+- }, [projectName, dbGroupStore]);
++ }, [projectName]);
+ ...
+- await dbGroupStore.deleteDatabaseGroup(deleteTarget.name);
++ await useAppStore.getState().deleteDatabaseGroup(deleteTarget.name);
+- }, [deleteTarget, dbGroupStore]);
++ }, [deleteTarget]);
+```
+
+After each task, verify the touched files no longer reference the Pinia store:
+
+Run: `grep -rn "useDBGroupStore\|dbGroupStore" <files in this task>`
+Expected: no matches.
+
+---
+
+## Task 3: Migrate straightforward source consumers
+
+**Files (read each, apply the transformation rule):**
+- Modify: `frontend/src/react/components/MatchedDatabaseView.tsx` — `fetchDatabaseGroupMatchList` (line ~148)
+- Modify: `frontend/src/react/components/DatabaseGroupForm.tsx` — `getOrFetchDBGroupByName`, `createDatabaseGroup`, `updateDatabaseGroup`
+- Modify: `frontend/src/react/pages/project/ProjectDatabaseGroupsPage.tsx` — `fetchDBGroupListByProjectName`, `deleteDatabaseGroup`
+- Modify: `frontend/src/react/pages/project/ProjectDatabaseGroupDetailPage.tsx` — `getDBGroupByName`, `getOrFetchDBGroupByName`, `deleteDatabaseGroup`
+- Modify: `frontend/src/react/pages/project/export-center/DataExportPrepSheet.tsx` — `getOrFetchDBGroupByName` (lines ~99, ~181, ~869)
+- Modify: `frontend/src/react/lib/plan/issue.ts` — `getDBGroupByName` (line ~26)
+- Modify: `frontend/src/react/pages/project/plan-detail/utils/rolloutPreview.ts` — `getOrFetchDBGroupByName` (line ~106)
+
+- [ ] **Step 1: Apply the transformation rule to each file above.** For `issue.ts` and `rolloutPreview.ts` (plain `.ts` helpers, not components), the same rule applies — `useAppStore.getState()` works outside React render.
+
+- [ ] **Step 2: Verify no Pinia references remain in these files**
+
+Run:
+```bash
+grep -rn "useDBGroupStore\|dbGroupStore" frontend/src/react/components/MatchedDatabaseView.tsx frontend/src/react/components/DatabaseGroupForm.tsx frontend/src/react/pages/project/ProjectDatabaseGroupsPage.tsx frontend/src/react/pages/project/ProjectDatabaseGroupDetailPage.tsx frontend/src/react/pages/project/export-center/DataExportPrepSheet.tsx frontend/src/react/lib/plan/issue.ts frontend/src/react/pages/project/plan-detail/utils/rolloutPreview.ts
+```
+Expected: no matches.
+
+- [ ] **Step 3: Type-check**
+
+Run: `pnpm --dir frontend type-check`
+Expected: PASS for these files (other unmigrated consumers and their tests may still reference Pinia — that is fine).
+
+- [ ] **Step 4: Commit**
+
+```bash
+git add frontend/src/react/components/MatchedDatabaseView.tsx frontend/src/react/components/DatabaseGroupForm.tsx frontend/src/react/pages/project/ProjectDatabaseGroupsPage.tsx frontend/src/react/pages/project/ProjectDatabaseGroupDetailPage.tsx frontend/src/react/pages/project/export-center/DataExportPrepSheet.tsx frontend/src/react/lib/plan/issue.ts frontend/src/react/pages/project/plan-detail/utils/rolloutPreview.ts
+git commit -m "refactor(react): migrate straightforward dbGroup consumers to useAppStore"
+```
+
+---
+
+## Task 4: Migrate IssueDetailDatabaseExportView
+
+**Files:**
+- Modify: `frontend/src/react/pages/project/issue-detail/components/IssueDetailDatabaseExportView.tsx`
+
+This file has two `const dbGroupStore = useDBGroupStore()` declarations (lines ~591, ~681) and several `getDBGroupByName` / `getOrFetchDBGroupByName` calls (lines ~598, ~684, ~696). No threaded param.
+
+- [ ] **Step 1: Apply the transformation rule** to both blocks. Remove both `const dbGroupStore = ...` lines; replace each call with `useAppStore.getState().METHOD(...)`; drop `dbGroupStore` from any dep arrays.
+
+- [ ] **Step 2: Verify no Pinia references remain**
+
+Run: `grep -rn "useDBGroupStore\|dbGroupStore" frontend/src/react/pages/project/issue-detail/components/IssueDetailDatabaseExportView.tsx`
+Expected: no matches.
+
+- [ ] **Step 3: Type-check**
+
+Run: `pnpm --dir frontend type-check`
+Expected: PASS for this file.
+
+- [ ] **Step 4: Commit**
+
+```bash
+git add frontend/src/react/pages/project/issue-detail/components/IssueDetailDatabaseExportView.tsx
+git commit -m "refactor(react): migrate IssueDetailDatabaseExportView dbGroup usage"
+```
+
+---
+
+## Task 5: Migrate consumers that thread the store as a parameter
+
+**Files:**
+- Modify: `frontend/src/react/pages/project/issue-detail/components/IssueDetailDatabaseChangeView.tsx`
+- Modify: `frontend/src/react/pages/project/plan-detail/components/PlanDetailChangesBranch.tsx`
+
+These thread the store into a non-component helper typed `dbGroupStore: ReturnType<typeof useDBGroupStore>` (`IssueDetailDatabaseChangeView.tsx:916`, `PlanDetailChangesBranch.tsx:2041`). Each also has plain in-component usage (`getDBGroupByName`, `getOrFetchDBGroupByName`).
+
+- [ ] **Step 1: Refactor the threaded helpers.** In each helper signature, delete the `dbGroupStore: ReturnType<typeof useDBGroupStore>` parameter. Inside the helper body, replace `dbGroupStore.METHOD(...)` with `useAppStore.getState().METHOD(...)`. Update the call sites to stop passing the store argument.
+
+- [ ] **Step 2: Apply the transformation rule** to the in-component `const dbGroupStore = useDBGroupStore()` declarations and their `.METHOD(...)` calls (including `PlanDetailChangesBranch.tsx:1870` which passes `DatabaseGroupView.FULL`).
+
+- [ ] **Step 3: Verify no Pinia references remain**
+
+Run: `grep -rn "useDBGroupStore\|dbGroupStore" frontend/src/react/pages/project/issue-detail/components/IssueDetailDatabaseChangeView.tsx frontend/src/react/pages/project/plan-detail/components/PlanDetailChangesBranch.tsx`
+Expected: no matches.
+
+- [ ] **Step 4: Type-check**
+
+Run: `pnpm --dir frontend type-check`
+Expected: PASS for these files.
+
+- [ ] **Step 5: Commit**
+
+```bash
+git add frontend/src/react/pages/project/issue-detail/components/IssueDetailDatabaseChangeView.tsx frontend/src/react/pages/project/plan-detail/components/PlanDetailChangesBranch.tsx
+git commit -m "refactor(react): migrate threaded dbGroup-store helpers to useAppStore"
+```
+
+---
+
+## Task 6: Migrate remaining "declared but verify" source consumers
+
+**Files:**
+- Modify: `frontend/src/react/components/DatabaseGroupTable.tsx:65`
+- Modify: `frontend/src/react/pages/project/ProjectGitOpsPage.tsx:45`
+- Modify: `frontend/src/react/pages/project/ProjectPlanDashboardPage.tsx:1122`
+
+Each declares `const dbGroupStore = useDBGroupStore()`. The earlier inventory grep did not surface a `dbGroupStore.METHOD` call in these — the store may be threaded into JSX/helpers or be dead.
+
+- [ ] **Step 1: For each file, locate every `dbGroupStore` reference.**
+
+Run (per file): `grep -n "dbGroupStore" <file>`
+
+- [ ] **Step 2: Apply the transformation rule.** If the declaration is unused, delete it and the `useDBGroupStore` import (dead code). If used, replace per the rule. If threaded into a helper, follow Task 5's helper-refactor approach.
+
+- [ ] **Step 3: Verify no Pinia references remain**
+
+Run: `grep -rn "useDBGroupStore\|dbGroupStore" frontend/src/react/components/DatabaseGroupTable.tsx frontend/src/react/pages/project/ProjectGitOpsPage.tsx frontend/src/react/pages/project/ProjectPlanDashboardPage.tsx`
+Expected: no matches.
+
+- [ ] **Step 4: Type-check**
+
+Run: `pnpm --dir frontend type-check`
+Expected: PASS for these files.
+
+- [ ] **Step 5: Commit**
+
+```bash
+git add frontend/src/react/components/DatabaseGroupTable.tsx frontend/src/react/pages/project/ProjectGitOpsPage.tsx frontend/src/react/pages/project/ProjectPlanDashboardPage.tsx
+git commit -m "refactor(react): migrate remaining dbGroup source consumers to useAppStore"
+```
+
+---
+
+## Task 7: Relocate dbGroup mocks in test consumers
+
+**Files:**
+- Modify: `frontend/src/react/components/sql-editor/ConnectionPane/ConnectionPane.test.tsx` (lines ~147, ~218)
+- Modify: `frontend/src/react/pages/project/issue-detail/components/IssueDetailDatabaseChangeView.test.tsx` (line ~232)
+- Modify: `frontend/src/react/pages/project/plan-detail/components/PlanDetailChangesBranch.test.tsx` (lines ~270, ~462, ~472, ~691, ~697)
+- Modify: `frontend/src/react/pages/project/export-center/DataExportPrepSheet.test.tsx` (line ~229)
+
+Each currently mocks `useDBGroupStore` inside a `vi.mock("@/store", ...)` factory. The source files now import `useAppStore` from `@/react/stores/app`, so the dbGroup methods must be exposed through a `useAppStore` mock.
+
+- [ ] **Step 1: For each test, move the dbGroup mock to `@/react/stores/app`.**
+
+Remove `useDBGroupStore` from the `@/store` mock factory. Add or extend a `@/react/stores/app` mock that exposes the dbGroup methods via `getState()`. Follow the established pattern in `react/stores/sqlEditor/worksheet.test.ts:85`:
+
+```typescript
+vi.mock("@/react/stores/app", () => ({
+ useAppStore: { getState: () => mocks.dbGroupStore },
+}));
+```
+
+If the test ALSO needs the hook-call form (`useAppStore((s) => s.x)`) for other state, make the mock both callable and carry `getState` — e.g.:
+
+```typescript
+const useAppStore = Object.assign(
+ (selector: (s: AppStoreShape) => unknown) => selector(mocks.appState),
+ { getState: () => mocks.appState }
+);
+vi.mock("@/react/stores/app", () => ({ useAppStore }));
+```
+
+Reuse the existing `mocks.dbGroupStore` object (with `getDBGroupByName`, `getOrFetchDBGroupByName`, `fetchDBGroupListByProjectName`, etc.) so the per-test `mockResolvedValue` / `mockReturnValue` setup (e.g. `PlanDetailChangesBranch.test.tsx:462-697`) keeps working — only the mocked module path changes.
+
+- [ ] **Step 2: Run each migrated test file**
+
+Run:
+```bash
+pnpm --dir frontend test -- src/react/components/sql-editor/ConnectionPane/ConnectionPane.test.tsx src/react/pages/project/issue-detail/components/IssueDetailDatabaseChangeView.test.tsx src/react/pages/project/plan-detail/components/PlanDetailChangesBranch.test.tsx src/react/pages/project/export-center/DataExportPrepSheet.test.tsx
+```
+Expected: PASS.
+
+- [ ] **Step 3: Commit**
+
+```bash
+git add frontend/src/react/components/sql-editor/ConnectionPane/ConnectionPane.test.tsx frontend/src/react/pages/project/issue-detail/components/IssueDetailDatabaseChangeView.test.tsx frontend/src/react/pages/project/plan-detail/components/PlanDetailChangesBranch.test.tsx frontend/src/react/pages/project/export-center/DataExportPrepSheet.test.tsx
+git commit -m "test(react): point dbGroup mocks at useAppStore"
+```
+
+---
+
+## Task 8: Final verification — React is dbGroup-Pinia-free
+
+- [ ] **Step 1: Assert zero Pinia dbGroup references under react/**
+
+Run:
+```bash
+grep -rn "useDBGroupStore" frontend/src/react
+```
+Expected: **no matches.** (If any remain, return to the relevant task.)
+
+- [ ] **Step 2: Confirm the Pinia store still has its Vue consumers (must NOT be deleted)**
+
+Run:
+```bash
+grep -rln "useDBGroupStore\|useDBGroupListByProject\|useDatabaseGroupByName" frontend/src --include="*.vue" --include="*.ts" | grep -v "/react/"
+```
+Expected: matches outside `react/` (Vue side). The file `frontend/src/store/modules/dbGroup.ts` is unchanged.
+
+- [ ] **Step 3: Full frontend verification suite**
+
+Run:
+```bash
+pnpm --dir frontend fix
+pnpm --dir frontend check
+pnpm --dir frontend type-check
+pnpm --dir frontend test
+```
+Expected: all PASS. (Note: the background-task exit code can be misleading — read the actual log output before claiming a pass.)
+
+- [ ] **Step 4: Final commit (if `fix` changed formatting)**
+
+```bash
+git add -A
+git commit -m "chore(react): format after dbGroup decoupling"
+```
+
+---
+
+## Self-Review Notes
+
+- **Spec coverage:** This plan covers the `dbGroup` row of the spec's scope table (PR #1). The parity step (spec recipe step 1) is Tasks 1–2; consumer cutover (step 2) is Tasks 3–7; verification (step 3) is Task 8. The guard script (spec PR #13) is intentionally out of scope for this PR.
+- **Out of scope, confirmed:** Pinia `dbGroup.ts` is not deleted (Task 8 Step 2 guards this); Vue composables `useDBGroupListByProject` / `useDatabaseGroupByName` have no React consumers.
+- **Type consistency:** Method names are identical between the Pinia store, the new slice (Task 2), the type (Task 1), and the consumer calls — enabling the mechanical 1:1 rewrite. `getDBGroupByName` default view is `UNSPECIFIED` (sync getter), matching the Pinia store.
diff --git a/docs/superpowers/specs/2026-06-01-react-store-decoupling-design.md b/docs/superpowers/specs/2026-06-01-react-store-decoupling-design.md
new file mode 100644
index 0000000000..436a5a8a98
--- /dev/null
+++ b/docs/superpowers/specs/2026-06-01-react-store-decoupling-design.md
@@ -0,0 +1,139 @@
+# React Store Decoupling — Design
+
+Date: 2026-06-01
+Status: Approved (design)
+
+## Background
+
+The Vue→React migration's view layer is effectively complete: 722 `.tsx` files,
+0 `naive-ui` imports, and all 86 dashboard/auth/setup/sqlEditor routes mount React
+through bridge components. The remaining Vue footprint is the runtime substrate —
+the Vue Router config, the app shell (`App.vue`, `AuthContext.vue`, 3 layouts, 5
+mount bridges), and the Pinia store layer (~40 modules, ~7,300 lines using Vue
+reactivity).
+
+The end goal is to **fully delete Vue**. Routing is the keystone that collapses
+the 10 remaining `.vue` files, but it is high-risk. The lower-risk first track is
+the **store layer**, and that work is already ~80% done on the React side: a
+Zustand `useAppStore` (`src/react/stores/app/index.ts:68`) is live and consumed by
+168 React files across ~26 slices (auth, project, instance, database, user, role,
+workspace, iam, etc.).
+
+What remains is a concentrated tail of React code still reaching back into Pinia.
+
+## Goal
+
+Sever React's remaining dependency on Pinia / Vue reactivity. Concretely:
+
+- `frontend/src/react/**` imports **zero** Pinia store modules (`@/store/...`).
+- `frontend/src/react/**` has **zero** `useVueState` reads that resolve to a Pinia
+ store.
+
+## Scope
+
+### In scope
+
+The ~12 Pinia stores still consumed from `react/` (~68 call sites). Counts are
+`useXxxStore()` call sites within `react/` at design time:
+
+| Pinia store | React call sites | Zustand slice today |
+|---|---|---|
+| `useDBGroupStore` | 19 | partial (`app/dbGroup.ts`) |
+| `useAuthStore` | 18 | exists (`app/auth.ts`) |
+| `useSQLReviewStore` | 9 | none |
+| `useUIStateStore` | 7 | none |
+| `useIssueCommentStore` | 4 | none |
+| `useWorkspaceApprovalSettingStore` | 3 | none |
+| `useStorageStore` | 2 | none |
+| `useProjectIamPolicyStore` | 2 | maybe (`app/iam.ts`) |
+| `useSQLStore` | 1 | exists (`app/sql.ts`) |
+| `useSQLEditorStore` | 1 | exists (`react/stores/sqlEditor`) |
+| `useRolloutStore` | 1 | none |
+| `usePlanStore` | 1 | none |
+
+Even stores with an existing slice need an **API-parity step** — the slices are
+partial. Example: the dbGroup slice has `fetchDBGroup` / `listDBGroupsForProject`,
+but the 19 consumers call `getOrFetchDBGroupByName` (11), `getDBGroupByName` (8),
+`create/update/deleteDatabaseGroup`, and `fetchDatabaseGroupMatchList` — none of
+which exist on the slice yet.
+
+### Explicitly NOT in scope (deferred to the later routing/shell phase)
+
+- **Deleting the Pinia store files.** They keep their Vue-side consumers (router,
+ the 10 `.vue` files, plugins, and 22 inter-store imports). They are deleted when
+ routing flips to React, not in this increment.
+- Vue Router, `App.vue`, `AuthContext.vue`, layouts, mount bridges.
+- Migrating store internals that have **no** React consumers (e.g. `setting`,
+ `subscription`, `environment`) — untouched until routing.
+
+## Approach
+
+**Store-by-store, one PR per store** (chosen over a single mega-PR and over a
+file-by-file `useVueState` sweep). Each PR is independently reviewable and
+verifiable, ships a fully-decoupled store, and front-loads the highest-value cases.
+
+### Per-store recipe (applied in each PR)
+
+1. **Parity.** Ensure the Zustand slice in `react/stores/app/<slice>.ts` exposes
+ every method the React consumers actually call. Newly-ported stores
+ (`sqlReview`, `uistate`, `issueComment`, `workspaceApprovalSetting`, `storage`,
+ `rollout`, `plan`) are added as **new slices inside `createAppStore`**,
+ consistent with the existing 26 slices. Port logic from the Pinia method
+ verbatim and reuse the same Connect client calls.
+2. **Cut consumers.** Replace `useVueState(() => useXStore().foo)` reactive reads
+ with Zustand selectors (`useAppStore(s => s.foo)`); replace plain
+ `useXStore().method()` calls with `useAppStore.getState().method()` or a
+ selector. Remove the now-dead `useVueState` wrappers.
+3. **Verify.** Confirm `react/` no longer imports that Pinia store, then run the
+ full frontend verification suite.
+
+### PR order
+
+1. `dbGroup` (19) — partial slice; validates the parity+cutover recipe at high value.
+2. `auth` (18) — existing slice; high count.
+3. `sqlReview` (9)
+4. `uistate` (7)
+5. `issueComment` (4)
+6. `workspaceApprovalSetting` (3)
+7. `storage` (2)
+8. `projectIamPolicy` (2)
+9. `sql` (1)
+10. `sqlEditor` (1)
+11. `rollout` (1)
+12. `plan` (1)
+13. **Guard PR** — add `frontend/scripts/check-react-no-pinia.mjs`, wired into
+ `pnpm --dir frontend check`, matching the `check-react-i18n.mjs` /
+ `check-react-layering.mjs` convention. It fails if anything under `react/**`
+ imports a `@/store` Pinia module or calls a Pinia `useXxxStore()`. This locks
+ the gain so the decoupling cannot regress.
+
+## Verification
+
+Per the migration playbook, every PR runs:
+
+- `pnpm --dir frontend fix`
+- `pnpm --dir frontend check`
+- `pnpm --dir frontend type-check`
+- `pnpm --dir frontend test`
+
+Parity ports add focused tests where the Pinia store had non-trivial behavior worth
+pinning (e.g. dbGroup's cache-with-fallback logic). The guard script lands last and
+makes the zero-Pinia-in-React invariant enforceable in CI.
+
+## Risks & mitigations
+
+- **Partial-parity surprises.** A slice may silently differ from the Pinia method
+ (caching, in-place mutation, error handling). Mitigation: port verbatim and add a
+ focused test before cutting consumers.
+- **Reactivity semantics drift.** `useVueState` surfaces in-place proxy mutations;
+ Zustand selectors compare by reference. Ports must produce new references on
+ update (immutable updates) so selectors re-render correctly.
+- **Hidden Vue consumers.** A method removed from Pinia could still be called by
+ Vue code. Mitigation: parity step **adds** to the slice and leaves the Pinia
+ store intact; nothing is removed from Pinia in this increment.
+
+## Out-of-increment follow-up
+
+After all 13 PRs, React is Pinia-free. The Pinia layer then has only Vue-side
+consumers and is deleted as part of the subsequent routing/app-shell migration —
+the keystone that also removes the 10 remaining `.vue` files.
diff --git a/frontend/src/react/components/DatabaseGroupForm.tsx b/frontend/src/react/components/DatabaseGroupForm.tsx
index 47194f22cc..0a93c64671 100644
--- a/frontend/src/react/components/DatabaseGroupForm.tsx
+++ b/frontend/src/react/components/DatabaseGroupForm.tsx
@@ -19,7 +19,8 @@ import {
FactorList,
getDatabaseGroupOptionConfigMap,
} from "@/react/lib/database-group/utils";
-import { pushNotification, useDBGroupStore } from "@/store";
+import { useAppStore } from "@/react/stores/app";
+import { pushNotification } from "@/store";
import {
databaseGroupNamePrefix,
getProjectNameAndDatabaseGroupName,
@@ -57,7 +58,6 @@ export function DatabaseGroupForm({
onCreated,
}: DatabaseGroupFormProps) {
const { t } = useTranslation();
- const dbGroupStore = useDBGroupStore();
const [title, setTitle] = useState("");
const [resourceId, setResourceId] = useState("");
@@ -109,7 +109,7 @@ export function DatabaseGroupForm({
async (id: string): Promise<ValidatedMessage[]> => {
try {
const name = `${project.name}/${databaseGroupNamePrefix}${id}`;
- await dbGroupStore.getOrFetchDBGroupByName(name, {
+ await useAppStore.getState().getOrFetchDBGroupByName(name, {
silent: true,
view: DatabaseGroupView.FULL,
});
@@ -120,7 +120,7 @@ export function DatabaseGroupForm({
return [];
}
},
- [project.name, dbGroupStore]
+ [project.name]
);
const doConfirm = async () => {
@@ -152,7 +152,7 @@ export function DatabaseGroupForm({
}
if (isCreating) {
- await dbGroupStore.createDatabaseGroup({
+ await useAppStore.getState().createDatabaseGroup({
projectName: project.name,
databaseGroup: create(DatabaseGroupSchema, {
name: `${project.name}/databaseGroups/${resourceId}`,
@@ -177,7 +177,7 @@ export function DatabaseGroupForm({
) {
updateMask.push("database_expr");
}
- await dbGroupStore.updateDatabaseGroup(
+ await useAppStore.getState().updateDatabaseGroup(
{
...databaseGroup,
title,
diff --git a/frontend/src/react/components/DatabaseGroupTable.tsx b/frontend/src/react/components/DatabaseGroupTable.tsx
index a7a748b076..7dfc4063dd 100644
--- a/frontend/src/react/components/DatabaseGroupTable.tsx
+++ b/frontend/src/react/components/DatabaseGroupTable.tsx
@@ -3,7 +3,7 @@ import { useEffect, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { DatabaseGroupDataTable } from "@/react/components/DatabaseGroupDataTable";
import { SearchInput } from "@/react/components/ui/search-input";
-import { useDBGroupStore } from "@/store/modules";
+import { useAppStore } from "@/react/stores/app";
import type { DatabaseGroup } from "@/types/proto-es/v1/database_group_service_pb";
import { DatabaseGroupView } from "@/types/proto-es/v1/database_group_service_pb";
@@ -62,7 +62,6 @@ export function DatabaseGroupTable({
searchPlaceholder,
}: Props) {
const { t } = useTranslation();
- const dbGroupStore = useDBGroupStore();
const [search, setSearch] = useState("");
const [internalList, setInternalList] = useState<DatabaseGroup[]>([]);
@@ -74,7 +73,8 @@ export function DatabaseGroupTable({
let cancelled = false;
setInternalReady(false);
setInternalList([]);
- void dbGroupStore
+ void useAppStore
+ .getState()
.fetchDBGroupListByProjectName(projectName, view)
.then((groups) => {
if (cancelled) return;
@@ -84,7 +84,7 @@ export function DatabaseGroupTable({
return () => {
cancelled = true;
};
- }, [dbGroupStore, projectName, view, externalList]);
+ }, [projectName, view, externalList]);
const sourceList = externalList ?? internalList;
const loading =
diff --git a/frontend/src/react/components/MatchedDatabaseView.tsx b/frontend/src/react/components/MatchedDatabaseView.tsx
index 81a3f1433d..f07ed38a0d 100644
--- a/frontend/src/react/components/MatchedDatabaseView.tsx
+++ b/frontend/src/react/components/MatchedDatabaseView.tsx
@@ -2,7 +2,8 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import type { ConditionGroupExpr } from "@/plugins/cel";
import { validateSimpleExpr } from "@/plugins/cel";
-import { useDatabaseV1Store, useDBGroupStore } from "@/store";
+import { useAppStore } from "@/react/stores/app";
+import { useDatabaseV1Store } from "@/store";
import { DEBOUNCE_SEARCH_DELAY, isValidDatabaseName } from "@/types";
import type { Database } from "@/types/proto-es/v1/database_service_pb";
import {
@@ -51,7 +52,6 @@ export function MatchedDatabaseView({
matchedNamesRef.current = matchedNames;
const pageSize = getDefaultPagination();
- const dbGroupStore = useDBGroupStore();
const databaseStore = useDatabaseV1Store();
const toggleSection = useCallback((name: string) => {
@@ -145,7 +145,7 @@ export function MatchedDatabaseView({
try {
const names = presetNames
? presetNames
- : await dbGroupStore.fetchDatabaseGroupMatchList({
+ : await useAppStore.getState().fetchDatabaseGroupMatchList({
projectName: project,
expr,
});
@@ -205,7 +205,7 @@ export function MatchedDatabaseView({
}
}, DEBOUNCE_SEARCH_DELAY);
return () => clearTimeout(timerRef.current);
- }, [expr, project, presetNames, dbGroupStore, databaseStore, pageSize]);
+ }, [expr, project, presetNames, databaseStore, pageSize]);
const hasMoreMatched = matchedToken < matchedNames.length;
const hasMoreUnmatched = !!unmatchedToken;
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 ba4ae891f5..50d1674f87 100644
--- a/frontend/src/react/components/sql-editor/ConnectionPane/ConnectionPane.test.tsx
+++ b/frontend/src/react/components/sql-editor/ConnectionPane/ConnectionPane.test.tsx
@@ -50,19 +50,6 @@ const mocks = vi.hoisted(() => {
getDatabaseByName: vi.fn(() => undefined),
getOrFetchDatabaseByName: vi.fn().mockResolvedValue(undefined),
};
- const dbGroupStore = {
- fetchDBGroupListByProjectName: vi.fn().mockResolvedValue([]),
- // The component reads `.name` and `.matchedDatabases` off the result
- // and validates `.name` via `isValidDatabaseGroupName`. Returning an
- // unknown-name placeholder preserves the "skip invalid" branch
- // without leaking real groups into tests that don't set them up.
- getDBGroupByName: vi.fn(() => ({
- name: "",
- matchedDatabases: [],
- title: "",
- })),
- getOrFetchDBGroupByName: vi.fn().mockResolvedValue(undefined),
- };
const project = {
name: "projects/p",
title: "Project One",
@@ -111,7 +98,6 @@ const mocks = vi.hoisted(() => {
features,
uiStore,
databaseStore,
- dbGroupStore,
project,
treeStore,
instanceStore,
@@ -144,7 +130,6 @@ vi.mock("@/react/hooks/useAppState", () => ({
vi.mock("@/store", () => ({
pushNotification: mocks.pushNotification,
useDatabaseV1Store: () => mocks.databaseStore,
- useDBGroupStore: () => mocks.dbGroupStore,
useInstanceV1Store: () => mocks.instanceStore,
}));
@@ -214,10 +199,6 @@ vi.mock("@/react/stores/sqlEditor", () => ({
}),
}));
-vi.mock("@/store/modules", () => ({
- useDBGroupStore: () => mocks.dbGroupStore,
-}));
-
vi.mock("@/react/lib/resourceName", () => ({
instanceNamePrefix: "instances/",
}));
diff --git a/frontend/src/react/lib/plan/issue.ts b/frontend/src/react/lib/plan/issue.ts
index 6ca960b51b..5fdf08e2f5 100644
--- a/frontend/src/react/lib/plan/issue.ts
+++ b/frontend/src/react/lib/plan/issue.ts
@@ -1,10 +1,7 @@
+import { useAppStore } from "@/react/stores/app";
import { router } from "@/router";
import { PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL } from "@/router/dashboard/projectV1";
-import {
- useDatabaseV1Store,
- useDBGroupStore,
- useProjectV1Store,
-} from "@/store";
+import { useDatabaseV1Store, useProjectV1Store } from "@/store";
import { isValidDatabaseGroupName, isValidDatabaseName } from "@/types";
import {
extractDatabaseGroupName,
@@ -17,13 +14,12 @@ import { applyPlanTitleToQuery } from "./title";
export const preCreateIssue = async (project: string, targets: string[]) => {
const type = "bb.plan.change-database";
const databaseStore = useDatabaseV1Store();
- const dbGroupStore = useDBGroupStore();
const projectStore = useProjectV1Store();
const databaseNames: string[] = [];
for (const target of targets) {
if (isValidDatabaseGroupName(target)) {
- const dbGroup = dbGroupStore.getDBGroupByName(target);
+ const dbGroup = useAppStore.getState().getDBGroupByName(target);
databaseNames.push(dbGroup.title);
} else if (isValidDatabaseName(target)) {
const db = databaseStore.getDatabaseByName(target);
diff --git a/frontend/src/react/pages/project/ProjectDatabaseGroupDetailPage.tsx b/frontend/src/react/pages/project/ProjectDatabaseGroupDetailPage.tsx
index 27ae61414e..b07310cf01 100644
--- a/frontend/src/react/pages/project/ProjectDatabaseGroupDetailPage.tsx
+++ b/frontend/src/react/pages/project/ProjectDatabaseGroupDetailPage.tsx
@@ -18,14 +18,15 @@ import {
} from "@/react/components/ui/dropdown-menu";
import { useVueState } from "@/react/hooks/useVueState";
import { preCreateIssue } from "@/react/lib/plan/issue";
+import { useAppStore } from "@/react/stores/app";
import { router } from "@/router";
import { PROJECT_V1_ROUTE_DATABASE_GROUPS } from "@/router/dashboard/projectV1";
-import { hasFeature, useDBGroupStore, useProjectV1Store } from "@/store";
+import { hasFeature, useProjectV1Store } from "@/store";
import {
databaseGroupNamePrefix,
projectNamePrefix,
} from "@/store/modules/v1/common";
-import { isValidDatabaseGroupName } from "@/types";
+import { isValidDatabaseGroupName, unknownDatabaseGroup } from "@/types";
import { DatabaseGroupView } from "@/types/proto-es/v1/database_group_service_pb";
import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";
import {
@@ -42,15 +43,19 @@ export function ProjectDatabaseGroupDetailPage({
}) {
const { t } = useTranslation();
const projectStore = useProjectV1Store();
- const dbGroupStore = useDBGroupStore();
const projectName = `${projectNamePrefix}${projectId}`;
const project = useVueState(() => projectStore.getProjectByName(projectName));
const resourceName = `${projectName}/${databaseGroupNamePrefix}${databaseGroupName}`;
- const databaseGroup = useVueState(() =>
- dbGroupStore.getDBGroupByName(resourceName)
+ // Subscribe to the cached entry directly (stable ref) and derive the
+ // unknown fallback outside the selector — returning `unknownDatabaseGroup()`
+ // from the selector would yield a fresh object each call and loop forever.
+ const cachedGroup = useAppStore((s) => s.dbGroupsByName[resourceName]);
+ const databaseGroup = useMemo(
+ () => cachedGroup ?? unknownDatabaseGroup(),
+ [cachedGroup]
);
const [editing, setEditing] = useState(false);
@@ -58,11 +63,11 @@ export function ProjectDatabaseGroupDetailPage({
// Fetch the database group on mount
useEffect(() => {
- dbGroupStore.getOrFetchDBGroupByName(resourceName, {
+ useAppStore.getState().getOrFetchDBGroupByName(resourceName, {
skipCache: true,
view: DatabaseGroupView.FULL,
});
- }, [resourceName, dbGroupStore]);
+ }, [resourceName]);
const hasDatabaseGroupFeature = useVueState(() =>
hasFeature(PlanFeature.FEATURE_DATABASE_GROUPS)
@@ -100,10 +105,10 @@ export function ProjectDatabaseGroupDetailPage({
);
const handleDelete = useCallback(async () => {
- await dbGroupStore.deleteDatabaseGroup(resourceName);
+ await useAppStore.getState().deleteDatabaseGroup(resourceName);
router.push({ name: PROJECT_V1_ROUTE_DATABASE_GROUPS });
setShowDeleteDialog(false);
- }, [resourceName, dbGroupStore]);
+ }, [resourceName]);
if (!databaseGroup || !project) return null;
if (!isValidDatabaseGroupName(databaseGroup.name)) return null;
diff --git a/frontend/src/react/pages/project/ProjectDatabaseGroupsPage.tsx b/frontend/src/react/pages/project/ProjectDatabaseGroupsPage.tsx
index 026cef48b8..b9a76a3402 100644
--- a/frontend/src/react/pages/project/ProjectDatabaseGroupsPage.tsx
+++ b/frontend/src/react/pages/project/ProjectDatabaseGroupsPage.tsx
@@ -11,12 +11,13 @@ import {
DialogTitle,
} from "@/react/components/ui/dialog";
import { useVueState } from "@/react/hooks/useVueState";
+import { useAppStore } from "@/react/stores/app";
import { router } from "@/router";
import {
PROJECT_V1_ROUTE_DATABASE_GROUP_DETAIL,
PROJECT_V1_ROUTE_DATABASE_GROUPS_CREATE,
} from "@/router/dashboard/projectV1";
-import { useDBGroupStore, useProjectV1Store } from "@/store";
+import { useProjectV1Store } from "@/store";
import {
getProjectNameAndDatabaseGroupName,
projectNamePrefix,
@@ -33,7 +34,6 @@ export function ProjectDatabaseGroupsPage({
}) {
const { t } = useTranslation();
const projectStore = useProjectV1Store();
- const dbGroupStore = useDBGroupStore();
const projectName = `${projectNamePrefix}${projectId}`;
const project = useVueState(() => projectStore.getProjectByName(projectName));
@@ -46,13 +46,14 @@ export function ProjectDatabaseGroupsPage({
useEffect(() => {
setLoading(true);
setDbGroupList([]);
- dbGroupStore
+ useAppStore
+ .getState()
.fetchDBGroupListByProjectName(projectName, DatabaseGroupView.BASIC)
.then((list) => {
setDbGroupList(list);
setLoading(false);
});
- }, [projectName, dbGroupStore]);
+ }, [projectName]);
const canCreate = useMemo(
() =>
@@ -92,10 +93,10 @@ export function ProjectDatabaseGroupsPage({
const handleDelete = useCallback(async () => {
if (!deleteTarget) return;
- await dbGroupStore.deleteDatabaseGroup(deleteTarget.name);
+ await useAppStore.getState().deleteDatabaseGroup(deleteTarget.name);
setDbGroupList((prev) => prev.filter((g) => g.name !== deleteTarget.name));
setDeleteTarget(null);
- }, [deleteTarget, dbGroupStore]);
+ }, [deleteTarget]);
return (
<div className="py-4 flex flex-col gap-y-2">
diff --git a/frontend/src/react/pages/project/ProjectGitOpsPage.tsx b/frontend/src/react/pages/project/ProjectGitOpsPage.tsx
index 3d0337037f..0bf362dc61 100644
--- a/frontend/src/react/pages/project/ProjectGitOpsPage.tsx
+++ b/frontend/src/react/pages/project/ProjectGitOpsPage.tsx
@@ -25,7 +25,6 @@ import {
useDatabaseV1Store,
useProjectV1Store,
} from "@/store";
-import { useDBGroupStore } from "@/store/modules/dbGroup";
import { projectNamePrefix } from "@/store/modules/v1/common";
import { DatabaseGroupView } from "@/types/proto-es/v1/database_group_service_pb";
import type { WorkloadIdentity } from "@/types/proto-es/v1/workload_identity_service_pb";
@@ -42,7 +41,6 @@ import {
export function ProjectGitOpsPage({ projectId }: { projectId: string }) {
const { t } = useTranslation();
const actuatorStore = useActuatorV1Store();
- const dbGroupStore = useDBGroupStore();
const databaseStore = useDatabaseV1Store();
const projectStore = useProjectV1Store();
const listWorkloadIdentities = useAppStore(
@@ -112,7 +110,8 @@ export function ProjectGitOpsPage({ projectId }: { projectId: string }) {
// Database group options
const [dbGroupOptions, setDbGroupOptions] = useState<ComboboxOption[]>([]);
useEffect(() => {
- dbGroupStore
+ useAppStore
+ .getState()
.fetchDBGroupListByProjectName(projectName, DatabaseGroupView.BASIC)
.then((groups) => {
setDbGroupOptions(
@@ -123,7 +122,7 @@ export function ProjectGitOpsPage({ projectId }: { projectId: string }) {
);
})
.catch(() => {});
- }, [projectName, dbGroupStore]);
+ }, [projectName]);
// Database options for individual selection
const [dbOptions, setDbOptions] = useState<ComboboxOption[]>([]);
diff --git a/frontend/src/react/pages/project/ProjectPlanDashboardPage.tsx b/frontend/src/react/pages/project/ProjectPlanDashboardPage.tsx
index 98200ad4cf..147479e59c 100644
--- a/frontend/src/react/pages/project/ProjectPlanDashboardPage.tsx
+++ b/frontend/src/react/pages/project/ProjectPlanDashboardPage.tsx
@@ -61,7 +61,6 @@ import {
import {
pushNotification,
useDatabaseV1Store,
- useDBGroupStore,
useEnvironmentV1Store,
useProjectV1Store,
useUIStateStore,
@@ -1119,19 +1118,19 @@ function DatabaseGroupSelector({
onSelectedGroupChange: (name: string | undefined) => void;
}) {
const { t } = useTranslation();
- const dbGroupStore = useDBGroupStore();
const [groups, setGroups] = useState<DatabaseGroup[]>([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
setLoading(true);
- dbGroupStore
+ useAppStore
+ .getState()
.fetchDBGroupListByProjectName(projectName, DatabaseGroupView.BASIC)
.then((result) => {
setGroups(result);
})
.finally(() => setLoading(false));
- }, [projectName, dbGroupStore]);
+ }, [projectName]);
if (loading) {
return (
diff --git a/frontend/src/react/pages/project/export-center/DataExportPrepSheet.test.tsx b/frontend/src/react/pages/project/export-center/DataExportPrepSheet.test.tsx
index 0d5aa87e87..cdbfcea50a 100644
--- a/frontend/src/react/pages/project/export-center/DataExportPrepSheet.test.tsx
+++ b/frontend/src/react/pages/project/export-center/DataExportPrepSheet.test.tsx
@@ -226,13 +226,16 @@ vi.mock("@/store", () => ({
DEFAULT_MAX_RESULT_SIZE_IN_MB: 100,
useProjectV1Store: () => stableProjectStore,
useDatabaseV1Store: () => stableDatabaseStore,
- useDBGroupStore: () => stableDBGroupStore,
useSheetV1Store: () => stableSheetStore,
useSettingV1Store: () => stableSettingStore,
experimentalCreateIssueByPlan: mocks.experimentalCreateIssueByPlan,
pushNotification: mocks.pushNotification,
}));
+vi.mock("@/react/stores/app", () => ({
+ useAppStore: { getState: () => stableDBGroupStore },
+}));
+
vi.mock("@/react/hooks/useAppState", () => ({
useCurrentUser: () => mocks.currentUser,
}));
diff --git a/frontend/src/react/pages/project/export-center/DataExportPrepSheet.tsx b/frontend/src/react/pages/project/export-center/DataExportPrepSheet.tsx
index 92062a5ec7..b8eb9fcfb0 100644
--- a/frontend/src/react/pages/project/export-center/DataExportPrepSheet.tsx
+++ b/frontend/src/react/pages/project/export-center/DataExportPrepSheet.tsx
@@ -23,6 +23,7 @@ import { useCurrentUser } from "@/react/hooks/useAppState";
import { useSessionPageSize } from "@/react/hooks/useSessionPageSize";
import { useVueState } from "@/react/hooks/useVueState";
import { cn } from "@/react/lib/utils";
+import { useAppStore } from "@/react/stores/app";
import { router } from "@/router";
import { PROJECT_V1_ROUTE_ISSUE_DETAIL } from "@/router/dashboard/projectV1";
import {
@@ -30,7 +31,6 @@ import {
experimentalCreateIssueByPlan,
pushNotification,
useDatabaseV1Store,
- useDBGroupStore,
useProjectV1Store,
useSettingV1Store,
useSheetV1Store,
@@ -96,7 +96,6 @@ export function DataExportPrepSheet({
const currentUser = useCurrentUser();
const sheetStore = useSheetV1Store();
const dbStore = useDatabaseV1Store();
- const dbGroupStore = useDBGroupStore();
const projectStore = useProjectV1Store();
const settingStore = useSettingV1Store();
@@ -178,12 +177,12 @@ export function DataExportPrepSheet({
if (isValidDatabaseName(target)) {
dbStore.getOrFetchDatabaseByName(target);
} else if (isValidDatabaseGroupName(target)) {
- dbGroupStore.getOrFetchDBGroupByName(target, {
+ useAppStore.getState().getOrFetchDBGroupByName(target, {
view: DatabaseGroupView.FULL,
});
}
}
- }, [targets, dbStore, dbGroupStore]);
+ }, [targets, dbStore]);
// Reset on open or when seed changes while open
const seedKey = seed?.selectedDatabaseNames?.join(",") ?? "";
@@ -866,19 +865,19 @@ function DatabaseGroupSelector({
onSelectedGroupChange: (name: string | undefined) => void;
}) {
const { t } = useTranslation();
- const dbGroupStore = useDBGroupStore();
const [groups, setGroups] = useState<DatabaseGroup[]>([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
setLoading(true);
- dbGroupStore
+ useAppStore
+ .getState()
.fetchDBGroupListByProjectName(projectName, DatabaseGroupView.BASIC)
.then((result) => {
setGroups(result);
})
.finally(() => setLoading(false));
- }, [projectName, dbGroupStore]);
+ }, [projectName]);
if (loading) {
return (
diff --git a/frontend/src/react/pages/project/issue-detail/components/IssueDetailDatabaseChangeView.test.tsx b/frontend/src/react/pages/project/issue-detail/components/IssueDetailDatabaseChangeView.test.tsx
index 927df025d3..776416621f 100644
--- a/frontend/src/react/pages/project/issue-detail/components/IssueDetailDatabaseChangeView.test.tsx
+++ b/frontend/src/react/pages/project/issue-detail/components/IssueDetailDatabaseChangeView.test.tsx
@@ -229,10 +229,6 @@ vi.mock("@/store", () => ({
getDatabaseByName: mocks.getDatabaseByName,
batchGetOrFetchDatabases: mocks.batchGetOrFetchDatabases,
}),
- useDBGroupStore: () => ({
- getDBGroupByName: mocks.getDBGroupByName,
- getOrFetchDBGroupByName: mocks.getOrFetchDBGroupByName,
- }),
useEnvironmentV1Store: () => ({
getEnvironmentByName: mocks.getEnvironmentByName,
}),
@@ -244,8 +240,31 @@ vi.mock("@/store", () => ({
vi.mock("@/types", () => ({
isValidDatabaseGroupName: mocks.isValidDatabaseGroupName,
isValidDatabaseName: mocks.isValidDatabaseName,
+ unknownDatabaseGroup: () => ({ name: "", matchedDatabases: [] }),
}));
+vi.mock("@/react/stores/app", () => {
+ // The migrated component reads dbGroup state two ways: imperative
+ // `useAppStore.getState().<method>()` and the reactive selector
+ // `useAppStore((s) => s.dbGroupsByName[name])`. Delegate the map lookup to
+ // the existing `getDBGroupByName` mock so per-test setup keeps working.
+ const dbGroupsByName = new Proxy({} as Record<string, unknown>, {
+ get: (_t, key) =>
+ typeof key === "string" ? mocks.getDBGroupByName(key) : undefined,
+ });
+ const useAppStore = Object.assign(
+ (selector: (s: { dbGroupsByName: Record<string, unknown> }) => unknown) =>
+ selector({ dbGroupsByName }),
+ {
+ getState: () => ({
+ getDBGroupByName: mocks.getDBGroupByName,
+ getOrFetchDBGroupByName: mocks.getOrFetchDBGroupByName,
+ }),
+ }
+ );
+ return { useAppStore };
+});
+
vi.mock("@/utils", () => ({
extractDatabaseResourceName: mocks.extractDatabaseResourceName,
extractInstanceResourceName: mocks.extractInstanceResourceName,
diff --git a/frontend/src/react/pages/project/issue-detail/components/IssueDetailDatabaseChangeView.tsx b/frontend/src/react/pages/project/issue-detail/components/IssueDetailDatabaseChangeView.tsx
index 66607e0185..9cad9257c8 100644
--- a/frontend/src/react/pages/project/issue-detail/components/IssueDetailDatabaseChangeView.tsx
+++ b/frontend/src/react/pages/project/issue-detail/components/IssueDetailDatabaseChangeView.tsx
@@ -23,6 +23,7 @@ import { Switch } from "@/react/components/ui/switch";
import { Tooltip } from "@/react/components/ui/tooltip";
import { useVueState } from "@/react/hooks/useVueState";
import { cn } from "@/react/lib/utils";
+import { useAppStore } from "@/react/stores/app";
import { router } from "@/router";
import {
PROJECT_V1_ROUTE_DATABASE_GROUP_DETAIL,
@@ -32,11 +33,14 @@ import { buildPlanDeployRouteFromPlanName } from "@/router/dashboard/projectV1Ro
import {
getProjectNameAndDatabaseGroupName,
useDatabaseV1Store,
- useDBGroupStore,
useEnvironmentV1Store,
useSheetV1Store,
} from "@/store";
-import { isValidDatabaseGroupName, isValidDatabaseName } from "@/types";
+import {
+ isValidDatabaseGroupName,
+ isValidDatabaseName,
+ unknownDatabaseGroup,
+} from "@/types";
import { Engine } from "@/types/proto-es/v1/common_pb";
import { DatabaseGroupView } from "@/types/proto-es/v1/database_group_service_pb";
import { ListInstanceRolesRequestSchema } from "@/types/proto-es/v1/instance_role_service_pb";
@@ -508,7 +512,6 @@ function IssueDetailDatabaseChangeTargets({
}) {
const { t } = useTranslation();
const databaseStore = useDatabaseV1Store();
- const dbGroupStore = useDBGroupStore();
const [showAllTargetsDialog, setShowAllTargetsDialog] = useState(false);
const [searchText, setSearchText] = useState("");
const [isLoadingTargets, setIsLoadingTargets] = useState(false);
@@ -533,7 +536,8 @@ function IssueDetailDatabaseChangeTargets({
return [target];
}
return (
- dbGroupStore
+ useAppStore
+ .getState()
.getDBGroupByName(target)
.matchedDatabases?.map((database) => database.name) ?? []
);
@@ -578,7 +582,7 @@ function IssueDetailDatabaseChangeTargets({
setIsLoadingTargets(true);
try {
- await fetchTargets(visibleTargets, dbGroupStore, databaseStore);
+ await fetchTargets(visibleTargets, databaseStore);
} catch {
// Ignore target loading failures to match the current Vue behavior.
} finally {
@@ -593,7 +597,7 @@ function IssueDetailDatabaseChangeTargets({
return () => {
canceled = true;
};
- }, [databaseStore, dbGroupStore, targets, visibleTargets]);
+ }, [databaseStore, targets, visibleTargets]);
useEffect(() => {
if (!showAllTargetsDialog) {
@@ -606,7 +610,7 @@ function IssueDetailDatabaseChangeTargets({
const loadAllTargets = async () => {
setIsLoadingAllTargets(true);
try {
- await fetchTargets(targets, dbGroupStore, databaseStore);
+ await fetchTargets(targets, databaseStore);
} catch {
// Ignore target loading failures to match the current Vue behavior.
} finally {
@@ -621,7 +625,7 @@ function IssueDetailDatabaseChangeTargets({
return () => {
canceled = true;
};
- }, [databaseStore, dbGroupStore, showAllTargetsDialog, targets]);
+ }, [databaseStore, showAllTargetsDialog, targets]);
return (
<>
@@ -816,10 +820,14 @@ function IssueDetailDatabaseGroupTarget({
target: string;
}) {
const { t } = useTranslation();
- const dbGroupStore = useDBGroupStore();
const databaseStore = useDatabaseV1Store();
- const databaseGroup = useVueState(() =>
- dbGroupStore.getDBGroupByName(target)
+ // Subscribe to the cached entry directly (stable ref) and derive the unknown
+ // fallback outside the selector — a selector returning `unknownDatabaseGroup()`
+ // would yield a fresh object each call and loop forever.
+ const cachedGroup = useAppStore((s) => s.dbGroupsByName[target]);
+ const databaseGroup = useMemo(
+ () => cachedGroup ?? unknownDatabaseGroup(),
+ [cachedGroup]
);
const databases = useMemo(
() => databaseGroup.matchedDatabases?.map((db) => db.name) ?? [],
@@ -831,11 +839,11 @@ function IssueDetailDatabaseGroupTarget({
if (!isValidDatabaseGroupName(target)) {
return;
}
- void dbGroupStore.getOrFetchDBGroupByName(target, {
+ void useAppStore.getState().getOrFetchDBGroupByName(target, {
silent: true,
view: DatabaseGroupView.FULL,
});
- }, [dbGroupStore, target]);
+ }, [target]);
useEffect(() => {
if (databases.length > 0) {
@@ -913,7 +921,6 @@ function IssueDetailDatabaseGroupTarget({
const fetchTargets = async (
targets: string[],
- dbGroupStore: ReturnType<typeof useDBGroupStore>,
databaseStore: ReturnType<typeof useDatabaseV1Store>
) => {
const databaseTargets = new Set<string>();
@@ -921,13 +928,12 @@ const fetchTargets = async (
for (const target of targets) {
if (isValidDatabaseGroupName(target)) {
try {
- const databaseGroup = await dbGroupStore.getOrFetchDBGroupByName(
- target,
- {
+ const databaseGroup = await useAppStore
+ .getState()
+ .getOrFetchDBGroupByName(target, {
silent: true,
view: DatabaseGroupView.FULL,
- }
- );
+ });
for (const database of databaseGroup.matchedDatabases ?? []) {
databaseTargets.add(database.name);
}
diff --git a/frontend/src/react/pages/project/issue-detail/components/IssueDetailDatabaseExportView.tsx b/frontend/src/react/pages/project/issue-detail/components/IssueDetailDatabaseExportView.tsx
index ae9597c635..efe9459dc1 100644
--- a/frontend/src/react/pages/project/issue-detail/components/IssueDetailDatabaseExportView.tsx
+++ b/frontend/src/react/pages/project/issue-detail/components/IssueDetailDatabaseExportView.tsx
@@ -26,6 +26,7 @@ import { Switch } from "@/react/components/ui/switch";
import { Tooltip } from "@/react/components/ui/tooltip";
import { useVueState } from "@/react/hooks/useVueState";
import { cn } from "@/react/lib/utils";
+import { useAppStore } from "@/react/stores/app";
import { router } from "@/router";
import { PROJECT_V1_ROUTE_DATABASE_GROUP_DETAIL } from "@/router/dashboard/projectV1";
import {
@@ -33,11 +34,14 @@ import {
getProjectNameAndDatabaseGroupName,
pushNotification,
useDatabaseV1Store,
- useDBGroupStore,
useEnvironmentV1Store,
useSettingV1Store,
} from "@/store";
-import { isValidDatabaseGroupName, isValidDatabaseName } from "@/types";
+import {
+ isValidDatabaseGroupName,
+ isValidDatabaseName,
+ unknownDatabaseGroup,
+} from "@/types";
import { ExportFormat } from "@/types/proto-es/v1/common_pb";
import { DatabaseGroupView } from "@/types/proto-es/v1/database_group_service_pb";
import {
@@ -588,19 +592,18 @@ function IssueDetailDatabaseExportExecutionHistory({
function IssueDetailDatabaseExportTargets({ targets }: { targets: string[] }) {
const { t } = useTranslation();
const databaseStore = useDatabaseV1Store();
- const dbGroupStore = useDBGroupStore();
useEffect(() => {
for (const target of targets) {
if (isValidDatabaseName(target)) {
void databaseStore.getOrFetchDatabaseByName(target);
} else if (isValidDatabaseGroupName(target)) {
- void dbGroupStore.getOrFetchDBGroupByName(target, {
+ void useAppStore.getState().getOrFetchDBGroupByName(target, {
view: DatabaseGroupView.FULL,
});
}
}
- }, [databaseStore, dbGroupStore, targets]);
+ }, [databaseStore, targets]);
if (targets.length === 0) {
return (
@@ -678,10 +681,11 @@ function IssueDetailDatabaseExportDatabaseGroupTarget({
target: string;
}) {
const { t } = useTranslation();
- const dbGroupStore = useDBGroupStore();
const databaseStore = useDatabaseV1Store();
- const databaseGroup = useVueState(() =>
- dbGroupStore.getDBGroupByName(target)
+ const cachedGroup = useAppStore((s) => s.dbGroupsByName[target]);
+ const databaseGroup = useMemo(
+ () => cachedGroup ?? unknownDatabaseGroup(),
+ [cachedGroup]
);
const databases = useMemo(
() => databaseGroup.matchedDatabases?.map((db) => db.name) ?? [],
@@ -693,11 +697,11 @@ function IssueDetailDatabaseExportDatabaseGroupTarget({
if (!isValidDatabaseGroupName(target)) {
return;
}
- void dbGroupStore.getOrFetchDBGroupByName(target, {
+ void useAppStore.getState().getOrFetchDBGroupByName(target, {
silent: true,
view: DatabaseGroupView.FULL,
});
- }, [dbGroupStore, target]);
+ }, [target]);
useEffect(() => {
if (databases.length > 0) {
diff --git a/frontend/src/react/pages/project/plan-detail/components/PlanDetailChangesBranch.test.tsx b/frontend/src/react/pages/project/plan-detail/components/PlanDetailChangesBranch.test.tsx
index fe7b9f9d9b..eefe29d18b 100644
--- a/frontend/src/react/pages/project/plan-detail/components/PlanDetailChangesBranch.test.tsx
+++ b/frontend/src/react/pages/project/plan-detail/components/PlanDetailChangesBranch.test.tsx
@@ -253,6 +253,7 @@ vi.mock("@/types", () => ({
name?.includes("/databaseGroups/"),
isValidDatabaseName: (name: string) => name?.includes("/databases/"),
isValidReleaseName: (name: string) => name?.includes("/releases/"),
+ unknownDatabaseGroup: () => ({ name: "", matchedDatabases: [] }),
}));
vi.mock("@/connect", () => ({
@@ -267,12 +268,42 @@ vi.mock("@/store", () => ({
name.split("/databaseGroups/"),
pushNotification: vi.fn(),
useDatabaseV1Store: () => mocks.databaseStore,
- useDBGroupStore: () => mocks.dbGroupStore,
useEnvironmentV1Store: () => mocks.environmentStore,
useProjectV1Store: () => mocks.projectStore,
useSheetV1Store: () => mocks.sheetStore,
}));
+// The migrated component reads dbGroup state via imperative
+// `useAppStore.getState().<method>()` and reactive selectors over
+// `dbGroupsByName` / `dbGroupViewByName`. Delegate the map lookups to the
+// existing `dbGroupStore` mock (treating every cached entry as FULL) so the
+// per-test `getDBGroupByName` / `getOrFetchDBGroupByName` setup keeps working.
+vi.mock("@/react/stores/app", async () => {
+ const { DatabaseGroupView } = await vi.importActual<
+ typeof import("@/types/proto-es/v1/database_group_service_pb")
+ >("@/types/proto-es/v1/database_group_service_pb");
+ const dbGroupsByName = new Proxy({} as Record<string, unknown>, {
+ get: (_t, key) =>
+ typeof key === "string"
+ ? mocks.dbGroupStore.getDBGroupByName(key)
+ : undefined,
+ });
+ const dbGroupViewByName = new Proxy({} as Record<string, unknown>, {
+ get: (_t, key) =>
+ typeof key === "string" ? DatabaseGroupView.FULL : undefined,
+ });
+ const useAppStore = Object.assign(
+ (
+ selector: (s: {
+ dbGroupsByName: Record<string, unknown>;
+ dbGroupViewByName: Record<string, unknown>;
+ }) => unknown
+ ) => selector({ dbGroupsByName, dbGroupViewByName }),
+ { getState: () => mocks.dbGroupStore }
+ );
+ return { useAppStore };
+});
+
vi.mock("@/react/hooks/useAppState", () => ({
useCurrentUser: () => ({
name: "users/[email protected]",
diff --git a/frontend/src/react/pages/project/plan-detail/components/PlanDetailChangesBranch.tsx b/frontend/src/react/pages/project/plan-detail/components/PlanDetailChangesBranch.tsx
index e3cc2c7bf5..a953611fde 100644
--- a/frontend/src/react/pages/project/plan-detail/components/PlanDetailChangesBranch.tsx
+++ b/frontend/src/react/pages/project/plan-detail/components/PlanDetailChangesBranch.tsx
@@ -61,6 +61,7 @@ import { useCurrentUser } from "@/react/hooks/useAppState";
import { useSessionPageSize } from "@/react/hooks/useSessionPageSize";
import { useVueState } from "@/react/hooks/useVueState";
import { cn } from "@/react/lib/utils";
+import { useAppStore } from "@/react/stores/app";
import { router } from "@/router";
import {
PROJECT_V1_ROUTE_DATABASE_GROUP_DETAIL,
@@ -70,7 +71,6 @@ import {
getProjectNameAndDatabaseGroupName,
pushNotification,
useDatabaseV1Store,
- useDBGroupStore,
useProjectV1Store,
useSheetV1Store,
} from "@/store";
@@ -78,6 +78,7 @@ import {
isValidDatabaseGroupName,
isValidDatabaseName,
isValidReleaseName,
+ unknownDatabaseGroup,
} from "@/types";
import { Engine, State } from "@/types/proto-es/v1/common_pb";
import type { DatabaseGroup } from "@/types/proto-es/v1/database_group_service_pb";
@@ -718,7 +719,6 @@ function OptionsSection({
projectStore.getProjectByName(`projects/${page.projectId}`)
);
const databaseStore = useDatabaseV1Store();
- const dbGroupStore = useDBGroupStore();
const sheetStore = useSheetV1Store();
const [sheetStatement, setSheetStatementValue] = useState("");
const [isSheetOversize, setIsSheetOversize] = useState(false);
@@ -737,10 +737,9 @@ function OptionsSection({
return [databaseStore.getDatabaseByName(target)];
}
if (isValidDatabaseGroupName(target)) {
- const dbGroup = dbGroupStore.getDBGroupByName(
- target,
- DatabaseGroupView.FULL
- );
+ const dbGroup = useAppStore
+ .getState()
+ .getDBGroupByName(target, DatabaseGroupView.FULL);
return (dbGroup.matchedDatabases ?? []).map((database) =>
databaseStore.getDatabaseByName(database.name)
);
@@ -822,8 +821,8 @@ function OptionsSection({
if (targets.length === 0) {
return;
}
- void fetchTargets(targets, dbGroupStore, databaseStore);
- }, [databaseStore, dbGroupStore, targets]);
+ void fetchTargets(targets, databaseStore);
+ }, [databaseStore, targets]);
useEffect(() => {
let canceled = false;
@@ -1209,7 +1208,6 @@ function TargetsSection({
}) {
const { t } = useTranslation();
const databaseStore = useDatabaseV1Store();
- const dbGroupStore = useDBGroupStore();
const [showAllTargetsDialog, setShowAllTargetsDialog] = useState(false);
const [searchText, setSearchText] = useState("");
const [isLoadingTargets, setIsLoadingTargets] = useState(false);
@@ -1231,7 +1229,8 @@ function TargetsSection({
.flatMap((target) => {
if (!isValidDatabaseGroupName(target)) return [target];
return (
- dbGroupStore
+ useAppStore
+ .getState()
.getDBGroupByName(target)
.matchedDatabases?.map((database) => database.name) ?? []
);
@@ -1239,7 +1238,7 @@ function TargetsSection({
.filter(
(name) => !databaseStore.getDatabaseByName(name).effectiveEnvironment
);
- }, [databaseStore, dbGroupStore, isLoadingTargets, targets]);
+ }, [databaseStore, isLoadingTargets, targets]);
const filteredTargets = useMemo(
() =>
filterPlanTargets({
@@ -1271,7 +1270,7 @@ function TargetsSection({
}
setIsLoadingTargets(true);
try {
- await fetchTargets(visibleTargets, dbGroupStore, databaseStore);
+ await fetchTargets(visibleTargets, databaseStore);
} finally {
if (!canceled) setIsLoadingTargets(false);
}
@@ -1280,7 +1279,7 @@ function TargetsSection({
return () => {
canceled = true;
};
- }, [databaseStore, dbGroupStore, targets, visibleTargets]);
+ }, [databaseStore, targets, visibleTargets]);
useEffect(() => {
if (!showAllTargetsDialog) return;
@@ -1289,7 +1288,7 @@ function TargetsSection({
const load = async () => {
setIsLoadingAllTargets(true);
try {
- await fetchTargets(targets, dbGroupStore, databaseStore);
+ await fetchTargets(targets, databaseStore);
} finally {
if (!canceled) setIsLoadingAllTargets(false);
}
@@ -1298,7 +1297,7 @@ function TargetsSection({
return () => {
canceled = true;
};
- }, [databaseStore, dbGroupStore, showAllTargetsDialog, targets]);
+ }, [databaseStore, showAllTargetsDialog, targets]);
return (
<>
@@ -1782,17 +1781,17 @@ function DatabaseGroupSelector({
onSelectedGroupChange: (name: string | undefined) => void;
}) {
const { t } = useTranslation();
- const dbGroupStore = useDBGroupStore();
const [groups, setGroups] = useState<DatabaseGroup[]>([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
setLoading(true);
- dbGroupStore
+ useAppStore
+ .getState()
.fetchDBGroupListByProjectName(projectName, DatabaseGroupView.BASIC)
.then((result) => setGroups(result))
.finally(() => setLoading(false));
- }, [dbGroupStore, projectName]);
+ }, [projectName]);
if (loading) {
return (
@@ -1865,9 +1864,18 @@ export function DatabaseGroupTarget({
}) {
const { t } = useTranslation();
const databaseStore = useDatabaseV1Store();
- const dbGroupStore = useDBGroupStore();
const [searchText, setSearchText] = useState("");
- const dbGroup = dbGroupStore.getDBGroupByName(target, DatabaseGroupView.FULL);
+ // Subscribe to the cached FULL entry directly (stable ref); deriving the
+ // unknown fallback inside the selector would loop on a fresh object each call.
+ const cachedGroup = useAppStore((s) =>
+ s.dbGroupViewByName[target] === DatabaseGroupView.FULL
+ ? s.dbGroupsByName[target]
+ : undefined
+ );
+ const dbGroup = useMemo(
+ () => cachedGroup ?? unknownDatabaseGroup(),
+ [cachedGroup]
+ );
const matchedDatabases = dbGroup.matchedDatabases ?? [];
const { extraDatabases, inlineDatabases } = splitInlineDatabases(
matchedDatabases,
@@ -1892,10 +1900,12 @@ export function DatabaseGroupTarget({
useEffect(() => {
const load = async () => {
- const group = await dbGroupStore.getOrFetchDBGroupByName(target, {
- view: DatabaseGroupView.FULL,
- silent: true,
- });
+ const group = await useAppStore
+ .getState()
+ .getOrFetchDBGroupByName(target, {
+ view: DatabaseGroupView.FULL,
+ silent: true,
+ });
const databaseNames =
group.matchedDatabases?.map((database) => database.name) ?? [];
if (databaseNames.length > 0) {
@@ -1903,7 +1913,7 @@ export function DatabaseGroupTarget({
}
};
void load();
- }, [databaseStore, dbGroupStore, target]);
+ }, [databaseStore, target]);
const route = {
name: PROJECT_V1_ROUTE_DATABASE_GROUP_DETAIL,
@@ -2038,7 +2048,6 @@ function parseStatement(statement: string): {
async function fetchTargets(
targets: string[],
- dbGroupStore: ReturnType<typeof useDBGroupStore>,
databaseStore: ReturnType<typeof useDatabaseV1Store>
) {
await Promise.all(
@@ -2048,10 +2057,12 @@ async function fetchTargets(
return;
}
if (isValidDatabaseGroupName(target)) {
- const dbGroup = await dbGroupStore.getOrFetchDBGroupByName(target, {
- silent: true,
- view: DatabaseGroupView.FULL,
- });
+ const dbGroup = await useAppStore
+ .getState()
+ .getOrFetchDBGroupByName(target, {
+ silent: true,
+ view: DatabaseGroupView.FULL,
+ });
const databaseNames =
dbGroup.matchedDatabases?.map((database) => database.name) ?? [];
if (databaseNames.length > 0) {
diff --git a/frontend/src/react/pages/project/plan-detail/utils/rolloutPreview.ts b/frontend/src/react/pages/project/plan-detail/utils/rolloutPreview.ts
index 96b0fe0da8..bc3bda37bc 100644
--- a/frontend/src/react/pages/project/plan-detail/utils/rolloutPreview.ts
+++ b/frontend/src/react/pages/project/plan-detail/utils/rolloutPreview.ts
@@ -1,9 +1,6 @@
import { create } from "@bufbuild/protobuf";
-import {
- useDatabaseV1Store,
- useDBGroupStore,
- useEnvironmentV1Store,
-} from "@/store";
+import { useAppStore } from "@/react/stores/app";
+import { useDatabaseV1Store, useEnvironmentV1Store } from "@/store";
import { isValidDatabaseGroupName, isValidDatabaseName } from "@/types";
import { DatabaseGroupView } from "@/types/proto-es/v1/database_group_service_pb";
import type {
@@ -101,12 +98,13 @@ async function extractAndExpandDatabaseTargets(
async function expandDatabaseGroup(
databaseGroupName: string
): Promise<string[]> {
- const dbGroupStore = useDBGroupStore();
try {
- const dbGroup = await dbGroupStore.getOrFetchDBGroupByName(
- databaseGroupName,
- { view: DatabaseGroupView.FULL, silent: true }
- );
+ const dbGroup = await useAppStore
+ .getState()
+ .getOrFetchDBGroupByName(databaseGroupName, {
+ view: DatabaseGroupView.FULL,
+ silent: true,
+ });
return dbGroup.matchedDatabases?.map((db) => db.name) ?? [];
} catch {
return [];
diff --git a/frontend/src/react/stores/app/dbGroup.ts b/frontend/src/react/stores/app/dbGroup.ts
index 6d2abbc293..345982ae1e 100644
--- a/frontend/src/react/stores/app/dbGroup.ts
+++ b/frontend/src/react/stores/app/dbGroup.ts
@@ -1,99 +1,257 @@
import { create as createProto } from "@bufbuild/protobuf";
+import { createContextValues } from "@connectrpc/connect";
import { databaseGroupServiceClientConnect } from "@/connect";
-import { isValidDatabaseGroupName } from "@/types/dbGroup";
+import { silentContextKey } from "@/connect/context-key";
+import { buildCELExpr } from "@/plugins/cel";
+import { databaseGroupNamePrefix } from "@/store/modules/v1/common";
import {
+ isValidDatabaseGroupName,
+ unknownDatabaseGroup,
+} from "@/types/dbGroup";
+import { ExprSchema } from "@/types/proto-es/google/type/expr_pb";
+import {
+ CreateDatabaseGroupRequestSchema,
type DatabaseGroup,
+ DatabaseGroupSchema,
DatabaseGroupView,
+ DeleteDatabaseGroupRequestSchema,
GetDatabaseGroupRequestSchema,
ListDatabaseGroupsRequestSchema,
+ UpdateDatabaseGroupRequestSchema,
} from "@/types/proto-es/v1/database_group_service_pb";
+import { batchConvertParsedExprToCELString } from "@/utils";
import type { AppSliceCreator, DBGroupSlice } from "./types";
import { toError } from "./utils";
-export const createDBGroupSlice: AppSliceCreator<DBGroupSlice> = (
- set,
- get
-) => ({
- dbGroupsByName: {},
- dbGroupViewByName: {},
- dbGroupRequests: {},
- dbGroupErrorsByName: {},
-
- fetchDBGroup: async (name, view = DatabaseGroupView.BASIC) => {
- if (!isValidDatabaseGroupName(name)) return undefined;
- const existing = get().dbGroupsByName[name];
- // A FULL request needs `matchedDatabases`; only reuse the cache when it
- // already holds the FULL view (a BASIC request is satisfied by either).
- if (
- existing &&
- (view !== DatabaseGroupView.FULL ||
- get().dbGroupViewByName[name] === DatabaseGroupView.FULL)
- ) {
- return existing;
- }
- const pending = get().dbGroupRequests[name];
- if (pending) return pending;
-
- const request = databaseGroupServiceClientConnect
- .getDatabaseGroup(
- createProto(GetDatabaseGroupRequestSchema, { name, view })
- )
- .then((group: DatabaseGroup) => {
- set((state) => {
- const { [name]: _, ...dbGroupRequests } = state.dbGroupRequests;
- return {
- dbGroupsByName: {
- ...state.dbGroupsByName,
- [group.name]: group,
- },
- dbGroupViewByName: {
- ...state.dbGroupViewByName,
- [group.name]: view,
- },
- dbGroupErrorsByName: {
- ...state.dbGroupErrorsByName,
- [name]: undefined,
- },
- dbGroupRequests,
- };
- });
- return group;
- })
- .catch((error) => {
- set((state) => {
- const { [name]: _, ...dbGroupRequests } = state.dbGroupRequests;
- return {
- dbGroupErrorsByName: {
- ...state.dbGroupErrorsByName,
- [name]: toError(error),
- },
- dbGroupRequests,
- };
- });
- return undefined;
- });
+export const createDBGroupSlice: AppSliceCreator<DBGroupSlice> = (set, get) => {
+ // Immutable cache write. A name maps to a single group + the view it was
+ // fetched with; overwriting is sufficient (no per-view keying needed). Also
+ // clears any stale error so a successful (re)fetch doesn't leave a prior
+ // failure visible to consumers reading `dbGroupErrorsByName`.
+ const setCache = (group: DatabaseGroup, view: DatabaseGroupView) => {
set((state) => ({
- dbGroupRequests: {
- ...state.dbGroupRequests,
- [name]: request,
+ dbGroupsByName: { ...state.dbGroupsByName, [group.name]: group },
+ dbGroupViewByName: { ...state.dbGroupViewByName, [group.name]: view },
+ dbGroupErrorsByName: {
+ ...state.dbGroupErrorsByName,
+ [group.name]: undefined,
},
}));
- return request;
- },
-
- listDBGroupsForProject: async (project) => {
- const response = await databaseGroupServiceClientConnect.listDatabaseGroups(
- createProto(ListDatabaseGroupsRequestSchema, { parent: project })
- );
+ };
+ const removeCache = (name: string) => {
set((state) => {
- const next = { ...state.dbGroupsByName };
- const nextView = { ...state.dbGroupViewByName };
- for (const group of response.databaseGroups) {
- next[group.name] = group;
- nextView[group.name] = DatabaseGroupView.BASIC;
+ const { [name]: _g, ...dbGroupsByName } = state.dbGroupsByName;
+ const { [name]: _v, ...dbGroupViewByName } = state.dbGroupViewByName;
+ return { dbGroupsByName, dbGroupViewByName };
+ });
+ };
+ // Bulk variant of `setCache` — merges every group in one `set()` so a list
+ // fetch notifies subscribers once instead of N times.
+ const cacheGroups = (groups: DatabaseGroup[], view: DatabaseGroupView) => {
+ set((state) => {
+ const dbGroupsByName = { ...state.dbGroupsByName };
+ const dbGroupViewByName = { ...state.dbGroupViewByName };
+ for (const group of groups) {
+ dbGroupsByName[group.name] = group;
+ dbGroupViewByName[group.name] = view;
}
- return { dbGroupsByName: next, dbGroupViewByName: nextView };
+ return { dbGroupsByName, dbGroupViewByName };
});
- return response.databaseGroups;
- },
-});
+ };
+
+ return {
+ dbGroupsByName: {},
+ dbGroupViewByName: {},
+ dbGroupRequests: {},
+ dbGroupErrorsByName: {},
+
+ fetchDBGroup: async (name, view = DatabaseGroupView.BASIC) => {
+ if (!isValidDatabaseGroupName(name)) return undefined;
+ const existing = get().dbGroupsByName[name];
+ // A FULL request needs `matchedDatabases`; only reuse the cache when it
+ // already holds the FULL view (a BASIC request is satisfied by either).
+ if (
+ existing &&
+ (view !== DatabaseGroupView.FULL ||
+ get().dbGroupViewByName[name] === DatabaseGroupView.FULL)
+ ) {
+ return existing;
+ }
+ const pending = get().dbGroupRequests[name];
+ if (pending) return pending;
+
+ const request = databaseGroupServiceClientConnect
+ .getDatabaseGroup(
+ createProto(GetDatabaseGroupRequestSchema, { name, view })
+ )
+ .then((group: DatabaseGroup) => {
+ set((state) => {
+ const { [name]: _, ...dbGroupRequests } = state.dbGroupRequests;
+ return {
+ dbGroupsByName: {
+ ...state.dbGroupsByName,
+ [group.name]: group,
+ },
+ dbGroupViewByName: {
+ ...state.dbGroupViewByName,
+ [group.name]: view,
+ },
+ dbGroupErrorsByName: {
+ ...state.dbGroupErrorsByName,
+ [name]: undefined,
+ },
+ dbGroupRequests,
+ };
+ });
+ return group;
+ })
+ .catch((error) => {
+ set((state) => {
+ const { [name]: _, ...dbGroupRequests } = state.dbGroupRequests;
+ return {
+ dbGroupErrorsByName: {
+ ...state.dbGroupErrorsByName,
+ [name]: toError(error),
+ },
+ dbGroupRequests,
+ };
+ });
+ return undefined;
+ });
+ set((state) => ({
+ dbGroupRequests: {
+ ...state.dbGroupRequests,
+ [name]: request,
+ },
+ }));
+ return request;
+ },
+
+ listDBGroupsForProject: async (project) => {
+ const response =
+ await databaseGroupServiceClientConnect.listDatabaseGroups(
+ createProto(ListDatabaseGroupsRequestSchema, { parent: project })
+ );
+ cacheGroups(response.databaseGroups, DatabaseGroupView.BASIC);
+ return response.databaseGroups;
+ },
+
+ getDBGroupByName: (name, view = DatabaseGroupView.UNSPECIFIED) => {
+ const { dbGroupsByName, dbGroupViewByName } = get();
+ const group = dbGroupsByName[name];
+ if (group) {
+ const satisfied =
+ view === DatabaseGroupView.FULL
+ ? dbGroupViewByName[name] === DatabaseGroupView.FULL
+ : true; // BASIC/UNSPECIFIED requests accept any cached view
+ if (satisfied) return group;
+ }
+ return unknownDatabaseGroup();
+ },
+
+ getOrFetchDBGroupByName: async (name, options) => {
+ const {
+ skipCache = false,
+ silent = false,
+ view = DatabaseGroupView.BASIC,
+ } = options ?? {};
+ if (!skipCache) {
+ const cached = get().getDBGroupByName(name, view);
+ if (isValidDatabaseGroupName(cached.name)) {
+ return cached;
+ }
+ }
+ const group = await databaseGroupServiceClientConnect.getDatabaseGroup(
+ createProto(GetDatabaseGroupRequestSchema, { name, view }),
+ { contextValues: createContextValues().set(silentContextKey, silent) }
+ );
+ setCache(group, view);
+ return group;
+ },
+
+ fetchDBGroupListByProjectName: async (projectName, view) => {
+ const response =
+ await databaseGroupServiceClientConnect.listDatabaseGroups(
+ createProto(ListDatabaseGroupsRequestSchema, {
+ parent: projectName,
+ view,
+ })
+ );
+ cacheGroups(response.databaseGroups, view);
+ return response.databaseGroups;
+ },
+
+ createDatabaseGroup: async ({
+ projectName,
+ databaseGroup,
+ databaseGroupId,
+ validateOnly = false,
+ }) => {
+ const newDatabaseGroup = createProto(DatabaseGroupSchema, {
+ name: databaseGroup.name,
+ title: databaseGroup.title,
+ databaseExpr: databaseGroup.databaseExpr,
+ matchedDatabases: [],
+ });
+ const created =
+ await databaseGroupServiceClientConnect.createDatabaseGroup(
+ createProto(CreateDatabaseGroupRequestSchema, {
+ parent: projectName,
+ databaseGroup: newDatabaseGroup,
+ databaseGroupId,
+ validateOnly,
+ }),
+ {
+ contextValues: createContextValues().set(
+ silentContextKey,
+ validateOnly
+ ),
+ }
+ );
+ if (!validateOnly) {
+ setCache(created, DatabaseGroupView.FULL);
+ }
+ return created;
+ },
+
+ updateDatabaseGroup: async (databaseGroup, updateMask) => {
+ const updated =
+ await databaseGroupServiceClientConnect.updateDatabaseGroup(
+ createProto(UpdateDatabaseGroupRequestSchema, {
+ databaseGroup,
+ updateMask: { paths: updateMask },
+ })
+ );
+ setCache(updated, DatabaseGroupView.FULL);
+ return updated;
+ },
+
+ deleteDatabaseGroup: async (name) => {
+ await databaseGroupServiceClientConnect.deleteDatabaseGroup(
+ createProto(DeleteDatabaseGroupRequestSchema, { name })
+ );
+ removeCache(name);
+ },
+
+ fetchDatabaseGroupMatchList: async ({ projectName, expr }) => {
+ const celexpr = await buildCELExpr(expr);
+ if (!celexpr) {
+ return [];
+ }
+ const celStrings = await batchConvertParsedExprToCELString([celexpr]);
+ const expression = celStrings[0] || "true";
+ const validateOnlyResourceId = `creating-database-group-${Date.now()}`;
+ const result = await get().createDatabaseGroup({
+ projectName,
+ databaseGroup: createProto(DatabaseGroupSchema, {
+ name: `${projectName}/${databaseGroupNamePrefix}${validateOnlyResourceId}`,
+ title: validateOnlyResourceId,
+ databaseExpr: createProto(ExprSchema, { expression }),
+ }),
+ databaseGroupId: validateOnlyResourceId,
+ validateOnly: true,
+ });
+ return result.matchedDatabases.map((item) => item.name);
+ },
+ };
+};
diff --git a/frontend/src/react/stores/app/index.test.ts b/frontend/src/react/stores/app/index.test.ts
index 0989a50d8a..4433921b71 100644
--- a/frontend/src/react/stores/app/index.test.ts
+++ b/frontend/src/react/stores/app/index.test.ts
@@ -1,7 +1,7 @@
import { create as createProto } from "@bufbuild/protobuf";
import { beforeEach, describe, expect, test, vi } from "vitest";
import { ReactShellBridgeEvent } from "@/react/shell-bridge";
-import { UNKNOWN_PROJECT_NAME } from "@/types";
+import { isValidDatabaseGroupName, UNKNOWN_PROJECT_NAME } from "@/types";
import { ExprSchema } from "@/types/proto-es/google/type/expr_pb";
import {
AccessGrant_Status,
@@ -9,7 +9,10 @@ import {
} from "@/types/proto-es/v1/access_grant_service_pb";
import { ActuatorInfoSchema } from "@/types/proto-es/v1/actuator_service_pb";
import { State } from "@/types/proto-es/v1/common_pb";
-import { DatabaseGroupSchema } from "@/types/proto-es/v1/database_group_service_pb";
+import {
+ DatabaseGroupSchema,
+ DatabaseGroupView,
+} from "@/types/proto-es/v1/database_group_service_pb";
import {
ChangelogSchema,
ChangelogView,
@@ -1912,4 +1915,43 @@ describe("useAppStore", () => {
expect(mocks.getDatabaseMetadata).toHaveBeenCalledTimes(2);
});
+
+ describe("getDBGroupByName / getOrFetchDBGroupByName cache semantics", () => {
+ test("getDBGroupByName returns unknownDatabaseGroup when absent", () => {
+ const store = createAppStore();
+ const group = store
+ .getState()
+ .getDBGroupByName("projects/p/databaseGroups/x");
+ expect(isValidDatabaseGroupName(group.name)).toBe(false);
+ });
+
+ test("getDBGroupByName with FULL view misses a BASIC-only cache entry", () => {
+ const store = createAppStore();
+ const name = "projects/p/databaseGroups/g";
+ store.setState({
+ dbGroupsByName: {
+ [name]: createProto(DatabaseGroupSchema, { name, title: "g" }),
+ },
+ dbGroupViewByName: { [name]: DatabaseGroupView.BASIC },
+ });
+ expect(store.getState().getDBGroupByName(name).name).toBe(name);
+ const full = store
+ .getState()
+ .getDBGroupByName(name, DatabaseGroupView.FULL);
+ expect(isValidDatabaseGroupName(full.name)).toBe(false);
+ });
+
+ test("getOrFetchDBGroupByName returns cached entry without a request", async () => {
+ const store = createAppStore();
+ const name = "projects/p/databaseGroups/g";
+ store.setState({
+ dbGroupsByName: {
+ [name]: createProto(DatabaseGroupSchema, { name, title: "g" }),
+ },
+ dbGroupViewByName: { [name]: DatabaseGroupView.BASIC },
+ });
+ const group = await store.getState().getOrFetchDBGroupByName(name);
+ expect(group.name).toBe(name);
+ });
+ });
});
diff --git a/frontend/src/react/stores/app/types.ts b/frontend/src/react/stores/app/types.ts
index 0139963a3e..a57bcb1444 100644
--- a/frontend/src/react/stores/app/types.ts
+++ b/frontend/src/react/stores/app/types.ts
@@ -1,4 +1,5 @@
import type { StateCreator } from "zustand";
+import type { ConditionGroupExpr } from "@/plugins/cel";
import type { DatabaseFilter } from "@/react/lib/databaseFilter";
import type { AppFeatures } from "@/types/appProfile";
import type { Permission } from "@/types/iam/permission";
@@ -317,6 +318,39 @@ export type DBGroupSlice = {
view?: DatabaseGroupView
) => Promise<DatabaseGroup | undefined>;
listDBGroupsForProject: (project: string) => Promise<DatabaseGroup[]>;
+ // Synchronous cache read. Returns `unknownDatabaseGroup()` when absent or
+ // when a FULL view is requested but only BASIC is cached.
+ getDBGroupByName: (name: string, view?: DatabaseGroupView) => DatabaseGroup;
+ getOrFetchDBGroupByName: (
+ name: string,
+ options?: {
+ skipCache?: boolean;
+ silent?: boolean;
+ view?: DatabaseGroupView;
+ }
+ ) => Promise<DatabaseGroup>;
+ fetchDBGroupListByProjectName: (
+ projectName: string,
+ view: DatabaseGroupView
+ ) => Promise<DatabaseGroup[]>;
+ createDatabaseGroup: (params: {
+ projectName: string;
+ databaseGroup: Pick<
+ DatabaseGroup,
+ "$typeName" | "name" | "title" | "databaseExpr"
+ >;
+ databaseGroupId: string;
+ validateOnly?: boolean;
+ }) => Promise<DatabaseGroup>;
+ updateDatabaseGroup: (
+ databaseGroup: DatabaseGroup,
+ updateMask: string[]
+ ) => Promise<DatabaseGroup>;
+ deleteDatabaseGroup: (name: string) => Promise<void>;
+ fetchDatabaseGroupMatchList: (params: {
+ projectName: string;
+ expr: ConditionGroupExpr;
+ }) => Promise<string[]>;
};
export type SheetSlice = {
diff --git a/frontend/src/store/modules/dbGroup.ts b/frontend/src/store/modules/dbGroup.ts
deleted file mode 100644
index 5c00978ca0..0000000000
--- a/frontend/src/store/modules/dbGroup.ts
+++ /dev/null
@@ -1,275 +0,0 @@
-import { create } from "@bufbuild/protobuf";
-import { createContextValues } from "@connectrpc/connect";
-import { head } from "lodash-es";
-import { defineStore } from "pinia";
-import type { MaybeRef } from "vue";
-import { computed, ref, unref, watch, watchEffect } from "vue";
-import { databaseGroupServiceClientConnect } from "@/connect";
-import { silentContextKey } from "@/connect/context-key";
-import type { ConditionGroupExpr } from "@/plugins/cel";
-import { buildCELExpr } from "@/plugins/cel";
-import { isValidDatabaseGroupName, unknownDatabaseGroup } from "@/types";
-import { ExprSchema } from "@/types/proto-es/google/type/expr_pb";
-import type { DatabaseGroup } from "@/types/proto-es/v1/database_group_service_pb";
-import {
- CreateDatabaseGroupRequestSchema,
- DatabaseGroupSchema,
- DatabaseGroupView,
- DeleteDatabaseGroupRequestSchema,
- GetDatabaseGroupRequestSchema,
- ListDatabaseGroupsRequestSchema,
- UpdateDatabaseGroupRequestSchema,
-} from "@/types/proto-es/v1/database_group_service_pb";
-import { batchConvertParsedExprToCELString } from "@/utils";
-import { useCache } from "../cache";
-import { databaseGroupNamePrefix } from "./v1/common";
-
-type DatabaseGroupCacheKey = [string /* name */, DatabaseGroupView];
-
-export const useDBGroupStore = defineStore("db-group", () => {
- const cacheByName = useCache<DatabaseGroupCacheKey, DatabaseGroup>(
- "bb.database-group.by-name"
- );
-
- const getCacheWithFallback = (
- name: string,
- view: DatabaseGroupView = DatabaseGroupView.UNSPECIFIED
- ): DatabaseGroup | undefined => {
- let views: DatabaseGroupView[] = [];
- switch (view) {
- case DatabaseGroupView.UNSPECIFIED:
- case DatabaseGroupView.BASIC:
- views = [DatabaseGroupView.BASIC, DatabaseGroupView.FULL];
- break;
- case DatabaseGroupView.FULL:
- views = [DatabaseGroupView.FULL];
- break;
- }
-
- for (const v of views) {
- const entity = cacheByName.getEntity([name, v]);
- if (entity) {
- return entity;
- }
- }
- };
-
- const removeDatabaseGroupCache = (name: string) => {
- const views = [DatabaseGroupView.BASIC, DatabaseGroupView.FULL];
- for (const view of views) {
- cacheByName.invalidateEntity([name, view]);
- }
- };
-
- // Cache utils
- const setDatabaseGroupCache = (
- databaseGroup: DatabaseGroup,
- view: DatabaseGroupView
- ) => {
- removeDatabaseGroupCache(databaseGroup.name);
- cacheByName.setEntity([databaseGroup.name, view], databaseGroup);
- };
-
- const getOrFetchDBGroupByName = async (
- name: string,
- options?: {
- skipCache?: boolean;
- silent?: boolean;
- view?: DatabaseGroupView;
- }
- ) => {
- const {
- skipCache = false,
- silent = false,
- view = DatabaseGroupView.BASIC,
- } = options ?? {};
- if (!skipCache) {
- const cached = getDBGroupByName(name, view);
- if (isValidDatabaseGroupName(cached.name)) {
- return cached;
- }
- }
-
- const request = create(GetDatabaseGroupRequestSchema, {
- name,
- view,
- });
- const databaseGroup =
- await databaseGroupServiceClientConnect.getDatabaseGroup(request, {
- contextValues: createContextValues().set(silentContextKey, silent),
- });
- setDatabaseGroupCache(databaseGroup, view);
- return databaseGroup;
- };
-
- const fetchDBGroupListByProjectName = async (
- projectName: string,
- view: DatabaseGroupView
- ) => {
- const request = create(ListDatabaseGroupsRequestSchema, {
- parent: projectName,
- view,
- });
- const { databaseGroups } =
- await databaseGroupServiceClientConnect.listDatabaseGroups(request);
- for (const databaseGroup of databaseGroups) {
- setDatabaseGroupCache(databaseGroup, view);
- }
- return databaseGroups;
- };
-
- const getDBGroupByName = (
- name: string,
- view?: DatabaseGroupView
- ): DatabaseGroup => {
- return getCacheWithFallback(name, view) ?? unknownDatabaseGroup();
- };
-
- const createDatabaseGroup = async ({
- projectName,
- databaseGroup,
- databaseGroupId,
- validateOnly = false,
- }: {
- projectName: string;
- databaseGroup: Pick<
- DatabaseGroup,
- "$typeName" | "name" | "title" | "databaseExpr"
- >;
- databaseGroupId: string;
- validateOnly?: boolean;
- }) => {
- const newDatabaseGroup = create(DatabaseGroupSchema, {
- name: databaseGroup.name,
- title: databaseGroup.title,
- databaseExpr: databaseGroup.databaseExpr,
- matchedDatabases: [],
- });
- const request = create(CreateDatabaseGroupRequestSchema, {
- parent: projectName,
- databaseGroup: newDatabaseGroup,
- databaseGroupId,
- validateOnly,
- });
- const createdDatabaseGroup =
- await databaseGroupServiceClientConnect.createDatabaseGroup(request, {
- contextValues: createContextValues().set(
- silentContextKey,
- validateOnly
- ),
- });
- if (!validateOnly) {
- setDatabaseGroupCache(createdDatabaseGroup, DatabaseGroupView.FULL);
- }
- return createdDatabaseGroup;
- };
-
- const updateDatabaseGroup = async (
- databaseGroup: DatabaseGroup,
- updateMask: string[]
- ) => {
- const request = create(UpdateDatabaseGroupRequestSchema, {
- databaseGroup,
- updateMask: { paths: updateMask },
- });
- const updatedDatabaseGroup =
- await databaseGroupServiceClientConnect.updateDatabaseGroup(request);
- setDatabaseGroupCache(updatedDatabaseGroup, DatabaseGroupView.FULL);
- return updatedDatabaseGroup;
- };
-
- const deleteDatabaseGroup = async (name: string) => {
- const request = create(DeleteDatabaseGroupRequestSchema, {
- name: name,
- });
- await databaseGroupServiceClientConnect.deleteDatabaseGroup(request);
- removeDatabaseGroupCache(name);
- };
-
- const fetchDatabaseGroupMatchList = async ({
- projectName,
- expr,
- }: {
- projectName: string;
- expr: ConditionGroupExpr;
- }) => {
- const celexpr = await buildCELExpr(expr);
- if (!celexpr) {
- return [];
- }
- const celStrings = await batchConvertParsedExprToCELString([celexpr]);
- const expression = head(celStrings) || "true"; // Fallback to true.
- const validateOnlyResourceId = `creating-database-group-${Date.now()}`;
-
- const result = await createDatabaseGroup({
- projectName: projectName,
- databaseGroup: create(DatabaseGroupSchema, {
- name: `${projectName}/${databaseGroupNamePrefix}${validateOnlyResourceId}`,
- title: validateOnlyResourceId,
- databaseExpr: create(ExprSchema, {
- expression,
- }),
- }),
- databaseGroupId: validateOnlyResourceId,
- validateOnly: true,
- });
-
- return result.matchedDatabases.map((item) => item.name);
- };
-
- return {
- getOrFetchDBGroupByName,
- fetchDBGroupListByProjectName,
- getDBGroupByName,
- createDatabaseGroup,
- updateDatabaseGroup,
- deleteDatabaseGroup,
- fetchDatabaseGroupMatchList,
- };
-});
-
-export const useDBGroupListByProject = (
- project: MaybeRef<string>,
- view: DatabaseGroupView = DatabaseGroupView.BASIC
-) => {
- const store = useDBGroupStore();
- const ready = ref(false);
- const dbGroupList = ref<DatabaseGroup[]>([]);
-
- watchEffect(() => {
- ready.value = false;
- dbGroupList.value = [];
- store
- .fetchDBGroupListByProjectName(unref(project), view)
- .then((response) => {
- ready.value = true;
- dbGroupList.value = response;
- });
- });
-
- return { dbGroupList, ready };
-};
-
-export const useDatabaseGroupByName = (
- name: MaybeRef<string>,
- view: DatabaseGroupView
-) => {
- const store = useDBGroupStore();
- const ready = ref(true);
- watch(
- () => unref(name),
- (name) => {
- ready.value = false;
- store.getOrFetchDBGroupByName(name, { view }).then(() => {
- ready.value = true;
- });
- },
- { immediate: true }
- );
- const databaseGroup = computed(() => store.getDBGroupByName(unref(name)));
-
- return {
- databaseGroup,
- ready,
- };
-};
diff --git a/frontend/src/store/modules/index.ts b/frontend/src/store/modules/index.ts
index af8dc0b310..c210f9d48b 100644
--- a/frontend/src/store/modules/index.ts
+++ b/frontend/src/store/modules/index.ts
@@ -8,7 +8,6 @@ export * from "./serviceAccount";
export * from "./workloadIdentity";
export * from "./workspaceApprovalSetting";
export * from "./role";
-export * from "./dbGroup";
export * from "./utils";
export * from "./rollout";