Skip to content

armgit / dbx

Public Imported from GitHub
0

25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。

fix(objects): add safe object browser batch empty action

zipg085d7661afb1
diff --git a/apps/desktop/src/components/objects/ObjectBrowser.vue b/apps/desktop/src/components/objects/ObjectBrowser.vue
index 1ef4c8a19c..00def092c7 100644
--- a/apps/desktop/src/components/objects/ObjectBrowser.vue
+++ b/apps/desktop/src/components/objects/ObjectBrowser.vue
@@ -80,6 +80,7 @@ import QueryEditor from "@/components/editor/QueryEditor.vue";
import DdlViewDialog from "./DdlViewDialog.vue";
import { formatSqlForDisplay, sqlFormatDialectForDbType, type SqlFormatDialect } from "@/lib/sql/sqlFormatter";
import { isCancelSearchShortcut } from "@/lib/editor/keyboardShortcuts";
+import { batchTableEmptyFeedback, buildBatchTableEmptyPlan, runBatchTableEmpty, type BatchTableEmptyPlanItem } from "@/lib/sidebar/batchTableEmpty";
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import {
buildObjectBrowserRows,
@@ -202,6 +203,9 @@ const batchDropPreviewSql = ref("");
const showBatchTruncateConfirm = ref(false);
const batchTruncatePreviewSql = ref("");
const batchTruncateCascade = ref(false);
+const showBatchEmptyConfirm = ref(false);
+const batchEmptyPreviewSql = ref("");
+const batchEmptyPlan = ref<BatchTableEmptyPlanItem<ObjectBrowserRow>[]>([]);
// Paste table dialog state
const showPasteDialog = ref(false);
const pasteTableMode = ref<PasteTableMode>("structure-and-data");
@@ -1455,6 +1459,57 @@ async function confirmBatchTruncateTables() {
}
}
+async function refreshBatchEmptyPreviewSql(targets: ObjectBrowserRow[]) {
+ const plan = await buildBatchTableEmptyPlan(targets, (row) => buildEmptyTableSql(tableAdminSqlOptions(row)));
+ // Freeze the reviewed SQL with its target so confirmation cannot execute a different destructive statement.
+ batchEmptyPlan.value = plan;
+ batchEmptyPreviewSql.value = plan.map(({ sql }) => sql).join("\n");
+}
+
+function requestBatchEmptyTables() {
+ const targets = [...selectedTableRows.value];
+ if (targets.length === 0) return;
+ batchEmptyPlan.value = [];
+ batchEmptyPreviewSql.value = "";
+ void refreshBatchEmptyPreviewSql(targets)
+ .then(() => {
+ showBatchEmptyConfirm.value = true;
+ })
+ .catch((e: any) => {
+ batchEmptyPlan.value = [];
+ toast(t("contextMenu.tableOperationFailed", { message: e?.message || String(e) }), 5000);
+ });
+}
+
+async function confirmBatchEmptyTables() {
+ const plan = batchEmptyPlan.value.slice();
+ if (plan.length === 0) return;
+ const asynchronousMutation = effectiveDatabaseType.value === "clickhouse";
+ const result = await runBatchTableEmpty(plan, async ({ sql }) => {
+ await api.executeQuery(props.connection.id, props.database, sql);
+ });
+ for (const failure of result.failed) {
+ console.error(`Failed to empty table "${failure.target.target.name}":`, failure.error);
+ }
+ const feedback = batchTableEmptyFeedback(result, asynchronousMutation);
+ if (feedback === "success") {
+ toast(t("contextMenu.batchEmptySuccess", { count: result.succeeded.length }), 3000);
+ } else if (feedback === "submitted") {
+ toast(t("contextMenu.batchEmptySubmitted", { count: result.succeeded.length }), 3000);
+ } else if (feedback === "submitted-partial") {
+ toast(t("contextMenu.batchEmptySubmittedPartial", { success: result.succeeded.length, failed: result.failed.length }), 5000);
+ } else {
+ toast(t("contextMenu.batchEmptyPartialFail", { success: result.succeeded.length, failed: result.failed.length }), 5000);
+ }
+ batchEmptyPlan.value = [];
+ showBatchEmptyConfirm.value = false;
+ if (result.succeeded.length > 0) {
+ clearTableSelection();
+ await reload();
+ await connectionStore.refreshObjectListTreeNode(props.connection.id, props.database, selectedSchema.value);
+ }
+}
+
async function exportStructure(row: ObjectBrowserRow) {
try {
const schema = row.schema || selectedSchema.value || props.database;
@@ -2075,7 +2130,16 @@ function exportDataSubmenu(item: ObjectBrowserRow): ContextMenuItem {
};
}
+function isSelectedBatchTableContext(item: ObjectBrowserRow): boolean {
+ return item.type === "TABLE" && selectedTableCount.value > 1 && selectedTableIds.value.has(item.id);
+}
+
+function selectedBatchTableCountLabel(key: "batchDrop" | "batchTruncate" | "batchEmpty"): string {
+ return t(`contextMenu.${key}`, { count: selectedTableCount.value });
+}
+
function getTableMenuItems(item: ObjectBrowserRow): ContextMenuItem[] {
+ const useBatchActions = isSelectedBatchTableContext(item);
return [
{ label: t("contextMenu.viewData"), action: () => openViewData(item), icon: Table2 },
{
@@ -2103,22 +2167,22 @@ function getTableMenuItems(item: ObjectBrowserRow): ContextMenuItem[] {
...(supportsTruncateTable.value
? [
{
- label: t("contextMenu.truncateTable"),
- action: () => requestTruncateTable(item),
+ label: useBatchActions ? selectedBatchTableCountLabel("batchTruncate") : t("contextMenu.truncateTable"),
+ action: useBatchActions ? requestBatchTruncateTables : () => requestTruncateTable(item),
icon: Scissors,
variant: "destructive" as const,
},
]
: []),
{
- label: t("contextMenu.emptyTable"),
- action: () => requestEmptyTable(item),
+ label: useBatchActions ? selectedBatchTableCountLabel("batchEmpty") : t("contextMenu.emptyTable"),
+ action: useBatchActions ? requestBatchEmptyTables : () => requestEmptyTable(item),
icon: Eraser,
variant: "destructive" as const,
},
{
- label: t("contextMenu.dropTable"),
- action: () => requestDrop(item),
+ label: useBatchActions ? selectedBatchTableCountLabel("batchDrop") : t("contextMenu.dropTable"),
+ action: useBatchActions ? requestBatchDropTables : () => requestDrop(item),
icon: Trash2,
variant: "destructive" as const,
},
@@ -2293,6 +2357,10 @@ function getObjectBrowserMenuItems(item: ObjectBrowserRow): ContextMenuItem[] {
<Scissors class="mr-1.5 h-3.5 w-3.5" />
{{ t("objects.truncateSelected") }}
</Button>
+ <Button variant="ghost" size="sm" class="h-7 px-2 text-xs text-destructive" @click="requestBatchEmptyTables">
+ <Eraser class="mr-1.5 h-3.5 w-3.5" />
+ {{ t("contextMenu.batchEmpty", { count: selectedTableCount }) }}
+ </Button>
<Button variant="ghost" size="sm" class="h-7 px-2 text-xs text-destructive" @click="requestBatchDropTables">
<Trash2 class="mr-1.5 h-3.5 w-3.5" />
{{ t("objects.dropSelected") }}
@@ -2774,6 +2842,15 @@ function getObjectBrowserMenuItems(item: ObjectBrowserRow): ContextMenuItem[] {
</template>
</DangerConfirmDialog>
+ <DangerConfirmDialog
+ v-model:open="showBatchEmptyConfirm"
+ :title="t('contextMenu.confirmBatchEmptyTitle', { count: batchEmptyPlan.length })"
+ :message="t('contextMenu.confirmBatchEmptyMessage', { count: batchEmptyPlan.length })"
+ :sql="batchEmptyPreviewSql"
+ :confirm-label="t('contextMenu.batchEmpty', { count: batchEmptyPlan.length })"
+ @confirm="confirmBatchEmptyTables"
+ />
+
<Dialog v-model:open="showRenameDialog">
<DialogContent class="sm:max-w-[420px]">
<DialogHeader>
diff --git a/apps/desktop/src/lib/__tests__/sidebar/batchTableEmpty.spec.ts b/apps/desktop/src/lib/__tests__/sidebar/batchTableEmpty.spec.ts
index e5896b57b2..1f3d15df4b 100644
--- a/apps/desktop/src/lib/__tests__/sidebar/batchTableEmpty.spec.ts
+++ b/apps/desktop/src/lib/__tests__/sidebar/batchTableEmpty.spec.ts
@@ -1,7 +1,26 @@
import { describe, expect, it } from "vitest";
-import { batchTableEmptyFeedback, runBatchTableEmpty } from "@/lib/sidebar/batchTableEmpty";
+import { batchTableEmptyFeedback, buildBatchTableEmptyPlan, runBatchTableEmpty } from "@/lib/sidebar/batchTableEmpty";
describe("batch table empty", () => {
+ it("executes the exact SQL captured for the confirmation preview", async () => {
+ const targets = [{ name: "orders" }, { name: "customers" }];
+ let schema = "public";
+ const plan = await buildBatchTableEmptyPlan(targets, async (target) => `TRUNCATE TABLE "${schema}"."${target.name}";`);
+ schema = "archive";
+
+ const executed: string[] = [];
+ await runBatchTableEmpty(plan, async ({ sql }) => {
+ executed.push(sql);
+ });
+
+ expect(plan.map(({ sql }) => sql).join("\n")).toBe('TRUNCATE TABLE "public"."orders";\nTRUNCATE TABLE "public"."customers";');
+ expect(executed).toEqual(['TRUNCATE TABLE "public"."orders";', 'TRUNCATE TABLE "public"."customers";']);
+ });
+
+ it("rejects the entire destructive plan when any preview SQL is unavailable", async () => {
+ await expect(buildBatchTableEmptyPlan(["orders", "customers"], async (target) => (target === "customers" ? "" : `TRUNCATE TABLE ${target};`))).rejects.toThrow("Empty table SQL preview is unavailable");
+ });
+
it("continues after a table fails and collects each result", async () => {
const executed: string[] = [];
const result = await runBatchTableEmpty(["orders", "locked", "customers"], async (table) => {
diff --git a/apps/desktop/src/lib/sidebar/batchTableEmpty.ts b/apps/desktop/src/lib/sidebar/batchTableEmpty.ts
index 6549e0e9ca..8409721bc2 100644
--- a/apps/desktop/src/lib/sidebar/batchTableEmpty.ts
+++ b/apps/desktop/src/lib/sidebar/batchTableEmpty.ts
@@ -3,8 +3,23 @@ export interface BatchTableEmptyResult<T> {
failed: Array<{ target: T; error: unknown }>;
}
+export interface BatchTableEmptyPlanItem<T> {
+ target: T;
+ sql: string;
+}
+
export type BatchTableEmptyFeedback = "success" | "partial" | "submitted" | "submitted-partial";
+export async function buildBatchTableEmptyPlan<T>(targets: readonly T[], buildSql: (target: T) => Promise<string>): Promise<BatchTableEmptyPlanItem<T>[]> {
+ const plan: BatchTableEmptyPlanItem<T>[] = [];
+ for (const target of targets) {
+ const sql = await buildSql(target);
+ if (!sql.trim()) throw new Error("Empty table SQL preview is unavailable");
+ plan.push({ target, sql });
+ }
+ return plan;
+}
+
export async function runBatchTableEmpty<T>(targets: readonly T[], execute: (target: T) => Promise<void>): Promise<BatchTableEmptyResult<T>> {
const result: BatchTableEmptyResult<T> = { succeeded: [], failed: [] };
for (const target of targets) {