Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
refactor: use react app store (#20442)
ecmadao38fd0d68a6bc
diff --git a/frontend/src/react/components/sql-editor/AccessGrantRequestDrawer.test.tsx b/frontend/src/react/components/sql-editor/AccessGrantRequestDrawer.test.tsxindex 052db50718..9aa8893e22 100644--- a/frontend/src/react/components/sql-editor/AccessGrantRequestDrawer.test.tsx+++ b/frontend/src/react/components/sql-editor/AccessGrantRequestDrawer.test.tsx@@ -19,7 +19,9 @@ const mocks = vi.hoisted(() => ({setAsidePanelTab: vi.fn(),setHighlightAccessGrantName: vi.fn(),pushNotification: vi.fn(),- useDatabaseV1Store: vi.fn(),+ fetchDatabases: vi+ .fn()+ .mockResolvedValue({ databases: [], nextPageToken: "" }),createAccessGrant: vi.fn(),routerResolve: vi.fn(() => ({ fullPath: "/projects/proj1/issues/123" })),}));@@ -41,7 +43,11 @@ vi.mock("@/react/hooks/useAppState", () => ({vi.mock("@/store", () => ({pushNotification: mocks.pushNotification,- useDatabaseV1Store: mocks.useDatabaseV1Store,+}));++vi.mock("@/react/stores/app", () => ({+ useAppStore: (selector: (state: unknown) => unknown) =>+ selector({ fetchDatabases: mocks.fetchDatabases }),}));// Zustand editor store — active project read.@@ -313,9 +319,7 @@ const setupMocks = () => {mocks.project = "projects/proj1";mocks.currentTabDatabase = "instances/inst1/databases/db1";- mocks.useDatabaseV1Store.mockReturnValue({- fetchDatabases: vi.fn().mockResolvedValue({ databases: [] }),- });+ mocks.fetchDatabases.mockResolvedValue({ databases: [], nextPageToken: "" });mocks.usePiniaBridge.mockImplementation((getter: () => unknown) => getter());};diff --git a/frontend/src/react/components/sql-editor/AccessGrantRequestDrawer.tsx b/frontend/src/react/components/sql-editor/AccessGrantRequestDrawer.tsxindex a3f1406277..f64efdbe62 100644--- a/frontend/src/react/components/sql-editor/AccessGrantRequestDrawer.tsx+++ b/frontend/src/react/components/sql-editor/AccessGrantRequestDrawer.tsx@@ -20,12 +20,13 @@ import {} from "@/react/components/ui/sheet";import { Textarea } from "@/react/components/ui/textarea";import { useCurrentUser } from "@/react/hooks/useAppState";+import { useAppStore } from "@/react/stores/app";import { useSQLEditorStore } from "@/react/stores/sqlEditor";import { useSQLEditorEditorState } from "@/react/stores/sqlEditor/editor";import { getSQLEditorTabsState } from "@/react/stores/sqlEditor/tab";import { router } from "@/router";import { PROJECT_V1_ROUTE_ISSUE_DETAIL } from "@/router/dashboard/projectV1";-import { pushNotification, useDatabaseV1Store } from "@/store";+import { pushNotification } from "@/store";import {AccessGrant_Status,AccessGrantSchema,@@ -52,16 +53,15 @@ function MultiDatabaseSelect({{ name: string; displayName: string }[]>([]);- const databaseStore = useDatabaseV1Store();+ const fetchDatabases = useAppStore((s) => s.fetchDatabases);useEffect(() => {- databaseStore- .fetchDatabases({- parent: projectName,- filter: { query: "" },- pageSize: 100,- silent: true,- })+ fetchDatabases({+ parent: projectName,+ filter: { query: "" },+ pageSize: 100,+ silent: true,+ }).then((result) => {setDatabases(result.databases.map((db) => {@@ -73,7 +73,7 @@ function MultiDatabaseSelect({.catch(() => {/* ignore */});- }, [databaseStore, projectName]);+ }, [fetchDatabases, projectName]);return (<Comboboxdiff --git a/frontend/src/react/components/sql-editor/AccessPane.test.tsx b/frontend/src/react/components/sql-editor/AccessPane.test.tsxindex c94d45ea14..5b83cf5060 100644--- a/frontend/src/react/components/sql-editor/AccessPane.test.tsx+++ b/frontend/src/react/components/sql-editor/AccessPane.test.tsx@@ -9,8 +9,12 @@ import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";const mocks = vi.hoisted(() => ({useTranslation: vi.fn(() => ({ t: (key: string) => key })),- useProjectV1Store: vi.fn(),- // Zustand editor store project read.+ // useAppProject (app store) return value.+ projectData: { name: "projects/proj1", title: "Project 1" } as {+ name: string;+ title: string;+ },+ // Zustand editor store project name.project: "projects/proj1" as string,// New zustand store state + setter.state: {@@ -19,7 +23,10 @@ const mocks = vi.hoisted(() => ({setHighlightAccessGrantName: vi.fn(),searchMyAccessGrants: vi.fn(),useIssueV1Store: vi.fn(),- useDatabaseV1Store: vi.fn(),+ fetchDatabases: vi+ .fn()+ .mockResolvedValue({ databases: [], nextPageToken: "" }),+ getOrFetchDatabaseByName: vi.fn().mockResolvedValue({}),hasFeature: vi.fn(() => true),sqlEditorEventsEmit: vi.fn().mockResolvedValue(undefined),getDefaultPagination: vi.fn(() => 20),@@ -30,16 +37,20 @@ vi.mock("react-i18next", () => ({}));vi.mock("@/store", () => ({- useProjectV1Store: mocks.useProjectV1Store,useIssueV1Store: mocks.useIssueV1Store,- useDatabaseV1Store: mocks.useDatabaseV1Store,hasFeature: mocks.hasFeature,}));+vi.mock("@/react/hooks/useAppProject", () => ({+ useAppProject: () => mocks.projectData,+}));+vi.mock("@/react/stores/app", () => ({useAppStore: (selector: (state: unknown) => unknown) =>selector({searchMyAccessGrants: mocks.searchMyAccessGrants,+ fetchDatabases: mocks.fetchDatabases,+ getOrFetchDatabaseByName: mocks.getOrFetchDatabaseByName,}),}));@@ -226,12 +237,7 @@ const renderIntoContainer = (element: ReactElement) => {const setupDefaultMocks = () => {mocks.useTranslation.mockReturnValue({ t: (key: string) => key });- mocks.useProjectV1Store.mockReturnValue({- getProjectByName: vi.fn(() => ({- name: "projects/proj1",- title: "Project 1",- })),- });+ mocks.projectData = { name: "projects/proj1", title: "Project 1" };mocks.project = "projects/proj1";@@ -246,10 +252,8 @@ const setupDefaultMocks = () => {fetchIssueByName: vi.fn().mockResolvedValue({}),});- mocks.useDatabaseV1Store.mockReturnValue({- fetchDatabases: vi.fn().mockResolvedValue({ databases: [] }),- getOrFetchDatabaseByName: vi.fn().mockResolvedValue({}),- });+ mocks.fetchDatabases.mockResolvedValue({ databases: [], nextPageToken: "" });+ mocks.getOrFetchDatabaseByName.mockResolvedValue({});mocks.hasFeature.mockReturnValue(true);mocks.getDefaultPagination.mockReturnValue(20);diff --git a/frontend/src/react/components/sql-editor/AccessPane.tsx b/frontend/src/react/components/sql-editor/AccessPane.tsxindex 7ae57bbdcd..c00ca59f0b 100644--- a/frontend/src/react/components/sql-editor/AccessPane.tsx+++ b/frontend/src/react/components/sql-editor/AccessPane.tsx@@ -16,16 +16,12 @@ import { AdvancedSearch } from "@/react/components/AdvancedSearch";import { FeatureBadge } from "@/react/components/FeatureBadge";import { PermissionGuard } from "@/react/components/PermissionGuard";import { Button } from "@/react/components/ui/button";+import { useAppProject } from "@/react/hooks/useAppProject";import { useAppStore } from "@/react/stores/app";import type { AccessGrantFilter as AccessFilter } from "@/react/stores/app/types";import { useSQLEditorStore } from "@/react/stores/sqlEditor";import { useSQLEditorEditorState } from "@/react/stores/sqlEditor/editor";-import {- hasFeature,- useDatabaseV1Store,- useIssueV1Store,- useProjectV1Store,-} from "@/store";+import { hasFeature, useIssueV1Store } from "@/store";import type { AccessGrant } from "@/types/proto-es/v1/access_grant_service_pb";import { AccessGrant_Status } from "@/types/proto-es/v1/access_grant_service_pb";import type { Issue } from "@/types/proto-es/v1/issue_service_pb";@@ -46,12 +42,14 @@ const DEFAULT_SCOPES = [export function AccessPane() {const { t } = useTranslation();- const projectStore = useProjectV1Store();const searchMyAccessGrants = useAppStore((state) => state.searchMyAccessGrants);+ const fetchDatabases = useAppStore((state) => state.fetchDatabases);+ const getOrFetchDatabaseByName = useAppStore(+ (state) => state.getOrFetchDatabaseByName+ );const issueStore = useIssueV1Store();- const databaseStore = useDatabaseV1Store();const highlightAccessGrantName = useSQLEditorStore((s) => s.highlightAccessGrantName);@@ -82,10 +80,8 @@ export function AccessPane() {const projectName = useSQLEditorEditorState((s) => s.project);- const project = useMemo(() => {- if (!projectName) return undefined;- return projectStore.getProjectByName(projectName as string);- }, [projectStore, projectName]);+ const resolvedProject = useAppProject(projectName as string);+ const project = projectName ? resolvedProject : undefined;const hasJITFeature = useMemo(() => hasFeature(PlanFeature.FEATURE_JIT), []);@@ -127,7 +123,7 @@ export function AccessPane() {onSearch: async (keyword: string) => {const parent = projectName as string | undefined;if (!parent) return [];- const result = await databaseStore.fetchDatabases({+ const result = await fetchDatabases({parent,filter: { query: keyword },pageSize: getDefaultPagination(),@@ -140,7 +136,7 @@ export function AccessPane() {},},];- }, [t, projectName, databaseStore]);+ }, [t, projectName, fetchDatabases]);// Build AccessFilter from React SearchParamsconst filter = useMemo((): AccessFilter => {@@ -264,14 +260,14 @@ export function AccessPane() {async (grant: AccessGrant) => {const database = grant.targets[0] ?? "";const instanceName = database.replace(/\/databases\/.*$/, "");- await databaseStore.getOrFetchDatabaseByName(database);+ await getOrFetchDatabaseByName(database);await sqlEditorEvents.emit("execute-sql", {connection: { instance: instanceName, database },statement: grant.query,batchQueryContext: { databases: grant.targets },});},- [databaseStore]+ [getOrFetchDatabaseByName]);return (diff --git a/frontend/src/react/components/sql-editor/ConnectionPane/ConnectionPane.test.tsx b/frontend/src/react/components/sql-editor/ConnectionPane/ConnectionPane.test.tsxindex 5528360951..82a12b5a80 100644--- a/frontend/src/react/components/sql-editor/ConnectionPane/ConnectionPane.test.tsx+++ b/frontend/src/react/components/sql-editor/ConnectionPane/ConnectionPane.test.tsx@@ -63,7 +63,22 @@ const mocks = vi.hoisted(() => {})),getOrFetchDBGroupByName: vi.fn().mockResolvedValue(undefined),};- const environmentStore = {+ const project = {+ name: "projects/p",+ title: "Project One",+ };+ const treeStore = {+ state: "READY" as "LOADING" | "READY" | "UNSET",+ nodeKeysByTarget: vi.fn(() => []),+ };+ const instanceStore = {+ getInstanceByName: vi.fn(),+ };+ const appStore = {+ fetchInstance: vi.fn(async () => undefined),+ fetchDBGroup: vi.fn(async () => undefined),+ listDBGroupsForProject: vi.fn(async () => []),+ dbGroupsByName: {} as Record<string, unknown>,environmentList: [{name: "environments/prod",@@ -78,19 +93,16 @@ const mocks = vi.hoisted(() => {color: "",tags: {},})),- };- const projectStore = {- getProjectByName: vi.fn(() => ({- name: "projects/p",- title: "Project One",+ getDatabaseByName: vi.fn((name: string) => ({+ name,+ instanceResource: { engine: 0, title: "", name: "" },})),- };- const treeStore = {- state: "READY" as "LOADING" | "READY" | "UNSET",- nodeKeysByTarget: vi.fn(() => []),- };- const instanceStore = {- getInstanceByName: vi.fn(),+ getOrFetchDatabaseByName: vi.fn(async (name: string) => ({ name })),+ batchGetOrFetchDatabases: vi.fn(async () => []),+ fetchDatabases: vi+ .fn()+ .mockResolvedValue({ databases: [], nextPageToken: "" }),+ databasesByName: {} as Record<string, unknown>,};const currentUser = { email: "[email protected]" };return {@@ -100,10 +112,10 @@ const mocks = vi.hoisted(() => {uiStore,databaseStore,dbGroupStore,- environmentStore,- projectStore,+ project,treeStore,instanceStore,+ appStore,currentUser,usePiniaBridge: vi.fn<(getter: () => unknown) => unknown>(),pushNotification: vi.fn(),@@ -133,9 +145,25 @@ vi.mock("@/store", () => ({pushNotification: mocks.pushNotification,useDatabaseV1Store: () => mocks.databaseStore,useDBGroupStore: () => mocks.dbGroupStore,- useEnvironmentV1Store: () => mocks.environmentStore,useInstanceV1Store: () => mocks.instanceStore,- useProjectV1Store: () => mocks.projectStore,+}));++vi.mock("@/react/hooks/useAppProject", () => ({+ useAppProject: () => mocks.project,+}));++vi.mock("@/react/hooks/useAppDatabase", () => ({+ useAppDatabase: (name: string) => ({+ name,+ instanceResource: { engine: 0, title: "", name: "" },+ }),+}));++vi.mock("@/react/stores/app", () => ({+ useAppStore: Object.assign(+ (selector: (state: unknown) => unknown) => selector(mocks.appStore),+ { getState: () => mocks.appStore, subscribe: () => () => {} }+ ),}));vi.mock("@/react/stores/sqlEditor/tab", () => ({diff --git a/frontend/src/react/components/sql-editor/ConnectionPane/ConnectionPane.tsx b/frontend/src/react/components/sql-editor/ConnectionPane/ConnectionPane.tsxindex 19c457e0f8..da844cef13 100644--- a/frontend/src/react/components/sql-editor/ConnectionPane/ConnectionPane.tsx+++ b/frontend/src/react/components/sql-editor/ConnectionPane/ConnectionPane.tsx@@ -2,6 +2,7 @@ import { cloneDeep } from "lodash-es";import { ChevronDown, ChevronRight, Info, X } from "lucide-react";import { useCallback, useEffect, useMemo, useRef, useState } from "react";import { useTranslation } from "react-i18next";+import { useShallow } from "zustand/react/shallow";import {AdvancedSearch,emptySearchParams,@@ -23,10 +24,12 @@ import { Tooltip } from "@/react/components/ui/tooltip";import { Tree, type TreeDataNode } from "@/react/components/ui/tree";import { countVisibleRows } from "@/react/components/ui/tree-utils";import { useCommonSearchScopeOptions } from "@/react/components/useCommonSearchScopeOptions";+import { useAppDatabase } from "@/react/hooks/useAppDatabase";+import { useAppProject } from "@/react/hooks/useAppProject";import { useCurrentUser } from "@/react/hooks/useAppState";-import { usePiniaBridge } from "@/react/hooks/usePiniaBridge";import { useSQLEditorFeature } from "@/react/hooks/useSQLEditorBridge";import { cn } from "@/react/lib/utils";+import { useAppStore } from "@/react/stores/app";import { useSQLEditorStore } from "@/react/stores/sqlEditor";import { useSQLEditorEditorState } from "@/react/stores/sqlEditor/editor";import {@@ -35,14 +38,7 @@ import {useIsInBatchMode,useSupportBatchMode,} from "@/react/stores/sqlEditor/tab";-import {- pushNotification,- useDatabaseV1Store,- useDBGroupStore,- useEnvironmentV1Store,- useInstanceV1Store,- useProjectV1Store,-} from "@/store";+import { pushNotification } from "@/store";import { instanceNamePrefix } from "@/store/modules/v1/common";import type { DatabaseFilter } from "@/store/modules/v1/database";import type {@@ -146,11 +142,13 @@ function ConnectionPaneInner({ show, onMissingFeature }: Props) {const setShowConnectionPanel = useSQLEditorStore((s) => s.setShowConnectionPanel);- const databaseStore = useDatabaseV1Store();- const dbGroupStore = useDBGroupStore();- const environmentStore = useEnvironmentV1Store();- const projectStore = useProjectV1Store();- const instanceStore = useInstanceV1Store();+ const getOrFetchDatabaseByName = useAppStore(+ (s) => s.getOrFetchDatabaseByName+ );+ const batchGetOrFetchDatabases = useAppStore(+ (s) => s.batchGetOrFetchDatabases+ );+ const fetchDBGroup = useAppStore((s) => s.fetchDBGroup);const setTreeState = useSQLEditorStore((s) => s.setTreeState);const treeNodeKeysByTarget = useSQLEditorStore((s) => s.treeNodeKeysByTarget);const currentUserEmail = useCurrentUser().email;@@ -163,9 +161,7 @@ function ConnectionPaneInner({ show, onMissingFeature }: Props) {const projectContextReady = useSQLEditorEditorState((s) => s.projectContextReady);- const environmentList = usePiniaBridge(- () => environmentStore.environmentList- );+ const environmentList = useAppStore((s) => s.environmentList);const hasBatchQueryFeature = useSQLEditorFeature(PlanFeature.FEATURE_BATCH_QUERY@@ -218,27 +214,34 @@ function ConnectionPaneInner({ show, onMissingFeature }: Props) {[currentTab?.batchQueryContext?.databaseGroups]);+ // Ensure each selected group is fetched with the FULL view so its+ // `matchedDatabases` are available for the coverage map + query routing.+ useEffect(() => {+ for (const groupName of selectedDatabaseGroupNames) {+ void fetchDBGroup(groupName, DatabaseGroupView.FULL);+ }+ }, [fetchDBGroup, selectedDatabaseGroupNames]);+// Map<databaseResourceName, groupTitle> for every database covered by// any currently-selected database group. Mirrors Vue's// `flattenSelectedDatabasesFromGroup` and drives the tree-row checkbox// so users can see which databases are already implicitly included via// group selection (rendered as checked + disabled + tooltip in batch- // mode). usePiniaBridge — the underlying group cache mutates without the- // store reference changing, so a deep subscription catches new- // matchedDatabases as they arrive from the FULL-view fetch.- const groupCoveredDatabaseTitles = usePiniaBridge(- () => {+ // mode). `useShallow` over the Map keeps the snapshot stable (zustand's+ // shallow equality compares Map entries) and picks up the FULL-view+ // `matchedDatabases` as they land in the store.+ const groupCoveredDatabaseTitles = useAppStore(+ useShallow((s) => {const map = new Map<string, string>();for (const groupName of selectedDatabaseGroupNames) {- const group = dbGroupStore.getDBGroupByName(groupName);- if (!isValidDatabaseGroupName(group.name)) continue;+ const group = s.dbGroupsByName[groupName];+ if (!group || !isValidDatabaseGroupName(group.name)) continue;for (const m of group.matchedDatabases) {map.set(m.name, group.title);}}return map;- },- { deep: true }+ }));const selectedDatabaseNames = useMemo(() => {@@ -257,10 +260,8 @@ function ConnectionPaneInner({ show, onMissingFeature }: Props) {selectedDatabaseGroupNames.length,]);- const projectTitle = usePiniaBridge(() => {- if (!projectName) return "";- return projectStore.getProjectByName(projectName).title;- });+ const currentProject = useAppProject(projectName);+ const projectTitle = projectName ? currentProject.title : "";const scopeOptions = useCommonSearchScopeOptions(["instance",@@ -330,8 +331,8 @@ function ConnectionPaneInner({ show, onMissingFeature }: Props) {// with the right title immediately).useEffect(() => {if (!currentTab) return;- void databaseStore.batchGetOrFetchDatabases(selectedDatabaseNames);- }, [currentTab, databaseStore, selectedDatabaseNames]);+ void batchGetOrFetchDatabases(selectedDatabaseNames);+ }, [currentTab, batchGetOrFetchDatabases, selectedDatabaseNames]);// Drive treeStore.state transitions so the mask spinner lifts when the// project is ready and hides again when the project changes.@@ -367,17 +368,19 @@ function ConnectionPaneInner({ show, onMissingFeature }: Props) {return;}if (connection.database) {- const database = await databaseStore.getOrFetchDatabaseByName(- connection.database- );+ const database = await getOrFetchDatabaseByName(connection.database);if (cancelled) return;setSelectedKeys(treeNodeKeysByTarget("database", database));return;}if (connection.instance) {- const instance = instanceStore.getInstanceByName(connection.instance);+ const instance = await useAppStore+ .getState()+ .fetchInstance(connection.instance);if (cancelled) return;- setSelectedKeys(treeNodeKeysByTarget("instance", instance));+ setSelectedKeys(+ instance ? treeNodeKeysByTarget("instance", instance) : []+ );return;}if (!cancelled) setSelectedKeys([]);@@ -392,7 +395,7 @@ function ConnectionPaneInner({ show, onMissingFeature }: Props) {cancelled = true;unsubscribe();};- }, [databaseStore, instanceStore, treeNodeKeysByTarget]);+ }, [getOrFetchDatabaseByName, treeNodeKeysByTarget]);// Context-menu imperative handle.const contextMenuRef = useRef<ConnectionContextMenuHandle>(null);@@ -427,11 +430,7 @@ function ConnectionPaneInner({ show, onMissingFeature }: Props) {async (ctx: BatchQueryContext): Promise<boolean> => {setSwitchingConnection(true);try {- const queryable = await getQueryableDatabase(- ctx,- databaseStore,- dbGroupStore- );+ const queryable = await getQueryableDatabase(ctx);const tabsState = getSQLEditorTabsState();const currentConnection = getConnectionForSQLEditorTab(tabsState.tabsById.get(tabsState.currentTabId)@@ -454,7 +453,7 @@ function ConnectionPaneInner({ show, onMissingFeature }: Props) {setSwitchingConnection(false);}},- [databaseStore, dbGroupStore]+ []);const handleToggleDatabase = useCallback(@@ -717,7 +716,6 @@ function BatchModeHeader({onUncheckDatabaseGroup: (name: string) => void;}) {const { t } = useTranslation();- const databaseStore = useDatabaseV1Store();return (<div className="w-full px-4 mt-4">@@ -739,7 +737,6 @@ function BatchModeHeader({name={db}disabled={switchingConnection}onClose={() => onToggleDatabase(db, false)}- resolveDatabase={() => databaseStore.getDatabaseByName(db)}/>))}{hasDatabaseGroupFeature &&@@ -786,17 +783,13 @@ function SelectedDatabaseTag({name,disabled,onClose,- resolveDatabase,}: {name: string;disabled: boolean;onClose: () => void;- resolveDatabase: () => ReturnType<- ReturnType<typeof useDatabaseV1Store>["getDatabaseByName"]- >;}) {const { t } = useTranslation();- const database = usePiniaBridge(resolveDatabase);+ const database = useAppDatabase(name);const instance = useMemo(() => {if (!database) return null;return getInstanceResource(database);@@ -1251,20 +1244,18 @@ function collectAllNodeKeys(nodes: SQLEditorTreeNode[]): string[] {* "no-queriable-database" notification is only surfaced when the function* returns `undefined` (i.e. no databases at all in any picked group).*/-async function getQueryableDatabase(- ctx: BatchQueryContext,- databaseStore: ReturnType<typeof useDatabaseV1Store>,- dbGroupStore: ReturnType<typeof useDBGroupStore>-) {+async function getQueryableDatabase(ctx: BatchQueryContext) {if (ctx.databases.length > 0) {- return databaseStore.getDatabaseByName(ctx.databases[0]);+ return useAppStore.getState().getDatabaseByName(ctx.databases[0]);}for (const groupName of ctx.databaseGroups ?? []) {- const group = dbGroupStore.getDBGroupByName(groupName);- if (!isValidDatabaseGroupName(group.name)) continue;- const databases = await databaseStore.batchGetOrFetchDatabases(- group.matchedDatabases.map((d) => d.name)- );+ const group = await useAppStore+ .getState()+ .fetchDBGroup(groupName, DatabaseGroupView.FULL);+ if (!group || !isValidDatabaseGroupName(group.name)) continue;+ const databases = await useAppStore+ .getState()+ .batchGetOrFetchDatabases(group.matchedDatabases.map((d) => d.name));if (databases.length > 0) return databases[0];}return undefined;diff --git a/frontend/src/react/components/sql-editor/ConnectionPane/DatabaseGroupTag.test.tsx b/frontend/src/react/components/sql-editor/ConnectionPane/DatabaseGroupTag.test.tsxindex 6181295660..1facd17d21 100644--- a/frontend/src/react/components/sql-editor/ConnectionPane/DatabaseGroupTag.test.tsx+++ b/frontend/src/react/components/sql-editor/ConnectionPane/DatabaseGroupTag.test.tsx@@ -8,24 +8,25 @@ import { beforeEach, describe, expect, test, vi } from "vitest";).IS_REACT_ACT_ENVIRONMENT = true;const mocks = vi.hoisted(() => ({- getOrFetchDBGroupByName: vi.fn().mockResolvedValue(undefined),+ fetchDBGroup: vi.fn().mockResolvedValue(undefined),getDBGroupByName: vi.fn(),- useVueState: vi.fn<(getter: () => unknown) => unknown>(),}));vi.mock("react-i18next", () => ({useTranslation: () => ({ t: (key: string) => key }),}));-vi.mock("@/store", () => ({- useDBGroupStore: () => ({- getOrFetchDBGroupByName: mocks.getOrFetchDBGroupByName,- getDBGroupByName: mocks.getDBGroupByName,- }),-}));--vi.mock("@/react/hooks/useVueState", () => ({- useVueState: mocks.useVueState,+vi.mock("@/react/stores/app", () => ({+ useAppStore: (selector: (state: unknown) => unknown) =>+ selector({+ fetchDBGroup: mocks.fetchDBGroup,+ // Proxy so `dbGroupsByName[name]` resolves through the per-test+ // `getDBGroupByName` mock (preserves the existing test bodies).+ dbGroupsByName: new Proxy(+ {},+ { get: (_t, prop: string) => mocks.getDBGroupByName(prop) }+ ),+ }),}));vi.mock("@/types/proto-es/v1/database_group_service_pb", () => ({@@ -60,7 +61,6 @@ const renderIntoContainer = (element: ReactElement) => {beforeEach(async () => {vi.clearAllMocks();- mocks.useVueState.mockImplementation((getter) => getter());({ DatabaseGroupTag } = await import("./DatabaseGroupTag"));});diff --git a/frontend/src/react/components/sql-editor/ConnectionPane/DatabaseGroupTag.tsx b/frontend/src/react/components/sql-editor/ConnectionPane/DatabaseGroupTag.tsxindex 10ad011e32..aa300a7b22 100644--- a/frontend/src/react/components/sql-editor/ConnectionPane/DatabaseGroupTag.tsx+++ b/frontend/src/react/components/sql-editor/ConnectionPane/DatabaseGroupTag.tsx@@ -2,9 +2,8 @@ import { Boxes, X } from "lucide-react";import { useEffect } from "react";import { useTranslation } from "react-i18next";import { Tooltip } from "@/react/components/ui/tooltip";-import { usePiniaBridge } from "@/react/hooks/usePiniaBridge";import { cn } from "@/react/lib/utils";-import { useDBGroupStore } from "@/store";+import { useAppStore } from "@/react/stores/app";import { DatabaseGroupView } from "@/types/proto-es/v1/database_group_service_pb";type Props = {@@ -24,17 +23,13 @@ export function DatabaseGroupTag({onUncheck,}: Props) {const { t } = useTranslation();- const store = useDBGroupStore();+ const fetchDBGroup = useAppStore((s) => s.fetchDBGroup);useEffect(() => {- void store.getOrFetchDBGroupByName(databaseGroupName, {- view: DatabaseGroupView.FULL,- });- }, [store, databaseGroupName]);+ void fetchDBGroup(databaseGroupName, DatabaseGroupView.FULL);+ }, [fetchDBGroup, databaseGroupName]);- const databaseGroup = usePiniaBridge(() =>- store.getDBGroupByName(databaseGroupName)- );+ const databaseGroup = useAppStore((s) => s.dbGroupsByName[databaseGroupName]);if (!databaseGroup || !databaseGroup.name) return null;diff --git a/frontend/src/react/components/sql-editor/ConnectionPane/tree.ts b/frontend/src/react/components/sql-editor/ConnectionPane/tree.tsindex f0bf8cd0fa..043c270e9f 100644--- a/frontend/src/react/components/sql-editor/ConnectionPane/tree.ts+++ b/frontend/src/react/components/sql-editor/ConnectionPane/tree.ts@@ -1,14 +1,11 @@import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import { useAppStore } from "@/react/stores/app";import { useSQLEditorEditorState } from "@/react/stores/sqlEditor/editor";import {buildTreeImpl,mapTreeNodeByType,} from "@/react/stores/sqlEditor/tree-utils";-import {- type DatabaseFilter,- useDatabaseV1Store,- useEnvironmentV1Store,-} from "@/store";+import type { DatabaseFilter } from "@/store";import type {SQLEditorTreeNode,StatefulSQLEditorTreeFactor as StatefulFactor,@@ -90,9 +87,9 @@ export function useSQLEditorTreeByEnvironment(environment: string,{ email }: Options): TreeByEnvironment {- const databaseStore = useDatabaseV1Store();+ const fetchDatabaseList = useAppStore((s) => s.fetchDatabases);const project = useSQLEditorEditorState((s) => s.project);- const environmentStore = useEnvironmentV1Store();+ const getEnvironmentByName = useAppStore((s) => s.getEnvironmentByName);const storageKey = useMemo(() => storageKeySqlEditorConnExpanded(environment, email),@@ -143,17 +140,15 @@ export function useSQLEditorTreeByEnvironment(setFetchDataState((prev) => ({ ...prev, loading: true }));const pageToken = fetchDataStateRef.current.nextPageToken;try {- const { databases, nextPageToken } = await databaseStore.fetchDatabases(- {- parent: project,- pageToken,- pageSize: getDefaultPagination(),- filter: {- ...filter,- environment,- },- }- );+ const { databases, nextPageToken } = await fetchDatabaseList({+ parent: project,+ pageToken,+ pageSize: getDefaultPagination(),+ filter: {+ ...filter,+ environment,+ },+ });databaseListRef.current = pageToken? [...databaseListRef.current, ...databases]: [...databases];@@ -163,7 +158,7 @@ export function useSQLEditorTreeByEnvironment(setFetchDataState({ loading: false });}},- [databaseStore, project, environment]+ [fetchDatabaseList, project, environment]);// Keep a ref to the latest fetchDataState so the debounced fn can read it@@ -206,14 +201,14 @@ export function useSQLEditorTreeByEnvironment(}let next = buildTreeImpl(list, [defaultEnvironmentFactor.factor]);if (next.length === 0) {- const env = environmentStore.getEnvironmentByName(environment);+ const env = getEnvironmentByName(environment);const rootNode = mapTreeNodeByType("environment", env, undefined);rootNode.children = [];next = [rootNode];}setTree(next);},- [environmentStore, environment]+ [getEnvironmentByName, environment]);return {diff --git a/frontend/src/react/components/sql-editor/ExecuteHint.tsx b/frontend/src/react/components/sql-editor/ExecuteHint.tsxindex 46e1739733..1bb696581a 100644--- a/frontend/src/react/components/sql-editor/ExecuteHint.tsx+++ b/frontend/src/react/components/sql-editor/ExecuteHint.tsx@@ -4,16 +4,12 @@ import { Alert } from "@/react/components/ui/alert";import { Button } from "@/react/components/ui/button";import { useSQLEditorAllowAdmin } from "@/react/hooks/useSQLEditorBridge";import { applyPlanTitleToQuery } from "@/react/lib/plan/title";+import { useAppStore } from "@/react/stores/app";import { useSQLEditorEditorState } from "@/react/stores/sqlEditor/editor";import { getSQLEditorTabsState } from "@/react/stores/sqlEditor/tab";import { router } from "@/router";import { PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL } from "@/router/dashboard/projectV1";-import {- pushNotification,- useDatabaseV1Store,- useProjectV1Store,- useStorageStore,-} from "@/store";+import { pushNotification, useStorageStore } from "@/store";import { unknownProject } from "@/types";import type { Database } from "@/types/proto-es/v1/database_service_pb";import {@@ -34,8 +30,6 @@ type Props = {*/export function ExecuteHint({ database, onClose }: Props) {const { t } = useTranslation();- const databaseStore = useDatabaseV1Store();- const projectStore = useProjectV1Store();const storageStore = useStorageStore();const project = useSQLEditorEditorState((s) => s.project);const allowAdmin = useSQLEditorAllowAdmin(project);@@ -57,12 +51,14 @@ export function ExecuteHint({ database, onClose }: Props) {onClose();- const db = await databaseStore.getOrFetchDatabaseByName(connectedDatabase);+ const db = await useAppStore+ .getState()+ .getOrFetchDatabaseByName(connectedDatabase);// Fall back to `unknownProject()` (enforceIssueTitle=true) if the project- // fetch rejects so the plan page opens with a blank title.- const projectInfo = await projectStore- .getOrFetchProjectByName(db.project)- .catch(() => unknownProject());+ // can't be resolved so the plan page opens with a blank title.+ const projectInfo =+ (await useAppStore.getState().fetchProject(db.project)) ??+ unknownProject();const tab = tabsState.tabsById.get(tabsState.currentTabId);const statement = tab?.selectedStatement || tab?.statement || "";diff --git a/frontend/src/react/components/sql-editor/GutterBar.test.tsx b/frontend/src/react/components/sql-editor/GutterBar.test.tsxindex 23968d9ce9..bc73f596b9 100644--- a/frontend/src/react/components/sql-editor/GutterBar.test.tsx+++ b/frontend/src/react/components/sql-editor/GutterBar.test.tsx@@ -11,9 +11,12 @@ const mocks = vi.hoisted(() => ({useTranslation: vi.fn(() => ({ t: (key: string) => key })),// Pinia bridge — runs the getter against the (mocked) Pinia stores.usePiniaBridge: vi.fn<(getter: () => unknown) => unknown>(),- useProjectV1Store: vi.fn(),- // Zustand editor store project read.+ // Zustand editor store project name.project: "projects/test" as string,+ // useAppProject (app store) return value.+ projectData: { allowJustInTimeAccess: false } as {+ allowJustInTimeAccess: boolean;+ },// New zustand store.state: {asidePanelTab: "WORKSHEET" as string,@@ -30,8 +33,8 @@ vi.mock("@/react/hooks/usePiniaBridge", () => ({usePiniaBridge: mocks.usePiniaBridge,}));-vi.mock("@/store", () => ({- useProjectV1Store: mocks.useProjectV1Store,+vi.mock("@/react/hooks/useAppProject", () => ({+ useAppProject: () => mocks.projectData,}));vi.mock("@/react/stores/sqlEditor/editor", () => ({@@ -100,9 +103,7 @@ const renderIntoContainer = (element: ReactElement) => {beforeEach(async () => {vi.clearAllMocks();mocks.project = "projects/test";- mocks.useProjectV1Store.mockReturnValue({- getProjectByName: () => ({ allowJustInTimeAccess: false }),- });+ mocks.projectData = { allowJustInTimeAccess: false };mocks.state.asidePanelTab = "WORKSHEET";mocks.routerResolve.mockReturnValue({ href: "/workspace/home" });({ GutterBar } = await import("./GutterBar"));@@ -111,9 +112,7 @@ beforeEach(async () => {describe("GutterBar", () => {test("renders 3 tabs when project does not allow JIT access", () => {mocks.usePiniaBridge.mockImplementation((getter) => getter());- mocks.useProjectV1Store.mockReturnValue({- getProjectByName: () => ({ allowJustInTimeAccess: false }),- });+ mocks.projectData = { allowJustInTimeAccess: false };const { container, render, unmount } = renderIntoContainer(<GutterBar />);render();const buttons = container.querySelectorAll("button");@@ -123,9 +122,7 @@ describe("GutterBar", () => {test("renders 4 tabs when project allows JIT access", () => {mocks.usePiniaBridge.mockImplementation((getter) => getter());- mocks.useProjectV1Store.mockReturnValue({- getProjectByName: () => ({ allowJustInTimeAccess: true }),- });+ mocks.projectData = { allowJustInTimeAccess: true };const { container, render, unmount } = renderIntoContainer(<GutterBar />);render();const buttons = container.querySelectorAll("button");@@ -135,9 +132,7 @@ describe("GutterBar", () => {test("click writes asidePanelTab via setAsidePanelTab", () => {mocks.usePiniaBridge.mockImplementation((getter) => getter());- mocks.useProjectV1Store.mockReturnValue({- getProjectByName: () => ({ allowJustInTimeAccess: false }),- });+ mocks.projectData = { allowJustInTimeAccess: false };const { container, render, unmount } = renderIntoContainer(<GutterBar />);render();const buttons = container.querySelectorAll("button");@@ -150,9 +145,7 @@ describe("GutterBar", () => {test("logo link has target=_blank and rel=noopener noreferrer", () => {mocks.usePiniaBridge.mockImplementation((getter) => getter());- mocks.useProjectV1Store.mockReturnValue({- getProjectByName: () => ({ allowJustInTimeAccess: false }),- });+ mocks.projectData = { allowJustInTimeAccess: false };mocks.routerResolve.mockReturnValue({ href: "/workspace/home" });const { container, render, unmount } = renderIntoContainer(<GutterBar />);render();diff --git a/frontend/src/react/components/sql-editor/GutterBar.tsx b/frontend/src/react/components/sql-editor/GutterBar.tsxindex 277d1c10de..44c0e08b68 100644--- a/frontend/src/react/components/sql-editor/GutterBar.tsx+++ b/frontend/src/react/components/sql-editor/GutterBar.tsx@@ -1,5 +1,6 @@import logoIcon from "@/assets/logo-icon.svg";import { Separator } from "@/react/components/ui/separator";+import { useAppProject } from "@/react/hooks/useAppProject";import { usePiniaBridge } from "@/react/hooks/usePiniaBridge";import type { AsidePanelTab } from "@/react/stores/sqlEditor";import { useSQLEditorStore } from "@/react/stores/sqlEditor";@@ -7,7 +8,6 @@ import { useSQLEditorEditorState } from "@/react/stores/sqlEditor/editor";import { router } from "@/router";import { PROJECT_V1_ROUTE_DETAIL } from "@/router/dashboard/projectV1";import { WORKSPACE_ROUTE_LANDING } from "@/router/dashboard/workspaceRoutes";-import { useProjectV1Store } from "@/store";import { TabItem } from "./TabItem";/**@@ -18,13 +18,11 @@ import { TabItem } from "./TabItem";* Replaces frontend/src/views/sql-editor/AsidePanel/GutterBar/GutterBar.vue.*/export function GutterBar() {- const projectStore = useProjectV1Store();const setAsidePanelTab = useSQLEditorStore((s) => s.setAsidePanelTab);const projectName = useSQLEditorEditorState((s) => s.project);- const project = usePiniaBridge(() => {- return projectName ? projectStore.getProjectByName(projectName) : undefined;- });+ const resolvedProject = useAppProject(projectName);+ const project = projectName ? resolvedProject : undefined;const routeProjectParam = usePiniaBridge(() => router.currentRoute.value.params.project as string | undefineddiff --git a/frontend/src/react/components/sql-editor/MaskingReasonPopover.test.tsx b/frontend/src/react/components/sql-editor/MaskingReasonPopover.test.tsxindex b137ca8da8..ad3b854213 100644--- a/frontend/src/react/components/sql-editor/MaskingReasonPopover.test.tsx+++ b/frontend/src/react/components/sql-editor/MaskingReasonPopover.test.tsx@@ -10,7 +10,10 @@ import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";const mocks = vi.hoisted(() => ({useTranslation: vi.fn(() => ({ t: (key: string) => key })),useVueState: vi.fn<(getter: () => unknown) => unknown>(),- useProjectV1Store: vi.fn(),+ projectData: { name: "projects/proj1", allowJustInTimeAccess: false } as {+ name: string;+ allowJustInTimeAccess: boolean;+ },useSQLEditorVueState: vi.fn(),hasFeature: vi.fn(() => true),}));@@ -24,10 +27,13 @@ vi.mock("@/react/hooks/useVueState", () => ({}));vi.mock("@/store", () => ({- useProjectV1Store: mocks.useProjectV1Store,hasFeature: mocks.hasFeature,}));+vi.mock("@/react/hooks/useAppProject", () => ({+ useAppProject: () => mocks.projectData,+}));+vi.mock("@/react/stores/sqlEditor/editor-vue-state", () => ({useSQLEditorVueState: mocks.useSQLEditorVueState,}));@@ -140,12 +146,10 @@ const makeReason = (overrides?: {const setupDefaultMocks = (allowJIT = false) => {mocks.useTranslation.mockReturnValue({ t: (key: string) => key });- mocks.useProjectV1Store.mockReturnValue({- getProjectByName: vi.fn(() => ({- name: "projects/proj1",- allowJustInTimeAccess: allowJIT,- })),- });+ mocks.projectData = {+ name: "projects/proj1",+ allowJustInTimeAccess: allowJIT,+ };mocks.useSQLEditorVueState.mockReturnValue({ project: "projects/proj1" });mocks.hasFeature.mockReturnValue(true);mocks.useVueState.mockImplementation((getter: () => unknown) => getter());diff --git a/frontend/src/react/components/sql-editor/MaskingReasonPopover.tsx b/frontend/src/react/components/sql-editor/MaskingReasonPopover.tsxindex fdfd7d69db..a5aebc64c0 100644--- a/frontend/src/react/components/sql-editor/MaskingReasonPopover.tsx+++ b/frontend/src/react/components/sql-editor/MaskingReasonPopover.tsx@@ -7,9 +7,9 @@ import {PopoverContent,PopoverTrigger,} from "@/react/components/ui/popover";-import { usePiniaBridge } from "@/react/hooks/usePiniaBridge";+import { useAppProject } from "@/react/hooks/useAppProject";import { useSQLEditorEditorState } from "@/react/stores/sqlEditor/editor";-import { hasFeature, useProjectV1Store } from "@/store";+import { hasFeature } from "@/store";import type { MaskingReason } from "@/types/proto-es/v1/sql_service_pb";import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";import { AccessGrantRequestDrawer } from "./AccessGrantRequestDrawer";@@ -30,12 +30,8 @@ export function MaskingReasonPopover({const { t } = useTranslation();const [showDrawer, setShowDrawer] = useState(false);- const projectStore = useProjectV1Store();-const projectName = useSQLEditorEditorState((s) => s.project);- const project = usePiniaBridge(() =>- projectStore.getProjectByName(projectName)- );+ const project = useAppProject(projectName);const hasJITFeature = useMemo(() =>diff --git a/frontend/src/react/components/sql-editor/Panels/Panels.tsx b/frontend/src/react/components/sql-editor/Panels/Panels.tsxindex b083522c14..95092bec10 100644--- a/frontend/src/react/components/sql-editor/Panels/Panels.tsx+++ b/frontend/src/react/components/sql-editor/Panels/Panels.tsx@@ -27,6 +27,7 @@ import { ViewsPanel } from "@/react/components/sql-editor/ViewsPanel";import { Alert } from "@/react/components/ui/alert";import { useExecuteSQL } from "@/react/hooks/useExecuteSQL";import { useConnectionOfCurrentSQLEditorTab } from "@/react/hooks/useSQLEditorBridge";+import { useAppStore } from "@/react/stores/app";import {selectEditorPanelSize,useSQLEditorStore,@@ -36,7 +37,7 @@ import {useCurrentSQLEditorTab,useSQLEditorTabState,} from "@/react/stores/sqlEditor/tab";-import { useDatabaseV1Store, useDBSchemaV1Store } from "@/store";+import { useDBSchemaV1Store } from "@/store";import { isValidDatabaseName } from "@/types";import {extractDatabaseResourceName,@@ -100,7 +101,6 @@ export function Panels() {const showAIPaneAlongsidePanel = showAIPanel && isShowingCode;const { setSchema, updateViewState } = useViewStateNav();- const databaseV1Store = useDatabaseV1Store();const { execute } = useExecuteSQL();// AI plugin "run-statement" handler — mirrors Vue's@@ -115,9 +115,9 @@ export function Panels() {updateViewState({ view: "CODE" });await nextAnimationFrame();const connection = t.connection;- const database = await databaseV1Store.getOrFetchDatabaseByName(- connection.database- );+ const database = await useAppStore+ .getState()+ .getOrFetchDatabaseByName(connection.database);void execute({connection,statement,@@ -129,7 +129,7 @@ export function Panels() {return () => {off();};- }, [updateViewState, databaseV1Store, execute]);+ }, [updateViewState, execute]);const [databaseMetadata, setDatabaseMetadata] = useState<| Awaited<ReturnType<typeof dbSchemaStore.getOrFetchDatabaseMetadata>>diff --git a/frontend/src/react/components/sql-editor/RequestQueryButton.test.tsx b/frontend/src/react/components/sql-editor/RequestQueryButton.test.tsxindex 0c46efd31c..11ae59de4d 100644--- a/frontend/src/react/components/sql-editor/RequestQueryButton.test.tsx+++ b/frontend/src/react/components/sql-editor/RequestQueryButton.test.tsx@@ -10,11 +10,22 @@ import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";const mocks = vi.hoisted(() => ({useTranslation: vi.fn(() => ({ t: (key: string) => key })),useVueState: vi.fn<(getter: () => unknown) => unknown>(),- useProjectV1Store: vi.fn(),+ projectData: {+ name: "projects/proj1",+ allowJustInTimeAccess: false,+ allowRequestRole: true,+ } as {+ name: string;+ allowJustInTimeAccess: boolean;+ allowRequestRole: boolean;+ },roleList: [] as Array<{ name: string; permissions: string[] }>,useSQLEditorVueState: vi.fn(),useSubscriptionV1Store: vi.fn(),hasFeature: vi.fn(() => true),+ loadSubscription: vi.fn(),+ hasInstanceFeature: vi.fn(() => true),+ appHasFeature: vi.fn(() => true),parseStringToResource: vi.fn((s: string) => ({databaseFullName: s,databaseName: s,@@ -30,15 +41,21 @@ vi.mock("@/react/hooks/useVueState", () => ({}));vi.mock("@/store", () => ({- useProjectV1Store: mocks.useProjectV1Store,useSubscriptionV1Store: mocks.useSubscriptionV1Store,hasFeature: mocks.hasFeature,}));+vi.mock("@/react/hooks/useAppProject", () => ({+ useAppProject: () => mocks.projectData,+}));+vi.mock("@/react/stores/app", () => ({useAppStore: (selector: (state: unknown) => unknown) =>selector({roleList: mocks.roleList,+ loadSubscription: mocks.loadSubscription,+ hasInstanceFeature: mocks.hasInstanceFeature,+ hasFeature: mocks.appHasFeature,}),}));@@ -166,13 +183,11 @@ const makePermissionDeniedDetail = (overrides?: {const setupDefaultMocks = (allowJIT = false, allowRequestRole = true) => {mocks.useTranslation.mockReturnValue({ t: (key: string) => key });- mocks.useProjectV1Store.mockReturnValue({- getProjectByName: vi.fn(() => ({- name: "projects/proj1",- allowJustInTimeAccess: allowJIT,- allowRequestRole,- })),- });+ mocks.projectData = {+ name: "projects/proj1",+ allowJustInTimeAccess: allowJIT,+ allowRequestRole,+ };mocks.roleList = [{name: "roles/sqlEditorUser",@@ -188,10 +203,8 @@ const setupDefaultMocks = (allowJIT = false, allowRequestRole = true) => {},];mocks.useSQLEditorVueState.mockReturnValue({ project: "projects/proj1" });- mocks.useSubscriptionV1Store.mockReturnValue({- hasInstanceFeature: vi.fn(() => false),- });- mocks.hasFeature.mockReturnValue(true);+ mocks.hasInstanceFeature.mockReturnValue(false);+ mocks.appHasFeature.mockReturnValue(true);mocks.useVueState.mockImplementation((getter: () => unknown) => getter());};@@ -354,9 +367,7 @@ describe("RequestQueryButton", () => {test("non-JIT role request can default to custom role when feature is enabled", async () => {setupDefaultMocks(false, true);- mocks.useSubscriptionV1Store.mockReturnValue({- hasInstanceFeature: vi.fn(() => true),- });+ mocks.hasInstanceFeature.mockReturnValue(true);const { container, render, unmount } = renderIntoContainer(<RequestQueryButtontext={false}diff --git a/frontend/src/react/components/sql-editor/RequestQueryButton.tsx b/frontend/src/react/components/sql-editor/RequestQueryButton.tsxindex 723376ef66..838290cf7f 100644--- a/frontend/src/react/components/sql-editor/RequestQueryButton.tsx+++ b/frontend/src/react/components/sql-editor/RequestQueryButton.tsx@@ -1,15 +1,15 @@import { ShieldUser } from "lucide-react";-import { useMemo, useState } from "react";+import { useEffect, useMemo, useState } from "react";import { useTranslation } from "react-i18next";import { FeatureBadge } from "@/react/components/FeatureBadge";import { PermissionGuard } from "@/react/components/PermissionGuard";import { Button } from "@/react/components/ui/button";+import { useAppProject } from "@/react/hooks/useAppProject";import { usePiniaBridge } from "@/react/hooks/usePiniaBridge";import { cn } from "@/react/lib/utils";import { RequestRoleSheet } from "@/react/pages/settings/RequestRoleSheet";import { useAppStore } from "@/react/stores/app";import { useSQLEditorEditorState } from "@/react/stores/sqlEditor/editor";-import { hasFeature, useProjectV1Store, useSubscriptionV1Store } from "@/store";import type { DatabaseResource, Permission } from "@/types";import { PRESET_ROLES, PresetRoleType } from "@/types";import type { PermissionDeniedDetail } from "@/types/proto-es/v1/common_pb";@@ -77,15 +77,18 @@ export function RequestQueryButton({const [showPanel, setShowPanel] = useState(false);const [showJITDrawer, setShowJITDrawer] = useState(false);- const projectStore = useProjectV1Store();- const subscriptionStore = useSubscriptionV1Store();+ const loadSubscription = useAppStore((s) => s.loadSubscription);+ // The SQL editor route doesn't mount the dashboard shells that load the+ // app-store subscription, so load it here before reading feature gates+ // (mirrors ComponentPermissionGuard).+ useEffect(() => {+ void loadSubscription();+ }, [loadSubscription]);const projectName = useSQLEditorEditorState((s) => s.project);- const project = usePiniaBridge(() =>- projectStore.getProjectByName(projectName)- );- const hasCustomRoleFeature = usePiniaBridge(() =>- subscriptionStore.hasInstanceFeature(PlanFeature.FEATURE_CUSTOM_ROLES)+ const project = useAppProject(projectName);+ const hasCustomRoleFeature = useAppStore((s) =>+ s.hasInstanceFeature(PlanFeature.FEATURE_CUSTOM_ROLES));const defaultQueryRole = usePiniaBridge(() =>getDefaultQueryRole(@@ -112,7 +115,7 @@ export function RequestQueryButton({? PlanFeature.FEATURE_JIT: PlanFeature.FEATURE_REQUEST_ROLE_WORKFLOW;- const hasRequestFeature = hasFeature(requiredFeature);+ const hasRequestFeature = useAppStore((s) => s.hasFeature(requiredFeature));const missingResources = useMemo((): DatabaseResource[] => {const resources: DatabaseResource[] = [];diff --git a/frontend/src/react/components/sql-editor/ResultPanel/BatchQuerySelect.tsx b/frontend/src/react/components/sql-editor/ResultPanel/BatchQuerySelect.tsxindex 6cf310fde9..a145c0b458 100644--- a/frontend/src/react/components/sql-editor/ResultPanel/BatchQuerySelect.tsx+++ b/frontend/src/react/components/sql-editor/ResultPanel/BatchQuerySelect.tsx@@ -15,13 +15,14 @@ import { Button } from "@/react/components/ui/button";import { Tooltip } from "@/react/components/ui/tooltip";import { useSQLEditorQueryDataPolicy } from "@/react/hooks/useSQLEditorBridge";import { cn } from "@/react/lib/utils";+import { useAppStore } from "@/react/stores/app";import { useSQLEditorEditorState } from "@/react/stores/sqlEditor/editor";import {getSQLEditorTabsState,useCurrentSQLEditorTab,useSQLEditorTabState,} from "@/react/stores/sqlEditor/tab";-import { pushNotification, useDatabaseV1Store, useSQLStore } from "@/store";+import { pushNotification, useSQLStore } from "@/store";import { isValidDatabaseName } from "@/types";import { ExportFormat } from "@/types/proto-es/v1/common_pb";import type { Database } from "@/types/proto-es/v1/database_service_pb";@@ -82,7 +83,7 @@ export function BatchQuerySelect({onSelectedDatabaseChange,}: Props) {const { t } = useTranslation();- const databaseStore = useDatabaseV1Store();+ const getDatabaseByName = useAppStore((s) => s.getDatabaseByName);const sqlStore = useSQLStore();const currentTab = useCurrentSQLEditorTab();const project = useSQLEditorEditorState((s) => s.project);@@ -122,10 +123,10 @@ export function BatchQuerySelect({const items = useMemo<BatchQueryItem[]>(() => {return queriedDatabaseNames.map((name) => ({- database: databaseStore.getDatabaseByName(name),+ database: getDatabaseByName(name),context: contextsByDatabase.get(name),}));- }, [queriedDatabaseNames, contextsByDatabase, databaseStore]);+ }, [queriedDatabaseNames, contextsByDatabase, getDatabaseByName]);const showEmptySwitch = useMemo(() => items.length > 1 && items.some((item) => isEmptyQueryItem(item)),@@ -149,9 +150,8 @@ export function BatchQuerySelect({}, [filteredItems, selectedDatabase, onSelectedDatabaseChange]);const databaseList = useMemo(- () =>- queriedDatabaseNames.map((name) => databaseStore.getDatabaseByName(name)),- [queriedDatabaseNames, databaseStore]+ () => queriedDatabaseNames.map((name) => getDatabaseByName(name)),+ [queriedDatabaseNames, getDatabaseByName]);// Drop SQL from the export drawer when isDev() is active and any@@ -170,14 +170,14 @@ export function BatchQuerySelect({if (!isDev()) return all;if (selectedDatabaseNames.size === 0) return all;const allSupportSql = Array.from(selectedDatabaseNames).every((name) => {- const db = databaseStore.getDatabaseByName(name);+ const db = getDatabaseByName(name);if (!isValidDatabaseName(db.name)) return true; // skipped at export timereturn SQL_ENGINE_QUOTES.has(getInstanceResource(db).engine);});return allSupportSql? all: [ExportFormat.CSV, ExportFormat.JSON, ExportFormat.XLSX];- }, [selectedDatabaseNames, databaseStore]);+ }, [selectedDatabaseNames, getDatabaseByName]);const handleCloseSingleResultView = (item: BatchQueryItem) => {const contexts = currentTab?.databaseQueryContexts?.get(item.database.name);@@ -246,7 +246,7 @@ export function BatchQuerySelect({const groups: DownloadGroup[] = [];const limit = options.limit > 0 ? options.limit : Infinity;for (const databaseName of Array.from(selectedDatabaseNames)) {- const database = databaseStore.getDatabaseByName(databaseName);+ const database = getDatabaseByName(databaseName);// Skip stub-database returns with a WARN toast so the user// knows their selection became stale (tab torn down mid-export).if (!isValidDatabaseName(database.name)) {@@ -346,7 +346,7 @@ export function BatchQuerySelect({const tabsState = getSQLEditorTabsState();const tab = tabsState.tabsById.get(tabsState.currentTabId);for (const databaseName of Array.from(selectedDatabaseNames)) {- const database = databaseStore.getDatabaseByName(databaseName);+ const database = getDatabaseByName(databaseName);const context = head(tab?.databaseQueryContexts?.get(databaseName));if (!context) continue;try {diff --git a/frontend/src/react/components/sql-editor/ResultView/ResultView.tsx b/frontend/src/react/components/sql-editor/ResultView/ResultView.tsxindex a7afc084d1..25b03fe1bc 100644--- a/frontend/src/react/components/sql-editor/ResultView/ResultView.tsx+++ b/frontend/src/react/components/sql-editor/ResultView/ResultView.tsx@@ -20,14 +20,10 @@ import { Tooltip } from "@/react/components/ui/tooltip";import { isDisallowChangeDatabaseError } from "@/react/hooks/useExecuteSQL";import { useSQLEditorQueryDataPolicy } from "@/react/hooks/useSQLEditorBridge";import { cn } from "@/react/lib/utils";+import { useAppStore } from "@/react/stores/app";import { useSQLEditorEditorState } from "@/react/stores/sqlEditor/editor";import { getSQLEditorTabsState } from "@/react/stores/sqlEditor/tab";-import {- pushNotification,- useDatabaseV1Store,- useDBSchemaV1Store,- useSQLStore,-} from "@/store";+import { pushNotification, useDBSchemaV1Store, useSQLStore } from "@/store";import { usePolicyV1Store } from "@/store/modules/v1/policy";import type { SQLEditorQueryParams, SQLResultSetV1 } from "@/types";import { isValidDatabaseName } from "@/types";@@ -462,7 +458,6 @@ export function ResultView({function SyncDatabaseButton({ database }: { database: Database }) {const { t } = useTranslation();- const databaseStore = useDatabaseV1Store();const dbSchemaStore = useDBSchemaV1Store();const [syncing, setSyncing] = useState(false);@@ -476,7 +471,7 @@ function SyncDatabaseButton({ database }: { database: Database }) {setSyncing(true);const { databaseName } = extractDatabaseResourceName(database.name);try {- await databaseStore.syncDatabase(database.name);+ await useAppStore.getState().syncDatabase(database.name);await dbSchemaStore.getOrFetchDatabaseMetadata({database: database.name,skipCache: true,diff --git a/frontend/src/react/components/sql-editor/SQLEditorHomePage.tsx b/frontend/src/react/components/sql-editor/SQLEditorHomePage.tsxindex 3c7fd8f58b..9d10872d64 100644--- a/frontend/src/react/components/sql-editor/SQLEditorHomePage.tsx+++ b/frontend/src/react/components/sql-editor/SQLEditorHomePage.tsx@@ -19,10 +19,11 @@ import {LAYER_BACKDROP_CLASS,LAYER_SURFACE_CLASS,} from "@/react/components/ui/layer";-import { usePiniaBridge } from "@/react/hooks/usePiniaBridge";+import { useAppProject } from "@/react/hooks/useAppProject";import { applyPlanTitleToQuery } from "@/react/lib/plan/title";import { cn } from "@/react/lib/utils";import { useNavigate } from "@/react/router";+import { useAppStore } from "@/react/stores/app";import { useSQLEditorStore } from "@/react/stores/sqlEditor";import { useSQLEditorEditorState } from "@/react/stores/sqlEditor/editor";import {@@ -31,7 +32,6 @@ import {useIsDisconnected,} from "@/react/stores/sqlEditor/tab";import { PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL } from "@/router/dashboard/projectV1";-import { useDatabaseV1Store, useProjectV1Store } from "@/store";import { unknownProject } from "@/types";import {extractDatabaseResourceName,@@ -66,18 +66,16 @@ export function SQLEditorHomePage() {const setPendingInsertAtCaret = useSQLEditorStore((s) => s.setPendingInsertAtCaret);- const databaseStore = useDatabaseV1Store();- const projectStore = useProjectV1Store();const projectContextReady = useSQLEditorEditorState((s) => s.projectContextReady);const projectName = useSQLEditorEditorState((s) => s.project);- const project = usePiniaBridge(() => {- if (!projectName) return undefined;- const proj = projectStore.getProjectByName(projectName);- return proj.name === projectName ? proj : undefined;- });+ const resolvedProject = useAppProject(projectName);+ const project =+ projectName && resolvedProject.name === projectName+ ? resolvedProject+ : undefined;const tab = useCurrentSQLEditorTab();const isDisconnected = useIsDisconnected();@@ -98,11 +96,12 @@ export function SQLEditorHomePage() {const off = sqlEditorEvents.on("alter-schema",async ({ databaseName, schema, table }) => {- const database =- await databaseStore.getOrFetchDatabaseByName(databaseName);- const project = await projectStore- .getOrFetchProjectByName(database.project)- .catch(() => unknownProject());+ const database = await useAppStore+ .getState()+ .getOrFetchDatabaseByName(databaseName);+ const project =+ (await useAppStore.getState().fetchProject(database.project)) ??+ unknownProject();const exampleSQL = ["ALTER TABLE"];if (table) {if (schema) exampleSQL.push(`${schema}.${table}`);@@ -136,7 +135,7 @@ export function SQLEditorHomePage() {return () => {off();};- }, [databaseStore, projectStore, navigate, t]);+ }, [navigate, t]);// insert-at-caret: flip view to CODE, stage content into// pendingInsertAtCaret. The React `<SQLEditor>` reads the same Piniadiff --git a/frontend/src/react/components/sql-editor/SQLEditorLayout.tsx b/frontend/src/react/components/sql-editor/SQLEditorLayout.tsxindex 0cfa6a5374..9b14174442 100644--- a/frontend/src/react/components/sql-editor/SQLEditorLayout.tsx+++ b/frontend/src/react/components/sql-editor/SQLEditorLayout.tsx@@ -1,7 +1,8 @@import { useEffect, useState } from "react";import { BannersWrapper } from "@/react/components/BannersWrapper";+import { useAppStore } from "@/react/stores/app";import { router } from "@/router";-import { useEnvironmentV1Store, useSettingV1Store } from "@/store";+import { useSettingV1Store } from "@/store";import { Setting_SettingName } from "@/types/proto-es/v1/setting_service_pb";import { provideSheetContext } from "@/views/sql-editor/Sheet";import { RequestDrawerHost } from "./RequestDrawerHost";@@ -24,7 +25,7 @@ import { useSQLEditorAutoSave } from "./useSQLEditorAutoSave";*/export function SQLEditorLayout() {const settingStore = useSettingV1Store();- const environmentStore = useEnvironmentV1Store();+ const loadEnvironmentList = useAppStore((s) => s.loadEnvironmentList);// Boots the per-view watchers (selectedKeys ↔ active tab) the moment// the layout appears. The sheet-context singleton is module-level and// lazy — calling it here ensures the watchers are wired before any@@ -41,14 +42,14 @@ export function SQLEditorLayout() {settingStore.getOrFetchSettingByName(Setting_SettingName.WORKSPACE_PROFILE),- environmentStore.fetchEnvironments(),+ loadEnvironmentList(),]);if (!cancelled) setReady(true);})();return () => {cancelled = true;};- }, [settingStore, environmentStore]);+ }, [settingStore, loadEnvironmentList]);useSQLEditorAutoSave();diff --git a/frontend/src/react/components/sql-editor/SQLEditorRouteShell.tsx b/frontend/src/react/components/sql-editor/SQLEditorRouteShell.tsxindex de61755fa7..267ee0f213 100644--- a/frontend/src/react/components/sql-editor/SQLEditorRouteShell.tsx+++ b/frontend/src/react/components/sql-editor/SQLEditorRouteShell.tsx@@ -6,7 +6,7 @@ import {useComponentPermissionState,usePermissionDataReady,} from "@/react/components/ComponentPermissionGuard";-import { usePiniaBridge } from "@/react/hooks/usePiniaBridge";+import { useAppProject } from "@/react/hooks/useAppProject";import { useClampResultRowsLimitToPolicy } from "@/react/hooks/useSQLEditorBridge";import { useCurrentRoute, useNavigate } from "@/react/router";import { useAppStore } from "@/react/stores/app";@@ -28,12 +28,7 @@ import {SQL_EDITOR_PROJECT_MODULE,SQL_EDITOR_WORKSHEET_MODULE,} from "@/router/sqlEditor";-import {- pushNotification,- useActuatorV1Store,- useDatabaseV1Store,- useProjectV1Store,-} from "@/store";+import { pushNotification, useActuatorV1Store } from "@/store";import { migrateLegacyCache } from "@/store/modules/sqlEditor/legacy/migration";import {DEFAULT_SQL_EDITOR_TAB_MODE,@@ -107,8 +102,6 @@ export function SQLEditorRouteShell() {const navigate = useNavigate();const route = useCurrentRoute();const actuatorStore = useActuatorV1Store();- const projectStore = useProjectV1Store();- const databaseStore = useDatabaseV1Store();const setAsidePanelTab = useSQLEditorStore((s) => s.setAsidePanelTab);const maybeSwitchProject = useSQLEditorStore((s) => s.maybeSwitchProject);@@ -116,11 +109,10 @@ export function SQLEditorRouteShell() {(s) => s.projectContextReady);const projectNameState = useSQLEditorEditorState((s) => s.project);- const project = usePiniaBridge(() => {- const proj = projectStore.getProjectByName(projectNameState);- if (!isValidProjectName(proj.name)) return undefined;- return proj;- });+ const resolvedProject = useAppProject(projectNameState);+ const project = isValidProjectName(resolvedProject.name)+ ? resolvedProject+ : undefined;// Keep the persisted result-row limit within the project's// query-data policy maximum (re-clamps if the policy lowers the cap).@@ -153,9 +145,9 @@ export function SQLEditorRouteShell() {}, []);const fallbackToFirstProject = async () => {- const { projects } = await projectStore.fetchProjectList({+ const { projects } = await useAppStore.getState().searchProjects({pageSize: getDefaultPagination(),- filter: { excludeDefault: true },+ pageToken: "",});return (head(projects)?.name ?? actuatorStore.serverInfo?.defaultProject ?? ""@@ -243,8 +235,16 @@ export function SQLEditorRouteShell() {}const databaseName = `instances/${route.params.instance}/databases/${route.params.database}`;if (!isValidDatabaseName(databaseName)) return false;- const database = await databaseStore.getOrFetchDatabaseByName(databaseName);- await maybeSwitchProject(database.project);+ const database = await useAppStore+ .getState()+ .getOrFetchDatabaseByName(databaseName);+ // The app-store getter returns the `unknownDatabase` fallback (rather+ // than throwing) when the database can't be resolved — e.g. a bookmarked+ // URL to a deleted or no-longer-readable database. Bail so bootstrap+ // falls back to the default project instead of opening a bogus+ // `instances/-1/databases/-1` connection.+ if (!isValidDatabaseName(database.name)) return false;+ if (!(await maybeSwitchProject(database.project))) return false;const { instance } = extractDatabaseResourceName(database.name);const connection = { instance, database: database.name };getSQLEditorTabsState().addTab({@@ -345,25 +345,32 @@ export function SQLEditorRouteShell() {}}if (vals.dbName && isValidDatabaseName(vals.dbName)) {- const database = await databaseStore.getOrFetchDatabaseByName(- vals.dbName- );- if (vals.schema) query.schema = vals.schema;- if (vals.table) {- query.table = vals.table;- query.schema = vals.schema ?? "";+ const database = await useAppStore+ .getState()+ .getOrFetchDatabaseByName(vals.dbName);+ // The app-store getter returns the `unknownDatabase` fallback (rather+ // than throwing) when the database can't be resolved — deleted or+ // permission revoked. Skip navigation in that case so we don't rewrite+ // the URL to a bogus `projects/-1/instances/-1/databases/-1` route;+ // fall through to the instance / default sync instead.+ if (isValidDatabaseName(database.name)) {+ if (vals.schema) query.schema = vals.schema;+ if (vals.table) {+ query.table = vals.table;+ query.schema = vals.schema ?? "";+ }+ const dbResource = extractDatabaseResourceName(database.name);+ await navigate.replace({+ name: SQL_EDITOR_DATABASE_MODULE,+ params: {+ project: extractProjectResourceName(database.project),+ instance: extractInstanceResourceName(dbResource.instance),+ database: dbResource.databaseName,+ },+ query,+ });+ return;}- const dbResource = extractDatabaseResourceName(database.name);- await navigate.replace({- name: SQL_EDITOR_DATABASE_MODULE,- params: {- project: extractProjectResourceName(database.project),- instance: extractInstanceResourceName(dbResource.instance),- database: dbResource.databaseName,- },- query,- });- return;}if (vals.instanceName && isValidInstanceName(vals.instanceName)) {if (vals.table) {diff --git a/frontend/src/react/components/sql-editor/SchemaPane/HoverPanel/ColumnInfo.tsx b/frontend/src/react/components/sql-editor/SchemaPane/HoverPanel/ColumnInfo.tsxindex 0f66385a07..b177a11aba 100644--- a/frontend/src/react/components/sql-editor/SchemaPane/HoverPanel/ColumnInfo.tsx+++ b/frontend/src/react/components/sql-editor/SchemaPane/HoverPanel/ColumnInfo.tsx@@ -2,7 +2,8 @@ import { create } from "@bufbuild/protobuf";import { Check, X } from "lucide-react";import { useTranslation } from "react-i18next";import { getColumnDefaultValuePlaceholder } from "@/react/components/SchemaEditorLite/core/columnDefaultValue";-import { useDatabaseV1Store, useDBSchemaV1Store } from "@/store";+import { useAppDatabase } from "@/react/hooks/useAppDatabase";+import { useDBSchemaV1Store } from "@/store";import { Engine } from "@/types/proto-es/v1/common_pb";import { ColumnMetadataSchema } from "@/types/proto-es/v1/database_service_pb";import { getInstanceResource } from "@/utils";@@ -23,16 +24,14 @@ type Props = {export function ColumnInfo({ database, schema, table, column }: Props) {const { t } = useTranslation();const dbSchema = useDBSchemaV1Store();- const databaseStore = useDatabaseV1Store();+ const databaseEntity = useAppDatabase(database);const columnMetadata =dbSchema.getTableMetadata({ database, schema, table }).columns.find((col) => col.name === column) ??create(ColumnMetadataSchema, {});- const instanceEngine = getInstanceResource(- databaseStore.getDatabaseByName(database)- ).engine;+ const instanceEngine = getInstanceResource(databaseEntity).engine;const characterSet =instanceEngine === Engine.POSTGRES ||diff --git a/frontend/src/react/components/sql-editor/SchemaPane/HoverPanel/TableInfo.tsx b/frontend/src/react/components/sql-editor/SchemaPane/HoverPanel/TableInfo.tsxindex 6c4a3f7721..4e97e3a976 100644--- a/frontend/src/react/components/sql-editor/SchemaPane/HoverPanel/TableInfo.tsx+++ b/frontend/src/react/components/sql-editor/SchemaPane/HoverPanel/TableInfo.tsx@@ -1,6 +1,7 @@import { useTranslation } from "react-i18next";import { EngineIcon } from "@/react/components/EngineIcon";-import { useDatabaseV1Store, useDBSchemaV1Store } from "@/store";+import { useAppDatabase } from "@/react/hooks/useAppDatabase";+import { useDBSchemaV1Store } from "@/store";import { Engine } from "@/types/proto-es/v1/common_pb";import { bytesToString, getInstanceResource } from "@/utils";import { engineNameV1 } from "@/utils/v1/instance";@@ -21,12 +22,10 @@ type Props = {export function TableInfo({ database, schema, table }: Props) {const { t } = useTranslation();const dbSchema = useDBSchemaV1Store();- const databaseStore = useDatabaseV1Store();+ const databaseEntity = useAppDatabase(database);const tableMetadata = dbSchema.getTableMetadata({ database, schema, table });- const instanceEngine = getInstanceResource(- databaseStore.getDatabaseByName(database)- ).engine;+ const instanceEngine = getInstanceResource(databaseEntity).engine;const indexSize =instanceEngine === Engine.CLICKHOUSE || instanceEngine === Engine.SNOWFLAKEdiff --git a/frontend/src/react/components/sql-editor/SchemaPane/SchemaPane.test.tsx b/frontend/src/react/components/sql-editor/SchemaPane/SchemaPane.test.tsxindex e31d558008..bb2b5fbba1 100644--- a/frontend/src/react/components/sql-editor/SchemaPane/SchemaPane.test.tsx+++ b/frontend/src/react/components/sql-editor/SchemaPane/SchemaPane.test.tsx@@ -48,10 +48,30 @@ vi.mock("@/store", () => ({syncDatabase: vi.fn(),getTableMetadata: vi.fn(),}),- useDatabaseV1Store: () => ({ getDatabaseByName: vi.fn() }),pushNotification: vi.fn(),}));+vi.mock("@/react/hooks/useAppDatabase", () => ({+ useAppDatabase: (name: string) => ({ name }),+}));++vi.mock("@/react/stores/app", () => {+ const state = {+ getDatabaseByName: (name: string) => ({ name }),+ getOrFetchDatabaseByName: vi.fn(async (name: string) => ({ name })),+ batchGetOrFetchDatabases: vi.fn(async () => []),+ syncDatabase: vi.fn(),+ fetchDatabases: vi.fn(async () => ({ databases: [], nextPageToken: "" })),+ databasesByName: {} as Record<string, unknown>,+ };+ return {+ useAppStore: Object.assign(+ (selector: (s: unknown) => unknown) => selector(state),+ { getState: () => state }+ ),+ };+});+vi.mock("@/react/hooks/useSQLEditorBridge", () => ({// Returns plain values now — `database` is the unwrapped object.useConnectionOfCurrentSQLEditorTab: () => ({diff --git a/frontend/src/react/components/sql-editor/SchemaPane/SyncSchemaButton.test.tsx b/frontend/src/react/components/sql-editor/SchemaPane/SyncSchemaButton.test.tsxindex 86eea43f17..b49a5b90cd 100644--- a/frontend/src/react/components/sql-editor/SchemaPane/SyncSchemaButton.test.tsx+++ b/frontend/src/react/components/sql-editor/SchemaPane/SyncSchemaButton.test.tsx@@ -65,12 +65,15 @@ vi.mock("@/react/components/ui/button", () => ({}));vi.mock("@/store", () => ({- useDatabaseV1Store: () => ({ syncDatabase: mocks.syncDatabase }),useDBSchemaV1Store: () => ({getOrFetchDatabaseMetadata: mocks.getOrFetchDatabaseMetadata,}),}));+vi.mock("@/react/stores/app", () => ({+ useAppStore: { getState: () => ({ syncDatabase: mocks.syncDatabase }) },+}));+vi.mock("@/react/hooks/useSQLEditorBridge", () => ({// Returns plain values now — `database` is the unwrapped object.useConnectionOfCurrentSQLEditorTab: () => ({diff --git a/frontend/src/react/components/sql-editor/SchemaPane/SyncSchemaButton.tsx b/frontend/src/react/components/sql-editor/SchemaPane/SyncSchemaButton.tsxindex 78a683277f..a26d599713 100644--- a/frontend/src/react/components/sql-editor/SchemaPane/SyncSchemaButton.tsx+++ b/frontend/src/react/components/sql-editor/SchemaPane/SyncSchemaButton.tsx@@ -6,7 +6,8 @@ import { Button } from "@/react/components/ui/button";import { Tooltip } from "@/react/components/ui/tooltip";import { useConnectionOfCurrentSQLEditorTab } from "@/react/hooks/useSQLEditorBridge";import { cn } from "@/react/lib/utils";-import { useDatabaseV1Store, useDBSchemaV1Store } from "@/store";+import { useAppStore } from "@/react/stores/app";+import { useDBSchemaV1Store } from "@/store";import { getDateForPbTimestampProtoEs, isValidDatabaseName } from "@/types";/**@@ -23,7 +24,6 @@ import { getDateForPbTimestampProtoEs, isValidDatabaseName } from "@/types";export function SyncSchemaButton({ className }: { className?: string }) {const { t } = useTranslation();const { database } = useConnectionOfCurrentSQLEditorTab();- const databaseStore = useDatabaseV1Store();const dbSchemaStore = useDBSchemaV1Store();const [isSyncing, setIsSyncing] = useState(false);@@ -33,7 +33,7 @@ export function SyncSchemaButton({ className }: { className?: string }) {if (disabled) return;setIsSyncing(true);try {- await databaseStore.syncDatabase(database.name, true);+ await useAppStore.getState().syncDatabase(database.name, true);await dbSchemaStore.getOrFetchDatabaseMetadata({database: database.name,skipCache: true,diff --git a/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/DatabaseNode.tsx b/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/DatabaseNode.tsxindex b3a34c9a90..a7d051fe4a 100644--- a/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/DatabaseNode.tsx+++ b/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/DatabaseNode.tsx@@ -1,5 +1,5 @@import { EngineIcon } from "@/react/components/EngineIcon";-import { useDatabaseV1Store } from "@/store";+import { useAppDatabase } from "@/react/hooks/useAppDatabase";import { extractDatabaseResourceName, getInstanceResource } from "@/utils";import type { TreeNode } from "../schemaTree";import { CommonNode } from "./CommonNode";@@ -14,10 +14,9 @@ type Props = {* engine icon + database display name (highlight-aware).*/export function DatabaseNode({ node, keyword }: Props) {- const databaseStore = useDatabaseV1Store();const target = (node as TreeNode<"database">).meta.target;- const database = databaseStore.getDatabaseByName(target.database);+ const database = useAppDatabase(target.database);const databaseName = extractDatabaseResourceName(database.name).databaseName;const instance = getInstanceResource(database);diff --git a/frontend/src/react/components/sql-editor/SchemaPane/actions.test.tsx b/frontend/src/react/components/sql-editor/SchemaPane/actions.test.tsxindex 791f3f1dba..380a4663af 100644--- a/frontend/src/react/components/sql-editor/SchemaPane/actions.test.tsx+++ b/frontend/src/react/components/sql-editor/SchemaPane/actions.test.tsx@@ -52,10 +52,17 @@ vi.mock("@/react/i18n", () => ({vi.mock("@/store", () => ({pushNotification: vi.fn(),- useDatabaseV1Store: () => ({ getDatabaseByName: mocks.getDatabaseByName }),useDBSchemaV1Store: () => ({ getTableMetadata: mocks.getTableMetadata }),}));+vi.mock("@/react/stores/app", () => ({+ useAppStore: Object.assign(+ (selector: (state: unknown) => unknown) =>+ selector({ getDatabaseByName: mocks.getDatabaseByName }),+ { getState: () => ({ getDatabaseByName: mocks.getDatabaseByName }) }+ ),+}));+vi.mock("@/react/stores/sqlEditor/tab", () => ({// actions.tsx only reaches the store imperatively via getSQLEditorTabsState// when a menu handler runs; building the menu items (what these testsdiff --git a/frontend/src/react/components/sql-editor/SchemaPane/actions.tsx b/frontend/src/react/components/sql-editor/SchemaPane/actions.tsxindex 7dde5c2055..6dface349d 100644--- a/frontend/src/react/components/sql-editor/SchemaPane/actions.tsx+++ b/frontend/src/react/components/sql-editor/SchemaPane/actions.tsx@@ -18,14 +18,11 @@ import { useTranslation } from "react-i18next";import { formatSQL } from "@/react/components/monaco/sqlFormatter";import { useExecuteSQL } from "@/react/hooks/useExecuteSQL";import { keyWithPosition } from "@/react/lib/keyWithPosition";+import { useAppStore } from "@/react/stores/app";import { getSQLEditorTabsState } from "@/react/stores/sqlEditor/tab";import { router } from "@/router";import { SQL_EDITOR_DATABASE_MODULE } from "@/router/sqlEditor";-import {- pushNotification,- useDatabaseV1Store,- useDBSchemaV1Store,-} from "@/store";+import { pushNotification, useDBSchemaV1Store } from "@/store";import {DEFAULT_SQL_EDITOR_TAB_MODE,dialectOfEngineV1,@@ -98,7 +95,7 @@ export type AvailableAction = {* Vue reactive computed.*/const engineForDatabase = (database: string): Engine => {- const db = useDatabaseV1Store().getDatabaseByName(database);+ const db = useAppStore.getState().getDatabaseByName(database);return getInstanceResource(db).engine;};@@ -197,7 +194,7 @@ const runQuery = async (};export function useSchemaPaneActions() {- const databaseStore = useDatabaseV1Store();+ const getDatabaseByName = useAppStore((s) => s.getDatabaseByName);const { execute } = useExecuteSQL();const openNewTab = useCallback(@@ -260,7 +257,7 @@ export function useSchemaPaneActions() {if (!tableOrViewName) return;const { database, schema } = target;- const db = databaseStore.getDatabaseByName(database);+ const db = getDatabaseByName(database);const engine = getInstanceResource(db).engine;const query = await formatCode(@@ -275,7 +272,7 @@ export function useSchemaPaneActions() {updateCurrentTabViewState({ view: "CODE" });await runQuery(execute, db, schema, tableOrViewName, query);},- [databaseStore, execute]+ [getDatabaseByName, execute]);const viewDetail = useCallback(@@ -392,7 +389,7 @@ export function useSchemaPaneContextMenu(deps: SchemaMenuDeps): SchemaMenuItem[] {const { t } = useTranslation();- const databaseStore = useDatabaseV1Store();+ const getDatabaseByName = useAppStore((s) => s.getDatabaseByName);const dbSchema = useDBSchemaV1Store();const { selectAllFromTableOrView, viewDetail, openNewTab } =useSchemaPaneActions();@@ -414,7 +411,7 @@ export function useSchemaPaneContextMenu(const { database, schema } = target as NodeTarget<"schema">;if (!database) return [];- const db = databaseStore.getDatabaseByName(database);+ const db = getDatabaseByName(database);const items: SchemaMenuItem[] = [];if (type === "schema") {@@ -662,7 +659,7 @@ export function useSchemaPaneContextMenu(}, [node,deps,- databaseStore,+ getDatabaseByName,dbSchema,notify,openNewTab,diff --git a/frontend/src/react/components/sql-editor/StandardPanel/EditorMain.tsx b/frontend/src/react/components/sql-editor/StandardPanel/EditorMain.tsxindex b1a447649e..168eaf976a 100644--- a/frontend/src/react/components/sql-editor/StandardPanel/EditorMain.tsx+++ b/frontend/src/react/components/sql-editor/StandardPanel/EditorMain.tsx@@ -2,12 +2,12 @@ import { useCallback, useEffect } from "react";import { ReadonlyModeNotSupported } from "@/react/components/sql-editor/ReadonlyModeNotSupported";import { useExecuteSQL } from "@/react/hooks/useExecuteSQL";import { useConnectionOfCurrentSQLEditorTab } from "@/react/hooks/useSQLEditorBridge";+import { useAppStore } from "@/react/stores/app";import {getSQLEditorTabsState,useIsDisconnected,useSQLEditorTabState,} from "@/react/stores/sqlEditor/tab";-import { useDatabaseV1Store } from "@/store";import type { SQLEditorQueryParams } from "@/types";import { Engine } from "@/types/proto-es/v1/common_pb";import { getInstanceResource, instanceV1HasReadonlyMode } from "@/utils";@@ -36,7 +36,6 @@ interface EditorMainProps {* the cross-framework boundary stays clean — see Stage 17 design.*/export function EditorMain({ onChangeConnection }: EditorMainProps) {- const databaseStore = useDatabaseV1Store();const { instance } = useConnectionOfCurrentSQLEditorTab();const tabId = useSQLEditorTabState((s) => s.tabsById.get(s.currentTabId)?.id);@@ -82,9 +81,9 @@ export function EditorMain({ onChangeConnection }: EditorMainProps) {const off = sqlEditorEvents.on("execute-sql",async ({ connection, statement, batchQueryContext }) => {- const database = await databaseStore.getOrFetchDatabaseByName(- connection.database- );+ const database = await useAppStore+ .getState()+ .getOrFetchDatabaseByName(connection.database);const newTab = getSQLEditorTabsState().addTab({ connection, statement, batchQueryContext },/* beside */ true@@ -103,7 +102,7 @@ export function EditorMain({ onChangeConnection }: EditorMainProps) {return () => {off();};- }, [databaseStore, execute]);+ }, [execute]);if (!isDisconnected && !allowReadonlyMode) {// Connected to an instance without a read-only data source —diff --git a/frontend/src/react/components/sql-editor/TabItem/AdminLabel.tsx b/frontend/src/react/components/sql-editor/TabItem/AdminLabel.tsxindex f475e50dcc..4e5fd2c22e 100644--- a/frontend/src/react/components/sql-editor/TabItem/AdminLabel.tsx+++ b/frontend/src/react/components/sql-editor/TabItem/AdminLabel.tsx@@ -1,7 +1,5 @@import { ChevronRight } from "lucide-react";-import { useEffect } from "react";-import { usePiniaBridge } from "@/react/hooks/usePiniaBridge";-import { useDatabaseV1Store } from "@/store";+import { useAppDatabase } from "@/react/hooks/useAppDatabase";import { UNKNOWN_ID } from "@/types/const";import type { SQLEditorTab } from "@/types/sqlEditor/tab";import { isValidDatabaseName } from "@/types/v1/database";@@ -24,18 +22,9 @@ type Props = {*/export function AdminLabel({ tab }: Props) {const dbName = tab.connection.database;- const databaseStore = useDatabaseV1Store();-- // Mirror Vue's `useDatabaseV1ByName`: fire a fetch on mount and every time- // the database resource name changes.- useEffect(() => {- if (!dbName) return;- void databaseStore.getOrFetchDatabaseByName(dbName);- }, [databaseStore, dbName]);-- const database = usePiniaBridge(() =>- databaseStore.getDatabaseByName(dbName)- );+ // Mirrors Vue's `useDatabaseV1ByName`: self-fetches on mount / name change+ // and reactively re-reads the cached database.+ const database = useAppDatabase(dbName);const instance = getInstanceResource(database);const environment = getDatabaseEnvironment(database);const { databaseName } = extractDatabaseResourceName(database.name);diff --git a/frontend/src/react/components/sql-editor/TerminalPanel/TerminalPanel.tsx b/frontend/src/react/components/sql-editor/TerminalPanel/TerminalPanel.tsxindex a10db41a98..750369590e 100644--- a/frontend/src/react/components/sql-editor/TerminalPanel/TerminalPanel.tsx+++ b/frontend/src/react/components/sql-editor/TerminalPanel/TerminalPanel.tsx@@ -5,6 +5,7 @@ import type { IStandaloneCodeEditor } from "@/react/components/monaco/types";import { ConnectionHolder } from "@/react/components/sql-editor/ConnectionHolder";import { EditorAction } from "@/react/components/sql-editor/EditorAction";import { ResultView } from "@/react/components/sql-editor/ResultView";+import { useAppStore } from "@/react/stores/app";import { useSQLEditorStore } from "@/react/stores/sqlEditor";import {getSQLEditorTabsState,@@ -12,7 +13,6 @@ import {useSQLEditorTabState,} from "@/react/stores/sqlEditor/tab";import { getWebTerminalQuerySession } from "@/react/stores/sqlEditor/webTerminal-service";-import { useDatabaseV1Store } from "@/store";import type { SQLEditorQueryParams, WebTerminalQueryItemV1 } from "@/types";import { CompactSQLEditor } from "./CompactSQLEditor";import { useHistory } from "./useHistory";@@ -37,7 +37,10 @@ import { useHistory } from "./useHistory";*/export function TerminalPanel() {const { t } = useTranslation();- const databaseStore = useDatabaseV1Store();+ const batchGetOrFetchDatabases = useAppStore(+ (s) => s.batchGetOrFetchDatabases+ );+ const getDatabaseByName = useAppStore((s) => s.getDatabaseByName);const updateWebTerminalQueryItem = useSQLEditorStore((s) => s.updateWebTerminalQueryItem);@@ -95,10 +98,10 @@ export function TerminalPanel() {// Pre-fetch any database referenced by an existing query item so the// ResultView can render `database.environment` etc. synchronously.useEffect(() => {- void databaseStore.batchGetOrFetchDatabases(+ void batchGetOrFetchDatabases(queryList.map((q) => q?.params?.connection.database ?? ""));- }, [queryList, databaseStore]);+ }, [queryList, batchGetOrFetchDatabases]);const currentQuery = queryList[queryList.length - 1];const isEditableQueryItem = (item: WebTerminalQueryItemV1) =>@@ -211,9 +214,7 @@ export function TerminalPanel() {{queryList.map((query) => {const editable = isEditableQueryItem(query);const database = query.params?.connection.database- ? databaseStore.getDatabaseByName(- query.params.connection.database- )+ ? getDatabaseByName(query.params.connection.database): undefined;return (<div key={query.id} className="relative">diff --git a/frontend/src/react/components/sql-editor/Welcome.test.tsx b/frontend/src/react/components/sql-editor/Welcome.test.tsxindex c5dc80580b..4b7f920ed4 100644--- a/frontend/src/react/components/sql-editor/Welcome.test.tsx+++ b/frontend/src/react/components/sql-editor/Welcome.test.tsx@@ -18,6 +18,7 @@ const mocks = vi.hoisted(() => ({>(),useVueState: vi.fn<(getter: () => unknown) => unknown>(),routerPush: vi.fn(),+ projectData: { name: "projects/test" } as { name: string },}));vi.mock("react-i18next", () => ({@@ -36,6 +37,10 @@ vi.mock("@/react/hooks/useVueState", () => ({useVueState: mocks.useVueState,}));+vi.mock("@/react/hooks/useAppProject", () => ({+ useAppProject: () => mocks.projectData,+}));+vi.mock("@/router", () => ({router: { push: mocks.routerPush },}));diff --git a/frontend/src/react/components/sql-editor/Welcome.tsx b/frontend/src/react/components/sql-editor/Welcome.tsxindex 80e4ac9d71..903448345d 100644--- a/frontend/src/react/components/sql-editor/Welcome.tsx+++ b/frontend/src/react/components/sql-editor/Welcome.tsx@@ -2,11 +2,10 @@ import { LayersIcon, LinkIcon } from "lucide-react";import { useTranslation } from "react-i18next";import { BytebaseLogo } from "@/react/components/BytebaseLogo";import { usePermissionCheck } from "@/react/components/PermissionGuard";-import { usePiniaBridge } from "@/react/hooks/usePiniaBridge";+import { useAppProject } from "@/react/hooks/useAppProject";import { useSQLEditorEditorState } from "@/react/stores/sqlEditor/editor";import { router } from "@/router";import { INSTANCE_ROUTE_DASHBOARD } from "@/router/dashboard/workspaceRoutes";-import { useProjectV1Store } from "@/store";import { WelcomeButton } from "./WelcomeButton";export type WelcomeProps = {@@ -20,14 +19,10 @@ export type WelcomeProps = {export function Welcome({ onChangeConnection }: WelcomeProps) {const { t } = useTranslation();- const projectV1Store = useProjectV1Store();const projectName = useSQLEditorEditorState((s) => s.project);- const project = usePiniaBridge(() => {- return projectName- ? projectV1Store.getProjectByName(projectName)- : undefined;- });+ const resolvedProject = useAppProject(projectName);+ const project = projectName ? resolvedProject : undefined;const [showCreateInstanceButton] = usePermissionCheck(["bb.instances.create",diff --git a/frontend/src/react/hooks/useAppDatabase.ts b/frontend/src/react/hooks/useAppDatabase.tsnew file mode 100644index 0000000000..fddb818884--- /dev/null+++ b/frontend/src/react/hooks/useAppDatabase.ts@@ -0,0 +1,32 @@+import { useEffect, useMemo } from "react";+import { useAppStore } from "@/react/stores/app";+import type { Database } from "@/types/proto-es/v1/database_service_pb";+import { isValidDatabaseName } from "@/types/v1/database";++/**+ * Reactively reads a database from the Zustand app store, self-fetching when+ * the current route hasn't preloaded it (the SQL editor route does not mount+ * the dashboard shells that hydrate the app store). Returns the+ * Pinia-compatible `unknownDatabase` fallback so callers can read+ * `.project` / `.instanceResource` without null checks — mirroring the legacy+ * `useDatabaseV1Store().getDatabaseByName`.+ */+export const useAppDatabase = (name: string): Database => {+ const getDatabaseByName = useAppStore((s) => s.getDatabaseByName);+ const getOrFetchDatabaseByName = useAppStore(+ (s) => s.getOrFetchDatabaseByName+ );+ // Subscribe to the specific cache entry so the value recomputes once the+ // database resolves. Selecting the raw entry keeps the snapshot stable for+ // `useSyncExternalStore`.+ const cached = useAppStore((s) => s.databasesByName[name]);+ useEffect(() => {+ if (isValidDatabaseName(name)) {+ void getOrFetchDatabaseByName(name);+ }+ }, [getOrFetchDatabaseByName, name]);+ return useMemo(+ () => getDatabaseByName(name),+ [getDatabaseByName, name, cached]+ );+};diff --git a/frontend/src/react/hooks/useAppProject.ts b/frontend/src/react/hooks/useAppProject.tsnew file mode 100644index 0000000000..f9acd48f0f--- /dev/null+++ b/frontend/src/react/hooks/useAppProject.ts@@ -0,0 +1,30 @@+import { useEffect, useMemo } from "react";+import { isValidProjectName } from "@/react/lib/resourceName";+import { useAppStore } from "@/react/stores/app";+import type { Project } from "@/types/proto-es/v1/project_service_pb";++/**+ * Reactively reads a project from the Zustand app store, self-fetching+ * when the current route hasn't preloaded it (the SQL editor route does+ * not mount the dashboard shells that hydrate the app store). Returns the+ * Pinia-compatible fallback (`unknownProject` / default project) so+ * callers can read `.title` etc. without null checks — mirroring the+ * legacy `useProjectV1Store().getProjectByName`.+ */+export const useAppProject = (name: string): Project => {+ const getProjectByName = useAppStore((s) => s.getProjectByName);+ const fetchProject = useAppStore((s) => s.fetchProject);+ // Subscribe to the specific cache entry so the value recomputes once+ // the project resolves. Selecting the raw entry (not the fallback)+ // keeps the snapshot stable for `useSyncExternalStore`.+ const cached = useAppStore((s) => s.projectsByName[name]);+ useEffect(() => {+ if (isValidProjectName(name)) {+ void fetchProject(name);+ }+ }, [fetchProject, name]);+ return useMemo(+ () => getProjectByName(name),+ [getProjectByName, name, cached]+ );+};diff --git a/frontend/src/react/hooks/useExecuteSQL.ts b/frontend/src/react/hooks/useExecuteSQL.tsindex 17c934a374..21f004283d 100644--- a/frontend/src/react/hooks/useExecuteSQL.ts+++ b/frontend/src/react/hooks/useExecuteSQL.ts@@ -4,19 +4,14 @@ import { cloneDeep, isEmpty } from "lodash-es";import { useCallback, useRef } from "react";import { useTranslation } from "react-i18next";import { v4 as uuidv4 } from "uuid";+import { useAppStore } from "@/react/stores/app";import { useSQLEditorStore as useSQLEditorReactStore } from "@/react/stores/sqlEditor";import { getSQLEditorEditorState } from "@/react/stores/sqlEditor/editor";import {getDatabaseQueryContext,getSQLEditorTabsState,} from "@/react/stores/sqlEditor/tab";-import {- hasFeature,- pushNotification,- useDatabaseV1Store,- useDBGroupStore,- useSQLStore,-} from "@/store";+import { hasFeature, pushNotification, useSQLStore } from "@/store";import type {BBNotificationStyle,QueryContextStatus,@@ -51,9 +46,6 @@ const QUERY_INTERVAL_LIMIT = 1000;export const useExecuteSQL = () => {const { t } = useTranslation();const lastQueryTimeRef = useRef<number | undefined>(undefined);- const dbGroupStore = useDBGroupStore();- const dbStore = useDatabaseV1Store();-const notify = (type: BBNotificationStyle,title: string,@@ -200,14 +192,10 @@ export const useExecuteSQL = () => {if (hasFeature(PlanFeature.FEATURE_DATABASE_GROUPS)) {for (const databaseGroupName of databaseGroups) {try {- const databaseGroup = await dbGroupStore.getOrFetchDBGroupByName(- databaseGroupName,- {- skipCache: false,- silent: true,- view: DatabaseGroupView.FULL,- }- );+ const databaseGroup = await useAppStore+ .getState()+ .fetchDBGroup(databaseGroupName, DatabaseGroupView.FULL);+ if (!databaseGroup) continue;for (const matchedDatabase of databaseGroup.matchedDatabases) {if (!isValidDatabaseName(matchedDatabase.name)) {continue;@@ -238,7 +226,9 @@ export const useExecuteSQL = () => {}const isBatch = batchQueryDatabaseSet.size > 1;- await dbStore.batchGetOrFetchDatabases([...batchQueryDatabaseSet.keys()]);+ await useAppStore+ .getState()+ .batchGetOrFetchDatabases([...batchQueryDatabaseSet.keys()]);for (const databaseName of batchQueryDatabaseSet.values()) {// Re-read the latest tab snapshot inside the loop so each@@ -262,7 +252,7 @@ export const useExecuteSQL = () => {}}- const database = dbStore.getDatabaseByName(databaseName);+ const database = useAppStore.getState().getDatabaseByName(databaseName);const resolvedDataSourceId =isBatch && loopTab.batchQueryContext.dataSourceType? ((await getValidDataSourceByPolicy(@@ -288,7 +278,7 @@ export const useExecuteSQL = () => {loopState.updateTab(loopTab.id, { databaseQueryContexts: nextMap });}},- [dbStore, dbGroupStore, preflight]+ [preflight]);const runQuery = useCallback(diff --git a/frontend/src/react/hooks/useSQLEditorBridge.ts b/frontend/src/react/hooks/useSQLEditorBridge.tsindex c8e006c4d8..64441f89fe 100644--- a/frontend/src/react/hooks/useSQLEditorBridge.ts+++ b/frontend/src/react/hooks/useSQLEditorBridge.ts@@ -1,16 +1,16 @@import { useEffect } from "react";import { effectScope, unref } from "vue";+import { useAppStore } from "@/react/stores/app";import {getSQLEditorEditorState,useSQLEditorEditorState,} from "@/react/stores/sqlEditor/editor";import { useSQLEditorTabsStore } from "@/react/stores/sqlEditor/tab";-import { featureToRef, useProjectV1Store } from "@/store";+import { featureToRef } from "@/store";import { useDatabaseV1ByName } from "@/store/modules/v1/database";-import { useEnvironmentV1Store } from "@/store/modules/v1/environment";import { useQueryDataPolicy } from "@/store/modules/v1/policy";import type { SQLEditorConnection } from "@/types";-import { isValidDatabaseName } from "@/types";+import { isValidDatabaseName, isValidProjectName } from "@/types";import type { Database } from "@/types/proto-es/v1/database_service_pb";import type { InstanceResource } from "@/types/proto-es/v1/instance_service_pb";import type { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";@@ -157,11 +157,20 @@ export const useClampResultRowsLimitToPolicy = (project: string): void => {* project?". Reads project IAM via Pinia.*/export const useSQLEditorAllowAdmin = (project: string): boolean => {- const projectStore = useProjectV1Store();- return useVueState(() => {- const proj = projectStore.getProjectByName(project);- return hasProjectPermissionV2(proj, "bb.sql.admin");- });+ const getProjectByName = useAppStore((s) => s.getProjectByName);+ const fetchProject = useAppStore((s) => s.fetchProject);+ // Re-subscribe the IAM watch once the project resolves in the app store+ // (a non-Vue signal the watch can't track on its own).+ const cachedProject = useAppStore((s) => s.projectsByName[project]);+ useEffect(() => {+ if (isValidProjectName(project)) {+ void fetchProject(project);+ }+ }, [fetchProject, project]);+ return useVueState(+ () => hasProjectPermissionV2(getProjectByName(project), "bb.sql.admin"),+ { deps: [project, cachedProject] }+ );};/**@@ -208,9 +217,9 @@ export const useSQLEditorConnection = (if (isValidDatabaseName(db.name)) {return getDatabaseEnvironment(db);}- return useEnvironmentV1Store().getEnvironmentByName(- instance.environment ?? ""- );+ return useAppStore+ .getState()+ .getEnvironmentByName(instance.environment ?? "");},{ deps: [connection.database] });diff --git a/frontend/src/react/stores/app/database.ts b/frontend/src/react/stores/app/database.tsindex 730e7fcee8..58920402ef 100644--- a/frontend/src/react/stores/app/database.ts+++ b/frontend/src/react/stores/app/database.ts@@ -1,24 +1,75 @@import { create as createProto } from "@bufbuild/protobuf";+import { createContextValues } from "@connectrpc/connect";+import { uniq } from "lodash-es";import { databaseServiceClientConnect } from "@/connect";+import { silentContextKey } from "@/connect/context-key";+import { UNKNOWN_ID } from "@/types/const";+import { State } from "@/types/proto-es/v1/common_pb";import {BatchGetDatabasesRequestSchema,type Database,+ DatabaseSchema$,GetDatabaseRequestSchema,ListDatabasesRequestSchema,+ SyncDatabaseRequestSchema,} from "@/types/proto-es/v1/database_service_pb";import { isValidDatabaseName } from "@/types/v1/database";+import {+ formatEnvironmentName,+ unknownEnvironment,+} from "@/types/v1/environment";+import { unknownInstanceResource } from "@/types/v1/instance";import type { AppSliceCreator, DatabaseSlice } from "./types";-import { toError } from "./utils";+import { buildDatabaseFilter, toError } from "./utils";++const UNKNOWN_PROJECT_NAME = `projects/${UNKNOWN_ID}`;++// Inlined to keep the app store's load graph free of the Pinia `@/store`+// barrel that `@/utils/v1/database` pulls in.+function instanceResourceNameFromDatabase(databaseName: string): string {+ const match = databaseName.match(/(?:^|\/)instances\/([^/]+)\/databases\//);+ return match ? `instances/${match[1]}` : "";+}++// Mirrors the legacy Pinia `unknownDatabase`, inlined so this module does not+// import `@/types/v1/project` (which pulls the Pinia actuator store).+function createUnknownDatabase(): Database {+ const instanceResource = unknownInstanceResource();+ return createProto(DatabaseSchema$, {+ name: `${instanceResource.name}/databases/${UNKNOWN_ID}`,+ state: State.ACTIVE,+ project: UNKNOWN_PROJECT_NAME,+ effectiveEnvironment: formatEnvironmentName(unknownEnvironment().id),+ instanceResource,+ });+}export const createDatabaseSlice: AppSliceCreator<DatabaseSlice> = (set,get-) => ({- databasesByName: {},- databaseRequests: {},- databaseErrorsByName: {},+) => {+ // Mirrors the legacy Pinia `batchComposeDatabase`: pre-caches the owning+ // projects and guarantees `instanceResource` is populated (with a fallback)+ // so consumers can read engine / instance off any database.+ const composeDatabases = async (+ databases: Database[]+ ): Promise<Database[]> => {+ await get().batchFetchProjects(databases.map((db) => db.project));+ for (const database of databases) {+ if (!database.instanceResource) {+ database.instanceResource = {+ ...unknownInstanceResource(),+ name: instanceResourceNameFromDatabase(database.name),+ };+ }+ }+ return databases;+ };- fetchDatabase: async (name) => {+ const fetchByName = async (+ name: string,+ silent: boolean+ ): Promise<Database | undefined> => {if (!isValidDatabaseName(name)) return undefined;const existing = get().databasesByName[name];if (existing) return existing;@@ -26,14 +77,17 @@ export const createDatabaseSlice: AppSliceCreator<DatabaseSlice> = (if (pending) return pending;const request = databaseServiceClientConnect- .getDatabase(createProto(GetDatabaseRequestSchema, { name }))- .then((database: Database) => {+ .getDatabase(createProto(GetDatabaseRequestSchema, { name }), {+ contextValues: createContextValues().set(silentContextKey, silent),+ })+ .then(async (database: Database) => {+ const [composed] = await composeDatabases([database]);set((state) => {const { [name]: _, ...databaseRequests } = state.databaseRequests;return {databasesByName: {...state.databasesByName,- [database.name]: database,+ [composed.name]: composed,},databaseErrorsByName: {...state.databaseErrorsByName,@@ -42,7 +96,7 @@ export const createDatabaseSlice: AppSliceCreator<DatabaseSlice> = (databaseRequests,};});- return database;+ return composed;}).catch((error) => {set((state) => {@@ -64,43 +118,113 @@ export const createDatabaseSlice: AppSliceCreator<DatabaseSlice> = (},}));return request;- },+ };- batchFetchDatabases: async (names) => {- if (!names.length) return [];- const response = await databaseServiceClientConnect.batchGetDatabases(- createProto(BatchGetDatabasesRequestSchema, { parent: "-", names })- );- set((state) => {- const next = { ...state.databasesByName };- for (const db of response.databases) {- next[db.name] = db;- }- return { databasesByName: next };- });- return response.databases;- },+ return {+ databasesByName: {},+ databaseRequests: {},+ databaseErrorsByName: {},- fetchDatabases: async ({ parent, pageSize, pageToken, filter, orderBy }) => {- const response = await databaseServiceClientConnect.listDatabases(- createProto(ListDatabasesRequestSchema, {- parent,- pageSize,- pageToken: pageToken ?? "",- filter: filter ?? "",- orderBy: orderBy ?? "",- })- );- set((state) => {- const next = { ...state.databasesByName };- for (const db of response.databases) {- next[db.name] = db;+ getDatabaseByName: (name) =>+ get().databasesByName[name] ?? createUnknownDatabase(),++ fetchDatabase: (name) => fetchByName(name, false),++ getOrFetchDatabaseByName: async (name, silent = true) =>+ (await fetchByName(name, silent)) ?? createUnknownDatabase(),++ batchFetchDatabases: async (names) => {+ const validNames = uniq(names).filter(isValidDatabaseName);+ if (!validNames.length) return [];+ const response = await databaseServiceClientConnect.batchGetDatabases(+ createProto(BatchGetDatabasesRequestSchema, {+ parent: "-",+ names: validNames,+ })+ );+ const composed = await composeDatabases(response.databases);+ set((state) => {+ const next = { ...state.databasesByName };+ for (const db of composed) {+ next[db.name] = db;+ }+ return { databasesByName: next };+ });+ return composed;+ },++ batchGetOrFetchDatabases: async (names) => {+ const validNames = uniq(names).filter(isValidDatabaseName);+ const pending = validNames.filter((name) => {+ const cached = get().databasesByName[name];+ return !(cached && isValidDatabaseName(cached.name));+ });+ await get().batchFetchDatabases(pending);+ return validNames.map((name) => get().getDatabaseByName(name));+ },++ fetchDatabases: async ({+ parent,+ pageSize,+ pageToken,+ filter,+ orderBy,+ silent,+ }) => {+ const filterString =+ typeof filter === "string"+ ? filter+ : filter+ ? buildDatabaseFilter(filter)+ : "";+ const showDeleted =+ typeof filter === "object" ? filter?.showDeleted : undefined;+ const response = await databaseServiceClientConnect.listDatabases(+ createProto(ListDatabasesRequestSchema, {+ parent,+ pageSize,+ pageToken: pageToken ?? "",+ filter: filterString,+ orderBy: orderBy ?? "",+ showDeleted,+ }),+ {+ contextValues: createContextValues().set(+ silentContextKey,+ silent ?? false+ ),+ }+ );+ const composed = await composeDatabases(response.databases);+ set((state) => {+ const next = { ...state.databasesByName };+ for (const db of composed) {+ next[db.name] = db;+ }+ return { databasesByName: next };+ });+ return {+ databases: composed,+ nextPageToken: response.nextPageToken,+ };+ },++ syncDatabase: async (name, refresh = false) => {+ await databaseServiceClientConnect.syncDatabase(+ createProto(SyncDatabaseRequestSchema, { name })+ );+ if (refresh) {+ const database = await databaseServiceClientConnect.getDatabase(+ createProto(GetDatabaseRequestSchema, { name })+ );+ const [composed] = await composeDatabases([database]);+ set((state) => ({+ databasesByName: {+ ...state.databasesByName,+ [composed.name]: composed,+ },+ }));}- return { databasesByName: next };- });- return {- databases: response.databases,- nextPageToken: response.nextPageToken,- };- },-});+ },+ };+};diff --git a/frontend/src/react/stores/app/dbGroup.ts b/frontend/src/react/stores/app/dbGroup.tsindex f5cc539ac4..6d2abbc293 100644--- a/frontend/src/react/stores/app/dbGroup.ts+++ b/frontend/src/react/stores/app/dbGroup.ts@@ -3,6 +3,7 @@ import { databaseGroupServiceClientConnect } from "@/connect";import { isValidDatabaseGroupName } from "@/types/dbGroup";import {type DatabaseGroup,+ DatabaseGroupView,GetDatabaseGroupRequestSchema,ListDatabaseGroupsRequestSchema,} from "@/types/proto-es/v1/database_group_service_pb";@@ -14,18 +15,29 @@ export const createDBGroupSlice: AppSliceCreator<DBGroupSlice> = (get) => ({dbGroupsByName: {},+ dbGroupViewByName: {},dbGroupRequests: {},dbGroupErrorsByName: {},- fetchDBGroup: async (name) => {+ fetchDBGroup: async (name, view = DatabaseGroupView.BASIC) => {if (!isValidDatabaseGroupName(name)) return undefined;const existing = get().dbGroupsByName[name];- if (existing) return existing;+ // 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 }))+ .getDatabaseGroup(+ createProto(GetDatabaseGroupRequestSchema, { name, view })+ ).then((group: DatabaseGroup) => {set((state) => {const { [name]: _, ...dbGroupRequests } = state.dbGroupRequests;@@ -34,6 +46,10 @@ export const createDBGroupSlice: AppSliceCreator<DBGroupSlice> = (...state.dbGroupsByName,[group.name]: group,},+ dbGroupViewByName: {+ ...state.dbGroupViewByName,+ [group.name]: view,+ },dbGroupErrorsByName: {...state.dbGroupErrorsByName,[name]: undefined,@@ -71,10 +87,12 @@ export const createDBGroupSlice: AppSliceCreator<DBGroupSlice> = ();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;}- return { dbGroupsByName: next };+ return { dbGroupsByName: next, dbGroupViewByName: nextView };});return response.databaseGroups;},diff --git a/frontend/src/react/stores/app/project.ts b/frontend/src/react/stores/app/project.tsindex 15653bcbd2..ae80e59ef9 100644--- a/frontend/src/react/stores/app/project.ts+++ b/frontend/src/react/stores/app/project.ts@@ -15,16 +15,30 @@ import { buildProjectFilter, defaultProjectName, toError } from "./utils";const UNKNOWN_PROJECT_NAME = `projects/${UNKNOWN_ID}`;+// The default project's feature gates. Inlined here (rather than reusing+// the `@/types/v1/project` helpers) so the app store's load graph stays+// free of the Pinia actuator store those helpers pull in.+const PROJECT_DEFAULTS = {+ state: State.ACTIVE,+ enforceIssueTitle: true,+ enforceSqlReview: true,+ requireIssueApproval: true,+ requirePlanCheckNoError: true,+ allowRequestRole: true,+} as const;+function createDefaultProject(name: string) {return createProto(ProjectSchema, {name,title: "Default project",- state: State.ACTIVE,- enforceIssueTitle: true,- enforceSqlReview: true,- requireIssueApproval: true,- requirePlanCheckNoError: true,- allowRequestRole: true,+ ...PROJECT_DEFAULTS,+ });+}++function createUnknownProject() {+ return createProto(ProjectSchema, {+ name: UNKNOWN_PROJECT_NAME,+ ...PROJECT_DEFAULTS,});}@@ -36,6 +50,18 @@ export const createProjectSlice: AppSliceCreator<ProjectSlice> = (projectRequests: {},projectErrorsByName: {},+ // Mirrors the Pinia `useProjectV1Store().getProjectByName`: always+ // returns a non-null Project, synthesizing the default-project or+ // unknown-project placeholder when the name is not in the cache.+ getProjectByName: (name) => {+ if (name === UNKNOWN_PROJECT_NAME) return createUnknownProject();+ const defaultProject = defaultProjectName(get);+ if (name && name === defaultProject) {+ return get().projectsByName[name] ?? createDefaultProject(name);+ }+ return get().projectsByName[name] ?? createUnknownProject();+ },+fetchProject: async (name) => {const defaultProject = defaultProjectName(get);if (name && name === defaultProject) {diff --git a/frontend/src/react/stores/app/types.ts b/frontend/src/react/stores/app/types.tsindex 102ad87547..a4c5bfd09d 100644--- a/frontend/src/react/stores/app/types.ts+++ b/frontend/src/react/stores/app/types.ts@@ -1,11 +1,15 @@import type { StateCreator } from "zustand";+import type { DatabaseFilter } from "@/store/modules/v1/database";import type { AppFeatures } from "@/types/appProfile";import type { Permission } from "@/types/iam/permission";import type { NotificationCreate } from "@/types/notification";import type { AccessGrant } from "@/types/proto-es/v1/access_grant_service_pb";import type { ActuatorInfo } from "@/types/proto-es/v1/actuator_service_pb";import type { State } from "@/types/proto-es/v1/common_pb";-import type { DatabaseGroup } from "@/types/proto-es/v1/database_group_service_pb";+import type {+ DatabaseGroup,+ DatabaseGroupView,+} from "@/types/proto-es/v1/database_group_service_pb";import type {Changelog,ChangelogView,@@ -141,6 +145,7 @@ export type WorkspaceSlice = {) => Promise<WorkspaceProfileSetting | undefined>;loadEnvironmentList: (force?: boolean) => Promise<Environment[]>;refreshEnvironmentList: () => Promise<Environment[]>;+ getEnvironmentByName: (name: string, fallback?: boolean) => Environment;loadSubscription: () => Promise<Subscription | undefined>;refreshSubscription: () => Promise<Subscription | undefined>;uploadLicense: (license: string) => Promise<Subscription | undefined>;@@ -194,6 +199,7 @@ export type ProjectSlice = {projectsByName: Record<string, Project>;projectRequests: Record<string, Promise<Project | undefined>>;projectErrorsByName: Record<string, Error | undefined>;+ getProjectByName: (name: string) => Project;fetchProject: (name: string) => Promise<Project | undefined>;batchFetchProjects: (names: string[]) => Promise<Project[]>;searchProjects: (params: ProjectListParams) => Promise<{@@ -214,27 +220,48 @@ export type DatabaseListParams = {parent: string;pageSize: number;pageToken?: string;- filter?: string;+ // Either a pre-built CEL filter string or a structured `DatabaseFilter`+ // (built via `buildDatabaseFilter`), matching the legacy Pinia store.+ filter?: string | DatabaseFilter;orderBy?: string;+ silent?: boolean;};export type DatabaseSlice = {databasesByName: Record<string, Database>;databaseRequests: Record<string, Promise<Database | undefined>>;databaseErrorsByName: Record<string, Error | undefined>;+ // Synchronous read with the `unknownDatabase` fallback (never null), so+ // callers can read `.project` / `.instanceResource` without null checks.+ getDatabaseByName: (name: string) => Database;fetchDatabase: (name: string) => Promise<Database | undefined>;+ // Async read that resolves to the cached/fetched database, or the+ // `unknownDatabase` fallback for invalid names / fetch failures.+ getOrFetchDatabaseByName: (+ name: string,+ silent?: boolean+ ) => Promise<Database>;batchFetchDatabases: (names: string[]) => Promise<Database[]>;+ batchGetOrFetchDatabases: (names: string[]) => Promise<Database[]>;fetchDatabases: (params: DatabaseListParams) => Promise<{databases: Database[];nextPageToken: string;}>;+ syncDatabase: (name: string, refresh?: boolean) => Promise<void>;};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) => Promise<DatabaseGroup | undefined>;+ fetchDBGroup: (+ name: string,+ view?: DatabaseGroupView+ ) => Promise<DatabaseGroup | undefined>;listDBGroupsForProject: (project: string) => Promise<DatabaseGroup[]>;};diff --git a/frontend/src/react/stores/app/utils.ts b/frontend/src/react/stores/app/utils.tsindex 5872e894db..b9677f2f86 100644--- a/frontend/src/react/stores/app/utils.ts+++ b/frontend/src/react/stores/app/utils.ts@@ -2,12 +2,20 @@ import { Code, ConnectError } from "@connectrpc/connect";import {getProjectName,getUserName,+ isValidProjectName,projectNamePrefix,userNamePrefix,} from "@/react/lib/resourceName";+import type { DatabaseFilter } from "@/store/modules/v1/database";+import { Engine } from "@/types/proto-es/v1/common_pb";import type { Binding } from "@/types/proto-es/v1/iam_policy_pb";import type { Project } from "@/types/proto-es/v1/project_service_pb";import type { User } from "@/types/proto-es/v1/user_service_pb";+import {+ isValidEnvironmentName,+ unknownEnvironment,+} from "@/types/v1/environment";+import { isValidInstanceName } from "@/types/v1/instance";import type { AppStoreState } from "./types";export const MAX_RECENT_PROJECT = 5;@@ -44,6 +52,82 @@ export function buildProjectFilter(query: string | undefined) {return filters.join(" && ");}+// Converts label selectors like "{key}:{v1},{v2}" into API filter clauses+// (`labels.{key} == "v"` or `labels.{key} in [...]`). Ported verbatim from+// the legacy Pinia database store.+function getLabelFilter(labels: string[]): string[] {+ const labelMap = new Map<string, string[]>();+ for (const label of labels) {+ const sections = label.split(":");+ if (sections.length !== 2) {+ continue;+ }+ const [key, rawValue] = sections;+ const values = rawValue.split(",");+ if (!labelMap.has(key)) {+ labelMap.set(key, []);+ }+ labelMap.get(key)?.push(...values);+ }+ return [...labelMap.entries()].reduce((result, [key, values]) => {+ switch (values.length) {+ case 0:+ return result;+ case 1:+ result.push(`labels.${key} == "${values[0]}"`);+ return result;+ default:+ result.push(+ `labels.${key} in [${values.map((v) => `"${v}"`).join(", ")}]`+ );+ return result;+ }+ }, [] as string[]);+}++// Builds the CEL filter string for `listDatabases` from a structured+// `DatabaseFilter`. Mirrors the legacy Pinia `getListDatabaseFilter` so the+// app store lists databases identically to the old store.+export function buildDatabaseFilter(filter: DatabaseFilter): string {+ const params: string[] = [];+ if (isValidProjectName(filter.project)) {+ params.push(`project == "${filter.project}"`);+ }+ if (isValidInstanceName(filter.instance)) {+ params.push(`instance == "${filter.instance}"`);+ }+ if (filter.environment === unknownEnvironment().name) {+ params.push(`environment == ""`);+ } else if (isValidEnvironmentName(filter.environment)) {+ params.push(`environment == "${filter.environment}"`);+ }+ if (filter.excludeUnassigned) {+ params.push(`exclude_unassigned == true`);+ }+ if (filter.engines && filter.engines.length > 0) {+ params.push(+ `engine in [${filter.engines.map((e) => `"${Engine[e]}"`).join(", ")}]`+ );+ } else if (filter.excludeEngines && filter.excludeEngines.length > 0) {+ params.push(+ `!(engine in [${filter.excludeEngines+ .map((e) => `"${Engine[e]}"`)+ .join(", ")}])`+ );+ }+ const keyword = filter.query?.trim()?.toLowerCase();+ if (keyword) {+ params.push(`name.contains("${keyword}")`);+ }+ if (filter.labels) {+ params.push(...getLabelFilter(filter.labels));+ }+ if (filter.table) {+ params.push(`table.contains("${filter.table}")`);+ }+ return params.join(" && ");+}+function bindingMemberToNames(member: string): string[] {if (member === "allUsers" || member === "user:allUsers") {return [ALL_USERS_NAME];diff --git a/frontend/src/react/stores/app/workspace.ts b/frontend/src/react/stores/app/workspace.tsindex 18f1afa987..d632260c56 100644--- a/frontend/src/react/stores/app/workspace.ts+++ b/frontend/src/react/stores/app/workspace.ts@@ -13,6 +13,7 @@ import {settingNamePrefix,workspaceNamePrefix,} from "@/react/lib/resourceName";+import { getEnvironmentId } from "@/store/modules/v1/common";import {broadcastWorkspaceSwitch,workspaceSwitchChannel,@@ -45,6 +46,12 @@ import {getTimeForPbTimestampProtoEs,} from "@/types/timestamp";import type { Environment } from "@/types/v1/environment";+import {+ isValidEnvironmentName,+ NULL_ENVIRONMENT_NAME,+ nullEnvironment,+ unknownEnvironment,+} from "@/types/v1/environment";import { formatAbsoluteDateTime } from "@/utils/datetime";import type { AppSliceCreator, WorkspaceSlice } from "./types";@@ -289,6 +296,25 @@ export const createWorkspaceSlice: AppSliceCreator<WorkspaceSlice> = (refreshEnvironmentList: async () => get().loadEnvironmentList(true),+ // Mirrors the Pinia `useEnvironmentV1Store().getEnvironmentByName`: maps+ // a resource name to its environment, falling back to a synthesized+ // entry (id-as-title) for unknown names when `fallback` is set.+ getEnvironmentByName: (name, fallback = true) => {+ if (name === NULL_ENVIRONMENT_NAME) {+ return nullEnvironment();+ }+ const id = getEnvironmentId(name);+ if (!id) {+ return unknownEnvironment();+ }+ const environment =+ get().environmentList.find((e) => e.id === id) ?? unknownEnvironment();+ if (!isValidEnvironmentName(environment.name) && fallback) {+ return { ...environment, id, name, title: id };+ }+ return environment;+ },+loadSubscription: async () => {const existing = get().subscription;if (existing) return existing;diff --git a/frontend/src/react/stores/sqlEditor/tree-utils.ts b/frontend/src/react/stores/sqlEditor/tree-utils.tsindex 0183c44d6a..a1204af885 100644--- a/frontend/src/react/stores/sqlEditor/tree-utils.ts+++ b/frontend/src/react/stores/sqlEditor/tree-utils.ts@@ -1,8 +1,6 @@import { orderBy } from "lodash-es";-import {- useEnvironmentV1Store,- useInstanceResourceByName,-} from "@/store/modules/v1";+import { useAppStore } from "@/react/stores/app";+import { useInstanceResourceByName } from "@/store/modules/v1";import type {SQLEditorTreeFactor as Factor,SQLEditorTreeNodeTarget as NodeTarget,@@ -99,9 +97,9 @@ const mapGroupNode = (parent: TreeNode | undefined) => {if (factor === "environment") {- const environment = useEnvironmentV1Store().getEnvironmentByName(- value || ""- );+ const environment = useAppStore+ .getState()+ .getEnvironmentByName(value || "");return mapTreeNodeByType("environment", environment, parent);}if (factor === "instance") {diff --git a/frontend/src/react/stores/sqlEditor/webTerminal-service.ts b/frontend/src/react/stores/sqlEditor/webTerminal-service.tsindex 60e136bcbb..46aef94de6 100644--- a/frontend/src/react/stores/sqlEditor/webTerminal-service.ts+++ b/frontend/src/react/stores/sqlEditor/webTerminal-service.ts@@ -9,7 +9,8 @@ import {type CancelableTimer,createCancelableTimer,} from "@/react/lib/cancelableTimer";-import { pushNotification, useDatabaseV1Store } from "@/store";+import { useAppStore } from "@/react/stores/app";+import { pushNotification } from "@/store";import type {SQLEditorQueryParams,SQLEditorTab,@@ -329,7 +330,9 @@ export const mockAffectedV1Rows0 = (): QueryResult => {const mapRequest = (params: SQLEditorQueryParams): AdminExecuteRequest => {const { connection, statement, explain } = params;- const database = useDatabaseV1Store().getDatabaseByName(connection.database);+ const database = useAppStore+ .getState()+ .getDatabaseByName(connection.database);const request = create(AdminExecuteRequestSchema, {name: database.name,statement: explain ? `EXPLAIN ${statement}` : statement,diff --git a/frontend/src/react/stores/sqlEditor/worksheet.test.ts b/frontend/src/react/stores/sqlEditor/worksheet.test.tsindex 43bbb9049d..02bb36c900 100644--- a/frontend/src/react/stores/sqlEditor/worksheet.test.ts+++ b/frontend/src/react/stores/sqlEditor/worksheet.test.ts@@ -74,6 +74,7 @@ const piniaMocks = vi.hoisted(() => ({patchWorksheet: vi.fn(),upsertWorksheetOrganizer: vi.fn(),createWorksheet: vi.fn(),+ fetchProject: vi.fn(),},}));diff --git a/frontend/src/react/stores/sqlEditor/worksheet.ts b/frontend/src/react/stores/sqlEditor/worksheet.tsindex 67b9fa947d..6b30964318 100644--- a/frontend/src/react/stores/sqlEditor/worksheet.ts+++ b/frontend/src/react/stores/sqlEditor/worksheet.ts@@ -15,10 +15,9 @@ import { getSQLEditorTabsState } from "./tab";import type { SQLEditorSliceCreator, WorksheetSaveSlice } from "./types";// Pinia store barrel transitively re-imports `@/react/stores/sqlEditor`,-// so we still pull the Pinia bits in at call time via the helpers below+// so we still pull the Pinia bits in at call time via the helper below// to avoid a TDZ cycle. The new Zustand editor / tab stores are local// to this module's directory and safe to import statically.-const importStores = () => import("@/store");const importProjectIamPolicyStore = () =>import("@/store/modules/v1/projectIamPolicy");@@ -39,10 +38,8 @@ export const createWorksheetSaveSlice: SQLEditorSliceCreator<},maybeSwitchProject: async (projectName) => {- const { useProjectV1Store } = await importStores();const { useProjectIamPolicyStore } = await importProjectIamPolicyStore();const editorStore = getSQLEditorEditorState();- const projectStore = useProjectV1Store();const projectIamPolicyStore = useProjectIamPolicyStore();editorStore.setProjectContextReady(false);@@ -50,7 +47,10 @@ export const createWorksheetSaveSlice: SQLEditorSliceCreator<if (!isValidProjectName(projectName)) {return;}- const project = await projectStore.getOrFetchProjectByName(projectName);+ const project = await useAppStore.getState().fetchProject(projectName);+ if (!project) {+ return;+ }// Fetch IAM policy to ensure permission checks work correctly.await projectIamPolicyStore.getOrFetchProjectIamPolicy(project.name);editorStore.setProject(project.name);