Skip to content

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

fix(frontend): JIT Request Data Access picker resolves all project databases via server search (BYT-9801) (#20726)

zchpeter01a080e38179
diff --git a/frontend/src/react/components/DatabaseSelect.test.tsx b/frontend/src/react/components/DatabaseSelect.test.tsx
new file mode 100644
index 0000000000..731ee56387
--- /dev/null
+++ b/frontend/src/react/components/DatabaseSelect.test.tsx
@@ -0,0 +1,378 @@
+import { act, type ReactElement } from "react";
+import { createRoot } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
+import type { Database } from "@/types/proto-es/v1/database_service_pb";
+
+(
+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+// Captured props from the mocked Combobox — inspected/driven by each test.
+type ComboProps = {
+ multiple?: boolean;
+ value: string | string[];
+ onChange: (v: string | string[]) => void;
+ onSearch?: (q: string) => void;
+ options: { value: string; label: string }[];
+ renderValue?: (opt: { value: string; label: string }) => unknown;
+};
+const combo: { props?: ComboProps } = {};
+
+const mocks = vi.hoisted(() => {
+ // Simulated global database cache. The store upserts every fetched database
+ // here, so getDatabaseByName resolves on-page and previously-seen names; a
+ // miss returns an "unknown" placeholder ({ name: "" }) → synthesized label.
+ const cache = new Map<
+ string,
+ { name: string; effectiveEnvironment?: string }
+ >();
+ return {
+ cache,
+ fetchDatabases: vi.fn(),
+ workspaceResourceName: vi.fn(() => "workspaces/-"),
+ getDatabaseByName: vi.fn((name: string) => cache.get(name) ?? { name: "" }),
+ };
+});
+
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({ t: (k: string) => k }),
+}));
+
+vi.mock("@/react/stores/app", () => {
+ const state = () => ({
+ fetchDatabases: mocks.fetchDatabases,
+ workspaceResourceName: mocks.workspaceResourceName,
+ getDatabaseByName: mocks.getDatabaseByName,
+ });
+ return {
+ useAppStore: Object.assign(
+ (selector: (s: ReturnType<typeof state>) => unknown) => selector(state()),
+ { getState: state }
+ ),
+ };
+});
+
+// Capture-only Combobox mock (repo convention). Renders nothing interactive.
+vi.mock("@/react/components/ui/combobox", () => ({
+ Combobox: (props: ComboProps) => {
+ combo.props = props;
+ return null;
+ },
+}));
+
+// EngineIcon / EnvironmentLabel are only used inside option.render — never
+// invoked by these tests — but stub them so the module imports cleanly.
+vi.mock("@/react/components/EngineIcon", () => ({ EngineIcon: () => null }));
+vi.mock("@/react/components/EnvironmentLabel", () => ({
+ EnvironmentLabel: () => null,
+}));
+
+vi.mock("@/utils", () => ({
+ extractDatabaseResourceName: (name: string) => {
+ const parts = name.split("/");
+ return { databaseName: parts[3] ?? name, instance: parts[1] ?? "" };
+ },
+ getDatabaseEnvironment: () => ({ name: "environments/prod" }),
+ getDefaultPagination: () => 50,
+ getInstanceResource: () => ({ engine: 0, title: "inst" }),
+}));
+
+let DatabaseSelect: typeof import("./DatabaseSelect").DatabaseSelect;
+
+const db = (
+ name: string,
+ effectiveEnvironment = "environments/prod"
+): Database => ({ name, effectiveEnvironment }) as unknown as Database;
+
+const render = (element: ReactElement) => {
+ const container = document.createElement("div");
+ const root = createRoot(container);
+ document.body.appendChild(container);
+ act(() => root.render(element));
+ return {
+ container,
+ rerender: (el: ReactElement) => act(() => root.render(el)),
+ unmount: () => {
+ act(() => root.unmount());
+ container.remove();
+ },
+ };
+};
+
+// Let the mount-time fetch's .then() microtask resolve and re-render.
+const flush = async () => {
+ await act(async () => {
+ await Promise.resolve();
+ await Promise.resolve();
+ });
+};
+
+beforeEach(async () => {
+ vi.clearAllMocks();
+ combo.props = undefined;
+ mocks.fetchDatabases.mockResolvedValue({ databases: [], nextPageToken: "" });
+ mocks.cache.clear();
+ ({ DatabaseSelect } = await import("./DatabaseSelect"));
+});
+
+afterEach(() => {
+ document.body.innerHTML = "";
+});
+
+describe("DatabaseSelect — multi mode", () => {
+ test("passes multiple=true and returns string[] from onChange", async () => {
+ const dbA = db("instances/i/databases/a");
+ const dbB = db("instances/i/databases/b");
+ mocks.cache.set(dbA.name, dbA);
+ mocks.cache.set(dbB.name, dbB);
+ mocks.fetchDatabases.mockResolvedValue({
+ databases: [dbA, dbB],
+ nextPageToken: "",
+ });
+ const onChange = vi.fn();
+ const { unmount } = render(
+ <DatabaseSelect
+ multiple
+ value={[]}
+ onChange={onChange}
+ projectName="projects/p"
+ />
+ );
+ await flush();
+
+ expect(combo.props?.multiple).toBe(true);
+ act(() => combo.props?.onChange(["instances/i/databases/a"]));
+ expect(onChange).toHaveBeenCalledWith(
+ ["instances/i/databases/a"],
+ expect.arrayContaining([
+ expect.objectContaining({ name: "instances/i/databases/a" }),
+ ])
+ );
+ unmount();
+ });
+
+ // GREEN GUARD: the initial load fetches the first page with an empty query.
+ test("mount fetches the first page with an empty query (guard)", async () => {
+ const { unmount } = render(
+ <DatabaseSelect
+ multiple
+ value={[]}
+ onChange={vi.fn()}
+ projectName="projects/p"
+ />
+ );
+ await flush();
+ expect(mocks.fetchDatabases).toHaveBeenCalledWith(
+ expect.objectContaining({
+ parent: "projects/p",
+ filter: expect.objectContaining({ query: "" }),
+ })
+ );
+ unmount();
+ });
+
+ // GREEN GUARD (passes pre- and post-fix). Not the bug repro — DatabaseSelect
+ // already wires onSearch; the missing onSearch was in the DRAWER's local
+ // MultiDatabaseSelect. The true red bug-repro lives in the drawer test.
+ test("multi mode wires a server-querying onSearch (guard)", async () => {
+ const { unmount } = render(
+ <DatabaseSelect
+ multiple
+ value={[]}
+ onChange={vi.fn()}
+ projectName="projects/p"
+ />
+ );
+ await flush();
+
+ expect(combo.props?.onSearch).toBeTypeOf("function");
+ act(() => combo.props?.onSearch?.("orders"));
+ expect(mocks.fetchDatabases).toHaveBeenCalledWith(
+ expect.objectContaining({
+ parent: "projects/p",
+ filter: expect.objectContaining({ query: "orders" }),
+ })
+ );
+ unmount();
+ });
+
+ test("a selected value absent from current results still renders as an option (chip preservation)", async () => {
+ // Server never returns the pre-selected db (it's past page 1).
+ mocks.fetchDatabases.mockResolvedValue({
+ databases: [db("instances/i/databases/other")],
+ nextPageToken: "",
+ });
+ const { unmount } = render(
+ <DatabaseSelect
+ multiple
+ value={["instances/i/databases/mydb"]}
+ onChange={vi.fn()}
+ projectName="projects/p"
+ />
+ );
+ await flush();
+
+ const opt = combo.props?.options.find(
+ (o) => o.value === "instances/i/databases/mydb"
+ );
+ expect(opt).toBeDefined();
+ expect(opt?.label).toBe("mydb"); // derived from resource name
+ unmount();
+ });
+
+ test("dedup: a value in BOTH results and selection yields exactly one option", async () => {
+ mocks.fetchDatabases.mockResolvedValue({
+ databases: [db("instances/i/databases/dup")],
+ nextPageToken: "",
+ });
+ const { unmount } = render(
+ <DatabaseSelect
+ multiple
+ value={["instances/i/databases/dup"]}
+ onChange={vi.fn()}
+ projectName="projects/p"
+ />
+ );
+ await flush();
+
+ const matches = combo.props?.options.filter(
+ (o) => o.value === "instances/i/databases/dup"
+ );
+ expect(matches).toHaveLength(1);
+ unmount();
+ });
+
+ test("out-of-order fetch responses do not clobber the latest results (race guard)", async () => {
+ let resolveMount: (v: unknown) => void = () => {};
+ let resolveSearch: (v: unknown) => void = () => {};
+ mocks.fetchDatabases
+ .mockImplementationOnce(
+ () =>
+ new Promise((r) => {
+ resolveMount = r;
+ })
+ )
+ .mockImplementationOnce(
+ () =>
+ new Promise((r) => {
+ resolveSearch = r;
+ })
+ );
+
+ const { unmount } = render(
+ <DatabaseSelect
+ multiple
+ value={[]}
+ onChange={vi.fn()}
+ projectName="projects/p"
+ />
+ );
+ // Mount fetch (call 1) is in flight; fire a search (call 2).
+ act(() => combo.props?.onSearch?.("q"));
+
+ // Resolve the NEWER search first, then the OLDER mount fetch.
+ await act(async () => {
+ resolveSearch({
+ databases: [db("instances/i/databases/newer")],
+ nextPageToken: "",
+ });
+ await Promise.resolve();
+ });
+ await act(async () => {
+ resolveMount({
+ databases: [db("instances/i/databases/older")],
+ nextPageToken: "",
+ });
+ await Promise.resolve();
+ });
+
+ const values = combo.props?.options.map((o) => o.value) ?? [];
+ expect(values).toContain("instances/i/databases/newer");
+ expect(values).not.toContain("instances/i/databases/older");
+ unmount();
+ });
+});
+
+describe("DatabaseSelect — single mode (regression guard for Sync Schema)", () => {
+ test("onChange yields the real Database (not a synthesized stub)", async () => {
+ const dbS = db("instances/i/databases/s", "environments/staging");
+ mocks.cache.set(dbS.name, dbS);
+ mocks.fetchDatabases.mockResolvedValue({
+ databases: [dbS],
+ nextPageToken: "",
+ });
+ const onChange = vi.fn();
+ const { unmount } = render(
+ <DatabaseSelect value="" onChange={onChange} projectName="projects/p" />
+ );
+ await flush();
+
+ act(() => combo.props?.onChange("instances/i/databases/s"));
+ expect(onChange).toHaveBeenCalledWith(
+ "instances/i/databases/s",
+ expect.objectContaining({ effectiveEnvironment: "environments/staging" })
+ );
+ unmount();
+ });
+
+ test("selected label survives a search that drops it from the page (cache-resolved)", async () => {
+ const keep = db("instances/i/databases/keep", "environments/prod");
+ mocks.cache.set(keep.name, keep);
+ mocks.fetchDatabases.mockResolvedValue({
+ databases: [keep],
+ nextPageToken: "",
+ });
+ const { unmount } = render(
+ <DatabaseSelect
+ value="instances/i/databases/keep"
+ onChange={vi.fn()}
+ projectName="projects/p"
+ />
+ );
+ await flush();
+
+ // A search returns a different page not containing "keep".
+ mocks.fetchDatabases.mockResolvedValue({
+ databases: [db("instances/i/databases/zzz")],
+ nextPageToken: "",
+ });
+ act(() => combo.props?.onSearch?.("zzz"));
+ await flush();
+
+ // The selected value must still be resolvable as an option/label.
+ const opt = combo.props?.options.find(
+ (o) => o.value === "instances/i/databases/keep"
+ );
+ expect(opt).toBeDefined();
+ expect(opt?.label).toBe("keep");
+ unmount();
+ });
+
+ test("resolves a selected off-page value from the store cache (Sync Schema deep-link)", async () => {
+ const cached = db("instances/i/databases/deeplink", "environments/prod");
+ mocks.cache.set(cached.name, cached);
+ // The mount fetch page does NOT contain the pre-selected value.
+ mocks.fetchDatabases.mockResolvedValue({
+ databases: [db("instances/i/databases/other")],
+ nextPageToken: "",
+ });
+ const onChange = vi.fn();
+ const { unmount } = render(
+ <DatabaseSelect
+ value="instances/i/databases/deeplink"
+ onChange={onChange}
+ projectName="projects/p"
+ />
+ );
+ await flush();
+
+ // Re-selecting the pre-filled (off-page) value must yield the REAL cached
+ // Database, not undefined (undefined would make Sync Schema clear it).
+ act(() => combo.props?.onChange("instances/i/databases/deeplink"));
+ expect(onChange).toHaveBeenCalledWith(
+ "instances/i/databases/deeplink",
+ expect.objectContaining({ effectiveEnvironment: "environments/prod" })
+ );
+ unmount();
+ });
+});
diff --git a/frontend/src/react/components/DatabaseSelect.tsx b/frontend/src/react/components/DatabaseSelect.tsx
index 25f2d05b10..f71245fa32 100644
--- a/frontend/src/react/components/DatabaseSelect.tsx
+++ b/frontend/src/react/components/DatabaseSelect.tsx
@@ -2,7 +2,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { EngineIcon } from "@/react/components/EngineIcon";
import { EnvironmentLabel } from "@/react/components/EnvironmentLabel";
-import { Combobox } from "@/react/components/ui/combobox";
+import { Combobox, type ComboboxOption } from "@/react/components/ui/combobox";
import { useAppStore } from "@/react/stores/app";
import type { Engine } from "@/types/proto-es/v1/common_pb";
import type { Database } from "@/types/proto-es/v1/database_service_pb";
@@ -13,9 +13,7 @@ import {
getInstanceResource,
} from "@/utils";
-export interface DatabaseSelectProps {
- value: string;
- onChange: (value: string, database: Database | undefined) => void;
+interface BaseProps {
placeholder?: string;
disabled?: boolean;
className?: string;
@@ -25,22 +23,55 @@ export interface DatabaseSelectProps {
allowedEngineTypeList?: Engine[];
}
-export function DatabaseSelect({
- value,
- onChange,
- placeholder,
- disabled,
- className,
- portal,
- projectName,
- environmentName,
- allowedEngineTypeList,
-}: DatabaseSelectProps) {
+interface SingleProps {
+ multiple?: false;
+ value: string;
+ onChange: (value: string, database: Database | undefined) => void;
+}
+
+interface MultiProps {
+ multiple: true;
+ value: string[];
+ // `databases[i]` corresponds to `values[i]`, resolved best-effort from the
+ // current page and the app store's database cache; a value neither has (yet)
+ // resolved is `undefined` (the chip still renders from its resource name).
+ onChange: (values: string[], databases: (Database | undefined)[]) => void;
+}
+
+export type DatabaseSelectProps = BaseProps & (SingleProps | MultiProps);
+
+export function DatabaseSelect(props: DatabaseSelectProps) {
+ const {
+ placeholder,
+ disabled,
+ className,
+ portal,
+ projectName,
+ environmentName,
+ allowedEngineTypeList,
+ } = props;
const { t } = useTranslation();
const workspaceResourceName = useAppStore((s) => s.workspaceResourceName());
+ // The app store's global database cache — populated by every fetch below
+ // (upserted fresh) plus databases fetched elsewhere (e.g. Sync Schema's
+ // deep-link preload) and not evicted by this picker's own project-parent
+ // fetches. It resolves a selected value that is not on the current page, so
+ // chips stay labeled across searches and `onChange` payloads carry the real,
+ // fresh `Database`. Read non-reactively on purpose: `onChange` reads it live
+ // at click time (payload always current), and every flow that sets a selected
+ // value either populates the cache first (deep-link) or triggers a local
+ // re-render (search -> setDatabases), so a selected option never lingers as a
+ // synthesized label in practice.
+ const getDatabaseByName = useAppStore((s) => s.getDatabaseByName);
+
+ // Current page / latest search results (drives the dropdown rows).
const [databases, setDatabases] = useState<Database[]>([]);
+ // Monotonic fetch id: only the latest in-flight fetch may apply its result,
+ // so an out-of-order (slow mount / stale search) response can't clobber newer
+ // results. Mirrors DatabaseResourceSelector / the plan-detail DatabaseSelector.
+ const fetchIdRef = useRef(0);
- // Stabilize engines array to avoid re-fetching on every render
+ // Stabilize engines array to avoid re-fetching on every render.
const enginesRef = useRef(allowedEngineTypeList);
const stableEngines = useMemo(() => {
const prev = enginesRef.current;
@@ -58,6 +89,7 @@ export function DatabaseSelect({
const fetchDatabases = useCallback(
(query: string) => {
+ const fetchId = ++fetchIdRef.current;
useAppStore
.getState()
.fetchDatabases({
@@ -70,7 +102,15 @@ export function DatabaseSelect({
pageSize: getDefaultPagination(),
silent: true,
})
- .then((result) => setDatabases(result.databases));
+ .then((result) => {
+ // Drop stale responses so a slower earlier fetch can't overwrite the
+ // results of a newer query.
+ if (fetchId !== fetchIdRef.current) return;
+ setDatabases(result.databases);
+ })
+ .catch(() => {
+ /* keep existing options on error — never wipe the selection */
+ });
},
[projectName, environmentName, stableEngines, workspaceResourceName]
);
@@ -79,65 +119,125 @@ export function DatabaseSelect({
fetchDatabases("");
}, [fetchDatabases]);
- const handleChange = useCallback(
- (name: string) => {
- const db = databases.find((d) => d.name === name);
- onChange(name, db);
+ const selectedValues: string[] = useMemo(() => {
+ if (props.multiple === true) return props.value;
+ return props.value ? [props.value] : [];
+ }, [props.multiple, props.value]);
+
+ // Resolve a database name to its real `Database`: current page first, then
+ // the store cache. Returns undefined when neither has it (a never-fetched
+ // value) so callers can synthesize a label / omit it from the payload.
+ // The store upserts every fetched database into its global cache, so the
+ // current page is always a subset of the cache — resolve straight from it.
+ // getDatabaseByName returns an "unknown" placeholder on a miss (its name won't
+ // equal what we asked for), which we treat as unresolved.
+ const resolveDatabase = useCallback(
+ (name: string): Database | undefined => {
+ const cached = getDatabaseByName(name);
+ return cached.name === name ? cached : undefined;
},
- [databases, onChange]
+ [getDatabaseByName]
);
+ const buildOption = useCallback((database: Database): ComboboxOption => {
+ const inst = getInstanceResource(database);
+ const { databaseName, instance } = extractDatabaseResourceName(
+ database.name
+ );
+ return {
+ value: database.name,
+ label: databaseName,
+ description: instance,
+ render: () => (
+ <div className="flex flex-col gap-0.5">
+ <div className="flex items-center gap-1.5">
+ {inst.title && (
+ <>
+ <EngineIcon engine={inst.engine} className="h-4 w-4" />
+ <span>{inst.title}</span>
+ <span className="text-control-placeholder">&gt;</span>
+ </>
+ )}
+ <EnvironmentLabel
+ environmentName={getDatabaseEnvironment(database).name}
+ />
+ <span className="text-control-placeholder">&gt;</span>
+ <span>{databaseName}</span>
+ </div>
+ <span className="text-xs text-control-placeholder">
+ {database.name}
+ </span>
+ </div>
+ ),
+ };
+ }, []);
+
+ // Deduped union: current results + any selected value not on the page
+ // (resolved from the cache, else a label-only synthesized option from the
+ // name) — so a selected chip never loses its label after a search narrows
+ // the page or for a pre-filled value that was never fetched.
+ const options: ComboboxOption[] = useMemo(() => {
+ const present = new Set(databases.map((d) => d.name));
+ const opts = databases.map(buildOption);
+ for (const name of selectedValues) {
+ if (!name || present.has(name)) continue;
+ present.add(name);
+ const resolved = resolveDatabase(name);
+ if (resolved) {
+ opts.push(buildOption(resolved));
+ } else {
+ const { databaseName, instance } = extractDatabaseResourceName(name);
+ opts.push({ value: name, label: databaseName, description: instance });
+ }
+ }
+ return opts;
+ }, [databases, selectedValues, buildOption, resolveDatabase]);
+
+ const commonProps = {
+ placeholder: placeholder ?? t("database.select"),
+ noResultsText: t("common.no-data"),
+ onSearch: fetchDatabases,
+ disabled,
+ className,
+ portal,
+ options,
+ };
+
+ if (props.multiple === true) {
+ const onChange = props.onChange;
+ return (
+ <Combobox
+ {...commonProps}
+ multiple
+ value={props.value}
+ onChange={(values) => {
+ // Index-aligned with `values`; unresolved entries are undefined.
+ onChange(
+ values,
+ values.map((v) => resolveDatabase(v))
+ );
+ }}
+ />
+ );
+ }
+
+ const onChange = props.onChange;
return (
<Combobox
- value={value}
- onChange={handleChange}
- placeholder={placeholder ?? t("database.select")}
- noResultsText={t("common.no-data")}
- onSearch={fetchDatabases}
- disabled={disabled}
- className={className}
- portal={portal}
+ {...commonProps}
+ value={props.value}
+ onChange={(name) => onChange(name, resolveDatabase(name))}
renderValue={(opt) => {
- const db = databases.find((d) => d.name === opt.value);
- if (!db) return opt.label;
- const inst = getInstanceResource(db);
+ const database = resolveDatabase(opt.value);
+ if (!database) return opt.label;
+ const inst = getInstanceResource(database);
return (
<span className="flex items-center gap-1.5 truncate">
<EngineIcon engine={inst.engine} className="h-4 w-4" />
- {extractDatabaseResourceName(db.name).databaseName}
+ {extractDatabaseResourceName(database.name).databaseName}
</span>
);
}}
- options={databases.map((db) => {
- const inst = getInstanceResource(db);
- return {
- value: db.name,
- label: extractDatabaseResourceName(db.name).databaseName,
- description: extractDatabaseResourceName(db.name).instance,
- render: () => (
- <div className="flex flex-col gap-0.5">
- <div className="flex items-center gap-1.5">
- {inst.title && (
- <>
- <EngineIcon engine={inst.engine} className="h-4 w-4" />
- <span>{inst.title}</span>
- <span className="text-control-placeholder">&gt;</span>
- </>
- )}
- <EnvironmentLabel
- environmentName={getDatabaseEnvironment(db).name}
- />
- <span className="text-control-placeholder">&gt;</span>
- <span>{extractDatabaseResourceName(db.name).databaseName}</span>
- </div>
- <span className="text-xs text-control-placeholder">
- {extractDatabaseResourceName(db.name).instance}/databases/
- {extractDatabaseResourceName(db.name).databaseName}
- </span>
- </div>
- ),
- };
- })}
/>
);
}
diff --git a/frontend/src/react/components/sql-editor/AccessGrantRequestDrawer.test.tsx b/frontend/src/react/components/sql-editor/AccessGrantRequestDrawer.test.tsx
index 509d688fab..936d29c701 100644
--- a/frontend/src/react/components/sql-editor/AccessGrantRequestDrawer.test.tsx
+++ b/frontend/src/react/components/sql-editor/AccessGrantRequestDrawer.test.tsx
@@ -22,6 +22,8 @@ const mocks = vi.hoisted(() => ({
.mockResolvedValue({ databases: [], nextPageToken: "" }),
createAccessGrant: vi.fn(),
routerResolve: vi.fn(() => ({ fullPath: "/projects/proj1/issues/123" })),
+ // Captures the multi picker's server-search callback (undefined pre-fix).
+ dbOnSearch: undefined as ((q: string) => void) | undefined,
}));
vi.mock("react-i18next", () => ({
@@ -46,6 +48,9 @@ vi.mock("@/react/stores/app", () => {
// which drives the drawer's Monaco theme). Empty profile resolves to the
// default theme.
getWorkspaceProfile: () => ({}),
+ // Consumed by the shared DatabaseSelect (rendered by the drawer's picker).
+ workspaceResourceName: () => "workspaces/-",
+ getDatabaseByName: () => ({ name: "" }),
});
return {
useAppStore: Object.assign(
@@ -122,6 +127,10 @@ vi.mock("@/utils", () => ({
const match = name.match(/projects\/(.+?)(?:\/|$)/);
return match?.[1] ?? "";
}),
+ // Consumed by the shared DatabaseSelect (rendered by the drawer's picker).
+ getDefaultPagination: () => 50,
+ getInstanceResource: () => ({ engine: 0, title: "" }),
+ getDatabaseEnvironment: () => ({ name: "environments/prod" }),
}));
vi.mock("@bufbuild/protobuf", () => ({
@@ -217,40 +226,58 @@ vi.mock("@/react/components/ui/button", () => ({
),
}));
+// The drawer now renders the real DatabaseSelect, which imports EngineIcon and
+// EnvironmentLabel. Stub them so their transitive proto-es imports don't load
+// (they conflict with this file's minimal @bufbuild/protobuf(/wkt) mocks). They
+// are only referenced inside the picker's option.render, never invoked here
+// because the Combobox mock below renders plain <option> labels.
+vi.mock("@/react/components/EngineIcon", () => ({ EngineIcon: () => null }));
+vi.mock("@/react/components/EnvironmentLabel", () => ({
+ EnvironmentLabel: () => null,
+}));
+
vi.mock("@/react/components/ui/combobox", () => ({
Combobox: ({
value,
onChange,
options,
multiple,
+ onSearch,
}: {
value: string | string[];
onChange: (val: string | string[]) => void;
options: { value: string; label: string }[];
multiple?: boolean;
- }) => (
- <select
- data-testid={multiple ? "multi-combobox" : "combobox"}
- multiple={multiple}
- value={multiple ? (value as string[]) : (value as string)}
- onChange={(e) => {
- if (multiple) {
- const selected = Array.from(e.target.selectedOptions).map(
- (o) => o.value
- );
- onChange(selected);
- } else {
- onChange(e.target.value);
- }
- }}
- >
- {options.map((opt) => (
- <option key={opt.value} value={opt.value}>
- {opt.label}
- </option>
- ))}
- </select>
- ),
+ onSearch?: (q: string) => void;
+ }) => {
+ // Only the multi database picker sets this; the single Expiration combobox
+ // (multiple falsy) is skipped. Pre-fix the local MultiDatabaseSelect passes
+ // no onSearch, so this stays undefined — the red bug-repro assertion.
+ if (multiple) mocks.dbOnSearch = onSearch;
+ return (
+ <select
+ data-testid={multiple ? "multi-combobox" : "combobox"}
+ multiple={multiple}
+ value={multiple ? (value as string[]) : (value as string)}
+ onChange={(e) => {
+ if (multiple) {
+ const selected = Array.from(e.target.selectedOptions).map(
+ (o) => o.value
+ );
+ onChange(selected);
+ } else {
+ onChange(e.target.value);
+ }
+ }}
+ >
+ {options.map((opt) => (
+ <option key={opt.value} value={opt.value}>
+ {opt.label}
+ </option>
+ ))}
+ </select>
+ );
+ },
}));
vi.mock("@/react/components/ui/expiration-picker", () => ({
@@ -337,6 +364,8 @@ const setupMocks = () => {
mocks.currentTabDatabase = "instances/inst1/databases/db1";
mocks.fetchDatabases.mockResolvedValue({ databases: [], nextPageToken: "" });
+ // vi.clearAllMocks() does not reset a plain hoisted property.
+ mocks.dbOnSearch = undefined;
};
beforeEach(async () => {
@@ -531,4 +560,81 @@ describe("AccessGrantRequestDrawer", () => {
expect(onClose).toHaveBeenCalled();
unmount();
});
+
+ test("typing in the Request Data Access database picker re-queries the server (BYT-9801)", async () => {
+ const onClose = vi.fn();
+ const { render: renderFn, unmount } = renderIntoContainer(
+ <AccessGrantRequestDrawer
+ targets={["instances/inst1/databases/db1"]}
+ onClose={onClose}
+ />
+ );
+ renderFn();
+ await act(async () => {
+ await Promise.resolve(); // let the picker's mount fetch resolve
+ });
+
+ // Pre-fix: the local MultiDatabaseSelect passes no onSearch → undefined.
+ expect(mocks.dbOnSearch).toBeTypeOf("function");
+
+ await act(async () => {
+ mocks.dbOnSearch?.("orders");
+ await Promise.resolve();
+ });
+
+ expect(mocks.fetchDatabases).toHaveBeenCalledWith(
+ expect.objectContaining({
+ filter: expect.objectContaining({ query: "orders" }),
+ })
+ );
+ unmount();
+ });
+
+ test("pre-filled targets are submitted to createAccessGrant", async () => {
+ mocks.createAccessGrant.mockResolvedValue({
+ status: 2,
+ issue: "",
+ name: "projects/proj1/accessGrants/g",
+ });
+ const onClose = vi.fn();
+ const {
+ container,
+ render: renderFn,
+ unmount,
+ } = renderIntoContainer(
+ <AccessGrantRequestDrawer
+ targets={["instances/inst1/databases/db1"]}
+ query="SELECT * FROM t"
+ onClose={onClose}
+ />
+ );
+ renderFn();
+
+ const textarea = container.querySelector(
+ "[data-testid='textarea']"
+ ) as HTMLTextAreaElement;
+ await act(async () => {
+ const changeEvent = new Event("change", { bubbles: true });
+ Object.defineProperty(textarea, "value", { writable: true, value: "r" });
+ Object.defineProperty(changeEvent, "target", {
+ writable: false,
+ value: textarea,
+ });
+ textarea.dispatchEvent(changeEvent);
+ });
+
+ const submitBtn = container.querySelector(
+ "[data-submit-btn]"
+ ) as HTMLButtonElement;
+ await act(async () => submitBtn.click());
+
+ expect(mocks.createAccessGrant).toHaveBeenCalledWith(
+ expect.objectContaining({
+ accessGrant: expect.objectContaining({
+ targets: ["instances/inst1/databases/db1"],
+ }),
+ })
+ );
+ unmount();
+ });
});
diff --git a/frontend/src/react/components/sql-editor/AccessGrantRequestDrawer.tsx b/frontend/src/react/components/sql-editor/AccessGrantRequestDrawer.tsx
index 9c292fb8e2..2862b2da16 100644
--- a/frontend/src/react/components/sql-editor/AccessGrantRequestDrawer.tsx
+++ b/frontend/src/react/components/sql-editor/AccessGrantRequestDrawer.tsx
@@ -5,6 +5,7 @@ import { Loader2 } from "lucide-react";
import { useEffect, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { accessGrantServiceClientConnect } from "@/connect";
+import { DatabaseSelect } from "@/react/components/DatabaseSelect";
import { MonacoEditor } from "@/react/components/monaco/MonacoEditor";
import {
monacoThemeName,
@@ -45,58 +46,6 @@ import {
extractProjectResourceName,
} from "@/utils";
-// Multi-select database combobox
-function MultiDatabaseSelect({
- value,
- projectName,
- onChange,
-}: {
- value: string[];
- projectName: string;
- onChange: (val: string[]) => void;
-}) {
- const { t } = useTranslation();
- const [databases, setDatabases] = useState<
- { name: string; displayName: string }[]
- >([]);
-
- const fetchDatabases = useAppStore((s) => s.fetchDatabases);
-
- useEffect(() => {
- fetchDatabases({
- parent: projectName,
- filter: { query: "" },
- pageSize: 100,
- silent: true,
- })
- .then((result) => {
- setDatabases(
- result.databases.map((db) => {
- const { databaseName } = extractDatabaseResourceName(db.name);
- return { name: db.name, displayName: databaseName };
- })
- );
- })
- .catch(() => {
- /* ignore */
- });
- }, [fetchDatabases, projectName]);
-
- return (
- <Combobox
- multiple={true}
- value={value}
- onChange={onChange}
- placeholder={t("database.select")}
- noResultsText={t("common.no-data")}
- options={databases.map((db) => ({
- value: db.name,
- label: db.displayName,
- }))}
- />
- );
-}
-
interface Props {
readonly targets?: string[];
readonly query?: string;
@@ -351,10 +300,11 @@ function AccessGrantRequestDrawerInner({
{t("common.databases")}
<span className="text-error ml-0.5">*</span>
</div>
- <MultiDatabaseSelect
+ <DatabaseSelect
+ multiple
value={targets}
- projectName={project as string}
onChange={setTargets}
+ projectName={project as string}
/>
</div>