Skip to content

armgit / dbx

Public Imported from GitHub
0

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

feat(dameng): native dexp/dimp (.dmp) fast export/import

弈秋fc84e0973880
diff --git a/apps/desktop/src/components/document/DamengDumpDialog.vue b/apps/desktop/src/components/document/DamengDumpDialog.vue
new file mode 100644
index 0000000000..ded2de259a
--- /dev/null
+++ b/apps/desktop/src/components/document/DamengDumpDialog.vue
@@ -0,0 +1,259 @@
+<script setup lang="ts">
+import { computed, onBeforeUnmount, ref, watch } from "vue";
+import { useI18n } from "vue-i18n";
+import { ArrowLeft, DatabaseBackup, FolderOpen, Loader2, Play, ShieldAlert, Square, X } from "@lucide/vue";
+import { Dialog, DialogFooter, DialogHeader, DialogScrollContent, DialogTitle } from "@/components/ui/dialog";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
+import { useConnectionStore } from "@/stores/connectionStore";
+import { useSettingsStore } from "@/stores/settingsStore";
+import { connectionIsEffectivelyReadOnly } from "@/lib/database/readOnlyWriteAccess";
+import { executeWithProductionContextGuard } from "@/lib/database/productionExecutionGuard";
+import { isTauriRuntime } from "@/lib/backend/tauriRuntime";
+import { uuid } from "@/lib/common/utils";
+import * as api from "@/lib/backend/api";
+
+const props = defineProps<{ connectionId: string; database: string; mode: "export" | "import" }>();
+const open = defineModel<boolean>("open", { default: false });
+const { t } = useI18n();
+const connectionStore = useConnectionStore();
+const settingsStore = useSettingsStore();
+const desktop = isTauriRuntime();
+const exporting = computed(() => props.mode === "export");
+const connection = computed(() => connectionStore.getConfig(props.connectionId));
+const readonly = computed(() => !exporting.value && connectionIsEffectivelyReadOnly(connection.value));
+
+const binDir = computed(() => settingsStore.editorSettings.damengClientBinDir.trim());
+const toolMissing = computed(() => !binDir.value);
+
+const filePath = ref("");
+const schemas = ref(props.database);
+const tables = ref("");
+const remapFrom = ref("");
+const remapTo = ref("");
+const tableExistsAction = ref("SKIP");
+
+const running = ref(false);
+const cancelling = ref(false);
+const confirming = ref(false);
+const error = ref("");
+const step = ref<"configure" | "result">("configure");
+const progress = ref<api.DamengDumpProgress | null>(null);
+const taskId = ref("");
+let generation = 0;
+
+const tableExistsActionOptions = ["SKIP", "REPLACE", "TRUNCATE", "APPEND"] as const;
+
+const canStart = computed(
+ () =>
+ desktop &&
+ !toolMissing.value &&
+ !running.value &&
+ !confirming.value &&
+ !readonly.value &&
+ !!filePath.value.trim() &&
+ // Import remap is optional, but a target without a source is a mistake.
+ (!exporting.value ? !remapTo.value.trim() || !!remapFrom.value.trim() : true),
+);
+
+function resetConfigure() {
+ generation += 1;
+ filePath.value = "";
+ schemas.value = props.database;
+ tables.value = "";
+ remapFrom.value = "";
+ remapTo.value = "";
+ tableExistsAction.value = "SKIP";
+ error.value = "";
+ progress.value = null;
+ step.value = "configure";
+}
+function cleanup() {
+ generation += 1;
+}
+onBeforeUnmount(cleanup);
+watch(open, (value) => {
+ if (value) resetConfigure();
+ else cleanup();
+});
+
+async function chooseFile() {
+ const dialog = await import("@tauri-apps/plugin-dialog");
+ if (exporting.value) {
+ const stamp = new Date().toISOString().slice(0, 19).replace(/[:T]/g, "-");
+ const path = await dialog.save({
+ defaultPath: filePath.value.trim() || `${props.database}-${stamp}.dmp`,
+ filters: [{ name: "Dameng dump", extensions: ["dmp"] }],
+ });
+ if (path) filePath.value = path;
+ } else {
+ const path = await dialog.open({ multiple: false, filters: [{ name: "Dameng dump", extensions: ["dmp"] }] });
+ if (typeof path === "string") filePath.value = path;
+ }
+}
+
+function parseList(value: string): string[] {
+ return value
+ .split(",")
+ .map((part) => part.trim())
+ .filter(Boolean);
+}
+
+async function start() {
+ if (!canStart.value) return;
+ confirming.value = true;
+ const current = ++generation;
+ error.value = "";
+ progress.value = null;
+ try {
+ if (!exporting.value) {
+ const allowed = await executeWithProductionContextGuard({
+ connection: connection.value,
+ database: remapTo.value.trim() || schemas.value.trim() || props.database,
+ source: t("damengDump.importTitle"),
+ reviewText: `IMPORT ${filePath.value.trim()}${remapFrom.value.trim() ? ` REMAP_SCHEMA=${remapFrom.value.trim()}:${remapTo.value.trim() || remapFrom.value.trim()}` : ""} TABLE_EXISTS_ACTION=${tableExistsAction.value}`,
+ execute: async () => true,
+ });
+ if (!allowed || current !== generation || !open.value) return;
+ }
+ if (current !== generation || !open.value) return;
+ running.value = true;
+ confirming.value = false;
+ step.value = "result";
+ taskId.value = uuid();
+ await connectionStore.ensureConnected(props.connectionId);
+ if (current !== generation) return;
+ const toolPath = await api.resolveDamengDumpTool(binDir.value, props.mode);
+ if (current !== generation) return;
+ const remapSchema: [string, string] | null = !exporting.value && remapFrom.value.trim() ? [remapFrom.value.trim(), remapTo.value.trim() || remapFrom.value.trim()] : null;
+ progress.value = await api.startDamengDump(
+ {
+ taskId: taskId.value,
+ connectionId: props.connectionId,
+ kind: props.mode,
+ toolPath,
+ filePath: filePath.value.trim(),
+ schemas: parseList(schemas.value),
+ tables: exporting.value ? parseList(tables.value) : [],
+ remapSchema,
+ tableExistsAction: exporting.value ? null : tableExistsAction.value,
+ },
+ (value) => {
+ if (current === generation) progress.value = value;
+ },
+ );
+ } catch (cause) {
+ if (current === generation) error.value = String(cause instanceof Error ? cause.message : cause);
+ } finally {
+ confirming.value = false;
+ if (current === generation) {
+ running.value = false;
+ cancelling.value = false;
+ }
+ }
+}
+async function cancel() {
+ cancelling.value = true;
+ try {
+ await api.cancelDamengDump(taskId.value);
+ } catch (cause) {
+ cancelling.value = false;
+ error.value = String(cause instanceof Error ? cause.message : cause);
+ }
+}
+function close() {
+ if (!running.value) open.value = false;
+}
+</script>
+
+<template>
+ <Dialog
+ :open="open"
+ @update:open="
+ (value) => {
+ if (!value) close();
+ }
+ "
+ >
+ <DialogScrollContent class="flex max-h-[calc(var(--dbx-viewport-height)-4rem)] min-h-0 flex-col overflow-hidden sm:max-w-[640px]">
+ <DialogHeader class="shrink-0 pr-8"
+ ><DialogTitle class="flex items-center gap-2 text-base"><DatabaseBackup class="h-4 w-4" />{{ t(exporting ? "damengDump.exportTitle" : "damengDump.importTitle") }}</DialogTitle></DialogHeader
+ >
+ <div class="min-h-0 flex-1 space-y-4 overflow-y-auto py-3 text-sm">
+ <div class="border-b pb-2 font-medium break-all">{{ connection?.name }} / {{ props.database }}</div>
+ <div v-if="!desktop" class="text-xs text-amber-600">{{ t("damengDump.desktopOnly") }}</div>
+ <div v-if="readonly" class="text-xs text-amber-600">{{ t("damengDump.readonly") }}</div>
+ <div v-if="toolMissing" class="text-xs text-amber-600">
+ {{ t("damengDump.binDirMissing") }}
+ <span class="block text-muted-foreground">{{ t("damengDump.binDirSettingHint") }}</span>
+ </div>
+ <div class="flex items-start gap-2 text-xs text-muted-foreground">
+ <ShieldAlert class="mt-0.5 h-3.5 w-3.5 shrink-0" /><span>{{ t("damengDump.passwordOnArgv") }}</span>
+ </div>
+ <template v-if="step === 'configure'">
+ <div class="space-y-1">
+ <Label>{{ t(exporting ? "damengDump.outputFile" : "damengDump.inputFile") }}</Label>
+ <div class="flex gap-2">
+ <Input v-model="filePath" class="h-8 min-w-0" :placeholder="t('damengDump.filePlaceholder')" :disabled="running" />
+ <Button variant="outline" size="icon" class="h-8 w-8 shrink-0" :title="t('damengDump.chooseFile')" :aria-label="t('damengDump.chooseFile')" :disabled="running || !desktop" @click="chooseFile">
+ <FolderOpen class="h-4 w-4" />
+ </Button>
+ </div>
+ </div>
+ <div class="space-y-1">
+ <Label>{{ t("damengDump.schemas") }}</Label>
+ <Input v-model="schemas" class="h-8" :placeholder="props.database" :disabled="running" />
+ <p class="text-xs text-muted-foreground">{{ t("damengDump.schemasHint") }}</p>
+ </div>
+ <div v-if="exporting" class="space-y-1">
+ <Label>{{ t("damengDump.tables") }}</Label>
+ <Input v-model="tables" class="h-8" :placeholder="t('damengDump.tablesPlaceholder')" :disabled="running" />
+ <p class="text-xs text-muted-foreground">{{ t("damengDump.tablesHint") }}</p>
+ </div>
+ <div v-if="!exporting" class="grid grid-cols-1 gap-3 sm:grid-cols-2">
+ <div class="space-y-1">
+ <Label>{{ t("damengDump.remapFrom") }}</Label>
+ <Input v-model="remapFrom" class="h-8" :placeholder="t('damengDump.remapFromPlaceholder')" :disabled="running" />
+ </div>
+ <div class="space-y-1">
+ <Label>{{ t("damengDump.remapTo") }}</Label>
+ <Input v-model="remapTo" class="h-8" :placeholder="t('damengDump.remapToPlaceholder')" :disabled="running" />
+ </div>
+ </div>
+ <div v-if="!exporting" class="space-y-1">
+ <Label>{{ t("damengDump.tableExistsAction") }}</Label>
+ <Select v-model="tableExistsAction" :disabled="running">
+ <SelectTrigger class="h-8 w-44"><SelectValue /></SelectTrigger>
+ <SelectContent>
+ <SelectItem v-for="action in tableExistsActionOptions" :key="action" :value="action">{{ t(`damengDump.tableExists.${action}`) }}</SelectItem>
+ </SelectContent>
+ </Select>
+ <p class="text-xs text-muted-foreground">{{ t("damengDump.tableExistsHint") }}</p>
+ </div>
+ </template>
+ <template v-else>
+ <div class="flex items-center gap-2 font-medium">
+ <Loader2 v-if="running || !progress" class="h-4 w-4 animate-spin" />{{ running ? t("damengDump.running") : progress?.status === "done" ? t("damengDump.done") : progress?.status === "cancelled" ? t("damengDump.cancelled") : t("damengDump.failed") }}
+ </div>
+ <div class="break-all text-xs text-muted-foreground">{{ filePath }}</div>
+ <dl v-if="progress" class="grid grid-cols-2 gap-3 border-y py-3 text-xs">
+ <dt>{{ t("damengDump.elapsed") }}</dt>
+ <dd class="text-right tabular-nums">{{ progress.elapsedSeconds ?? "-" }}</dd>
+ <dt>{{ t("damengDump.warnings") }}</dt>
+ <dd class="text-right">{{ progress.warnings ? t("damengDump.warningsPresent") : t("damengDump.warningsNone") }}</dd>
+ </dl>
+ <div v-if="progress?.error" class="break-words border-l-2 border-destructive pl-3 text-xs text-destructive" role="alert">{{ progress.error }}</div>
+ </template>
+ <div v-if="error" class="break-words border-l-2 border-destructive pl-3 text-xs text-destructive" role="alert">{{ error }}</div>
+ </div>
+ <DialogFooter class="shrink-0"
+ ><Button v-if="running" variant="destructive" :disabled="cancelling" @click="cancel"><Square class="mr-1.5 h-4 w-4" />{{ t("damengDump.cancel") }}</Button
+ ><Button v-else variant="outline" :disabled="cancelling || confirming" @click="close"><X class="mr-1.5 h-4 w-4" />{{ t("damengDump.close") }}</Button
+ ><Button v-if="step !== 'configure' && !running" variant="outline" :disabled="confirming" @click="step = 'configure'"><ArrowLeft class="mr-1.5 h-4 w-4" />{{ t("damengDump.back") }}</Button
+ ><Button v-if="step === 'configure'" :disabled="!canStart" @click="start"><Play class="mr-1.5 h-4 w-4" />{{ t(exporting ? "damengDump.startExport" : "damengDump.startImport") }}</Button></DialogFooter
+ >
+ </DialogScrollContent>
+ </Dialog>
+</template>
diff --git a/apps/desktop/src/components/document/__tests__/DamengDumpDialog.spec.ts b/apps/desktop/src/components/document/__tests__/DamengDumpDialog.spec.ts
new file mode 100644
index 0000000000..a85d9d9f00
--- /dev/null
+++ b/apps/desktop/src/components/document/__tests__/DamengDumpDialog.spec.ts
@@ -0,0 +1,162 @@
+// @vitest-environment happy-dom
+import { createApp, nextTick, type App } from "vue";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ api: { startDamengDump: vi.fn(), cancelDamengDump: vi.fn(), resolveDamengDumpTool: vi.fn() },
+ store: { getConfig: vi.fn(), ensureConnected: vi.fn() },
+ settings: { editorSettings: { damengClientBinDir: "/opt/dm8/bin" } },
+ guard: vi.fn(),
+ readOnly: vi.fn(() => false),
+}));
+vi.mock("@/lib/backend/api", () => mocks.api);
+vi.mock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => true }));
+vi.mock("@/stores/connectionStore", () => ({ useConnectionStore: () => mocks.store }));
+vi.mock("@/stores/settingsStore", () => ({ useSettingsStore: () => mocks.settings }));
+vi.mock("vue-i18n", async (original) => ({ ...(await original<typeof import("vue-i18n")>()), useI18n: () => ({ t: (key: string) => key }) }));
+vi.mock("@/lib/database/productionExecutionGuard", () => ({ executeWithProductionContextGuard: mocks.guard }));
+vi.mock("@/lib/database/readOnlyWriteAccess", () => ({ connectionIsEffectivelyReadOnly: mocks.readOnly }));
+vi.mock("@/lib/common/utils", async (importOriginal) => ({ ...(await importOriginal<typeof import("@/lib/common/utils")>()), uuid: () => "task-1" }));
+import DamengDumpDialog from "../DamengDumpDialog.vue";
+
+const done = { taskId: "task-1", status: "done" as const, success: true, warnings: false, elapsedSeconds: "1.2s", error: null };
+let app: App | null;
+async function flush() {
+ for (let i = 0; i < 5; i++) {
+ await Promise.resolve();
+ await nextTick();
+ }
+}
+function button(key: string): HTMLButtonElement {
+ const button = Array.from(document.querySelectorAll("button")).find((button) => button.textContent?.trim() === key);
+ if (!button) throw new Error(`Missing button ${key}`);
+ return button;
+}
+function filePathInput(): HTMLInputElement {
+ const input = document.querySelector<HTMLInputElement>('input[placeholder="damengDump.filePlaceholder"]');
+ if (!input) throw new Error("Missing file path input");
+ return input;
+}
+function setFilePath(path: string) {
+ const input = filePathInput();
+ input.value = path;
+ input.dispatchEvent(new Event("input", { bubbles: true }));
+}
+function setInputByLabel(labelKey: string, value: string) {
+ const label = Array.from(document.querySelectorAll("label")).find((label) => label.textContent?.trim() === labelKey);
+ const input = label?.parentElement?.querySelector<HTMLInputElement>("input");
+ if (!input) throw new Error(`Missing input for ${labelKey}`);
+ input.value = value;
+ input.dispatchEvent(new Event("input", { bubbles: true }));
+}
+async function mount(mode: "export" | "import") {
+ app = createApp(DamengDumpDialog, { open: true, connectionId: "c1", database: "APP", mode });
+ app.mount(document.body);
+ await flush();
+}
+
+describe("DamengDumpDialog", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.store.getConfig.mockReturnValue({ name: "Dameng", read_only: false });
+ mocks.store.ensureConnected.mockResolvedValue(undefined);
+ mocks.settings.editorSettings.damengClientBinDir = "/opt/dm8/bin";
+ mocks.api.resolveDamengDumpTool.mockResolvedValue("/opt/dm8/bin/dexp");
+ mocks.api.startDamengDump.mockResolvedValue(done);
+ mocks.api.cancelDamengDump.mockResolvedValue(undefined);
+ mocks.guard.mockImplementation(async ({ execute }: { execute: () => Promise<boolean> }) => execute());
+ mocks.readOnly.mockReturnValue(false);
+ });
+ afterEach(() => {
+ app?.unmount();
+ app = null;
+ document.body.innerHTML = "";
+ });
+
+ it("exports the selected schema to the chosen .dmp path without the production guard", async () => {
+ await mount("export");
+ setFilePath("C:/backups/app.dmp");
+ await flush();
+ button("damengDump.startExport").click();
+ await flush();
+ expect(mocks.api.resolveDamengDumpTool).toHaveBeenCalledWith("/opt/dm8/bin", "export");
+ expect(mocks.api.startDamengDump).toHaveBeenCalledWith(
+ expect.objectContaining({ taskId: "task-1", connectionId: "c1", kind: "export", toolPath: "/opt/dm8/bin/dexp", filePath: "C:/backups/app.dmp", schemas: ["APP"], tables: [], remapSchema: null, tableExistsAction: null }),
+ expect.any(Function),
+ );
+ expect(mocks.guard).not.toHaveBeenCalled();
+ });
+
+ it("parses comma-separated tables and keeps them out of the schema list", async () => {
+ await mount("export");
+ setFilePath("C:/backups/tables.dmp");
+ setInputByLabel("damengDump.tables", "EMP, DEPT");
+ await flush();
+ button("damengDump.startExport").click();
+ await flush();
+ expect(mocks.api.startDamengDump).toHaveBeenCalledWith(expect.objectContaining({ schemas: ["APP"], tables: ["EMP", "DEPT"] }), expect.any(Function));
+ });
+
+ it("imports with remap and the default table-exists action after the production guard", async () => {
+ mocks.api.resolveDamengDumpTool.mockResolvedValue("/opt/dm8/bin/dimp");
+ await mount("import");
+ setFilePath("C:/backups/app.dmp");
+ setInputByLabel("damengDump.remapFrom", "SRC");
+ setInputByLabel("damengDump.remapTo", "DST");
+ await flush();
+ button("damengDump.startImport").click();
+ await flush();
+ expect(mocks.guard).toHaveBeenCalledWith(expect.objectContaining({ database: "DST", reviewText: expect.stringContaining("REMAP_SCHEMA=SRC:DST TABLE_EXISTS_ACTION=SKIP") }));
+ expect(mocks.api.resolveDamengDumpTool).toHaveBeenCalledWith("/opt/dm8/bin", "import");
+ expect(mocks.api.startDamengDump).toHaveBeenCalledWith(expect.objectContaining({ kind: "import", toolPath: "/opt/dm8/bin/dimp", remapSchema: ["SRC", "DST"], tableExistsAction: "SKIP", tables: [] }), expect.any(Function));
+ });
+
+ it("does not import when the production guard declines", async () => {
+ mocks.guard.mockResolvedValueOnce(false);
+ await mount("import");
+ setFilePath("C:/backups/app.dmp");
+ await flush();
+ button("damengDump.startImport").click();
+ await flush();
+ expect(mocks.api.startDamengDump).not.toHaveBeenCalled();
+ expect(button("damengDump.startImport").disabled).toBe(false);
+ });
+
+ it("disables start while the client bin directory is missing", async () => {
+ mocks.settings.editorSettings.damengClientBinDir = "";
+ await mount("export");
+ setFilePath("C:/backups/app.dmp");
+ await flush();
+ expect(button("damengDump.startExport").disabled).toBe(true);
+ expect(document.body.textContent).toContain("damengDump.binDirMissing");
+ });
+
+ it("disables start for read-only connections in import mode", async () => {
+ mocks.readOnly.mockReturnValue(true);
+ await mount("import");
+ setFilePath("C:/backups/app.dmp");
+ await flush();
+ expect(button("damengDump.startImport").disabled).toBe(true);
+ expect(document.body.textContent).toContain("damengDump.readonly");
+ });
+
+ it("cancels a running task through the backend", async () => {
+ let resolveStart!: (value: typeof done) => void;
+ mocks.api.startDamengDump.mockReturnValue(
+ new Promise((resolve) => {
+ resolveStart = resolve;
+ }),
+ );
+ await mount("export");
+ setFilePath("C:/backups/app.dmp");
+ await flush();
+ button("damengDump.startExport").click();
+ await flush();
+ button("damengDump.cancel").click();
+ await flush();
+ expect(mocks.api.cancelDamengDump).toHaveBeenCalledWith("task-1");
+ resolveStart({ ...done, status: "cancelled" });
+ await flush();
+ expect(document.body.textContent).toContain("damengDump.cancelled");
+ });
+});
diff --git a/apps/desktop/src/components/editor/EditorSettingsDialog.vue b/apps/desktop/src/components/editor/EditorSettingsDialog.vue
index d7c3348fdd..555a129582 100644
--- a/apps/desktop/src/components/editor/EditorSettingsDialog.vue
+++ b/apps/desktop/src/components/editor/EditorSettingsDialog.vue
@@ -944,6 +944,7 @@ const editSidebarFontSize = ref(settingsStore.editorSettings.sidebarFontSize);
const editSidebarDensity = ref<SidebarDensity>(settingsStore.editorSettings.sidebarDensity);
const editExportBatchSize = ref(settingsStore.editorSettings.exportBatchSize);
const editPreferredExportPath = ref(settingsStore.editorSettings.preferredExportPath);
+const editDamengClientBinDir = ref(settingsStore.editorSettings.damengClientBinDir);
const editAutoOpenExportFolder = ref(settingsStore.editorSettings.autoOpenExportFolder);
const editCsvQuoteMode = ref<CsvQuoteMode>(settingsStore.editorSettings.csvQuoteMode);
const editCsvNullMode = ref<CsvNullMode>(settingsStore.editorSettings.csvNullMode);
@@ -1233,6 +1234,7 @@ function currentEditorSettingsDraft(): EditorSettingsDraft {
redisDatabaseDisplayLimit: editRedisDatabaseDisplayLimit.value,
exportBatchSize: editExportBatchSize.value,
preferredExportPath: editPreferredExportPath.value,
+ damengClientBinDir: editDamengClientBinDir.value,
autoOpenExportFolder: editAutoOpenExportFolder.value,
csvQuoteMode: editCsvQuoteMode.value,
csvNullMode: editCsvNullMode.value,
@@ -1921,6 +1923,7 @@ function syncEditorSettingsDraftFromStore() {
editSidebarDensity.value = settingsStore.editorSettings.sidebarDensity;
editExportBatchSize.value = settingsStore.editorSettings.exportBatchSize;
editPreferredExportPath.value = settingsStore.editorSettings.preferredExportPath;
+ editDamengClientBinDir.value = settingsStore.editorSettings.damengClientBinDir;
editAutoOpenExportFolder.value = settingsStore.editorSettings.autoOpenExportFolder;
editCsvQuoteMode.value = settingsStore.editorSettings.csvQuoteMode;
editCsvNullMode.value = settingsStore.editorSettings.csvNullMode;
@@ -2081,6 +2084,7 @@ const editorSettingsDraftRefs: EditorSettingsDraftRefMap = {
redisDatabaseDisplayLimit: editRedisDatabaseDisplayLimit,
exportBatchSize: editExportBatchSize,
preferredExportPath: editPreferredExportPath,
+ damengClientBinDir: editDamengClientBinDir,
autoOpenExportFolder: editAutoOpenExportFolder,
csvQuoteMode: editCsvQuoteMode,
csvNullMode: editCsvNullMode,
@@ -2437,6 +2441,7 @@ async function persistSettings() {
// reporting unsaved changes after a successful apply.
editRedisDatabaseDisplayLimit.value = settingsStore.editorSettings.redisDatabaseDisplayLimit;
editPreferredExportPath.value = settingsStore.editorSettings.preferredExportPath;
+ editDamengClientBinDir.value = settingsStore.editorSettings.damengClientBinDir;
// 同理:落盘口径可能改写键位(跨平台默认键、保留键回退),草稿要跟着回到
// 落盘值,避免面板卡在“未保存”无法应用(#9881)。
editShortcuts.value = normalizeShortcutSettings(settingsStore.editorSettings.shortcuts);
@@ -2670,6 +2675,7 @@ function resetDefaultsForTab(tab: SettingsCategory) {
editRedisDatabaseDisplayLimit.value = DEFAULT_EDITOR_SETTINGS.redisDatabaseDisplayLimit;
editExportBatchSize.value = DEFAULT_EDITOR_SETTINGS.exportBatchSize;
editPreferredExportPath.value = DEFAULT_EDITOR_SETTINGS.preferredExportPath;
+ editDamengClientBinDir.value = DEFAULT_EDITOR_SETTINGS.damengClientBinDir;
editAutoOpenExportFolder.value = DEFAULT_EDITOR_SETTINGS.autoOpenExportFolder;
editCsvQuoteMode.value = DEFAULT_EDITOR_SETTINGS.csvQuoteMode;
editCsvNullMode.value = DEFAULT_EDITOR_SETTINGS.csvNullMode;
@@ -2835,6 +2841,7 @@ function resetAllDefaults() {
editRedisDatabaseDisplayLimit.value = DEFAULT_EDITOR_SETTINGS.redisDatabaseDisplayLimit;
editExportBatchSize.value = DEFAULT_EDITOR_SETTINGS.exportBatchSize;
editPreferredExportPath.value = DEFAULT_EDITOR_SETTINGS.preferredExportPath;
+ editDamengClientBinDir.value = DEFAULT_EDITOR_SETTINGS.damengClientBinDir;
editAutoOpenExportFolder.value = DEFAULT_EDITOR_SETTINGS.autoOpenExportFolder;
editCsvQuoteMode.value = DEFAULT_EDITOR_SETTINGS.csvQuoteMode;
editCsvNullMode.value = DEFAULT_EDITOR_SETTINGS.csvNullMode;
@@ -3342,6 +3349,17 @@ async function pickPreferredExportPath() {
if (typeof selected !== "string" || !selected.trim()) return;
editPreferredExportPath.value = selected.trim();
}
+async function pickDamengClientBinDir() {
+ const { open } = await import("@tauri-apps/plugin-dialog");
+ const selected = await open({
+ directory: true,
+ multiple: false,
+ title: t("settings.damengClientBinDirChoose"),
+ defaultPath: editDamengClientBinDir.value.trim() || undefined,
+ });
+ if (typeof selected !== "string" || !selected.trim()) return;
+ editDamengClientBinDir.value = selected.trim();
+}
async function pickCustomSkillRoot() {
const { open } = await import("@tauri-apps/plugin-dialog");
@@ -9345,6 +9363,19 @@ onUnmounted(() => {
</div>
<p class="text-xs text-muted-foreground">{{ t("settings.preferredExportPathDescription") }}</p>
</div>
+ <div v-if="!isWeb" data-settings-search-id="data-dameng-client-bin-dir" :class="['space-y-2', settingsSearchTargetClass('data-dameng-client-bin-dir')]">
+ <Label for="dameng-client-bin-dir">{{ t("settings.damengClientBinDir") }}</Label>
+ <div class="flex items-center gap-2">
+ <Input id="dameng-client-bin-dir" v-model="editDamengClientBinDir" :placeholder="t('settings.damengClientBinDirPlaceholder')" class="h-9 flex-1 font-mono text-xs" />
+ <Button v-if="!isWeb" type="button" variant="outline" size="sm" class="h-9 shrink-0 px-2.5" :title="t('settings.damengClientBinDirChoose')" :aria-label="t('settings.damengClientBinDirChoose')" @click="pickDamengClientBinDir">
+ <FolderOpen class="h-4 w-4" />
+ </Button>
+ <Button v-if="editDamengClientBinDir" type="button" variant="ghost" size="sm" class="h-9 shrink-0 px-2" :title="t('settings.damengClientBinDirClear')" :aria-label="t('settings.damengClientBinDirClear')" @click="editDamengClientBinDir = ''">
+ <X class="h-4 w-4" />
+ </Button>
+ </div>
+ <p class="text-xs text-muted-foreground">{{ t("settings.damengClientBinDirDescription") }}</p>
+ </div>
<div v-if="!isWeb" data-settings-search-id="data-export-auto-open-folder" :class="['flex items-start justify-between gap-3', settingsSearchTargetClass('data-export-auto-open-folder')]">
<div class="space-y-0.5">
<Label for="export-auto-open-folder">{{ t("settings.autoOpenExportFolder") }}</Label>
diff --git a/apps/desktop/src/components/layout/AppDialogs.vue b/apps/desktop/src/components/layout/AppDialogs.vue
index 184f301ee6..5f31046c0b 100644
--- a/apps/desktop/src/components/layout/AppDialogs.vue
+++ b/apps/desktop/src/components/layout/AppDialogs.vue
@@ -17,6 +17,7 @@ const DataDictionaryDialog = defineAsyncComponent(() => import("@/components/doc
const TableImportDialog = defineAsyncComponent(() => import("@/components/import/TableImportDialog.vue"));
const MongoImportDialog = defineAsyncComponent(() => import("@/components/document/MongoImportDialog.vue"));
const MongoDatabaseDumpDialog = defineAsyncComponent(() => import("@/components/document/MongoDatabaseDumpDialog.vue"));
+const DamengDumpDialog = defineAsyncComponent(() => import("@/components/document/DamengDumpDialog.vue"));
const FieldLineageDialog = defineAsyncComponent(() => import("@/components/lineage/FieldLineageDialog.vue"));
const ConfigPassphraseDialog = defineAsyncComponent(() => import("@/components/config/ConfigPassphraseDialog.vue"));
const ConfigConnectionSelectDialog = defineAsyncComponent(() => import("@/components/config/ConfigConnectionSelectDialog.vue"));
@@ -307,6 +308,7 @@ watch(
:database="dialogs.mongoDatabaseDumpPrefillDatabase.value"
:mode="dialogs.mongoDatabaseDumpMode.value"
/>
+ <DamengDumpDialog v-if="dialogs.showDamengDumpDialog.value" v-model:open="dialogs.showDamengDumpDialog.value" :connection-id="dialogs.damengDumpPrefillConnectionId.value" :database="dialogs.damengDumpPrefillDatabase.value" :mode="dialogs.damengDumpMode.value" />
<DataGenerateDialog
v-if="dialogs.showTableDataGenerateDialog.value"
v-model:open="dialogs.showTableDataGenerateDialog.value"
diff --git a/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue b/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue
index af5b874881..047bf47426 100644
--- a/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue
+++ b/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue
@@ -33,6 +33,8 @@ import {
Plug,
Unplug,
Pin,
+ Package,
+ PackageOpen,
PlugZap,
ArrowRightLeft,
Download,
@@ -484,6 +486,7 @@ const { copyStructureAs, copyStructureDocText, copyStructurePreview, exportData,
const {
openAllDatabasesExport,
+ openDamengDump,
openDataCompare,
openDatabaseExport,
openDatabaseSearch,
@@ -6295,6 +6298,12 @@ function buildDatabaseSidebarMenu(context: SidebarMenuFactoryContext): boolean {
items.push({ sidebarActionId: "diff.title", label: t("diff.title"), action: openSchemaDiff, icon: ArrowRightLeft });
items.push({ sidebarActionId: "dataCompare.title", label: t("dataCompare.title"), action: openDataCompare, icon: ArrowRightLeft });
items.push({ sidebarActionId: "contextMenu.exportDatabase", label: t("contextMenu.exportDatabase"), action: openDatabaseExport, icon: Upload });
+ // Native dexp/dimp (.dmp) shortcut — Dameng only; the dialog guides the user
+ // to the client bin-dir setting when the tools are not installed.
+ if (currentDatabaseType() === "dameng") {
+ items.push({ sidebarActionId: "damengDump.menuExport", label: t("damengDump.menuExport"), action: () => openDamengDump("export"), icon: Package });
+ items.push({ sidebarActionId: "damengDump.menuImport", label: t("damengDump.menuImport"), action: () => openDamengDump("import"), icon: PackageOpen });
+ }
if (canOpenDataDictionary.value) {
items.push({ sidebarActionId: "dataDictionary.title", label: t("dataDictionary.title"), action: openDataDictionary, icon: FileText });
}
diff --git a/apps/desktop/src/composables/useDialogSources.ts b/apps/desktop/src/composables/useDialogSources.ts
index 6d05771c0e..e1a8e3b690 100644
--- a/apps/desktop/src/composables/useDialogSources.ts
+++ b/apps/desktop/src/composables/useDialogSources.ts
@@ -22,6 +22,10 @@ const showMongoDatabaseDumpDialog = ref(false);
const mongoDatabaseDumpPrefillConnectionId = ref("");
const mongoDatabaseDumpPrefillDatabase = ref("");
const mongoDatabaseDumpMode = ref<"dump" | "restore">("dump");
+const showDamengDumpDialog = ref(false);
+const damengDumpPrefillConnectionId = ref("");
+const damengDumpPrefillDatabase = ref("");
+const damengDumpMode = ref<"export" | "import">("export");
const showTableDataGenerateDialog = ref(false);
const tableDataGenerateSessionId = ref<string | null>(null);
const showFieldLineageDialog = ref(false);
@@ -329,6 +333,18 @@ export function useDialogSources() {
},
);
+ watch(
+ () => connectionStore.damengDumpSource,
+ (source) => {
+ if (!source) return;
+ damengDumpPrefillConnectionId.value = source.connectionId;
+ damengDumpPrefillDatabase.value = source.database;
+ damengDumpMode.value = source.mode;
+ showDamengDumpDialog.value = true;
+ connectionStore.damengDumpSource = null;
+ },
+ );
+
watch(
() => connectionStore.tableDataGenerateSource,
(v) => {
@@ -603,6 +619,10 @@ export function useDialogSources() {
mongoDatabaseDumpPrefillConnectionId,
mongoDatabaseDumpPrefillDatabase,
mongoDatabaseDumpMode,
+ showDamengDumpDialog,
+ damengDumpPrefillConnectionId,
+ damengDumpPrefillDatabase,
+ damengDumpMode,
showTableDataGenerateDialog,
tableDataGenerateSessionId,
showFieldLineageDialog,
diff --git a/apps/desktop/src/composables/useSidebarTreeToolRuntime.ts b/apps/desktop/src/composables/useSidebarTreeToolRuntime.ts
index 53a655d0a5..1a58af2cbf 100644
--- a/apps/desktop/src/composables/useSidebarTreeToolRuntime.ts
+++ b/apps/desktop/src/composables/useSidebarTreeToolRuntime.ts
@@ -174,6 +174,15 @@ export function useSidebarTreeToolRuntime(options: SidebarTreeToolRuntimeOptions
connectionStore.mongoDatabaseDumpSource = { connectionId: node.connectionId, database: node.database, mode };
}
+ function openDamengDump(mode: "export" | "import") {
+ const node = activeNode.value;
+ if ((node.type !== "database" && node.type !== "schema") || !node.connectionId || !node.database) return;
+ // For Dameng (single-database, schema-aware) the schema node's database
+ // field carries the schema name; plain database nodes use it directly.
+ const schema = node.type === "schema" && node.schema ? node.schema : node.database;
+ connectionStore.damengDumpSource = { connectionId: node.connectionId, database: schema, mode };
+ }
+
function openStructureEditor() {
const node = activeNode.value;
if (!node.connectionId || !node.database) return;
@@ -210,6 +219,7 @@ export function useSidebarTreeToolRuntime(options: SidebarTreeToolRuntimeOptions
return {
openAllDatabasesExport,
+ openDamengDump,
openDataCompare,
openDatabaseExport,
openDatabaseSearch,
diff --git a/apps/desktop/src/i18n/__tests__/backendErrors.spec.ts b/apps/desktop/src/i18n/__tests__/backendErrors.spec.ts
index 4cff70f46c..0f3109c3ba 100644
--- a/apps/desktop/src/i18n/__tests__/backendErrors.spec.ts
+++ b/apps/desktop/src/i18n/__tests__/backendErrors.spec.ts
@@ -215,6 +215,26 @@ const CASES: { name: string; message: string; key: string; params?: Record<strin
key: "auth.rateLimited",
params: { seconds: "42" },
},
+ {
+ name: "dameng native dump tool missing",
+ message: "[damengToolNotFound] Dameng client tool 'dexp' was not found in 'C:\\dm8\\bin'. Configure the Dameng client bin directory in Settings > Data.",
+ key: "damengDump.errors.toolNotFound",
+ },
+ {
+ name: "dameng native dump on a non-dameng connection",
+ message: "[damengConnectionRequired] Native dexp/dimp dump is only available for Dameng connections.",
+ key: "damengDump.errors.connectionRequired",
+ },
+ {
+ name: "dameng native dump without a stored password",
+ message: "[damengPasswordMissing] The connection has no password available; reconnect and enter the password first.",
+ key: "damengDump.errors.passwordMissing",
+ },
+ {
+ name: "dameng native dump with a userid-breaking credential",
+ message: "[damengUseridInvalid] The connection's password contains '/' or '@', which the dexp/dimp USERID argument cannot encode; the task was not started.",
+ key: "damengDump.errors.useridInvalid",
+ },
];
function translatorFor(locale: LocaleKey): BackendErrorTranslate {
diff --git a/apps/desktop/src/i18n/__tests__/damengDumpLocales.spec.ts b/apps/desktop/src/i18n/__tests__/damengDumpLocales.spec.ts
new file mode 100644
index 0000000000..df9327c49f
--- /dev/null
+++ b/apps/desktop/src/i18n/__tests__/damengDumpLocales.spec.ts
@@ -0,0 +1,26 @@
+import { describe, expect, it } from "vitest";
+import * as messages from "../locales/damengDump";
+
+function leaves(value: Record<string, unknown>, prefix = ""): Record<string, string> {
+ return Object.fromEntries(
+ Object.entries(value).flatMap(([key, child]) => {
+ const path = prefix ? `${prefix}.${key}` : key;
+ if (typeof child === "string") return [[path, child]];
+ return Object.entries(leaves(child as Record<string, unknown>, path));
+ }),
+ );
+}
+
+describe("Dameng dump translations", () => {
+ const source = leaves(messages.damengDumpEn);
+ for (const [locale, value] of Object.entries(messages)) {
+ it(`${locale} includes every key and preserves placeholders`, () => {
+ const translated = leaves(value);
+ expect(Object.keys(translated).sort()).toEqual(Object.keys(source).sort());
+ for (const [key, text] of Object.entries(translated)) {
+ expect(text.trim(), key).not.toBe("");
+ expect((text.match(/\{\w+\}/g) ?? []).sort(), key).toEqual((source[key]!.match(/\{\w+\}/g) ?? []).sort());
+ }
+ });
+ }
+});
diff --git a/apps/desktop/src/i18n/backend-errors.ts b/apps/desktop/src/i18n/backend-errors.ts
index 374d3913ba..11d9bc561e 100644
--- a/apps/desktop/src/i18n/backend-errors.ts
+++ b/apps/desktop/src/i18n/backend-errors.ts
@@ -172,6 +172,12 @@ const patterns: [RegExp, string][] = [
// Web auth rate limiting (crates/dbx-web/src/auth.rs)
[/^Please try again in (\d+)s$/, "auth.rateLimited"],
+
+ // Dameng native dexp/dimp dump (crates/dbx-core/src/data/dameng_dump.rs)
+ [/^\[damengToolNotFound\]/, "damengDump.errors.toolNotFound"],
+ [/^\[damengConnectionRequired\]/, "damengDump.errors.connectionRequired"],
+ [/^\[damengPasswordMissing\]/, "damengDump.errors.passwordMissing"],
+ [/^\[damengUseridInvalid\]/, "damengDump.errors.useridInvalid"],
];
// Named placeholders for each pattern's capture groups, in capture order.
diff --git a/apps/desktop/src/i18n/locales/az.ts b/apps/desktop/src/i18n/locales/az.ts
index 055cbb612d..0cb2fcbd7a 100644
--- a/apps/desktop/src/i18n/locales/az.ts
+++ b/apps/desktop/src/i18n/locales/az.ts
@@ -7972,6 +7972,11 @@ export default withEnglishFallback({
preferredExportPathPlaceholder: "Təyin edilməyib (son ixrac yolunu istifadə edin)",
preferredExportPathChoose: "Üstünlük verilən ixrac qovluğunu seçin",
preferredExportPathClear: "Üstünlük verilən ixrac yolunu təmizləyin",
+ damengClientBinDir: "Dameng klient bin qovluğu",
+ damengClientBinDirDescription: "Dameng klient alətləri dexp/dimp-i ehtiva edən qovluq; yerli .dmp ixracı/idxalı üçün istifadə olunur.",
+ damengClientBinDirPlaceholder: "məs. C:\\dm8\\bin",
+ damengClientBinDirChoose: "Dameng klient bin qovluğunu seçin",
+ damengClientBinDirClear: "Dameng klient bin qovluğunu təmizləyin",
autoOpenExportFolder: "İxracdan sonra qovluğu avtomatik aç",
autoOpenExportFolderDescription: "Məlumat ixracı uğurla başa çatdıqda fayl menecerində ixrac edilən faylın qovluğunu avtomatik açır.",
exportSection: "İxrac",
diff --git a/apps/desktop/src/i18n/locales/damengDump.ts b/apps/desktop/src/i18n/locales/damengDump.ts
new file mode 100644
index 0000000000..b39ba8ed37
--- /dev/null
+++ b/apps/desktop/src/i18n/locales/damengDump.ts
@@ -0,0 +1,375 @@
+export const damengDumpEn = {
+ menuExport: "Export as .dmp (native dexp)...",
+ menuImport: "Import from .dmp (native dimp)...",
+ exportTitle: "Dameng Native Export (dexp)",
+ importTitle: "Dameng Native Import (dimp)",
+ outputFile: "Output .dmp file",
+ inputFile: "Input .dmp file",
+ filePlaceholder: "Path to the .dmp file",
+ chooseFile: "Choose file",
+ schemas: "Schemas",
+ schemasHint: "Comma-separated schema names. Defaults to the selected schema.",
+ tables: "Tables (optional)",
+ tablesPlaceholder: "e.g. EMP,DEPT",
+ tablesHint: "Comma-separated table names to export; leave empty for the whole schema.",
+ remapFrom: "REMAP source schema",
+ remapFromPlaceholder: "Source schema",
+ remapTo: "REMAP target schema",
+ remapToPlaceholder: "Target schema",
+ tableExistsAction: "If table exists",
+ tableExistsHint: "How dimp handles tables that already exist in the target schema.",
+ tableExists: { SKIP: "Skip", REPLACE: "Drop and recreate", TRUNCATE: "Truncate", APPEND: "Append rows" },
+ passwordOnArgv: "Dameng requires the password on the dexp/dimp command line; it may be visible in the process list while the task runs.",
+ desktopOnly: "Native dexp/dimp export is only available in the desktop app.",
+ readonly: "This connection is read-only; import is disabled.",
+ binDirMissing: "Dameng client bin directory is not configured.",
+ binDirSettingHint: "Set the directory containing dexp/dimp under Settings → Data → Dameng client bin directory.",
+ running: "Running...",
+ done: "Completed",
+ cancelled: "Cancelled",
+ failed: "Failed",
+ elapsed: "Elapsed",
+ warnings: "Warnings",
+ warningsPresent: "Yes",
+ warningsNone: "No",
+ cancel: "Cancel task",
+ close: "Close",
+ back: "Back",
+ startExport: "Start export",
+ startImport: "Start import",
+ errors: {
+ toolNotFound: "Dameng client tools (dexp/dimp) were not found in the configured bin directory.",
+ connectionRequired: "Native dexp/dimp dump is only available for Dameng connections.",
+ passwordMissing: "The connection has no stored password; reconnect and enter the password first.",
+ useridInvalid: "The connection's username or password contains / or {'@'}, which the dexp/dimp USERID argument cannot encode; the task was not started.",
+ },
+};
+
+export const damengDumpZhCN = {
+ menuExport: "导出为 .dmp(达梦原生 dexp)...",
+ menuImport: "从 .dmp 导入(达梦原生 dimp)...",
+ exportTitle: "达梦原生导出(dexp)",
+ importTitle: "达梦原生导入(dimp)",
+ outputFile: "输出 .dmp 文件",
+ inputFile: "输入 .dmp 文件",
+ filePlaceholder: ".dmp 文件路径",
+ chooseFile: "选择文件",
+ schemas: "模式(Schema)",
+ schemasHint: "逗号分隔的模式名,默认为当前选中的模式。",
+ tables: "表(可选)",
+ tablesPlaceholder: "如 EMP,DEPT",
+ tablesHint: "逗号分隔的表名;留空则导出整个模式。",
+ remapFrom: "REMAP 源模式",
+ remapFromPlaceholder: "源模式",
+ remapTo: "REMAP 目标模式",
+ remapToPlaceholder: "目标模式",
+ tableExistsAction: "表已存在时",
+ tableExistsHint: "dimp 遇到目标模式中已存在的表时的处理方式。",
+ tableExists: { SKIP: "跳过", REPLACE: "删除并重建", TRUNCATE: "清空", APPEND: "追加数据" },
+ passwordOnArgv: "达梦要求密码出现在 dexp/dimp 命令行上;任务运行期间密码可能在进程列表中可见。",
+ desktopOnly: "达梦原生 dexp/dimp 导出仅在桌面端可用。",
+ readonly: "该连接处于只读模式,导入已禁用。",
+ binDirMissing: "尚未配置达梦客户端 bin 目录。",
+ binDirSettingHint: "请在 设置 → 数据 → 达梦客户端 bin 目录 中指定包含 dexp/dimp 的目录。",
+ running: "正在运行...",
+ done: "已完成",
+ cancelled: "已取消",
+ failed: "失败",
+ elapsed: "耗时",
+ warnings: "警告",
+ warningsPresent: "有",
+ warningsNone: "无",
+ cancel: "取消任务",
+ close: "关闭",
+ back: "返回",
+ startExport: "开始导出",
+ startImport: "开始导入",
+ errors: {
+ toolNotFound: "在配置的 bin 目录中未找到达梦客户端工具(dexp/dimp)。",
+ connectionRequired: "原生 dexp/dimp 导出仅支持达梦连接。",
+ passwordMissing: "该连接没有保存密码,请先重新连接并输入密码。",
+ useridInvalid: "连接的用户名或密码包含 / 或 {'@'},无法编码进 dexp/dimp 的 USERID 参数;任务未启动。",
+ },
+};
+
+export const damengDumpEs = {
+ menuExport: "Exportar como .dmp (dexp nativo)...",
+ menuImport: "Importar desde .dmp (dimp nativo)...",
+ exportTitle: "Exportación nativa de Dameng (dexp)",
+ importTitle: "Importación nativa de Dameng (dimp)",
+ outputFile: "Archivo .dmp de salida",
+ inputFile: "Archivo .dmp de entrada",
+ filePlaceholder: "Ruta del archivo .dmp",
+ chooseFile: "Elegir archivo",
+ schemas: "Esquemas",
+ schemasHint: "Nombres de esquemas separados por comas. Por defecto, el esquema seleccionado.",
+ tables: "Tablas (opcional)",
+ tablesPlaceholder: "p. ej. EMP,DEPT",
+ tablesHint: "Nombres de tablas separados por comas; deje vacío para todo el esquema.",
+ remapFrom: "Esquema de origen REMAP",
+ remapFromPlaceholder: "Esquema de origen",
+ remapTo: "Esquema de destino REMAP",
+ remapToPlaceholder: "Esquema de destino",
+ tableExistsAction: "Si la tabla existe",
+ tableExistsHint: "Cómo dimp maneja las tablas que ya existen en el esquema de destino.",
+ tableExists: { SKIP: "Omitir", REPLACE: "Eliminar y recrear", TRUNCATE: "Truncar", APPEND: "Añadir filas" },
+ passwordOnArgv: "Dameng requiere la contraseña en la línea de comandos de dexp/dimp; puede ser visible en la lista de procesos mientras la tarea se ejecuta.",
+ desktopOnly: "La exportación nativa dexp/dimp solo está disponible en la aplicación de escritorio.",
+ readonly: "Esta conexión es de solo lectura; la importación está desactivada.",
+ binDirMissing: "No se ha configurado el directorio bin del cliente de Dameng.",
+ binDirSettingHint: "Establezca el directorio que contiene dexp/dimp en Configuración → Datos → Directorio bin del cliente de Dameng.",
+ running: "Ejecutando...",
+ done: "Completado",
+ cancelled: "Cancelado",
+ failed: "Error",
+ elapsed: "Tiempo transcurrido",
+ warnings: "Advertencias",
+ warningsPresent: "Sí",
+ warningsNone: "No",
+ cancel: "Cancelar tarea",
+ close: "Cerrar",
+ back: "Volver",
+ startExport: "Iniciar exportación",
+ startImport: "Iniciar importación",
+ errors: {
+ toolNotFound: "No se encontraron las herramientas del cliente de Dameng (dexp/dimp) en el directorio bin configurado.",
+ connectionRequired: "La exportación nativa dexp/dimp solo está disponible para conexiones de Dameng.",
+ passwordMissing: "La conexión no tiene contraseña guardada; reconéctese e introduzca la contraseña primero.",
+ useridInvalid: "El nombre de usuario o la contraseña de la conexión contiene / o {'@'}, que el argumento USERID de dexp/dimp no puede codificar; la tarea no se inició.",
+ },
+};
+
+export const damengDumpIt = {
+ menuExport: "Esporta come .dmp (dexp nativo)...",
+ menuImport: "Importa da .dmp (dimp nativo)...",
+ exportTitle: "Esportazione nativa Dameng (dexp)",
+ importTitle: "Importazione nativa Dameng (dimp)",
+ outputFile: "File .dmp di output",
+ inputFile: "File .dmp di input",
+ filePlaceholder: "Percorso del file .dmp",
+ chooseFile: "Scegli file",
+ schemas: "Schema",
+ schemasHint: "Nomi di schema separati da virgole. Predefinito: lo schema selezionato.",
+ tables: "Tabelle (facoltativo)",
+ tablesPlaceholder: "es. EMP,DEPT",
+ tablesHint: "Nomi di tabelle separati da virgole; lascia vuoto per l'intero schema.",
+ remapFrom: "Schema di origine REMAP",
+ remapFromPlaceholder: "Schema di origine",
+ remapTo: "Schema di destinazione REMAP",
+ remapToPlaceholder: "Schema di destinazione",
+ tableExistsAction: "Se la tabella esiste",
+ tableExistsHint: "Come dimp gestisce le tabelle già presenti nello schema di destinazione.",
+ tableExists: { SKIP: "Salta", REPLACE: "Elimina e ricrea", TRUNCATE: "Svuota", APPEND: "Aggiungi righe" },
+ passwordOnArgv: "Dameng richiede la password sulla riga di comando di dexp/dimp; potrebbe essere visibile nell'elenco dei processi mentre l'attività è in esecuzione.",
+ desktopOnly: "L'esportazione nativa dexp/dimp è disponibile solo nell'app desktop.",
+ readonly: "Questa connessione è di sola lettura; l'importazione è disabilitata.",
+ binDirMissing: "La directory bin del client Dameng non è configurata.",
+ binDirSettingHint: "Imposta la directory contenente dexp/dimp in Impostazioni → Dati → Directory bin del client Dameng.",
+ running: "Esecuzione in corso...",
+ done: "Completato",
+ cancelled: "Annullato",
+ failed: "Non riuscito",
+ elapsed: "Tempo trascorso",
+ warnings: "Avvisi",
+ warningsPresent: "Sì",
+ warningsNone: "No",
+ cancel: "Annulla attività",
+ close: "Chiudi",
+ back: "Indietro",
+ startExport: "Avvia esportazione",
+ startImport: "Avvia importazione",
+ errors: {
+ toolNotFound: "Strumenti del client Dameng (dexp/dimp) non trovati nella directory bin configurata.",
+ connectionRequired: "L'esportazione nativa dexp/dimp è disponibile solo per le connessioni Dameng.",
+ passwordMissing: "La connessione non ha una password salvata; riconnettiti e inserisci prima la password.",
+ useridInvalid: "Il nome utente o la password della connessione contiene / o {'@'}, che l'argomento USERID di dexp/dimp non può codificare; l'attività non è stata avviata.",
+ },
+};
+
+export const damengDumpJa = {
+ menuExport: "ネイティブ dexp で .dmp にエクスポート...",
+ menuImport: "ネイティブ dimp で .dmp からインポート...",
+ exportTitle: "Dameng ネイティブエクスポート(dexp)",
+ importTitle: "Dameng ネイティブインポート(dimp)",
+ outputFile: "出力 .dmp ファイル",
+ inputFile: "入力 .dmp ファイル",
+ filePlaceholder: ".dmp ファイルのパス",
+ chooseFile: "ファイルを選択",
+ schemas: "スキーマ",
+ schemasHint: "カンマ区切りのスキーマ名。既定は選択中のスキーマです。",
+ tables: "テーブル(任意)",
+ tablesPlaceholder: "例: EMP,DEPT",
+ tablesHint: "エクスポートするテーブル名をカンマ区切りで指定。空欄ならスキーマ全体。",
+ remapFrom: "REMAP 元スキーマ",
+ remapFromPlaceholder: "元スキーマ",
+ remapTo: "REMAP 先スキーマ",
+ remapToPlaceholder: "先スキーマ",
+ tableExistsAction: "テーブルが存在する場合",
+ tableExistsHint: "dimp が先スキーマに既に存在するテーブルをどう処理するか。",
+ tableExists: { SKIP: "スキップ", REPLACE: "削除して再作成", TRUNCATE: "全削除", APPEND: "行を追加" },
+ passwordOnArgv: "Dameng は dexp/dimp のコマンドラインにパスワードを必要とします。タスク実行中はプロセス一覧に表示される可能性があります。",
+ desktopOnly: "ネイティブ dexp/dimp エクスポートはデスクトップアプリでのみ利用できます。",
+ readonly: "この接続は読み取り専用のため、インポートは無効です。",
+ binDirMissing: "Dameng クライアントの bin ディレクトリが設定されていません。",
+ binDirSettingHint: "設定 → データ → Dameng クライアント bin ディレクトリ で dexp/dimp を含むディレクトリを指定してください。",
+ running: "実行中...",
+ done: "完了",
+ cancelled: "キャンセル済み",
+ failed: "失敗",
+ elapsed: "経過時間",
+ warnings: "警告",
+ warningsPresent: "あり",
+ warningsNone: "なし",
+ cancel: "タスクをキャンセル",
+ close: "閉じる",
+ back: "戻る",
+ startExport: "エクスポート開始",
+ startImport: "インポート開始",
+ errors: {
+ toolNotFound: "設定された bin ディレクトリに Dameng クライアントツール(dexp/dimp)が見つかりません。",
+ connectionRequired: "ネイティブ dexp/dimp エクスポートは Dameng 接続でのみ利用できます。",
+ passwordMissing: "接続に保存されたパスワードがありません。先に再接続してパスワードを入力してください。",
+ useridInvalid: "接続のユーザー名またはパスワードに / または {'@'} が含まれており、dexp/dimp の USERID 引数としてエンコードできません。タスクは開始されませんでした。",
+ },
+};
+
+export const damengDumpKo = {
+ menuExport: "네이티브 dexp로 .dmp 내보내기...",
+ menuImport: "네이티브 dimp로 .dmp에서 가져오기...",
+ exportTitle: "Dameng 네이티브 내보내기 (dexp)",
+ importTitle: "Dameng 네이티브 가져오기 (dimp)",
+ outputFile: "출력 .dmp 파일",
+ inputFile: "입력 .dmp 파일",
+ filePlaceholder: ".dmp 파일 경로",
+ chooseFile: "파일 선택",
+ schemas: "스키마",
+ schemasHint: "쉼표로 구분된 스키마 이름. 기본값은 선택한 스키마입니다.",
+ tables: "테이블(선택)",
+ tablesPlaceholder: "예: EMP,DEPT",
+ tablesHint: "내보낼 테이블 이름을 쉼표로 구분하여 지정. 비워 두면 스키마 전체.",
+ remapFrom: "REMAP 원본 스키마",
+ remapFromPlaceholder: "원본 스키마",
+ remapTo: "REMAP 대상 스키마",
+ remapToPlaceholder: "대상 스키마",
+ tableExistsAction: "테이블이 있는 경우",
+ tableExistsHint: "dimp가 대상 스키마에 이미 존재하는 테이블을 처리하는 방식.",
+ tableExists: { SKIP: "건너뛰기", REPLACE: "삭제 후 다시 생성", TRUNCATE: "비우기", APPEND: "행 추가" },
+ passwordOnArgv: "Dameng은 dexp/dimp 명령줄에 비밀번호가 필요합니다. 작업 실행 중 프로세스 목록에 표시될 수 있습니다.",
+ desktopOnly: "네이티브 dexp/dimp 내보내기는 데스크톱 앱에서만 사용할 수 있습니다.",
+ readonly: "이 연결은 읽기 전용이므로 가져오기가 비활성화되었습니다.",
+ binDirMissing: "Dameng 클라이언트 bin 디렉터리가 구성되지 않았습니다.",
+ binDirSettingHint: "설정 → 데이터 → Dameng 클라이언트 bin 디렉터리에서 dexp/dimp가 있는 디렉터리를 지정하세요.",
+ running: "실행 중...",
+ done: "완료",
+ cancelled: "취소됨",
+ failed: "실패",
+ elapsed: "경과 시간",
+ warnings: "경고",
+ warningsPresent: "있음",
+ warningsNone: "없음",
+ cancel: "작업 취소",
+ close: "닫기",
+ back: "뒤로",
+ startExport: "내보내기 시작",
+ startImport: "가져오기 시작",
+ errors: {
+ toolNotFound: "구성된 bin 디렉터리에서 Dameng 클라이언트 도구(dexp/dimp)를 찾을 수 없습니다.",
+ connectionRequired: "네이티브 dexp/dimp 내보내기는 Dameng 연결에서만 사용할 수 있습니다.",
+ passwordMissing: "연결에 저장된 비밀번호가 없습니다. 먼저 다시 연결하여 비밀번호를 입력하세요.",
+ useridInvalid: "연결의 사용자 이름 또는 비밀번호에 / 또는 {'@'}가 포함되어 있어 dexp/dimp의 USERID 인수로 인코딩할 수 없습니다. 작업이 시작되지 않았습니다.",
+ },
+};
+
+export const damengDumpPtBR = {
+ menuExport: "Exportar como .dmp (dexp nativo)...",
+ menuImport: "Importar de .dmp (dimp nativo)...",
+ exportTitle: "Exportação nativa do Dameng (dexp)",
+ importTitle: "Importação nativa do Dameng (dimp)",
+ outputFile: "Arquivo .dmp de saída",
+ inputFile: "Arquivo .dmp de entrada",
+ filePlaceholder: "Caminho do arquivo .dmp",
+ chooseFile: "Escolher arquivo",
+ schemas: "Esquemas",
+ schemasHint: "Nomes de esquemas separados por vírgulas. Padrão: o esquema selecionado.",
+ tables: "Tabelas (opcional)",
+ tablesPlaceholder: "ex.: EMP,DEPT",
+ tablesHint: "Nomes de tabelas separados por vírgulas; deixe vazio para o esquema inteiro.",
+ remapFrom: "Esquema de origem REMAP",
+ remapFromPlaceholder: "Esquema de origem",
+ remapTo: "Esquema de destino REMAP",
+ remapToPlaceholder: "Esquema de destino",
+ tableExistsAction: "Se a tabela existir",
+ tableExistsHint: "Como o dimp trata tabelas que já existem no esquema de destino.",
+ tableExists: { SKIP: "Ignorar", REPLACE: "Excluir e recriar", TRUNCATE: "Esvaziar", APPEND: "Acrescentar linhas" },
+ passwordOnArgv: "O Dameng exige a senha na linha de comando do dexp/dimp; ela pode ficar visível na lista de processos enquanto a tarefa estiver em execução.",
+ desktopOnly: "A exportação nativa dexp/dimp está disponível apenas no aplicativo desktop.",
+ readonly: "Esta conexão é somente leitura; a importação está desativada.",
+ binDirMissing: "O diretório bin do cliente Dameng não está configurado.",
+ binDirSettingHint: "Defina o diretório contendo dexp/dimp em Configurações → Dados → Diretório bin do cliente Dameng.",
+ running: "Executando...",
+ done: "Concluído",
+ cancelled: "Cancelado",
+ failed: "Falhou",
+ elapsed: "Tempo decorrido",
+ warnings: "Avisos",
+ warningsPresent: "Sim",
+ warningsNone: "Não",
+ cancel: "Cancelar tarefa",
+ close: "Fechar",
+ back: "Voltar",
+ startExport: "Iniciar exportação",
+ startImport: "Iniciar importação",
+ errors: {
+ toolNotFound: "Ferramentas do cliente Dameng (dexp/dimp) não foram encontradas no diretório bin configurado.",
+ connectionRequired: "A exportação nativa dexp/dimp está disponível apenas para conexões Dameng.",
+ passwordMissing: "A conexão não tem senha salva; reconecte-se e insira a senha primeiro.",
+ useridInvalid: "O nome de usuário ou a senha da conexão contém / ou {'@'}, que o argumento USERID do dexp/dimp não consegue codificar; a tarefa não foi iniciada.",
+ },
+};
+
+export const damengDumpZhTW = {
+ menuExport: "匯出為 .dmp(達夢原生 dexp)...",
+ menuImport: "從 .dmp 匯入(達夢原生 dimp)...",
+ exportTitle: "達夢原生匯出(dexp)",
+ importTitle: "達夢原生匯入(dimp)",
+ outputFile: "輸出 .dmp 檔案",
+ inputFile: "輸入 .dmp 檔案",
+ filePlaceholder: ".dmp 檔案路徑",
+ chooseFile: "選擇檔案",
+ schemas: "綱要(Schema)",
+ schemasHint: "以逗號分隔的綱要名稱,預設為目前選取的綱要。",
+ tables: "資料表(可選)",
+ tablesPlaceholder: "如 EMP,DEPT",
+ tablesHint: "以逗號分隔的資料表名稱;留空則匯出整個綱要。",
+ remapFrom: "REMAP 來源綱要",
+ remapFromPlaceholder: "來源綱要",
+ remapTo: "REMAP 目標綱要",
+ remapToPlaceholder: "目標綱要",
+ tableExistsAction: "資料表已存在時",
+ tableExistsHint: "dimp 遇到目標綱要中已存在的資料表時的處理方式。",
+ tableExists: { SKIP: "跳過", REPLACE: "刪除並重建", TRUNCATE: "清空", APPEND: "附加資料" },
+ passwordOnArgv: "達夢要求密碼出現在 dexp/dimp 命令列上;任務執行期間密碼可能在處理程序清單中可見。",
+ desktopOnly: "達夢原生 dexp/dimp 匯出僅在桌面應用程式可用。",
+ readonly: "此連線處於唯讀模式,匯入已停用。",
+ binDirMissing: "尚未設定達夢用戶端 bin 目錄。",
+ binDirSettingHint: "請在 設定 → 資料 → 達夢用戶端 bin 目錄 中指定包含 dexp/dimp 的目錄。",
+ running: "正在執行...",
+ done: "已完成",
+ cancelled: "已取消",
+ failed: "失敗",
+ elapsed: "耗時",
+ warnings: "警告",
+ warningsPresent: "有",
+ warningsNone: "無",
+ cancel: "取消任務",
+ close: "關閉",
+ back: "返回",
+ startExport: "開始匯出",
+ startImport: "開始匯入",
+ errors: {
+ toolNotFound: "在設定的 bin 目錄中未找到達夢用戶端工具(dexp/dimp)。",
+ connectionRequired: "原生 dexp/dimp 匯出僅支援達夢連線。",
+ passwordMissing: "該連線沒有儲存密碼,請先重新連線並輸入密碼。",
+ useridInvalid: "連線的使用者名稱或密碼包含 / 或 {'@'},無法編碼進 dexp/dimp 的 USERID 參數;任務未啟動。",
+ },
+};
diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.ts
index 62d1a6d55e..1a3379b68d 100644
--- a/apps/desktop/src/i18n/locales/en.ts
+++ b/apps/desktop/src/i18n/locales/en.ts
@@ -6,6 +6,7 @@ import { consulUiMessages } from "./consulUi";
import { sqlServerTraceMessages as sqlServerTrace } from "./sqlServerTraceMessages";
import { meilisearchManagementEn } from "./meilisearchManagement";
import { mongodbDatabaseDumpEn as mongoDump } from "./mongodbDatabaseDump";
+import { damengDumpEn as damengDump } from "./damengDump";
const consul = {
...consulUiMessages,
@@ -6603,6 +6604,7 @@ export default {
},
},
mongoDump,
+ damengDump,
mongo: {
documents: "{count} documents",
addField: "Add Field",
@@ -9100,6 +9102,11 @@ export default {
preferredExportPathPlaceholder: "Not set (use last export path)",
preferredExportPathChoose: "Choose preferred export directory",
preferredExportPathClear: "Clear preferred export path",
+ damengClientBinDir: "Dameng client bin directory",
+ damengClientBinDirDescription: "Directory that contains the Dameng client tools dexp/dimp, used by the native .dmp export/import.",
+ damengClientBinDirPlaceholder: "e.g. C:\\dm8\\bin",
+ damengClientBinDirChoose: "Choose Dameng client bin directory",
+ damengClientBinDirClear: "Clear Dameng client bin directory",
autoOpenExportFolder: "Auto-open folder after export",
autoOpenExportFolderDescription: "Automatically reveal and open the containing folder in the file manager after data export succeeds.",
exportSection: "Export",
diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.ts
index 52e8d38bb3..0283dd5327 100644
--- a/apps/desktop/src/i18n/locales/es.ts
+++ b/apps/desktop/src/i18n/locales/es.ts
@@ -1,6 +1,7 @@
import { sidebarMenuEs as sidebarMenu } from "./sidebarMenuMessages";
import { withEnglishFallback } from "./fallback";
import { mongodbDatabaseDumpEs as mongoDump } from "./mongodbDatabaseDump";
+import { damengDumpEs as damengDump } from "./damengDump";
import { meilisearchManagementEs } from "./meilisearchManagement";
import { redisGroupingEs as redisGrouping } from "./redisGrouping";
import docs from "./docs/es";
@@ -112,6 +113,7 @@ export default withEnglishFallback({
updateFailed: "No se pudo actualizar la propiedad.",
},
mongoDump,
+ damengDump,
cellTransform: {
title: "Vista previa de conversión",
description: "Convierte el valor actual para verlo o copiarlo. El valor original y el borrador no cambian.",
@@ -8317,6 +8319,11 @@ export default withEnglishFallback({
preferredExportPathPlaceholder: "No establecido (usar última ruta)",
preferredExportPathChoose: "Elegir directorio de exportación preferido",
preferredExportPathClear: "Borrar ruta de exportación preferida",
+ damengClientBinDir: "Directorio bin del cliente de Dameng",
+ damengClientBinDirDescription: "Directorio que contiene las herramientas del cliente de Dameng dexp/dimp, usado por la exportación/importación nativa .dmp.",
+ damengClientBinDirPlaceholder: "p. ej. C:\\dm8\\bin",
+ damengClientBinDirChoose: "Elegir directorio bin del cliente de Dameng",
+ damengClientBinDirClear: "Borrar directorio bin del cliente de Dameng",
autoOpenExportFolder: "Abrir carpeta automáticamente después de exportar",
autoOpenExportFolderDescription: "Abre y muestra automáticamente la carpeta que contiene el archivo exportado en el administrador de archivos tras completarse la exportación.",
exportSection: "Exportar",
diff --git a/apps/desktop/src/i18n/locales/id.ts b/apps/desktop/src/i18n/locales/id.ts
index 6ec0b5fece..b959628334 100644
--- a/apps/desktop/src/i18n/locales/id.ts
+++ b/apps/desktop/src/i18n/locales/id.ts
@@ -8784,6 +8784,11 @@ export default withEnglishFallback({
preferredExportPathPlaceholder: "Belum diatur (gunakan jalur ekspor terakhir)",
preferredExportPathChoose: "Pilih direktori ekspor pilihan",
preferredExportPathClear: "Hapus jalur ekspor pilihan",
+ damengClientBinDir: "Direktori bin klien Dameng",
+ damengClientBinDirDescription: "Direktori yang berisi alat klien Dameng dexp/dimp, digunakan untuk ekspor/impor .dmp native.",
+ damengClientBinDirPlaceholder: "mis. C:\\dm8\\bin",
+ damengClientBinDirChoose: "Pilih direktori bin klien Dameng",
+ damengClientBinDirClear: "Hapus direktori bin klien Dameng",
autoOpenExportFolder: "Buka folder otomatis setelah ekspor",
autoOpenExportFolderDescription: "Buka dan tampilkan folder yang berisi berkas hasil ekspor secara otomatis di pengelola berkas setelah ekspor data berhasil.",
exportSection: "Ekspor",
diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.ts
index 1285fb721c..4249b84ce6 100644
--- a/apps/desktop/src/i18n/locales/it.ts
+++ b/apps/desktop/src/i18n/locales/it.ts
@@ -1,6 +1,7 @@
import { sidebarMenuIt as sidebarMenu } from "./sidebarMenuMessages";
import { withEnglishFallback } from "./fallback";
import { mongodbDatabaseDumpIt as mongoDump } from "./mongodbDatabaseDump";
+import { damengDumpIt as damengDump } from "./damengDump";
import { meilisearchManagementIt } from "./meilisearchManagement";
import docs from "./docs/it";
import { dataDictionaryIt as dataDictionary } from "./dataDictionaryMessages";
@@ -110,6 +111,7 @@ export default withEnglishFallback({
updateFailed: "Impossibile aggiornare la proprietà.",
},
mongoDump,
+ damengDump,
cellTransform: {
title: "Anteprima conversione",
description: "Converte il valore corrente per visualizzarlo o copiarlo. Il valore originale e la bozza restano invariati.",
@@ -8080,6 +8082,11 @@ export default withEnglishFallback({
preferredExportPathPlaceholder: "Non impostato (usa l'ultimo percorso)",
preferredExportPathChoose: "Scegli la directory di esportazione preferita",
preferredExportPathClear: "Cancella il percorso di esportazione preferito",
+ damengClientBinDir: "Directory bin del client Dameng",
+ damengClientBinDirDescription: "Directory che contiene gli strumenti del client Dameng dexp/dimp, usata dall'esportazione/importazione nativa .dmp.",
+ damengClientBinDirPlaceholder: "es. C:\\dm8\\bin",
+ damengClientBinDirChoose: "Scegli directory bin del client Dameng",
+ damengClientBinDirClear: "Cancella directory bin del client Dameng",
autoOpenExportFolder: "Apri cartella automaticamente dopo l'esportazione",
autoOpenExportFolderDescription: "Apre e mostra automaticamente la cartella contenente il file esportato nel file manager dopo il completamento dell'esportazione.",
exportSection: "Esportazione",
diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.ts
index 010d45a028..aba97ddb99 100644
--- a/apps/desktop/src/i18n/locales/ja.ts
+++ b/apps/desktop/src/i18n/locales/ja.ts
@@ -1,6 +1,7 @@
import { sidebarMenuJa as sidebarMenu } from "./sidebarMenuMessages";
import { withEnglishFallback } from "./fallback";
import { mongodbDatabaseDumpJa as mongoDump } from "./mongodbDatabaseDump";
+import { damengDumpJa as damengDump } from "./damengDump";
import docs from "./docs/ja";
import { dataDictionaryJa as dataDictionary } from "./dataDictionaryMessages";
import { consulJaMessages } from "./consulJa";
@@ -111,6 +112,7 @@ export default withEnglishFallback({
updateFailed: "プロパティを更新できませんでした。",
},
mongoDump,
+ damengDump,
cellTransform: {
title: "変換プレビュー",
description: "現在の値を変換して表示またはコピーします。元の値と編集中の内容は変更されません。",
@@ -8070,6 +8072,11 @@ export default withEnglishFallback({
preferredExportPathPlaceholder: "未設定(前回のパスを使用)",
preferredExportPathChoose: "優先エクスポートディレクトリを選択",
preferredExportPathClear: "優先エクスポートパスをクリア",
+ damengClientBinDir: "Dameng クライアント bin ディレクトリ",
+ damengClientBinDirDescription: "Dameng クライアントツール dexp/dimp を含むディレクトリ。ネイティブ .dmp エクスポート/インポートで使用されます。",
+ damengClientBinDirPlaceholder: "例: C:\\dm8\\bin",
+ damengClientBinDirChoose: "Dameng クライアント bin ディレクトリを選択",
+ damengClientBinDirClear: "Dameng クライアント bin ディレクトリをクリア",
autoOpenExportFolder: "エクスポート後に保存先フォルダーを開く",
autoOpenExportFolderDescription: "データエクスポート完了後、ファイルマネージャーで保存先フォルダーを自動的に開きます。",
exportSection: "エクスポート",
diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.ts
index b9ffeb1f9b..d1af6342cf 100644
--- a/apps/desktop/src/i18n/locales/ko.ts
+++ b/apps/desktop/src/i18n/locales/ko.ts
@@ -1,6 +1,7 @@
import { sidebarMenuKo as sidebarMenu } from "./sidebarMenuMessages";
import { withEnglishFallback } from "./fallback";
import { mongodbDatabaseDumpKo as mongoDump } from "./mongodbDatabaseDump";
+import { damengDumpKo as damengDump } from "./damengDump";
import { meilisearchManagementKo } from "./meilisearchManagement";
import docs from "./docs/ko";
import { dataDictionaryKo as dataDictionary } from "./dataDictionaryMessages";
@@ -110,6 +111,7 @@ export default withEnglishFallback({
updateFailed: "속성을 업데이트하지 못했습니다.",
},
mongoDump,
+ damengDump,
cellTransform: {
title: "변환 미리보기",
description: "현재 값을 변환하여 보거나 복사합니다. 원래 값과 편집 초안은 변경되지 않습니다.",
@@ -7961,6 +7963,11 @@ export default withEnglishFallback({
preferredExportPathPlaceholder: "설정되지 않음 (마지막 내보내기 경로 사용)",
preferredExportPathChoose: "기본 내보내기 디렉터리 선택",
preferredExportPathClear: "기본 내보내기 경로 지우기",
+ damengClientBinDir: "Dameng 클라이언트 bin 디렉터리",
+ damengClientBinDirDescription: "Dameng 클라이언트 도구 dexp/dimp가 있는 디렉터리. 네이티브 .dmp 내보내기/가져오기에 사용됩니다.",
+ damengClientBinDirPlaceholder: "예: C:\\dm8\\bin",
+ damengClientBinDirChoose: "Dameng 클라이언트 bin 디렉터리 선택",
+ damengClientBinDirClear: "Dameng 클라이언트 bin 디렉터리 지우기",
autoOpenExportFolder: "내보내기 후 폴더 자동 열기",
autoOpenExportFolderDescription: "데이터 내보내기가 완료된 후 파일 관리자에서 저장된 폴더를 자동으로 엽니다.",
exportSection: "내보내기",
diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.ts
index 78145a3bd6..a6e9154e41 100644
--- a/apps/desktop/src/i18n/locales/pt-BR.ts
+++ b/apps/desktop/src/i18n/locales/pt-BR.ts
@@ -1,6 +1,7 @@
import { sidebarMenuPtBR as sidebarMenu } from "./sidebarMenuMessages";
import { withEnglishFallback } from "./fallback";
import { mongodbDatabaseDumpPtBR as mongoDump } from "./mongodbDatabaseDump";
+import { damengDumpPtBR as damengDump } from "./damengDump";
import { meilisearchManagementPtBR } from "./meilisearchManagement";
import docs from "./docs/pt-BR";
import { dataDictionaryPtBR as dataDictionary } from "./dataDictionaryMessages";
@@ -111,6 +112,7 @@ export default withEnglishFallback({
updateFailed: "Não foi possível atualizar a propriedade.",
},
mongoDump,
+ damengDump,
cellTransform: {
title: "Prévia da conversão",
description: "Converte o valor atual para visualizar ou copiar. O valor original e o rascunho permanecem inalterados.",
@@ -8078,6 +8080,11 @@ export default withEnglishFallback({
preferredExportPathPlaceholder: "Não definido (usar último caminho)",
preferredExportPathChoose: "Escolher diretório de exportação preferencial",
preferredExportPathClear: "Limpar caminho de exportação preferencial",
+ damengClientBinDir: "Diretório bin do cliente Dameng",
+ damengClientBinDirDescription: "Diretório que contém as ferramentas do cliente Dameng dexp/dimp, usado pela exportação/importação nativa .dmp.",
+ damengClientBinDirPlaceholder: "ex.: C:\\dm8\\bin",
+ damengClientBinDirChoose: "Escolher diretório bin do cliente Dameng",
+ damengClientBinDirClear: "Limpar diretório bin do cliente Dameng",
autoOpenExportFolder: "Abrir pasta automaticamente após exportar",
autoOpenExportFolderDescription: "Abre e revela automaticamente a pasta que contém o arquivo exportado no gerenciador de arquivos após a conclusão da exportação.",
exportSection: "Exportar",
diff --git a/apps/desktop/src/i18n/locales/ru.ts b/apps/desktop/src/i18n/locales/ru.ts
index 1abf86910a..2690146274 100644
--- a/apps/desktop/src/i18n/locales/ru.ts
+++ b/apps/desktop/src/i18n/locales/ru.ts
@@ -6975,6 +6975,52 @@ export default withEnglishFallback({
done: "Завершено",
},
},
+ damengDump: {
+ menuExport: "Экспорт в .dmp (нативный dexp)...",
+ menuImport: "Импорт из .dmp (нативный dimp)...",
+ exportTitle: "Нативный экспорт Dameng (dexp)",
+ importTitle: "Нативный импорт Dameng (dimp)",
+ outputFile: "Выходной файл .dmp",
+ inputFile: "Входной файл .dmp",
+ filePlaceholder: "Путь к файлу .dmp",
+ chooseFile: "Выбрать файл",
+ schemas: "Схемы",
+ schemasHint: "Имена схем через запятую. По умолчанию — выбранная схема.",
+ tables: "Таблицы (необязательно)",
+ tablesPlaceholder: "напр. EMP,DEPT",
+ tablesHint: "Имена таблиц через запятую; пусто — вся схема.",
+ remapFrom: "Схема-источник REMAP",
+ remapFromPlaceholder: "Схема-источник",
+ remapTo: "Целевая схема REMAP",
+ remapToPlaceholder: "Целевая схема",
+ tableExistsAction: "Если таблица существует",
+ tableExistsHint: "Как dimp обрабатывает таблицы, уже существующие в целевой схеме.",
+ tableExists: { SKIP: "Пропустить", REPLACE: "Удалить и создать заново", TRUNCATE: "Очистить", APPEND: "Дополнить строки" },
+ passwordOnArgv: "Dameng требует пароль в командной строке dexp/dimp; во время работы задачи он может быть виден в списке процессов.",
+ desktopOnly: "Нативный экспорт dexp/dimp доступен только в настольном приложении.",
+ readonly: "Это подключение доступно только для чтения; импорт отключён.",
+ binDirMissing: "Каталог bin клиентов Dameng не настроен.",
+ binDirSettingHint: "Укажите каталог с dexp/dimp в Настройки → Данные → Каталог bin клиентов Dameng.",
+ running: "Выполняется...",
+ done: "Завершено",
+ cancelled: "Отменено",
+ failed: "Ошибка",
+ elapsed: "Затрачено времени",
+ warnings: "Предупреждения",
+ warningsPresent: "Есть",
+ warningsNone: "Нет",
+ cancel: "Отменить задачу",
+ close: "Закрыть",
+ back: "Назад",
+ startExport: "Начать экспорт",
+ startImport: "Начать импорт",
+ errors: {
+ toolNotFound: "Инструменты клиентов Dameng (dexp/dimp) не найдены в настроенном каталоге bin.",
+ connectionRequired: "Нативный экспорт dexp/dimp доступен только для подключений Dameng.",
+ passwordMissing: "У подключения нет сохранённого пароля; сначала переподключитесь и введите пароль.",
+ useridInvalid: "Имя пользователя или пароль подключения содержит / или {'@'}, что нельзя закодировать в аргументе USERID dexp/dimp; задача не была запущена.",
+ },
+ },
mongo: {
documents: "Документов: {count}",
addField: "Добавить поле",
@@ -9391,6 +9437,11 @@ export default withEnglishFallback({
preferredExportPathPlaceholder: "Не задан (использовать последний путь)",
preferredExportPathChoose: "Выбрать предпочтительный каталог экспорта",
preferredExportPathClear: "Очистить предпочтительный путь экспорта",
+ damengClientBinDir: "Каталог bin клиентов Dameng",
+ damengClientBinDirDescription: "Каталог с инструментами клиентов Dameng dexp/dimp; используется для нативного экспорта/импорта .dmp.",
+ damengClientBinDirPlaceholder: "напр. C:\\dm8\\bin",
+ damengClientBinDirChoose: "Выбрать каталог bin клиентов Dameng",
+ damengClientBinDirClear: "Очистить каталог bin клиентов Dameng",
autoOpenExportFolder: "Автоматически открывать папку после экспорта",
autoOpenExportFolderDescription: "Автоматически открывать папку с экспортированным файлом в файловом менеджере после завершения экспорта данных.",
exportSection: "Экспорт",
diff --git a/apps/desktop/src/i18n/locales/tr.ts b/apps/desktop/src/i18n/locales/tr.ts
index 306c697ab8..d72ffcce81 100644
--- a/apps/desktop/src/i18n/locales/tr.ts
+++ b/apps/desktop/src/i18n/locales/tr.ts
@@ -7874,6 +7874,11 @@ export default withEnglishFallback({
preferredExportPathPlaceholder: "Ayarlanmadı (son dışa aktarma yolunu kullan)",
preferredExportPathChoose: "Tercih edilen dışa aktarma dizinini seçin",
preferredExportPathClear: "Tercih edilen dışa aktarma yolunu temizle",
+ damengClientBinDir: "Dameng istemci bin dizini",
+ damengClientBinDirDescription: "Dameng istemci araçları dexp/dimp içeren dizin; yerel .dmp dışa/içe aktarımında kullanılır.",
+ damengClientBinDirPlaceholder: "örn. C:\\dm8\\bin",
+ damengClientBinDirChoose: "Dameng istemci bin dizinini seç",
+ damengClientBinDirClear: "Dameng istemci bin dizinini temizle",
autoOpenExportFolder: "Dışa aktardıktan sonra klasörü otomatik aç",
autoOpenExportFolderDescription: "Veri dışa aktarımı başarılı olduğunda dosya yöneticisinde dışa aktarılan dosyanın klasörünü otomatik olarak açar.",
exportSection: "Dışa Aktar",
diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.ts
index edf106b6f0..367036df8c 100644
--- a/apps/desktop/src/i18n/locales/zh-CN.ts
+++ b/apps/desktop/src/i18n/locales/zh-CN.ts
@@ -6,6 +6,7 @@ import { dataDictionaryZhCN as dataDictionary } from "./dataDictionaryMessages";
import { consul } from "./consulZhCN";
import { meilisearchManagementZhCN } from "./meilisearchManagement";
import { mongodbDatabaseDumpZhCN as mongoDump } from "./mongodbDatabaseDump";
+import { damengDumpZhCN as damengDump } from "./damengDump";
export default withEnglishFallback({
sidebarMenu,
@@ -6592,6 +6593,7 @@ export default withEnglishFallback({
},
},
mongoDump,
+ damengDump,
mongo: {
documents: "{count} 个文档",
addField: "添加字段",
@@ -9080,6 +9082,11 @@ export default withEnglishFallback({
preferredExportPathPlaceholder: "未设置(自动使用上次导出路径)",
preferredExportPathChoose: "选择首选导出目录",
preferredExportPathClear: "清除首选导出路径",
+ damengClientBinDir: "达梦客户端 bin 目录",
+ damengClientBinDirDescription: "包含达梦客户端工具 dexp/dimp 的目录,用于原生 .dmp 导出/导入。",
+ damengClientBinDirPlaceholder: "如 C:\\dm8\\bin",
+ damengClientBinDirChoose: "选择达梦客户端 bin 目录",
+ damengClientBinDirClear: "清除达梦客户端 bin 目录",
autoOpenExportFolder: "导出后自动打开所在文件夹",
autoOpenExportFolderDescription: "数据导出成功后,自动在系统文件管理器中打开并定位导出文件所在的文件夹。",
exportSection: "导出",
diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.ts
index 4e4be0396a..6e09a76377 100644
--- a/apps/desktop/src/i18n/locales/zh-TW.ts
+++ b/apps/desktop/src/i18n/locales/zh-TW.ts
@@ -2,6 +2,7 @@ import { sidebarMenuZhTW as sidebarMenu } from "./sidebarMenuMessages";
import { redisGroupingZhTW as redisGrouping } from "./redisGrouping";
import { withEnglishFallback } from "./fallback";
import { mongodbDatabaseDumpZhTW as mongoDump } from "./mongodbDatabaseDump";
+import { damengDumpZhTW as damengDump } from "./damengDump";
import { meilisearchManagementZhTW } from "./meilisearchManagement";
import docs from "./docs/zh-TW";
import { dataDictionaryZhTW as dataDictionary } from "./dataDictionaryMessages";
@@ -112,6 +113,7 @@ export default withEnglishFallback({
updateFailed: "屬性更新失敗。",
},
mongoDump,
+ damengDump,
cellTransform: {
title: "轉換預覽",
description: "將目前內容轉換後檢視或複製,不改變原值和編輯草稿。",
@@ -8001,6 +8003,11 @@ export default withEnglishFallback({
preferredExportPathPlaceholder: "未設定(自動使用上次匯出路徑)",
preferredExportPathChoose: "選擇首選匯出目錄",
preferredExportPathClear: "清除首選匯出路徑",
+ damengClientBinDir: "達夢用戶端 bin 目錄",
+ damengClientBinDirDescription: "包含達夢用戶端工具 dexp/dimp 的目錄,用於原生 .dmp 匯出/匯入。",
+ damengClientBinDirPlaceholder: "如 C:\\dm8\\bin",
+ damengClientBinDirChoose: "選擇達夢用戶端 bin 目錄",
+ damengClientBinDirClear: "清除達夢用戶端 bin 目錄",
autoOpenExportFolder: "匯出後自動開啟所在資料夾",
autoOpenExportFolderDescription: "資料匯出成功後,自動在系統檔案管理器中開啟並定位匯出檔案所在的資料夾。",
shortcutUppercaseSelection: "選取內容轉為大寫",
diff --git a/apps/desktop/src/lib/backend/api.ts b/apps/desktop/src/lib/backend/api.ts
index 3efe35a85b..ce83242b46 100644
--- a/apps/desktop/src/lib/backend/api.ts
+++ b/apps/desktop/src/lib/backend/api.ts
@@ -596,6 +596,12 @@ export const cancelQueryResultExport = forward("cancelQueryResultExport");
export const openQueryResultTempFile = forward("openQueryResultTempFile");
export const createQueryResultTempFile = forward("createQueryResultTempFile");
+// Dameng native .dmp dump (dexp/dimp)
+export const startDamengDump = forward("startDamengDump");
+export const cancelDamengDump = forward("cancelDamengDump");
+export const resolveDamengDumpTool = forward("resolveDamengDumpTool");
+export type { DamengDumpKind, DamengDumpRequest, DamengDumpProgress } from "./damengDumpTypes";
+
// Redis
export const redisListDatabases = forward("redisListDatabases");
export const redisScanKeys = forward("redisScanKeys");
diff --git a/apps/desktop/src/lib/backend/damengDumpTypes.ts b/apps/desktop/src/lib/backend/damengDumpTypes.ts
new file mode 100644
index 0000000000..ed177d25d0
--- /dev/null
+++ b/apps/desktop/src/lib/backend/damengDumpTypes.ts
@@ -0,0 +1,34 @@
+// Native Dameng dexp/dimp (.dmp) dump — request/progress shapes shared by the
+// Tauri and HTTP backends. Field names mirror the Rust `DamengDumpTaskRequest`
+// / `DamengDumpProgress` (serde camelCase).
+
+export type DamengDumpKind = "export" | "import";
+
+export interface DamengDumpRequest {
+ taskId: string;
+ connectionId: string;
+ kind: DamengDumpKind;
+ /** Absolute path to the dexp/dimp executable (from the client bin setting). */
+ toolPath: string;
+ /** `.dmp` file to write (export) or read (import). */
+ filePath: string;
+ /** Schemas to export/import; empty means whole-database. */
+ schemas: string[];
+ /** Explicit tables (export only); empty means the whole schema. */
+ tables: string[];
+ /** Import only: REMAP_SCHEMA=SRC:DST. */
+ remapSchema: [string, string] | null;
+ /** Import only: TABLE_EXISTS_ACTION=SKIP|REPLACE|TRUNCATE|APPEND. */
+ tableExistsAction: string | null;
+}
+
+export type DamengDumpStatus = "running" | "done" | "error" | "cancelled";
+
+export interface DamengDumpProgress {
+ taskId: string;
+ status: DamengDumpStatus;
+ success: boolean;
+ warnings: boolean;
+ elapsedSeconds: string | null;
+ error: string | null;
+}
diff --git a/apps/desktop/src/lib/backend/http.ts b/apps/desktop/src/lib/backend/http.ts
index 2d08fe5316..6e93db1967 100644
--- a/apps/desktop/src/lib/backend/http.ts
+++ b/apps/desktop/src/lib/backend/http.ts
@@ -1,5 +1,6 @@
import type { MongoDumpFormat, MongoDumpSourceInput, MongoDumpCatalog, MongoRestoreSourcePreview, MongoDatabaseDumpRequest, MongoDatabaseRestoreRequest, MongoDatabaseDumpProgress } from "./mongodbDumpTypes";
import type { MongoRestoreUpload, MongoSourceReadOptions } from "./mongodbDumpTypes";
+import type { DamengDumpKind, DamengDumpRequest, DamengDumpProgress } from "./damengDumpTypes";
import type { UserSkillRootSettings, UserSkillsListResult, UserSkillsReadResult } from "@/types/userSkills";
import type { DatabaseBackupCommand, DatabaseBackupBackgroundStatus } from "@/lib/backup/backgroundDatabaseBackup";
import type { PluginUiStorageItemRef, SqlFileFailureLogExportPayload, SqlFileFailureLogInfo, SqlFileFailureLogKey, SqlFileFailureLogTextPayload, SyncCatalogItem, SyncSelection, SyncSnapshotCatalog } from "@/lib/backend/tauri";
@@ -3519,6 +3520,22 @@ function downloadTableExportFile(exportId: string): void {
a.click();
}
+// Native dexp/dimp tools only exist next to a local Dameng client install, so
+// the web deployment has no server-side implementation by design.
+const DAMENG_DUMP_WEB_UNSUPPORTED = "Dameng native .dmp export/import requires the desktop application.";
+
+export async function startDamengDump(_request: DamengDumpRequest, _onProgress: (progress: DamengDumpProgress) => void): Promise<DamengDumpProgress> {
+ throw new Error(DAMENG_DUMP_WEB_UNSUPPORTED);
+}
+
+export async function cancelDamengDump(_taskId: string): Promise<void> {
+ throw new Error(DAMENG_DUMP_WEB_UNSUPPORTED);
+}
+
+export async function resolveDamengDumpTool(_binDir: string, _kind: DamengDumpKind): Promise<string> {
+ throw new Error(DAMENG_DUMP_WEB_UNSUPPORTED);
+}
+
export async function cancelTableExport(exportId: string): Promise<void> {
return post("/api/export/table/cancel", { exportId });
}
diff --git a/apps/desktop/src/lib/backend/tauri.ts b/apps/desktop/src/lib/backend/tauri.ts
index b89386e4e4..9ebf899fbd 100644
--- a/apps/desktop/src/lib/backend/tauri.ts
+++ b/apps/desktop/src/lib/backend/tauri.ts
@@ -2,6 +2,7 @@ import { invoke as tauriInvoke } from "@tauri-apps/api/core";
import { Channel } from "@tauri-apps/api/core";
import type { MongoDumpFormat, MongoDumpSourceInput, MongoDumpCatalog, MongoRestoreSourcePreview, MongoDatabaseDumpRequest, MongoDatabaseRestoreRequest, MongoDatabaseDumpProgress } from "./mongodbDumpTypes";
import type { MongoRestoreUpload, MongoSourceReadOptions } from "./mongodbDumpTypes";
+import type { DamengDumpKind, DamengDumpRequest, DamengDumpProgress } from "./damengDumpTypes";
import type { UserSkillRootSettings, UserSkillsListResult, UserSkillsReadResult } from "@/types/userSkills";
import type { DatabaseBackupCommand, DatabaseBackupBackgroundStatus } from "@/lib/backup/backgroundDatabaseBackup";
@@ -6501,6 +6502,53 @@ export async function recordDatabaseExportDestination(directory: string): Promis
await invoke("record_database_export_destination", { directory });
}
+export async function startDamengDump(request: DamengDumpRequest, onProgress: (progress: DamengDumpProgress) => void): Promise<DamengDumpProgress> {
+ let unlisten: UnlistenFn | undefined;
+ let settled = false;
+ let resolveTerminal: (progress: DamengDumpProgress) => void = () => {};
+ let rejectTerminal: (error: unknown) => void = () => {};
+
+ const terminalProgress = new Promise<DamengDumpProgress>((resolve, reject) => {
+ resolveTerminal = resolve;
+ rejectTerminal = reject;
+ });
+
+ const finish = (callback: () => void) => {
+ if (settled) return;
+ settled = true;
+ unlisten?.();
+ callback();
+ };
+
+ try {
+ unlisten = await listen<DamengDumpProgress>("dameng-dump-progress", (event) => {
+ if (event.payload.taskId !== request.taskId) return;
+ onProgress(event.payload);
+ if (event.payload.status === "error") {
+ finish(() => rejectTerminal(new BackendErrorException(event.payload.error || "Dameng dump failed")));
+ } else if (event.payload.status === "done" || event.payload.status === "cancelled") {
+ finish(() => resolveTerminal(event.payload));
+ }
+ });
+ await invoke("start_dameng_dump", { request });
+ return await terminalProgress;
+ } catch (error) {
+ if (!settled) {
+ settled = true;
+ unlisten?.();
+ }
+ throw error instanceof BackendErrorException ? error : new BackendErrorException(error);
+ }
+}
+
+export async function cancelDamengDump(taskId: string): Promise<void> {
+ await invoke("cancel_dameng_dump", { taskId });
+}
+
+export async function resolveDamengDumpTool(binDir: string, kind: DamengDumpKind): Promise<string> {
+ return invoke("resolve_dameng_dump_tool", { binDir, kind });
+}
+
export async function exportQueryResultCsv(filePath: string, columns: string[], rows: readonly (readonly XlsxCellValue[])[], csvQuoteMode: CsvQuoteMode = "all", nullLiteral?: string): Promise<void> {
return invoke("export_query_result_csv", {
request: {
diff --git a/apps/desktop/src/lib/settings/editorSettingsDraft.ts b/apps/desktop/src/lib/settings/editorSettingsDraft.ts
index cb3361e68b..d8ed5eba55 100644
--- a/apps/desktop/src/lib/settings/editorSettingsDraft.ts
+++ b/apps/desktop/src/lib/settings/editorSettingsDraft.ts
@@ -144,6 +144,7 @@ export const EDITOR_SETTINGS_DRAFT_KEYS = [
"redisDatabaseDisplayLimit",
"exportBatchSize",
"preferredExportPath",
+ "damengClientBinDir",
"autoOpenExportFolder",
"csvQuoteMode",
"csvNullMode",
diff --git a/apps/desktop/src/lib/settings/settingsSearch.ts b/apps/desktop/src/lib/settings/settingsSearch.ts
index e38938cbf2..766a4360ef 100644
--- a/apps/desktop/src/lib/settings/settingsSearch.ts
+++ b/apps/desktop/src/lib/settings/settingsSearch.ts
@@ -269,6 +269,7 @@ export const SETTINGS_SEARCH_DEFINITIONS: readonly SettingsSearchDefinition[] =
{ id: "data-datetime-import-format", category: "data", titleKey: "settings.globalDateTimeImportFormat", descriptionKey: "settings.globalDateTimeImportFormatDescription", targetId: "data" },
{ id: "data-export", category: "data", titleKey: "settings.exportSection", targetId: "data" },
{ id: "data-export-preferred-path", category: "data", titleKey: "settings.preferredExportPath", descriptionKey: "settings.preferredExportPathDescription", targetId: "data" },
+ { id: "data-dameng-client-bin-dir", category: "data", titleKey: "settings.damengClientBinDir", descriptionKey: "settings.damengClientBinDirDescription", targetId: "data" },
{ id: "data-export-auto-open-folder", category: "data", titleKey: "settings.autoOpenExportFolder", descriptionKey: "settings.autoOpenExportFolderDescription", targetId: "data", visible: desktopOnly },
{ id: "data-export-batch", category: "data", titleKey: "settings.exportBatchSize", descriptionKey: "settings.exportBatchSizeDescription", targetId: "data" },
{ id: "data-export-row-limit-enabled", category: "data", titleKey: "settings.exportRowLimitEnabled", descriptionKey: "settings.exportRowLimitEnabledDescription", targetId: "data" },
diff --git a/apps/desktop/src/lib/settings/settingsTransfer.ts b/apps/desktop/src/lib/settings/settingsTransfer.ts
index 58fcaafea2..010d55a06c 100644
--- a/apps/desktop/src/lib/settings/settingsTransfer.ts
+++ b/apps/desktop/src/lib/settings/settingsTransfer.ts
@@ -198,6 +198,7 @@ const SETTINGS_TRANSFER_CATEGORY_KEYS: Record<SettingsTransferCategoryId, readon
"redisDatabaseDisplayLimit",
"exportBatchSize",
"preferredExportPath",
+ "damengClientBinDir",
"autoOpenExportFolder",
"csvQuoteMode",
"csvNullMode",
diff --git a/apps/desktop/src/stores/connectionStore.ts b/apps/desktop/src/stores/connectionStore.ts
index aebd8371f8..1a355c4cd5 100644
--- a/apps/desktop/src/stores/connectionStore.ts
+++ b/apps/desktop/src/stores/connectionStore.ts
@@ -641,6 +641,7 @@ export const useConnectionStore = defineStore("connection", () => {
tableName?: string;
} | null>(null);
const mongoDatabaseDumpSource = ref<{ connectionId: string; database: string; mode: "dump" | "restore" } | null>(null);
+ const damengDumpSource = ref<{ connectionId: string; database: string; mode: "export" | "import" } | null>(null);
const mongoImportSource = ref<{
connectionId: string;
database: string;
@@ -10638,6 +10639,7 @@ export const useConnectionStore = defineStore("connection", () => {
dataDictionarySource,
tableImportSource,
mongoDatabaseDumpSource,
+ damengDumpSource,
mongoImportSource,
mongoImportCompleted,
tableDataGenerateSource,
diff --git a/apps/desktop/src/stores/settingsStore.ts b/apps/desktop/src/stores/settingsStore.ts
index 8f03e53995..fd65b28657 100644
--- a/apps/desktop/src/stores/settingsStore.ts
+++ b/apps/desktop/src/stores/settingsStore.ts
@@ -1018,6 +1018,12 @@ export interface EditorSettings {
* is OCI; the connection dialog backfills it and edits write it back here.
*/
oracleOciClientPath: string;
+ /**
+ * Dameng client bin directory (the directory that contains dexp/dimp).
+ * Shared by every Dameng connection's native .dmp export/import; the tools
+ * ship with the DM client install and are not bundled with DBX.
+ */
+ damengClientBinDir: string;
/**
* Client character set for OCI connections, injected as the NLS_LANG
* environment variable when the OCI agent starts. Empty keeps the OCI
@@ -1363,6 +1369,7 @@ export const DEFAULT_EDITOR_SETTINGS: EditorSettings = {
showColumnHeaderTooltips: true,
showResultSourceDatabase: true,
oracleOciClientPath: "",
+ damengClientBinDir: "",
oracleOciNlsLang: "",
oracleOciTnsAdmin: "",
resultTabNamingMode: "source",
@@ -2012,6 +2019,7 @@ export function normalizeEditorSettings(settings: Partial<EditorSettings>, exist
oracleOciNlsLang: typeof settings.oracleOciNlsLang === "string" ? settings.oracleOciNlsLang.trim() : "",
oracleOciTnsAdmin: typeof settings.oracleOciTnsAdmin === "string" ? settings.oracleOciTnsAdmin.trim() : "",
oracleOciClientPath: typeof settings.oracleOciClientPath === "string" ? settings.oracleOciClientPath.trim() : "",
+ damengClientBinDir: typeof settings.damengClientBinDir === "string" ? settings.damengClientBinDir.trim() : "",
resultTabNamingMode: normalizeResultTabNamingMode(settings.resultTabNamingMode),
resultTabPreferComments: settings.resultTabPreferComments !== false,
dataGridShowTransposeFieldMetadata: settings.dataGridShowTransposeFieldMetadata === true,
@@ -2893,6 +2901,7 @@ export const useSettingsStore = defineStore("settings", () => {
if (partial.oracleOciNlsLang !== undefined) editorSettings.value.oracleOciNlsLang = partial.oracleOciNlsLang.trim();
if (partial.oracleOciTnsAdmin !== undefined) editorSettings.value.oracleOciTnsAdmin = partial.oracleOciTnsAdmin.trim();
if (partial.oracleOciClientPath !== undefined) editorSettings.value.oracleOciClientPath = partial.oracleOciClientPath.trim();
+ if (partial.damengClientBinDir !== undefined) editorSettings.value.damengClientBinDir = partial.damengClientBinDir.trim();
if (partial.resultTabNamingMode !== undefined) editorSettings.value.resultTabNamingMode = normalizeResultTabNamingMode(partial.resultTabNamingMode);
if (partial.resultTabPreferComments !== undefined) editorSettings.value.resultTabPreferComments = partial.resultTabPreferComments !== false;
if (partial.dataGridShowTransposeFieldMetadata !== undefined) editorSettings.value.dataGridShowTransposeFieldMetadata = partial.dataGridShowTransposeFieldMetadata === true;
diff --git a/crates/dbx-core/src/data/dameng_dump.rs b/crates/dbx-core/src/data/dameng_dump.rs
new file mode 100644
index 0000000000..7416f1a491
--- /dev/null
+++ b/crates/dbx-core/src/data/dameng_dump.rs
@@ -0,0 +1,619 @@
+//! Native Dameng `dexp`/`dimp` process runner.
+//!
+//! [`dbx_sql::dameng_dump`] builds the invocation and interprets the tool log;
+//! this module drives the external process: it resolves the connection's
+//! credentials, writes the PARFILE to a temp directory, spawns the configured
+//! tool with managed process-tree ownership, streams a terminal progress
+//! event, and cleans up its scratch files.
+//!
+//! The password necessarily rides on the command line (Dameng requires `USERID`
+//! as the first argument — see the dbx-sql module docs), so the spawned
+//! process must stay short-lived; `PARFILE` keeps everything else out of the
+//! process list.
+
+use std::path::{Path, PathBuf};
+use std::sync::Arc;
+use std::time::Duration;
+
+use serde::{Deserialize, Serialize};
+use tokio::io::AsyncReadExt;
+
+pub use dbx_sql::dameng_dump::DamengDumpKind as DamengDumpKindReexport;
+use dbx_sql::dameng_dump::{
+ build_command, build_parfile_contents, parse_dump_log, userid_field_error, DamengDumpKind, DamengDumpOutcome,
+ DamengDumpRequest,
+};
+
+use crate::connection::AppState;
+use crate::data::database_export::{clear_export_cancelled, is_export_cancelled, EXPORT_CANCELLED_ERROR};
+use crate::models::connection::DatabaseType;
+
+/// Poll interval for the child's exit / the cancellation marker.
+const POLL_INTERVAL: Duration = Duration::from_millis(200);
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "lowercase")]
+pub enum DamengDumpKindArg {
+ Export,
+ Import,
+}
+
+impl From<DamengDumpKindArg> for DamengDumpKind {
+ fn from(value: DamengDumpKindArg) -> Self {
+ match value {
+ DamengDumpKindArg::Export => DamengDumpKind::Export,
+ DamengDumpKindArg::Import => DamengDumpKind::Import,
+ }
+ }
+}
+
+/// The request the frontend sends. Connection credentials are resolved
+/// server-side from the connection config (plus the session-credential
+/// fallback for `save_password=false` connections).
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct DamengDumpTaskRequest {
+ pub task_id: String,
+ pub connection_id: String,
+ pub kind: DamengDumpKindArg,
+ /// Absolute path to the `dexp`/`dimp` executable (from the user setting).
+ pub tool_path: String,
+ /// `.dmp` file to write (export) or read (import).
+ pub file_path: String,
+ /// Schemas to export/import; empty means whole-database.
+ #[serde(default)]
+ pub schemas: Vec<String>,
+ /// Explicit tables (export only); empty means the whole schema.
+ #[serde(default)]
+ pub tables: Vec<String>,
+ /// Import only: remap `REMAP_SCHEMA=SRC:DST`.
+ #[serde(default)]
+ pub remap_schema: Option<(String, String)>,
+ /// Import only: `TABLE_EXISTS_ACTION=SKIP|REPLACE|TRUNCATE|APPEND`.
+ #[serde(default)]
+ pub table_exists_action: Option<String>,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "lowercase")]
+pub enum DamengDumpStatus {
+ Running,
+ Done,
+ Error,
+ Cancelled,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct DamengDumpProgress {
+ pub task_id: String,
+ pub status: DamengDumpStatus,
+ pub success: bool,
+ pub warnings: bool,
+ pub elapsed_seconds: Option<String>,
+ pub error: Option<String>,
+}
+
+/// Tagged so the frontend can map it to a localized hint pointing at the
+/// Settings page (same convention as the AI CLI path errors).
+pub const DAMENG_TOOL_NOT_FOUND_TAG: &str = "damengToolNotFound";
+pub const DAMENG_CONNECTION_NOT_DAMENG_TAG: &str = "damengConnectionRequired";
+pub const DAMENG_PASSWORD_MISSING_TAG: &str = "damengPasswordMissing";
+pub const DAMENG_USERID_INVALID_TAG: &str = "damengUseridInvalid";
+
+fn tagged(tag: &str, message: &str) -> String {
+ format!("[{tag}] {message}")
+}
+
+/// Resolve the `dexp`/`dimp` executable inside a configured client `bin`
+/// directory. Windows installs use `dexp.exe`/`dimp.exe`; the extension-less
+/// form is accepted too (some clients ship a launcher script).
+pub fn resolve_damp_tool_path(bin_dir: &str, kind: DamengDumpKind) -> Result<PathBuf, String> {
+ let bin_dir = bin_dir.trim();
+ if bin_dir.is_empty() {
+ return Err(tagged(DAMENG_TOOL_NOT_FOUND_TAG, "Dameng client bin directory is not configured."));
+ }
+ let base = match kind {
+ DamengDumpKind::Export => "dexp",
+ DamengDumpKind::Import => "dimp",
+ };
+ let dir = Path::new(bin_dir);
+ let candidates = if cfg!(windows) {
+ vec![dir.join(format!("{base}.exe")), dir.join(base)]
+ } else {
+ vec![dir.join(base), dir.join(format!("{base}.exe"))]
+ };
+ candidates.into_iter().find(|candidate| candidate.is_file()).ok_or_else(|| {
+ tagged(
+ DAMENG_TOOL_NOT_FOUND_TAG,
+ &format!(
+ "Dameng client tool '{base}' was not found in '{bin_dir}'. \
+ Configure the Dameng client bin directory in Settings > Data."
+ ),
+ )
+ })
+}
+
+/// Export side: only validate the target — the actual write goes to a sibling
+/// temp file (see [`sibling_temp_dump_path`]) that is renamed over the target
+/// after a successful run, so a failed or cancelled export never destroys the
+/// user's previous dump. The frontend's save dialog has already asked the user
+/// to confirm the replacement.
+fn validate_export_target(file_path: &Path) -> Result<(), String> {
+ match std::fs::metadata(file_path) {
+ Ok(meta) if !meta.is_file() => {
+ Err(format!("Export target '{}' exists and is not a file.", file_path.display()))
+ }
+ Ok(_) => Ok(()),
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
+ Err(error) => Err(format!("Cannot access export file '{}': {error}", file_path.display())),
+ }
+}
+
+/// The temp `.dmp` the tool writes to during an export: same directory as the
+/// target (so the final rename stays on one volume), `.dmp` extension kept,
+/// and task-id-scoped so a leftover from an interrupted run cannot make the
+/// tool prompt `y/n` on an existing file.
+fn sibling_temp_dump_path(target: &Path, task_id: &str) -> PathBuf {
+ let stem = target.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default();
+ target.with_file_name(format!("{stem}.dbx-dameng-{task_id}-{}.tmp.dmp", std::process::id()))
+}
+
+/// Move the successful export's temp file over the user's target. On failure
+/// the temp file is kept (it holds a complete dump) and its path is surfaced
+/// so the user can recover it manually.
+fn finalize_export_target(temp_path: &Path, target: &Path) -> Result<(), String> {
+ std::fs::rename(temp_path, target).map_err(|error| {
+ format!(
+ "Export finished but replacing '{}' failed ({error}); the new dump was kept at '{}'.",
+ target.display(),
+ temp_path.display()
+ )
+ })
+}
+
+fn prepare_import_source(file_path: &Path) -> Result<(), String> {
+ if file_path.is_file() {
+ Ok(())
+ } else {
+ Err(format!("Import file not found: '{}'", file_path.display()))
+ }
+}
+
+/// Run the tool once and return the combined diagnostic text (log file
+/// preferred, console capture as fallback).
+async fn run_tool_and_collect(
+ argv: &[String],
+ log_path: &Path,
+ out_path: &Path,
+ err_path: &Path,
+ task_id: &str,
+) -> Result<String, String> {
+ if argv.is_empty() {
+ return Err("Empty dexp/dimp command".to_string());
+ }
+ let mut command = crate::process::new_tokio_command(&argv[0]);
+ command.args(&argv[1..]);
+ command.stdin(std::process::Stdio::null());
+ command.kill_on_drop(true);
+
+ let out_file = std::fs::File::create(out_path)
+ .map_err(|error| format!("Failed to create capture file '{}': {error}", out_path.display()))?;
+ let err_file = std::fs::File::create(err_path)
+ .map_err(|error| format!("Failed to create capture file '{}': {error}", err_path.display()))?;
+ command.stdout(std::process::Stdio::from(out_file));
+ command.stderr(std::process::Stdio::from(err_file));
+
+ let mut child = crate::process::spawn_managed_child(&mut command)
+ .await
+ .map_err(|error| format!("Failed to start '{}': {error}", argv[0]))?;
+
+ let cancelled = loop {
+ match child.try_wait() {
+ Ok(Some(_)) => break false,
+ Ok(None) => {}
+ Err(error) => return Err(format!("Failed to wait for '{}': {error}", argv[0])),
+ }
+ if is_export_cancelled(task_id).await {
+ let _ = child.terminate().await;
+ break true;
+ }
+ tokio::time::sleep(POLL_INTERVAL).await;
+ };
+
+ if cancelled {
+ return Err(EXPORT_CANCELLED_ERROR.to_string());
+ }
+
+ // Prefer the tool's own log (the parse target); fall back to console
+ // capture for early failures (missing lib, bad args) that never reach it.
+ let log_text = tokio::fs::read_to_string(log_path).await.unwrap_or_default();
+ if !log_text.trim().is_empty() {
+ return Ok(log_text);
+ }
+ let mut console = String::new();
+ let mut out_file = tokio::fs::File::open(out_path).await.ok();
+ let mut err_file = tokio::fs::File::open(err_path).await.ok();
+ if let Some(file) = out_file.as_mut() {
+ let _ = file.read_to_string(&mut console).await;
+ }
+ if let Some(file) = err_file.as_mut() {
+ let mut err_text = String::new();
+ let _ = file.read_to_string(&mut err_text).await;
+ if !err_text.trim().is_empty() {
+ if !console.trim().is_empty() {
+ console.push('\n');
+ }
+ console.push_str(&err_text);
+ }
+ }
+ Ok(console)
+}
+
+fn remove_if_exists(path: &Path) {
+ let _ = std::fs::remove_file(path);
+}
+
+/// Drive one native export/import. Emits a `Running` progress at start and a
+/// terminal `Done`/`Error`/`Cancelled` before returning. Returns `Ok(())` for
+/// both parsed success and parsed failure (the progress carries the outcome);
+/// `Err` is only for infrastructure problems before/around the run, which the
+/// caller surfaces as a terminal `Error` event too.
+pub async fn run_dameng_dump_task(
+ state: &Arc<AppState>,
+ request: &DamengDumpTaskRequest,
+ on_progress: impl Fn(DamengDumpProgress) + Sync,
+) -> Result<(), String> {
+ let emit =
+ |status: DamengDumpStatus, success: bool, warnings: bool, elapsed: Option<String>, error: Option<String>| {
+ on_progress(DamengDumpProgress {
+ task_id: request.task_id.clone(),
+ status,
+ success,
+ warnings,
+ elapsed_seconds: elapsed,
+ error,
+ })
+ };
+ emit(DamengDumpStatus::Running, false, false, None, None);
+
+ let kind: DamengDumpKind = request.kind.into();
+
+ let mut config = {
+ let configs = state.configs.read().await;
+ match configs.get(&request.connection_id).cloned() {
+ Some(config) => config,
+ None => {
+ let error = format!("Connection config not found: {}", request.connection_id);
+ emit(DamengDumpStatus::Error, false, false, None, Some(error.clone()));
+ return Err(error);
+ }
+ }
+ };
+ if config.db_type != DatabaseType::Dameng {
+ let error =
+ tagged(DAMENG_CONNECTION_NOT_DAMENG_TAG, "Native dexp/dimp dump is only available for Dameng connections.");
+ emit(DamengDumpStatus::Error, false, false, None, Some(error.clone()));
+ return Err(error);
+ }
+ // save_password=false connections keep the password only in the session store.
+ let config_snapshot = config.clone();
+ state.apply_session_credential(&config_snapshot, &mut config, &request.connection_id);
+ if config.password.is_empty() {
+ let error = tagged(
+ DAMENG_PASSWORD_MISSING_TAG,
+ "The connection has no password available; reconnect and enter the password first.",
+ );
+ emit(DamengDumpStatus::Error, false, false, None, Some(error.clone()));
+ return Err(error);
+ }
+ // A `/` or `@` in the user or password would be read as a USERID field
+ // separator by the tool and surface as a bogus host / connection error;
+ // reject it up front instead of launching.
+ if let Some(field) = userid_field_error(&config.username, &config.password) {
+ let error = tagged(
+ DAMENG_USERID_INVALID_TAG,
+ &format!(
+ "The connection's {field} contains '/' or '@', which the dexp/dimp USERID argument cannot encode; the task was not started."
+ ),
+ );
+ emit(DamengDumpStatus::Error, false, false, None, Some(error.clone()));
+ return Err(error);
+ }
+
+ let tool_path = Path::new(&request.tool_path);
+ if !tool_path.is_file() {
+ let error = tagged(
+ DAMENG_TOOL_NOT_FOUND_TAG,
+ &format!(
+ "Dameng client tool not found: '{}'. \
+ Configure the Dameng client bin directory in Settings > Data.",
+ request.tool_path
+ ),
+ );
+ emit(DamengDumpStatus::Error, false, false, None, Some(error.clone()));
+ return Err(error);
+ }
+
+ let file_path = Path::new(&request.file_path);
+ // Export writes to a sibling temp file first; only a successful run is
+ // renamed over the target, so a failed export leaves the previous dump intact.
+ let export_temp_path = match kind {
+ DamengDumpKind::Export => {
+ if let Err(error) = validate_export_target(file_path) {
+ emit(DamengDumpStatus::Error, false, false, None, Some(error.clone()));
+ return Err(error);
+ }
+ let temp_path = sibling_temp_dump_path(file_path, &request.task_id);
+ // A leftover from an interrupted run would make the tool prompt y/n.
+ remove_if_exists(&temp_path);
+ Some(temp_path)
+ }
+ DamengDumpKind::Import => {
+ if let Err(error) = prepare_import_source(file_path) {
+ emit(DamengDumpStatus::Error, false, false, None, Some(error.clone()));
+ return Err(error);
+ }
+ None
+ }
+ };
+
+ let temp_dir = std::env::temp_dir().join("dbx-dameng-dump");
+ if let Err(error) = std::fs::create_dir_all(&temp_dir) {
+ let error = format!("Failed to create temp dir '{}': {error}", temp_dir.display());
+ emit(DamengDumpStatus::Error, false, false, None, Some(error.clone()));
+ return Err(error);
+ }
+ let stem = format!("{}-{}", request.task_id, std::process::id());
+ let parfile_path = temp_dir.join(format!("{stem}.par"));
+ let log_path = temp_dir.join(format!("{stem}.log"));
+ let out_path = temp_dir.join(format!("{stem}.out"));
+ let err_path = temp_dir.join(format!("{stem}.err"));
+
+ let dump_request = DamengDumpRequest {
+ db_type: config.db_type,
+ kind,
+ tool_path: request.tool_path.clone(),
+ host: config.host.clone(),
+ port: config.port,
+ user: config.username.clone(),
+ password: config.password.clone(),
+ file_path: export_temp_path
+ .as_deref()
+ .map(|p| p.to_string_lossy().into_owned())
+ .unwrap_or_else(|| request.file_path.clone()),
+ log_path: log_path.to_string_lossy().into_owned(),
+ schemas: request.schemas.clone(),
+ tables: request.tables.clone(),
+ remap_schema: request.remap_schema.clone(),
+ table_exists_action: request.table_exists_action.clone(),
+ };
+
+ let parfile_contents = build_parfile_contents(&dump_request);
+ if let Err(error) = std::fs::write(&parfile_path, parfile_contents) {
+ let error = format!("Failed to write PARFILE '{}': {error}", parfile_path.display());
+ emit(DamengDumpStatus::Error, false, false, None, Some(error.clone()));
+ return Err(error);
+ }
+ let argv = build_command(&dump_request, &parfile_path.to_string_lossy());
+
+ let run_result = run_tool_and_collect(&argv, &log_path, &out_path, &err_path, &request.task_id).await;
+
+ remove_if_exists(&parfile_path);
+ remove_if_exists(&out_path);
+ remove_if_exists(&err_path);
+
+ let text = match run_result {
+ Ok(text) => text,
+ Err(error) if error == EXPORT_CANCELLED_ERROR => {
+ remove_if_exists(&log_path);
+ if let Some(temp_path) = &export_temp_path {
+ remove_if_exists(temp_path);
+ }
+ emit(DamengDumpStatus::Cancelled, false, false, None, None);
+ return Ok(());
+ }
+ Err(error) => {
+ remove_if_exists(&log_path);
+ if let Some(temp_path) = &export_temp_path {
+ remove_if_exists(temp_path);
+ }
+ emit(DamengDumpStatus::Error, false, false, None, Some(error.clone()));
+ return Err(error);
+ }
+ };
+ remove_if_exists(&log_path);
+
+ let outcome: DamengDumpOutcome = parse_dump_log(&text, kind);
+ if outcome.success {
+ if let Some(temp_path) = &export_temp_path {
+ if let Err(error) = finalize_export_target(temp_path, file_path) {
+ emit(
+ DamengDumpStatus::Error,
+ false,
+ outcome.warnings,
+ outcome.elapsed_seconds.clone(),
+ Some(error.clone()),
+ );
+ return Err(error);
+ }
+ }
+ emit(DamengDumpStatus::Done, true, outcome.warnings, outcome.elapsed_seconds, None);
+ Ok(())
+ } else {
+ if let Some(temp_path) = &export_temp_path {
+ remove_if_exists(temp_path);
+ }
+ let error = outcome
+ .error
+ .clone()
+ .or_else(|| {
+ Some(text.lines().rev().find(|l| !l.trim().is_empty()).unwrap_or("dexp/dimp failed").trim().to_string())
+ })
+ .unwrap_or_else(|| "dexp/dimp failed".to_string());
+ emit(DamengDumpStatus::Error, false, outcome.warnings, outcome.elapsed_seconds.clone(), Some(error.clone()));
+ Err(error)
+ }
+}
+
+/// The tauri command wrapper emits the terminal error itself; this keeps the
+/// cancellation marker cleanup next to the task spawn (mirrors the database
+/// export command).
+pub async fn finish_dameng_dump_task(task_id: &str) {
+ clear_export_cancelled(task_id).await;
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn resolve_tool_path_requires_configured_dir() {
+ let error = resolve_damp_tool_path(" ", DamengDumpKind::Export).unwrap_err();
+ assert!(error.starts_with("[damengToolNotFound]"), "tagged error, got: {error}");
+ }
+
+ #[test]
+ fn resolve_tool_path_finds_executable_in_dir() {
+ let dir = std::env::temp_dir().join(format!("dbx-dameng-tool-test-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let name = if cfg!(windows) { "dexp.exe" } else { "dexp" };
+ let tool = dir.join(name);
+ std::fs::write(&tool, b"fake").unwrap();
+ let resolved = resolve_damp_tool_path(&dir.to_string_lossy(), DamengDumpKind::Export).unwrap();
+ assert_eq!(resolved, tool);
+ let missing = resolve_damp_tool_path(&dir.to_string_lossy(), DamengDumpKind::Import).unwrap_err();
+ assert!(missing.starts_with("[damengToolNotFound]"), "got: {missing}");
+ let _ = std::fs::remove_file(&tool);
+ }
+
+ #[test]
+ fn validate_export_target_keeps_existing_file() {
+ let file = std::env::temp_dir().join(format!("dbx-dameng-overwrite-{}.dmp", std::process::id()));
+ std::fs::write(&file, b"old").unwrap();
+ validate_export_target(&file).unwrap();
+ assert!(file.exists(), "a failed or unstarted export must never remove the previous dump");
+ let dir = std::env::temp_dir().join(format!("dbx-dameng-dir-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let error = validate_export_target(&dir).unwrap_err();
+ assert!(error.contains("is not a file"), "got: {error}");
+ let _ = std::fs::remove_file(&file);
+ let _ = std::fs::remove_dir(&dir);
+ }
+
+ #[test]
+ fn sibling_temp_dump_path_stays_in_target_dir_with_dmp_suffix() {
+ let target = std::path::Path::new("/data/exports/dcss.dmp");
+ let temp = sibling_temp_dump_path(target, "task-7");
+ assert_eq!(temp.parent(), target.parent());
+ assert_eq!(temp.extension().and_then(|e| e.to_str()), Some("dmp"));
+ let name = temp.file_name().unwrap().to_string_lossy().into_owned();
+ assert!(name.starts_with("dcss.dbx-dameng-task-7-"), "got: {name}");
+ }
+
+ #[test]
+ fn finalize_export_target_replaces_old_dump_atomically() {
+ let dir = std::env::temp_dir().join(format!("dbx-dameng-finalize-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let target = dir.join("out.dmp");
+ std::fs::write(&target, b"old").unwrap();
+ let temp = sibling_temp_dump_path(&target, "task-9");
+ std::fs::write(&temp, b"new").unwrap();
+ finalize_export_target(&temp, &target).unwrap();
+ assert_eq!(std::fs::read(&target).unwrap(), b"new");
+ assert!(!temp.exists(), "the temp file must be gone after the rename");
+ let error = finalize_export_target(&temp, &target).unwrap_err();
+ assert!(error.contains("was kept at"), "a failed rename must point at the kept dump: {error}");
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
+ #[test]
+ fn prepare_import_source_requires_existing_file() {
+ let file = std::env::temp_dir().join(format!("dbx-dameng-missing-{}.dmp", std::process::id()));
+ let error = prepare_import_source(&file).unwrap_err();
+ assert!(error.contains("Import file not found"), "got: {error}");
+ }
+
+ /// End-to-end runner check against a fake tool that behaves like dexp:
+ /// it writes a real success log (the same markers parse_dump_log tests
+ /// use) and exits 0. Proves spawn → capture → log-preferring parse →
+ /// outcome wiring without a live DM8.
+ #[tokio::test]
+ async fn run_tool_and_collect_parses_fake_success_log() {
+ let dir = std::env::temp_dir().join(format!("dbx-dameng-fake-tool-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let log_path = dir.join("run.log");
+ let out_path = dir.join("run.out");
+ let err_path = dir.join("run.err");
+
+ // The fake tool mirrors dexp: it writes a success log where the real
+ // tool would and exits 0. Windows uses the English success marker
+ // because cmd.exe `echo` writes in the OEM codepage, not UTF-8.
+ #[cfg(windows)]
+ let (tool, tool_args, expect_elapsed) = {
+ let tool = dir.join("fake.bat");
+ std::fs::write(
+ &tool,
+ "@echo off\r\necho dexp V8> \"%~dp0run.log\"\r\necho terminated successfully>> \"%~dp0run.log\"\r\n",
+ )
+ .unwrap();
+ (tool, vec!["USERID=u/p@h:5236".to_string(), "PARFILE=x".to_string()], false)
+ };
+ #[cfg(not(windows))]
+ let (tool, tool_args, expect_elapsed) = {
+ use std::os::unix::fs::PermissionsExt;
+ let tool = dir.join("fake.sh");
+ std::fs::write(
+ &tool,
+ "#!/bin/sh\necho 'dexp V8' > \"$(dirname \"$0\")/run.log\"\necho '整个导出过程共花费 4.032 s' >> \"$(dirname \"$0\")/run.log\"\necho '成功终止导出, 没有出现警告' >> \"$(dirname \"$0\")/run.log\"\n",
+ )
+ .unwrap();
+ std::fs::set_permissions(&tool, std::fs::Permissions::from_mode(0o755)).unwrap();
+ (tool, vec!["USERID=u/p@h:5236".to_string(), "PARFILE=x".to_string()], true)
+ };
+
+ let mut argv = vec![tool.to_string_lossy().into_owned()];
+ argv.extend(tool_args);
+ let text = run_tool_and_collect(&argv, &log_path, &out_path, &err_path, "fake-task").await.unwrap();
+ let outcome = parse_dump_log(&text, DamengDumpKind::Export);
+ assert!(outcome.success, "should parse the fake success log: {outcome:?}");
+ if expect_elapsed {
+ assert_eq!(outcome.elapsed_seconds.as_deref(), Some("4.032s"));
+ }
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
+ /// A tool that fails without writing a log must surface its stderr through
+ /// the console fallback and parse as failure.
+ #[tokio::test]
+ async fn run_tool_and_collect_surfaces_stderr_without_log() {
+ let dir = std::env::temp_dir().join(format!("dbx-dameng-fake-fail-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let log_path = dir.join("never-written.log");
+ let out_path = dir.join("run.out");
+ let err_path = dir.join("run.err");
+
+ #[cfg(windows)]
+ let (tool, tool_args) = {
+ let tool = dir.join("fail.bat");
+ std::fs::write(&tool, "@echo off\r\necho DMException: bad thing 1>&2\r\nexit /b 1\r\n").unwrap();
+ (tool, vec![])
+ };
+ #[cfg(not(windows))]
+ let (tool, tool_args) = {
+ use std::os::unix::fs::PermissionsExt;
+ let tool = dir.join("fail.sh");
+ std::fs::write(&tool, "#!/bin/sh\necho 'dm.jdbc.driver.DMException: boom' >&2\nexit 1\n").unwrap();
+ std::fs::set_permissions(&tool, std::fs::Permissions::from_mode(0o755)).unwrap();
+ (tool, vec![])
+ };
+
+ let mut argv = vec![tool.to_string_lossy().into_owned()];
+ argv.extend(tool_args);
+ let text = run_tool_and_collect(&argv, &log_path, &out_path, &err_path, "fake-fail-task").await.unwrap();
+ let outcome = parse_dump_log(&text, DamengDumpKind::Export);
+ assert!(!outcome.success);
+ assert!(outcome.error.as_deref().unwrap_or_default().contains("DMException"), "got: {outcome:?}");
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+}
diff --git a/crates/dbx-core/src/data/database_export.rs b/crates/dbx-core/src/data/database_export.rs
index 074256743b..c324758dbd 100644
--- a/crates/dbx-core/src/data/database_export.rs
+++ b/crates/dbx-core/src/data/database_export.rs
@@ -29,7 +29,7 @@ use crate::types::{ObjectSourceKind, SpatialColumn, SqlExportColumnSelection};
static EXPORT_CANCELLED: std::sync::LazyLock<RwLock<HashSet<String>>> =
std::sync::LazyLock::new(|| RwLock::new(HashSet::new()));
-const EXPORT_CANCELLED_ERROR: &str = "Export cancelled";
+pub const EXPORT_CANCELLED_ERROR: &str = "Export cancelled";
const EXPORT_CANCEL_POLL_INTERVAL: Duration = Duration::from_millis(50);
/// MySQL scripts written by the exporter are always UTF-8: values are decoded off the
diff --git a/crates/dbx-core/src/data/mod.rs b/crates/dbx-core/src/data/mod.rs
index 760e9f8d51..f1dc15e6c2 100644
--- a/crates/dbx-core/src/data/mod.rs
+++ b/crates/dbx-core/src/data/mod.rs
@@ -1,6 +1,7 @@
pub mod cloudflare_d1;
pub mod correction;
pub mod csv_export;
+pub mod dameng_dump;
pub mod data_compare;
pub mod database_export;
pub mod docs;
diff --git a/crates/dbx-core/src/lib.rs b/crates/dbx-core/src/lib.rs
index 6c4fa63530..4abeae6c65 100644
--- a/crates/dbx-core/src/lib.rs
+++ b/crates/dbx-core/src/lib.rs
@@ -37,6 +37,7 @@ pub use admin::consul;
pub use connection::connection_secrets;
pub use data::correction;
pub use data::csv_export;
+pub use data::dameng_dump;
pub use data::data_compare;
pub use data::database_export;
pub use dbx_drivers::database_capabilities;
diff --git a/crates/dbx-sql/src/dameng_dump.rs b/crates/dbx-sql/src/dameng_dump.rs
new file mode 100644
index 0000000000..02fa197cfb
--- /dev/null
+++ b/crates/dbx-sql/src/dameng_dump.rs
@@ -0,0 +1,252 @@
+//! Dameng native export/import (`.dmp`) command construction and log parsing.
+//!
+//! DBX's generic export is row-by-row and slow for a whole schema. Dameng ships the
+//! native `dexp`/`dimp` command-line tools (DM8) which export/import a schema or a set
+//! of tables to/from a `.dmp` file in seconds. This module builds the invocation and
+//! interprets the tool's log so the caller can drive the external process.
+//!
+//! Security note (known limitation, flagged for maintainers in the PR): Dameng requires
+//! `USERID` to be the FIRST command-line argument — unlike Oracle, the password cannot be
+//! moved into the `PARFILE`. So the password is necessarily visible in the process list
+//! (`ps -ef`) for the duration of the run. `PARFILE` is still used for the non-sensitive
+//! parameters to keep the command line short and debuggable.
+
+use crate::models::connection::DatabaseType;
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum DamengDumpKind {
+ Export,
+ Import,
+}
+
+/// A single `KEY=value` token in a dexp/dimp parameter file. Values are emitted verbatim
+/// (the caller is responsible for quoting identifiers); the builder quotes file/log paths.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct DamengDumpRequest {
+ pub db_type: DatabaseType,
+ pub kind: DamengDumpKind,
+ /// Absolute path to the `dexp`/`dimp` executable (configured by the user; the Dameng
+ /// client tools are not bundled with DBX).
+ pub tool_path: String,
+ pub host: String,
+ pub port: u16,
+ pub user: String,
+ pub password: String,
+ /// `.dmp` file to write (export) or read (import).
+ pub file_path: String,
+ /// `.log` file the tool writes.
+ pub log_path: String,
+ /// Schemas to export/import (SCHEMAS=). Empty means whole-database / not schema-scoped.
+ pub schemas: Vec<String>,
+ /// Explicit tables (TABLES=), mutually exclusive with `schemas` in practice.
+ pub tables: Vec<String>,
+ /// Import only: `REMAP_SCHEMA=SRC:DST`.
+ pub remap_schema: Option<(String, String)>,
+ /// Import only: `TABLE_EXISTS_ACTION=SKIP|REPLACE|TRUNCATE|APPEND`.
+ pub table_exists_action: Option<String>,
+}
+
+/// The `USERID` token, always the first argument: `USERID=<user>/<password>@<host>:<port>`.
+/// Password is NOT URL-escaped; Dameng accepts it verbatim. A `/` or `@` inside the user or
+/// password would be parsed as a field separator (the tool parses up to the first `@`), so
+/// callers must reject those up front via [`userid_field_error`] instead of launching.
+pub fn userid_token(user: &str, password: &str, host: &str, port: u16) -> String {
+ format!("USERID={user}/{password}@{host}:{port}")
+}
+
+/// Returns the field name whose value cannot be encoded in the `USERID` token
+/// (`/` separates user/password, `@` starts the host part), or `None` if both
+/// are safe to pass.
+pub fn userid_field_error(user: &str, password: &str) -> Option<&'static str> {
+ [(user, "username"), (password, "password")]
+ .into_iter()
+ .find_map(|(field, name)| (field.contains('/') || field.contains('@')).then_some(name))
+}
+
+/// Contents of the PARFILE: the non-sensitive parameters, one `KEY=value` per line.
+/// File/log paths are double-quoted so spaces and Windows backslashes survive.
+pub fn build_parfile_contents(req: &DamengDumpRequest) -> String {
+ let mut lines: Vec<String> = Vec::new();
+ lines.push(format!("FILE=\"{}\"", req.file_path));
+ lines.push(format!("LOG=\"{}\"", req.log_path));
+ if !req.schemas.is_empty() {
+ lines.push(format!("SCHEMAS={}", req.schemas.join(",")));
+ }
+ if !req.tables.is_empty() {
+ lines.push(format!("TABLES={}", req.tables.join(",")));
+ }
+ match req.kind {
+ DamengDumpKind::Export => {
+ // Match SQLark's fast, non-interactive defaults.
+ lines.push("TABLESPACE=N".to_string());
+ lines.push("DROP=N".to_string());
+ }
+ DamengDumpKind::Import => {
+ if let Some((src, dst)) = &req.remap_schema {
+ lines.push(format!("REMAP_SCHEMA={src}:{dst}"));
+ }
+ if let Some(action) = &req.table_exists_action {
+ lines.push(format!("TABLE_EXISTS_ACTION={action}"));
+ }
+ }
+ }
+ let mut text = lines.join("\n");
+ text.push('\n');
+ text
+}
+
+/// The full argv (program + USERID + PARFILE). The caller writes `parfile_path` (with
+/// [`build_parfile_contents`]) before invoking. USERID must be the first argument.
+pub fn build_command(req: &DamengDumpRequest, parfile_path: &str) -> Vec<String> {
+ vec![
+ req.tool_path.clone(),
+ userid_token(&req.user, &req.password, &req.host, req.port),
+ format!("PARFILE={parfile_path}"),
+ ]
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct DamengDumpOutcome {
+ pub success: bool,
+ pub warnings: bool,
+ pub elapsed_seconds: Option<String>,
+ pub error: Option<String>,
+}
+
+/// Interpret a dexp/dimp log body. Success is signalled by "成功终止导出/导入" (or the
+/// English "terminated successfully"); a per-line "[警告]" marks warnings; "DMException"
+/// or a missing success marker with an error line marks failure.
+pub fn parse_dump_log(text: &str, kind: DamengDumpKind) -> DamengDumpOutcome {
+ let success_zh = match kind {
+ DamengDumpKind::Export => text.contains("成功终止导出"),
+ DamengDumpKind::Import => text.contains("成功终止导入"),
+ };
+ let success_en = text.to_ascii_lowercase().contains("terminated successfully");
+ let success = success_zh || success_en;
+
+ let warnings = text.contains("[警告]");
+
+ let elapsed_seconds = text.lines().rev().find(|l| l.contains("共花费")).and_then(|l| {
+ l.split_whitespace().find_map(|tok| {
+ let t = tok.trim_end_matches('s');
+ if !t.is_empty() && t.parse::<f64>().is_ok() {
+ Some(format!("{t}s"))
+ } else {
+ None
+ }
+ })
+ });
+
+ let error = if success {
+ None
+ } else {
+ text.lines()
+ .rev()
+ .find(|l| {
+ l.contains("DMException")
+ || l.contains("错误")
+ || l.contains("失败")
+ || l.contains("EXP-")
+ || l.contains("IMP-")
+ })
+ .map(|l| l.trim().to_string())
+ .or_else(|| Some("dexp/dimp did not report success".to_string()))
+ };
+
+ DamengDumpOutcome { success, warnings, elapsed_seconds, error }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn req(kind: DamengDumpKind) -> DamengDumpRequest {
+ DamengDumpRequest {
+ db_type: DatabaseType::Dameng,
+ kind,
+ tool_path: "/opt/dmdbms/bin/dexp".to_string(),
+ host: "127.0.0.1".to_string(),
+ port: 5236,
+ user: "SYSDBA".to_string(),
+ password: "Dameng123".to_string(),
+ file_path: "/tmp/dbx_dcss.dmp".to_string(),
+ log_path: "/tmp/dbx_dcss.log".to_string(),
+ schemas: vec!["DCSS".to_string()],
+ tables: vec![],
+ remap_schema: None,
+ table_exists_action: None,
+ }
+ }
+
+ #[test]
+ fn userid_is_first_and_carries_credentials() {
+ assert_eq!(userid_token("SYSDBA", "Dameng123", "127.0.0.1", 5236), "USERID=SYSDBA/[email protected]:5236");
+ }
+
+ #[test]
+ fn userid_field_error_flags_breaking_chars_in_either_field() {
+ assert_eq!(userid_field_error("SYSDBA", "Dameng123"), None);
+ assert_eq!(userid_field_error("SYSDBA", "p@ss"), Some("password"));
+ assert_eq!(userid_field_error("SYSDBA", "p/ss"), Some("password"));
+ assert_eq!(userid_field_error("user@dba", "Dameng123"), Some("username"));
+ assert_eq!(userid_field_error("us/er", "Dameng123"), Some("username"));
+ }
+
+ #[test]
+ fn export_parfile_matches_real_invocation() {
+ let par = build_parfile_contents(&req(DamengDumpKind::Export));
+ assert_eq!(par, "FILE=\"/tmp/dbx_dcss.dmp\"\nLOG=\"/tmp/dbx_dcss.log\"\nSCHEMAS=DCSS\nTABLESPACE=N\nDROP=N\n");
+ }
+
+ #[test]
+ fn command_puts_userid_first_then_parfile() {
+ let argv = build_command(&req(DamengDumpKind::Export), "/tmp/dbx_dcss.par");
+ assert_eq!(argv[0], "/opt/dmdbms/bin/dexp");
+ assert_eq!(argv[1], "USERID=SYSDBA/[email protected]:5236");
+ assert_eq!(argv[2], "PARFILE=/tmp/dbx_dcss.par");
+ }
+
+ #[test]
+ fn import_parfile_adds_remap_and_exists_action() {
+ let mut r = req(DamengDumpKind::Import);
+ r.remap_schema = Some(("DCSS".to_string(), "DCSS_BAK".to_string()));
+ r.table_exists_action = Some("SKIP".to_string());
+ let par = build_parfile_contents(&r);
+ assert!(par.contains("REMAP_SCHEMA=DCSS:DCSS_BAK"));
+ assert!(par.contains("TABLE_EXISTS_ACTION=SKIP"));
+ assert!(!par.contains("TABLESPACE=N"));
+ }
+
+ #[test]
+ fn parses_real_successful_export_log() {
+ // Excerpt of the actual dexp run against DM8 (schema dcss, 90 tables, 4.032s).
+ let log = "dexp V8 \nversion: 03134284552\nstart dexp: SYSDBA/******@127.0.0.1:5236 FILE=/tmp/dbx_dcss.dmp\n开始导出模式[dcss].....\n共导出 90 个TABLE \n模式[dcss]导出结束.....\n成功导出 第1 个SCHEMA :dcss\n整个导出过程共花费 4.032 s\n\n成功终止导出, 没有出现警告\n";
+ let out = parse_dump_log(log, DamengDumpKind::Export);
+ assert!(out.success, "should be success: {out:?}");
+ assert!(!out.warnings);
+ assert_eq!(out.elapsed_seconds.as_deref(), Some("4.032s"));
+ assert_eq!(out.error, None);
+ }
+
+ #[test]
+ fn parses_real_successful_import_log() {
+ let log = "dimp V8 \nstart dimp: SYSDBA/******@127.0.0.1:5236\n[908/908]整个导入过程共花费 16.299 s\n\n成功终止导入, 没有出现警告\n";
+ let out = parse_dump_log(log, DamengDumpKind::Import);
+ assert!(out.success);
+ assert_eq!(out.elapsed_seconds.as_deref(), Some("16.299s"));
+ }
+
+ #[test]
+ fn detects_failure_and_warning() {
+ let warn = "dexp V8\n[警告]文件\"/tmp/x.dmp\"已经存在\n是否覆盖(y/n):";
+ let out = parse_dump_log(warn, DamengDumpKind::Export);
+ assert!(!out.success);
+ assert!(out.warnings);
+ assert!(out.error.is_some());
+
+ let err = "dexp V8\ndm.jdbc.driver.DMException: 第1 行第5 列附近出现错误";
+ let out = parse_dump_log(err, DamengDumpKind::Export);
+ assert!(!out.success);
+ assert!(out.error.unwrap().contains("DMException"));
+ }
+}
diff --git a/crates/dbx-sql/src/lib.rs b/crates/dbx-sql/src/lib.rs
index 9806dc8603..ba735ce321 100644
--- a/crates/dbx-sql/src/lib.rs
+++ b/crates/dbx-sql/src/lib.rs
@@ -10,3 +10,5 @@ pub use dbx_sql_data::{
pub use dbx_sql_dialect::{dml_binding, postgres_index_key, sql_dialect};
pub use dbx_sql_schema::{db_admin_sql, schema_diff, sql_parser, table_structure_sql};
pub use dbx_types::{database_manifest, models, types};
+
+pub mod dameng_dump;
diff --git a/src-tauri/src/commands/dameng_dump.rs b/src-tauri/src/commands/dameng_dump.rs
new file mode 100644
index 0000000000..a7ae5cbdd7
--- /dev/null
+++ b/src-tauri/src/commands/dameng_dump.rs
@@ -0,0 +1,43 @@
+use std::sync::Arc;
+use tauri::{AppHandle, Emitter, State};
+
+use crate::commands::connection::AppState;
+
+pub use dbx_core::dameng_dump::{resolve_damp_tool_path, DamengDumpKindArg, DamengDumpProgress, DamengDumpTaskRequest};
+
+fn emit_progress(app: &AppHandle, progress: DamengDumpProgress) {
+ let _ = app.emit("dameng-dump-progress", progress);
+}
+
+/// Start one native dexp/dimp run. The core emits a `Running` progress at
+/// start and exactly one terminal event (`Done`/`Error`/`Cancelled`) before
+/// returning, so this wrapper never synthesizes progress of its own.
+#[tauri::command]
+pub async fn start_dameng_dump(
+ app: AppHandle,
+ state: State<'_, Arc<AppState>>,
+ request: DamengDumpTaskRequest,
+) -> Result<(), String> {
+ let state = state.inner().clone();
+ let task_id = request.task_id.clone();
+ dbx_core::export_runtime::spawn_export_task(async move {
+ let _ = dbx_core::dameng_dump::run_dameng_dump_task(&state, &request, |progress| emit_progress(&app, progress))
+ .await;
+ dbx_core::dameng_dump::finish_dameng_dump_task(&task_id).await;
+ });
+ Ok(())
+}
+
+#[tauri::command]
+pub async fn cancel_dameng_dump(task_id: String) -> Result<(), String> {
+ dbx_core::database_export::set_export_cancelled(&task_id).await;
+ Ok(())
+}
+
+/// Resolve the `dexp`/`dimp` executable inside the user-configured client bin
+/// directory, so the settings UI can show a precise "tool not found" state
+/// without starting a dump.
+#[tauri::command]
+pub async fn resolve_dameng_dump_tool(bin_dir: String, kind: DamengDumpKindArg) -> Result<String, String> {
+ resolve_damp_tool_path(&bin_dir, kind.into()).map(|path| path.to_string_lossy().into_owned())
+}
diff --git a/src-tauri/src/commands/mod.rs b/src-tauri/src/commands/mod.rs
index 018764dc3a..92fbc29f8a 100644
--- a/src-tauri/src/commands/mod.rs
+++ b/src-tauri/src/commands/mod.rs
@@ -9,6 +9,7 @@ pub mod connection;
#[allow(dead_code, unused_imports)]
mod connection_secrets;
pub mod csv_export;
+pub mod dameng_dump;
pub mod data_compare;
pub mod database_export;
pub mod deep_link;
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index 5dd1542bf7..c20d4e7b44 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -2683,6 +2683,9 @@ pub fn run() {
commands::database_export::record_database_export_destination,
commands::table_export::start_table_export,
commands::table_export::cancel_table_export,
+ commands::dameng_dump::start_dameng_dump,
+ commands::dameng_dump::cancel_dameng_dump,
+ commands::dameng_dump::resolve_dameng_dump_tool,
commands::query_result_export::start_query_result_export,
commands::query_result_export::create_query_result_temp_file,
commands::query_result_export::open_query_result_temp_file,