Skip to content

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

refactor(react): sql editor components and bugfix (#20157)

ecmadaob6c9b1879720
diff --git a/docs/superpowers/specs/2026-04-28-sql-editor-react-migration-stage-18-design.md b/docs/superpowers/specs/2026-04-28-sql-editor-react-migration-stage-18-design.md
new file mode 100644
index 0000000000..d3e2bd234e
--- /dev/null
+++ b/docs/superpowers/specs/2026-04-28-sql-editor-react-migration-stage-18-design.md
@@ -0,0 +1,142 @@
+# SQL Editor React Migration — Stage 18 Design
+
+**Date:** 2026-04-28
+**Author:** [email protected]
+**Status:** Draft
+
+## 1. Goal & non-goals
+
+**Goal:** Migrate the four remaining `ResultPanel/` Vue surfaces that
+don't transitively render `ResultView` (so Stage 20's perf spike on
+`ResultView` itself can land cleanly), plus the one chain dep that
+`BatchQuerySelect` pulls in (`DataExportButton`) and a small
+`DatabaseTable` extension. Single-track stage; `DiagramPanel`/`SchemaDiagram`
+have their own stage (19) since cytoscape is its own subsystem (~2,265 LOC).
+
+**Non-goals:**
+- `EditorCommon/ResultView/*` — Stage 20 (perf-spike headline).
+- `ResultPanel/DatabaseQueryContext.vue` — directly mounts `ResultViewV1`,
+ co-migrates with Stage 20.
+- `Panels/DiagramPanel/DiagramPanel.vue` + `components/SchemaDiagram/*`
+ — Stage 19, its own focused stage.
+- The five host shells (`Panels`, `EditorPanel`, `StandardPanel`,
+ `TerminalPanel`, `ResultPanel`, `SQLEditorHomePage`) — Stage 21.
+- Visual / behavioral changes — parity only.
+
+## 2. Inventory
+
+**In scope (~444 LOC of `sql-editor/` Vue + 414 LOC `DataExportButton` chain dep + small `DatabaseTable` extension):**
+
+| File | LOC | Notes |
+|---|---|---|
+| `EditorPanel/ResultPanel/BatchQuerySelect.vue` | 359 | Tab strip + batch-export button. The trickiest part is `<DataExportButton>` with its `:database-list` + `:show-selection` + `:pagination` form slot. |
+| `EditorPanel/ResultPanel/ContextMenu.vue` | 85 | Imperative `defineExpose({ show, hide })` API that `BatchQuerySelect` calls via `contextMenuRef.value?.show(index, $event)`. Convert to a Pinia/module store during the port to break the imperative coupling. |
+| `components/DataExportButton.vue` | 414 | Outside `sql-editor/` but a hard dep. Drawer + format picker (CSV/JSON/SQL/XLSX) + password toggle + validate hook + multi-file zip download flow. No React equivalent today (`DataExportPrepSheet.tsx` is a different surface — project-level export wizard, doesn't fit). |
+
+**`DatabaseTable` extension** (small, no separate file):
+- React `DatabaseTable.tsx` currently takes `filter: DatabaseFilter` and fetches its own list from the server.
+- Add an optional `databases?: Database[]` prop that, when present, skips the fetch and renders the provided list directly.
+- `BatchQuerySelect` consumes it that way (Vue does the same: `:database-list="databaseList"`).
+
+### Out of scope (later stages)
+
+```
+Panels/DiagramPanel/DiagramPanel.vue → Stage 19 (cytoscape subsystem)
+components/SchemaDiagram/* (44 files) → Stage 19
+EditorCommon/ResultView/* → Stage 20 (perf spike)
+ResultPanel/DatabaseQueryContext.vue → Stage 20 (mounts ResultViewV1)
+ResultPanel/ResultPanel.vue → Stage 21 (host shell)
+StandardPanel/StandardPanel.vue → Stage 21
+TerminalPanel/TerminalPanel.vue → Stage 21
+Panels/Panels.vue → Stage 21
+EditorPanel/EditorPanel.vue → Stage 21
+SQLEditorHomePage.vue → Stage 21
+SQLEditorPage.vue → Stage 21
+```
+
+## 3. External deps & primitives
+
+| Vue dep | React replacement | Status |
+|---|---|---|
+| `NDrawer` (Vue Naive UI drawer) for `DataExportButton` | shadcn `Sheet` (`@/react/components/ui/sheet`) — already used by other React drawers in the codebase | ✓ |
+| `NButton` (DataExportButton trigger) | `Button` | ✓ |
+| `NSelect` (export format picker) | `Select` | ✓ |
+| `NCheckbox` (password toggle) | native `<input type="checkbox">` (matches Stage 16/17 panel checkboxes) | ✓ |
+| `NDropdown` (`ContextMenu`) | shadcn `DropdownMenu` — already used by `OpenAIButton`, `EditorAction` | ✓ |
+| `NTooltip` (`BatchQuerySelect` "show empty" toggle, batch-export tooltip) | shared `Tooltip` (passes through children when content is falsy — Stage 17 lesson) | ✓ |
+| `NScrollbar` (`BatchQuerySelect` horizontal scroll) | native `overflow-x-auto` | ✓ |
+| `DatabaseV1Table` (Vue) | extended React `DatabaseTable` with `databases?` opt-out | New small extension |
+| `useEmitteryEventListener` (Vue composable) | `useEffect` + direct `.on()` (pattern from Stage 16+17) | ✓ |
+| `provideResultTabListContext` (Vue provide/inject for `ContextMenu` ↔ `BatchQuerySelect`) | Pinia store + module-level emittery (mirrors `aiContextEvents` from Stage 16) | New small store |
+
+## 4. Architecture & phases
+
+Single track. Order matters.
+
+### Phase 1 — Foundations (`DatabaseTable` extension + `DataExportButton`)
+
+1. Extend React `DatabaseTable.tsx` with `databases?: Database[]` opt-out. When provided, skip the fetch path entirely; render the given list with the existing selection/highlight/sort UI. Verify the existing settings page consumer still works through the unchanged filter path.
+2. Port `DataExportButton.tsx`. Substantial — drawer with form slot, format picker, password input, "Maximum N rows" warning, `validate()` predicate, multi-file zip download via the existing `sqlStore.exportData` API. Reuse `Sheet` + `Select` + `Button`. The `form` slot becomes a React `children` or `formContent` prop.
+
+**Deliverables:** 2 new React surfaces + 1 small extension + 3 tests.
+
+### Phase 2 — `ContextMenu` + Pinia state replacing the imperative coupling
+
+1. Build `Panels/common/resultTabContext.ts` — Pinia store + emittery singleton replacing Vue's `provideResultTabListContext`. Holds `contextMenu` state (`{ x, y, index } | undefined`) and a `close-tab` event channel.
+2. Port `ContextMenu.tsx` reading from the Pinia store + emitting on `close-tab`. No imperative `defineExpose` API — driven entirely by store state.
+
+**Deliverables:** 1 store + 1 React surface + 1 mount shim + 1 test.
+
+### Phase 3 — `BatchQuerySelect` + caller swap
+
+1. Port `BatchQuerySelect.tsx`:
+ - Tab strip with environment-tinted buttons (env color logic same as `TabItem`)
+ - "Show/hide empty results" toggle
+ - `DataExportButton` mount (form slot = the extended `DatabaseTable`)
+ - Right-click on a tab fires `contextMenuStore.open(x, y, index)` — no more imperative `ref.show()`
+2. `ResultPanel.vue` swaps `<BatchQuerySelect>` and `<ContextMenu>` to `<ReactPageMount>` calls. `ResultPanel.vue` itself stays Vue.
+3. Delete the Vue files (`BatchQuerySelect.vue`, `ContextMenu.vue`, `ResultPanel/context.ts`).
+4. `components/DataExportButton.vue` — keep around if any non-SQL-editor Vue surface still imports it; otherwise delete.
+
+**Deliverables:** 1 React surface + 1 mount shim + 1 test + Vue file deletions.
+
+## 5. Per-phase checklist
+
+### Phase 1 — Foundations (`DatabaseTable` extension + `DataExportButton`)
+- [ ] React `DatabaseTable` `databases?: Database[]` opt-out + test (verify settings-page consumer through filter path still works)
+- [ ] `DataExportButton.tsx` + shim + tests (open drawer, validate predicate, format pick CSV/JSON/SQL/XLSX, password toggle, multi-file zip download)
+- [ ] i18n keys synced for export drawer
+
+### Phase 2 — `ContextMenu` + Pinia state
+- [ ] `Panels/common/resultTabContext.ts` Pinia store (state: `{ x, y, index } | undefined`) + emittery (`close-tab` channel)
+- [ ] `ContextMenu.tsx` + shim + test (right-click → `contextMenuStore.open(x, y, index)`, item select → `events.emit("close-tab", { kind })`, ESC/outside-click closes)
+
+### Phase 3 — `BatchQuerySelect` + caller swap
+- [ ] `BatchQuerySelect.tsx` + shim + test (env-color tinting, tab close, show-empty toggle, batch-export selection table via extended `DatabaseTable`)
+- [ ] `ResultPanel.vue` swaps `<BatchQuerySelect>` and `<ContextMenu>` to `<ReactPageMount>` calls
+- [ ] Delete `BatchQuerySelect.vue`, `ContextMenu.vue`, and Vue `ResultPanel/context.ts`
+- [ ] Delete `components/DataExportButton.vue` if no remaining Vue caller; otherwise leave it for a follow-up
+- [ ] Gates green
+
+## 6. Manual UX verification
+
+- **DataExportButton** — open drawer, switch formats, pick "ZIP password", verify disabled state when validate predicate fails, click Export → multi-file zip downloads with one entry per selected database.
+- **BatchQuerySelect** — run `SELECT 1` against a batch of 3 databases. Tab strip renders 3 env-tinted tabs, one with "(empty)" if the query returns 0 rows, click to select, right-click → context menu close actions, Export button opens drawer with pre-filtered database list.
+- **ContextMenu** — Close, Close others, Close to the right, Close all behave the same as Vue.
+
+## 7. Out of scope (deferred)
+
+- `Panels/DiagramPanel/DiagramPanel.vue` + `components/SchemaDiagram/*` — Stage 19
+- `EditorCommon/ResultView/*` and `ResultPanel/DatabaseQueryContext.vue` — Stage 20 (perf spike)
+- The host shells (`Panels`, `EditorPanel`, `StandardPanel`, `TerminalPanel`, `ResultPanel`, `SQLEditorHomePage`, `SQLEditorPage`) — Stage 21
+- AI plugin port — separate effort (currently hosted by Vue at `Panels.vue`/`StandardPanel.vue` via the Stage 16/17 hoist)
+
+## 8. Risks & open questions
+
+- **`DataExportButton` is the headline of this stage.** 414 LOC of drawer + form-slot + zip download is non-trivial. The React port has multi-stage value (any "export to file" surface can reuse it), so the LOC is justified even though it sits outside `sql-editor/`.
+
+- **`ContextMenu` imperative API removal.** Currently `BatchQuerySelect` calls `contextMenuRef.value?.show(index, $event)` — this is a `defineExpose` imperative API. Replacing it with a Pinia store + emittery is a clean refactor but slightly changes the abstraction (state-driven instead of imperative). Mirrors how Stage 17 replaced `MonacoEditor.getActiveStatement()` ref API with the `activeStatementRef` shared shallowRef.
+
+- **`DatabaseV1Table`'s pre-fetched-list mode and React `DatabaseTable`'s server-fetch mode coexisting.** The `databases?: Database[]` opt-out is straightforward but needs careful interaction with the existing pagination/sort UI. Test both paths in Phase 1.
+
+- **AI plugin still Vue.** The Vue host at `Panels.vue` currently wraps its content in an `<NSplit>` with `<AIChatToSQL>` when `showAIPanel && isShowingCode`. `BatchQuerySelect`/`ContextMenu` don't host code surfaces, so this hoist stays untouched in Stage 18. (Stage 21 will revisit when `Panels.vue` itself migrates to React.)
diff --git a/frontend/src/react/components/DataExportButton.tsx b/frontend/src/react/components/DataExportButton.tsx
new file mode 100644
index 0000000000..2fa9bbdc11
--- /dev/null
+++ b/frontend/src/react/components/DataExportButton.tsx
@@ -0,0 +1,441 @@
+import dayjs from "dayjs";
+import saveAs from "file-saver";
+import JSZip from "jszip";
+import { ChevronDown, Download } from "lucide-react";
+import {
+ type ReactNode,
+ useCallback,
+ useEffect,
+ useMemo,
+ useState,
+} from "react";
+import { useTranslation } from "react-i18next";
+import { Button, type ButtonProps } from "@/react/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogTitle,
+} from "@/react/components/ui/dialog";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from "@/react/components/ui/dropdown-menu";
+import { Input } from "@/react/components/ui/input";
+import { RadioGroup, RadioGroupItem } from "@/react/components/ui/radio-group";
+import {
+ Sheet,
+ SheetBody,
+ SheetContent,
+ SheetFooter,
+ SheetHeader,
+ SheetTitle,
+} from "@/react/components/ui/sheet";
+import { Tooltip } from "@/react/components/ui/tooltip";
+import { cn } from "@/react/lib/utils";
+import { pushNotification } from "@/store";
+import { ExportFormat } from "@/types/proto-es/v1/common_pb";
+import { MaxRowCountSelect } from "./MaxRowCountSelect";
+
+export type DownloadContent = {
+ content: Uint8Array;
+ filename: string;
+};
+
+export interface ExportOption {
+ limit: number;
+ format: ExportFormat;
+ password: string;
+}
+
+export type DataExportRequest = {
+ options: ExportOption;
+ resolve: (content: DownloadContent[]) => void;
+ reject: (reason?: unknown) => void;
+};
+
+type Size = "tiny" | "sm" | "md" | "lg";
+type ViewMode = "DRAWER" | "DROPDOWN";
+
+interface DataExportButtonProps {
+ size?: Size;
+ disabled?: boolean;
+ supportFormats: ExportFormat[];
+ supportPassword?: boolean;
+ viewMode: ViewMode;
+ tooltip?: string;
+ text?: string;
+ validate?: (option: ExportOption) => boolean;
+ maximumExportCount?: number;
+ /** Custom form content rendered above the row-count / format / password fields in DRAWER mode. */
+ formContent?: ReactNode;
+ onExport: (req: DataExportRequest) => void;
+ className?: string;
+}
+
+const SIZE_TO_BUTTON: Record<Size, ButtonProps["size"]> = {
+ tiny: "icon",
+ sm: "sm",
+ md: "default",
+ lg: "lg",
+};
+
+const ROW_COUNT_PRESET = [1, 100, 500, 1000, 5000, 10000, 100000];
+
+const computeMaximumPreset = (maximum: number) => {
+ const list = ROW_COUNT_PRESET.filter((n) => n <= maximum);
+ if (maximum !== Number.MAX_VALUE && !list.includes(maximum)) {
+ list.push(maximum);
+ }
+ return list[list.length - 1] ?? 1000;
+};
+
+const getExportFileType = (format: ExportFormat) => {
+ switch (format) {
+ case ExportFormat.CSV:
+ return "text/csv";
+ case ExportFormat.JSON:
+ return "application/json";
+ case ExportFormat.SQL:
+ return "application/sql";
+ case ExportFormat.XLSX:
+ return "application/vnd.ms-excel";
+ default:
+ return "application/octet-stream";
+ }
+};
+
+const toBlob = (
+ { content, filename }: DownloadContent,
+ format: ExportFormat
+) => {
+ const isZip = filename.endsWith(".zip");
+ const fileType = isZip ? "application/zip" : getExportFileType(format);
+ const buffer = content.buffer.slice(
+ content.byteOffset,
+ content.byteOffset + content.byteLength
+ ) as ArrayBuffer;
+ return new Blob([buffer], { type: fileType });
+};
+
+const downloadSingle = (entry: DownloadContent, format: ExportFormat) => {
+ const blob = toBlob(entry, format);
+ const url = window.URL.createObjectURL(blob);
+ const link = document.createElement("a");
+ link.download = entry.filename;
+ link.href = url;
+ link.click();
+ window.URL.revokeObjectURL(url);
+};
+
+const downloadZip = async (
+ contents: DownloadContent[],
+ format: ExportFormat
+) => {
+ const zip = new JSZip();
+ for (const entry of contents) {
+ zip.file(entry.filename, toBlob(entry, format));
+ }
+ const zipFile = await zip.generateAsync({ type: "blob" });
+ saveAs(zipFile, `download_${dayjs().format("YYYY-MM-DDTHH-mm-ss")}.zip`);
+};
+
+const downloadAll = async (
+ contents: DownloadContent[],
+ format: ExportFormat
+) => {
+ if (contents.length === 0) return;
+ if (contents.length === 1) {
+ downloadSingle(contents[0], format);
+ return;
+ }
+ await downloadZip(contents, format);
+};
+
+/**
+ * React port of `frontend/src/components/DataExportButton.vue`.
+ *
+ * - DRAWER view: opens a Sheet with row-count / format / optional password
+ * fields, plus a `formContent` slot for caller-provided fields (e.g. the
+ * batch-export database picker).
+ * - DROPDOWN view: a hover dropdown of formats; if `supportPassword` is set,
+ * selecting a format opens a small Dialog to capture an optional password.
+ */
+export function DataExportButton({
+ size = "sm",
+ disabled = false,
+ supportFormats,
+ supportPassword = false,
+ viewMode,
+ tooltip,
+ text,
+ validate,
+ maximumExportCount = Number.MAX_VALUE,
+ formContent,
+ onExport,
+ className,
+}: DataExportButtonProps) {
+ const { t } = useTranslation();
+
+ const [isRequesting, setIsRequesting] = useState(false);
+ const [showDrawer, setShowDrawer] = useState(false);
+ const [showPasswordDialog, setShowPasswordDialog] = useState(false);
+
+ const presetMax = useMemo(
+ () => computeMaximumPreset(maximumExportCount),
+ [maximumExportCount]
+ );
+ const defaultLimit = useMemo(() => Math.min(presetMax, 1000), [presetMax]);
+
+ const [limit, setLimit] = useState<number>(defaultLimit);
+ const [format, setFormat] = useState<ExportFormat>(supportFormats[0]);
+ const [password, setPassword] = useState("");
+
+ const resetForm = useCallback(() => {
+ setLimit(defaultLimit);
+ setFormat(supportFormats[0]);
+ setPassword("");
+ }, [defaultLimit, supportFormats]);
+
+ // Reset form whenever the drawer opens, mirroring the Vue watcher.
+ useEffect(() => {
+ if (showDrawer) {
+ resetForm();
+ }
+ }, [showDrawer, resetForm]);
+
+ // Clear password each time the password dialog opens.
+ useEffect(() => {
+ if (showPasswordDialog) {
+ setPassword("");
+ }
+ }, [showPasswordDialog]);
+
+ const buttonText = text ?? t("common.export");
+
+ const currentOption: ExportOption = useMemo(
+ () => ({ limit, format, password }),
+ [limit, format, password]
+ );
+
+ const validateOption = validate ?? (() => true);
+ const formIsValid = limit > 0 && validateOption(currentOption);
+
+ const doExport = useCallback(() => {
+ if (isRequesting) return;
+ setIsRequesting(true);
+ const options: ExportOption = { ...currentOption };
+
+ new Promise<DownloadContent[]>((resolve, reject) => {
+ onExport({ options, resolve, reject });
+ })
+ .then((contents) => downloadAll(contents, options.format))
+ .then(() => {
+ pushNotification({
+ module: "bytebase",
+ style: "SUCCESS",
+ title: t("common.succeed"),
+ description: t("audit-log.export-finished"),
+ });
+ })
+ .catch((error: unknown) => {
+ pushNotification({
+ module: "bytebase",
+ style: "CRITICAL",
+ title: "Failed to export data",
+ description: JSON.stringify(error),
+ });
+ })
+ .finally(() => {
+ setIsRequesting(false);
+ setShowDrawer(false);
+ setShowPasswordDialog(false);
+ });
+ }, [currentOption, isRequesting, onExport, t]);
+
+ const handleSelectDropdownFormat = (selected: ExportFormat) => {
+ setFormat(selected);
+ if (supportPassword) {
+ setShowPasswordDialog(true);
+ } else {
+ // Run after state batched.
+ queueMicrotask(doExport);
+ }
+ };
+
+ const triggerButton = (
+ <Button
+ variant="default"
+ size={SIZE_TO_BUTTON[size]}
+ disabled={disabled || isRequesting}
+ onClick={(e) => {
+ e.preventDefault();
+ if (viewMode === "DRAWER") setShowDrawer(true);
+ }}
+ className={cn("gap-x-1", className)}
+ aria-label={buttonText}
+ >
+ <Download className="size-4" />
+ {size !== "tiny" && <span>{buttonText}</span>}
+ </Button>
+ );
+
+ const dropdownTrigger = (
+ <DropdownMenu>
+ <Tooltip content={tooltip} side="bottom">
+ <DropdownMenuTrigger
+ render={
+ <Button
+ variant="default"
+ size={SIZE_TO_BUTTON[size]}
+ disabled={disabled || isRequesting}
+ className={cn("gap-x-1", className)}
+ aria-label={buttonText}
+ >
+ <Download className="size-4" />
+ {size !== "tiny" && <span>{buttonText}</span>}
+ <ChevronDown className="size-3" />
+ </Button>
+ }
+ />
+ </Tooltip>
+ <DropdownMenuContent align="end">
+ {supportFormats.map((fmt) => (
+ <DropdownMenuItem
+ key={fmt}
+ onClick={() => handleSelectDropdownFormat(fmt)}
+ >
+ {t("sql-editor.download-as-file", {
+ file: ExportFormat[fmt],
+ })}
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+
+ return (
+ <>
+ {viewMode === "DROPDOWN" ? (
+ dropdownTrigger
+ ) : (
+ <Tooltip content={tooltip} side="bottom">
+ {triggerButton}
+ </Tooltip>
+ )}
+
+ {viewMode === "DRAWER" && (
+ <Sheet open={showDrawer} onOpenChange={setShowDrawer}>
+ <SheetContent width="medium">
+ <SheetHeader>
+ <SheetTitle>
+ {t("custom-approval.risk-rule.risk.namespace.data_export")}
+ </SheetTitle>
+ </SheetHeader>
+ <SheetBody>
+ <div className="flex flex-col gap-y-4">
+ {formContent}
+
+ <div className="flex flex-col gap-y-1">
+ <label className="text-sm text-control">
+ {t("export-data.export-rows")}
+ </label>
+ <MaxRowCountSelect
+ value={limit}
+ onChange={setLimit}
+ maximum={presetMax}
+ />
+ </div>
+
+ <div className="flex flex-col gap-y-1">
+ <label className="text-sm text-control">
+ {t("export-data.export-format")}
+ </label>
+ <RadioGroup
+ value={String(format)}
+ onValueChange={(v) => setFormat(Number(v) as ExportFormat)}
+ >
+ {supportFormats.map((fmt) => (
+ <RadioGroupItem key={fmt} value={String(fmt)}>
+ {ExportFormat[fmt]}
+ </RadioGroupItem>
+ ))}
+ </RadioGroup>
+ </div>
+
+ {supportPassword && (
+ <div className="flex flex-col gap-y-1">
+ <label className="text-sm text-control">
+ {t("export-data.password-optional")}
+ </label>
+ <Input
+ type="password"
+ autoComplete="new-password"
+ value={password}
+ onChange={(e) => setPassword(e.target.value)}
+ />
+ </div>
+ )}
+ </div>
+ </SheetBody>
+ <SheetFooter>
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => setShowDrawer(false)}
+ >
+ {t("common.cancel")}
+ </Button>
+ <Button
+ variant="default"
+ size="sm"
+ disabled={!formIsValid || isRequesting}
+ onClick={doExport}
+ >
+ {t("common.confirm")}
+ </Button>
+ </SheetFooter>
+ </SheetContent>
+ </Sheet>
+ )}
+
+ {viewMode === "DROPDOWN" && supportPassword && (
+ <Dialog open={showPasswordDialog} onOpenChange={setShowPasswordDialog}>
+ <DialogContent className="w-[26rem] max-w-[calc(100vw-4rem)]">
+ <div className="flex flex-col gap-y-3 p-6">
+ <DialogTitle>{t("export-data.password-optional")}</DialogTitle>
+ <p className="text-sm text-control-light">
+ {t("export-data.password-info")}
+ </p>
+ <Input
+ type="password"
+ autoComplete="new-password"
+ value={password}
+ onChange={(e) => setPassword(e.target.value)}
+ autoFocus
+ />
+ <div className="flex items-center justify-end gap-x-2 pt-2">
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => setShowPasswordDialog(false)}
+ >
+ {t("common.cancel")}
+ </Button>
+ <Button
+ variant="default"
+ size="sm"
+ disabled={isRequesting}
+ onClick={doExport}
+ >
+ {t("common.export")}
+ </Button>
+ </div>
+ </div>
+ </DialogContent>
+ </Dialog>
+ )}
+ </>
+ );
+}
diff --git a/frontend/src/react/components/ProjectSelect.tsx b/frontend/src/react/components/ProjectSelect.tsx
index 4f76afa020..b5e3381ff0 100644
--- a/frontend/src/react/components/ProjectSelect.tsx
+++ b/frontend/src/react/components/ProjectSelect.tsx
@@ -20,6 +20,10 @@ export interface ProjectSelectProps {
* of any projects" + "go to create" prompt). Falls back to the
* generic "no data" string when omitted. */
emptyContent?: ReactNode;
+ /** Render the dropdown via a portal so it isn't clipped by an
+ * `overflow:hidden` ancestor (e.g. inside a Sheet body that scopes
+ * its own scroll region). */
+ portal?: boolean;
}
export function ProjectSelect({
@@ -30,6 +34,7 @@ export function ProjectSelect({
className,
excludeDefault = true,
emptyContent,
+ portal,
}: ProjectSelectProps) {
const { t } = useTranslation();
const projectStore = useProjectV1Store();
@@ -104,6 +109,7 @@ export function ProjectSelect({
onSearch={fetchProjects}
disabled={disabled}
className={className}
+ portal={portal}
options={allProjects.map((p) => ({
value: p.name,
label: p.title,
diff --git a/frontend/src/react/components/database/DatabaseTable.tsx b/frontend/src/react/components/database/DatabaseTable.tsx
index 3e745eff14..05dd610df2 100644
--- a/frontend/src/react/components/database/DatabaseTable.tsx
+++ b/frontend/src/react/components/database/DatabaseTable.tsx
@@ -1,42 +1,22 @@
-import { CheckCircle, XCircle } from "lucide-react";
import { useCallback, useEffect, useRef, useState } from "react";
-import { useTranslation } from "react-i18next";
-import { EngineIcon } from "@/react/components/EngineIcon";
-import { EnvironmentLabel } from "@/react/components/EnvironmentLabel";
-import { LabelsDisplay } from "@/react/components/LabelsDisplay";
-import {
- Table,
- TableBody,
- TableCell,
- TableHead,
- TableHeader,
- TableRow,
-} from "@/react/components/ui/table";
-import { useColumnWidths } from "@/react/hooks/useColumnWidths";
import { PagedTableFooter } from "@/react/hooks/usePagedData";
import {
getPageSizeOptions,
useSessionPageSize,
} from "@/react/hooks/useSessionPageSize";
import { useVueState } from "@/react/hooks/useVueState";
-import { cn } from "@/react/lib/utils";
import { router } from "@/router";
import { useActuatorV1Store, useDatabaseV1Store } from "@/store";
import type { DatabaseFilter } from "@/store/modules/v1/database";
import type { Database } from "@/types/proto-es/v1/database_service_pb";
-import { SyncStatus } from "@/types/proto-es/v1/database_service_pb";
+import { autoDatabaseRoute } from "@/utils";
import {
- autoDatabaseRoute,
- extractDatabaseResourceName,
- extractProjectResourceName,
- getDatabaseEnvironment,
- getDatabaseProject,
- getInstanceResource,
- hostPortOfInstanceV1,
-} from "@/utils";
-import { extractReleaseUID } from "@/utils/v1/release";
+ type DatabaseTableMode,
+ type DatabaseTableSort,
+ DatabaseTableView,
+} from "./DatabaseTableView";
-export type DatabaseTableMode = "ALL" | "PROJECT";
+export type { DatabaseTableMode } from "./DatabaseTableView";
export interface DatabaseTableProps {
filter: DatabaseFilter;
@@ -47,18 +27,13 @@ export interface DatabaseTableProps {
refreshToken?: number;
}
-interface DatabaseColumn {
- key: string;
- title: React.ReactNode;
- defaultWidth: number;
- minWidth?: number;
- resizable?: boolean;
- sortable?: boolean;
- sortKey?: string;
- cellClassName?: string;
- render: (database: Database) => React.ReactNode;
-}
-
+/**
+ * Server-fetching wrapper around `DatabaseTableView`. Owns paging,
+ * filter, sort, and the workspace-resource scope; renders the pure view
+ * for layout. Used by settings/project pages that don't already have a
+ * pre-fetched database list — callers that do should compose
+ * `DatabaseTableView` directly.
+ */
export function DatabaseTable({
filter,
parent,
@@ -67,7 +42,6 @@ export function DatabaseTable({
onSelectedNamesChange,
refreshToken,
}: DatabaseTableProps) {
- const { t } = useTranslation();
const databaseStore = useDatabaseV1Store();
const actuatorStore = useActuatorV1Store();
@@ -79,26 +53,8 @@ export function DatabaseTable({
const [pageSize, setPageSize] = useSessionPageSize("bb.databases-table");
const fetchIdRef = useRef(0);
- const [sortKey, setSortKey] = useState<string | null>(null);
- const [sortOrder, setSortOrder] = useState<"asc" | "desc">("asc");
-
- const orderBy = sortKey ? `${sortKey} ${sortOrder}` : "";
-
- const toggleSort = useCallback(
- (key: string) => {
- if (sortKey === key) {
- if (sortOrder === "asc") setSortOrder("desc");
- else {
- setSortKey(null);
- setSortOrder("asc");
- }
- } else {
- setSortKey(key);
- setSortOrder("asc");
- }
- },
- [sortKey, sortOrder]
- );
+ const [sort, setSort] = useState<DatabaseTableSort | null>(null);
+ const orderBy = sort ? `${sort.key} ${sort.order}` : "";
const workspaceResourceName = useVueState(
() => actuatorStore.workspaceResourceName
@@ -176,28 +132,6 @@ export function DatabaseTable({
}
}, [isFetchingMore, fetchDatabases]);
- const showSelection = !!selectedNames && !!onSelectedNamesChange;
-
- const toggleSelection = useCallback(
- (name: string) => {
- if (!selectedNames || !onSelectedNamesChange) return;
- const next = new Set(selectedNames);
- if (next.has(name)) next.delete(name);
- else next.add(name);
- onSelectedNamesChange(next);
- },
- [selectedNames, onSelectedNamesChange]
- );
-
- const toggleSelectAll = useCallback(() => {
- if (!selectedNames || !onSelectedNamesChange) return;
- if (selectedNames.size === databases.length) {
- onSelectedNamesChange(new Set());
- } else {
- onSelectedNamesChange(new Set(databases.map((db) => db.name)));
- }
- }, [databases, selectedNames, onSelectedNamesChange]);
-
const handleRowClick = useCallback((db: Database, e: React.MouseEvent) => {
const url = router.resolve(autoDatabaseRoute(db)).fullPath;
if (e.ctrlKey || e.metaKey) {
@@ -207,236 +141,20 @@ export function DatabaseTable({
}
}, []);
- const allSelected =
- databases.length > 0 && (selectedNames?.size ?? 0) === databases.length;
- const someSelected =
- (selectedNames?.size ?? 0) > 0 &&
- (selectedNames?.size ?? 0) < databases.length;
- const headerCheckboxRef = useRef<HTMLInputElement>(null);
- useEffect(() => {
- if (headerCheckboxRef.current) {
- headerCheckboxRef.current.indeterminate = someSelected;
- }
- }, [someSelected]);
-
const pageSizeOptions = getPageSizeOptions();
- const showProjectColumn = mode === "ALL";
-
- const columns: DatabaseColumn[] = [];
- if (showSelection) {
- columns.push({
- key: "select",
- title: (
- <input
- ref={headerCheckboxRef}
- type="checkbox"
- checked={allSelected}
- onChange={toggleSelectAll}
- className="rounded-xs border-control-border"
- />
- ),
- defaultWidth: 48,
- render: (db) => (
- <input
- type="checkbox"
- checked={selectedNames?.has(db.name) ?? false}
- onChange={() => toggleSelection(db.name)}
- onClick={(e) => e.stopPropagation()}
- className="rounded-xs border-control-border"
- />
- ),
- });
- }
- columns.push({
- key: "name",
- title: t("common.name"),
- defaultWidth: 280,
- minWidth: 160,
- resizable: true,
- sortable: true,
- sortKey: "name",
- render: (db) => {
- const instanceResource = getInstanceResource(db);
- return (
- <div className="flex items-center gap-x-2">
- <EngineIcon engine={instanceResource.engine} className="h-5 w-5" />
- <span className="truncate">
- {extractDatabaseResourceName(db.name).databaseName}
- </span>
- </div>
- );
- },
- });
- columns.push({
- key: "environment",
- title: t("common.environment"),
- defaultWidth: 200,
- minWidth: 120,
- resizable: true,
- render: (db) => (
- <EnvironmentLabel environmentName={getDatabaseEnvironment(db).name} />
- ),
- });
- if (showProjectColumn) {
- columns.push({
- key: "project",
- title: t("common.project"),
- defaultWidth: 200,
- minWidth: 120,
- resizable: true,
- sortable: true,
- sortKey: "project",
- render: (db) => (
- <span className="truncate">
- {extractProjectResourceName(getDatabaseProject(db).name)}
- </span>
- ),
- });
- } else {
- columns.push({
- key: "release",
- title: t("common.release"),
- defaultWidth: 140,
- minWidth: 80,
- resizable: true,
- render: (db) => (
- <span className="truncate">
- {db.release ? extractReleaseUID(db.release) : "-"}
- </span>
- ),
- });
- }
- columns.push({
- key: "instance",
- title: t("common.instance"),
- defaultWidth: 240,
- minWidth: 120,
- resizable: true,
- sortable: true,
- sortKey: "instance",
- render: (db) => (
- <span className="block truncate">{getInstanceResource(db).title}</span>
- ),
- });
- columns.push({
- key: "address",
- title: t("common.address"),
- defaultWidth: 240,
- minWidth: 150,
- resizable: true,
- render: (db) => (
- <span className="truncate">
- {hostPortOfInstanceV1(getInstanceResource(db))}
- </span>
- ),
- });
- columns.push({
- key: "labels",
- title: t("common.labels"),
- defaultWidth: 240,
- minWidth: 150,
- resizable: true,
- render: (db) => <LabelsDisplay labels={db.labels} />,
- });
- columns.push({
- key: "status",
- title: t("common.status"),
- defaultWidth: 80,
- cellClassName: "whitespace-nowrap",
- render: (db) =>
- db.syncStatus === SyncStatus.FAILED ? (
- <span title={db.syncError || t("database.sync-status-failed")}>
- <XCircle className="w-4 h-4 text-error" />
- </span>
- ) : (
- <CheckCircle className="w-4 h-4 text-success" />
- ),
- });
-
- const { widths, totalWidth, onResizeStart } = useColumnWidths(columns);
return (
<>
- <div className="border rounded-sm">
- <div className="overflow-x-auto">
- <Table className="table-fixed" style={{ width: `${totalWidth}px` }}>
- <colgroup>
- {widths.map((w, i) => (
- <col key={columns[i].key} style={{ width: `${w}px` }} />
- ))}
- </colgroup>
- <TableHeader>
- <TableRow className="bg-gray-50">
- {columns.map((col, colIdx) => (
- <TableHead
- key={col.key}
- sortable={col.sortable}
- sortActive={
- col.sortable && sortKey === (col.sortKey ?? col.key)
- }
- sortDir={sortOrder}
- onSort={
- col.sortable
- ? () => toggleSort(col.sortKey ?? col.key)
- : undefined
- }
- resizable={col.resizable}
- onResizeStart={
- col.resizable
- ? (e) => onResizeStart(colIdx, e)
- : undefined
- }
- >
- {col.title}
- </TableHead>
- ))}
- </TableRow>
- </TableHeader>
- <TableBody>
- {loading && databases.length === 0 ? (
- <TableRow>
- <TableCell
- colSpan={columns.length}
- className="py-8 text-center text-control-placeholder"
- >
- <div className="flex items-center justify-center gap-x-2">
- <div className="animate-spin h-4 w-4 border-2 border-accent border-t-transparent rounded-full" />
- {t("common.loading")}
- </div>
- </TableCell>
- </TableRow>
- ) : databases.length === 0 ? (
- <TableRow>
- <TableCell
- colSpan={columns.length}
- className="py-8 text-center text-control-placeholder"
- >
- {t("common.no-data")}
- </TableCell>
- </TableRow>
- ) : (
- databases.map((db) => (
- <TableRow
- key={db.name}
- className="cursor-pointer"
- onClick={(e) => handleRowClick(db, e)}
- >
- {columns.map((col) => (
- <TableCell
- key={col.key}
- className={cn("overflow-hidden", col.cellClassName)}
- >
- {col.render(db)}
- </TableCell>
- ))}
- </TableRow>
- ))
- )}
- </TableBody>
- </Table>
- </div>
- </div>
-
+ <DatabaseTableView
+ databases={databases}
+ mode={mode}
+ loading={loading}
+ selectedNames={selectedNames}
+ onSelectedNamesChange={onSelectedNamesChange}
+ sort={sort}
+ onSortChange={setSort}
+ onRowClick={handleRowClick}
+ />
<div className="mx-2">
<PagedTableFooter
pageSize={pageSize}
diff --git a/frontend/src/react/components/database/DatabaseTableView.tsx b/frontend/src/react/components/database/DatabaseTableView.tsx
new file mode 100644
index 0000000000..b2ab9ebc3b
--- /dev/null
+++ b/frontend/src/react/components/database/DatabaseTableView.tsx
@@ -0,0 +1,360 @@
+import { CheckCircle, XCircle } from "lucide-react";
+import { useEffect, useMemo, useRef } from "react";
+import { useTranslation } from "react-i18next";
+import { EngineIcon } from "@/react/components/EngineIcon";
+import { EnvironmentLabel } from "@/react/components/EnvironmentLabel";
+import { LabelsDisplay } from "@/react/components/LabelsDisplay";
+import {
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+} from "@/react/components/ui/table";
+import { useColumnWidths } from "@/react/hooks/useColumnWidths";
+import { cn } from "@/react/lib/utils";
+import type { Database } from "@/types/proto-es/v1/database_service_pb";
+import { SyncStatus } from "@/types/proto-es/v1/database_service_pb";
+import {
+ extractDatabaseResourceName,
+ extractProjectResourceName,
+ getDatabaseEnvironment,
+ getDatabaseProject,
+ getInstanceResource,
+ hostPortOfInstanceV1,
+} from "@/utils";
+import { extractReleaseUID } from "@/utils/v1/release";
+
+export type DatabaseTableMode = "ALL" | "PROJECT";
+
+export type DatabaseTableSort = {
+ key: "name" | "project" | "instance";
+ order: "asc" | "desc";
+};
+
+interface DatabaseTableViewProps {
+ databases: Database[];
+ mode?: DatabaseTableMode;
+ loading?: boolean;
+ /** Selection — pass both to enable the checkbox column. */
+ selectedNames?: Set<string>;
+ onSelectedNamesChange?: (names: Set<string>) => void;
+ /** Sort state + handler — pass both to enable sortable headers. */
+ sort?: DatabaseTableSort | null;
+ onSortChange?: (sort: DatabaseTableSort | null) => void;
+ /** Row click handler. Not wired by default — pure UI doesn't navigate. */
+ onRowClick?: (db: Database, e: React.MouseEvent) => void;
+}
+
+interface DatabaseColumn {
+ key: string;
+ title: React.ReactNode;
+ defaultWidth: number;
+ minWidth?: number;
+ resizable?: boolean;
+ sortable?: boolean;
+ sortKey?: DatabaseTableSort["key"];
+ cellClassName?: string;
+ render: (database: Database) => React.ReactNode;
+}
+
+/**
+ * Pure presentational table — given a list of databases, renders the
+ * standard SQL Editor / settings database table layout with resizable
+ * columns (engine icon, environment, project/release, instance,
+ * address, labels, sync status).
+ *
+ * No data fetching, no pagination footer, no router navigation. Callers
+ * that need those compose this view inside their own wrapper:
+ *
+ * - `DatabaseTable.tsx` — server-fetch wrapper used by settings/project
+ * pages. Owns paging + filter + sort, threads them through this view.
+ * - SQL Editor `BatchQuerySelect.tsx` — already has the database list,
+ * renders this view directly with a Set-based selection model.
+ * - `TransferProjectSheet.tsx` — read-only summary of selected
+ * databases inside a sheet.
+ */
+export function DatabaseTableView({
+ databases,
+ mode = "ALL",
+ loading = false,
+ selectedNames,
+ onSelectedNamesChange,
+ sort,
+ onSortChange,
+ onRowClick,
+}: DatabaseTableViewProps) {
+ const { t } = useTranslation();
+
+ const showSelection = !!selectedNames && !!onSelectedNamesChange;
+ const showProjectColumn = mode === "ALL";
+ const sortable = !!onSortChange;
+
+ const toggleSort = (key: DatabaseTableSort["key"]) => {
+ if (!onSortChange) return;
+ if (sort?.key === key) {
+ if (sort.order === "asc") {
+ onSortChange({ key, order: "desc" });
+ } else {
+ onSortChange(null);
+ }
+ } else {
+ onSortChange({ key, order: "asc" });
+ }
+ };
+
+ const toggleSelection = (name: string) => {
+ if (!selectedNames || !onSelectedNamesChange) return;
+ const next = new Set(selectedNames);
+ if (next.has(name)) next.delete(name);
+ else next.add(name);
+ onSelectedNamesChange(next);
+ };
+
+ const toggleSelectAll = () => {
+ if (!selectedNames || !onSelectedNamesChange) return;
+ if (selectedNames.size === databases.length) {
+ onSelectedNamesChange(new Set());
+ } else {
+ onSelectedNamesChange(new Set(databases.map((db) => db.name)));
+ }
+ };
+
+ const allSelected =
+ databases.length > 0 && (selectedNames?.size ?? 0) === databases.length;
+ const someSelected =
+ (selectedNames?.size ?? 0) > 0 &&
+ (selectedNames?.size ?? 0) < databases.length;
+ const headerCheckboxRef = useRef<HTMLInputElement>(null);
+ useEffect(() => {
+ if (headerCheckboxRef.current) {
+ headerCheckboxRef.current.indeterminate = someSelected;
+ }
+ }, [someSelected]);
+
+ const columns = useMemo<DatabaseColumn[]>(() => {
+ const cols: DatabaseColumn[] = [];
+ if (showSelection) {
+ cols.push({
+ key: "select",
+ title: (
+ <input
+ ref={headerCheckboxRef}
+ type="checkbox"
+ checked={allSelected}
+ onChange={toggleSelectAll}
+ className="rounded-xs border-control-border"
+ />
+ ),
+ defaultWidth: 48,
+ render: (db) => (
+ <input
+ type="checkbox"
+ checked={selectedNames?.has(db.name) ?? false}
+ onChange={() => toggleSelection(db.name)}
+ onClick={(e) => e.stopPropagation()}
+ className="rounded-xs border-control-border"
+ />
+ ),
+ });
+ }
+ cols.push({
+ key: "name",
+ title: t("common.name"),
+ defaultWidth: 280,
+ minWidth: 160,
+ resizable: true,
+ sortable: true,
+ sortKey: "name",
+ render: (db) => {
+ const instanceResource = getInstanceResource(db);
+ return (
+ <div className="flex items-center gap-x-2">
+ <EngineIcon engine={instanceResource.engine} className="h-5 w-5" />
+ <span className="truncate">
+ {extractDatabaseResourceName(db.name).databaseName}
+ </span>
+ </div>
+ );
+ },
+ });
+ cols.push({
+ key: "environment",
+ title: t("common.environment"),
+ defaultWidth: 200,
+ minWidth: 120,
+ resizable: true,
+ render: (db) => (
+ <EnvironmentLabel environmentName={getDatabaseEnvironment(db).name} />
+ ),
+ });
+ if (showProjectColumn) {
+ cols.push({
+ key: "project",
+ title: t("common.project"),
+ defaultWidth: 200,
+ minWidth: 120,
+ resizable: true,
+ sortable: true,
+ sortKey: "project",
+ render: (db) => (
+ <span className="truncate">
+ {extractProjectResourceName(getDatabaseProject(db).name)}
+ </span>
+ ),
+ });
+ } else {
+ cols.push({
+ key: "release",
+ title: t("common.release"),
+ defaultWidth: 140,
+ minWidth: 80,
+ resizable: true,
+ render: (db) => (
+ <span className="truncate">
+ {db.release ? extractReleaseUID(db.release) : "-"}
+ </span>
+ ),
+ });
+ }
+ cols.push({
+ key: "instance",
+ title: t("common.instance"),
+ defaultWidth: 240,
+ minWidth: 120,
+ resizable: true,
+ sortable: true,
+ sortKey: "instance",
+ render: (db) => (
+ <span className="block truncate">{getInstanceResource(db).title}</span>
+ ),
+ });
+ cols.push({
+ key: "address",
+ title: t("common.address"),
+ defaultWidth: 240,
+ minWidth: 150,
+ resizable: true,
+ render: (db) => (
+ <span className="truncate">
+ {hostPortOfInstanceV1(getInstanceResource(db))}
+ </span>
+ ),
+ });
+ cols.push({
+ key: "labels",
+ title: t("common.labels"),
+ defaultWidth: 240,
+ minWidth: 150,
+ resizable: true,
+ render: (db) => <LabelsDisplay labels={db.labels} />,
+ });
+ cols.push({
+ key: "status",
+ title: t("common.status"),
+ defaultWidth: 80,
+ cellClassName: "whitespace-nowrap",
+ render: (db) =>
+ db.syncStatus === SyncStatus.FAILED ? (
+ <span title={db.syncError || t("database.sync-status-failed")}>
+ <XCircle className="w-4 h-4 text-error" />
+ </span>
+ ) : (
+ <CheckCircle className="w-4 h-4 text-success" />
+ ),
+ });
+ return cols;
+ // toggleSelection / toggleSelectAll close over selectedNames /
+ // onSelectedNamesChange but they're stable callbacks within a single
+ // render and the cell handlers re-bind on every render anyway.
+ }, [showSelection, showProjectColumn, allSelected, selectedNames, t]);
+
+ const { widths, totalWidth, onResizeStart } = useColumnWidths(columns);
+
+ return (
+ <div className="border rounded-sm">
+ <div className="overflow-x-auto">
+ <Table className="table-fixed" style={{ width: `${totalWidth}px` }}>
+ <colgroup>
+ {widths.map((w, i) => (
+ <col key={columns[i].key} style={{ width: `${w}px` }} />
+ ))}
+ </colgroup>
+ <TableHeader>
+ <TableRow className="bg-gray-50">
+ {columns.map((col, colIdx) => {
+ const colSortKey = col.sortKey;
+ const sortActive = Boolean(
+ col.sortable && colSortKey && sort?.key === colSortKey
+ );
+ return (
+ <TableHead
+ key={col.key}
+ sortable={col.sortable && sortable}
+ sortActive={sortActive}
+ sortDir={sort?.order ?? "asc"}
+ onSort={
+ col.sortable && sortable && colSortKey
+ ? () => toggleSort(colSortKey)
+ : undefined
+ }
+ resizable={col.resizable}
+ onResizeStart={
+ col.resizable
+ ? (e) => onResizeStart(colIdx, e)
+ : undefined
+ }
+ >
+ {col.title}
+ </TableHead>
+ );
+ })}
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {loading && databases.length === 0 ? (
+ <TableRow>
+ <TableCell
+ colSpan={columns.length}
+ className="py-8 text-center text-control-placeholder"
+ >
+ <div className="flex items-center justify-center gap-x-2">
+ <div className="animate-spin h-4 w-4 border-2 border-accent border-t-transparent rounded-full" />
+ {t("common.loading")}
+ </div>
+ </TableCell>
+ </TableRow>
+ ) : databases.length === 0 ? (
+ <TableRow>
+ <TableCell
+ colSpan={columns.length}
+ className="py-8 text-center text-control-placeholder"
+ >
+ {t("common.no-data")}
+ </TableCell>
+ </TableRow>
+ ) : (
+ databases.map((db) => (
+ <TableRow
+ key={db.name}
+ className={onRowClick ? "cursor-pointer" : undefined}
+ onClick={onRowClick ? (e) => onRowClick(db, e) : undefined}
+ >
+ {columns.map((col) => (
+ <TableCell
+ key={col.key}
+ className={cn("overflow-hidden", col.cellClassName)}
+ >
+ {col.render(db)}
+ </TableCell>
+ ))}
+ </TableRow>
+ ))
+ )}
+ </TableBody>
+ </Table>
+ </div>
+ </div>
+ );
+}
diff --git a/frontend/src/react/components/database/TransferProjectSheet.tsx b/frontend/src/react/components/database/TransferProjectSheet.tsx
index 556a171b42..276f4e3e6c 100644
--- a/frontend/src/react/components/database/TransferProjectSheet.tsx
+++ b/frontend/src/react/components/database/TransferProjectSheet.tsx
@@ -1,6 +1,6 @@
import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
-import { EngineIcon } from "@/react/components/EngineIcon";
+import { DatabaseTableView } from "@/react/components/database";
import { ProjectSelect } from "@/react/components/ProjectSelect";
import { Button } from "@/react/components/ui/button";
import {
@@ -14,7 +14,6 @@ import {
import { useVueState } from "@/react/hooks/useVueState";
import { useActuatorV1Store } from "@/store";
import type { Database } from "@/types/proto-es/v1/database_service_pb";
-import { extractDatabaseResourceName, getInstanceResource } from "@/utils";
export function TransferProjectSheet({
open,
@@ -50,27 +49,21 @@ export function TransferProjectSheet({
<SheetHeader>
<SheetTitle>{t("database.transfer-project")}</SheetTitle>
</SheetHeader>
- <SheetBody className="gap-y-4">
- <p className="text-sm text-control-light">
+ <SheetBody className="gap-y-4 overflow-hidden">
+ <p className="shrink-0 text-sm text-control-light">
{t("database.selected-n-databases", { n: databases.length })}
</p>
- <div className="border border-control-border rounded-xs max-h-48 overflow-y-auto">
- {databases.map((db) => (
- <div
- key={db.name}
- className="px-3 py-2 text-sm border-b last:border-b-0 flex items-center gap-x-2"
- >
- <EngineIcon
- engine={getInstanceResource(db).engine}
- className="size-4"
- />
- <span>{extractDatabaseResourceName(db.name).databaseName}</span>
- </div>
- ))}
+ {/* Table grows / shrinks to fill remaining SheetBody space and
+ becomes the scroll container when the rows exceed it. The
+ `min-h-0` is required so flex can shrink it below the
+ natural content height; without it the children's intrinsic
+ size would push the SheetBody to overflow instead. */}
+ <div className="flex-1 min-h-0 overflow-y-auto">
+ <DatabaseTableView databases={databases} />
</div>
- <div className="flex items-center gap-x-6">
+ <div className="shrink-0 flex items-center gap-x-6">
<label className="flex items-center gap-x-2 cursor-pointer">
<input
type="radio"
@@ -96,10 +89,13 @@ export function TransferProjectSheet({
</div>
{mode === "project" && (
- <ProjectSelect
- value={selectedProject}
- onChange={(name) => setSelectedProject(name)}
- />
+ <div className="shrink-0">
+ <ProjectSelect
+ value={selectedProject}
+ onChange={(name) => setSelectedProject(name)}
+ portal
+ />
+ </div>
)}
</SheetBody>
<SheetFooter>
diff --git a/frontend/src/react/components/database/index.tsx b/frontend/src/react/components/database/index.tsx
index 57cb4c58e6..84e8b6816f 100644
--- a/frontend/src/react/components/database/index.tsx
+++ b/frontend/src/react/components/database/index.tsx
@@ -4,5 +4,7 @@ export type { DatabaseBatchOperationsBarProps } from "./DatabaseBatchOperationsB
export { DatabaseBatchOperationsBar } from "./DatabaseBatchOperationsBar";
export type { DatabaseTableMode, DatabaseTableProps } from "./DatabaseTable";
export { DatabaseTable } from "./DatabaseTable";
+export type { DatabaseTableSort } from "./DatabaseTableView";
+export { DatabaseTableView } from "./DatabaseTableView";
export { LabelEditorSheet } from "./LabelEditorSheet";
export { TransferProjectSheet } from "./TransferProjectSheet";
diff --git a/frontend/src/react/components/monaco/lsp-client.ts b/frontend/src/react/components/monaco/lsp-client.ts
index 112eeb08fc..03d2cf4b76 100644
--- a/frontend/src/react/components/monaco/lsp-client.ts
+++ b/frontend/src/react/components/monaco/lsp-client.ts
@@ -9,6 +9,7 @@ import {
} from "vscode-ws-jsonrpc";
import { refreshTokens } from "@/connect/refreshToken";
import { sleep } from "@/utils";
+import { initializeMonacoServices } from "./services";
import {
createUrl,
errorNotification,
@@ -214,6 +215,16 @@ const reconnect = async () => {
};
const createLanguageClient = async (): Promise<MonacoLanguageClient> => {
+ // `monaco-languageclient` v9+ requires `@codingame/monaco-vscode-api`'s
+ // `initialize()` to have completed before `new MonacoLanguageClient(...)`,
+ // otherwise the constructor throws "Default api is not ready yet, do not
+ // forget to import 'vscode/localExtensionHost' and wait for services
+ // initialization". `MonacoEditor.tsx` kicks off `initializeLSPClient()`
+ // *before* awaiting `createMonacoEditor()` so the LSP WebSocket connects
+ // in parallel with Monaco loading — that means we can't rely on the
+ // caller to have initialized services first. Await it here so callers
+ // can fire-and-forget safely.
+ await initializeMonacoServices();
const ws = await connectWebSocket();
const socket = toSocket(ws);
const reader = new WebSocketMessageReader(socket);
diff --git a/frontend/src/react/components/sql-editor/BatchQuerySelect.tsx b/frontend/src/react/components/sql-editor/BatchQuerySelect.tsx
new file mode 100644
index 0000000000..ece3710bb3
--- /dev/null
+++ b/frontend/src/react/components/sql-editor/BatchQuerySelect.tsx
@@ -0,0 +1 @@
+export { BatchQuerySelect } from "./ResultPanel/BatchQuerySelect";
diff --git a/frontend/src/react/components/sql-editor/ResultPanel/BatchQuerySelect.tsx b/frontend/src/react/components/sql-editor/ResultPanel/BatchQuerySelect.tsx
new file mode 100644
index 0000000000..0250fb6e73
--- /dev/null
+++ b/frontend/src/react/components/sql-editor/ResultPanel/BatchQuerySelect.tsx
@@ -0,0 +1,404 @@
+import { create } from "@bufbuild/protobuf";
+import dayjs from "dayjs";
+import { head } from "lodash-es";
+import { CircleAlert, Eye, EyeOff, X } from "lucide-react";
+import { useEffect, useMemo, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { EngineIconPath } from "@/components/InstanceForm/constants";
+import {
+ DataExportButton,
+ type DataExportRequest,
+ type DownloadContent,
+} from "@/react/components/DataExportButton";
+import { DatabaseTableView } from "@/react/components/database";
+import { Button } from "@/react/components/ui/button";
+import { Tooltip } from "@/react/components/ui/tooltip";
+import { useVueState } from "@/react/hooks/useVueState";
+import { cn } from "@/react/lib/utils";
+import {
+ pushNotification,
+ useDatabaseV1Store,
+ useSQLEditorStore,
+ useSQLEditorTabStore,
+ useSQLStore,
+} from "@/store";
+import { ExportFormat } from "@/types/proto-es/v1/common_pb";
+import type { Database } from "@/types/proto-es/v1/database_service_pb";
+import { ExportRequestSchema } from "@/types/proto-es/v1/sql_service_pb";
+import type { SQLEditorDatabaseQueryContext } from "@/types/sqlEditor/tab";
+import {
+ extractDatabaseResourceName,
+ getDatabaseEnvironment,
+ getInstanceResource,
+ hexToRgb,
+} from "@/utils";
+import {
+ type CloseTabAction,
+ resultTabEvents,
+} from "@/views/sql-editor/EditorPanel/ResultPanel/resultTabContext";
+import { TabContextMenu } from "./ContextMenu";
+
+const MAX_EXPORT = 20;
+
+type Props = {
+ readonly selectedDatabase: Database | undefined;
+ readonly onSelectedDatabaseChange: (db: Database | undefined) => void;
+};
+
+type BatchQueryItem = {
+ database: Database;
+ context: SQLEditorDatabaseQueryContext | undefined;
+};
+
+const isEmptyQueryItem = (item: BatchQueryItem) => {
+ if (!item.context) return true;
+ if (item.context.resultSet?.error) return false;
+ if (item.context.status !== "DONE") return false;
+ return (
+ item.context.resultSet?.results.every(
+ (result) => result.rows.length === 0
+ ) ?? true
+ );
+};
+
+const isDatabaseQueryFailed = (item: BatchQueryItem) =>
+ Boolean(
+ item.context?.resultSet?.error ||
+ item.context?.resultSet?.results.find((result) => result.error)
+ );
+
+/**
+ * Replaces `frontend/src/views/sql-editor/EditorPanel/ResultPanel/BatchQuerySelect.vue`.
+ *
+ * Renders the batch-query tab strip above the result panel: one tab per
+ * queried database, with environment-tinted backgrounds, an empty-results
+ * toggle, a batch-export drawer, and a right-click context menu (close /
+ * close others / close to right / close all).
+ */
+export function BatchQuerySelect({
+ selectedDatabase,
+ onSelectedDatabaseChange,
+}: Props) {
+ const { t } = useTranslation();
+ const tabStore = useSQLEditorTabStore();
+ const databaseStore = useDatabaseV1Store();
+ const sqlStore = useSQLStore();
+ const editorStore = useSQLEditorStore();
+
+ const [showEmpty, setShowEmpty] = useState(true);
+ const [selectedDatabaseNames, setSelectedDatabaseNames] = useState<
+ Set<string>
+ >(new Set());
+
+ const queryDataPolicy = useVueState(() => editorStore.queryDataPolicy);
+
+ // Read the Map's `.keys()` directly inside the Vue getter so Vue's
+ // reactivity tracks the iteration. `useVueState(() => tabStore.currentTab)`
+ // would only fire when the tab object reference changes — Map mutations
+ // (which is how `useExecuteSQL.preExecute` adds new query contexts)
+ // wouldn't trigger React re-renders.
+ const queriedDatabaseNames = useVueState(
+ () => Array.from(tabStore.currentTab?.databaseQueryContexts?.keys() || []),
+ { deep: true }
+ );
+
+ // Track the contexts arrays themselves so the `items[].context` snapshot
+ // and `isEmptyQueryItem` computations stay in sync as `runQuery` mutates
+ // each context's `status` / `resultSet`.
+ const contextsByDatabase = useVueState(
+ () => {
+ const map = new Map<string, SQLEditorDatabaseQueryContext | undefined>();
+ const contexts = tabStore.currentTab?.databaseQueryContexts;
+ if (!contexts) return map;
+ for (const name of contexts.keys()) {
+ map.set(name, head(contexts.get(name)));
+ }
+ return map;
+ },
+ { deep: true }
+ );
+
+ const items = useMemo<BatchQueryItem[]>(() => {
+ return queriedDatabaseNames.map((name) => ({
+ database: databaseStore.getDatabaseByName(name),
+ context: contextsByDatabase.get(name),
+ }));
+ }, [queriedDatabaseNames, contextsByDatabase, databaseStore]);
+
+ const showEmptySwitch = useMemo(
+ () => items.length > 1 && items.some((item) => isEmptyQueryItem(item)),
+ [items]
+ );
+
+ const filteredItems = useMemo(() => {
+ if (showEmpty || !showEmptySwitch) return items;
+ return items.filter((item) => !isEmptyQueryItem(item));
+ }, [items, showEmpty, showEmptySwitch]);
+
+ // Auto-select a proper database when the items list changes (mirrors
+ // the Vue `watch(filteredItems, ..., { immediate: true })`).
+ useEffect(() => {
+ if (
+ !selectedDatabase ||
+ !filteredItems.find((item) => item.database === selectedDatabase)
+ ) {
+ onSelectedDatabaseChange(head(filteredItems)?.database);
+ }
+ }, [filteredItems, selectedDatabase, onSelectedDatabaseChange]);
+
+ const databaseList = useMemo(
+ () =>
+ queriedDatabaseNames.map((name) => databaseStore.getDatabaseByName(name)),
+ [queriedDatabaseNames, databaseStore]
+ );
+
+ const handleCloseSingleResultView = (item: BatchQueryItem) => {
+ const tab = tabStore.currentTab;
+ const contexts = tab?.databaseQueryContexts?.get(item.database.name);
+ if (!contexts) return;
+ for (const context of contexts) {
+ context.abortController?.abort();
+ }
+ tab?.databaseQueryContexts?.delete(item.database.name);
+ };
+
+ // Subscribe to context-menu close-tab events.
+ useEffect(() => {
+ const unsubscribe = resultTabEvents.on(
+ "close-tab",
+ ({ index, action }: { index: number; action: CloseTabAction }) => {
+ const max = items.length - 1;
+ switch (action) {
+ case "CLOSE":
+ handleCloseSingleResultView(items[index]);
+ return;
+ case "CLOSE_OTHERS":
+ for (let i = max; i > index; i--) {
+ handleCloseSingleResultView(items[i]);
+ }
+ for (let i = index - 1; i >= 0; i--) {
+ handleCloseSingleResultView(items[i]);
+ }
+ return;
+ case "CLOSE_TO_THE_RIGHT":
+ for (let i = max; i > index; i--) {
+ handleCloseSingleResultView(items[i]);
+ }
+ return;
+ case "CLOSE_ALL":
+ for (let i = max; i >= 0; i--) {
+ handleCloseSingleResultView(items[i]);
+ }
+ return;
+ }
+ }
+ );
+ return () => {
+ unsubscribe();
+ };
+ // `tab` reactivity is captured by `items`; including it explicitly
+ // re-creates the listener on every reactive tick.
+ }, [items]);
+
+ const validateExport = () =>
+ selectedDatabaseNames.size > 0 && selectedDatabaseNames.size <= MAX_EXPORT;
+
+ const handleExport = ({ options, resolve }: DataExportRequest) => {
+ void (async () => {
+ const contents: DownloadContent[] = [];
+ const tab = tabStore.currentTab;
+ for (const databaseName of Array.from(selectedDatabaseNames)) {
+ const database = databaseStore.getDatabaseByName(databaseName);
+ const context = head(tab?.databaseQueryContexts?.get(databaseName));
+ if (!context) continue;
+ try {
+ const content = await sqlStore.exportData(
+ create(ExportRequestSchema, {
+ name: databaseName,
+ ...(context.params.connection.dataSourceId
+ ? { dataSourceId: context.params.connection.dataSourceId }
+ : {}),
+ format: options.format,
+ statement: context.params.statement,
+ limit: options.limit,
+ admin: tabStore.currentTab?.mode === "ADMIN",
+ password: options.password,
+ schema: context.params.connection.schema,
+ })
+ );
+ contents.push({
+ content,
+ filename: `${
+ extractDatabaseResourceName(database.name).databaseName
+ }.${dayjs(new Date()).format("YYYY-MM-DDTHH-mm-ss")}.zip`,
+ });
+ } catch (e) {
+ pushNotification({
+ module: "bytebase",
+ style: "CRITICAL",
+ title: t("sql-editor.batch-export.failed-for-db", {
+ db: databaseName,
+ }),
+ description: String(e),
+ });
+ }
+ }
+ resolve(contents);
+ setSelectedDatabaseNames(new Set());
+ })();
+ };
+
+ if (queriedDatabaseNames.length <= 1) {
+ return null;
+ }
+
+ return (
+ <div className="w-full flex flex-row justify-start items-center p-2 pb-0 gap-2 shrink-0">
+ {showEmptySwitch && (
+ <Tooltip
+ content={t("sql-editor.batch-query.show-or-hide-empty-query-results")}
+ side="bottom"
+ >
+ <Button
+ variant={showEmpty ? "default" : "ghost"}
+ size="sm"
+ className="h-7 px-1.5 mb-2"
+ onClick={() => setShowEmpty(!showEmpty)}
+ aria-label={t(
+ "sql-editor.batch-query.show-or-hide-empty-query-results"
+ )}
+ >
+ {showEmpty ? (
+ <Eye className="size-4" />
+ ) : (
+ <EyeOff className="size-4" />
+ )}
+ </Button>
+ </Tooltip>
+ )}
+
+ <div className="mb-2">
+ <DataExportButton
+ size="sm"
+ viewMode="DRAWER"
+ supportFormats={[
+ ExportFormat.CSV,
+ ExportFormat.JSON,
+ ExportFormat.SQL,
+ ExportFormat.XLSX,
+ ]}
+ supportPassword
+ text={t("sql-editor.batch-export.self")}
+ tooltip={t("sql-editor.batch-export.tooltip", { max: MAX_EXPORT })}
+ validate={validateExport}
+ maximumExportCount={queryDataPolicy.maximumResultRows}
+ onExport={handleExport}
+ formContent={
+ <div className="w-full flex flex-col gap-y-2">
+ <div>
+ <p className="text-sm font-medium text-control">
+ {t("database.select")}
+ <span className="text-error ml-0.5">*</span>
+ </p>
+ <span className="text-xs text-control-light">
+ {t("sql-editor.batch-export.tooltip", { max: MAX_EXPORT })}
+ </span>
+ </div>
+ <DatabaseTableView
+ databases={databaseList}
+ mode="PROJECT"
+ selectedNames={selectedDatabaseNames}
+ onSelectedNamesChange={setSelectedDatabaseNames}
+ />
+ </div>
+ }
+ />
+ </div>
+
+ <div className="overflow-x-auto pb-2 flex-1">
+ <div className="flex flex-row justify-start items-center gap-2">
+ {filteredItems.map((item) => (
+ <TabContextMenu
+ key={item.database.name}
+ index={items.indexOf(item)}
+ >
+ <TabButton
+ item={item}
+ isSelected={selectedDatabase === item.database}
+ onSelect={() => onSelectedDatabaseChange(item.database)}
+ onClose={() => handleCloseSingleResultView(item)}
+ isFailed={isDatabaseQueryFailed(item)}
+ isEmpty={isEmptyQueryItem(item)}
+ />
+ </TabContextMenu>
+ ))}
+ </div>
+ </div>
+ </div>
+ );
+}
+
+type TabButtonProps = {
+ item: BatchQueryItem;
+ isSelected: boolean;
+ onSelect: () => void;
+ onClose: () => void;
+ isFailed: boolean;
+ isEmpty: boolean;
+};
+
+function TabButton({
+ item,
+ isSelected,
+ onSelect,
+ onClose,
+ isFailed,
+ isEmpty,
+}: TabButtonProps) {
+ const { t } = useTranslation();
+ const environment = getDatabaseEnvironment(item.database);
+ const colorRgb = hexToRgb(environment.color || "#4f46e5").join(", ");
+ const style = {
+ backgroundColor: `rgba(${colorRgb}, 0.1)`,
+ borderTopColor: `rgb(${colorRgb})`,
+ color: `rgb(${colorRgb})`,
+ borderTop: isSelected ? "3px solid" : "",
+ };
+ const instance = getInstanceResource(item.database);
+
+ return (
+ <button
+ type="button"
+ style={style}
+ onClick={onSelect}
+ className={cn(
+ "inline-flex items-center gap-x-1 h-7 px-2 rounded-xs text-xs font-medium",
+ "border border-control-border cursor-pointer whitespace-nowrap"
+ )}
+ >
+ {EngineIconPath[instance.engine] && (
+ <img
+ src={EngineIconPath[instance.engine]}
+ alt=""
+ className="size-4 shrink-0"
+ />
+ )}
+ <span className="truncate">
+ {extractDatabaseResourceName(item.database.name).databaseName}
+ </span>
+ {isFailed && <CircleAlert className="ml-1 text-error size-4 shrink-0" />}
+ {isEmpty && (
+ <span className="text-control-placeholder italic ml-1">
+ ({t("common.empty")})
+ </span>
+ )}
+ <X
+ className="ml-1 text-control-light hover:text-control size-4 shrink-0"
+ onClick={(e) => {
+ e.stopPropagation();
+ onClose();
+ }}
+ />
+ </button>
+ );
+}
diff --git a/frontend/src/react/components/sql-editor/ResultPanel/ContextMenu.tsx b/frontend/src/react/components/sql-editor/ResultPanel/ContextMenu.tsx
new file mode 100644
index 0000000000..a1ee8421b5
--- /dev/null
+++ b/frontend/src/react/components/sql-editor/ResultPanel/ContextMenu.tsx
@@ -0,0 +1,64 @@
+import type { ReactElement } from "react";
+import { useTranslation } from "react-i18next";
+import {
+ ContextMenu,
+ ContextMenuContent,
+ ContextMenuItem,
+ ContextMenuTrigger,
+} from "@/react/components/ui/context-menu";
+import {
+ type CloseTabAction,
+ resultTabEvents,
+} from "@/views/sql-editor/EditorPanel/ResultPanel/resultTabContext";
+
+interface TabContextMenuProps {
+ index: number;
+ /**
+ * The tab button. Wrapped with a right-click `ContextMenuTrigger` so Base
+ * UI handles positioning. The element must accept a ref / className via
+ * Base UI's `render` prop pattern — passing a single React element is the
+ * standard usage.
+ */
+ children: ReactElement;
+}
+
+const ACTIONS: readonly CloseTabAction[] = [
+ "CLOSE",
+ "CLOSE_OTHERS",
+ "CLOSE_TO_THE_RIGHT",
+ "CLOSE_ALL",
+];
+
+const ACTION_I18N_KEYS: Record<CloseTabAction, string> = {
+ CLOSE: "sql-editor.tab.context-menu.actions.close",
+ CLOSE_OTHERS: "sql-editor.tab.context-menu.actions.close-others",
+ CLOSE_TO_THE_RIGHT: "sql-editor.tab.context-menu.actions.close-to-the-right",
+ CLOSE_ALL: "sql-editor.tab.context-menu.actions.close-all",
+};
+
+/**
+ * Replaces `frontend/src/views/sql-editor/EditorPanel/ResultPanel/ContextMenu.vue`.
+ * Wraps a single tab button with a right-click context menu. Selecting an
+ * action emits `close-tab` on `resultTabEvents`; the parent
+ * `BatchQuerySelect` subscribes and performs the close.
+ */
+export function TabContextMenu({ index, children }: TabContextMenuProps) {
+ const { t } = useTranslation();
+
+ const handleSelect = (action: CloseTabAction) => {
+ void resultTabEvents.emit("close-tab", { index, action });
+ };
+
+ return (
+ <ContextMenu>
+ <ContextMenuTrigger render={children} />
+ <ContextMenuContent>
+ {ACTIONS.map((action) => (
+ <ContextMenuItem key={action} onClick={() => handleSelect(action)}>
+ {t(ACTION_I18N_KEYS[action])}
+ </ContextMenuItem>
+ ))}
+ </ContextMenuContent>
+ </ContextMenu>
+ );
+}
diff --git a/frontend/src/react/locales/en-US.json b/frontend/src/react/locales/en-US.json
index 4ed211bc84..fa2a38a8b7 100644
--- a/frontend/src/react/locales/en-US.json
+++ b/frontend/src/react/locales/en-US.json
@@ -88,6 +88,7 @@
}
}
},
+ "export-finished": "Export finished",
"export-tooltip": "Must select start time and end time within 30 days",
"table": {
"actor": "Actor",
@@ -399,6 +400,7 @@
"statement": "Statement",
"status": "Status",
"submit": "Submit",
+ "succeed": "Succeed",
"system": "System",
"table": "Table",
"title": "Title",
@@ -913,6 +915,9 @@
"data-export": "Data Export"
},
"export-data": {
+ "export-format": "Export format",
+ "export-rows": "Export rows",
+ "password-info": "Provide a password to encrypt the export file.",
"password-optional": "Encrypt with password (Optional)"
},
"export-data.password-optional": "Password (optional)",
@@ -2609,6 +2614,11 @@
},
"allow-admin-mode-only": "Instance <instance></instance> is accessible in admin mode only.",
"and-n-more-databases": "and {{n}} more databases",
+ "batch-export": {
+ "failed-for-db": "Failed to export data for {{db}}",
+ "self": "Batch export",
+ "tooltip": "Select at most {{max}} databases to batch export latest query results"
+ },
"batch-query": {
"batch": "Batch",
"description": "Batch query {{database}} additional databases and {{group}} database groups under {{project}}.",
@@ -2617,7 +2627,8 @@
"readonly": "Read-only",
"self": "Select data source for batch",
"tooltip": "Will find available data sources with restriction policy, then apply the selection."
- }
+ },
+ "show-or-hide-empty-query-results": "Show / hide empty query results"
},
"choose-folder": "Choose or create folder",
"choose-folder-tips": "You can create a new folder by entering a non-existent path. The folders should be joined with a \"/\".",
@@ -2629,6 +2640,7 @@
"copy-name": "Copy name",
"copy-url": "Copy URL",
"ddl-dml-requires-data-change-plan": "To execute DDL/DML statements in <environment></environment>, please submit a Data Change Plan for approval.",
+ "download-as-file": "Download as {{file}}",
"duration-day": "{{days}} day",
"duration-days": "{{days}} days",
"duration-hours": "{{hours}} hour | {{hours}} hours",
diff --git a/frontend/src/react/locales/es-ES.json b/frontend/src/react/locales/es-ES.json
index 7aa6b8b660..c717835b5a 100644
--- a/frontend/src/react/locales/es-ES.json
+++ b/frontend/src/react/locales/es-ES.json
@@ -87,6 +87,7 @@
}
}
},
+ "export-finished": "Exportación finalizada",
"export-tooltip": "Debe seleccionar hora de inicio y fin dentro de 30 días",
"table": {
"actor": "Actor",
@@ -393,6 +394,7 @@
"statement": "Declaración",
"status": "Estado",
"submit": "Submit",
+ "succeed": "Tener éxito",
"system": "Sistema",
"table": "Tabla",
"title": "Título",
@@ -906,6 +908,9 @@
"data-export": "Exportación de datos"
},
"export-data": {
+ "export-format": "Formato de exportación",
+ "export-rows": "Exportar filas",
+ "password-info": "Proporcione una contraseña para cifrar el archivo de exportación.",
"password-optional": "Cifrar con contraseña (opcional)"
},
"export-data.password-optional": "Contraseña (opcional)",
@@ -2595,6 +2600,11 @@
},
"allow-admin-mode-only": "La instancia <instance></instance> solo es accesible en modo administrador.",
"and-n-more-databases": "and {{n}} more databases",
+ "batch-export": {
+ "failed-for-db": "No se pudieron exportar los datos de {{db}}",
+ "self": "Exportación por lotes",
+ "tooltip": "Seleccione como máximo {{max}} bases de datos para exportar por lotes los resultados de las últimas consultas"
+ },
"batch-query": {
"batch": "Lote",
"description": "Consulta por lotes {{database}} bases de datos adicionales y {{group}} grupos de bases de datos bajo {{project}}.",
@@ -2603,7 +2613,8 @@
"readonly": "Sólo lectura",
"self": "Seleccionar la fuente de datos para el lote",
"tooltip": "Encontrará fuentes de datos disponibles con política de restricción y luego aplicará la selección."
- }
+ },
+ "show-or-hide-empty-query-results": "Mostrar/ocultar resultados de consulta vacíos"
},
"choose-folder": "Seleccionar o crear una carpeta",
"choose-folder-tips": "Puedes crear una nueva carpeta introduciendo una ruta que no exista. Las carpetas deben unirse con una barra diagonal (\"/\").",
@@ -2615,6 +2626,7 @@
"copy-name": "Copiar nombre",
"copy-url": "Copiar URL",
"ddl-dml-requires-data-change-plan": "Para ejecutar sentencias DDL/DML en <environment></environment>, envíe un Plan de Cambio de Datos para su aprobación.",
+ "download-as-file": "Descargar como {{file}}",
"duration-day": "{{days}} day",
"duration-days": "{{days}} days",
"duration-hours": "{{hours}} hour | {{hours}} hours",
diff --git a/frontend/src/react/locales/ja-JP.json b/frontend/src/react/locales/ja-JP.json
index 765f999ad0..ede84f5884 100644
--- a/frontend/src/react/locales/ja-JP.json
+++ b/frontend/src/react/locales/ja-JP.json
@@ -87,6 +87,7 @@
}
}
},
+ "export-finished": "エクスポートが完了しました",
"export-tooltip": "30日以内の開始時間と終了時間を選択する必要があります",
"table": {
"actor": "操作者",
@@ -393,6 +394,7 @@
"statement": "ステートメント",
"status": "ステータス",
"submit": "Submit",
+ "succeed": "成功する",
"system": "システム",
"table": "テーブル",
"title": "タイトル",
@@ -906,6 +908,9 @@
"data-export": "データエクスポート"
},
"export-data": {
+ "export-format": "エクスポート形式",
+ "export-rows": "エクスポート行数",
+ "password-info": "エクスポートされたファイルを暗号化するためのパスワードを入力します",
"password-optional": "パスワード暗号化の設定 (オプション)"
},
"export-data.password-optional": "パスワード(任意)",
@@ -2595,6 +2600,11 @@
},
"allow-admin-mode-only": "インスタンス <instance></instance> には管理者モードでのみアクセスできます。",
"and-n-more-databases": "and {{n}} more databases",
+ "batch-export": {
+ "failed-for-db": "{{db}} のデータのエクスポートに失敗しました",
+ "self": "一括エクスポート",
+ "tooltip": "最新のクエリ結果を一括エクスポートするには、最大 {{max}} 個のデータベースを選択してください"
+ },
"batch-query": {
"batch": "バッチ",
"description": "{{project}} の下の {{database}} 個の追加データベースと {{group}} 個のデータベース グループに対してバッチ クエリを実行します。",
@@ -2603,7 +2613,8 @@
"readonly": "読み取り専用",
"self": "バッチのデータソースを選択",
"tooltip": "制限ポリシーが設定された利用可能なデータ ソースを見つけて、選択を適用します。"
- }
+ },
+ "show-or-hide-empty-query-results": "空のクエリ結果の表示/非表示"
},
"choose-folder": "フォルダを選択または作成",
"choose-folder-tips": "存在しないパスを入力することで新しいフォルダを作成できます。フォルダは「/」で結合する必要があります。",
@@ -2615,6 +2626,7 @@
"copy-name": "名前をコピーする",
"copy-url": "URLをコピー",
"ddl-dml-requires-data-change-plan": "<environment></environment> で DDL/DML ステートメントを実行するには、承認のためデータ変更プランを送信してください。",
+ "download-as-file": "{{file}} 形式でダウンロード",
"duration-day": "{{days}} day",
"duration-days": "{{days}} days",
"duration-hours": "{{hours}} hour | {{hours}} hours",
diff --git a/frontend/src/react/locales/vi-VN.json b/frontend/src/react/locales/vi-VN.json
index 3ce68e82b3..7b246d9020 100644
--- a/frontend/src/react/locales/vi-VN.json
+++ b/frontend/src/react/locales/vi-VN.json
@@ -87,6 +87,7 @@
}
}
},
+ "export-finished": "Xuất hoàn tất",
"export-tooltip": "Phải chọn thời gian bắt đầu và kết thúc trong vòng 30 ngày",
"table": {
"actor": "Người thực hiện",
@@ -393,6 +394,7 @@
"statement": "Câu lệnh",
"status": "Trạng thái",
"submit": "Submit",
+ "succeed": "Thành công",
"system": "Hệ thống",
"table": "Bảng",
"title": "Tiêu đề",
@@ -906,6 +908,9 @@
"data-export": "Xuất dữ liệu"
},
"export-data": {
+ "export-format": "Định dạng xuất",
+ "export-rows": "Xuất số dòng",
+ "password-info": "Cung cấp mật khẩu để mã hóa tệp xuất.",
"password-optional": "Mã hóa bằng mật khẩu (Tùy chọn)"
},
"export-data.password-optional": "Mật khẩu (không bắt buộc)",
@@ -2595,6 +2600,11 @@
},
"allow-admin-mode-only": "Phiên bản <instance></instance> chỉ có thể truy cập ở chế độ quản trị.",
"and-n-more-databases": "and {{n}} more databases",
+ "batch-export": {
+ "failed-for-db": "Không xuất được dữ liệu cho {{db}}",
+ "self": "Xuất hàng loạt",
+ "tooltip": "Chọn tối đa {{max}} cơ sở dữ liệu để xuất hàng loạt kết quả truy vấn mới nhất"
+ },
"batch-query": {
"batch": "Hàng loạt",
"description": "Truy vấn hàng loạt {{database}} cơ sở dữ liệu bổ sung và {{group}} nhóm cơ sở dữ liệu trong {{project}}.",
@@ -2603,7 +2613,8 @@
"readonly": "Chỉ đọc",
"self": "Chọn nguồn dữ liệu cho lô",
"tooltip": "Sẽ tìm các nguồn dữ liệu có sẵn với chính sách hạn chế, sau đó áp dụng lựa chọn."
- }
+ },
+ "show-or-hide-empty-query-results": "Hiển thị / ẩn kết quả truy vấn trống"
},
"choose-folder": "Chọn hoặc tạo thư mục",
"choose-folder-tips": "Bạn có thể tạo một thư mục mới bằng cách nhập một đường dẫn không tồn tại. Các thư mục phải được nối bằng dấu \"/\".",
@@ -2615,6 +2626,7 @@
"copy-name": "Sao chép tên",
"copy-url": "Sao chép URL",
"ddl-dml-requires-data-change-plan": "Để thực thi câu lệnh DDL/DML trong <environment></environment>, vui lòng gửi Kế hoạch Thay đổi Dữ liệu để được phê duyệt.",
+ "download-as-file": "Tải xuống dưới dạng {{file}}",
"duration-day": "{{days}} day",
"duration-days": "{{days}} days",
"duration-hours": "{{hours}} hour | {{hours}} hours",
diff --git a/frontend/src/react/locales/zh-CN.json b/frontend/src/react/locales/zh-CN.json
index 5ca9f3d40a..0510ffb43a 100644
--- a/frontend/src/react/locales/zh-CN.json
+++ b/frontend/src/react/locales/zh-CN.json
@@ -87,6 +87,7 @@
}
}
},
+ "export-finished": "导出完成",
"export-tooltip": "必须选择 30 天范围内的开始和结束日期",
"table": {
"actor": "操作者",
@@ -393,6 +394,7 @@
"statement": "语句",
"status": "状态",
"submit": "提交",
+ "succeed": "成功",
"system": "系统",
"table": "表",
"title": "标题",
@@ -906,6 +908,9 @@
"data-export": "数据导出"
},
"export-data": {
+ "export-format": "导出格式",
+ "export-rows": "导出行数",
+ "password-info": "提供密码来对导出的文件进行加密",
"password-optional": "设置密码加密(可选)"
},
"export-data.password-optional": "密码(可选)",
@@ -2595,6 +2600,11 @@
},
"allow-admin-mode-only": "实例<instance></instance>只能通过管理员模式访问。",
"and-n-more-databases": "及其他 {{n}} 个数据库",
+ "batch-export": {
+ "failed-for-db": "无法导出 {{db}} 的数据",
+ "self": "批量导出",
+ "tooltip": "最多选择 {{max}} 个数据库,批量导出最后一次执行的查询结果"
+ },
"batch-query": {
"batch": "批量",
"description": "批量查询 {{project}} 下的 {{database}} 个数据库和 {{group}} 个数据库组。",
@@ -2603,7 +2613,8 @@
"readonly": "只读数据源",
"self": "选择批量查询使用的数据源",
"tooltip": "将先根据限制策略寻找数据源,然后应用该选择。"
- }
+ },
+ "show-or-hide-empty-query-results": "显示/隐藏空查询结果"
},
"choose-folder": "选择或创建文件夹",
"choose-folder-tips": "您可以通过输入不存在的路径来创建新文件夹。文件夹之间应以\"/\"连接。",
@@ -2615,6 +2626,7 @@
"copy-name": "复制名称",
"copy-url": "复制 URL",
"ddl-dml-requires-data-change-plan": "如需在 <environment></environment> 中执行 DDL/DML 语句,请创建变更计划以获得审批。",
+ "download-as-file": "下载为 {{file}} 格式",
"duration-day": "{{days}} 天",
"duration-days": "{{days}} 天",
"duration-hours": "{{hours}} 小时",
diff --git a/frontend/src/react/pages/settings/DatabasesPage.tsx b/frontend/src/react/pages/settings/DatabasesPage.tsx
index 11a5e06952..c119e61390 100644
--- a/frontend/src/react/pages/settings/DatabasesPage.tsx
+++ b/frontend/src/react/pages/settings/DatabasesPage.tsx
@@ -78,8 +78,11 @@ export function DatabasesPage() {
// Search state — default to showing unassigned databases from default project
const [searchParams, setSearchParams] = useState<SearchParams>(() => {
const currentRoute = router.currentRoute.value;
- const queryString = currentRoute.query.q as string;
- if (queryString) {
+ const hasQ = "q" in (currentRoute.query ?? {});
+ const queryString = (currentRoute.query.q as string) ?? "";
+ if (hasQ) {
+ // URL has an explicit `q` param (may be empty if the user cleared all
+ // filters) — parse it and do NOT re-apply the default project scope.
const scopes: { id: string; value: string }[] = [];
const queryParts: string[] = [];
for (const token of queryString.split(/\s+/).filter(Boolean)) {
@@ -101,6 +104,7 @@ export function DatabasesPage() {
}
return { query: queryParts.join(" "), scopes };
}
+ // First visit (no `q` in URL) — default to the unassigned project.
return {
query: "",
scopes: [
@@ -294,7 +298,7 @@ export function DatabasesPage() {
const queryString = parts.join(" ");
const currentQuery = router.currentRoute.value.query.q as string;
if (queryString !== (currentQuery ?? "")) {
- router.replace({ query: queryString ? { q: queryString } : {} });
+ router.replace({ query: { q: queryString } });
}
}, [searchParams]);
diff --git a/frontend/src/react/pages/settings/InstanceDetailPage.tsx b/frontend/src/react/pages/settings/InstanceDetailPage.tsx
index 0b3a370da4..9f7f751d69 100644
--- a/frontend/src/react/pages/settings/InstanceDetailPage.tsx
+++ b/frontend/src/react/pages/settings/InstanceDetailPage.tsx
@@ -1,3 +1,5 @@
+import { create } from "@bufbuild/protobuf";
+import { FieldMaskSchema } from "@bufbuild/protobuf/wkt";
import { useCallback, useEffect, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import {
@@ -7,7 +9,13 @@ import {
type SearchParams,
type ValueOption,
} from "@/react/components/AdvancedSearch";
-import { DatabaseTable } from "@/react/components/database";
+import {
+ DatabaseBatchOperationsBar,
+ DatabaseTable,
+ LabelEditorSheet,
+ TransferProjectSheet,
+} from "@/react/components/database";
+import { EditEnvironmentSheet } from "@/react/components/EditEnvironmentSheet";
import { EngineIcon } from "@/react/components/EngineIcon";
import { EnvironmentLabel } from "@/react/components/EnvironmentLabel";
import {
@@ -27,7 +35,9 @@ import {
} from "@/react/components/ui/tabs";
import { useVueState } from "@/react/hooks/useVueState";
import {
+ pushNotification,
useDatabaseV1Store,
+ useDBSchemaV1Store,
useEnvironmentV1Store,
useInstanceV1Store,
useProjectV1Store,
@@ -38,8 +48,17 @@ import {
projectNamePrefix,
} from "@/store/modules/v1/common";
import type { DatabaseFilter } from "@/store/modules/v1/database";
-import { UNKNOWN_ENVIRONMENT_NAME, unknownEnvironment } from "@/types";
+import {
+ isValidDatabaseName,
+ UNKNOWN_ENVIRONMENT_NAME,
+ unknownEnvironment,
+} from "@/types";
import { State } from "@/types/proto-es/v1/common_pb";
+import {
+ BatchUpdateDatabasesRequestSchema,
+ DatabaseSchema$,
+ UpdateDatabaseRequestSchema,
+} from "@/types/proto-es/v1/database_service_pb";
import {
extractProjectResourceName,
getDefaultPagination,
@@ -56,6 +75,7 @@ export function InstanceDetailPage({ instanceId }: { instanceId: string }) {
const { t } = useTranslation();
const instanceStore = useInstanceV1Store();
const databaseStore = useDatabaseV1Store();
+ const dbSchemaStore = useDBSchemaV1Store();
const instanceName = `${instanceNamePrefix}${instanceId}`;
const instance = useVueState(() =>
instanceStore.getInstanceByName(instanceName)
@@ -66,6 +86,167 @@ export function InstanceDetailPage({ instanceId }: { instanceId: string }) {
query: "",
scopes: [{ id: "instance", value: instanceId, readonly: true }],
});
+
+ // Selection / batch operations
+ const [selectedNames, setSelectedNames] = useState<Set<string>>(new Set());
+ const [refreshToken, setRefreshToken] = useState(0);
+ const [syncing, setSyncing] = useState(false);
+ const [showLabelEditor, setShowLabelEditor] = useState(false);
+ const [showEditEnvDrawer, setShowEditEnvDrawer] = useState(false);
+ const [showTransferDrawer, setShowTransferDrawer] = useState(false);
+
+ const selectedDatabases = useMemo(() => {
+ if (selectedNames.size === 0) return [];
+ return Array.from(selectedNames)
+ .filter((name) => isValidDatabaseName(name))
+ .map((name) => databaseStore.getDatabaseByName(name));
+ }, [selectedNames, databaseStore]);
+
+ const refresh = useCallback(() => {
+ setRefreshToken((prev) => prev + 1);
+ setSelectedNames(new Set());
+ }, []);
+
+ const handleSyncSchema = useCallback(async () => {
+ if (syncing) return;
+ setSyncing(true);
+ pushNotification({
+ module: "bytebase",
+ style: "INFO",
+ title: t("db.start-to-sync-schema"),
+ });
+ try {
+ await databaseStore.batchSyncDatabases(Array.from(selectedNames));
+ for (const name of selectedNames) {
+ dbSchemaStore.removeCache(name);
+ }
+ pushNotification({
+ module: "bytebase",
+ style: "SUCCESS",
+ title: t("db.successfully-synced-schema"),
+ });
+ setSelectedNames(new Set());
+ } catch {
+ pushNotification({
+ module: "bytebase",
+ style: "CRITICAL",
+ title: t("db.failed-to-sync-schema"),
+ });
+ } finally {
+ setSyncing(false);
+ }
+ }, [syncing, selectedNames, databaseStore, dbSchemaStore, t]);
+
+ const handleLabelsApply = useCallback(
+ async (labelsList: { [key: string]: string }[]) => {
+ try {
+ await databaseStore.batchUpdateDatabases(
+ create(BatchUpdateDatabasesRequestSchema, {
+ parent: "-",
+ requests: selectedDatabases.map((database, i) =>
+ create(UpdateDatabaseRequestSchema, {
+ database: create(DatabaseSchema$, {
+ ...database,
+ labels: labelsList[i],
+ }),
+ updateMask: create(FieldMaskSchema, { paths: ["labels"] }),
+ })
+ ),
+ })
+ );
+ refresh();
+ pushNotification({
+ module: "bytebase",
+ style: "SUCCESS",
+ title: t("common.updated"),
+ });
+ } catch {
+ pushNotification({
+ module: "bytebase",
+ style: "CRITICAL",
+ title: t("common.failed"),
+ });
+ }
+ },
+ [selectedDatabases, databaseStore, refresh, t]
+ );
+
+ const handleEnvironmentUpdate = useCallback(
+ async (environment: string) => {
+ try {
+ await databaseStore.batchUpdateDatabases(
+ create(BatchUpdateDatabasesRequestSchema, {
+ parent: "-",
+ requests: selectedDatabases.map((database) =>
+ create(UpdateDatabaseRequestSchema, {
+ database: create(DatabaseSchema$, {
+ name: database.name,
+ environment,
+ }),
+ updateMask: create(FieldMaskSchema, { paths: ["environment"] }),
+ })
+ ),
+ })
+ );
+ refresh();
+ pushNotification({
+ module: "bytebase",
+ style: "SUCCESS",
+ title: t("common.updated"),
+ });
+ } catch {
+ pushNotification({
+ module: "bytebase",
+ style: "CRITICAL",
+ title: t("common.failed"),
+ });
+ }
+ },
+ [selectedDatabases, databaseStore, refresh, t]
+ );
+
+ const handleTransferProject = useCallback(
+ async (projectName: string) => {
+ try {
+ await databaseStore.batchUpdateDatabases(
+ create(BatchUpdateDatabasesRequestSchema, {
+ parent: "-",
+ requests: selectedDatabases.map((database) =>
+ create(UpdateDatabaseRequestSchema, {
+ database: create(DatabaseSchema$, {
+ name: database.name,
+ project: projectName,
+ }),
+ updateMask: create(FieldMaskSchema, { paths: ["project"] }),
+ })
+ ),
+ })
+ );
+ refresh();
+ pushNotification({
+ module: "bytebase",
+ style: "SUCCESS",
+ title: t("database.successfully-transferred-databases"),
+ });
+ } catch {
+ pushNotification({
+ module: "bytebase",
+ style: "CRITICAL",
+ title: t("common.failed"),
+ });
+ }
+ },
+ [selectedDatabases, databaseStore, refresh, t]
+ );
+ // Trigger a Pinia-side fetch on mount. The parent `InstanceRouteShell`
+ // populates the React-side `useAppStore` cache, but this page reads
+ // from the Pinia v1 store (`useInstanceV1Store`) — they're separate
+ // caches. Without this, hard-refreshing the page shows "Unknown
+ // instance" because the Pinia cache hasn't been hydrated.
+ useEffect(() => {
+ void instanceStore.getOrFetchInstanceByName(instanceName);
+ }, [instanceStore, instanceName]);
+
// Sync tab with URL hash
useEffect(() => {
const hash = window.location.hash.replace(/^#?/, "");
@@ -241,7 +422,38 @@ export function InstanceDetailPage({ instanceId }: { instanceId: string }) {
placeholder={t("database.filter-database")}
scopeOptions={scopeOptions}
/>
- <DatabaseTable filter={filter} parent={instance.name} mode="ALL" />
+ <DatabaseBatchOperationsBar
+ databases={selectedDatabases}
+ onSyncSchema={handleSyncSchema}
+ onEditLabels={() => setShowLabelEditor(true)}
+ onEditEnvironment={() => setShowEditEnvDrawer(true)}
+ onTransferProject={() => setShowTransferDrawer(true)}
+ />
+ <EditEnvironmentSheet
+ open={showEditEnvDrawer}
+ onClose={() => setShowEditEnvDrawer(false)}
+ onUpdate={handleEnvironmentUpdate}
+ />
+ <LabelEditorSheet
+ open={showLabelEditor}
+ databases={selectedDatabases}
+ onClose={() => setShowLabelEditor(false)}
+ onApply={handleLabelsApply}
+ />
+ <TransferProjectSheet
+ open={showTransferDrawer}
+ databases={selectedDatabases}
+ onClose={() => setShowTransferDrawer(false)}
+ onTransfer={handleTransferProject}
+ />
+ <DatabaseTable
+ filter={filter}
+ parent={instance.name}
+ mode="ALL"
+ selectedNames={selectedNames}
+ onSelectedNamesChange={setSelectedNames}
+ refreshToken={refreshToken}
+ />
</div>
</TabsPanel>
diff --git a/frontend/src/react/pages/settings/InstancesPage.tsx b/frontend/src/react/pages/settings/InstancesPage.tsx
index 7491f5bdab..5fdfbeb0ea 100644
--- a/frontend/src/react/pages/settings/InstancesPage.tsx
+++ b/frontend/src/react/pages/settings/InstancesPage.tsx
@@ -820,12 +820,7 @@ export function InstancesPage() {
const currentQuery = router.currentRoute.value.query;
const currentQueryString = currentQuery.q as string;
if (queryString !== (currentQueryString ?? "")) {
- const nextQuery = { ...currentQuery };
- if (queryString) {
- nextQuery.q = queryString;
- } else {
- delete nextQuery.q;
- }
+ const nextQuery = { ...currentQuery, q: queryString };
router.replace({ query: nextQuery });
}
}, [searchParams]);
diff --git a/frontend/src/react/pages/settings/ProjectsPage.tsx b/frontend/src/react/pages/settings/ProjectsPage.tsx
index 72c84bd72e..28d6573f68 100644
--- a/frontend/src/react/pages/settings/ProjectsPage.tsx
+++ b/frontend/src/react/pages/settings/ProjectsPage.tsx
@@ -527,7 +527,7 @@ export function ProjectsPage() {
const queryString = parts.join(" ");
const currentQuery = router.currentRoute.value.query.q as string;
if (queryString !== (currentQuery ?? "")) {
- router.replace({ query: queryString ? { q: queryString } : {} });
+ router.replace({ query: { q: queryString } });
}
}, [searchParams]);
diff --git a/frontend/src/views/sql-editor/EditorPanel/ResultPanel/BatchQuerySelect.vue b/frontend/src/views/sql-editor/EditorPanel/ResultPanel/BatchQuerySelect.vue
deleted file mode 100644
index 17a488446c..0000000000
--- a/frontend/src/views/sql-editor/EditorPanel/ResultPanel/BatchQuerySelect.vue
+++ /dev/null
@@ -1,359 +0,0 @@
-<template>
- <div
- v-if="queriedDatabaseNames.length > 1"
- class="w-full flex flex-row justify-start items-center p-2 pb-0 gap-2 shrink-0"
- >
- <NTooltip v-if="showEmptySwitch">
- <template #trigger>
- <NButton
- tertiary
- size="small"
- :type="showEmpty ? 'primary' : 'default'"
- style="--n-padding: 6px; margin-bottom: 0.5rem"
- @click="showEmpty = !showEmpty"
- >
- <EyeIcon v-if="showEmpty" class="w-4 h-4" />
- <EyeOffIcon v-else class="w-4 h-4" />
- </NButton>
- </template>
- <template #default>
- {{ $t("sql-editor.batch-query.show-or-hide-empty-query-results") }}
- </template>
- </NTooltip>
-
- <DataExportButton
- tertiary
- size="small"
- :support-formats="[
- ExportFormat.CSV,
- ExportFormat.JSON,
- ExportFormat.SQL,
- ExportFormat.XLSX,
- ]"
- style="margin-bottom: 0.5rem"
- :view-mode="'DRAWER'"
- :text="$t('sql-editor.batch-export.self')"
- :tooltip="$t('sql-editor.batch-export.tooltip', { max: MAX_EXPORT })"
- :validate="validateExport"
- :support-password="true"
- :maximum-export-count="queryDataPolicy.maximumResultRows"
- @export="handleExportBtnClick"
- >
- <template #form>
- <div class="w-full mb-6 flex flex-col gap-y-2">
- <div>
- <p class="textlabel">
- {{ $t("database.select") }}
- <RequiredStar />
- </p>
- <span class="textinfolabel">
- {{ $t("sql-editor.batch-export.tooltip", { max: MAX_EXPORT }) }}
- </span>
- </div>
- <DatabaseV1Table
- :schemaless="true"
- :mode="'PROJECT_SHORT'"
- :database-list="databaseList"
- :show-selection="true"
- :pagination="{
- defaultPageSize: MAX_EXPORT,
- disabled: false,
- }"
- v-model:selected-database-names="selectedDatabaseNameList"
- />
- </div>
- </template>
- </DataExportButton>
-
- <NScrollbar x-scrollable class="pb-2">
- <div class="flex flex-row justify-start items-center gap-2">
- <NButton
- v-for="(item, index) in filteredItems"
- :key="item.database.name"
- secondary
- strong
- size="small"
- :type="'default'"
- :style="{
- ...getBackgroundColorRgb(item.database),
- borderTop: selectedDatabase === item.database ? '3px solid' : '',
- }"
- @contextmenu.stop.prevent="
- contextMenuRef?.show(index, $event)
- "
- @click="$emit('update:selected-database', item.database)"
- >
- <RichDatabaseName :database="item.database" />
- <CircleAlertIcon
- v-if="isDatabaseQueryFailed(item)"
- class="ml-1 text-red-600 w-4 h-auto"
- />
- <span
- v-if="isEmptyQueryItem(item)"
- class="text-control-placeholder italic ml-1"
- >
- ({{ $t("common.empty") }})
- </span>
- <XIcon
- class="ml-1 text-gray-400 w-4 h-auto hover:text-gray-600"
- @click.stop="handleCloseSingleResultView(item)"
- />
- </NButton>
- </div>
- </NScrollbar>
- <ContextMenu ref="contextMenuRef" />
- </div>
-</template>
-
-<script setup lang="ts">
-import { create } from "@bufbuild/protobuf";
-import dayjs from "dayjs";
-import { head } from "lodash-es";
-import { CircleAlertIcon, EyeIcon, EyeOffIcon, XIcon } from "lucide-vue-next";
-import { NButton, NScrollbar, NTooltip } from "naive-ui";
-import { storeToRefs } from "pinia";
-import { computed, ref, watch } from "vue";
-import type {
- DownloadContent,
- ExportOption,
-} from "@/components/DataExportButton.vue";
-import DataExportButton from "@/components/DataExportButton.vue";
-import RequiredStar from "@/components/RequiredStar.vue";
-import { RichDatabaseName } from "@/components/v2";
-import { DatabaseV1Table } from "@/components/v2/Model/DatabaseV1Table";
-import { useEmitteryEventListener } from "@/composables/useEmitteryEventListener";
-import { t } from "@/plugins/i18n";
-import {
- pushNotification,
- useDatabaseV1Store,
- useSQLEditorStore,
- useSQLEditorTabStore,
- useSQLStore,
-} from "@/store";
-import type { SQLEditorDatabaseQueryContext } from "@/types";
-import { ExportFormat } from "@/types/proto-es/v1/common_pb";
-import type { Database } from "@/types/proto-es/v1/database_service_pb";
-import { ExportRequestSchema } from "@/types/proto-es/v1/sql_service_pb";
-import {
- extractDatabaseResourceName,
- getDatabaseEnvironment,
- hexToRgb,
-} from "@/utils";
-import ContextMenu from "./ContextMenu.vue";
-import { provideResultTabListContext } from "./context";
-
-const MAX_EXPORT = 20;
-
-type BatchQueryItem = {
- database: Database;
- context: SQLEditorDatabaseQueryContext | undefined;
-};
-
-const props = defineProps<{
- selectedDatabase: Database | undefined;
-}>();
-
-const emit = defineEmits<{
- (event: "update:selected-database", db: Database | undefined): void;
-}>();
-
-const tabStore = useSQLEditorTabStore();
-const { currentTab: tab } = storeToRefs(tabStore);
-const databaseStore = useDatabaseV1Store();
-const sqlStore = useSQLStore();
-const showEmpty = ref<boolean>(true);
-const contextMenu = provideResultTabListContext();
-const contextMenuRef = ref<InstanceType<typeof ContextMenu>>();
-const { queryDataPolicy } = storeToRefs(useSQLEditorStore());
-
-const selectedDatabaseNameList = ref<string[]>([]);
-
-const queriedDatabaseNames = computed(() =>
- Array.from(tab.value?.databaseQueryContexts?.keys() || [])
-);
-
-const databaseList = computed(() => {
- return queriedDatabaseNames.value.map((name) =>
- databaseStore.getDatabaseByName(name)
- );
-});
-
-const validateExport = () => {
- return (
- selectedDatabaseNameList.value.length > 0 &&
- selectedDatabaseNameList.value.length <= MAX_EXPORT
- );
-};
-
-const items = computed(() => {
- return queriedDatabaseNames.value.map<BatchQueryItem>((name) => {
- const database = databaseStore.getDatabaseByName(name);
- const context = head(tab.value?.databaseQueryContexts?.get(name));
- return { database, context };
- });
-});
-
-const isEmptyQueryItem = (item: BatchQueryItem) => {
- if (!item.context) {
- return true;
- }
- if (item.context.resultSet?.error) {
- // Failed queries have empty result sets, but should not be recognized
- // as empty result sets.
- return false;
- }
- if (item.context.status !== "DONE") {
- return false;
- }
- return item.context.resultSet?.results.every(
- (result) => result.rows.length === 0
- );
-};
-
-const showEmptySwitch = computed(() => {
- if (items.value.length <= 1) {
- return false;
- }
- return items.value.some((item) => isEmptyQueryItem(item));
-});
-
-const filteredItems = computed(() => {
- if (showEmpty.value || !showEmptySwitch.value) {
- return items.value;
- }
-
- return items.value.filter((item) => !isEmptyQueryItem(item));
-});
-
-const isDatabaseQueryFailed = (item: BatchQueryItem) => {
- // If there is any error in the result set, we consider the query failed.
- return (
- item.context?.resultSet?.error ||
- item.context?.resultSet?.results.find((result) => result.error)
- );
-};
-
-const handleCloseSingleResultView = (item: BatchQueryItem) => {
- const contexts = tab.value?.databaseQueryContexts?.get(item.database.name);
- if (!contexts) {
- return;
- }
- for (const context of contexts) {
- context.abortController?.abort();
- }
- tab.value?.databaseQueryContexts?.delete(item.database.name);
-};
-
-// Auto select a proper database when the databases are ready.
-watch(
- () => filteredItems.value,
- (items) => {
- const curr = props.selectedDatabase;
- if (!curr || !items.find((item) => item.database === curr)) {
- emit("update:selected-database", head(items)?.database);
- }
- },
- {
- immediate: true,
- }
-);
-
-const getBackgroundColorRgb = (database: Database) => {
- const color = hexToRgb(
- getDatabaseEnvironment(database).color || "#4f46e5"
- ).join(", ");
- return {
- backgroundColor: `rgba(${color}, 0.1)`,
- borderTopColor: `rgb(${color})`,
- color: `rgb(${color})`,
- borderTop: "3px solid",
- };
-};
-
-const handleExportBtnClick = async ({
- options,
- resolve,
-}: {
- options: ExportOption;
- reject: (reason?: unknown) => void;
- resolve: (content: DownloadContent[]) => void;
-}) => {
- const contents: DownloadContent[] = [];
- for (const databaseName of selectedDatabaseNameList.value) {
- const database = databaseStore.getDatabaseByName(databaseName);
- const context = head(tab.value?.databaseQueryContexts?.get(databaseName));
- if (!context) {
- continue;
- }
- try {
- const content = await sqlStore.exportData(
- create(ExportRequestSchema, {
- name: databaseName,
- ...(context.params.connection.dataSourceId
- ? { dataSourceId: context.params.connection.dataSourceId }
- : {}),
- format: options.format,
- statement: context.params.statement,
- limit: options.limit,
- admin: tabStore.currentTab?.mode === "ADMIN",
- password: options.password,
- schema: context.params.connection.schema,
- })
- );
-
- contents.push({
- content,
- // the download file is always zip file.
- filename: `${extractDatabaseResourceName(database.name).databaseName}.${dayjs(new Date()).format("YYYY-MM-DDTHH-mm-ss")}.zip`,
- });
- } catch (e) {
- pushNotification({
- module: "bytebase",
- style: "CRITICAL",
- title: t("sql-editor.batch-export.failed-for-db", {
- db: databaseName,
- }),
- description: String(e),
- });
- }
- }
-
- resolve(contents);
- selectedDatabaseNameList.value = [];
-};
-
-useEmitteryEventListener(
- contextMenu.events,
- "close-tab",
- async ({ index, action }) => {
- const max = items.value.length - 1;
- switch (action) {
- case "CLOSE": {
- handleCloseSingleResultView(items.value[index]);
- return;
- }
- case "CLOSE_OTHERS": {
- for (let i = max; i > index; i--) {
- handleCloseSingleResultView(items.value[i]);
- }
- for (let i = index - 1; i >= 0; i--) {
- handleCloseSingleResultView(items.value[i]);
- }
- return;
- }
- case "CLOSE_TO_THE_RIGHT": {
- for (let i = max; i > index; i--) {
- handleCloseSingleResultView(items.value[i]);
- }
- return;
- }
- case "CLOSE_ALL": {
- for (let i = max; i >= 0; i--) {
- handleCloseSingleResultView(items.value[i]);
- }
- return;
- }
- }
- }
-);
-</script>
diff --git a/frontend/src/views/sql-editor/EditorPanel/ResultPanel/ContextMenu.vue b/frontend/src/views/sql-editor/EditorPanel/ResultPanel/ContextMenu.vue
deleted file mode 100644
index b2866f5c02..0000000000
--- a/frontend/src/views/sql-editor/EditorPanel/ResultPanel/ContextMenu.vue
+++ /dev/null
@@ -1,85 +0,0 @@
-<template>
- <NDropdown
- v-if="state"
- trigger="manual"
- placement="bottom-start"
- :show="true"
- :x="state?.x"
- :y="state?.y"
- :options="options"
- @clickoutside="state = undefined"
- @update:show="handleUpdateShow"
- @select="handleSelect"
- />
-</template>
-
-<script setup lang="ts">
-import type { DropdownOption } from "naive-ui";
-import { NDropdown } from "naive-ui";
-import { computed, nextTick } from "vue";
-import { useI18n } from "vue-i18n";
-import { type CloseTabAction, useResultTabListContext } from "./context";
-
-const { t } = useI18n();
-const { contextMenu: state, events } = useResultTabListContext();
-
-const options = computed((): DropdownOption[] => {
- if (!state.value) {
- return [];
- }
-
- const CLOSE: DropdownOption = {
- key: "CLOSE",
- label: t("sql-editor.tab.context-menu.actions.close"),
- };
- const CLOSE_OTHERS: DropdownOption = {
- key: "CLOSE_OTHERS",
- label: t("sql-editor.tab.context-menu.actions.close-others"),
- };
- const CLOSE_TO_THE_RIGHT: DropdownOption = {
- key: "CLOSE_TO_THE_RIGHT",
- label: t("sql-editor.tab.context-menu.actions.close-to-the-right"),
- };
- const CLOSE_ALL: DropdownOption = {
- key: "CLOSE_ALL",
- label: t("sql-editor.tab.context-menu.actions.close-all"),
- };
-
- return [CLOSE, CLOSE_OTHERS, CLOSE_TO_THE_RIGHT, CLOSE_ALL];
-});
-
-const show = (index: number, e: MouseEvent) => {
- e.preventDefault();
- e.stopPropagation();
- state.value = undefined;
- nextTick(() => {
- const { pageX, pageY } = e;
- state.value = {
- x: pageX,
- y: pageY,
- index,
- };
- });
-};
-
-const hide = () => {
- state.value = undefined;
-};
-
-const handleUpdateShow = (show: boolean) => {
- if (!show) {
- hide();
- }
-};
-
-const handleSelect = (action: CloseTabAction) => {
- if (!state.value) return;
- const { index } = state.value;
- events.emit("close-tab", { index, action });
-};
-
-defineExpose({
- show,
- hide,
-});
-</script>
diff --git a/frontend/src/views/sql-editor/EditorPanel/ResultPanel/ResultPanel.vue b/frontend/src/views/sql-editor/EditorPanel/ResultPanel/ResultPanel.vue
index 9f1aaac7cb..d3ccf29041 100644
--- a/frontend/src/views/sql-editor/EditorPanel/ResultPanel/ResultPanel.vue
+++ b/frontend/src/views/sql-editor/EditorPanel/ResultPanel/ResultPanel.vue
@@ -2,7 +2,14 @@
<div
class="relative w-full h-full flex flex-col justify-start items-start z-10 overflow-x-hidden"
>
- <BatchQuerySelect v-model:selected-database="selectedDatabase" />
+ <ReactPageMount
+ page="BatchQuerySelect"
+ container-class="w-full shrink-0"
+ :page-props="{
+ selectedDatabase,
+ onSelectedDatabaseChange: handleSelectedDatabaseChange,
+ }"
+ />
<NTabs
v-if="selectedDatabase && queryContexts"
type="card"
@@ -94,15 +101,18 @@ import { NDropdown, NTabPane, NTabs, NTooltip } from "naive-ui";
import { computed, nextTick, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import { BBAttention, BBSpin } from "@/bbkit";
+import ReactPageMount from "@/react/ReactPageMount.vue";
import { useSQLEditorTabStore } from "@/store";
import type { SQLEditorDatabaseQueryContext } from "@/types";
import { getDataSourceTypeI18n } from "@/types";
import type { Database } from "@/types/proto-es/v1/database_service_pb";
import { formatAbsoluteDateTime, getInstanceResource } from "@/utils";
-import BatchQuerySelect from "./BatchQuerySelect.vue";
import DatabaseQueryContext from "./DatabaseQueryContext.vue";
const selectedDatabase = ref<Database>();
+const handleSelectedDatabaseChange = (db: Database | undefined) => {
+ selectedDatabase.value = db;
+};
const tabStore = useSQLEditorTabStore();
const selectedTab = ref<string>();
const { t } = useI18n();
diff --git a/frontend/src/views/sql-editor/EditorPanel/ResultPanel/context.ts b/frontend/src/views/sql-editor/EditorPanel/ResultPanel/context.ts
deleted file mode 100644
index d0424273c7..0000000000
--- a/frontend/src/views/sql-editor/EditorPanel/ResultPanel/context.ts
+++ /dev/null
@@ -1,43 +0,0 @@
-import Emittery from "emittery";
-import type { InjectionKey, Ref } from "vue";
-import { inject, provide, ref } from "vue";
-
-export type CloseTabAction =
- | "CLOSE"
- | "CLOSE_OTHERS"
- | "CLOSE_TO_THE_RIGHT"
- | "CLOSE_ALL";
-
-type TabListEvents = Emittery<{
- "close-tab": { index: number; action: CloseTabAction };
-}>;
-
-export type TabListContextMenuState = {
- x: number;
- y: number;
- index: number;
-};
-
-export type TabListContext = {
- contextMenu: Ref<TabListContextMenuState | undefined>;
- events: TabListEvents;
-};
-
-export const KEY = Symbol(
- "bb.sql-editor.result-tab-list"
-) as InjectionKey<TabListContext>;
-
-export const useResultTabListContext = () => {
- return inject(KEY)!;
-};
-
-export const provideResultTabListContext = () => {
- const context: TabListContext = {
- contextMenu: ref(),
- events: new Emittery(),
- };
-
- provide(KEY, context);
-
- return context;
-};
diff --git a/frontend/src/views/sql-editor/EditorPanel/ResultPanel/resultTabContext.ts b/frontend/src/views/sql-editor/EditorPanel/ResultPanel/resultTabContext.ts
new file mode 100644
index 0000000000..7b788b73a1
--- /dev/null
+++ b/frontend/src/views/sql-editor/EditorPanel/ResultPanel/resultTabContext.ts
@@ -0,0 +1,21 @@
+import Emittery from "emittery";
+
+export type CloseTabAction =
+ | "CLOSE"
+ | "CLOSE_OTHERS"
+ | "CLOSE_TO_THE_RIGHT"
+ | "CLOSE_ALL";
+
+/**
+ * Module-level singleton replacing the per-instance Vue provide/inject in
+ * `./context.ts`. The React `ContextMenu` (mounted per-tab inside
+ * `BatchQuerySelect`) emits on this channel; `BatchQuerySelect` subscribes
+ * to it to handle close-tab actions.
+ *
+ * Base UI's `ContextMenuTrigger` handles right-click positioning natively, so
+ * the previous `{ x, y, index }` state from the Vue context is no longer
+ * needed — only the close-tab event bus survives.
+ */
+export const resultTabEvents = new Emittery<{
+ "close-tab": { index: number; action: CloseTabAction };
+}>();