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。
TypeScript aicliclickhousedatabasedatabase-clientdatabase-managementdockerguimcpmongodbmysqlpostgresqlredisrustsql-serversqlitetaurivue
feat(mysql): add database-wide table cleanup actions
二丫讲梵1ed598308a4c
diff --git a/Cargo.lock b/Cargo.lockindex 1d45dec347..aa86b1a5bf 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -2689,6 +2689,7 @@ version = "0.1.0"dependencies = ["dbx-core","tauri",+ "tokio",][[package]]diff --git a/apps/desktop/src/components/editor/DangerConfirmDialog.vue b/apps/desktop/src/components/editor/DangerConfirmDialog.vueindex 064729614a..aa13a1e065 100644--- a/apps/desktop/src/components/editor/DangerConfirmDialog.vue+++ b/apps/desktop/src/components/editor/DangerConfirmDialog.vue@@ -29,6 +29,7 @@ let focusRestoreGeneration = 0;const props = withDefaults(defineProps<{sql?: string;+ copySql?: string | (() => string);title?: string;message?: string;details?: string;@@ -52,6 +53,7 @@ const props = withDefaults(}>(),{sql: "",+ copySql: "",title: "",message: "",details: "",@@ -155,7 +157,8 @@ function onConfirm() {}async function copyFullCode() {- await copyToClipboard(code.value);+ const copySql = typeof props.copySql === "function" ? props.copySql() : props.copySql;+ await copyToClipboard(copySql || code.value);copied.value = true;window.setTimeout(() => {copied.value = false;diff --git a/apps/desktop/src/components/editor/__tests__/DangerConfirmDialog.spec.ts b/apps/desktop/src/components/editor/__tests__/DangerConfirmDialog.spec.tsindex 26d1853f68..9f2066a2ad 100644--- a/apps/desktop/src/components/editor/__tests__/DangerConfirmDialog.spec.ts+++ b/apps/desktop/src/components/editor/__tests__/DangerConfirmDialog.spec.ts@@ -121,6 +121,21 @@ describe("DangerConfirmDialog SQL preview", () => {expect(copyToClipboard).toHaveBeenCalledWith(sql);});+ it("builds lazy full SQL only when the copy action is used", async () => {+ const fullSql = "DELETE FROM orders;\nDELETE FROM customers;";+ const getCopySql = vi.fn(() => fullSql);++ await mountDialog("DELETE FROM orders;", { copySql: getCopySql });+ expect(getCopySql).not.toHaveBeenCalled();++ const copyButton = Array.from(document.body.querySelectorAll("button")).find((button) => button.title === "Copy full text");+ copyButton?.click();+ await nextTick();++ expect(getCopySql).toHaveBeenCalledOnce();+ expect(copyToClipboard).toHaveBeenCalledWith(fullSql);+ });+it("restores a previously focused CodeMirror editor through EditorView on close", async () => {const editorRoot = document.createElement("div");editorRoot.className = "cm-editor";diff --git a/apps/desktop/src/components/sidebar/ConnectionTree.vue b/apps/desktop/src/components/sidebar/ConnectionTree.vueindex 4970f89fcf..03678355dc 100644--- a/apps/desktop/src/components/sidebar/ConnectionTree.vue+++ b/apps/desktop/src/components/sidebar/ConnectionTree.vue@@ -2921,6 +2921,7 @@ defineExpose({ focusSearch, createNewGroup, collapseAllTreeNodes, locateTabInSid:title="sidebarDangerDialogRequest.title":message="sidebarDangerDialogRequest.message":sql="sidebarDangerDialogRequest.sql"+ :copy-sql="sidebarDangerDialogRequest.copySql":details="sidebarDangerDialogRequest.details":details-text="sidebarDangerDialogRequest.detailsText":confirm-label="sidebarDangerDialogRequest.confirmLabel"@@ -2933,9 +2934,9 @@ defineExpose({ focusSearch, createNewGroup, collapseAllTreeNodes, locateTabInSid@cancel-running="cancelSidebarDangerDialogRunning"><template #options>- <div v-if="sidebarDangerDialogConfirming && sidebarDangerDialogRequest.progress" class="mb-3 rounded-md border bg-muted/20 px-3 py-2.5">+ <div v-if="sidebarDangerDialogRequest.progress" class="mb-3 rounded-md border bg-muted/20 px-3 py-2.5"><div class="mb-1.5 flex items-center justify-between text-xs tabular-nums text-muted-foreground">- <span>{{ sidebarDangerDialogRequest.progress.completed }} / {{ sidebarDangerDialogRequest.progress.total }}</span>+ <span>{{ sidebarDangerDialogRequest.progress.phase === "preparing" ? t("databaseEmpty.preparing", { database: sidebarDangerDialogRequest.target.database }) : "" }} {{ sidebarDangerDialogRequest.progress.completed }} / {{ sidebarDangerDialogRequest.progress.total }}</span><span>{{ Math.round((sidebarDangerDialogRequest.progress.completed / sidebarDangerDialogRequest.progress.total) * 100) }}%</span></div><div class="h-2 overflow-hidden rounded-full bg-muted" role="progressbar" :aria-valuemin="0" :aria-valuemax="sidebarDangerDialogRequest.progress.total" :aria-valuenow="sidebarDangerDialogRequest.progress.completed">diff --git a/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue b/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vueindex 33d3481a6a..e4ce890fce 100644--- a/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue+++ b/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue@@ -11,6 +11,7 @@ import { useSidebarDatabaseSpecificMutationRuntime } from "@/composables/useSideimport { useSidebarTableMutationRuntime } from "@/composables/useSidebarTableMutationRuntime";import { useSidebarTreeExportRuntime } from "@/composables/useSidebarTreeExportRuntime";import { useSidebarTreeToolRuntime } from "@/composables/useSidebarTreeToolRuntime";+import { canDropDatabaseTables, canEmptyDatabaseTables, useDatabaseTableEmpty } from "@/composables/useDatabaseTableEmpty";import { useI18n } from "vue-i18n";import { translateBackendError } from "@/i18n/backend-errors";import {@@ -531,6 +532,8 @@ const emit = defineEmits<{"open-event-trigger-details": [node: TreeNode];}>();+const { requestEmptyDatabaseTables, requestDropDatabaseTables } = useDatabaseTableEmpty((request) => emit("open-danger-dialog", request));+const {setNodeAsDefaultDatabase,clearNodeDefaultDatabase,@@ -6222,6 +6225,12 @@ function buildDatabaseSidebarMenu(context: SidebarMenuFactoryContext): boolean {items.push({ label: t("dataDictionary.title"), action: openDataDictionary, icon: FileText });}const destructiveActions: ContextMenuItem[] = [];+ if (canEmptyDatabaseTables(node, node.connectionId ? connectionStore.getConfig(node.connectionId) : undefined)) {+ destructiveActions.push({ label: t("databaseEmpty.menu"), action: () => void requestEmptyDatabaseTables(node), icon: Eraser, variant: "destructive" as const });+ }+ if (canDropDatabaseTables(node, node.connectionId ? connectionStore.getConfig(node.connectionId) : undefined)) {+ destructiveActions.push({ label: t("databaseDrop.menu"), action: () => void requestDropDatabaseTables(node), icon: Trash2, variant: "destructive" as const });+ }if (canDropDatabase.value) {destructiveActions.push({label: t("contextMenu.dropDatabase"),diff --git a/apps/desktop/src/composables/useDatabaseTableEmpty.ts b/apps/desktop/src/composables/useDatabaseTableEmpty.tsnew file mode 100644index 0000000000..1ef4f460e2--- /dev/null+++ b/apps/desktop/src/composables/useDatabaseTableEmpty.ts@@ -0,0 +1,253 @@+import { ref, shallowRef } from "vue";+import { useI18n } from "vue-i18n";+import { useToast } from "@/composables/useToast";+import { useConnectionStore } from "@/stores/connectionStore";+import { useQueryStore } from "@/stores/queryStore";+import * as api from "@/lib/backend/api";+import { connectionObjectTreeNodeSchema } from "@/lib/database/jdbcDialect";+import { connectionIsEffectivelyReadOnly } from "@/lib/database/readOnlyWriteAccess";+import { executeWithProductionSqlGuard } from "@/lib/database/productionExecutionGuard";+import { translateBackendError } from "@/i18n/backend-errors";+import { getTableMutationHistoryStoreOrNull, recordTableMutationHistory } from "@/lib/history/tableMutationHistory";+import { runBatchTableEmptyLayers, type BatchTableEmptyPlanItem } from "@/lib/sidebar/batchTableEmpty";+import { buildDatabaseTableEmptyPlanLayers, buildMysqlTableMutationSql, DatabaseTableEmptyPlanError, type DatabaseEmptyTable } from "@/lib/sidebar/databaseTableEmpty";+import { createSidebarActionTarget } from "@/lib/sidebar/sidebarActionTarget";+import { uuid } from "@/lib/common/utils";+import type { SidebarDangerDialogRequest } from "@/lib/sidebar/sidebarDangerDialog";+import type { ConnectionConfig, TreeNode } from "@/types/database";++export function canEmptyDatabaseTables(node: TreeNode, connection?: ConnectionConfig): boolean {+ const profile = connection?.driver_profile?.toLowerCase();+ const unsupportedMysqlProfiles = ["doris", "selectdb", "starrocks", "manticoresearch"];+ return (+ node.type === "database" &&+ !!node.database &&+ !!node.connectionId &&+ connection?.db_type === "mysql" &&+ !unsupportedMysqlProfiles.includes(profile ?? "") &&+ !connectionIsEffectivelyReadOnly(connection) &&+ !["mysql", "sys", "information_schema", "performance_schema", "ndbinfo"].includes(node.database.toLowerCase())+ );+}+export const canDropDatabaseTables = canEmptyDatabaseTables;++export function useDatabaseTableEmpty(openDialog: (request: SidebarDangerDialogRequest) => void) {+ const { t } = useI18n();+ const { toast } = useToast();+ const connections = useConnectionStore();+ const queries = useQueryStore();+ async function requestDatabaseTables(node: TreeNode, operation: "empty" | "drop") {+ const target = createSidebarActionTarget(node);+ const connectionId = target.connectionId!;+ const database = target.database!;+ if (!canEmptyDatabaseTables(target, connections.getConfig(connectionId))) return;+ const typedName = ref("");+ const loading = ref(true);+ const executing = ref(false);+ const finished = ref(false);+ const cancelled = ref(false);+ const details = ref("");+ const completed = ref(0);+ const preparing = ref(0);+ const preparingTotal = ref(0);+ const plan = shallowRef<BatchTableEmptyPlanItem<DatabaseEmptyTable>[]>([]);+ const layers = shallowRef<{ items: BatchTableEmptyPlanItem<DatabaseEmptyTable>[]; dependencies?: Record<string, string[]> }[]>([]);+ const activeExecutionIds = new Set<string>();+ const preparationExecutionIds = new Set<string>();+ const connectionName = connections.getConfig(connectionId)?.name ?? connectionId;+ const fullSql = () => plan.value.map(({ sql }) => sql).join("\n");+ const previewSql = () => {+ const preview = plan.value+ .slice(0, 100)+ .map(({ sql }) => sql)+ .join("\n");+ return plan.value.length > 100 ? `${preview}\n-- ${plan.value.length - 100} more statements` : preview;+ };+ const request: SidebarDangerDialogRequest = {+ target,+ title: t(operation === "empty" ? "databaseEmpty.title" : "databaseDrop.title"),+ get message() {+ if (loading.value && plan.value.length === 0) return `${t(operation === "empty" ? "databaseEmpty.preparing" : "databaseDrop.preparing", { database })} ${preparingTotal.value ? `${preparing.value} / ${preparingTotal.value}` : ""}`;+ return t(operation === "empty" ? "databaseEmpty.message" : "databaseDrop.message", { connection: connectionName, database, count: plan.value.length });+ },+ get sql() {+ return previewSql();+ },+ copySql: fullSql,+ get detailsText() {+ return details.value;+ },+ get loading() {+ return loading.value;+ },+ get confirmDisabled() {+ return loading.value || finished.value || cancelled.value || !plan.value.length || typedName.value !== database;+ },+ confirmLabel: t(operation === "empty" ? "databaseEmpty.title" : "databaseDrop.title"),+ closeOnConfirm: false,+ get progress() {+ return executing.value && plan.value.length ? { completed: completed.value, total: plan.value.length, phase: "executing" as const } : loading.value && preparingTotal.value ? { completed: preparing.value, total: preparingTotal.value, phase: "preparing" as const } : undefined;+ },+ async cancelRunning() {+ cancelled.value = true;+ await Promise.all([...activeExecutionIds, ...preparationExecutionIds].map((id) => api.cancelQuery(id).catch(() => false)));+ },+ textInput: {+ value: "",+ label: t(operation === "empty" ? "databaseEmpty.typeName" : "databaseDrop.typeName", { database }),+ placeholder: database,+ onInput(value) {+ typedName.value = value;+ },+ },+ async confirm() {+ if (request.confirmDisabled) return false;+ loading.value = true;+ executing.value = true;+ const frozenPlan = plan.value;+ const reviewSql = previewSql();+ const start = Date.now();+ try {+ const result = await executeWithProductionSqlGuard({+ connection: connections.getConfig(connectionId),+ database,+ sql: reviewSql,+ source: t("production.sourceSidebar"),+ execute: () =>+ runBatchTableEmptyLayers(layers.value, {+ concurrency: 8,+ isCancelled: () => cancelled.value,+ keyOf: (table) => table.name,+ execute: async (item, executionId) => {+ activeExecutionIds.add(executionId);+ try {+ const response = await api.executeQuery(connectionId, database, item.sql, database, executionId);+ if (response.execution_error) throw new Error(String(response.rows[0]?.[0] ?? "Statement failed"));+ } finally {+ activeExecutionIds.delete(executionId);+ }+ },+ onProgress: (value) => {+ completed.value = value;+ },+ }),+ });+ if (!result) return false;+ finished.value = true;+ const failures = result.failed.map(({ target: item, error }) => `${item.name}: ${translateBackendError(t, error)}`);+ const cancelledCount = result.cancelled?.length ?? 0;+ const skippedCount = result.skipped?.length ?? 0;+ const skippedDetails = (result.skipped ?? []).slice(0, 100).map(({ target: item, reason, dependency }) => (dependency ? t(`${operation === "empty" ? "databaseEmpty" : "databaseDrop"}.blockedBy`, { table: item.name, dependency }) : `${item.name}: ${reason}`));+ const omittedFailures = failures.length > 100 ? [`... ${failures.length - 100} more failures`] : [];+ const omittedSkipped = skippedCount > 100 ? [`... ${skippedCount - 100} more skipped tables`] : [];+ details.value = [+ t(operation === "empty" ? "databaseEmpty.result" : "databaseDrop.result", { success: result.succeeded.length, failed: result.failed.length }),+ skippedCount ? t(operation === "empty" ? "databaseEmpty.skipped" : "databaseDrop.skipped", { count: skippedCount }) : "",+ ...skippedDetails,+ ...omittedSkipped,+ cancelledCount ? t(operation === "empty" ? "databaseEmpty.cancelled" : "databaseDrop.cancelled", { count: cancelledCount }) : "",+ ...failures.slice(0, 100),+ ...omittedFailures,+ ]+ .filter(Boolean)+ .join("\n");+ toast(details.value, result.failed.length || cancelledCount || skippedCount ? 5000 : 3000);+ const historyTarget =+ frozenPlan.length > 100+ ? `${frozenPlan+ .slice(0, 100)+ .map(({ target: table }) => table.name)+ .join(", ")}, +${frozenPlan.length - 100} more`+ : frozenPlan.map(({ target: table }) => table.name).join(", ");+ const historyError = failures.length > 100 ? `${failures.slice(0, 100).join("; ")}; +${failures.length - 100} more failures` : failures.join("; ");+ await recordTableMutationHistory(getTableMutationHistoryStoreOrNull(), {+ connectionId,+ connectionName,+ database,+ sql: reviewSql,+ elapsedMs: Date.now() - start,+ success: result.failed.length === 0 && cancelledCount === 0 && skippedCount === 0,+ error: historyError || undefined,+ target: historyTarget,+ }).catch((error) => console.warn("[DBX] failed to record database empty history", error));+ const complete = result.failed.length === 0 && cancelledCount === 0 && skippedCount === 0;+ if (result.succeeded.length) {+ const schema = connectionObjectTreeNodeSchema(connections.getConfig(connectionId), database, database);+ for (const table of result.succeeded) {+ if (operation === "drop") queries.closeDroppedTableObjectTabs({ connectionId, database, schema, schemaCandidates: [database, schema], name: table.name, objectType: "TABLE" });+ if (operation === "empty") await queries.refreshDataTabsForTable({ connectionId, database, schema, schemaCandidates: [database, schema], catalog: target.catalog, name: table.name }).catch((error) => console.warn("[DBX] failed to refresh emptied table", error));+ }+ await connections.refreshObjectListTreeNode(connectionId, database, undefined, target.catalog).catch((error) => {+ details.value += `\n${t("databaseEmpty.refreshFailed", { message: translateBackendError(t, error) })}`;+ });+ }+ return complete;+ } catch (error) {+ details.value = translateBackendError(t, error);+ toast(t("contextMenu.tableOperationFailed", { message: details.value }), 5000);+ return false;+ } finally {+ loading.value = false;+ executing.value = false;+ }+ },+ };+ openDialog(request);+ const ensurePreparationActive = () => {+ if (cancelled.value) throw new DatabaseTableEmptyPlanError("cancelled", []);+ };+ const runPreparationRequest = async <T>(request: (executionId: string) => Promise<T>): Promise<T> => {+ ensurePreparationActive();+ const executionId = uuid();+ preparationExecutionIds.add(executionId);+ try {+ const result = await request(executionId);+ ensurePreparationActive();+ return result;+ } catch (error) {+ if (cancelled.value) throw new DatabaseTableEmptyPlanError("cancelled", []);+ throw error;+ } finally {+ preparationExecutionIds.delete(executionId);+ }+ };+ try {+ await connections.ensureConnected(connectionId);+ const externalReferences = await runPreparationRequest((executionId) =>+ api.executeQuery(connectionId, database, "SELECT TABLE_SCHEMA, TABLE_NAME FROM information_schema.KEY_COLUMN_USAGE WHERE REFERENCED_TABLE_SCHEMA = DATABASE() AND TABLE_SCHEMA <> DATABASE() LIMIT 1", undefined, executionId),+ );+ if (externalReferences.execution_error) throw new Error(t("databaseEmpty.metadataFailed"));+ if (externalReferences.rows.length) throw new Error(t("databaseEmpty.externalReferences"));+ const foreignKeysByTable = await runPreparationRequest((executionId) => api.listForeignKeysForDatabase(connectionId, database, database, target.catalog, executionId));+ layers.value = await buildDatabaseTableEmptyPlanLayers({+ database,+ listTables: () => runPreparationRequest((executionId) => api.listObjects(connectionId, database, database, ["TABLE"], undefined, undefined, undefined, target.catalog, undefined, executionId)),+ foreignKeysByTable,+ isCancelled: () => cancelled.value,+ onProgress: (value, total) => {+ preparing.value = value;+ preparingTotal.value = total * 2;+ },+ onSqlProgress: (value, total) => {+ preparing.value = total + value;+ preparingTotal.value = total * 2;+ },+ buildSql: async (table) => buildMysqlTableMutationSql(operation, database, table.name),+ });+ plan.value = layers.value.flatMap((layer) => layer.items);+ if (!plan.value.length) details.value = t(operation === "empty" ? "databaseEmpty.noTables" : "databaseDrop.noTables");+ else if (plan.value.length > 2000) details.value = t(operation === "empty" ? "databaseEmpty.veryLargeWarning" : "databaseDrop.veryLargeWarning", { count: plan.value.length });+ else if (plan.value.length > 500) details.value = t(operation === "empty" ? "databaseEmpty.largeWarning" : "databaseDrop.largeWarning", { count: plan.value.length });+ } catch (error) {+ details.value =+ error instanceof DatabaseTableEmptyPlanError && error.reason === "cancelled"+ ? t(`${operation === "empty" ? "databaseEmpty" : "databaseDrop"}.cancelledPreparation`)+ : error instanceof DatabaseTableEmptyPlanError+ ? t(`${operation === "empty" ? "databaseEmpty" : "databaseDrop"}.${error.reason}`, { tables: error.tables.join(", ") })+ : translateBackendError(t, error);+ } finally {+ loading.value = false;+ }+ }+ return { requestEmptyDatabaseTables: (node: TreeNode) => requestDatabaseTables(node, "empty"), requestDropDatabaseTables: (node: TreeNode) => requestDatabaseTables(node, "drop") };+}diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.tsindex 686f6b77be..8e4bd3d70a 100644--- a/apps/desktop/src/i18n/locales/en.ts+++ b/apps/desktop/src/i18n/locales/en.ts@@ -2025,6 +2025,44 @@ export default {defaultCharset: "Charset",defaultCollation: "Collation",},+ databaseEmpty: {+ menu: "Empty all table data",+ title: "Empty all table data",+ preparing: "Loading all tables in {database}...",+ cancelledPreparation: "Operation cancelled before execution.",+ message: "This will delete all rows from {count} tables in {database} on {connection}.",+ typeName: "Type {database} to confirm",+ result: "Completed: {success}; failed: {failed}",+ skipped: "Skipped: {count}",+ blockedBy: "Skipped {table}: dependency {dependency} did not complete.",+ cancelled: "Cancelled: {count}",+ largeWarning: "This operation affects {count} tables and may take a long time. Partial failures are possible.",+ veryLargeWarning: "This operation affects {count} tables. Expect a long run and review partial failures carefully.",+ noTables: "No tables were found in this database.",+ metadataFailed: "Could not read the database table metadata.",+ externalReferences: "The database has foreign-key references from another database; the operation was stopped.",+ scope: "The table list contains objects outside the selected database: {tables}",+ cycle: "Foreign-key cycle detected; the operation was stopped for: {tables}",+ refreshFailed: "Refresh failed: {message}",+ },+ databaseDrop: {+ menu: "Drop all tables",+ title: "Drop all tables",+ preparing: "Loading all tables in {database}...",+ cancelledPreparation: "Operation cancelled before execution.",+ message: "This will permanently drop {count} tables from {database} on {connection}.",+ typeName: "Type {database} to confirm",+ result: "Completed: {success}; failed: {failed}",+ skipped: "Skipped: {count}",+ blockedBy: "Skipped {table}: dependency {dependency} did not complete.",+ cancelled: "Cancelled: {count}",+ largeWarning: "This operation affects {count} tables and may take a long time. Partial failures are possible.",+ veryLargeWarning: "This operation affects {count} tables. Expect a long run and review partial failures carefully.",+ noTables: "No tables were found in this database.",+ scope: "The table list contains objects outside the selected database: {tables}",+ cycle: "Foreign-key cycle detected; the operation was stopped for: {tables}",+ refreshFailed: "Refresh failed: {message}",+ },gridfsBrowser: {bucketCount: "buckets",fileCount: "files",diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.tsindex eac391b3c0..43597eddad 100644--- a/apps/desktop/src/i18n/locales/es.ts+++ b/apps/desktop/src/i18n/locales/es.ts@@ -9377,6 +9377,44 @@ export default withEnglishFallback({defaultCharset: "Juego de caracteres",defaultCollation: "Cotejamiento",},+ databaseEmpty: {+ menu: "Vaciar los datos de todas las tablas",+ title: "Vaciar los datos de todas las tablas",+ preparing: "Cargando todas las tablas de {database}...",+ cancelledPreparation: "Operación cancelada antes de ejecutarse.",+ message: "Se eliminarán todas las filas de {count} tablas de {database} en {connection}.",+ typeName: "Escribe {database} para confirmar",+ result: "Completadas: {success}; fallidas: {failed}",+ skipped: "Omitidas: {count}",+ blockedBy: "Se omitió {table}: la dependencia {dependency} no se completó.",+ cancelled: "Canceladas: {count}",+ largeWarning: "Esta operación afecta a {count} tablas y puede tardar mucho. Es posible que haya fallos parciales.",+ veryLargeWarning: "Esta operación afecta a {count} tablas. Espera una ejecución larga y revisa con atención los fallos parciales.",+ noTables: "No se encontraron tablas en esta base de datos.",+ metadataFailed: "No se pudieron leer los metadatos de las tablas de la base de datos.",+ externalReferences: "La base de datos recibe referencias de claves foráneas de otra base de datos; la operación se detuvo.",+ scope: "La lista de tablas incluye objetos fuera de la base de datos seleccionada: {tables}",+ cycle: "Se detectó un ciclo de claves foráneas; la operación se detuvo para: {tables}",+ refreshFailed: "Error al actualizar: {message}",+ },+ databaseDrop: {+ menu: "Eliminar todas las tablas",+ title: "Eliminar todas las tablas",+ preparing: "Cargando todas las tablas de {database}...",+ cancelledPreparation: "Operación cancelada antes de ejecutarse.",+ message: "Se eliminarán permanentemente {count} tablas de {database} en {connection}.",+ typeName: "Escribe {database} para confirmar",+ result: "Completadas: {success}; fallidas: {failed}",+ skipped: "Omitidas: {count}",+ blockedBy: "Se omitió {table}: la dependencia {dependency} no se completó.",+ cancelled: "Canceladas: {count}",+ largeWarning: "Esta operación afecta a {count} tablas y puede tardar mucho. Es posible que haya fallos parciales.",+ veryLargeWarning: "Esta operación afecta a {count} tablas. Espera una ejecución larga y revisa con atención los fallos parciales.",+ noTables: "No se encontraron tablas en esta base de datos.",+ scope: "La lista de tablas incluye objetos fuera de la base de datos seleccionada: {tables}",+ cycle: "Se detectó un ciclo de claves foráneas; la operación se detuvo para: {tables}",+ refreshFailed: "Error al actualizar: {message}",+ },gridfsBrowser: {bucketCount: "Cantidad de buckets",fileCount: "Archivos",diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.tsindex 916ec75eb5..c5caa9af4b 100644--- a/apps/desktop/src/i18n/locales/it.ts+++ b/apps/desktop/src/i18n/locales/it.ts@@ -9122,6 +9122,44 @@ export default withEnglishFallback({defaultCharset: "Set di caratteri",defaultCollation: "Regole di confronto",},+ databaseEmpty: {+ menu: "Svuota i dati di tutte le tabelle",+ title: "Svuota i dati di tutte le tabelle",+ preparing: "Caricamento di tutte le tabelle in {database}...",+ cancelledPreparation: "Operazione annullata prima dell'esecuzione.",+ message: "Verranno eliminate tutte le righe di {count} tabelle in {database} su {connection}.",+ typeName: "Digita {database} per confermare",+ result: "Completate: {success}; non riuscite: {failed}",+ skipped: "Ignorate: {count}",+ blockedBy: "{table} ignorata: la dipendenza {dependency} non è stata completata.",+ cancelled: "Annullate: {count}",+ largeWarning: "Questa operazione coinvolge {count} tabelle e può richiedere molto tempo. Sono possibili errori parziali.",+ veryLargeWarning: "Questa operazione coinvolge {count} tabelle. Prevedi un'esecuzione lunga e controlla attentamente gli errori parziali.",+ noTables: "Nessuna tabella trovata in questo database.",+ metadataFailed: "Impossibile leggere i metadati delle tabelle del database.",+ externalReferences: "Il database riceve riferimenti di chiavi esterne da un altro database; operazione interrotta.",+ scope: "L'elenco delle tabelle contiene oggetti esterni al database selezionato: {tables}",+ cycle: "Rilevato un ciclo di chiavi esterne; operazione interrotta per: {tables}",+ refreshFailed: "Aggiornamento non riuscito: {message}",+ },+ databaseDrop: {+ menu: "Elimina tutte le tabelle",+ title: "Elimina tutte le tabelle",+ preparing: "Caricamento di tutte le tabelle in {database}...",+ cancelledPreparation: "Operazione annullata prima dell'esecuzione.",+ message: "Verranno eliminate definitivamente {count} tabelle da {database} su {connection}.",+ typeName: "Digita {database} per confermare",+ result: "Completate: {success}; non riuscite: {failed}",+ skipped: "Ignorate: {count}",+ blockedBy: "{table} ignorata: la dipendenza {dependency} non è stata completata.",+ cancelled: "Annullate: {count}",+ largeWarning: "Questa operazione coinvolge {count} tabelle e può richiedere molto tempo. Sono possibili errori parziali.",+ veryLargeWarning: "Questa operazione coinvolge {count} tabelle. Prevedi un'esecuzione lunga e controlla attentamente gli errori parziali.",+ noTables: "Nessuna tabella trovata in questo database.",+ scope: "L'elenco delle tabelle contiene oggetti esterni al database selezionato: {tables}",+ cycle: "Rilevato un ciclo di chiavi esterne; operazione interrotta per: {tables}",+ refreshFailed: "Aggiornamento non riuscito: {message}",+ },gridfsBrowser: {bucketCount: "Bucket",fileCount: "File",diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.tsindex 9a32624032..0e40990fcc 100644--- a/apps/desktop/src/i18n/locales/ja.ts+++ b/apps/desktop/src/i18n/locales/ja.ts@@ -9162,6 +9162,44 @@ export default withEnglishFallback({defaultCharset: "文字セット",defaultCollation: "照合順序",},+ databaseEmpty: {+ menu: "全テーブルのデータを空にする",+ title: "全テーブルのデータを空にする",+ preparing: "{database} 内のすべてのテーブルを読み込み中...",+ cancelledPreparation: "実行前に操作がキャンセルされました。",+ message: "接続 {connection} の {database} にある {count} 個のテーブルのすべての行を削除します。",+ typeName: "確認のため {database} を入力してください",+ result: "完了: {success}、失敗: {failed}",+ skipped: "スキップ: {count}",+ blockedBy: "{table} をスキップしました: 依存テーブル {dependency} が完了していません。",+ cancelled: "キャンセル: {count}",+ largeWarning: "この操作は {count} 個のテーブルを対象とするため時間がかかる可能性があり、一部が失敗する場合もあります。",+ veryLargeWarning: "この操作は {count} 個のテーブルを対象とします。実行に長い時間がかかるため、部分失敗の結果を慎重に確認してください。",+ noTables: "このデータベースにはテーブルが見つかりませんでした。",+ metadataFailed: "データベースのテーブルメタデータを読み取れませんでした。",+ externalReferences: "他のデータベースからこのデータベースへの外部キー参照があるため、操作を中止しました。",+ scope: "テーブル一覧に、選択したデータベースの外側にあるオブジェクトが含まれています: {tables}",+ cycle: "外部キーの循環参照が検出されたため、対象の操作を中止しました: {tables}",+ refreshFailed: "更新に失敗しました: {message}",+ },+ databaseDrop: {+ menu: "すべてのテーブルを削除",+ title: "すべてのテーブルを削除",+ preparing: "{database} 内のすべてのテーブルを読み込み中...",+ cancelledPreparation: "実行前に操作がキャンセルされました。",+ message: "接続 {connection} の {database} から {count} 個のテーブルを完全に削除します。",+ typeName: "確認のため {database} を入力してください",+ result: "完了: {success}、失敗: {failed}",+ skipped: "スキップ: {count}",+ blockedBy: "{table} をスキップしました: 依存テーブル {dependency} が完了していません。",+ cancelled: "キャンセル: {count}",+ largeWarning: "この操作は {count} 個のテーブルを対象とするため時間がかかる可能性があり、一部が失敗する場合があります。",+ veryLargeWarning: "この操作は {count} 個のテーブルを対象とします。実行に長い時間がかかるため、部分失敗の結果を慎重に確認してください。",+ noTables: "このデータベースにはテーブルが見つかりませんでした。",+ scope: "テーブル一覧に、選択したデータベースの外側にあるオブジェクトが含まれています: {tables}",+ cycle: "外部キーの循環参照が検出されたため、対象の操作を中止しました: {tables}",+ refreshFailed: "更新に失敗しました: {message}",+ },gridfsBrowser: {bucketCount: "バケット",fileCount: "ファイル",diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.tsindex a819c06a3a..85cf1e87b9 100644--- a/apps/desktop/src/i18n/locales/ko.ts+++ b/apps/desktop/src/i18n/locales/ko.ts@@ -1840,6 +1840,44 @@ export default withEnglishFallback({defaultCharset: "문자 집합",defaultCollation: "데이터 정렬",},+ databaseEmpty: {+ menu: "모든 테이블 데이터 비우기",+ title: "모든 테이블 데이터 비우기",+ preparing: "{database}의 모든 테이블을 불러오는 중...",+ cancelledPreparation: "실행 전에 작업이 취소되었습니다.",+ message: "{connection} 연결의 {database}에 있는 {count}개 테이블의 모든 행을 삭제합니다.",+ typeName: "확인하려면 {database}를 입력하세요",+ result: "완료: {success}, 실패: {failed}",+ skipped: "건너뜀: {count}",+ blockedBy: "{table}을(를) 건너뛰었습니다: 종속 테이블 {dependency}이(가) 완료되지 않았습니다.",+ cancelled: "취소됨: {count}",+ largeWarning: "이 작업은 {count}개 테이블에 영향을 주며 오랜 시간이 걸릴 수 있습니다. 일부가 실패할 수도 있습니다.",+ veryLargeWarning: "이 작업은 {count}개 테이블에 영향을 줍니다. 오래 걸릴 것으로 예상되며 부분 실패 결과를 꼼꼼히 확인하세요.",+ noTables: "이 데이터베이스에서 테이블을 찾지 못했습니다.",+ metadataFailed: "데이터베이스 테이블 메타데이터를 읽지 못했습니다.",+ externalReferences: "다른 데이터베이스가 외래 키로 이 데이터베이스를 참조하고 있어 작업을 중단했습니다.",+ scope: "테이블 목록에 선택한 데이터베이스 외부의 객체가 포함되어 있습니다: {tables}",+ cycle: "외래 키 순환 참조가 감지되어 해당 작업을 중단했습니다: {tables}",+ refreshFailed: "새로 고침 실패: {message}",+ },+ databaseDrop: {+ menu: "모든 테이블 삭제",+ title: "모든 테이블 삭제",+ preparing: "{database}의 모든 테이블을 불러오는 중...",+ cancelledPreparation: "실행 전에 작업이 취소되었습니다.",+ message: "{connection} 연결의 {database}에 있는 {count}개 테이블을 영구 삭제합니다.",+ typeName: "확인하려면 {database}를 입력하세요",+ result: "완료: {success}, 실패: {failed}",+ skipped: "건너뜀: {count}",+ blockedBy: "{table}을(를) 건너뛰었습니다: 종속 테이블 {dependency}이(가) 완료되지 않았습니다.",+ cancelled: "취소됨: {count}",+ largeWarning: "이 작업은 {count}개 테이블에 영향을 주며 오랜 시간이 걸릴 수 있습니다. 일부가 실패할 수도 있습니다.",+ veryLargeWarning: "이 작업은 {count}개 테이블에 영향을 줍니다. 오래 걸릴 것으로 예상되며 부분 실패 결과를 꼼꼼히 확인하세요.",+ noTables: "이 데이터베이스에서 테이블을 찾지 못했습니다.",+ scope: "테이블 목록에 선택한 데이터베이스 외부의 객체가 포함되어 있습니다: {tables}",+ cycle: "외래 키 순환 참조가 감지되어 해당 작업을 중단했습니다: {tables}",+ refreshFailed: "새로 고침 실패: {message}",+ },gridfsBrowser: {bucketCount: "버킷",fileCount: "파일",diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.tsindex a819d07b94..ddb1dba35d 100644--- a/apps/desktop/src/i18n/locales/pt-BR.ts+++ b/apps/desktop/src/i18n/locales/pt-BR.ts@@ -9121,6 +9121,44 @@ export default withEnglishFallback({defaultCharset: "Conjunto de caracteres",defaultCollation: "Agrupamento",},+ databaseEmpty: {+ menu: "Esvaziar dados de todas as tabelas",+ title: "Esvaziar dados de todas as tabelas",+ preparing: "Carregando todas as tabelas em {database}...",+ cancelledPreparation: "Operação cancelada antes da execução.",+ message: "Isso excluirá todas as linhas de {count} tabelas em {database} na conexão {connection}.",+ typeName: "Digite {database} para confirmar",+ result: "Concluídas: {success}; com falha: {failed}",+ skipped: "Ignoradas: {count}",+ blockedBy: "{table} ignorada: a dependência {dependency} não foi concluída.",+ cancelled: "Canceladas: {count}",+ largeWarning: "Esta operação afeta {count} tabelas e pode demorar bastante. Falhas parciais são possíveis.",+ veryLargeWarning: "Esta operação afeta {count} tabelas. Espere uma execução longa e revise com atenção as falhas parciais.",+ noTables: "Nenhuma tabela foi encontrada neste banco de dados.",+ metadataFailed: "Não foi possível ler os metadados das tabelas do banco de dados.",+ externalReferences: "O banco de dados tem referências de chaves estrangeiras de outro banco de dados; a operação foi interrompida.",+ scope: "A lista de tabelas contém objetos fora do banco de dados selecionado: {tables}",+ cycle: "Ciclo de chaves estrangeiras detectado; a operação foi interrompida para: {tables}",+ refreshFailed: "Falha ao atualizar: {message}",+ },+ databaseDrop: {+ menu: "Remover todas as tabelas",+ title: "Remover todas as tabelas",+ preparing: "Carregando todas as tabelas em {database}...",+ cancelledPreparation: "Operação cancelada antes da execução.",+ message: "Isso removerá permanentemente {count} tabelas de {database} na conexão {connection}.",+ typeName: "Digite {database} para confirmar",+ result: "Concluídas: {success}; com falha: {failed}",+ skipped: "Ignoradas: {count}",+ blockedBy: "{table} ignorada: a dependência {dependency} não foi concluída.",+ cancelled: "Canceladas: {count}",+ largeWarning: "Esta operação afeta {count} tabelas e pode demorar bastante. Falhas parciais são possíveis.",+ veryLargeWarning: "Esta operação afeta {count} tabelas. Espere uma execução longa e revise com atenção as falhas parciais.",+ noTables: "Nenhuma tabela foi encontrada neste banco de dados.",+ scope: "A lista de tabelas contém objetos fora do banco de dados selecionado: {tables}",+ cycle: "Ciclo de chaves estrangeiras detectado; a operação foi interrompida para: {tables}",+ refreshFailed: "Falha ao atualizar: {message}",+ },gridfsBrowser: {bucketCount: "Buckets",fileCount: "Arquivos",diff --git a/apps/desktop/src/i18n/locales/ru.ts b/apps/desktop/src/i18n/locales/ru.tsindex 9b27f595ae..f81e017b5d 100644--- a/apps/desktop/src/i18n/locales/ru.ts+++ b/apps/desktop/src/i18n/locales/ru.ts@@ -1933,6 +1933,44 @@ export default withEnglishFallback({defaultCharset: "Кодировка",defaultCollation: "Сортировка",},+ databaseEmpty: {+ menu: "Очистить данные всех таблиц",+ title: "Очистить данные всех таблиц",+ preparing: "Загрузка всех таблиц в {database}...",+ cancelledPreparation: "Операция отменена до выполнения.",+ message: "Будут удалены все строки из {count} таблиц в {database} на подключении {connection}.",+ typeName: "Введите {database} для подтверждения",+ result: "Завершено: {success}; с ошибками: {failed}",+ skipped: "Пропущено: {count}",+ blockedBy: "Пропущена {table}: зависимость {dependency} не была завершена.",+ cancelled: "Отменено: {count}",+ largeWarning: "Операция затрагивает {count} таблиц и может занять много времени. Возможны частичные сбои.",+ veryLargeWarning: "Операция затрагивает {count} таблиц. Ожидайте длительного выполнения и внимательно проверьте частичные сбои.",+ noTables: "В этой базе данных таблицы не найдены.",+ metadataFailed: "Не удалось прочитать метаданные таблиц базы данных.",+ externalReferences: "На базу данных есть ссылки по внешним ключам из другой базы данных; операция остановлена.",+ scope: "Список таблиц содержит объекты вне выбранной базы данных: {tables}",+ cycle: "Обнаружен цикл по внешним ключам; операция остановлена для: {tables}",+ refreshFailed: "Не удалось обновить: {message}",+ },+ databaseDrop: {+ menu: "Удалить все таблицы",+ title: "Удалить все таблицы",+ preparing: "Загрузка всех таблиц в {database}...",+ cancelledPreparation: "Операция отменена до выполнения.",+ message: "Будут безвозвратно удалены {count} таблиц из {database} на подключении {connection}.",+ typeName: "Введите {database} для подтверждения",+ result: "Завершено: {success}; с ошибками: {failed}",+ skipped: "Пропущено: {count}",+ blockedBy: "Пропущена {table}: зависимость {dependency} не была завершена.",+ cancelled: "Отменено: {count}",+ largeWarning: "Операция затрагивает {count} таблиц и может занять много времени. Возможны частичные сбои.",+ veryLargeWarning: "Операция затрагивает {count} таблиц. Ожидайте длительного выполнения и внимательно проверьте частичные сбои.",+ noTables: "В этой базе данных таблицы не найдены.",+ scope: "Список таблиц содержит объекты вне выбранной базы данных: {tables}",+ cycle: "Обнаружен цикл по внешним ключам; операция остановлена для: {tables}",+ refreshFailed: "Не удалось обновить: {message}",+ },gridfsBrowser: {bucketCount: "контейнеров",fileCount: "файлов",diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.tsindex 343f163893..655d982767 100644--- a/apps/desktop/src/i18n/locales/zh-CN.ts+++ b/apps/desktop/src/i18n/locales/zh-CN.ts@@ -1961,6 +1961,44 @@ export default withEnglishFallback({defaultCharset: "默认字符集",defaultCollation: "默认排序规则",},+ databaseEmpty: {+ menu: "清空所有表数据",+ title: "清空所有表数据",+ preparing: "正在加载数据库 {database} 的全部表...",+ cancelledPreparation: "操作已取消,尚未执行 SQL。",+ message: "将清空连接 {connection} 中数据库 {database} 的 {count} 张表数据。",+ typeName: "输入 {database} 以确认",+ result: "已完成:{success};失败:{failed}",+ skipped: "跳过:{count}",+ blockedBy: "已跳过 {table}:依赖表 {dependency} 未完成。",+ cancelled: "已取消:{count}",+ largeWarning: "本次操作涉及 {count} 张表,可能需要较长时间,并可能出现部分失败。",+ veryLargeWarning: "本次操作涉及 {count} 张表,执行时间可能很长,请重点关注部分失败结果。",+ noTables: "数据库中没有找到表。",+ metadataFailed: "读取数据库表元数据失败。",+ externalReferences: "检测到其他数据库对当前库存在外键引用,已停止操作。",+ scope: "表清单包含当前数据库之外的对象:{tables}",+ cycle: "检测到外键循环依赖,已停止操作:{tables}",+ refreshFailed: "刷新失败:{message}",+ },+ databaseDrop: {+ menu: "删除所有表",+ title: "删除所有表",+ preparing: "正在加载数据库 {database} 的全部表...",+ cancelledPreparation: "操作已取消,尚未执行 SQL。",+ message: "将永久删除连接 {connection} 中数据库 {database} 的 {count} 张表。",+ typeName: "输入 {database} 以确认",+ result: "已完成:{success};失败:{failed}",+ skipped: "跳过:{count}",+ blockedBy: "已跳过 {table}:依赖表 {dependency} 未完成。",+ cancelled: "已取消:{count}",+ largeWarning: "本次操作涉及 {count} 张表,可能需要较长时间,并可能出现部分失败。",+ veryLargeWarning: "本次操作涉及 {count} 张表,执行时间可能很长,请重点关注部分失败结果。",+ noTables: "数据库中没有找到表。",+ scope: "表清单包含当前数据库之外的对象:{tables}",+ cycle: "检测到外键循环依赖,已停止操作:{tables}",+ refreshFailed: "刷新失败:{message}",+ },gridfsBrowser: {bucketCount: "\u5b58\u50a8\u6876",fileCount: "\u6587\u4ef6",diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.tsindex b5bdf46673..c9884afd62 100644--- a/apps/desktop/src/i18n/locales/zh-TW.ts+++ b/apps/desktop/src/i18n/locales/zh-TW.ts@@ -9139,6 +9139,44 @@ export default withEnglishFallback({defaultCharset: "預設字元集",defaultCollation: "預設定序規則",},+ databaseEmpty: {+ menu: "清空所有資料表資料",+ title: "清空所有資料表資料",+ preparing: "正在載入資料庫 {database} 的全部資料表...",+ cancelledPreparation: "操作已取消,尚未執行 SQL。",+ message: "將清空連線 {connection} 中資料庫 {database} 的 {count} 張資料表資料。",+ typeName: "輸入 {database} 以確認",+ result: "已完成:{success};失敗:{failed}",+ skipped: "已略過:{count}",+ blockedBy: "已略過 {table}:相依資料表 {dependency} 未完成。",+ cancelled: "已取消:{count}",+ largeWarning: "本次操作涉及 {count} 張資料表,可能需要較長時間,並可能出現部分失敗。",+ veryLargeWarning: "本次操作涉及 {count} 張資料表,執行時間可能很長,請重點關注部分失敗結果。",+ noTables: "資料庫中沒有找到資料表。",+ metadataFailed: "讀取資料庫資料表中繼資料失敗。",+ externalReferences: "偵測到其他資料庫對目前資料庫存在外鍵引用,已停止操作。",+ scope: "資料表清單包含目前資料庫之外的物件:{tables}",+ cycle: "偵測到外鍵循環相依,已停止操作:{tables}",+ refreshFailed: "重新整理失敗:{message}",+ },+ databaseDrop: {+ menu: "刪除所有資料表",+ title: "刪除所有資料表",+ preparing: "正在載入資料庫 {database} 的全部資料表...",+ cancelledPreparation: "操作已取消,尚未執行 SQL。",+ message: "將永久刪除連線 {connection} 中資料庫 {database} 的 {count} 張資料表。",+ typeName: "輸入 {database} 以確認",+ result: "已完成:{success};失敗:{failed}",+ skipped: "已略過:{count}",+ blockedBy: "已略過 {table}:相依資料表 {dependency} 未完成。",+ cancelled: "已取消:{count}",+ largeWarning: "本次操作涉及 {count} 張資料表,可能需要較長時間,並可能出現部分失敗。",+ veryLargeWarning: "本次操作涉及 {count} 張資料表,執行時間可能很長,請重點關注部分失敗結果。",+ noTables: "資料庫中沒有找到資料表。",+ scope: "資料表清單包含目前資料庫之外的物件:{tables}",+ cycle: "偵測到外鍵循環相依,已停止操作:{tables}",+ refreshFailed: "重新整理失敗:{message}",+ },gridfsBrowser: {bucketCount: "儲存桶",fileCount: "檔案",diff --git a/apps/desktop/src/lib/__tests__/sidebar/batchTableEmpty.spec.ts b/apps/desktop/src/lib/__tests__/sidebar/batchTableEmpty.spec.tsindex 1f3d15df4b..4f3ead93be 100644--- a/apps/desktop/src/lib/__tests__/sidebar/batchTableEmpty.spec.ts+++ b/apps/desktop/src/lib/__tests__/sidebar/batchTableEmpty.spec.ts@@ -1,5 +1,5 @@import { describe, expect, it } from "vitest";-import { batchTableEmptyFeedback, buildBatchTableEmptyPlan, runBatchTableEmpty } from "@/lib/sidebar/batchTableEmpty";+import { batchTableEmptyFeedback, buildBatchTableEmptyPlan, runBatchTableEmpty, runBatchTableEmptyLayers } from "@/lib/sidebar/batchTableEmpty";describe("batch table empty", () => {it("executes the exact SQL captured for the confirmation preview", async () => {@@ -37,6 +37,8 @@ describe("batch table empty", () => {const succeeded = { succeeded: ["events"], failed: [] };const partial = { succeeded: ["events"], failed: [{ target: "logs", error: new Error("failed") }] };const failed = { succeeded: [], failed: [{ target: "logs", error: new Error("failed") }] };+ const skipped = { succeeded: ["events"], failed: [], skipped: [{ target: "logs", reason: "blocked" }] };+ const cancelled = { succeeded: ["events"], failed: [], cancelled: ["logs"] };expect(batchTableEmptyFeedback(succeeded, true)).toBe("submitted");expect(batchTableEmptyFeedback(partial, true)).toBe("submitted-partial");@@ -44,5 +46,102 @@ describe("batch table empty", () => {expect(batchTableEmptyFeedback(succeeded, false)).toBe("success");expect(batchTableEmptyFeedback(partial, false)).toBe("partial");expect(batchTableEmptyFeedback(failed, false)).toBe("partial");+ expect(batchTableEmptyFeedback(skipped, false)).toBe("partial");+ expect(batchTableEmptyFeedback(cancelled, true)).toBe("submitted-partial");+ });++ it("limits independent table execution concurrency", async () => {+ let active = 0;+ let peak = 0;+ const result = await runBatchTableEmptyLayers([{ items: Array.from({ length: 40 }, (_, i) => ({ target: i, sql: `DELETE ${i}` })) }], {+ concurrency: 8,+ execute: async () => {+ active += 1;+ peak = Math.max(peak, active);+ await new Promise((resolve) => setTimeout(resolve, 1));+ active -= 1;+ },+ });+ expect(peak).toBeLessThanOrEqual(8);+ expect(result.succeeded).toHaveLength(40);+ });++ it("stops dispatching after cancellation", async () => {+ let dispatched = 0;+ let cancelled = false;+ const result = await runBatchTableEmptyLayers([{ items: Array.from({ length: 20 }, (_, i) => ({ target: i, sql: `DELETE ${i}` })) }], {+ concurrency: 4,+ isCancelled: () => cancelled,+ execute: async () => {+ dispatched += 1;+ cancelled = true;+ },+ });+ expect(dispatched).toBe(1);+ expect(result.cancelled?.length).toBe(19);+ });++ it("classifies an in-flight cancellation separately from a failure", async () => {+ let cancelled = false;+ const result = await runBatchTableEmptyLayers([{ items: [{ target: "orders", sql: "DELETE FROM orders" }] }], {+ isCancelled: () => cancelled,+ execute: async () => {+ cancelled = true;+ throw new Error("request aborted");+ },+ });++ expect(result.failed).toHaveLength(0);+ expect(result.cancelled).toEqual(["orders"]);+ });++ it("skips a parent after a child in an earlier layer fails", async () => {+ const executed: string[] = [];+ const result = await runBatchTableEmptyLayers([{ items: [{ target: "child", sql: "DELETE FROM child" }] }, { items: [{ target: "parent", sql: "DELETE FROM parent" }], dependencies: { parent: ["child"] } }], {+ keyOf: (target) => target,+ execute: async ({ target }) => {+ executed.push(target);+ throw new Error("permission denied");+ },+ });++ expect(executed).toEqual(["child"]);+ expect(result.failed.map(({ target }) => target)).toEqual(["child"]);+ expect(result.skipped?.map(({ target }) => target)).toEqual(["parent"]);+ });++ it("builds SQL previews with bounded concurrency", async () => {+ let active = 0;+ let peak = 0;+ const plan = await buildBatchTableEmptyPlan(+ Array.from({ length: 40 }, (_, index) => index),+ async (target) => {+ active += 1;+ peak = Math.max(peak, active);+ await new Promise((resolve) => setTimeout(resolve, 1));+ active -= 1;+ return `DELETE FROM table_${target};`;+ },+ );++ expect(plan).toHaveLength(40);+ expect(peak).toBeLessThanOrEqual(8);+ });++ it("stops scheduling new SQL previews after the first build failure", async () => {+ let calls = 0;+ await expect(+ buildBatchTableEmptyPlan(+ Array.from({ length: 40 }, (_, index) => index),+ async (target) => {+ calls += 1;+ if (target === 0) throw new Error("preview failed");+ await new Promise((resolve) => setTimeout(resolve, 1));+ return `DELETE FROM table_${target};`;+ },+ ),+ ).rejects.toThrow("preview failed");++ expect(calls).toBeLessThanOrEqual(8);});});diff --git a/apps/desktop/src/lib/__tests__/sidebar/databaseTableEmpty.spec.ts b/apps/desktop/src/lib/__tests__/sidebar/databaseTableEmpty.spec.tsnew file mode 100644index 0000000000..474c749e8a--- /dev/null+++ b/apps/desktop/src/lib/__tests__/sidebar/databaseTableEmpty.spec.ts@@ -0,0 +1,125 @@+import { describe, expect, it } from "vitest";+import { buildDatabaseTableEmptyPlan, buildDatabaseTableEmptyPlanLayers, buildMysqlTableMutationSql, DatabaseTableEmptyPlanError } from "@/lib/sidebar/databaseTableEmpty";++describe("database table empty plan", () => {+ it("renders MySQL mutation SQL locally and escapes backticks", () => {+ expect(buildMysqlTableMutationSql("empty", "app`db", "order`items")).toBe("DELETE FROM `app``db`.`order``items`;");+ expect(buildMysqlTableMutationSql("drop", "app", "orders")).toBe("DROP TABLE `app`.`orders`;");+ expect(buildMysqlTableMutationSql("empty", " app ", "orders")).toBe("DELETE FROM ` app `.`orders`;");+ });++ it("uses a stable table-name order for independent tables", async () => {+ const plan = await buildDatabaseTableEmptyPlan({+ database: "app",+ listTables: async () => [+ { name: "zebra", object_type: "TABLE", schema: "app" },+ { name: "alpha", object_type: "TABLE", schema: "app" },+ ],+ foreignKeysByTable: {},+ buildSql: async (table) => `DELETE FROM \`app\`.\`${table.name}\`;`,+ });++ expect(plan.map(({ target }) => target.name)).toEqual(["alpha", "zebra"]);+ });++ it("does not treat inherited object keys as foreign-key metadata", async () => {+ const foreignKeysByTable = Object.create({ toString: [{ name: "inherited", column: "id", ref_table: "parent", ref_column: "id" }] }) as Record<string, never>;+ const plan = await buildDatabaseTableEmptyPlan({+ database: "app",+ listTables: async () => [{ name: "toString", object_type: "TABLE", schema: "app" }],+ foreignKeysByTable,+ buildSql: async (table) => `DELETE FROM \`app\`.\`${table.name}\`;`,+ });++ expect(plan.map(({ target }) => target.name)).toEqual(["toString"]);+ });++ it("orders referencing tables before their parents", async () => {+ const options = {+ database: "app",+ listTables: async () => [+ { name: "parent", object_type: "TABLE", schema: "app" },+ { name: "child", object_type: "TABLE", schema: "app" },+ ],+ listForeignKeys: async (table) => (table.name === "child" ? [{ name: "fk", column: "parent_id", ref_table: "parent", ref_column: "id" }] : []),+ buildSql: async (table) => `DELETE FROM \`${table.schema}\`.\`${table.name}\`;`,+ };+ const plan = await buildDatabaseTableEmptyPlan(options);+ const layers = await buildDatabaseTableEmptyPlanLayers(options);+ expect(plan.map(({ target }) => target.name)).toEqual(["child", "parent"]);+ expect(layers[1]?.dependencies).toEqual({ parent: ["child"] });+ });++ it("stops on a foreign-key cycle instead of falling back to unsafe order", async () => {+ await expect(+ buildDatabaseTableEmptyPlan({+ database: "app",+ listTables: async () => [+ { name: "a", object_type: "TABLE", schema: "app" },+ { name: "b", object_type: "TABLE", schema: "app" },+ ],+ listForeignKeys: async (table) => [{ name: "fk", column: "id", ref_table: table.name === "a" ? "b" : "a", ref_column: "id" }],+ buildSql: async () => "DELETE FROM t;",+ }),+ ).rejects.toBeInstanceOf(DatabaseTableEmptyPlanError);+ });++ it("treats a self-referencing foreign key as independent instead of a cycle", async () => {+ const plan = await buildDatabaseTableEmptyPlan({+ database: "app",+ listTables: async () => [+ { name: "departments", object_type: "TABLE", schema: "app" },+ { name: "employees", object_type: "TABLE", schema: "app" },+ ],+ listForeignKeys: async (table) =>+ table.name === "employees"+ ? [+ { name: "fk_manager", column: "manager_id", ref_table: "employees", ref_column: "id" },+ { name: "fk_department", column: "department_id", ref_table: "departments", ref_column: "id" },+ ]+ : [],+ buildSql: async (table) => `DELETE FROM \`${table.schema}\`.\`${table.name}\`;`,+ });++ expect(plan.map(({ target }) => target.name)).toEqual(["employees", "departments"]);+ });++ it("builds a large no-dependency plan without per-table metadata calls", async () => {+ const tables = Array.from({ length: 1000 }, (_, index) => ({ name: `table_${index}`, object_type: "TABLE", schema: "app" }));+ let metadataCalls = 0;+ const sqlProgress: Array<[number, number]> = [];+ const layers = await buildDatabaseTableEmptyPlanLayers({+ database: "app",+ listTables: async () => tables,+ foreignKeysByTable: {},+ buildSql: async (table) => `DELETE FROM \`app\`.\`${table.name}\`;`,+ onProgress: () => {+ metadataCalls += 1;+ },+ onSqlProgress: (completed, total) => {+ sqlProgress.push([completed, total]);+ },+ });+ expect(layers).toHaveLength(1);+ expect(layers[0]!.items).toHaveLength(1000);+ expect(metadataCalls).toBe(1000);+ expect(sqlProgress.at(-1)).toEqual([1000, 1000]);+ });++ it("does not start table metadata loading after cancellation", async () => {+ let listTablesCalls = 0;+ await expect(+ buildDatabaseTableEmptyPlan({+ database: "app",+ listTables: async () => {+ listTablesCalls += 1;+ return [];+ },+ foreignKeysByTable: {},+ buildSql: async () => "DELETE FROM app.table;",+ isCancelled: () => true,+ }),+ ).rejects.toMatchObject({ reason: "cancelled" });+ expect(listTablesCalls).toBe(0);+ });+});diff --git a/apps/desktop/src/lib/backend/api.ts b/apps/desktop/src/lib/backend/api.tsindex 8376e1839f..0d8779e9be 100644--- a/apps/desktop/src/lib/backend/api.ts+++ b/apps/desktop/src/lib/backend/api.ts@@ -233,6 +233,7 @@ export const listIndexes = forward("listIndexes");export const listReferenceKeyColumns = forward("listReferenceKeyColumns");export const listReferenceKeys = forward("listReferenceKeys");export const listForeignKeys = forward("listForeignKeys");+export const listForeignKeysForDatabase = forward("listForeignKeysForDatabase");export const listTriggers = forward("listTriggers");export const listConstraints = forward("listConstraints");export const listPartitions = forward("listPartitions");diff --git a/apps/desktop/src/lib/backend/http.ts b/apps/desktop/src/lib/backend/http.tsindex 47dfafca6f..66a2a5f553 100644--- a/apps/desktop/src/lib/backend/http.ts+++ b/apps/desktop/src/lib/backend/http.ts@@ -1194,7 +1194,7 @@ export async function getMysqlTableAutoIncrement(connectionId: string, database:return get(`/api/schema/mysql/auto-increment?${qs({ connection_id: connectionId, database, table })}`);}-export async function listObjects(connectionId: string, database: string, schema: string, objectTypes?: (SidebarObjectKind | "EVENT")[], filter?: string, limit?: number, offset?: number, catalog?: string, tableNameFilter?: TableNameFilter): Promise<ObjectInfo[]> {+export async function listObjects(connectionId: string, database: string, schema: string, objectTypes?: (SidebarObjectKind | "EVENT")[], filter?: string, limit?: number, offset?: number, catalog?: string, tableNameFilter?: TableNameFilter, executionId?: string): Promise<ObjectInfo[]> {return get(`/api/schema/objects?${qs({connection_id: connectionId,@@ -1206,6 +1206,7 @@ export async function listObjects(connectionId: string, database: string, schemaoffset,catalog,table_name_filter: tableNameFilter ? JSON.stringify(tableNameFilter) : undefined,+ execution_id: executionId,})}`,);}@@ -1276,6 +1277,10 @@ export async function listForeignKeys(connectionId: string, database: string, screturn get(`/api/schema/foreign-keys?${qs({ connection_id: connectionId, database, schema, table, catalog })}`);}+export async function listForeignKeysForDatabase(connectionId: string, database: string, schema: string, catalog?: string, executionId?: string): Promise<Record<string, ForeignKeyInfo[]>> {+ return get(`/api/schema/foreign-keys-for-database?${qs({ connection_id: connectionId, database, schema, catalog, execution_id: executionId })}`);+}+export async function listTriggers(connectionId: string, database: string, schema: string, table: string, catalog?: string): Promise<TriggerInfo[]> {return get(`/api/schema/triggers?${qs({ connection_id: connectionId, database, schema, table, catalog })}`);}diff --git a/apps/desktop/src/lib/backend/tauri.ts b/apps/desktop/src/lib/backend/tauri.tsindex a9e3ad2f0e..c0e4ecd466 100644--- a/apps/desktop/src/lib/backend/tauri.ts+++ b/apps/desktop/src/lib/backend/tauri.ts@@ -1693,7 +1693,18 @@ export async function getMysqlTableAutoIncrement(connectionId: string, database:return invoke("get_mysql_table_auto_increment", { connectionId, database, table });}-export async function listObjects(connectionId: string, database: string, schema: string, objectTypes?: (SidebarObjectKind | "EVENT")[], filter?: string, limit?: number, offset?: number, catalog?: string, tableNameFilter?: import("@/types/database").TableNameFilter): Promise<ObjectInfo[]> {+export async function listObjects(+ connectionId: string,+ database: string,+ schema: string,+ objectTypes?: (SidebarObjectKind | "EVENT")[],+ filter?: string,+ limit?: number,+ offset?: number,+ catalog?: string,+ tableNameFilter?: import("@/types/database").TableNameFilter,+ executionId?: string,+): Promise<ObjectInfo[]> {return invoke("list_objects", {connectionId,database,@@ -1704,6 +1715,7 @@ export async function listObjects(connectionId: string, database: string, schemaoffset,catalog,tableNameFilter,+ executionId,});}@@ -2448,6 +2460,10 @@ export async function listForeignKeys(connectionId: string, database: string, sc});}+export async function listForeignKeysForDatabase(connectionId: string, database: string, schema: string, catalog?: string, executionId?: string): Promise<Record<string, ForeignKeyInfo[]>> {+ return invoke("list_foreign_keys_for_database", { connectionId, database, schema, catalog, executionId });+}+export async function listTriggers(connectionId: string, database: string, schema: string, table: string, catalog?: string): Promise<TriggerInfo[]> {return invoke("list_triggers", {connectionId,diff --git a/apps/desktop/src/lib/sidebar/batchTableEmpty.ts b/apps/desktop/src/lib/sidebar/batchTableEmpty.tsindex 8409721bc2..467832e595 100644--- a/apps/desktop/src/lib/sidebar/batchTableEmpty.ts+++ b/apps/desktop/src/lib/sidebar/batchTableEmpty.ts@@ -1,6 +1,10 @@+import { uuid } from "@/lib/common/utils";+export interface BatchTableEmptyResult<T> {succeeded: T[];failed: Array<{ target: T; error: unknown }>;+ skipped?: Array<{ target: T; reason: string; dependency?: string }>;+ cancelled?: T[];}export interface BatchTableEmptyPlanItem<T> {@@ -10,14 +14,37 @@ export interface BatchTableEmptyPlanItem<T> {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 buildBatchTableEmptyPlan<T>(targets: readonly T[], buildSql: (target: T) => Promise<string>, options: { concurrency?: number; isCancelled?: () => boolean; onProgress?: (completed: number, total: number) => void } = {}): Promise<BatchTableEmptyPlanItem<T>[]> {+ const plan: Array<BatchTableEmptyPlanItem<T> | undefined> = Array.from({ length: targets.length });+ const concurrency = Math.max(1, Math.min(options.concurrency ?? 8, 16));+ let cursor = 0;+ let completed = 0;+ let stopped = false;+ let firstError: unknown;+ const workers = Array.from({ length: Math.min(concurrency, targets.length) }, async () => {+ while (!stopped && cursor < targets.length) {+ if (options.isCancelled?.()) {+ stopped = true;+ firstError ??= new Error("Operation cancelled");+ return;+ }+ const index = cursor++;+ try {+ const sql = await buildSql(targets[index]!);+ if (!sql.trim()) throw new Error("Empty table SQL preview is unavailable");+ if (stopped) return;+ plan[index] = { target: targets[index]!, sql };+ options.onProgress?.(++completed, targets.length);+ } catch (error) {+ stopped = true;+ firstError ??= error;+ return;+ }+ }+ });+ await Promise.all(workers);+ if (firstError) throw firstError;+ return plan.filter((item): item is BatchTableEmptyPlanItem<T> => item !== undefined);}export async function runBatchTableEmpty<T>(targets: readonly T[], execute: (target: T) => Promise<void>): Promise<BatchTableEmptyResult<T>> {@@ -33,7 +60,61 @@ export async function runBatchTableEmpty<T>(targets: readonly T[], execute: (tarreturn result;}+export async function runBatchTableEmptyLayers<T>(+ layers: readonly { items: readonly BatchTableEmptyPlanItem<T>[]; dependencies?: Record<string, string[]> }[],+ options: {+ concurrency?: number;+ execute: (item: BatchTableEmptyPlanItem<T>, executionId: string) => Promise<void>;+ isCancelled?: () => boolean;+ keyOf?: (target: T) => string;+ onProgress?: (completed: number, total: number) => void;+ },+): Promise<BatchTableEmptyResult<T>> {+ const result: BatchTableEmptyResult<T> = { succeeded: [], failed: [], skipped: [], cancelled: [] };+ const concurrency = Math.max(1, Math.min(options.concurrency ?? 8, 16));+ let completed = 0;+ const total = layers.reduce((sum, layer) => sum + layer.items.length, 0);++ for (const layer of layers) {+ const queue = [...layer.items];+ let cursor = 0;+ const workers = Array.from({ length: Math.min(concurrency, queue.length) }, async () => {+ while (cursor < queue.length) {+ const item = queue[cursor++];+ const key = options.keyOf?.(item.target);+ const blockedBy = key && layer.dependencies?.[key]?.find((dependency) => result.failed.some(({ target }) => options.keyOf?.(target) === dependency) || result.skipped?.some(({ target }) => options.keyOf?.(target) === dependency));+ if (blockedBy) {+ (result.skipped ??= []).push({ target: item.target, reason: `blocked by ${blockedBy}`, dependency: blockedBy });+ completed += 1;+ options.onProgress?.(completed, total);+ continue;+ }+ if (options.isCancelled?.()) {+ (result.cancelled ??= []).push(item.target);+ completed += 1;+ options.onProgress?.(completed, total);+ continue;+ }+ const executionId = uuid();+ try {+ await options.execute(item, executionId);+ result.succeeded.push(item.target);+ } catch (error) {+ if (options.isCancelled?.()) (result.cancelled ??= []).push(item.target);+ else result.failed.push({ target: item.target, error });+ } finally {+ completed += 1;+ options.onProgress?.(completed, total);+ }+ }+ });+ await Promise.all(workers);+ }+ return result;+}+export function batchTableEmptyFeedback(result: BatchTableEmptyResult<unknown>, asynchronousMutation: boolean): BatchTableEmptyFeedback {- if (asynchronousMutation) return result.failed.length > 0 ? "submitted-partial" : "submitted";- return result.failed.length > 0 ? "partial" : "success";+ const incomplete = result.failed.length > 0 || (result.skipped?.length ?? 0) > 0 || (result.cancelled?.length ?? 0) > 0;+ if (asynchronousMutation) return incomplete ? "submitted-partial" : "submitted";+ return incomplete ? "partial" : "success";}diff --git a/apps/desktop/src/lib/sidebar/databaseTableEmpty.ts b/apps/desktop/src/lib/sidebar/databaseTableEmpty.tsnew file mode 100644index 0000000000..ad06eb4615--- /dev/null+++ b/apps/desktop/src/lib/sidebar/databaseTableEmpty.ts@@ -0,0 +1,140 @@+import type { ForeignKeyInfo, ObjectInfo } from "@/types/database";+import { buildBatchTableEmptyPlan, type BatchTableEmptyPlanItem } from "@/lib/sidebar/batchTableEmpty";++export interface DatabaseEmptyTable {+ name: string;+ schema: string;+}++export type DatabaseTableEmptyOperation = "empty" | "drop";++function quoteMysqlIdentifier(value: string): string {+ return `\`${value.replaceAll("`", "``")}\``;+}++export function buildMysqlTableMutationSql(operation: DatabaseTableEmptyOperation, database: string, tableName: string): string {+ const table = database ? `${quoteMysqlIdentifier(database)}.${quoteMysqlIdentifier(tableName)}` : quoteMysqlIdentifier(tableName);+ return `${operation === "empty" ? "DELETE FROM" : "DROP TABLE"} ${table};`;+}++export class DatabaseTableEmptyPlanError extends Error {+ constructor(+ public readonly reason: "cycle" | "scope" | "cancelled",+ public readonly tables: string[],+ ) {+ super(`${reason}: ${tables.join(", ")}`);+ }+}++export interface DatabaseEmptyTableLayer {+ items: BatchTableEmptyPlanItem<DatabaseEmptyTable>[];+ dependencies?: Record<string, string[]>;+}++interface BuildOptions {+ database: string;+ listTables: () => Promise<ObjectInfo[]>;+ listForeignKeys?: (table: DatabaseEmptyTable) => Promise<ForeignKeyInfo[]>;+ foreignKeysByTable?: Record<string, ForeignKeyInfo[]>;+ buildSql: (table: DatabaseEmptyTable) => Promise<string>;+ isCancelled?: () => boolean;+ onProgress?: (completed: number, total: number) => void;+ onSqlProgress?: (completed: number, total: number) => void;+}++/** Only fresh, unfiltered metadata belongs in a database-wide destructive plan. */+async function buildLayers(options: BuildOptions): Promise<DatabaseEmptyTableLayer[]> {+ if (options.isCancelled?.()) throw new DatabaseTableEmptyPlanError("cancelled", []);+ const objects = await options.listTables();+ if (options.isCancelled?.()) throw new DatabaseTableEmptyPlanError("cancelled", []);+ const tables = new Map<string, DatabaseEmptyTable>();+ for (const object of objects) {+ if (object.object_type !== "TABLE") continue;+ if (object.schema && object.schema !== options.database) throw new DatabaseTableEmptyPlanError("scope", [object.name]);+ tables.set(object.name, { name: object.name, schema: options.database });+ }++ const tableNames = [...tables.keys()].sort((left, right) => (left < right ? -1 : left > right ? 1 : 0));+ const dependencies = new Map<string, Set<string>>();+ const incoming = new Map(tableNames.map((name) => [name, 0]));+ let metadataCompleted = 0;+ for (const name of tableNames) {+ const table = tables.get(name)!;+ if (options.isCancelled?.()) throw new DatabaseTableEmptyPlanError("cancelled", []);+ const parents = new Set<string>();+ const hasBatchForeignKeys = options.foreignKeysByTable && Object.prototype.hasOwnProperty.call(options.foreignKeysByTable, table.name);+ const foreignKeys = hasBatchForeignKeys ? (options.foreignKeysByTable![table.name] ?? []) : options.listForeignKeys ? await options.listForeignKeys(table) : [];+ for (const fk of foreignKeys) {+ if (fk.ref_schema && fk.ref_schema !== options.database) continue;+ // A self-referencing foreign key is not a dependency edge: per-table DELETE/DROP are not+ // blocked by it and runtime constraints catch any leftover violations.+ if (fk.ref_table === table.name) continue;+ if (!tables.has(fk.ref_table)) throw new DatabaseTableEmptyPlanError("scope", [fk.ref_table]);+ parents.add(fk.ref_table);+ }+ dependencies.set(table.name, parents);+ for (const parent of parents) incoming.set(parent, incoming.get(parent)! + 1);+ options.onProgress?.(++metadataCompleted, tables.size);+ }++ const layers: DatabaseEmptyTableLayer[] = [];+ let ready = tableNames.filter((name) => incoming.get(name) === 0);+ let processed = 0;+ let sqlCompleted = 0;+ while (ready.length) {+ if (options.isCancelled?.()) throw new DatabaseTableEmptyPlanError("cancelled", []);+ const names = ready;+ ready = [];+ const targets = names.map((name) => tables.get(name)!);+ let items: BatchTableEmptyPlanItem<DatabaseEmptyTable>[];+ try {+ items = await buildBatchTableEmptyPlan(targets, options.buildSql, {+ concurrency: 8,+ isCancelled: options.isCancelled,+ onProgress: (completed) => options.onSqlProgress?.(sqlCompleted + completed, tables.size),+ });+ } catch (error) {+ if (options.isCancelled?.()) throw new DatabaseTableEmptyPlanError("cancelled", []);+ throw error;+ }+ const reverseDependencies = new Map<string, string[]>();+ for (const [child, parents] of dependencies) {+ for (const parent of parents) {+ const children = reverseDependencies.get(parent) ?? [];+ children.push(child);+ reverseDependencies.set(parent, children);+ }+ }+ layers.push({+ items,+ dependencies: Object.fromEntries(names.map((name) => [name, reverseDependencies.get(name) ?? []])),+ });+ sqlCompleted += targets.length;+ processed += names.length;+ for (const name of names) {+ for (const parent of dependencies.get(name)!) {+ const remaining = incoming.get(parent)! - 1;+ incoming.set(parent, remaining);+ if (remaining === 0) ready.push(parent);+ }+ }+ ready.sort((left, right) => (left < right ? -1 : left > right ? 1 : 0));+ }+ // Unlike the legacy drop sorter, never silently fall back to an unsafe order.+ if (processed !== tables.size) {+ throw new DatabaseTableEmptyPlanError(+ "cycle",+ [...incoming].filter(([, count]) => count > 0).map(([name]) => name),+ );+ }+ return layers;+}++export async function buildDatabaseTableEmptyPlanLayers(options: BuildOptions): Promise<DatabaseEmptyTableLayer[]> {+ return buildLayers(options);+}++export async function buildDatabaseTableEmptyPlan(options: BuildOptions) {+ const layers = await buildLayers(options);+ return layers.flatMap((layer) => layer.items);+}diff --git a/apps/desktop/src/lib/sidebar/sidebarDangerDialog.ts b/apps/desktop/src/lib/sidebar/sidebarDangerDialog.tsindex dfb9b69b44..6ab82fc065 100644--- a/apps/desktop/src/lib/sidebar/sidebarDangerDialog.ts+++ b/apps/desktop/src/lib/sidebar/sidebarDangerDialog.ts@@ -12,6 +12,7 @@ export interface SidebarDangerDialogOption {export interface SidebarDangerDialogProgress {completed: number;total: number;+ phase?: "preparing" | "executing";}export interface SidebarDangerDialogTextInput {@@ -28,6 +29,7 @@ export interface SidebarDangerDialogRequest {message: string;confirmLabel: string;sql?: string;+ copySql?: string | (() => string);details?: string;detailsText?: string;loading?: boolean;diff --git a/crates/dbx-core/src/schema/mod.rs b/crates/dbx-core/src/schema/mod.rsindex cbc32e3f01..8d19017823 100644--- a/crates/dbx-core/src/schema/mod.rs+++ b/crates/dbx-core/src/schema/mod.rs@@ -8437,6 +8437,35 @@ pub async fn list_foreign_keys_core(result}+pub async fn list_foreign_keys_for_database_core(+ state: &AppState,+ connection_id: &str,+ database: &str,+ schema: &str,+) -> Result<HashMap<String, Vec<db::ForeignKeyInfo>>, String> {+ if crate::sql_dialect::parse_sqlserver_linked_schema_ref(schema).is_some() {+ return Ok(HashMap::new());+ }+ retry_metadata_connection(state, connection_id, Some(database), || async {+ let pool_key = state.get_or_create_metadata_pool_for_session(connection_id, Some(database), None).await?;+ let db_config = connection_config(state, connection_id).await;+ let pool = clone_metadata_pool(state, &pool_key).await.ok_or("Pool not found")?;+ match &pool {+ PoolKind::Mysql(p, mode)+ if *mode != MysqlMode::OceanBaseOracle+ && !db_config.as_ref().is_some_and(db::mysql_compatible::uses_show_metadata) =>+ {+ db::mysql::list_foreign_keys_for_database(p, mysql_table_metadata_catalog(database, schema)).await+ }+ PoolKind::Mysql(_, _) => {+ Err("Database-wide foreign-key metadata is not supported for this MySQL variant".to_string())+ }+ _ => Err("Database-wide foreign-key metadata requires a native MySQL connection".to_string()),+ }+ })+ .await+}+async fn list_foreign_keys_core_for_session(state: &AppState,connection_id: &str,diff --git a/crates/dbx-driver-mysql/src/mysql.rs b/crates/dbx-driver-mysql/src/mysql.rsindex 1e14f22671..cf29cd375b 100644--- a/crates/dbx-driver-mysql/src/mysql.rs+++ b/crates/dbx-driver-mysql/src/mysql.rs@@ -7132,6 +7132,64 @@ pub async fn list_foreign_keys(pool: &MySqlPool, database: &str, table: &str) ->.collect())}+/// Reads all foreign keys for a database with two catalog queries. The+/// per-table variant above is intentionally kept for table metadata panels;+/// destructive database-wide operations use this bounded variant instead.+pub async fn list_foreign_keys_for_database(+ pool: &MySqlPool,+ database: &str,+) -> Result<HashMap<String, Vec<ForeignKeyInfo>>, String> {+ let column_sql = format!(+ "SELECT TABLE_NAME, CONSTRAINT_NAME, COLUMN_NAME, REFERENCED_TABLE_SCHEMA, \+ REFERENCED_TABLE_NAME, REFERENCED_COLUMN_NAME \+ FROM information_schema.KEY_COLUMN_USAGE \+ WHERE TABLE_SCHEMA = {} AND REFERENCED_TABLE_NAME IS NOT NULL \+ ORDER BY TABLE_NAME, CONSTRAINT_NAME, ORDINAL_POSITION",+ quote_value(database),+ );+ let mut conn = get_conn_with_timeout(pool, super::connection_timeout()).await?;+ let column_result = conn.query_iter(&column_sql).await.map_err(|e| e.to_string())?;+ let column_rows: Vec<mysql_async::Row> = column_result.collect_and_drop().await.map_err(|e| e.to_string())?;+ if column_rows.is_empty() {+ return Ok(HashMap::new());+ }++ let rule_sql = format!(+ "SELECT TABLE_NAME, CONSTRAINT_NAME, UPDATE_RULE, DELETE_RULE \+ FROM information_schema.REFERENTIAL_CONSTRAINTS \+ WHERE CONSTRAINT_SCHEMA = {}",+ quote_value(database),+ );+ let rule_result = conn.query_iter(&rule_sql).await.map_err(|e| e.to_string())?;+ let rule_rows: Vec<mysql_async::Row> = rule_result.collect_and_drop().await.map_err(|e| e.to_string())?;+ let rules = rule_rows+ .iter()+ .map(|row| {+ (+ (get_str_by_name(row, "TABLE_NAME"), get_str_by_name(row, "CONSTRAINT_NAME")),+ (get_str_by_name(row, "UPDATE_RULE"), get_str_by_name(row, "DELETE_RULE")),+ )+ })+ .collect::<HashMap<_, _>>();++ let mut result: HashMap<String, Vec<ForeignKeyInfo>> = HashMap::new();+ for row in &column_rows {+ let table = get_str_by_name(row, "TABLE_NAME");+ let name = get_str_by_name(row, "CONSTRAINT_NAME");+ let (on_update, on_delete) = rules.get(&(table.clone(), name.clone())).cloned().unwrap_or_default();+ result.entry(table).or_default().push(ForeignKeyInfo {+ name,+ column: get_str_by_name(row, "COLUMN_NAME"),+ ref_schema: Some(get_str_by_name(row, "REFERENCED_TABLE_SCHEMA")),+ ref_table: get_str_by_name(row, "REFERENCED_TABLE_NAME"),+ ref_column: get_str_by_name(row, "REFERENCED_COLUMN_NAME"),+ on_update: Some(on_update).filter(|value| !value.is_empty()),+ on_delete: Some(on_delete).filter(|value| !value.is_empty()),+ });+ }+ Ok(result)+}+pub async fn list_triggers(pool: &MySqlPool, database: &str, table: &str) -> Result<Vec<TriggerInfo>, String> {let sql = format!("SELECT TRIGGER_NAME, EVENT_MANIPULATION, ACTION_TIMING, ACTION_STATEMENT \diff --git a/crates/dbx-tauri-schema/Cargo.toml b/crates/dbx-tauri-schema/Cargo.tomlindex 4a4a58ef58..995936a809 100644--- a/crates/dbx-tauri-schema/Cargo.toml+++ b/crates/dbx-tauri-schema/Cargo.toml@@ -7,3 +7,4 @@ rust-version = "1.88.0"[dependencies]dbx-core = { path = "../dbx-core", default-features = false }tauri = "2.10.3"+tokio = { version = "1", features = ["macros", "rt", "sync"] }diff --git a/crates/dbx-tauri-schema/src/commands.rs b/crates/dbx-tauri-schema/src/commands.rsindex 0328dacf21..661fb3864a 100644--- a/crates/dbx-tauri-schema/src/commands.rs+++ b/crates/dbx-tauri-schema/src/commands.rs@@ -1,9 +1,28 @@+use std::future::Future;use std::sync::Arc;use tauri::State;use dbx_core::connection::AppState;use dbx_core::db;+async fn run_cancellable<T, F>(state: &Arc<AppState>, execution_id: Option<String>, future: F) -> Result<T, String>+where+ F: Future<Output = Result<T, String>>,+{+ let registered =+ execution_id.as_ref().filter(|id| !id.trim().is_empty()).map(|id| state.running_queries.register(id.clone()));+ if let Some(query) = registered.as_ref() {+ let token = query.token();+ tokio::select! {+ biased;+ _ = token.cancelled() => Err(dbx_core::query::canceled_error()),+ result = future => result,+ }+ } else {+ future.await+ }+}+/// Resolve a non-internal catalog for dispatch to the Doris multi-catalog path./// Thin wrapper around the shared dbx-core resolver so the Tauri and HTTP/// backends stay in sync.@@ -230,6 +249,7 @@ pub async fn get_mysql_table_auto_increment(}#[tauri::command]+#[allow(clippy::too_many_arguments)]pub async fn list_objects(state: State<'_, Arc<AppState>>,connection_id: String,@@ -241,51 +261,57 @@ pub async fn list_objects(object_types: Option<Vec<String>>,catalog: Option<String>,table_name_filter: Option<dbx_core::schema::TableNameFilter>,+ execution_id: Option<String>,) -> Result<Vec<db::ObjectInfo>, String> {- if let Some(catalog) = external_doris_catalog(&state, &connection_id, catalog.as_deref()).await {- let tables = dbx_core::schema::list_doris_catalog_tables_core(- &state,+ let app = Arc::clone(state.inner());+ let operation_app = Arc::clone(&app);+ run_cancellable(&app, execution_id, async move {+ if let Some(catalog) = external_doris_catalog(&operation_app, &connection_id, catalog.as_deref()).await {+ let tables = dbx_core::schema::list_doris_catalog_tables_core(+ &operation_app,+ &connection_id,+ &catalog,+ &database,+ filter.as_deref(),+ limit,+ offset,+ object_types.as_deref(),+ table_name_filter.as_ref(),+ )+ .await?;+ return Ok(tables+ .into_iter()+ .map(|table| db::ObjectInfo {+ name: table.name,+ object_type: table.table_type,+ schema: Some(database.clone()),+ valid: None,+ signature: None,+ comment: table.comment,+ created_at: None,+ updated_at: None,+ parent_schema: table.parent_schema,+ parent_name: table.parent_name,+ custom_type_kind: None,+ has_members: None,+ trigger: None,+ xugu_type_members_expandable: None,+ })+ .collect());+ }+ dbx_core::schema::list_objects_core(+ &operation_app,&connection_id,- &catalog,&database,+ &schema,filter.as_deref(),limit,offset,object_types.as_deref(),table_name_filter.as_ref(),)- .await?;- return Ok(tables- .into_iter()- .map(|table| db::ObjectInfo {- name: table.name,- object_type: table.table_type,- schema: Some(database.clone()),- valid: None,- signature: None,- comment: table.comment,- created_at: None,- updated_at: None,- parent_schema: table.parent_schema,- parent_name: table.parent_name,- custom_type_kind: None,- has_members: None,- trigger: None,- xugu_type_members_expandable: None,- })- .collect());- }- dbx_core::schema::list_objects_core(- &state,- &connection_id,- &database,- &schema,- filter.as_deref(),- limit,- offset,- object_types.as_deref(),- table_name_filter.as_ref(),- )+ .await+ }).await}@@ -493,6 +519,26 @@ pub async fn list_foreign_keys(dbx_core::schema::list_foreign_keys_core(&state, &connection_id, &database, &schema, &table).await}+#[tauri::command]+pub async fn list_foreign_keys_for_database(+ state: State<'_, Arc<AppState>>,+ connection_id: String,+ database: String,+ schema: String,+ catalog: Option<String>,+ execution_id: Option<String>,+) -> Result<std::collections::HashMap<String, Vec<db::ForeignKeyInfo>>, String> {+ let app = Arc::clone(state.inner());+ let operation_app = Arc::clone(&app);+ run_cancellable(&app, execution_id, async move {+ if external_doris_catalog(&operation_app, &connection_id, catalog.as_deref()).await.is_some() {+ return Ok(std::collections::HashMap::new());+ }+ dbx_core::schema::list_foreign_keys_for_database_core(&operation_app, &connection_id, &database, &schema).await+ })+ .await+}+#[tauri::command]pub async fn list_triggers(state: State<'_, Arc<AppState>>,diff --git a/crates/dbx-tauri-schema/src/lib.rs b/crates/dbx-tauri-schema/src/lib.rsindex 8f23d1c7c8..b6ecef3734 100644--- a/crates/dbx-tauri-schema/src/lib.rs+++ b/crates/dbx-tauri-schema/src/lib.rs@@ -43,6 +43,7 @@ define_registry![list_reference_key_columns,list_reference_keys,list_foreign_keys,+ list_foreign_keys_for_database,list_triggers,list_constraints,list_partitions,@@ -84,7 +85,7 @@ mod tests {#[test]fn handles_only_schema_commands() {- assert_eq!(COMMANDS.len(), 48);+ assert_eq!(COMMANDS.len(), 49);assert!(handles("list_databases"));assert!(handles("list_event_triggers"));assert!(!handles("prepare_schema_diff"));diff --git a/crates/dbx-web/src/main.rs b/crates/dbx-web/src/main.rsindex 9fee84792b..1f34486779 100644--- a/crates/dbx-web/src/main.rs+++ b/crates/dbx-web/src/main.rs@@ -760,6 +760,7 @@ async fn serve() -> Result<(), String> {.route("/schema/reference-key-columns", get(routes::schema::list_reference_key_columns)).route("/schema/reference-keys", get(routes::schema::list_reference_keys)).route("/schema/foreign-keys", get(routes::schema::list_foreign_keys))+ .route("/schema/foreign-keys-for-database", get(routes::schema::list_foreign_keys_for_database)).route("/schema/triggers", get(routes::schema::list_triggers)).route("/schema/constraints", get(routes::schema::list_constraints)).route("/schema/partitions", get(routes::schema::list_partitions))diff --git a/crates/dbx-web/src/routes/schema.rs b/crates/dbx-web/src/routes/schema.rsindex 851f629b8c..8634225a2f 100644--- a/crates/dbx-web/src/routes/schema.rs+++ b/crates/dbx-web/src/routes/schema.rs@@ -29,6 +29,27 @@ pub struct SchemaQuery {pub client_session_id: Option<String>,pub include_postgres_access: Option<bool>,pub portable: Option<bool>,+ pub execution_id: Option<String>,+}++async fn run_cancellable<T, F>(state: &Arc<WebState>, execution_id: Option<String>, future: F) -> Result<T, AppError>+where+ F: Future<Output = Result<T, String>>,+{+ let registered = execution_id+ .as_ref()+ .filter(|id| !id.trim().is_empty())+ .map(|id| state.app.running_queries.register(id.clone()));+ if let Some(query) = registered.as_ref() {+ let token = query.token();+ tokio::select! {+ biased;+ _ = token.cancelled() => Err(AppError::from(dbx_core::query::canceled_error())),+ result = future => result.map_err(AppError::from),+ }+ } else {+ future.await.map_err(AppError::from)+ }}#[derive(Deserialize)]@@ -257,8 +278,12 @@ pub async fn list_objects(State(state): State<Arc<WebState>>,Query(q): Query<SchemaQuery>,) -> Result<Json<serde_json::Value>, AppError> {- let database = q.database.as_deref().unwrap_or("");- let schema = q.schema.as_deref().unwrap_or("");+ let database = q.database.unwrap_or_default();+ let schema = q.schema.unwrap_or_default();+ let connection_id = q.connection_id;+ let filter = q.filter;+ let catalog = q.catalog;+ let execution_id = q.execution_id;let object_types = q.object_types.as_ref().map(|value| {value.split(',').map(str::trim).filter(|value| !value.is_empty()).map(str::to_string).collect::<Vec<_>>()});@@ -266,54 +291,55 @@ pub async fn list_objects(.table_name_filter.as_deref().and_then(|value| serde_json::from_str::<dbx_core::schema::TableNameFilter>(value).ok());- let result = if let Some(catalog) = external_doris_catalog(&state, &q.connection_id, q.catalog.as_deref()).await {- let tables = dbx_core::schema::list_doris_catalog_tables_core(- &state.app,- &q.connection_id,- &catalog,- database,- q.filter.as_deref(),- q.limit,- q.offset,- object_types.as_deref(),- table_name_filter.as_ref(),- )- .await- .map_err(AppError::from)?;- tables- .into_iter()- .map(|table| dbx_core::db::ObjectInfo {- name: table.name,- object_type: table.table_type,- schema: Some(database.to_string()),- valid: None,- signature: None,- custom_type_kind: None,- has_members: None,- comment: table.comment,- created_at: None,- updated_at: None,- parent_schema: table.parent_schema,- parent_name: table.parent_name,- trigger: None,- xugu_type_members_expandable: None,- })- .collect::<Vec<_>>()- } else {- dbx_core::schema::list_objects_core(- &state.app,- &q.connection_id,- database,- schema,- q.filter.as_deref(),- q.limit,- q.offset,- object_types.as_deref(),- table_name_filter.as_ref(),- )- .await- .map_err(AppError::from)?- };+ let result = run_cancellable(&state, execution_id, async {+ if let Some(catalog) = external_doris_catalog(&state, &connection_id, catalog.as_deref()).await {+ let tables = dbx_core::schema::list_doris_catalog_tables_core(+ &state.app,+ &connection_id,+ &catalog,+ &database,+ filter.as_deref(),+ q.limit,+ q.offset,+ object_types.as_deref(),+ table_name_filter.as_ref(),+ )+ .await?;+ Ok(tables+ .into_iter()+ .map(|table| dbx_core::db::ObjectInfo {+ name: table.name,+ object_type: table.table_type,+ schema: Some(database.clone()),+ valid: None,+ signature: None,+ custom_type_kind: None,+ has_members: None,+ comment: table.comment,+ created_at: None,+ updated_at: None,+ parent_schema: table.parent_schema,+ parent_name: table.parent_name,+ trigger: None,+ xugu_type_members_expandable: None,+ })+ .collect::<Vec<_>>())+ } else {+ dbx_core::schema::list_objects_core(+ &state.app,+ &connection_id,+ &database,+ &schema,+ filter.as_deref(),+ q.limit,+ q.offset,+ object_types.as_deref(),+ table_name_filter.as_ref(),+ )+ .await+ }+ })+ .await?;Ok(Json(serde_json::to_value(result).map_err(|e| AppError::from(e.to_string()))?))}@@ -653,6 +679,21 @@ pub async fn list_foreign_keys(Ok(Json(serde_json::to_value(result).map_err(|e| AppError::from(e.to_string()))?))}+pub async fn list_foreign_keys_for_database(+ State(state): State<Arc<WebState>>,+ Query(q): Query<SchemaQuery>,+) -> Result<Json<serde_json::Value>, AppError> {+ let database = q.database.as_deref().unwrap_or("");+ let schema = q.schema.as_deref().unwrap_or("");+ let result = run_cancellable(+ &state,+ q.execution_id,+ dbx_core::schema::list_foreign_keys_for_database_core(&state.app, &q.connection_id, database, schema),+ )+ .await?;+ Ok(Json(serde_json::to_value(result).map_err(|e| AppError::from(e.to_string()))?))+}+pub async fn list_triggers(State(state): State<Arc<WebState>>,Query(q): Query<SchemaQuery>,