Skip to content

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

fix: frontend issues (#20899)

ecmadaod6f0b66f349a
diff --git a/frontend/biome.json b/frontend/biome.json
index c603e1e8fc..829ff5596a 100644
--- a/frontend/biome.json
+++ b/frontend/biome.json
@@ -1,10 +1,11 @@
{
- "$schema": "https://biomejs.dev/schemas/2.5.2/schema.json",
+ "$schema": "https://biomejs.dev/schemas/2.5.3/schema.json",
"vcs": { "enabled": true, "clientKind": "git", "useIgnoreFile": true },
"files": {
"ignoreUnknown": true,
"includes": [
"src/**/*",
+ "!src/**/*.test.tsx",
"!**/*.svg",
"!!src/bbkit/BBUtil.ts",
"!!src/types/proto-es/**"
diff --git a/frontend/src/react/components/sql-editor/ResultView/TableCell.test.tsx b/frontend/src/react/components/sql-editor/ResultView/TableCell.test.tsx
new file mode 100644
index 0000000000..e8426d7687
--- /dev/null
+++ b/frontend/src/react/components/sql-editor/ResultView/TableCell.test.tsx
@@ -0,0 +1,110 @@
+import { create } from "@bufbuild/protobuf";
+import { render, screen } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
+import { Engine } from "@/types/proto-es/v1/common_pb";
+import type { Database } from "@/types/proto-es/v1/database_service_pb";
+import {
+ QueryRowSchema,
+ RowValueSchema,
+} from "@/types/proto-es/v1/sql_service_pb";
+import { SQLResultViewProvider } from "./context";
+import { TableCell } from "./TableCell";
+import type { ResultTableColumn, ResultTableRow } from "./types";
+
+vi.mock("react-i18next", () => ({
+ initReactI18next: {
+ init: vi.fn(),
+ type: "3rdParty",
+ },
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+vi.mock("@/utils/v1/database", () => ({
+ getInstanceResource: () => ({
+ name: "instances/prod",
+ engine: Engine.POSTGRES,
+ }),
+}));
+
+class ResizeObserverStub implements ResizeObserver {
+ private readonly callback: ResizeObserverCallback;
+
+ constructor(callback: ResizeObserverCallback) {
+ this.callback = callback;
+ }
+ observe() {
+ this.callback([], this);
+ }
+ unobserve() {}
+ disconnect() {}
+ takeRecords(): ResizeObserverEntry[] {
+ return [];
+ }
+}
+
+globalThis.ResizeObserver = ResizeObserverStub;
+
+const database = {
+ name: "instances/prod/databases/main",
+ project: "projects/prod",
+ instanceResource: {
+ name: "instances/prod",
+ engine: Engine.POSTGRES,
+ },
+} as Database;
+
+const columns: ResultTableColumn[] = [
+ { id: "created_at", name: "created_at", columnType: "TEXT" },
+];
+
+const longValue = "1.779696812227E+12";
+const value = create(RowValueSchema, {
+ kind: { case: "stringValue", value: longValue },
+});
+
+const rows: ResultTableRow[] = [
+ {
+ key: 0,
+ item: create(QueryRowSchema, {
+ values: [value],
+ }),
+ },
+];
+
+describe("TableCell", () => {
+ beforeEach(() => {
+ vi.spyOn(HTMLElement.prototype, "scrollWidth", "get").mockReturnValue(160);
+ vi.spyOn(HTMLElement.prototype, "offsetWidth", "get").mockReturnValue(80);
+ vi.spyOn(HTMLElement.prototype, "scrollHeight", "get").mockReturnValue(20);
+ vi.spyOn(HTMLElement.prototype, "offsetHeight", "get").mockReturnValue(20);
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ test("reserves space for the expand action when cell content is truncated", async () => {
+ const { container } = render(
+ <SQLResultViewProvider
+ engine={Engine.POSTGRES}
+ rows={rows}
+ columns={columns}
+ >
+ <TableCell
+ value={value}
+ rowIndex={0}
+ colIndex={0}
+ allowSelect
+ columnType="TEXT"
+ database={database}
+ keyword=""
+ />
+ </SQLResultViewProvider>
+ );
+
+ expect(await screen.findByRole("button")).toBeInTheDocument();
+ expect(container.querySelector(".line-clamp-3")).toHaveClass(
+ "max-w-[calc(100%-1.5rem)]"
+ );
+ });
+});
diff --git a/frontend/src/react/components/sql-editor/ResultView/TableCell.tsx b/frontend/src/react/components/sql-editor/ResultView/TableCell.tsx
index 28d03db141..d3ef775f41 100644
--- a/frontend/src/react/components/sql-editor/ResultView/TableCell.tsx
+++ b/frontend/src/react/components/sql-editor/ResultView/TableCell.tsx
@@ -63,7 +63,8 @@ export function TableCell({
if (!cell || !wrapper) return;
const measure = () => {
const verticalTruncated = wrapper.scrollHeight > wrapper.offsetHeight + 2;
- const horizontalTruncated = wrapper.scrollWidth > cell.offsetWidth + 2;
+ const availableWidth = Math.min(cell.offsetWidth, wrapper.offsetWidth);
+ const horizontalTruncated = wrapper.scrollWidth > availableWidth + 2;
setTruncated(verticalTruncated || horizontalTruncated);
};
measure();
@@ -133,14 +134,18 @@ export function TableCell({
onClick={handleClick}
onDoubleClick={showDetail}
className={cn(
- "w-full h-full px-2 py-1 flex items-center",
+ "relative w-full h-full px-2 py-1 flex items-center",
allowSelect ? "cursor-pointer hover:bg-accent/10" : "select-none",
selected && "bg-accent/20!"
)}
>
<div
ref={wrapperRef}
- className="font-mono text-start wrap-break-word line-clamp-3"
+ className={cn(
+ "font-mono text-start wrap-break-word line-clamp-3",
+ (hasByteData || clickable) && "max-w-[calc(100%-1.5rem)]",
+ hasByteData && clickable && "max-w-[calc(100%-3.25rem)]"
+ )}
>
{inner}
</div>
diff --git a/frontend/src/react/components/sql-editor/ResultView/VirtualDataBlock.test.tsx b/frontend/src/react/components/sql-editor/ResultView/VirtualDataBlock.test.tsx
new file mode 100644
index 0000000000..3b35a3ce2b
--- /dev/null
+++ b/frontend/src/react/components/sql-editor/ResultView/VirtualDataBlock.test.tsx
@@ -0,0 +1,204 @@
+import { create } from "@bufbuild/protobuf";
+import { fireEvent, render, screen } from "@testing-library/react";
+import type { ReactNode } from "react";
+import { beforeEach, describe, expect, test, vi } from "vitest";
+import { Engine } from "@/types/proto-es/v1/common_pb";
+import type { Database } from "@/types/proto-es/v1/database_service_pb";
+import {
+ QueryRowSchema,
+ type RowValue,
+ RowValueSchema,
+} from "@/types/proto-es/v1/sql_service_pb";
+import { SQLResultViewProvider } from "./context";
+import type { ResultTableColumn, ResultTableRow } from "./types";
+import { VirtualDataBlock } from "./VirtualDataBlock";
+
+const virtualizerOptions: Array<{
+ count: number;
+ estimateSize: (index: number) => number;
+ gap?: number;
+ paddingEnd?: number;
+}> = [];
+
+vi.mock("@tanstack/react-virtual", () => ({
+ useVirtualizer: (options: {
+ count: number;
+ estimateSize: (index: number) => number;
+ gap?: number;
+ paddingEnd?: number;
+ }) => {
+ virtualizerOptions.push(options);
+ const itemSize = options.estimateSize(0);
+ const gap = options.gap ?? 0;
+ const paddingEnd = options.paddingEnd ?? 0;
+ return {
+ getVirtualItems: () =>
+ Array.from({ length: options.count }, (_, index) => ({
+ index,
+ key: index,
+ start: index * (itemSize + gap),
+ })),
+ getTotalSize: () =>
+ options.count * itemSize +
+ Math.max(0, options.count - 1) * gap +
+ paddingEnd,
+ measureElement: vi.fn(),
+ scrollToIndex: vi.fn(),
+ };
+ },
+}));
+
+vi.mock("react-i18next", () => ({
+ initReactI18next: {
+ init: vi.fn(),
+ type: "3rdParty",
+ },
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+vi.mock("@/react/components/ui/tooltip", () => ({
+ Tooltip: ({ children }: { children: ReactNode }) => <>{children}</>,
+}));
+
+vi.mock("@/react/components/sql-editor/MaskingReasonPopover", () => ({
+ MaskingReasonPopover: () => null,
+}));
+
+vi.mock("@/react/stores/app", () => {
+ const state = () => ({
+ notify: vi.fn(),
+ });
+ return {
+ useAppStore: Object.assign(
+ (selector: (s: ReturnType<typeof state>) => unknown) => selector(state()),
+ { getState: state }
+ ),
+ };
+});
+
+vi.mock("@/types", () => ({
+ getDateForPbTimestampProtoEs: (ts: { seconds: bigint; nanos: number }) =>
+ new Date(Number(ts.seconds) * 1000 + Math.floor((ts.nanos ?? 0) / 1e6)),
+}));
+
+vi.mock("@/utils/v1/database", () => ({
+ getInstanceResource: () => ({
+ name: "instances/prod",
+ engine: Engine.POSTGRES,
+ }),
+}));
+
+class ResizeObserverStub implements ResizeObserver {
+ constructor(_callback: ResizeObserverCallback) {}
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ takeRecords(): ResizeObserverEntry[] {
+ return [];
+ }
+}
+
+globalThis.ResizeObserver = ResizeObserverStub;
+
+const textValue = (value: string): RowValue =>
+ create(RowValueSchema, {
+ kind: { case: "stringValue", value },
+ });
+
+const columns: ResultTableColumn[] = [
+ { id: "company", name: "company", columnType: "TEXT" },
+ { id: "status", name: "status", columnType: "TEXT" },
+];
+
+const rows: ResultTableRow[] = [
+ {
+ key: 0,
+ item: create(QueryRowSchema, {
+ values: [textValue("Acme"), textValue("reviewed")],
+ }),
+ },
+ {
+ key: 1,
+ item: create(QueryRowSchema, {
+ values: [textValue("Bytebase"), textValue("approved")],
+ }),
+ },
+ {
+ key: 2,
+ item: create(QueryRowSchema, {
+ values: [textValue("Longbridge"), textValue("final-row")],
+ }),
+ },
+];
+
+const database = {
+ name: "instances/prod/databases/main",
+ project: "projects/prod",
+ instanceResource: {
+ name: "instances/prod",
+ engine: Engine.POSTGRES,
+ },
+} as Database;
+
+const renderBlock = () =>
+ render(
+ <SQLResultViewProvider
+ engine={Engine.POSTGRES}
+ rows={rows}
+ columns={columns}
+ >
+ <VirtualDataBlock
+ rows={rows}
+ columns={columns}
+ activeRowIndex={-1}
+ isSensitiveColumn={() => false}
+ database={database}
+ search={{ query: "", scopes: [] }}
+ />
+ </SQLResultViewProvider>
+ );
+
+describe("VirtualDataBlock", () => {
+ beforeEach(() => {
+ virtualizerOptions.length = 0;
+ Object.defineProperty(navigator, "clipboard", {
+ value: { writeText: vi.fn().mockResolvedValue(undefined) },
+ configurable: true,
+ writable: true,
+ });
+ });
+
+ test("reserves end scroll space and keeps the final row copy action clickable", () => {
+ const { container } = renderBlock();
+
+ const virtualizerConfig = virtualizerOptions.at(-1);
+ expect(virtualizerConfig?.paddingEnd).toBeGreaterThanOrEqual(96);
+
+ const scrollContent = container.querySelector(
+ "div[style*='position: relative']"
+ );
+ expect(scrollContent).toBeInstanceOf(HTMLDivElement);
+ const height = Number.parseFloat(
+ (scrollContent as HTMLDivElement).style.height
+ );
+ const rowHeight = virtualizerConfig?.estimateSize(0) ?? 0;
+ const gap = virtualizerConfig?.gap ?? 0;
+ expect(height).toBeGreaterThanOrEqual(
+ rows.length * rowHeight + (rows.length - 1) * gap + 96
+ );
+
+ const copyButtons = screen.getAllByRole("button", { name: "common.copy" });
+ fireEvent.click(copyButtons[copyButtons.length - 1]);
+
+ expect(navigator.clipboard.writeText).toHaveBeenCalledWith(
+ JSON.stringify(
+ {
+ company: "Longbridge",
+ status: "final-row",
+ },
+ null,
+ 4
+ )
+ );
+ });
+});
diff --git a/frontend/src/react/components/sql-editor/ResultView/VirtualDataBlock.tsx b/frontend/src/react/components/sql-editor/ResultView/VirtualDataBlock.tsx
index 51586f9e7d..b564ff2a19 100644
--- a/frontend/src/react/components/sql-editor/ResultView/VirtualDataBlock.tsx
+++ b/frontend/src/react/components/sql-editor/ResultView/VirtualDataBlock.tsx
@@ -79,6 +79,7 @@ export const VirtualDataBlock = forwardRef<
// gap to the next row. The virtualizer's `gap` option adds the
// requested pixels into each row's `start` so cards visibly breathe.
gap: 16,
+ paddingEnd: 96,
});
useImperativeHandle(
@@ -231,6 +232,7 @@ function CopyJSONButton({
<Button
size="sm"
appearance="secondary"
+ aria-label={label}
className="size-7 p-0"
onClick={handleCopy}
>
diff --git a/frontend/src/react/components/sql-editor/SQLEditorRouteShell.test.tsx b/frontend/src/react/components/sql-editor/SQLEditorRouteShell.test.tsx
new file mode 100644
index 0000000000..1dd313e7f1
--- /dev/null
+++ b/frontend/src/react/components/sql-editor/SQLEditorRouteShell.test.tsx
@@ -0,0 +1,484 @@
+import { act } from "react";
+import { createRoot } from "react-dom/client";
+import { beforeEach, describe, expect, test, vi } from "vitest";
+import type { ReactRoute } from "@/react/router";
+import type { SQLEditorTab } from "@/types";
+import { SQLEditorRouteShell } from "./SQLEditorRouteShell";
+
+(
+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+const mocks = vi.hoisted(() => {
+ const tabsState = {
+ tabsById: new Map(),
+ openTmpTabList: [],
+ currentTabId: "",
+ addTab: vi.fn((payload: Partial<SQLEditorTab> = {}) => {
+ const tab = {
+ id: "tab-1",
+ worksheet: "",
+ connection: {
+ instance: "",
+ database: "",
+ },
+ ...payload,
+ } as SQLEditorTab;
+ tabsState.tabsById.set(tab.id, tab);
+ tabsState.currentTabId = tab.id;
+ return tab;
+ }),
+ initProject: vi.fn(async () => undefined),
+ updateCurrentTab: vi.fn(),
+ };
+ const editorState = {
+ project: "projects/proj1",
+ projectContextReady: true,
+ setProjectContextReady: vi.fn(),
+ setProject: vi.fn(),
+ };
+ return {
+ tabsState,
+ editorState,
+ maybeSwitchProject: vi.fn<(project: string) => Promise<string | undefined>>(
+ async (project: string) => project
+ ),
+ setAsidePanelTab: vi.fn(),
+ getOrFetchDatabaseByName: vi.fn(async (name: string) => ({
+ name,
+ project: "projects/proj1",
+ })),
+ searchProjects: vi.fn(),
+ beforeEach: vi.fn(() => vi.fn()),
+ navigateReplace: vi.fn(),
+ renderRoute: {
+ name: "sql-editor.database",
+ fullPath:
+ "/sql-editor/projects/proj1/instances/inst1/databases/db1?schema=public&table=users",
+ hash: "",
+ params: {
+ project: "proj1",
+ instance: "inst1",
+ database: "db1",
+ },
+ query: {
+ schema: "public",
+ table: "users",
+ },
+ requiredPermissions: [],
+ overrideDocumentTitle: false,
+ meta: {},
+ } as ReactRoute,
+ currentRoute: {
+ name: "sql-editor.database",
+ fullPath:
+ "/sql-editor/projects/proj1/instances/inst1/databases/db1?schema=public&table=users",
+ hash: "",
+ params: {
+ project: "proj1",
+ instance: "inst1",
+ database: "db1",
+ },
+ query: {
+ schema: "public",
+ table: "users",
+ },
+ requiredPermissions: [],
+ overrideDocumentTitle: false,
+ meta: {},
+ } as ReactRoute,
+ };
+});
+
+vi.mock("react-i18next", () => ({
+ initReactI18next: { type: "3rdParty", init: () => undefined },
+ useTranslation: () => ({
+ t: (key: string) => key,
+ }),
+}));
+
+vi.mock("@/react/components/ComponentPermissionGuard", () => ({
+ PermissionDeniedFallback: () => <div data-testid="denied" />,
+ useComponentPermissionState: () => ({
+ missedBasicPermissions: [],
+ missedPermissions: [],
+ permitted: true,
+ }),
+ usePermissionDataReady: () => true,
+}));
+
+vi.mock("@/react/hooks/useAppProject", () => ({
+ useAppProject: () => ({
+ name: "projects/proj1",
+ }),
+}));
+
+vi.mock("@/react/hooks/useSQLEditorBridge", () => ({
+ useClampResultRowsLimitToPolicy: vi.fn(),
+}));
+
+vi.mock("@/react/router", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@/react/router")>()),
+ router: {
+ currentRoute: {
+ get value() {
+ return mocks.currentRoute;
+ },
+ },
+ beforeEach: mocks.beforeEach,
+ },
+ useCurrentRoute: () => mocks.renderRoute,
+ useNavigate: () => ({
+ replace: mocks.navigateReplace,
+ }),
+}));
+
+vi.mock("@/react/stores/app", () => ({
+ useAppStore: {
+ getState: () => ({
+ getOrFetchDatabaseByName: mocks.getOrFetchDatabaseByName,
+ searchProjects: mocks.searchProjects,
+ serverInfo: {
+ defaultProject: "projects/proj1",
+ },
+ }),
+ },
+}));
+
+vi.mock("@/react/stores/sqlEditor", () => ({
+ useSQLEditorStore: Object.assign(
+ (selector: (state: unknown) => unknown) =>
+ selector({
+ maybeSwitchProject: mocks.maybeSwitchProject,
+ setAsidePanelTab: mocks.setAsidePanelTab,
+ asidePanelTab: "SCHEMA",
+ }),
+ {
+ getState: () => ({
+ fetchQueryHistory: vi.fn(),
+ setLinkedQueryHistory: vi.fn(),
+ }),
+ }
+ ),
+}));
+
+vi.mock("@/react/stores/sqlEditor/editor", () => ({
+ getSQLEditorEditorState: () => mocks.editorState,
+ useSQLEditorEditorState: (selector: (state: unknown) => unknown) =>
+ selector(mocks.editorState),
+}));
+
+vi.mock("@/react/stores/sqlEditor/tab", () => ({
+ getSQLEditorTabsState: () => mocks.tabsState,
+ useSQLEditorTabState: (selector: (state: unknown) => unknown) =>
+ selector(mocks.tabsState),
+}));
+
+vi.mock("@/store/modules/sqlEditor/legacy/migration", () => ({
+ migrateLegacyCache: vi.fn(async () => undefined),
+}));
+
+vi.mock("./SQLEditorHomePage", () => ({
+ SQLEditorHomePage: () => <div data-testid="sql-editor-home" />,
+}));
+
+const renderShell = () => {
+ const container = document.createElement("div");
+ document.body.appendChild(container);
+ const root = createRoot(container);
+ act(() => {
+ root.render(<SQLEditorRouteShell />);
+ });
+ return {
+ unmount: () =>
+ act(() => {
+ root.unmount();
+ container.remove();
+ }),
+ };
+};
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.maybeSwitchProject.mockImplementation(
+ async (project: string) => project
+ );
+ mocks.tabsState.addTab.mockImplementation(
+ (payload: Partial<SQLEditorTab> = {}) => {
+ const tab = {
+ id: "tab-1",
+ worksheet: "",
+ connection: {
+ instance: "",
+ database: "",
+ },
+ ...payload,
+ } as SQLEditorTab;
+ mocks.tabsState.tabsById.set(tab.id, tab);
+ mocks.tabsState.currentTabId = tab.id;
+ return tab;
+ }
+ );
+ mocks.getOrFetchDatabaseByName.mockImplementation(async (name: string) => ({
+ name,
+ project: "projects/proj1",
+ }));
+ mocks.editorState.project = "projects/proj1";
+ mocks.tabsState.tabsById = new Map();
+ mocks.tabsState.openTmpTabList = [];
+ mocks.tabsState.currentTabId = "";
+ mocks.renderRoute = {
+ ...mocks.renderRoute,
+ name: "sql-editor.database",
+ params: {
+ project: "proj1",
+ instance: "inst1",
+ database: "db1",
+ },
+ query: {
+ schema: "public",
+ table: "users",
+ },
+ requiredPermissions: [],
+ };
+ mocks.currentRoute = {
+ ...mocks.currentRoute,
+ name: "sql-editor.database",
+ params: {
+ project: "proj1",
+ instance: "inst1",
+ database: "db1",
+ },
+ query: {
+ schema: "public",
+ table: "users",
+ },
+ requiredPermissions: [],
+ };
+});
+
+describe("SQLEditorRouteShell", () => {
+ test("seeds database route tabs with schema and table from the URL", async () => {
+ const { unmount } = renderShell();
+
+ await act(async () => {
+ await Promise.resolve();
+ await Promise.resolve();
+ await Promise.resolve();
+ });
+
+ expect(mocks.tabsState.addTab).toHaveBeenCalledWith({
+ connection: {
+ instance: "instances/inst1",
+ database: "instances/inst1/databases/db1",
+ schema: "public",
+ table: "users",
+ },
+ mode: "WORKSHEET",
+ });
+ expect(mocks.navigateReplace).toHaveBeenCalledWith({
+ name: "sql-editor.database",
+ params: {
+ project: "proj1",
+ instance: "inst1",
+ database: "db1",
+ },
+ query: {
+ table: "users",
+ schema: "public",
+ },
+ });
+
+ unmount();
+ });
+
+ test("uses the render route when the imperative router snapshot is still on the parent route", async () => {
+ mocks.currentRoute = {
+ ...mocks.currentRoute,
+ name: "sql-editor",
+ params: {},
+ query: {},
+ requiredPermissions: [],
+ };
+
+ const { unmount } = renderShell();
+
+ await act(async () => {
+ await Promise.resolve();
+ await Promise.resolve();
+ await Promise.resolve();
+ });
+
+ expect(mocks.tabsState.addTab).toHaveBeenCalledWith({
+ connection: {
+ instance: "instances/inst1",
+ database: "instances/inst1/databases/db1",
+ schema: "public",
+ table: "users",
+ },
+ mode: "WORKSHEET",
+ });
+ expect(mocks.navigateReplace).toHaveBeenCalledWith({
+ name: "sql-editor.database",
+ params: {
+ project: "proj1",
+ instance: "inst1",
+ database: "db1",
+ },
+ query: {
+ table: "users",
+ schema: "public",
+ },
+ });
+
+ unmount();
+ });
+
+ test("opens the database route when the editor is already on that project", async () => {
+ mocks.editorState.project = "projects/proj1";
+ let switchProjectCallCount = 0;
+ mocks.maybeSwitchProject.mockImplementation(async (project: string) => {
+ switchProjectCallCount++;
+ return switchProjectCallCount === 1 ? project : undefined;
+ });
+
+ const { unmount } = renderShell();
+
+ await act(async () => {
+ await Promise.resolve();
+ await Promise.resolve();
+ await Promise.resolve();
+ });
+
+ expect(mocks.tabsState.addTab).toHaveBeenCalledWith({
+ connection: {
+ instance: "instances/inst1",
+ database: "instances/inst1/databases/db1",
+ schema: "public",
+ table: "users",
+ },
+ mode: "WORKSHEET",
+ });
+
+ unmount();
+ });
+
+ test("opens the database route when project context enrichment fails after database fetch", async () => {
+ mocks.editorState.project = "projects/other";
+ let switchProjectCallCount = 0;
+ mocks.maybeSwitchProject.mockImplementation(async (project: string) => {
+ switchProjectCallCount++;
+ return switchProjectCallCount === 1 ? project : undefined;
+ });
+
+ const { unmount } = renderShell();
+
+ await act(async () => {
+ await Promise.resolve();
+ await Promise.resolve();
+ await Promise.resolve();
+ });
+
+ expect(mocks.editorState.setProject).toHaveBeenCalledWith("projects/proj1");
+ expect(mocks.tabsState.addTab).toHaveBeenCalledWith({
+ connection: {
+ instance: "instances/inst1",
+ database: "instances/inst1/databases/db1",
+ schema: "public",
+ table: "users",
+ },
+ mode: "WORKSHEET",
+ });
+
+ unmount();
+ });
+
+ test("does not downgrade a database deep link while the tab connection is pending", async () => {
+ mocks.tabsState.addTab.mockImplementation(
+ (payload: Partial<SQLEditorTab> = {}) =>
+ ({
+ id: "tab-pending",
+ worksheet: "",
+ connection: {
+ instance: "",
+ database: "",
+ },
+ ...payload,
+ }) as SQLEditorTab
+ );
+
+ const { unmount } = renderShell();
+
+ await act(async () => {
+ await Promise.resolve();
+ await Promise.resolve();
+ await Promise.resolve();
+ });
+
+ expect(mocks.tabsState.addTab).toHaveBeenCalledWith({
+ connection: {
+ instance: "instances/inst1",
+ database: "instances/inst1/databases/db1",
+ schema: "public",
+ table: "users",
+ },
+ mode: "WORKSHEET",
+ });
+ expect(mocks.navigateReplace).not.toHaveBeenCalledWith({
+ name: "sql-editor.project",
+ params: {
+ project: "proj1",
+ },
+ query: {
+ table: "users",
+ },
+ });
+
+ unmount();
+ });
+
+ test("updates a stale database URL when the active tab is disconnected", async () => {
+ mocks.tabsState.tabsById.set("tab-blank", {
+ id: "tab-blank",
+ worksheet: "",
+ connection: {
+ instance: "",
+ database: "",
+ },
+ } as SQLEditorTab);
+ mocks.tabsState.currentTabId = "tab-blank";
+ mocks.tabsState.addTab.mockImplementation(
+ (payload: Partial<SQLEditorTab> = {}) => {
+ const tab = {
+ id: "tab-from-route",
+ worksheet: "",
+ connection: {
+ instance: "",
+ database: "",
+ },
+ ...payload,
+ } as SQLEditorTab;
+ mocks.tabsState.tabsById.set(tab.id, tab);
+ return tab;
+ }
+ );
+
+ const { unmount } = renderShell();
+
+ await act(async () => {
+ await Promise.resolve();
+ await Promise.resolve();
+ await Promise.resolve();
+ });
+
+ expect(mocks.navigateReplace).toHaveBeenCalledWith({
+ name: "sql-editor.project",
+ params: {
+ project: "proj1",
+ },
+ query: {},
+ });
+
+ unmount();
+ });
+});
diff --git a/frontend/src/react/components/sql-editor/SQLEditorRouteShell.tsx b/frontend/src/react/components/sql-editor/SQLEditorRouteShell.tsx
index c92145af70..eee4bd0ad6 100644
--- a/frontend/src/react/components/sql-editor/SQLEditorRouteShell.tsx
+++ b/frontend/src/react/components/sql-editor/SQLEditorRouteShell.tsx
@@ -37,9 +37,9 @@ import {
isValidDatabaseName,
isValidInstanceName,
isValidProjectName,
+ type SQLEditorConnection,
} from "@/types";
import {
- emptySQLEditorConnection,
extractDatabaseResourceName,
extractInstanceResourceName,
extractProjectResourceName,
@@ -260,9 +260,26 @@ export function SQLEditorRouteShell() {
// 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;
+ if (
+ getSQLEditorEditorState().project !== database.project &&
+ !(await maybeSwitchProject(database.project))
+ ) {
+ getSQLEditorEditorState().setProject(database.project);
+ }
const { instance } = extractDatabaseResourceName(database.name);
- const connection = { instance, database: database.name };
+ const connection: SQLEditorConnection = {
+ instance,
+ database: database.name,
+ };
+ const schema = route.query.schema;
+ const table = route.query.table;
+ if (typeof schema === "string" && schema) {
+ connection.schema = schema;
+ }
+ if (typeof table === "string" && table) {
+ connection.table = table;
+ connection.schema ??= "";
+ }
getSQLEditorTabsState().addTab({
connection,
mode: DEFAULT_SQL_EDITOR_TAB_MODE,
@@ -413,16 +430,21 @@ export function SQLEditorRouteShell() {
"project",
"schema",
"database",
+ "table",
"panel"
) as Record<string, string>;
- // Touch the connection so the omit() above sees the live tab —
- // identical to the Vue version's `connection.value` read at the top.
const tabsState = getSQLEditorTabsState();
- void (
- tabsState.tabsById.get(tabsState.currentTabId)?.connection ??
- emptySQLEditorConnection()
- );
+ const currentTab = tabsState.tabsById.get(tabsState.currentTabId);
+
+ if (
+ currentRoute.name === SQL_EDITOR_DATABASE_MODULE &&
+ !vals.sheetName &&
+ !vals.dbName &&
+ !currentTab
+ ) {
+ return;
+ }
if (vals.sheetName) {
const sheet = useAppStore.getState().getWorksheetByName(vals.sheetName);
diff --git a/frontend/src/react/pages/project/ProjectDatabaseDetailPage.tsx b/frontend/src/react/pages/project/ProjectDatabaseDetailPage.tsx
index b2f101d839..91389bf7f3 100644
--- a/frontend/src/react/pages/project/ProjectDatabaseDetailPage.tsx
+++ b/frontend/src/react/pages/project/ProjectDatabaseDetailPage.tsx
@@ -195,11 +195,7 @@ export function ProjectDatabaseDetailPage({
description={
<div className="flex flex-row items-center justify-between gap-x-2">
<div>{t("instance.no-environment")}</div>
- <Button
- appearance="link"
- size="sm"
- onClick={handleSetEnvironment}
- >
+ <Button size="sm" onClick={handleSetEnvironment}>
{t("database.edit-environment")}
</Button>
</div>
diff --git a/frontend/src/react/pages/settings/EnvironmentsPage.tsx b/frontend/src/react/pages/settings/EnvironmentsPage.tsx
index 3e3d7529b6..332de28e45 100644
--- a/frontend/src/react/pages/settings/EnvironmentsPage.tsx
+++ b/frontend/src/react/pages/settings/EnvironmentsPage.tsx
@@ -823,10 +823,10 @@ function EnvironmentDetail({
{/* Tier section */}
<FormField
title={
- <>
+ <span className="inline-flex items-center gap-x-1">
{t("policy.environment-tier.name")}
<FeatureBadge feature={PlanFeature.FEATURE_ENVIRONMENT_TIERS} />
- </>
+ </span>
}
description={
<>
@@ -1131,7 +1131,14 @@ function CreateSheet({
{/* Tier */}
<FormField
- title={<>{t("policy.environment-tier.name")}</>}
+ title={
+ <span className="inline-flex items-center gap-x-1">
+ {t("policy.environment-tier.name")}
+ <FeatureBadge
+ feature={PlanFeature.FEATURE_ENVIRONMENT_TIERS}
+ />
+ </span>
+ }
description={
<>
{t("policy.environment-tier.description", { newline: "\n" })}
diff --git a/frontend/src/react/pages/settings/EnvironmentsPageLayout.test.ts b/frontend/src/react/pages/settings/EnvironmentsPageLayout.test.ts
new file mode 100644
index 0000000000..cbe99a48f0
--- /dev/null
+++ b/frontend/src/react/pages/settings/EnvironmentsPageLayout.test.ts
@@ -0,0 +1,26 @@
+import { readFileSync } from "node:fs";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+import { describe, expect, test } from "vitest";
+
+const settingsDir = dirname(fileURLToPath(import.meta.url));
+
+const readEnvironmentsPage = () =>
+ readFileSync(join(settingsDir, "EnvironmentsPage.tsx"), "utf8");
+
+describe("EnvironmentsPage layout", () => {
+ test("keeps the environment tier feature badge spaced from both titles", () => {
+ const source = readEnvironmentsPage();
+
+ expect(
+ source.match(/<span className="inline-flex items-center gap-x-1">/g)
+ ?.length
+ ).toBeGreaterThanOrEqual(2);
+ expect(source).toContain('{t("policy.environment-tier.name")}');
+ expect(
+ source.match(
+ /<FeatureBadge\s+feature=\{PlanFeature\.FEATURE_ENVIRONMENT_TIERS\}\s*\/>/g
+ )?.length
+ ).toBeGreaterThanOrEqual(2);
+ });
+});
diff --git a/frontend/src/react/router/index.ts b/frontend/src/react/router/index.ts
index bddf0ee3d1..e86885b97e 100644
--- a/frontend/src/react/router/index.ts
+++ b/frontend/src/react/router/index.ts
@@ -184,13 +184,13 @@ function assembleRoute(
/** React-router-backed current route, shaped like the legacy bridge. */
export function useCurrentRoute(): ReactRoute {
const location = useLocation();
- const params = useParams();
const matches = useMatches();
- return assembleRoute(
- location,
- matches,
- params as Record<string, string | string[] | undefined>
- );
+ const params = useParams();
+ const leafParams = (matches.at(-1)?.params ?? params) as Record<
+ string,
+ string | string[] | undefined
+ >;
+ return assembleRoute(location, matches, leafParams);
}
// Non-hook snapshot of the current route, read from the registered data router
diff --git a/frontend/src/react/router/navigation.test.ts b/frontend/src/react/router/navigation.test.ts
index 98d7f9a55e..b17a0cee38 100644
--- a/frontend/src/react/router/navigation.test.ts
+++ b/frontend/src/react/router/navigation.test.ts
@@ -1,4 +1,5 @@
import { beforeEach, describe, expect, test, vi } from "vitest";
+import { SQL_EDITOR_DATABASE_MODULE } from "./handles";
import {
navigateByName,
navigateToPath,
@@ -6,6 +7,7 @@ import {
setAppRouter,
setRouteNameIndex,
} from "./navigation";
+import { buildRouteNameIndex } from "./routes";
beforeEach(() => {
setRouteNameIndex(
@@ -76,6 +78,25 @@ describe("navigation resolvePath", () => {
})
).toBe("/projects/p1/issues/i1");
});
+
+ test("resolves the SQL Editor database route with all resource params", () => {
+ setRouteNameIndex(buildRouteNameIndex());
+
+ expect(
+ resolvePath(SQL_EDITOR_DATABASE_MODULE, {
+ params: {
+ project: "new-project-ticw",
+ instance: "new-instance-rr9e",
+ database: "bytebase-3.16.1",
+ },
+ query: {
+ schema: "public",
+ },
+ })
+ ).toBe(
+ "/sql-editor/projects/new-project-ticw/instances/new-instance-rr9e/databases/bytebase-3.16.1?schema=public"
+ );
+ });
});
describe("navigation dispatch", () => {
diff --git a/frontend/src/react/router/useCurrentRoute.integration.test.tsx b/frontend/src/react/router/useCurrentRoute.integration.test.tsx
new file mode 100644
index 0000000000..4889c74bca
--- /dev/null
+++ b/frontend/src/react/router/useCurrentRoute.integration.test.tsx
@@ -0,0 +1,63 @@
+import { act } from "react";
+import { createRoot } from "react-dom/client";
+import { createMemoryRouter, Outlet, RouterProvider } from "react-router-dom";
+import { describe, expect, test } from "vitest";
+import { SQL_EDITOR_DATABASE_MODULE } from "./handles";
+import { type ReactRoute, useCurrentRoute } from "./index";
+
+(
+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+describe("useCurrentRoute with real router context", () => {
+ test("returns leaf SQL Editor params when called from the parent layout", async () => {
+ let route: ReactRoute | undefined;
+ const CaptureFromParentLayout = () => {
+ route = useCurrentRoute();
+ return <Outlet />;
+ };
+
+ const router = createMemoryRouter(
+ [
+ {
+ path: "/sql-editor",
+ handle: { name: "sql-editor" },
+ element: <CaptureFromParentLayout />,
+ children: [
+ {
+ path: "projects/:project/instances/:instance/databases/:database",
+ handle: { name: SQL_EDITOR_DATABASE_MODULE },
+ element: null,
+ },
+ ],
+ },
+ ],
+ {
+ initialEntries: [
+ "/sql-editor/projects/proj1/instances/inst1/databases/db1?schema=public",
+ ],
+ }
+ );
+
+ const container = document.createElement("div");
+ document.body.appendChild(container);
+ const root = createRoot(container);
+
+ await act(async () => {
+ root.render(<RouterProvider router={router} />);
+ });
+
+ expect(route?.name).toBe(SQL_EDITOR_DATABASE_MODULE);
+ expect(route?.params).toEqual({
+ project: "proj1",
+ instance: "inst1",
+ database: "db1",
+ });
+ expect(route?.query).toEqual({ schema: "public" });
+
+ act(() => {
+ root.unmount();
+ container.remove();
+ });
+ });
+});
diff --git a/frontend/src/react/router/useCurrentRoute.test.tsx b/frontend/src/react/router/useCurrentRoute.test.tsx
new file mode 100644
index 0000000000..cf54fe15a2
--- /dev/null
+++ b/frontend/src/react/router/useCurrentRoute.test.tsx
@@ -0,0 +1,72 @@
+import { act } from "react";
+import { createRoot } from "react-dom/client";
+import { beforeEach, describe, expect, test, vi } from "vitest";
+import { type ReactRoute, useCurrentRoute } from "./index";
+
+(
+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+const mocks = vi.hoisted(() => ({
+ location: {
+ pathname: "/sql-editor/projects/proj1/instances/inst1/databases/db1",
+ search: "?schema=public",
+ hash: "",
+ },
+ parentParams: {},
+ matches: [
+ {
+ handle: { name: "sql-editor" },
+ params: {},
+ },
+ {
+ handle: { name: "sql-editor.database" },
+ params: {
+ project: "proj1",
+ instance: "inst1",
+ database: "db1",
+ },
+ },
+ ],
+}));
+
+vi.mock("react-router-dom", () => ({
+ useLocation: () => mocks.location,
+ useMatches: () => mocks.matches,
+ useNavigate: () => vi.fn(),
+ useParams: () => mocks.parentParams,
+}));
+
+beforeEach(() => {
+ vi.clearAllMocks();
+});
+
+describe("useCurrentRoute", () => {
+ test("uses leaf match params when rendered from a parent layout", () => {
+ let route: ReactRoute | undefined;
+ const CaptureRoute = () => {
+ route = useCurrentRoute();
+ return null;
+ };
+
+ const container = document.createElement("div");
+ document.body.appendChild(container);
+ const root = createRoot(container);
+
+ act(() => {
+ root.render(<CaptureRoute />);
+ });
+
+ expect(route?.name).toBe("sql-editor.database");
+ expect(route?.params).toEqual({
+ project: "proj1",
+ instance: "inst1",
+ database: "db1",
+ });
+
+ act(() => {
+ root.unmount();
+ container.remove();
+ });
+ });
+});
diff --git a/frontend/src/react/stores/sqlEditor/tab.test.ts b/frontend/src/react/stores/sqlEditor/tab.test.ts
index 9fa7bebe57..fc66369d38 100644
--- a/frontend/src/react/stores/sqlEditor/tab.test.ts
+++ b/frontend/src/react/stores/sqlEditor/tab.test.ts
@@ -1,4 +1,5 @@
-import { afterEach, beforeEach, describe, expect, test } from "vitest";
+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
+import { storageKeySqlEditorTabs } from "@/utils";
import {
__resetTabStoreProjectCursor,
getSQLEditorTabsState,
@@ -6,6 +7,38 @@ import {
useSQLEditorTabsStore,
} from "./tab";
+const mocks = vi.hoisted(() => ({
+ loadCurrentUser: vi.fn(async () => undefined),
+ getOrFetchWorksheetByName: vi.fn(),
+}));
+
+vi.mock("@/react/lib/sqlEditorConnection", () => ({
+ extractWorksheetConnection: vi.fn(async () => ({
+ instance: "instances/mysql-instance",
+ database: "instances/mysql-instance/databases/bytebase",
+ })),
+ isConnectedSQLEditorTab: vi.fn(() => true),
+}));
+
+vi.mock("@/react/stores/app", () => ({
+ useAppStore: {
+ getState: () => ({
+ currentUser: {
+ email: "[email protected]",
+ workspace: "",
+ },
+ isSaaSMode: () => false,
+ loadCurrentUser: mocks.loadCurrentUser,
+ getOrFetchWorksheetByName: mocks.getOrFetchWorksheetByName,
+ }),
+ },
+}));
+
+vi.mock("@/store/modules/sqlEditor/legacy/migration", () => ({
+ migrateDraftsFromCache: vi.fn(async () => undefined),
+ migrateTabViewState: vi.fn(),
+}));
+
const storage = new Map<string, string>();
const originalLocalStorage = globalThis.localStorage;
@@ -35,6 +68,16 @@ beforeEach(() => {
});
getSQLEditorTabsState().reset();
__resetTabStoreProjectCursor();
+ mocks.loadCurrentUser.mockClear();
+ mocks.getOrFetchWorksheetByName.mockImplementation(async (name: string) => ({
+ name,
+ project: name.startsWith("projects/project-sample/")
+ ? "projects/project-sample"
+ : "projects/aaa",
+ database: "instances/mysql-instance/databases/bytebase",
+ content: new TextEncoder().encode("SELECT 1"),
+ contentSize: BigInt(new TextEncoder().encode("SELECT 1").length),
+ }));
});
afterEach(() => {
@@ -223,4 +266,32 @@ describe("useSQLEditorTabsStore", () => {
expect(count).toBeGreaterThanOrEqual(3);
unsubscribe();
});
+
+ test("initProject ignores persisted worksheets from other projects", async () => {
+ storage.set(
+ storageKeySqlEditorTabs("", "projects/aaa", "[email protected]"),
+ JSON.stringify([
+ {
+ id: "cross-project-tab",
+ worksheet: "projects/project-sample/worksheets/sample-sheet",
+ mode: "WORKSHEET",
+ },
+ {
+ id: "same-project-tab",
+ worksheet: "projects/aaa/worksheets/aaa-sheet",
+ mode: "WORKSHEET",
+ },
+ ])
+ );
+
+ await getSQLEditorTabsState().initProject("projects/aaa");
+
+ const state = useSQLEditorTabsStore.getState();
+ expect(state.tabsById.has("cross-project-tab")).toBe(false);
+ expect(state.tabsById.has("same-project-tab")).toBe(true);
+ expect(state.openTmpTabList.map((tab) => tab.id)).toEqual([
+ "same-project-tab",
+ ]);
+ expect(state.currentTabId).toBe("same-project-tab");
+ });
});
diff --git a/frontend/src/react/stores/sqlEditor/tab.ts b/frontend/src/react/stores/sqlEditor/tab.ts
index 4065838342..879d39f427 100644
--- a/frontend/src/react/stores/sqlEditor/tab.ts
+++ b/frontend/src/react/stores/sqlEditor/tab.ts
@@ -437,6 +437,7 @@ const hydrateProjectTabs = async (project: string): Promise<void> => {
.getState()
.getOrFetchWorksheetByName(persisted.worksheet, true);
if (!worksheet) continue;
+ if (worksheet.project !== project) continue;
const statement = getSheetStatement(worksheet);
const connection = await extractWorksheetConnection(worksheet);
diff --git a/frontend/src/react/stores/sqlEditor/worksheet.test.ts b/frontend/src/react/stores/sqlEditor/worksheet.test.ts
index 903c3927a6..76c1809205 100644
--- a/frontend/src/react/stores/sqlEditor/worksheet.test.ts
+++ b/frontend/src/react/stores/sqlEditor/worksheet.test.ts
@@ -1,5 +1,6 @@
import { beforeEach, describe, expect, test, vi } from "vitest";
import { create, type StoreApi } from "zustand";
+import { getSQLEditorEditorState } from "./editor";
import type {
QueryHistorySlice,
SQLEditorStoreState,
@@ -80,6 +81,7 @@ const piniaMocks = vi.hoisted(() => ({
upsertWorksheetOrganizer: vi.fn(),
createWorksheet: vi.fn(),
fetchProject: vi.fn(),
+ loadProjectIamPolicy: vi.fn(),
},
}));
@@ -143,6 +145,7 @@ beforeEach(() => {
});
piniaMocks.editorStore.project = "projects/default";
piniaMocks.editorStore.projectContextReady = true;
+ getSQLEditorEditorState().setProject("");
});
describe("worksheet save slice — autoSaveController", () => {
@@ -182,4 +185,19 @@ describe("worksheet save slice — maybeSwitchProject", () => {
expect(result).toBeUndefined();
expect(piniaMocks.editorStore.setProject).not.toHaveBeenCalled();
});
+
+ test("switches project even when project IAM policy preload fails", async () => {
+ piniaMocks.worksheetStore.fetchProject.mockResolvedValue({
+ name: "projects/aaa",
+ });
+ piniaMocks.worksheetStore.loadProjectIamPolicy.mockRejectedValue(
+ new Error("permission denied")
+ );
+
+ const store = makeStore();
+ const result = await store.getState().maybeSwitchProject("projects/aaa");
+
+ expect(result).toBe("projects/aaa");
+ expect(getSQLEditorEditorState().project).toBe("projects/aaa");
+ });
});
diff --git a/frontend/src/react/stores/sqlEditor/worksheet.ts b/frontend/src/react/stores/sqlEditor/worksheet.ts
index cd42cd465d..3a97079de1 100644
--- a/frontend/src/react/stores/sqlEditor/worksheet.ts
+++ b/frontend/src/react/stores/sqlEditor/worksheet.ts
@@ -46,7 +46,10 @@ export const createWorksheetSaveSlice: SQLEditorSliceCreator<
// Pinia permission store falls back to `app.projectPoliciesByName` when
// its own cache is empty, so populating the app `iam` slice is enough
// (see `src/store/modules/v1/permission.ts`).
- await useAppStore.getState().loadProjectIamPolicy(project.name);
+ await useAppStore
+ .getState()
+ .loadProjectIamPolicy(project.name)
+ .catch(() => undefined);
editorStore.setProject(project.name);
await sqlEditorEvents.emit("project-context-ready", {
project: project.name,