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
fix(mysql): run table copies in existing background task list
zipg91cd83355815
diff --git a/apps/desktop/src/App.vue b/apps/desktop/src/App.vueindex 518c0d7836..9871725720 100644--- a/apps/desktop/src/App.vue+++ b/apps/desktop/src/App.vue@@ -26,6 +26,7 @@ import WelcomeScreen from "@/components/layout/WelcomeScreen.vue";import type { ConfigTab } from "@/components/connection/ConnectionDialog.vue";import { useConnectionStore } from "@/stores/connectionStore";import { useQueryStore } from "@/stores/queryStore";+import { useTableCopyTaskStore } from "@/stores/tableCopyTaskStore";import { usePlDebugStore } from "@/stores/plDebugStore";import { dispatchPlDebugStepShortcut } from "@/lib/editor/plDebugStepShortcut";import { useNavigationStore } from "@/stores/navigationStore";@@ -248,6 +249,7 @@ const DriverStorePage = defineAsyncComponent(() => import("@/components/config/Dconst PluginCenterPage = defineAsyncComponent(() => import("@/components/plugins/PluginContributionsPanel.vue"));const PluginBottomDock = defineAsyncComponent(() => import("@/components/plugins/PluginBottomDock.vue"));const EditorSettingsPage = defineAsyncComponent(() => import("@/components/editor/EditorSettingsDialog.vue"));+const TableCopyProgressDialog = defineAsyncComponent(() => import("@/components/objects/TableCopyProgressDialog.vue"));const UpdateDialog = defineAsyncComponent(() => import("@/components/layout/UpdateDialog.vue"));const CloseActionPromptDialog = defineAsyncComponent(() => import("@/components/layout/CloseActionPromptDialog.vue"));const AiRunsClosePromptDialog = defineAsyncComponent(() => import("@/components/layout/AiRunsClosePromptDialog.vue"));@@ -324,6 +326,7 @@ connectionStore.setBeforeConnectHandler(async (config) => {const { message: toastMessage, visible: toastVisible, action: toastAction, toast } = useToast();const { isDark, themeMode, applyTheme, setThemeMode, writeRootToken } = useTheme();const { activeCount: activeBackgroundTaskCount, tasks: backgroundTasks, cancelTask: cancelBackgroundTask } = useExportTracker();+const tableCopyTasks = useTableCopyTaskStore();const trackedUpdateTaskCount = computed(() => countActiveUpdateBlockingTasks(activeBackgroundTaskCount.value, queryStore.tabs));const {initialize: initializeUpdater,@@ -2491,7 +2494,7 @@ function confirmQuitWithActiveBackgroundTasks() {showBackgroundTasksClosePrompt.value = false;backgroundTasksQuitConfirmed = true;for (const task of backgroundTasks.value) {- if (task.status === "Running" || task.status === "Writing") void cancelBackgroundTask(task.exportId);+ if (task.status === "Running" || task.status === "Writing" || (task.kind === "table-copy" && task.canCancel)) void cancelBackgroundTask(task.exportId);}void finishPendingAppClose(action);}@@ -5930,6 +5933,7 @@ onUnmounted(() => {@open-database-search-target="openDatabaseSearchTarget"@open-diagram-target="openDiagramTarget"/>+ <TableCopyProgressDialog v-if="tableCopyTasks.open" /><MultiDbExecuteDialogv-model:open="showMultiDbExecuteDialog":sql="multiExecuteSql"diff --git a/apps/desktop/src/components/export/ExportProgressPopover.vue b/apps/desktop/src/components/export/ExportProgressPopover.vueindex 081f5f71ea..7dd1c5f505 100644--- a/apps/desktop/src/components/export/ExportProgressPopover.vue+++ b/apps/desktop/src/components/export/ExportProgressPopover.vue@@ -98,6 +98,7 @@ const taskFileName = (task: ExportTask) => {};const taskTitle = (task: ExportTask) => {+ if (task.kind === "table-copy") return `${t("tableCopyTask.title")}: ${task.tableName}`;if (task.kind === "data-dictionary") return `${t("dataDictionary.title")}: ${task.tableName}`;// database-export and sql-file keep their task labels on purpose: the former// names the database (filePath may be a directory), the latter already names@@ -131,6 +132,9 @@ const comparePhaseText = (phase?: string) => {};const rowsText = (task: ExportTask) => {+ if (task.kind === "table-copy") {+ return [t(`tableCopyTask.${task.copyPhase ?? "preparing"}`), task.affectedRows === undefined ? "" : t("tableCopyTask.copiedRows", { count: task.affectedRows })].filter(Boolean).join(" · ");+ }if (task.kind === "data-dictionary") {if (task.status === "Done") return [t("exportProgress.done"), task.dictionaryWarnings ? t("dataDictionary.warningCount", { count: task.dictionaryWarnings }) : ""].filter(Boolean).join(" · ");if (task.status === "Error") return t("exportProgress.error");@@ -243,6 +247,7 @@ const databaseObjectText = (task: ExportTask) => {const statusIcon = (task: ExportTask) => {if (isActive(task.status)) {+ if (task.kind === "table-copy") return Copy;if (task.kind === "database-export") return DatabaseBackup;if (task.kind === "data-dictionary") return FileDown;if (task.kind === "sql-file") return FileCode2;@@ -472,7 +477,7 @@ function openTask(task: ExportTask): void {<Loader2 v-if="task.status === 'Cancelling'" class="h-3.5 w-3.5 animate-spin text-primary" /><X v-else class="h-3.5 w-3.5 text-muted-foreground hover:text-destructive" /></button>- <button v-else-if="isFinished(task.status) || task.status === 'Unknown'" class="flex h-6 w-6 items-center justify-center rounded hover:bg-muted" :title="t('exportProgress.delete')" @click="removeTask(task.exportId)">+ <button v-else-if="task.canRemove !== false && (isFinished(task.status) || task.status === 'Unknown')" class="flex h-6 w-6 items-center justify-center rounded hover:bg-muted" :title="t('exportProgress.delete')" @click="removeTask(task.exportId)"><X class="h-3.5 w-3.5 text-muted-foreground hover:text-foreground" /></button></div>diff --git a/apps/desktop/src/components/export/__tests__/ExportProgressPopover.spec.ts b/apps/desktop/src/components/export/__tests__/ExportProgressPopover.spec.tsindex d9d16a79fe..1188e4082c 100644--- a/apps/desktop/src/components/export/__tests__/ExportProgressPopover.spec.ts+++ b/apps/desktop/src/components/export/__tests__/ExportProgressPopover.spec.ts@@ -84,6 +84,40 @@ async function mountPopover() {await nextTick();}+describe("table copy background task", () => {+ it("shares phase, elapsed time, details and cancellation without claiming a row percentage", async () => {+ const tracker = useExportTracker();+ const onOpen = vi.fn();+ const cancel = vi.fn();+ const task = tracker.addTableCopyTask("copy-task", "orders_copy", onOpen);+ task.copyPhase = "data";+ tracker.registerTaskCancelHandler(task.exportId, cancel);+ await mountPopover();+ expect(document.body.textContent).toContain("Table copy: orders_copy");+ expect(document.body.textContent).toContain("Copying data");+ expect(document.body.textContent).toContain("Elapsed:");+ expect(document.body.textContent).not.toContain("0 rows");+ expect(document.body.textContent).not.toContain("0%");+ (document.querySelector('button[title="Open task"]') as HTMLButtonElement).click();+ expect(onOpen).toHaveBeenCalledOnce();+ (document.querySelector('button[title="Cancel"]') as HTMLButtonElement).click();+ await nextTick();+ expect(cancel).toHaveBeenCalledOnce();+ task.status = "Unknown";+ await nextTick();+ expect(document.querySelector('button[title="Delete"]')).toBeNull();+ tracker.removeTask(task.exportId);+ expect(tracker.tasks.value).toContain(task);+ task.status = "Done";+ task.copyPhase = "succeeded";+ task.canRemove = true;+ task.canCancel = false;+ task.affectedRows = 1000;+ await nextTick();+ expect(document.body.textContent).toContain("Database-confirmed copied rows: 1000");+ });+});+describe("failure detail copy text", () => {it("formats a data-transfer failure from its authoritative fields", () => {expect(dataTransferFailureCopyText({ table: "users", error: "permission denied" })).toBe("users\npermission denied");diff --git a/apps/desktop/src/components/objects/ObjectBrowser.vue b/apps/desktop/src/components/objects/ObjectBrowser.vueindex a29d561f26..db698d49e6 100644--- a/apps/desktop/src/components/objects/ObjectBrowser.vue+++ b/apps/desktop/src/components/objects/ObjectBrowser.vue@@ -1,4 +1,5 @@<script setup lang="ts">+import { useTableCopyTaskStore } from "@/stores/tableCopyTaskStore";import { uuid } from "@/lib/common/utils";import { OBJECT_BROWSER_COMPACT_WIDTHS, normalizeObjectBrowserCompactWidth, type ObjectBrowserCompactWidth } from "@/lib/table/objectBrowserCompactWidth";import { applyDdlTextPreferences } from "@/lib/sql/ddlPreferences";@@ -4390,6 +4391,18 @@ async function confirmPasteTableImpl() {const mode = pasteTableMode.value;const copyData = pasteTableModeCopiesData(mode) && pasteTableDataCopySupported.value;showPasteDialog.value = false;+ if (context.databaseType === "mysql") {+ const copies = entries.map((entry) => ({ ...entry, connection: context.connection, database: context.database, catalog: context.catalog, schema: entry.schema || context.schema, identifierQuote: context.identifierQuote }));+ const completed = await useTableCopyTaskStore().run(copies, mode);+ if (completed && shouldConsumeTableClipboard && connectionStore.treeClipboard === clipboardAtPasteStart) connectionStore.treeClipboard = null;+ try {+ await reloadTableCopyContext(context);+ } catch (error) {+ const task = useTableCopyTaskStore().task;+ if (task) task.refreshError = error instanceof Error ? error.message : String(error);+ }+ return;+ }let successCount = 0;let pasteFailCount = 0;let firstPasteError: unknown;diff --git a/apps/desktop/src/components/objects/TableCopyProgressDialog.vue b/apps/desktop/src/components/objects/TableCopyProgressDialog.vuenew file mode 100644index 0000000000..93939f00f9--- /dev/null+++ b/apps/desktop/src/components/objects/TableCopyProgressDialog.vue@@ -0,0 +1,65 @@+<script setup lang="ts">+import { computed, onUnmounted, ref } from "vue";+import { useI18n } from "vue-i18n";+import { Loader2 } from "@lucide/vue";+import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog";+import { Button } from "@/components/ui/button";+import { useTableCopyTaskStore } from "@/stores/tableCopyTaskStore";++const store = useTableCopyTaskStore();+const task = computed(() => store.displayedTask);+const isCurrent = computed(() => task.value === store.task);+const { t } = useI18n();+const now = ref(Date.now());+const timer = setInterval(() => {+ now.value = Date.now();+}, 1000);+onUnmounted(() => clearInterval(timer));+const elapsed = computed(() => Math.max(0, Math.floor(((task.value?.finishedAt ?? now.value) - (task.value?.startedAt ?? now.value)) / 1000)));+const working = computed(() => isCurrent.value && store.busy && task.value?.status !== "unknown");+</script>++<template>+ <Dialog+ :open="store.open"+ @update:open="+ (value) => {+ if (!value) store.close();+ }+ "+ >+ <DialogContent class="sm:max-w-[520px]">+ <DialogHeader>+ <DialogTitle>{{ t("tableCopyTask.title") }}</DialogTitle>+ </DialogHeader>+ <template v-if="task">+ <div class="flex items-center gap-2" role="status" aria-live="polite">+ <Loader2 v-if="working" class="size-4 shrink-0 animate-spin" />+ <span>{{ t(`tableCopyTask.${working ? (task.status === "cancelling" ? "cancelling" : task.phase) : task.status}`) }}</span>+ </div>+ <p class="text-xs text-muted-foreground">{{ t("tableCopyTask.elapsed", { seconds: elapsed }) }}</p>+ <p v-if="working && task.phase === 'data'" class="text-xs text-muted-foreground">{{ t("tableCopyTask.visibility") }}</p>+ <div class="max-h-60 space-y-2 overflow-y-auto rounded border p-3 text-sm">+ <div v-for="(target, index) in task.targets" :key="index" class="space-y-1">+ <div class="flex justify-between gap-3">+ <span class="break-all">{{ target.name }}</span>+ <span class="shrink-0 text-muted-foreground">{{ t(`tableCopyTask.${target.status}`) }}</span>+ </div>+ <p v-if="target.structureCreated" class="text-xs text-muted-foreground">{{ t("tableCopyTask.structureCreated") }}</p>+ <p v-if="target.copiedRows !== undefined" class="text-xs text-muted-foreground">{{ t("tableCopyTask.copiedRows", { count: target.copiedRows }) }}</p>+ <p v-if="target.error" class="break-words text-xs text-destructive">{{ target.error }}</p>+ </div>+ </div>+ <p v-if="task.status === 'unknown'" class="text-sm text-destructive">{{ t("tableCopyTask.unknownHint") }}</p>+ <p v-if="['failed', 'cancelled', 'unknown'].includes(task.status)" class="text-xs text-muted-foreground">{{ t("tableCopyTask.retained") }}</p>+ <p v-if="task.refreshError" class="break-words text-sm text-destructive">{{ t("tableCopyTask.refreshFailed", { message: task.refreshError }) }}</p>+ <p v-if="task.cancelError" class="break-words text-sm text-destructive">{{ t("tableCopyTask.cancelFailed", { message: task.cancelError }) }}</p>+ <DialogFooter>+ <Button v-if="isCurrent && task.status === 'unknown' && store.busy" variant="outline" :disabled="store.cancelSending" @click="store.checkCompletion()">{{ t("tableCopyTask.checkCompletion") }}</Button>+ <Button v-if="isCurrent && store.busy && task.phase !== 'refreshing'" variant="outline" :disabled="store.cancelSending" @click="store.cancel()">{{ t(task.status === "cancelling" ? "tableCopyTask.retryCancel" : "tableCopyTask.cancel") }}</Button>+ <Button @click="store.close()">{{ t(working ? "tableCopyTask.hide" : "tableCopyTask.close") }}</Button>+ </DialogFooter>+ </template>+ </DialogContent>+ </Dialog>+</template>diff --git a/apps/desktop/src/components/objects/__tests__/OceanbaseClone.entrypoints.spec.ts b/apps/desktop/src/components/objects/__tests__/OceanbaseClone.entrypoints.spec.tsindex e85438a33f..491f23c5ff 100644--- a/apps/desktop/src/components/objects/__tests__/OceanbaseClone.entrypoints.spec.ts+++ b/apps/desktop/src/components/objects/__tests__/OceanbaseClone.entrypoints.spec.ts@@ -6,13 +6,15 @@ import i18n, { loadLocaleMessages } from "@/i18n";import SidebarTreeRuntimeHost from "@/components/sidebar/SidebarTreeRuntimeHost.vue";import ObjectBrowser from "@/components/objects/ObjectBrowser.vue";import { useConnectionStore } from "@/stores/connectionStore";+import { useQueryStore } from "@/stores/queryStore";+import { useTableCopyTaskStore } from "@/stores/tableCopyTaskStore";import { useProductionSafetyStore } from "@/stores/productionSafetyStore";import { invalidateObjectBrowserRowsCache } from "@/lib/table/objectBrowserRowsCache";import type { ConnectionConfig, TreeNode } from "@/types/database";import * as api from "@/lib/backend/api";import { OraclePackageSaveAsFailure, type OraclePackageSaveAsPlan } from "@/lib/table/oraclePackageSaveAs";-const backend = vi.hoisted(() => ({ executeQuery: vi.fn(), buildCreateTableSql: vi.fn(), buildCopyTableDataSql: vi.fn() }));+const backend = vi.hoisted(() => ({ executeQuery: vi.fn(), executeConditionalUpdate: vi.fn(), buildDuplicateTableStructureSql: vi.fn(), buildCreateTableSql: vi.fn(), buildCopyTableDataSql: vi.fn() }));const packageSaveAs = vi.hoisted(() => ({ prepare: vi.fn(), prepareExecution: vi.fn(), execute: vi.fn(), dispose: vi.fn() }));vi.mock("@/lib/backend/api", async (importOriginal) => ({...(await importOriginal<typeof import("@/lib/backend/api")>()),@@ -625,3 +627,39 @@ describe.each(["sidebar", "objects"] as const)("%s Oracle package Save As failurexpect(controller.packageSaveAsError).toBe("");});});++describe.each(["sidebar", "objects"] as const)("%s MySQL copy task entry point", (surface) => {+ it("uses the owned copy task for clone and paste, blocks reentry, and refreshes the target data tab", async () => {+ const { controller, context } = await mountEntry(surface);+ const mysql = { ...connection, db_type: "mysql", driver_profile: "mysql" } as ConnectionConfig;+ useConnectionStore().connections = [mysql];+ context.value = { connection: mysql, database: "APP", schema: "APP" };+ controller.pasteTableEntries = [{ sourceName: "SOURCE", targetName: "mysql_copy", connectionId: connection.id, database: "APP", schema: "APP" }];+ backend.buildDuplicateTableStructureSql.mockResolvedValue("CREATE TABLE `mysql_copy` LIKE `SOURCE`;");+ backend.buildCopyTableDataSql.mockResolvedValue("INSERT INTO `mysql_copy` (`ID`) SELECT `ID` FROM `SOURCE`;");+ let finish!: () => void;+ const copying = new Promise<void>((resolve) => {+ finish = resolve;+ });+ backend.executeConditionalUpdate.mockImplementation(async (_id, _db, sql: string) => {+ if (sql.startsWith("INSERT")) await copying;+ return { ...result(), affected_rows: sql.startsWith("INSERT") ? 7000001 : 0 };+ });+ const refreshData = vi.spyOn(useQueryStore(), "refreshDataTabsForTable").mockResolvedValue(1);+ await nextTick();+ const pending = controller.confirmPasteTable();+ await vi.waitFor(() => expect(backend.executeConditionalUpdate).toHaveBeenCalledTimes(2));+ const task = useTableCopyTaskStore();+ expect(task.open).toBe(false);+ expect(task.task?.phase).toBe("data");+ expect(controller.showPasteDialog).toBe(false);+ expect(refreshData).not.toHaveBeenCalled();+ await controller.confirmPasteTable();+ expect(backend.executeConditionalUpdate).toHaveBeenCalledTimes(2);+ finish();+ await pending;+ expect(task.task?.status).toBe("succeeded");+ expect(task.task?.targets[0]?.copiedRows).toBe(7000001);+ expect(refreshData).toHaveBeenCalledWith(expect.objectContaining({ connectionId: connection.id, database: "APP", name: "mysql_copy" }));+ });+});diff --git a/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue b/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vueindex 5aa0214e26..45a951ff38 100644--- a/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue+++ b/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue@@ -1,4 +1,5 @@<script setup lang="ts">+import { useTableCopyTaskStore } from "@/stores/tableCopyTaskStore";import { uuid } from "@/lib/common/utils";import { computed, defineAsyncComponent, nextTick, watch, onBeforeUnmount, onScopeDispose, inject, reactive, ref, shallowRef } from "vue";import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog";@@ -5990,6 +5991,12 @@ async function confirmPasteTableImpl() {const mode = pasteTableMode.value;const copyData = pasteTableModeCopiesData(mode) && pasteTableDataCopySupported.value;showPasteDialog.value = false;+ if (entries.every((entry) => entry.databaseType === "mysql")) {+ const copies = entries.map((entry) => ({ ...entry, connection: { ...connectionStore.getConfig(entry.connectionId)! } }));+ const completed = await useTableCopyTaskStore().run(copies, mode);+ if (completed && shouldConsumeTableClipboard && connectionStore.treeClipboard === clipboardAtPasteStart) connectionStore.treeClipboard = null;+ return;+ }let successCount = 0;let pasteFailCount = 0;let firstPasteError: unknown;diff --git a/apps/desktop/src/composables/useExportTracker.ts b/apps/desktop/src/composables/useExportTracker.tsindex 94bbe2d84d..f828761d75 100644--- a/apps/desktop/src/composables/useExportTracker.ts+++ b/apps/desktop/src/composables/useExportTracker.ts@@ -7,7 +7,7 @@ import { autoRevealExportedPathIfConfigured } from "@/lib/export/exportPath";import { releaseManualExport, submitManualExport, type ManualExportMode } from "@/lib/export/manualExportQueue";import { acceptOraclePackageTransferApproval, acceptOraclePackageTransferPreflight, acceptOracleRoutineDeploymentOperation, type OracleRoutineDeployment } from "@/lib/schema/oracleRoutineDeploy";-export type BackgroundTaskKind = "table-export" | "database-export" | "data-dictionary" | "sql-file" | "data-transfer" | "data-generation" | "multi-db-execution" | "schema-diff" | "data-compare";+export type BackgroundTaskKind = "table-export" | "table-copy" | "database-export" | "data-dictionary" | "sql-file" | "data-transfer" | "data-generation" | "multi-db-execution" | "schema-diff" | "data-compare";export type BackgroundTaskStatus = "Queued" | "Unknown" | "PreparingSnapshot" | "Running" | "Writing" | "Cancelling" | "Done" | "Error" | "Cancelled";export type DatabaseExportSource = "manual" | "scheduled";@@ -102,6 +102,8 @@ export interface ExportTask {dictionaryWarnings?: number;dictionaryProgressKnown?: boolean;canCancel?: boolean;+ canRemove?: boolean;+ copyPhase?: "preparing" | "structure" | "data" | "refreshing" | "cancelling" | "succeeded" | "failed" | "cancelled" | "unknown";onOpen?: () => void;onRemove?: () => void;}@@ -501,6 +503,26 @@ export function useExportTracker() {return task;}+ function addTableCopyTask(id: string, label: string, onOpen: () => void): ExportTask {+ const task = reactive<ExportTask>({+ exportId: id,+ kind: "table-copy",+ tableName: label,+ format: "",+ filePath: "",+ rowsExported: 0,+ totalRows: null,+ status: "Running",+ errorMessage: null,+ canCancel: true,+ canRemove: false,+ onOpen,+ startedAt: Date.now(),+ });+ taskMap.set(id, task);+ return task;+ }+function addDatabaseExportTask(exportId: string, label: string, filePath: string, databaseExportSource: DatabaseExportSource = "manual"): ExportTask {const task = reactive<ExportTask>({exportId,@@ -932,6 +954,7 @@ export function useExportTracker() {function removeTask(exportId: string) {const task = taskMap.get(exportId);+ if (task?.canRemove === false) return;if (task?.status === "Unknown") releaseManualExport(exportId);if (task && (task.status === "Done" || task.status === "Error" || task.status === "Cancelled")) cleanupFinishedTask(task);taskMap.delete(exportId);@@ -942,7 +965,7 @@ export function useExportTracker() {function clearFinished() {for (const [id, task] of taskMap) {- if (task.status === "Done" || task.status === "Error" || task.status === "Cancelled") {+ if (task.canRemove !== false && (task.status === "Done" || task.status === "Error" || task.status === "Cancelled")) {cleanupFinishedTask(task);taskMap.delete(id);taskCancelHandlers.delete(id);@@ -989,6 +1012,7 @@ export function useExportTracker() {hasActive,submitExportTask,addTask,+ addTableCopyTask,addDatabaseExportTask,addDataDictionaryTask,updateDataDictionaryTask,diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.tsindex 63dc1ff03f..13d5e439ea 100644--- a/apps/desktop/src/i18n/locales/en.ts+++ b/apps/desktop/src/i18n/locales/en.ts@@ -1,3 +1,4 @@+import { tableCopyTaskEn as tableCopyTask } from "./tableCopyTask";import { tableColumnPasteEn as tableColumnPaste } from "./tableColumnPaste";import { sidebarMenuEn as sidebarMenu } from "./sidebarMenuMessages";import { oceanbaseCloneDialogEn as oceanbaseCloneDialog } from "./oceanbaseCloneDialog";@@ -414,6 +415,7 @@ export default {},oceanbaseCloneDialog,+ tableCopyTask,oracleForeignKey: {resultTitle: "Foreign key operation result",executionFailed: "The foreign key operation did not complete cleanly. Check each statement and the database state.",diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.tsindex a2035b6558..b9eb6bf196 100644--- a/apps/desktop/src/i18n/locales/es.ts+++ b/apps/desktop/src/i18n/locales/es.ts@@ -13794,4 +13794,34 @@ export default withEnglishFallback({noEligibleColumns: "No hay columnas compatibles",bucketCountHint: "La base de datos determina automáticamente el número de buckets según los recursos del clúster y el volumen de datos; no es fijo. Introduzca un número para fijarlo por partición.",},+ tableCopyTask: {+ backgroundFinished: "Copia de tabla: {status}. Puedes ver los detalles en «Tareas en segundo plano».",+ backgroundStarted: "La copia ha comenzado; puedes consultar el progreso en «Tareas en segundo plano» en la parte superior.",+ cancel: "Cancelar copia",+ cancelFailed: "No se puede confirmar el resultado de la cancelación: {message}",+ cancelled: "Cancelado",+ cancelling: "Deteniendo la ejecución; la limpieza de la base de datos puede tardar un poco…",+ checkCompletion: "Comprobar estado de ejecución",+ close: "Cerrar",+ copiedRows: "La base de datos confirma que se han copiado {count} filas",+ data: "Copiando datos…",+ details: "Ver detalles",+ elapsed: "Tiempo transcurrido: {seconds} segundos",+ failed: "Fallido",+ hide: "Ocultar en segundo plano",+ pending: "Sin ejecutar",+ preparing: "Preparando la copia…",+ refreshFailed: "El resultado de la copia no cambia, pero la actualización falló: {message}",+ refreshing: "Actualizando la tabla de destino…",+ retained: "Las tablas creadas y las copias completadas se conservarán. Verifica los datos de destino antes de reintentar.",+ retryCancel: "Reintentar cancelación",+ running: "En ejecución",+ structure: "Creando la tabla de destino…",+ structureCreated: "Se ha creado la estructura de la tabla de destino",+ succeeded: "Completado",+ title: "Copiar tabla",+ unknown: "El resultado de la ejecución aún no se ha confirmado",+ unknownHint: "Es posible que la solicitud original siga ejecutándose o que ya se haya confirmado. Comprueba el estado de la ejecución original y los datos de destino; no repitas la copia por ahora.",+ visibility: "Antes de confirmar en la base de datos, los datos copiados pueden no ser visibles temporalmente. Esta operación no puede proporcionar un porcentaje exacto de filas.",+ },});diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.tsindex 3c405e5e00..c75fb2d00d 100644--- a/apps/desktop/src/i18n/locales/it.ts+++ b/apps/desktop/src/i18n/locales/it.ts@@ -13335,4 +13335,34 @@ export default withEnglishFallback({noEligibleColumns: "Nessuna colonna supportata",bucketCountHint: "Il database determina automaticamente il numero di bucket in base alle risorse del cluster e al volume dei dati; non è fisso. Inserire un numero per fissarlo per ogni partizione.",},+ tableCopyTask: {+ backgroundFinished: "Copia tabella: {status}. Puoi visualizzare i dettagli in «Attività in background».",+ backgroundStarted: "Copia avviata. Puoi controllare l'avanzamento in «Attività in background» nella parte superiore.",+ cancel: "Annulla copia",+ cancelFailed: "Impossibile confermare l'esito dell'annullamento: {message}",+ cancelled: "Annullato",+ cancelling: "Interruzione dell'esecuzione in corso; la pulizia del database potrebbe richiedere del tempo…",+ checkCompletion: "Controlla stato esecuzione",+ close: "Chiudi",+ copiedRows: "Il database conferma che sono state copiate {count} righe",+ data: "Copia dei dati…",+ details: "Visualizza dettagli",+ elapsed: "Tempo trascorso: {seconds} secondi",+ failed: "Non riuscito",+ hide: "Riduci in background",+ pending: "Non eseguito",+ preparing: "Preparazione della copia…",+ refreshFailed: "Il risultato della copia è invariato, ma l'aggiornamento non è riuscito: {message}",+ refreshing: "Aggiornamento della tabella di destinazione…",+ retained: "Le tabelle create e le copie completate verranno mantenute. Prima di riprovare, verifica i dati di destinazione.",+ retryCancel: "Riprova annullamento",+ running: "In esecuzione",+ structure: "Creazione della tabella di destinazione…",+ structureCreated: "Struttura della tabella di destinazione creata",+ succeeded: "Completato",+ title: "Copia tabella",+ unknown: "Risultato dell'esecuzione non ancora confermato",+ unknownHint: "La richiesta originale potrebbe essere ancora in esecuzione oppure potrebbe essere già stata inviata. Controlla lo stato dell'esecuzione originale e i dati di destinazione; per ora non ripetere la copia.",+ visibility: "Prima del commit del database, i dati copiati potrebbero non essere temporaneamente visibili. Questa operazione non può fornire una percentuale accurata delle righe.",+ },});diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.tsindex eda5bce648..6ebcb9d9d0 100644--- a/apps/desktop/src/i18n/locales/ja.ts+++ b/apps/desktop/src/i18n/locales/ja.ts@@ -13372,4 +13372,34 @@ export default withEnglishFallback({noEligibleColumns: "対応する列がありません",bucketCountHint: "自動バケット数は、クラスターのリソースとデータ量に応じてデータベースが決定し、固定ではありません。数値を入力すると各パーティションに指定の数を使用します。",},+ tableCopyTask: {+ backgroundFinished: "テーブルのコピー:{status}。「バックグラウンドタスク」で詳細を確認できます。",+ backgroundStarted: "コピーを開始しました。上部の「バックグラウンドタスク」で進行状況を確認できます。",+ cancel: "コピーをキャンセル",+ cancelFailed: "キャンセル結果を確認できません:{message}",+ cancelled: "キャンセル済み",+ cancelling: "実行を停止しています。データベースのクリーンアップにはしばらく時間がかかる場合があります…",+ checkCompletion: "実行状態を確認",+ close: "閉じる",+ copiedRows: "データベースが {count} 行のコピーを確認しました",+ data: "データをコピー中…",+ details: "詳細を表示",+ elapsed: "経過時間 {seconds} 秒",+ failed: "失敗",+ hide: "バックグラウンドに折りたたむ",+ pending: "未実行",+ preparing: "コピーの準備中…",+ refreshFailed: "コピー結果は変わりませんが、更新に失敗しました:{message}",+ refreshing: "ターゲットテーブルを更新中…",+ retained: "作成済みのテーブルおよび完了したコピーは保持されます。再試行する前にターゲットデータを確認してください。",+ retryCancel: "キャンセルを再試行",+ running: "実行中",+ structure: "ターゲットテーブルを作成中…",+ structureCreated: "ターゲットテーブルの構造を作成しました",+ succeeded: "完了",+ title: "テーブルをコピー",+ unknown: "実行結果はまだ確認されていません",+ unknownHint: "元のリクエストはまだ実行中か、すでにコミットされている可能性があります。元の実行状態とターゲットデータを確認し、当面は重複してコピーしないでください。",+ visibility: "データベースがコミットされるまで、コピー済みのデータは一時的に表示されない場合があります。現在の操作では正確な行数の割合を提供できません。",+ },});diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.tsindex 4d9e037e65..9b9bfdc967 100644--- a/apps/desktop/src/i18n/locales/ko.ts+++ b/apps/desktop/src/i18n/locales/ko.ts@@ -12829,4 +12829,34 @@ export default withEnglishFallback({noEligibleColumns: "지원되는 열 없음",bucketCountHint: "자동 버킷 수는 클러스터 리소스와 데이터 양에 따라 데이터베이스가 결정하며 고정되지 않습니다. 숫자를 입력하면 각 파티션에 지정된 버킷 수를 사용합니다.",},+ tableCopyTask: {+ backgroundFinished: "테이블 복사: {status}. '백그라운드 작업'에서 세부 정보를 확인할 수 있습니다.",+ backgroundStarted: "복사가 시작되었습니다. 상단의 '백그라운드 작업'에서 진행 상황을 확인할 수 있습니다.",+ cancel: "복사 취소",+ cancelFailed: "취소 결과를 확인할 수 없습니다: {message}",+ cancelled: "취소됨",+ cancelling: "실행을 중지하는 중입니다. 데이터베이스 정리에 시간이 걸릴 수 있습니다…",+ checkCompletion: "실행 상태 확인",+ close: "닫기",+ copiedRows: "데이터베이스에서 {count}개 행이 복사되었음을 확인했습니다",+ data: "데이터 복사 중…",+ details: "세부 정보 보기",+ elapsed: "경과 시간 {seconds}초",+ failed: "실패",+ hide: "백그라운드로 최소화",+ pending: "실행되지 않음",+ preparing: "복사 준비 중…",+ refreshFailed: "복사 결과는 변경되지 않았지만 새로 고침에 실패했습니다: {message}",+ refreshing: "대상 테이블 새로 고치는 중…",+ retained: "생성된 테이블과 완료된 복사는 유지됩니다. 재시도 전에 대상 데이터를 확인하세요.",+ retryCancel: "취소 재시도",+ running: "실행 중",+ structure: "대상 테이블 생성 중…",+ structureCreated: "대상 테이블 구조가 생성되었습니다",+ succeeded: "완료됨",+ title: "테이블 복사",+ unknown: "실행 결과가 아직 확인되지 않았습니다",+ unknownHint: "원래 요청이 아직 실행 중이거나 이미 커밋되었을 수 있습니다. 원래 실행 상태와 대상 데이터를 확인하고, 아직 복사를 반복하지 마세요.",+ visibility: "데이터베이스가 커밋되기 전에는 복사된 데이터가 일시적으로 표시되지 않을 수 있습니다. 현재 작업에서는 정확한 행 수 비율을 제공할 수 없습니다.",+ },});diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.tsindex e43134cc61..05ba1dd1d7 100644--- a/apps/desktop/src/i18n/locales/pt-BR.ts+++ b/apps/desktop/src/i18n/locales/pt-BR.ts@@ -13352,4 +13352,34 @@ export default withEnglishFallback({noEligibleColumns: "Nenhuma coluna compatível",bucketCountHint: "O banco de dados determina automaticamente o número de buckets conforme os recursos do cluster e o volume de dados; ele não é fixo. Informe um número para fixá-lo em cada partição.",},+ tableCopyTask: {+ backgroundFinished: "Copiar tabela: {status}. Veja os detalhes em “Tarefas em segundo plano”.",+ backgroundStarted: "A cópia foi iniciada. Você pode acompanhar o progresso em “Tarefas em segundo plano” na parte superior.",+ cancel: "Cancelar cópia",+ cancelFailed: "Não foi possível confirmar o resultado do cancelamento: {message}",+ cancelled: "Cancelado",+ cancelling: "Parando a execução; a limpeza do banco de dados pode levar algum tempo…",+ checkCompletion: "Verificar status da execução",+ close: "Fechar",+ copiedRows: "O banco de dados confirmou {count} linhas copiadas",+ data: "Copiando dados…",+ details: "Ver detalhes",+ elapsed: "Tempo decorrido: {seconds} segundos",+ failed: "Falhou",+ hide: "Recolher para segundo plano",+ pending: "Não executado",+ preparing: "Preparando a cópia…",+ refreshFailed: "O resultado da cópia não foi alterado, mas a atualização falhou: {message}",+ refreshing: "Atualizando tabela de destino…",+ retained: "As tabelas criadas e as cópias concluídas serão mantidas. Verifique os dados de destino antes de tentar novamente.",+ retryCancel: "Tentar cancelar novamente",+ running: "Em execução",+ structure: "Criando tabela de destino…",+ structureCreated: "Estrutura da tabela de destino criada",+ succeeded: "Concluído",+ title: "Copiar tabela",+ unknown: "O resultado da execução ainda não foi confirmado",+ unknownHint: "A solicitação original pode ainda estar em execução ou já ter sido confirmada. Verifique o status da execução original e os dados de destino; não repita a cópia por enquanto.",+ visibility: "Antes do commit no banco de dados, os dados já copiados podem ficar temporariamente invisíveis. Esta operação não consegue fornecer uma porcentagem exata de linhas.",+ },});diff --git a/apps/desktop/src/i18n/locales/ru.ts b/apps/desktop/src/i18n/locales/ru.tsindex 7630272d25..8c4eeb5310 100644--- a/apps/desktop/src/i18n/locales/ru.ts+++ b/apps/desktop/src/i18n/locales/ru.ts@@ -14364,4 +14364,34 @@ export default withEnglishFallback({noEligibleColumns: "Нет поддерживаемых столбцов",bucketCountHint: "Автоматическое число бакетов определяется базой данных по ресурсам кластера и объёму данных и не является фиксированным. Введите число, чтобы задать его для каждой партиции.",},+ tableCopyTask: {+ backgroundFinished: "Копирование таблицы: {status}. Подробности можно посмотреть в разделе «Фоновые задачи».",+ backgroundStarted: "Копирование началось. Прогресс можно посмотреть в разделе «Фоновые задачи» в верхней части.",+ cancel: "Отменить копирование",+ cancelFailed: "Не удалось подтвердить результат отмены: {message}",+ cancelled: "Отменено",+ cancelling: "Остановка выполнения. Очистка базы данных может занять некоторое время…",+ checkCompletion: "Проверить состояние выполнения",+ close: "Закрыть",+ copiedRows: "База данных подтвердила копирование строк: {count}",+ data: "Копирование данных…",+ details: "Подробнее",+ elapsed: "Затрачено {seconds} с",+ failed: "Ошибка",+ hide: "Свернуть в фоновые задачи",+ pending: "Не выполнено",+ preparing: "Подготовка к копированию…",+ refreshFailed: "Результат копирования не изменился, но обновление не удалось: {message}",+ refreshing: "Обновление целевой таблицы…",+ retained: "Созданные таблицы и завершённое копирование сохранятся. Перед повторной попыткой проверьте целевые данные.",+ retryCancel: "Повторить отмену",+ running: "Выполняется",+ structure: "Создание целевой таблицы…",+ structureCreated: "Структура целевой таблицы создана",+ succeeded: "Выполнено",+ title: "Копирование таблицы",+ unknown: "Результат выполнения ещё не подтверждён",+ unknownHint: "Исходный запрос может всё ещё выполняться или уже быть зафиксирован. Проверьте состояние исходного выполнения и целевые данные; пока не повторяйте копирование.",+ visibility: "До фиксации транзакции в базе данных скопированные данные могут быть временно не видны. Для текущей операции невозможно предоставить точный процент строк.",+ },});diff --git a/apps/desktop/src/i18n/locales/tableCopyTask.ts b/apps/desktop/src/i18n/locales/tableCopyTask.tsnew file mode 100644index 0000000000..51dfd47207--- /dev/null+++ b/apps/desktop/src/i18n/locales/tableCopyTask.ts@@ -0,0 +1,93 @@+export const tableCopyTaskEn = {+ backgroundStarted: "Table copy started. Follow its progress in Background Tasks.",+ backgroundFinished: "Table copy: {status}. View details in Background Tasks.",+ details: "View details",+ hide: "Run in background",+ title: "Table copy",+ preparing: "Preparing table copy…",+ structure: "Creating the target table…",+ data: "Copying data…",+ refreshing: "Refreshing the target table…",+ pending: "Not started",+ running: "Running",+ cancelling: "Stopping execution; database cleanup may take time…",+ succeeded: "Completed",+ failed: "Failed",+ cancelled: "Cancelled",+ unknown: "Execution result not confirmed",+ elapsed: "Elapsed: {seconds}s",+ visibility: "Copied rows may not be visible until the database commits. This operation does not provide a reliable row percentage.",+ structureCreated: "Target table structure created",+ copiedRows: "Database-confirmed copied rows: {count}",+ retained: "Created tables and completed copies are retained. Check the target data before trying again.",+ unknownHint: "The request may still be running or may have committed. Check the original execution and target data; do not repeat the copy yet.",+ refreshFailed: "The copy result is unchanged, but refreshing failed: {message}",+ cancelFailed: "Cancellation could not be confirmed: {message}",+ checkCompletion: "Check execution status",+ cancel: "Cancel copy",+ retryCancel: "Retry cancellation",+ close: "Close",+};++export const tableCopyTaskZhCN = {+ backgroundStarted: "复制已开始,可在顶部「后台任务」中查看进度。",+ backgroundFinished: "复制表:{status}。可在「后台任务」中查看详情。",+ details: "查看详情",+ hide: "收起到后台",+ title: "复制表",+ preparing: "正在准备复制…",+ structure: "正在创建目标表…",+ data: "正在复制数据…",+ refreshing: "正在刷新目标表…",+ pending: "未执行",+ running: "执行中",+ cancelling: "正在停止执行,数据库清理可能需要一些时间…",+ succeeded: "已完成",+ failed: "失败",+ cancelled: "已取消",+ unknown: "执行结果尚未确认",+ elapsed: "已耗时 {seconds} 秒",+ visibility: "数据库提交前,已复制的数据可能暂不可见。当前操作无法提供准确的行数百分比。",+ structureCreated: "目标表结构已创建",+ copiedRows: "数据库确认已复制 {count} 行",+ retained: "已创建的表及已完成的复制会保留。重试前请核对目标数据。",+ unknownHint: "原请求可能仍在执行,也可能已提交。请检查原执行状态和目标数据,暂勿重复复制。",+ refreshFailed: "复制结果不变,但刷新失败:{message}",+ cancelFailed: "无法确认取消结果:{message}",+ checkCompletion: "检查执行状态",+ cancel: "取消复制",+ retryCancel: "重试取消",+ close: "关闭",+};++export const tableCopyTaskZhTW = {+ ...tableCopyTaskZhCN,+ backgroundStarted: "複製已開始,可在頂部「背景工作」中查看進度。",+ backgroundFinished: "複製資料表:{status}。可在「背景工作」中查看詳情。",+ details: "查看詳情",+ hide: "收起到背景",+ title: "複製資料表",+ preparing: "正在準備複製…",+ structure: "正在建立目標資料表…",+ data: "正在複製資料…",+ refreshing: "正在重新整理目標資料表…",+ pending: "未執行",+ running: "執行中",+ cancelling: "正在停止執行,資料庫清理可能需要一些時間…",+ succeeded: "已完成",+ failed: "失敗",+ cancelled: "已取消",+ unknown: "執行結果尚未確認",+ elapsed: "已耗時 {seconds} 秒",+ visibility: "資料庫提交前,已複製的資料可能暫不可見。目前操作無法提供準確的列數百分比。",+ structureCreated: "目標資料表結構已建立",+ copiedRows: "資料庫確認已複製 {count} 列",+ retained: "已建立的資料表及已完成的複製會保留。重試前請核對目標資料。",+ unknownHint: "原請求可能仍在執行,也可能已提交。請檢查原執行狀態和目標資料,暫勿重複複製。",+ refreshFailed: "複製結果不變,但重新整理失敗:{message}",+ cancelFailed: "無法確認取消結果:{message}",+ checkCompletion: "檢查執行狀態",+ cancel: "取消複製",+ retryCancel: "重試取消",+ close: "關閉",+};diff --git a/apps/desktop/src/i18n/locales/th.ts b/apps/desktop/src/i18n/locales/th.tsindex 735aa49e3c..e4d55a8cd8 100644--- a/apps/desktop/src/i18n/locales/th.ts+++ b/apps/desktop/src/i18n/locales/th.ts@@ -14624,4 +14624,34 @@ export default withEnglishFallback({read: { available: "โหลดแล้ว", incomplete: "ไม่สมบูรณ์", unavailable: "ไม่มีหรือมองไม่เห็น", unsupported: "ไม่รองรับ" },},docs,+ tableCopyTask: {+ backgroundFinished: "การคัดลอกตาราง: {status} สามารถดูรายละเอียดได้ใน 'งานเบื้องหลัง'",+ backgroundStarted: "เริ่มการคัดลอกแล้ว สามารถดูความคืบหน้าได้ที่ 'งานเบื้องหลัง' ด้านบน",+ cancel: "ยกเลิกการคัดลอก",+ cancelFailed: "ไม่สามารถยืนยันผลการยกเลิกได้: {message}",+ cancelled: "ยกเลิกแล้ว",+ cancelling: "กำลังหยุดการดำเนินการ การล้างข้อมูลในฐานข้อมูลอาจใช้เวลาสักครู่…",+ checkCompletion: "ตรวจสอบสถานะการดำเนินการ",+ close: "ปิด",+ copiedRows: "ฐานข้อมูลยืนยันว่าคัดลอกแล้ว {count} แถว",+ data: "กำลังคัดลอกข้อมูล…",+ details: "ดูรายละเอียด",+ elapsed: "ใช้เวลาแล้ว {seconds} วินาที",+ failed: "ล้มเหลว",+ hide: "ย่อไปยังงานเบื้องหลัง",+ pending: "ยังไม่เริ่มดำเนินการ",+ preparing: "กำลังเตรียมการคัดลอก…",+ refreshFailed: "ผลการคัดลอกไม่เปลี่ยนแปลง แต่การรีเฟรชล้มเหลว: {message}",+ refreshing: "กำลังรีเฟรชตารางปลายทาง…",+ retained: "ตารางที่สร้างแล้วและการคัดลอกที่เสร็จสมบูรณ์จะยังคงอยู่ โปรดตรวจสอบข้อมูลปลายทางก่อนลองใหม่",+ retryCancel: "ลองยกเลิกอีกครั้ง",+ running: "กำลังดำเนินการ",+ structure: "กำลังสร้างตารางปลายทาง…",+ structureCreated: "สร้างโครงสร้างตารางปลายทางแล้ว",+ succeeded: "สำเร็จ",+ title: "คัดลอกตาราง",+ unknown: "ยังไม่ยืนยันผลการดำเนินการ",+ unknownHint: "คำขอเดิมอาจยังดำเนินการอยู่หรืออาจถูกคอมมิตแล้ว โปรดตรวจสอบสถานะการดำเนินการเดิมและข้อมูลปลายทาง และอย่าคัดลอกซ้ำในตอนนี้",+ visibility: "ก่อนที่ฐานข้อมูลจะคอมมิต ข้อมูลที่คัดลอกแล้วอาจยังไม่ปรากฏชั่วคราว การดำเนินการปัจจุบันไม่สามารถแสดงเปอร์เซ็นต์จำนวนแถวที่แม่นยำได้",+ },});diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.tsindex ba36193ecb..b1da91c42c 100644--- a/apps/desktop/src/i18n/locales/zh-CN.ts+++ b/apps/desktop/src/i18n/locales/zh-CN.ts@@ -1,3 +1,4 @@+import { tableCopyTaskZhCN as tableCopyTask } from "./tableCopyTask";import { tableColumnPasteZhCN as tableColumnPaste } from "./tableColumnPaste";import { sidebarMenuZhCN as sidebarMenu } from "./sidebarMenuMessages";import { oceanbaseCloneDialogZhCN as oceanbaseCloneDialog } from "./oceanbaseCloneDialog";@@ -359,6 +360,7 @@ export default withEnglishFallback({},oceanbaseCloneDialog,+ tableCopyTask,oracleForeignKey: {resultTitle: "外键操作结果",executionFailed: "外键操作未完整完成,请核对逐条结果和数据库状态。",diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.tsindex f086cf0942..7f50c105c5 100644--- a/apps/desktop/src/i18n/locales/zh-TW.ts+++ b/apps/desktop/src/i18n/locales/zh-TW.ts@@ -1,3 +1,4 @@+import { tableCopyTaskZhTW as tableCopyTask } from "./tableCopyTask";import { tableColumnPasteZhTW as tableColumnPaste } from "./tableColumnPaste";import { sidebarMenuZhTW as sidebarMenu } from "./sidebarMenuMessages";import { oceanbaseCloneDialogZhTW as oceanbaseCloneDialog } from "./oceanbaseCloneDialog";@@ -342,6 +343,7 @@ export default withEnglishFallback({},oceanbaseCloneDialog,+ tableCopyTask,oracleForeignKey: {resultTitle: "外鍵操作結果",executionFailed: "外鍵操作未完整完成,請核對逐條結果和資料庫狀態。",diff --git a/apps/desktop/src/stores/__tests__/tableCopyTaskStore.spec.ts b/apps/desktop/src/stores/__tests__/tableCopyTaskStore.spec.tsnew file mode 100644index 0000000000..3df5bdae77--- /dev/null+++ b/apps/desktop/src/stores/__tests__/tableCopyTaskStore.spec.ts@@ -0,0 +1,303 @@+// @vitest-environment happy-dom+import { createPinia, getActivePinia, setActivePinia } from "pinia";+import { createApp, h, nextTick, type App } from "vue";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { useTableCopyTaskStore, type MysqlTableCopyEntry } from "@/stores/tableCopyTaskStore";+import { useProductionSafetyStore } from "@/stores/productionSafetyStore";+import TableCopyProgressDialog from "@/components/objects/TableCopyProgressDialog.vue";+import i18n from "@/i18n";+import { BackendErrorException } from "@/lib/backend/errorUtils";+import { useExportTracker } from "@/composables/useExportTracker";++const mocks = vi.hoisted(() => ({+ executeConditionalUpdate: vi.fn(),+ cancelConditionalUpdate: vi.fn(),+ getColumns: vi.fn(),+ buildDuplicateTableStructureSql: vi.fn(),+ buildCopyTableDataSql: vi.fn(),+ ensureConnected: vi.fn(),+ refreshObjectListTreeNode: vi.fn(),+ refreshDataTabsForTable: vi.fn(),+}));+vi.mock("@/lib/backend/api", () => mocks);+vi.mock("@/stores/connectionStore", () => ({ useConnectionStore: () => mocks }));+vi.mock("@/stores/queryStore", () => ({ useQueryStore: () => mocks }));++function deferred<T>() {+ let resolve!: (value: T) => void;+ let reject!: (error: unknown) => void;+ const promise = new Promise<T>((yes, no) => {+ resolve = yes;+ reject = no;+ });+ return { promise, resolve, reject };+}+const result = (rows = 0) => ({ columns: [], rows: [], affected_rows: rows, execution_time_ms: 1 });+const entry = () => ({ connection: { id: "local", name: "Local", db_type: "mysql" }, database: "demo", sourceName: "source", targetName: "copy" }) as MysqlTableCopyEntry;+const sqlFailure = (detail: string) => new BackendErrorException({ version: 1, code: "DBX-JDBC-4001", source: "jdbc-agent", messageKey: "backendErrors.sqlFailed", messageParams: {}, operationOutcome: "unknown", diagnostics: { category: "sql", stage: "execute" }, detail });+let mounted: App | undefined;++beforeEach(() => {+ vi.resetAllMocks();+ const tracker = useExportTracker();+ for (const task of tracker.tasks.value) {+ task.canRemove = true;+ tracker.removeTask(task.exportId);+ }+ setActivePinia(createPinia());+ i18n.global.locale.value = "en";+ mocks.ensureConnected.mockResolvedValue(undefined);+ mocks.refreshObjectListTreeNode.mockResolvedValue(undefined);+ mocks.refreshDataTabsForTable.mockResolvedValue(1);+ mocks.buildDuplicateTableStructureSql.mockResolvedValue("CREATE TABLE `copy` LIKE `source`;");+ mocks.buildCopyTableDataSql.mockResolvedValue("INSERT INTO `copy` (`id`) SELECT `id` FROM `source`;");+ mocks.getColumns.mockResolvedValue([{ name: "id", data_type: "int", extra: "", is_nullable: false }]);+ mocks.executeConditionalUpdate.mockResolvedValue(result(7000001));+ mocks.cancelConditionalUpdate.mockResolvedValue({ requested: true, terminal: false, databaseTerminal: false });+});+afterEach(() => {+ mounted?.unmount();+ mounted = undefined;+ document.body.innerHTML = "";+ vi.useRealTimers();+});++describe("MySQL table copy task", () => {+ it("keeps one running task and refreshes the captured target only after copy completion", async () => {+ const store = useTableCopyTaskStore();+ const data = deferred<ReturnType<typeof result>>();+ mocks.executeConditionalUpdate.mockImplementation(async (_id, _db, sql) => (sql.startsWith("INSERT") ? data.promise : result()));+ const original = entry();+ const pending = store.run([original], "structure-and-data");+ await vi.waitFor(() => expect(store.task?.phase).toBe("data"));+ original.targetName = "different";+ original.connection.id = "other-connection";+ expect(store.task?.targets[0]?.structureCreated).toBe(true);+ expect(store.busy).toBe(true);+ expect(store.open).toBe(false);+ const tracked = useExportTracker().tasks.value[0]!;+ expect(tracked.kind).toBe("table-copy");+ expect(tracked.copyPhase).toBe("data");+ expect(useExportTracker().activeCount.value).toBe(1);+ expect(await store.run([entry()], "structure-and-data")).toBe(false);+ expect(mocks.executeConditionalUpdate).toHaveBeenCalledTimes(2);+ expect(mocks.refreshDataTabsForTable).not.toHaveBeenCalled();+ expect(mocks.executeConditionalUpdate.mock.calls[1]).toEqual(["local", "demo", expect.stringContaining("INSERT"), undefined, expect.any(String), { timeoutSecs: 0, catalog: undefined }]);+ expect(mocks.executeConditionalUpdate.mock.calls[0]?.[4]).not.toBe(mocks.executeConditionalUpdate.mock.calls[1]?.[4]);+ data.resolve(result(7000001));+ expect(await pending).toBe(true);+ expect(store.task?.status).toBe("succeeded");+ expect(store.task?.targets[0]?.copiedRows).toBe(7000001);+ expect(mocks.refreshDataTabsForTable).toHaveBeenCalledWith({ connectionId: "local", database: "demo", schema: undefined, catalog: undefined, name: "copy" });+ expect(store.busy).toBe(false);+ expect(tracked.status).toBe("Done");+ expect(tracked.affectedRows).toBe(7000001);+ expect(useExportTracker().activeCount.value).toBe(0);+ });++ it("keeps the confirmed outcome when cancellation is requested during refresh", async () => {+ const store = useTableCopyTaskStore();+ const refresh = deferred<number>();+ mocks.refreshDataTabsForTable.mockReturnValue(refresh.promise);+ const pending = store.run([entry()], "data-only");+ await vi.waitFor(() => expect(store.task?.phase).toBe("refreshing"));+ expect(store.busy).toBe(true);+ await store.cancel();+ expect(store.task?.status).toBe("succeeded");+ expect(mocks.cancelConditionalUpdate).not.toHaveBeenCalled();+ refresh.resolve(1);+ expect(await pending).toBe(true);+ expect(store.busy).toBe(false);+ });++ it("cancels pending metadata before SQL is dispatched", async () => {+ const store = useTableCopyTaskStore();+ const metadata = deferred<any[]>();+ mocks.getColumns.mockReturnValue(metadata.promise);+ const pending = store.run([entry()], "data-only");+ await vi.waitFor(() => expect(mocks.getColumns).toHaveBeenCalled());+ await store.cancel();+ metadata.resolve([{ name: "id", extra: "" }]);+ await pending;+ expect(store.task?.status).toBe("cancelled");+ expect(mocks.executeConditionalUpdate).not.toHaveBeenCalled();+ expect(mocks.cancelConditionalUpdate).not.toHaveBeenCalled();+ });++ it("cancels only its production confirmation and never dispatches the reviewed SQL", async () => {+ const store = useTableCopyTaskStore();+ const source = entry();+ source.connection.is_production = true;+ const pending = store.run([source], "structure-only");+ const guard = useProductionSafetyStore();+ await vi.waitFor(() => expect(guard.pending?.scopeId).toBe(store.task?.id));+ await store.cancel();+ await pending;+ expect(guard.pending).toBeUndefined();+ expect(mocks.executeConditionalUpdate).not.toHaveBeenCalled();+ expect(store.task?.status).toBe("cancelled");+ });++ it("waits for the database response after requesting cancellation and retains the created structure", async () => {+ const store = useTableCopyTaskStore();+ const data = deferred<ReturnType<typeof result>>();+ mocks.executeConditionalUpdate.mockImplementation(async (_id, _db, sql) => (sql.startsWith("INSERT") ? data.promise : result()));+ const pending = store.run([entry(), { ...entry(), targetName: "second_copy" }], "structure-and-data");+ await vi.waitFor(() => expect(store.task?.phase).toBe("data"));+ const id = mocks.executeConditionalUpdate.mock.calls[1]![4];+ await store.cancel();+ expect(mocks.cancelConditionalUpdate).toHaveBeenCalledWith(id, undefined);+ expect(store.task?.status).toBe("cancelling");+ expect(store.busy).toBe(true);+ data.reject(sqlFailure("Server error: ERROR 1317 (70100): Query execution was interrupted"));+ await pending;+ expect(store.task?.status).toBe("cancelled");+ expect(store.task?.targets.map((target) => target.status)).toEqual(["cancelled", "pending"]);+ expect(store.task?.targets[0]?.structureCreated).toBe(true);+ expect(store.busy).toBe(false);+ expect(mocks.executeConditionalUpdate).toHaveBeenCalledTimes(2);+ });++ it("reports an acknowledged commit as success when it wins the cancellation race", async () => {+ const store = useTableCopyTaskStore();+ const data = deferred<ReturnType<typeof result>>();+ mocks.executeConditionalUpdate.mockReturnValue(data.promise);+ const pending = store.run([entry()], "data-only");+ await vi.waitFor(() => expect(mocks.executeConditionalUpdate).toHaveBeenCalled());+ await store.cancel();+ data.resolve(result(12));+ expect(await pending).toBe(true);+ expect(store.task?.status).toBe("succeeded");+ expect(store.task?.targets[0]?.copiedRows).toBe(12);+ });++ it("keeps the running guard on a lost response and never turns completion observation into success", async () => {+ const store = useTableCopyTaskStore();+ mocks.executeConditionalUpdate.mockRejectedValue(new Error("Connection lost while waiting for the response"));+ await store.run([entry()], "data-only");+ expect(store.task?.status).toBe("unknown");+ expect(store.busy).toBe(true);+ const tracker = useExportTracker();+ const tracked = tracker.tasks.value[0]!;+ expect(tracked.status).toBe("Unknown");+ tracker.removeTask(tracked.exportId);+ expect(tracker.tasks.value).toContain(tracked);+ expect(tracker.activeCount.value).toBe(1);+ expect(await store.run([entry()], "data-only")).toBe(false);+ mocks.cancelConditionalUpdate.mockResolvedValue({ requested: false, terminal: true, databaseTerminal: false });+ await store.checkCompletion();+ expect(store.busy).toBe(true);+ mocks.cancelConditionalUpdate.mockResolvedValue({ requested: false, terminal: true, databaseTerminal: true });+ await store.checkCompletion();+ expect(store.busy).toBe(false);+ expect(store.task?.status).toBe("unknown");+ expect(tracked.copyPhase).toBe("unknown");+ expect(tracked.status).toBe("Error");+ expect(tracker.activeCount.value).toBe(0);+ expect(mocks.executeConditionalUpdate).toHaveBeenCalledTimes(1);+ });++ it("preserves copy success when refreshing a target tab fails", async () => {+ const store = useTableCopyTaskStore();+ mocks.refreshDataTabsForTable.mockRejectedValue(new Error("Refresh unavailable"));+ expect(await store.run([entry()], "structure-and-data")).toBe(true);+ expect(store.task?.status).toBe("succeeded");+ expect(store.task?.refreshError).toBe("Refresh unavailable");+ });++ it("continues a batch after a confirmed SQL failure without reporting all targets successful", async () => {+ const store = useTableCopyTaskStore();+ mocks.executeConditionalUpdate.mockRejectedValueOnce(sqlFailure("Target exists")).mockResolvedValue(result(3));+ await store.run([entry(), { ...entry(), targetName: "second" }], "structure-only");+ expect(store.task?.status).toBe("failed");+ expect(store.task?.targets.map((target) => target.status)).toEqual(["failed", "succeeded"]);+ });++ it("does not refresh an untouched existing target after CREATE is rejected", async () => {+ const store = useTableCopyTaskStore();+ mocks.executeConditionalUpdate.mockRejectedValue(sqlFailure("Target already exists"));+ await store.run([entry()], "structure-and-data");+ expect(store.task?.status).toBe("failed");+ expect(mocks.refreshDataTabsForTable).not.toHaveBeenCalled();+ expect(mocks.getColumns).not.toHaveBeenCalled();+ });++ it("bounds a stalled cancellation request while continuing to observe the original execution", async () => {+ const store = useTableCopyTaskStore();+ const data = deferred<ReturnType<typeof result>>();+ mocks.executeConditionalUpdate.mockReturnValue(data.promise);+ const pending = store.run([entry()], "data-only");+ await vi.waitFor(() => expect(store.task?.phase).toBe("data"));+ vi.useFakeTimers();+ mocks.cancelConditionalUpdate.mockReturnValue(new Promise(() => {}));+ const cancel = store.cancel();+ await vi.advanceTimersByTimeAsync(12_000);+ await cancel;+ expect(store.cancelSending).toBe(false);+ expect(store.task?.cancelError).toContain("timed out");+ expect(store.busy).toBe(true);+ data.resolve(result(1));+ await pending;+ expect(store.task?.status).toBe("succeeded");+ });++ it("can hide and reopen active task details without cancelling the background copy", async () => {+ const store = useTableCopyTaskStore();+ const data = deferred<ReturnType<typeof result>>();+ mocks.executeConditionalUpdate.mockReturnValue(data.promise);+ const pending = store.run([entry()], "data-only");+ await vi.waitFor(() => expect(store.task?.phase).toBe("data"));+ const tracked = useExportTracker().tasks.value[0]!;+ tracked.onOpen!();+ mounted = createApp({ render: () => h(TableCopyProgressDialog) });+ mounted.use(i18n);+ mounted.use(getActivePinia()!);+ const root = document.createElement("div");+ document.body.append(root);+ mounted.mount(root);+ await nextTick();+ expect(document.body.textContent).toContain("Copying data");+ expect(document.body.textContent).toContain("Elapsed:");+ expect(document.body.textContent).toContain("Cancel copy");+ expect(document.querySelector('[role="progressbar"]')).toBeNull();+ store.close();+ expect(store.open).toBe(false);+ expect(store.busy).toBe(true);+ expect(mocks.cancelConditionalUpdate).not.toHaveBeenCalled();+ tracked.onOpen!();+ await nextTick();+ expect(store.open).toBe(true);+ document.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true }));+ await nextTick();+ expect(store.open).toBe(false);+ expect(store.busy).toBe(true);+ tracked.onOpen!();+ data.resolve(result(42));+ await pending;+ await nextTick();+ expect(document.body.textContent).toContain("Database-confirmed copied rows: 42");+ const close = [...document.querySelectorAll("button")].find((button) => button.textContent?.trim() === "Close");+ close!.click();+ await nextTick();+ expect(store.open).toBe(false);+ });++ it("opens historical results independently of a later running copy", async () => {+ const store = useTableCopyTaskStore();+ await store.run([entry()], "data-only");+ const previous = store.task;+ const historical = useExportTracker().tasks.value[0]!;+ const data = deferred<ReturnType<typeof result>>();+ mocks.executeConditionalUpdate.mockReturnValue(data.promise);+ const pending = store.run([{ ...entry(), targetName: "another" }], "data-only");+ await vi.waitFor(() => expect(store.task?.phase).toBe("data"));+ historical.onOpen!();+ expect(store.displayedTask).toBe(previous);+ expect(store.task?.targets[0]?.name).toBe("another");+ expect(store.busy).toBe(true);+ data.resolve(result(1));+ await pending;+ expect(store.displayedTask).toBe(previous);+ expect(historical.affectedRows).toBe(7000001);+ });+});diff --git a/apps/desktop/src/stores/tableCopyTaskStore.ts b/apps/desktop/src/stores/tableCopyTaskStore.tsnew file mode 100644index 0000000000..ad2333d3be--- /dev/null+++ b/apps/desktop/src/stores/tableCopyTaskStore.ts@@ -0,0 +1,278 @@+import { computed, ref, watch } from "vue";+import { defineStore } from "pinia";+import * as api from "@/lib/backend/api";+import { BackendErrorException, normalizeBackendError } from "@/lib/backend/errorUtils";+import { executeWithProductionSqlGuard } from "@/lib/database/productionExecutionGuard";+import { tableDataCopyColumnOptions, type PasteTableMode } from "@/lib/table/tableClipboard";+import { uuid } from "@/lib/common/utils";+import { useConnectionStore } from "./connectionStore";+import { useQueryStore } from "./queryStore";+import { useProductionSafetyStore } from "./productionSafetyStore";+import type { ConnectionConfig } from "@/types/database";+import { useExportTracker, type ExportTask } from "@/composables/useExportTracker";+import { useToast } from "@/composables/useToast";+import i18n from "@/i18n";++export interface MysqlTableCopyEntry {+ connection: ConnectionConfig;+ database: string;+ catalog?: string;+ schema?: string;+ sourceName: string;+ targetName: string;+ tableComment?: string | null;+ identifierQuote?: string;+}++type CopyStatus = "running" | "cancelling" | "succeeded" | "failed" | "cancelled" | "unknown";+export interface TableCopyTask {+ id: string;+ status: CopyStatus;+ phase: "preparing" | "structure" | "data" | "refreshing";+ startedAt: number;+ finishedAt?: number;+ currentIndex: number;+ targets: Array<{ name: string; status: "pending" | CopyStatus; structureCreated: boolean; copiedRows?: number; error?: string }>;+ error?: string;+ refreshError?: string;+ cancelError?: string;+}++class CopyCancelled extends Error {}+class CopyOutcomeUnknown extends Error {}+const message = (error: unknown) => (error instanceof Error ? error.message : String(error));++async function observeExecution(id: string, cancel: boolean) {+ let timer: ReturnType<typeof setTimeout> | undefined;+ try {+ return await Promise.race([+ api.cancelConditionalUpdate(id, cancel ? undefined : { cancel: false }),+ new Promise<never>((_, reject) => {+ timer = setTimeout(() => reject(new Error("Execution status request timed out. The original copy result is still pending.")), 12_000);+ }),+ ]);+ } finally {+ clearTimeout(timer);+ }+}++/** One app-owned task shared by both clone/paste entry points, independent of their lifetime. */+export const useTableCopyTaskStore = defineStore("tableCopyTask", () => {+ const task = ref<TableCopyTask>();+ const viewedTask = ref<TableCopyTask>();+ const displayedTask = computed(() => viewedTask.value ?? task.value);+ const open = ref(false);+ const executionId = ref<string>();+ const cancelSending = ref(false);+ const busy = computed(() => !!executionId.value || task.value?.status === "running" || task.value?.status === "cancelling" || (task.value?.phase === "refreshing" && !task.value.finishedAt));+ let cancelRequested = false;+ const tracker = useExportTracker();+ let trackedTask: ExportTask | undefined;++ function showDetails(record = task.value) {+ if (!record) return;+ viewedTask.value = record;+ open.value = true;+ }++ function syncBackgroundTask() {+ const current = task.value;+ if (!current || trackedTask?.exportId !== current.id) return;+ const status = current.status;+ Object.assign(trackedTask, {+ status: status === "unknown" ? (busy.value ? "Unknown" : "Error") : busy.value ? (status === "cancelling" ? "Cancelling" : "Running") : status === "succeeded" ? "Done" : status === "cancelled" ? "Cancelled" : "Error",+ copyPhase: busy.value && status !== "unknown" ? (status === "cancelling" ? "cancelling" : current.phase) : status,+ currentTable: current.targets[current.currentIndex]?.name,+ affectedRows: current.targets.some((target) => target.copiedRows !== undefined) ? current.targets.reduce((sum, target) => sum + (target.copiedRows ?? 0), 0) : undefined,+ errorMessage: [current.error, current.refreshError, current.cancelError].filter(Boolean).join("\n") || null,+ startedAt: current.startedAt,+ finishedAt: current.finishedAt,+ canCancel: busy.value && current.phase !== "refreshing" && !cancelSending.value,+ canRemove: !busy.value,+ });+ if (busy.value) tracker.registerTaskCancelHandler(current.id, cancel);+ else tracker.unregisterTaskCancelHandler(current.id);+ }+ watch([task, busy, cancelSending], syncBackgroundTask, { deep: true, flush: "sync" });++ function notify(record: TableCopyTask, started: boolean) {+ const t = i18n.global.t;+ useToast().toast(started ? t("tableCopyTask.backgroundStarted") : t("tableCopyTask.backgroundFinished", { status: t(`tableCopyTask.${record.status}`) }), 5000, { label: t("tableCopyTask.details"), onClick: () => showDetails(record) });+ }++ function checkCancelled() {+ if (cancelRequested) throw new CopyCancelled();+ }++ async function cancel() {+ if (!task.value || !busy.value || cancelSending.value) return;+ if (task.value.phase === "refreshing") return; // The database outcome is already final.+ cancelRequested = true;+ if (task.value.status !== "unknown") task.value.status = "cancelling";+ useProductionSafetyStore().cancelScope(task.value.id);+ const id = executionId.value;+ if (!id) return; // Planning and safety confirmation check again before dispatch.+ cancelSending.value = true;+ task.value.cancelError = undefined;+ try {+ // Registration can race a just-dispatched IPC/HTTP request. Never interpret+ // a missing registration, or a cancellation request, as a completed copy.+ for (let attempt = 0; attempt < 5 && executionId.value === id; attempt++) {+ const result = await observeExecution(id, true);+ if (result.requested || result.terminal) break;+ await new Promise((resolve) => setTimeout(resolve, 100));+ }+ } catch (error) {+ if (executionId.value === id) task.value.cancelError = message(error);+ } finally {+ cancelSending.value = false;+ }+ }++ async function checkCompletion() {+ const id = executionId.value;+ if (!id || !task.value || cancelSending.value) return;+ cancelSending.value = true;+ try {+ const result = await observeExecution(id, false);+ // A lost response never becomes a success or permission to replay. Only+ // release the running-task guard when the original DB execution ended.+ if (executionId.value === id && task.value.status === "unknown" && result.databaseTerminal === true) {+ executionId.value = undefined;+ task.value.finishedAt = Date.now();+ }+ } catch (error) {+ task.value.cancelError = message(error);+ } finally {+ cancelSending.value = false;+ }+ }++ function close() {+ open.value = false; // Only hides details; the app-owned task keeps running.+ }++ async function run(input: readonly MysqlTableCopyEntry[], mode: PasteTableMode): Promise<boolean> {+ if (busy.value) {+ showDetails();+ return false;+ }+ if (!input.length) return false;+ // Capture all identities before the first await. Do not retain credentials in UI state.+ const entries = input.map((entry) => ({ ...entry, connection: { ...entry.connection }, targetName: entry.targetName.trim() }));+ cancelRequested = false;+ task.value = { id: uuid(), status: "running", phase: "preparing", startedAt: Date.now(), currentIndex: 0, targets: entries.map((entry) => ({ name: entry.targetName, status: "pending", structureCreated: false })) };+ const current = task.value;+ viewedTask.value = current;+ open.value = false;+ trackedTask = tracker.addTableCopyTask(current.id, current.targets.map((target) => target.name).join(", "), () => showDetails(current));+ syncBackgroundTask();+ notify(current, true);+ const refresh = new Set<MysqlTableCopyEntry>();++ async function execute(entry: MysqlTableCopyEntry, sql: string) {+ checkCancelled();+ const result = await executeWithProductionSqlGuard({+ connection: entry.connection,+ database: entry.database,+ sql,+ source: "Table copy",+ scopeId: current.id,+ execute: async () => {+ checkCancelled();+ const id = uuid();+ executionId.value = id;+ try {+ // This existing command keeps the database execution owned until its+ // response/rollback settles instead of racing the cancellation token.+ const value = await api.executeConditionalUpdate(entry.connection.id, entry.database, sql, entry.schema, id, { timeoutSecs: 0, catalog: entry.catalog });+ if (value.execution_error) throw value.error ? new BackendErrorException(value.error) : new Error("The database did not confirm the table copy.");+ refresh.add(entry);+ executionId.value = undefined;+ return value;+ } catch (error) {+ const envelope = normalizeBackendError(error);+ const rejected = envelope?.operationOutcome === "not_started" || (envelope?.diagnostics?.category === "sql" && envelope.diagnostics.stage === "execute");+ if (!rejected) throw new CopyOutcomeUnknown(message(error));+ // A failed data write may have partially changed a nontransactional+ // target. A rejected CREATE, however, must not reload an existing,+ // untouched target (which may have unsaved edits).+ if (current.phase === "data") refresh.add(entry);+ executionId.value = undefined;+ if (cancelRequested && /cancel(?:led|ed)?|query execution was interrupted/i.test(envelope?.detail || message(error))) throw new CopyCancelled();+ throw error;+ }+ },+ });+ if (result === undefined) throw new CopyCancelled(); // Read-only/production guard denied dispatch.+ return result;+ }++ for (const [index, entry] of entries.entries()) {+ const target = current.targets[index]!;+ current.currentIndex = index;+ current.phase = "preparing";+ try {+ checkCancelled();+ target.status = "running";+ await useConnectionStore().ensureConnected(entry.connection.id);+ checkCancelled();+ const { buildCopyTableDataSql, buildDuplicateTableStructurePlan } = await import("@/lib/database/dbAdminSql");+ checkCancelled();+ if (mode !== "data-only") {+ const plan = await buildDuplicateTableStructurePlan({ ...entry, connectionId: entry.connection.id, databaseType: "mysql" });+ checkCancelled();+ current.phase = "structure";+ await execute(entry, plan.sql);+ target.structureCreated = true;+ }+ if (mode !== "structure-only") {+ checkCancelled();+ current.phase = "preparing";+ const columns = await api.getColumns(entry.connection.id, entry.database, entry.schema || "", entry.sourceName, entry.catalog);+ checkCancelled();+ const options = tableDataCopyColumnOptions("mysql", columns);+ if (!options.columns.length) throw new Error("No writable columns available for table data copy.");+ const sql = await buildCopyTableDataSql({ ...entry, ...options, databaseType: "mysql", normalizeNewTargetName: mode === "structure-and-data" });+ checkCancelled();+ current.phase = "data";+ const result = await execute(entry, sql);+ target.copiedRows = result.affected_rows;+ }+ target.status = "succeeded"; // A late cancel cannot undo an acknowledged successful statement.+ } catch (error) {+ if (error instanceof CopyCancelled) {+ target.status = "cancelled";+ current.status = "cancelled";+ break;+ }+ target.error = message(error);+ current.error ??= target.error;+ if (error instanceof CopyOutcomeUnknown) {+ target.status = "unknown";+ current.status = "unknown";+ break;+ }+ target.status = "failed";+ }+ }+ if (current.status === "running" || current.status === "cancelling") current.status = current.targets.some((target) => target.status === "failed") ? "failed" : "succeeded";+ if (current.status !== "unknown") {+ current.phase = "refreshing";+ // Mutation outcome and refresh errors are independent: never suggest+ // replaying a successful copy because refreshing an open tab failed.+ for (const entry of refresh) {+ const results = await Promise.allSettled([+ useConnectionStore().refreshObjectListTreeNode(entry.connection.id, entry.database, entry.schema),+ useQueryStore().refreshDataTabsForTable({ connectionId: entry.connection.id, database: entry.database, schema: entry.schema, catalog: entry.catalog, name: entry.targetName }),+ ]);+ for (const result of results) if (result.status === "rejected") current.refreshError ??= message(result.reason);+ }+ current.finishedAt = Date.now();+ }+ if (!open.value || displayedTask.value !== current) notify(current, false);+ return current.status === "succeeded";+ }++ return { task, displayedTask, open, busy, cancelSending, run, cancel, checkCompletion, close, showDetails };+});diff --git a/docs/screenshots/mysql-table-copy-background-completed.png b/docs/screenshots/mysql-table-copy-background-completed.pngnew file mode 100644index 0000000000..f3c71539e1Binary files /dev/null and b/docs/screenshots/mysql-table-copy-background-completed.png differdiff --git a/docs/screenshots/mysql-table-copy-background-running.png b/docs/screenshots/mysql-table-copy-background-running.pngnew file mode 100644index 0000000000..9a522b128eBinary files /dev/null and b/docs/screenshots/mysql-table-copy-background-running.png differ