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(backup): add Navicat .nb3 backup, restore, and external import

FrederykAbryan0297c5ecf9d7
diff --git a/apps/desktop/src/components/backup/DatabaseBackupConfigFields.vue b/apps/desktop/src/components/backup/DatabaseBackupConfigFields.vue
index e2aa531f6f..346cc3b1c8 100644
--- a/apps/desktop/src/components/backup/DatabaseBackupConfigFields.vue
+++ b/apps/desktop/src/components/backup/DatabaseBackupConfigFields.vue
@@ -238,11 +238,16 @@ watch(
</div>
<div class="space-y-2">
- <Label>{{ t("databaseBackup.compression") }}</Label>
- <label class="flex items-center gap-2 text-sm">
- <input :checked="draft.outputCompression === 'gzip'" type="checkbox" class="h-4 w-4 accent-primary" @change="draft.outputCompression = ($event.target as HTMLInputElement).checked ? 'gzip' : 'none'" />
- {{ t("databaseBackup.compressionGzip") }}
- </label>
+ <Label>{{ t("databaseBackup.backupFormat") }}</Label>
+ <Select v-model="draft.outputCompression">
+ <SelectTrigger data-backup-output-format class="w-full sm:w-65"><SelectValue /></SelectTrigger>
+ <SelectContent>
+ <SelectItem value="none">{{ t("databaseBackup.formatSql") }}</SelectItem>
+ <SelectItem value="gzip">{{ t("databaseBackup.compressionGzip") }}</SelectItem>
+ <SelectItem value="nb3">{{ t("databaseBackup.formatNb3") }}</SelectItem>
+ </SelectContent>
+ </Select>
+ <p v-if="draft.outputCompression === 'nb3'" data-backup-nb3-hint class="text-xs text-muted-foreground">{{ t("databaseBackup.formatNb3Hint") }}</p>
</div>
<div v-if="multipleConnectionsSelected" data-backup-multi-connection-hint class="rounded-md border border-border/70 bg-muted/30 px-3 py-2 text-xs text-muted-foreground">
diff --git a/apps/desktop/src/components/backup/ScheduledDatabaseBackupSettings.vue b/apps/desktop/src/components/backup/ScheduledDatabaseBackupSettings.vue
index e27b67bf0f..17cd5b98f2 100644
--- a/apps/desktop/src/components/backup/ScheduledDatabaseBackupSettings.vue
+++ b/apps/desktop/src/components/backup/ScheduledDatabaseBackupSettings.vue
@@ -10,7 +10,7 @@ import { Label } from "@/components/ui/label";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Switch } from "@/components/ui/switch";
-import { Check, ChevronDown, ChevronRight, DatabaseBackup, Download, FolderOpen, Loader2, Pencil, Play, Plus, RotateCcw, Search, Square, Trash2 } from "@lucide/vue";
+import { Check, ChevronDown, ChevronRight, DatabaseBackup, Download, FileInput, FolderOpen, Loader2, Pencil, Play, Plus, RotateCcw, Search, Square, Trash2 } from "@lucide/vue";
import * as api from "@/lib/backend/api";
import { useScheduledDatabaseBackups } from "@/composables/useScheduledDatabaseBackups";
import DatabaseBackupConfigFields from "@/components/backup/DatabaseBackupConfigFields.vue";
@@ -44,7 +44,27 @@ const { t, locale } = useI18n();
const { toast } = useToast();
const connectionStore = useConnectionStore();
const settingsStore = useSettingsStore();
-const { schedules, runs, activeScheduleIds, activeRunIds, cancellingRunIds, activeRuns, heartbeat, destinationRoot, error: backupError, saveSchedule, setScheduleEnabled, deleteSchedule, deleteRuns, renameRun, runSchedule, runOneShot, runOneShotBatch, cancelRun } = useScheduledDatabaseBackups();
+const {
+ schedules,
+ runs,
+ activeScheduleIds,
+ activeRunIds,
+ cancellingRunIds,
+ activeRuns,
+ heartbeat,
+ destinationRoot,
+ error: backupError,
+ saveSchedule,
+ setScheduleEnabled,
+ deleteSchedule,
+ deleteRuns,
+ importBackupFiles,
+ renameRun,
+ runSchedule,
+ runOneShot,
+ runOneShotBatch,
+ cancelRun,
+} = useScheduledDatabaseBackups();
const desktop = isTauriRuntime();
const backgroundEnabled = ref(false);
const backgroundBusy = ref(false);
@@ -117,7 +137,7 @@ const selectedRunIds = reactive(new Set<string>());
const historyConnectionId = ref("");
const historyConnectionPickerOpen = ref(false);
const historyConnectionSearch = ref("");
-const historyBackupMethod = ref<"all" | "manual" | "scheduled" | "one-shot">("all");
+const historyBackupMethod = ref<"all" | ReturnType<typeof runBackupMethod>>("all");
const historyStatus = ref<"all" | DatabaseBackupRun["status"]>("all");
const sqlConnections = computed(() => connectionStore.connections.filter((connection) => supportsScheduledDatabaseBackup(connection.db_type)));
@@ -126,7 +146,8 @@ const sortedRuns = computed(() => [...runs.value].sort((left, right) => Date.par
const historyConnections = computed(() => {
const connectionById = new Map<string, string>();
for (const run of sortedRuns.value) {
- if (!connectionById.has(run.connectionId)) connectionById.set(run.connectionId, run.connectionName || connectionName(run.connectionId));
+ // Imported backup files are not tied to a saved connection.
+ if (run.connectionId && !connectionById.has(run.connectionId)) connectionById.set(run.connectionId, run.connectionName || connectionName(run.connectionId));
}
return [...connectionById].map(([id, name]) => ({ id, name })).sort((left, right) => left.name.localeCompare(right.name, locale.value));
});
@@ -348,11 +369,18 @@ function selectHistoryConnection(connectionId: string) {
historyConnectionSearch.value = "";
}
-function runBackupMethod(run: DatabaseBackupRun): "manual" | "scheduled" | "one-shot" {
- if (run.source === "one-shot") return "one-shot";
+function runBackupMethod(run: DatabaseBackupRun): "manual" | "scheduled" | "one-shot" | "imported" {
+ if (run.source === "one-shot" || run.source === "imported") return run.source;
return run.trigger;
}
+function runBackupMethodLabel(run: DatabaseBackupRun): string {
+ const method = runBackupMethod(run);
+ if (method === "one-shot") return t("databaseBackup.oneShotTrigger");
+ if (method === "imported") return t("databaseBackup.importedTrigger");
+ return method === "scheduled" ? t("databaseBackup.scheduledTrigger") : t("databaseBackup.manualTrigger");
+}
+
function formatDate(value?: string): string {
if (!value || !Number.isFinite(Date.parse(value))) return t("databaseBackup.never");
return new Intl.DateTimeFormat(locale.value, { dateStyle: "medium", timeStyle: "short" }).format(new Date(value));
@@ -802,6 +830,46 @@ async function revealBackup(file: DatabaseBackupFile) {
}
}
+const BACKUP_FILE_FILTERS = [{ name: "Database backup", extensions: ["sql", "gz", "nb3"] }];
+
+async function pickBackupFiles(multiple: boolean): Promise<string[]> {
+ const { open } = await import("@tauri-apps/plugin-dialog");
+ const selected = await open({ multiple, filters: BACKUP_FILE_FILTERS });
+ return Array.isArray(selected) ? selected : selected ? [selected] : [];
+}
+
+/** Restores a backup file created anywhere, without adding it to the history. */
+async function restoreFromFile() {
+ try {
+ // The web SQL file dialog uploads the file itself; the desktop picks a local path first.
+ const [filePath] = desktop ? await pickBackupFiles(false) : [undefined];
+ if (desktop && !filePath) return;
+ connectionStore.sqlFileSource = { connectionId: "", database: "", ...(filePath ? { filePath } : {}) };
+ } catch (error) {
+ toast(translateBackendError(t, error), 5000);
+ }
+}
+
+async function importBackups() {
+ try {
+ const files = await pickBackupFiles(true);
+ if (files.length === 0) return;
+ const imported = await importBackupFiles(files);
+ toast(t("databaseBackup.backupsImported", { count: imported.length }), 2500);
+ } catch (error) {
+ toast(translateBackendError(t, error), 5000);
+ }
+}
+
+const pendingDeleteMessage = computed(() => {
+ const pending = pendingDeleteRunIds.value.map((runId) => runs.value.find((run) => run.id === runId)).filter((run): run is DatabaseBackupRun => !!run);
+ const owned = pending.filter((run) => run.source !== "imported");
+ if (owned.length === 0) return t("databaseBackup.deleteImportedConfirm", { count: pending.length });
+ const files = owned.reduce((total, run) => total + run.files.length, 0);
+ const message = pending.length === 1 ? t("databaseBackup.deleteBackupConfirm", { count: files }) : t("databaseBackup.deleteBackupsConfirm", { count: pending.length, files });
+ return owned.length === pending.length ? message : `${message} ${t("databaseBackup.importedFilesKept")}`;
+});
+
async function restoreBackup(run: DatabaseBackupRun, file: DatabaseBackupFile) {
try {
const prepared = desktop ? file.filePath : await api.prepareDatabaseBackupRestore(run.id, run.files.indexOf(file));
@@ -825,6 +893,14 @@ async function restoreBackup(run: DatabaseBackupRun, file: DatabaseBackupFile) {
<p v-if="!canCreateSchedule" class="mt-1 text-xs text-muted-foreground">{{ t("databaseBackup.noSupportedConnections") }}</p>
</div>
<div class="flex flex-wrap items-center justify-end gap-2">
+ <Button data-backup-restore-from-file variant="outline" size="sm" :title="t('databaseBackup.restoreFromFileHint')" @click="restoreFromFile">
+ <RotateCcw class="mr-2 h-4 w-4" />
+ {{ t("databaseBackup.restoreFromFile") }}
+ </Button>
+ <Button v-if="desktop" data-backup-import variant="outline" size="sm" :title="t('databaseBackup.importBackupHint')" @click="importBackups">
+ <FileInput class="mr-2 h-4 w-4" />
+ {{ t("databaseBackup.importBackup") }}
+ </Button>
<Button variant="outline" size="sm" :disabled="!canCreateSchedule" :title="canCreateSchedule ? t('databaseBackup.oneShotBackup') : t('databaseBackup.noSupportedConnections')" @click="openOneShotBackup">
<Play class="mr-2 h-4 w-4" />
{{ t("databaseBackup.oneShotBackup") }}
@@ -941,6 +1017,7 @@ async function restoreBackup(run: DatabaseBackupRun, file: DatabaseBackupFile) {
<SelectItem value="manual">{{ t("databaseBackup.manualTrigger") }}</SelectItem>
<SelectItem value="scheduled">{{ t("databaseBackup.scheduledTrigger") }}</SelectItem>
<SelectItem value="one-shot">{{ t("databaseBackup.oneShotTrigger") }}</SelectItem>
+ <SelectItem value="imported">{{ t("databaseBackup.importedTrigger") }}</SelectItem>
</SelectContent>
</Select>
<Select v-model="historyStatus">
@@ -987,10 +1064,10 @@ async function restoreBackup(run: DatabaseBackupRun, file: DatabaseBackupFile) {
<div class="flex min-w-0 flex-wrap items-center gap-2">
<span class="truncate text-sm font-medium">{{ run.displayName || run.scheduleName }}</span>
<Badge :variant="runStatusVariant(run.status)" class="font-normal">{{ displayedRunStatusLabel(run) }}</Badge>
- <Badge variant="outline" class="font-normal">{{ run.source === "one-shot" ? t("databaseBackup.oneShotTrigger") : run.trigger === "scheduled" ? t("databaseBackup.scheduledTrigger") : t("databaseBackup.manualTrigger") }}</Badge>
+ <Badge variant="outline" class="font-normal">{{ runBackupMethodLabel(run) }}</Badge>
</div>
<div class="mt-1 flex flex-wrap gap-x-4 gap-y-1 text-xs text-muted-foreground">
- <span>{{ run.connectionName || connectionName(run.connectionId) }}</span>
+ <span>{{ run.source === "imported" ? t("databaseBackup.externalFile") : run.connectionName || connectionName(run.connectionId) }}</span>
<span>{{ formatDate(run.startedAt) }}</span>
<span>{{ t("databaseBackup.fileCount", { count: run.files.length }) }}</span>
<span v-if="run.error" class="break-all text-destructive">{{ translateBackendError(t, run.error) }}</span>
@@ -1208,13 +1285,7 @@ async function restoreBackup(run: DatabaseBackupRun, file: DatabaseBackupFile) {
<DialogHeader
><DialogTitle>{{ t("databaseBackup.deleteBackup") }}</DialogTitle></DialogHeader
>
- <p class="text-sm text-muted-foreground">
- {{
- pendingDeleteRunIds.length === 1
- ? t("databaseBackup.deleteBackupConfirm", { count: runs.find((run) => run.id === pendingDeleteRunIds[0])?.files.length || 0 })
- : t("databaseBackup.deleteBackupsConfirm", { count: pendingDeleteRunIds.length, files: pendingDeleteRunIds.reduce((total, runId) => total + (runs.find((run) => run.id === runId)?.files.length || 0), 0) })
- }}
- </p>
+ <p data-backup-delete-message class="text-sm text-muted-foreground">{{ pendingDeleteMessage }}</p>
<DialogFooter>
<Button variant="outline" @click="deleteRunDialogOpen = false">{{ t("common.cancel") }}</Button>
<Button variant="destructive" @click="confirmDeleteRuns">{{ t("databaseBackup.delete") }}</Button>
diff --git a/apps/desktop/src/components/backup/__tests__/ScheduledDatabaseBackupSettings.spec.ts b/apps/desktop/src/components/backup/__tests__/ScheduledDatabaseBackupSettings.spec.ts
index 9495e9ff48..bad1a17ff1 100644
--- a/apps/desktop/src/components/backup/__tests__/ScheduledDatabaseBackupSettings.spec.ts
+++ b/apps/desktop/src/components/backup/__tests__/ScheduledDatabaseBackupSettings.spec.ts
@@ -32,6 +32,7 @@ const mocks = vi.hoisted(() => ({
deleteSchedule: vi.fn(),
deleteRun: vi.fn(),
deleteRuns: vi.fn(),
+ importBackupFiles: vi.fn(),
renameRun: vi.fn(),
runSchedule: vi.fn(),
runOneShot: vi.fn(),
@@ -75,6 +76,7 @@ vi.mock("@/composables/useScheduledDatabaseBackups", () => ({
deleteSchedule: mocks.deleteSchedule,
deleteRun: mocks.deleteRun,
deleteRuns: mocks.deleteRuns,
+ importBackupFiles: mocks.importBackupFiles,
renameRun: mocks.renameRun,
runSchedule: mocks.runSchedule,
runOneShot: mocks.runOneShot,
@@ -154,6 +156,9 @@ function destinationInput(): HTMLInputElement {
return input;
}
+// The backup format select precedes the table scope select in the config fields.
+const TABLE_SCOPE_SELECT = 1;
+
async function selectDialogOption(triggerIndex: number, optionText: string) {
const trigger = currentDialog().querySelectorAll<HTMLButtonElement>('[data-slot="select-trigger"]')[triggerIndex];
if (!trigger) throw new Error(`Select trigger not found: ${triggerIndex}`);
@@ -167,7 +172,7 @@ async function selectDialogOption(triggerIndex: number, optionText: string) {
}
async function setTablePattern(pattern: string) {
- await selectDialogOption(0, String(i18n.global.t("databaseBackup.includeTables")));
+ await selectDialogOption(TABLE_SCOPE_SELECT, String(i18n.global.t("databaseBackup.includeTables")));
const input = currentDialog().querySelector<HTMLInputElement>(`input[placeholder="${String(i18n.global.t("databaseBackup.tablePatternsPlaceholder"))}"]`);
if (!input) throw new Error("Table pattern input not found");
input.value = pattern;
@@ -252,7 +257,9 @@ async function showDatabaseOptions() {
}
function buttonWithText(text: string): HTMLButtonElement {
- const button = Array.from(document.body.querySelectorAll("button")).find((item) => item.textContent?.includes(text));
+ // Prefer an exact label so "Restore" does not match "Restore from file".
+ const buttons = Array.from(document.body.querySelectorAll("button"));
+ const button = buttons.find((item) => item.textContent?.trim() === text) ?? buttons.find((item) => item.textContent?.includes(text));
if (!button) throw new Error(`Button not found: ${text}`);
return button;
}
@@ -346,6 +353,7 @@ afterEach(() => {
mocks.saveSchedule.mockClear();
mocks.deleteRun.mockClear();
mocks.deleteRuns.mockClear();
+ mocks.importBackupFiles.mockReset();
mocks.renameRun.mockReset();
mocks.cancelRun.mockClear();
mocks.runSchedule.mockReset();
@@ -381,6 +389,57 @@ describe("ScheduledDatabaseBackupSettings schedule dialog", () => {
else expect(mocks.prepareDatabaseBackupRestore).toHaveBeenCalledWith("restore-run", 0);
});
+ it("imports outside backup files into the history and restores any file without importing it", async () => {
+ mocks.openDirectory.mockResolvedValueOnce(["/downloads/shop.nb3", "/downloads/old.sql.gz"]);
+ mocks.importBackupFiles.mockResolvedValue([{ id: "imported-1" }, { id: "imported-2" }]);
+ await mountSettings();
+
+ document.body.querySelector<HTMLButtonElement>("[data-backup-import]")!.click();
+ await flush();
+ expect(mocks.openDirectory).toHaveBeenCalledWith(expect.objectContaining({ multiple: true }));
+ expect(mocks.importBackupFiles).toHaveBeenCalledWith(["/downloads/shop.nb3", "/downloads/old.sql.gz"]);
+ expect(mocks.toast).toHaveBeenCalledWith(String(i18n.global.t("databaseBackup.backupsImported", { count: 2 })), 2500);
+
+ mocks.openDirectory.mockResolvedValueOnce("/downloads/navicat.nb3");
+ document.body.querySelector<HTMLButtonElement>("[data-backup-restore-from-file]")!.click();
+ await flush();
+ expect(mocks.sqlFileSource).toEqual({ connectionId: "", database: "", filePath: "/downloads/navicat.nb3" });
+ expect(mocks.importBackupFiles).toHaveBeenCalledTimes(1);
+ });
+
+ it("opens the uploading SQL file dialog to restore from a file on the web, where import is unavailable", async () => {
+ mocks.desktop = false;
+ await mountSettings();
+
+ expect(document.body.querySelector("[data-backup-import]")).toBeNull();
+ document.body.querySelector<HTMLButtonElement>("[data-backup-restore-from-file]")!.click();
+ await flush();
+ expect(mocks.openDirectory).not.toHaveBeenCalled();
+ expect(mocks.sqlFileSource).toEqual({ connectionId: "", database: "" });
+ });
+
+ it("labels imported backups and says deleting them keeps the files", async () => {
+ mocks.runs.push({
+ id: "imported-run",
+ scheduleName: "shop.nb3",
+ connectionId: "",
+ connectionName: "",
+ trigger: "manual",
+ source: "imported",
+ status: "success",
+ startedAt: "2026-09-08T02:00:00.000Z",
+ files: [{ database: "shop", schema: "sales", displayName: "shop.sales", filePath: "/downloads/shop.nb3" }],
+ });
+ await mountSettings();
+
+ expect(document.body.textContent).toContain(String(i18n.global.t("databaseBackup.importedTrigger")));
+ expect(document.body.textContent).toContain(String(i18n.global.t("databaseBackup.externalFile")));
+ expect(document.body.textContent).not.toContain(String(i18n.global.t("databaseBackup.missingConnection")));
+ buttonWithTitle(String(i18n.global.t("databaseBackup.deleteBackup"))).click();
+ await flush();
+ expect(currentDialog().querySelector("[data-backup-delete-message]")?.textContent).toBe(String(i18n.global.t("databaseBackup.deleteImportedConfirm", { count: 1 })));
+ });
+
it("shows a backup display name and saves edits through the rename dialog", async () => {
mocks.runs.push({
id: "renamed-run",
@@ -705,7 +764,7 @@ describe("ScheduledDatabaseBackupSettings schedule dialog", () => {
database.checked = true;
database.dispatchEvent(new Event("change", { bubbles: true }));
await flush();
- await selectDialogOption(0, String(i18n.global.t("databaseBackup.exactTables")));
+ await selectDialogOption(TABLE_SCOPE_SELECT, String(i18n.global.t("databaseBackup.exactTables")));
await flush();
const start = Array.from(currentDialog().querySelectorAll<HTMLButtonElement>("button")).find((item) => item.textContent?.trim() === String(i18n.global.t("databaseBackup.startBackup")))!;
expect(start.disabled).toBe(true);
@@ -824,7 +883,7 @@ describe("ScheduledDatabaseBackupSettings schedule dialog", () => {
const database = Array.from(currentDialog().querySelectorAll<HTMLInputElement>('input[type="checkbox"]')).find((item) => item.parentElement?.textContent?.trim() === "app")!;
database.checked = true;
database.dispatchEvent(new Event("change", { bubbles: true }));
- await selectDialogOption(0, String(i18n.global.t("databaseBackup.exactTables")));
+ await selectDialogOption(TABLE_SCOPE_SELECT, String(i18n.global.t("databaseBackup.exactTables")));
await flush();
expect(currentDialog().querySelector("[data-backup-table-selector]")).not.toBeNull();
@@ -835,7 +894,7 @@ describe("ScheduledDatabaseBackupSettings schedule dialog", () => {
expect(currentDialog().querySelector("[data-backup-database-search]")).toBeNull();
expect(currentDialog().querySelector("[data-backup-table-selector]")).toBeNull();
expect(startBackupButton().disabled).toBe(false);
- const trigger = currentDialog().querySelectorAll<HTMLButtonElement>('[data-slot="select-trigger"]')[0]!;
+ const trigger = currentDialog().querySelectorAll<HTMLButtonElement>('[data-slot="select-trigger"]')[TABLE_SCOPE_SELECT]!;
trigger.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowDown", bubbles: true, cancelable: true }));
await flush();
const options = Array.from(document.body.querySelectorAll<HTMLElement>('[role="option"]')).map((item) => item.textContent?.trim());
diff --git a/apps/desktop/src/components/sql-file/SqlFileExecutionDialog.vue b/apps/desktop/src/components/sql-file/SqlFileExecutionDialog.vue
index 4ba6cffafa..00c67c53d4 100644
--- a/apps/desktop/src/components/sql-file/SqlFileExecutionDialog.vue
+++ b/apps/desktop/src/components/sql-file/SqlFileExecutionDialog.vue
@@ -672,7 +672,7 @@ async function selectFile() {
const { open } = await import("@tauri-apps/plugin-dialog");
const selected = await open({
multiple: true,
- filters: [{ name: "SQL package", extensions: ["sql", "gz", "zip"] }],
+ filters: [{ name: "SQL package", extensions: ["sql", "gz", "zip", "nb3"] }],
});
const paths = Array.isArray(selected) ? selected : selected ? [selected] : [];
if (paths.length > 0) {
@@ -1018,7 +1018,7 @@ watch(
</div>
<div class="flex items-center gap-2">
- <input ref="fileInput" type="file" accept=".sql,.sql.gz,.zip,text/sql,application/gzip,application/zip" multiple class="hidden" @change="handleFileInputChange" />
+ <input ref="fileInput" type="file" accept=".sql,.sql.gz,.zip,.nb3,text/sql,application/gzip,application/zip" multiple class="hidden" @change="handleFileInputChange" />
<Input v-if="isDesktopRuntime" v-model="pathInput" :disabled="executionLocked" class="h-8 text-xs font-mono" :placeholder="t('sqlFile.selectSqlFile')" @keydown.enter="commitPathInputOnEnter" @blur="commitPathInput" />
<Input v-else :model-value="filePathDisplay" readonly class="h-8 text-xs font-mono" :placeholder="t('sqlFile.selectSqlFile')" />
<Button variant="outline" size="sm" class="h-8 shrink-0" :disabled="executionLocked || selectingFile" @click="selectFile">
diff --git a/apps/desktop/src/composables/useScheduledDatabaseBackups.ts b/apps/desktop/src/composables/useScheduledDatabaseBackups.ts
index 228976b6e0..f966991ace 100644
--- a/apps/desktop/src/composables/useScheduledDatabaseBackups.ts
+++ b/apps/desktop/src/composables/useScheduledDatabaseBackups.ts
@@ -115,6 +115,13 @@ export function useScheduledDatabaseBackups(_options: { scheduler?: boolean } =
await refreshAfterMutation();
}
+ /** Adds backup files created outside DBX to the history; returns the new runs. */
+ async function importBackupFiles(files: readonly string[]) {
+ const imported = await api.databaseBackupCommand<DatabaseBackupRun[]>({ action: "import", files: [...files] });
+ await refreshAfterMutation();
+ return imported;
+ }
+
async function renameRun(id: string, name: string) {
if (activeRunIds.has(id)) return false;
await api.databaseBackupCommand({ action: "rename", id, name: name.trim() });
@@ -203,6 +210,7 @@ export function useScheduledDatabaseBackups(_options: { scheduler?: boolean } =
deleteSchedule,
deleteRuns,
deleteRun: (id: string) => deleteRuns([id]),
+ importBackupFiles,
renameRun,
runSchedule,
runOneShot,
diff --git a/apps/desktop/src/i18n/locales/az.ts b/apps/desktop/src/i18n/locales/az.ts
index 893244bcdf..af1a19a0b8 100644
--- a/apps/desktop/src/i18n/locales/az.ts
+++ b/apps/desktop/src/i18n/locales/az.ts
@@ -9108,8 +9108,20 @@ export default withEnglishFallback({
runDirectoryPatternHint:
"Təyinat qovluğu daxilində nisbi yol. {'{'}schedule{'}'}, {'{'}date{'}'}, {'{'}timestamp{'}'} və {'{'}runId{'}'} şablonlarından istifadə edin. Standart şablona əlavə təcrid üçün {'{'}runId{'}'} daxildir. Nümunə: {'{'}schedule{'}'}/{'{'}date{'}'}/{'{'}timestamp{'}'}-{'{'}runId{'}'}",
runDirectoryPatternInvalid: ". və ya .. hissələri olmayan nisbi yoldan istifadə edin.",
- compression: "Sıxılma",
+ backupFormat: "Ehtiyat nüsxə formatı",
compressionGzip: "Gzip (.sql.gz)",
+ formatSql: "SQL (.sql)",
+ formatNb3: "Navicat ehtiyat nüsxəsi (.nb3)",
+ formatNb3Hint: "MySQL və PostgreSQL üçün Navicat ehtiyat nüsxə formatı. DBX onu istənilən SQL ehtiyat nüsxəsi kimi bərpa edir.",
+ restoreFromFile: "Fayldan bərpa et",
+ restoreFromFileHint: "İstənilən yerdən .sql, .sql.gz və ya .nb3 ehtiyat nüsxə faylını bərpa edin",
+ importBackup: "Ehtiyat nüsxəni idxal et",
+ importBackupHint: "DBX xaricində yaradılmış ehtiyat nüsxə fayllarını (məsələn, Navicat .nb3 arxivləri) tarixçəyə əlavə edin",
+ importedTrigger: "İdxal edilib",
+ externalFile: "Xarici fayl",
+ backupsImported: "Tarixçəyə {count} ehtiyat nüsxə əlavə edildi",
+ deleteImportedConfirm: "{count} idxal edilmiş ehtiyat nüsxə tarixçədən silinsin? Fayllar diskdə qalır.",
+ importedFilesKept: "İdxal edilmiş ehtiyat nüsxə faylları yalnız tarixçədən silinir və diskdə qalır.",
searchConnections: "Əlaqələrdə axtarış…",
noMatchingConnections: "Uyğun əlaqə yoxdur",
connectionsSelected: "{count} əlaqə seçilib",
diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.ts
index df19de5eb0..065935363c 100644
--- a/apps/desktop/src/i18n/locales/en.ts
+++ b/apps/desktop/src/i18n/locales/en.ts
@@ -11041,8 +11041,20 @@ export default {
runDirectoryPattern: "Run directory template",
runDirectoryPatternHint: "A relative path under the destination. Use {'{'}schedule{'}'}, {'{'}date{'}'}, {'{'}timestamp{'}'}, and {'{'}runId{'}'}. The default includes {'{'}runId{'}'} for extra isolation. Example: {'{'}schedule{'}'}/{'{'}date{'}'}/{'{'}timestamp{'}'}-{'{'}runId{'}'}",
runDirectoryPatternInvalid: "Use a relative path without . or .. segments.",
- compression: "Compression",
+ backupFormat: "Backup format",
compressionGzip: "Gzip (.sql.gz)",
+ formatSql: "SQL (.sql)",
+ formatNb3: "Navicat backup (.nb3)",
+ formatNb3Hint: "Navicat backup format for MySQL and PostgreSQL. DBX restores it like any SQL backup.",
+ restoreFromFile: "Restore from file",
+ restoreFromFileHint: "Restore a .sql, .sql.gz or .nb3 backup file from anywhere",
+ importBackup: "Import backup",
+ importBackupHint: "Add backup files created outside DBX, such as Navicat .nb3 archives, to the backup history",
+ importedTrigger: "Imported",
+ externalFile: "External file",
+ backupsImported: "Added {count} backups to history",
+ deleteImportedConfirm: "Remove {count} imported backups from the history? The files stay on disk.",
+ importedFilesKept: "Imported backup files are only removed from the history and stay on disk.",
searchConnections: "Search connections…",
noMatchingConnections: "No matching connections",
connectionsSelected: "{count} connections selected",
diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.ts
index 94212571cc..2ae8a6dfc8 100644
--- a/apps/desktop/src/i18n/locales/es.ts
+++ b/apps/desktop/src/i18n/locales/es.ts
@@ -11939,8 +11939,20 @@ export default withEnglishFallback({
runDirectoryPatternHint:
"Ruta relativa dentro del directorio de destino. Use {'{'}schedule{'}'}, {'{'}date{'}'}, {'{'}timestamp{'}'} y {'{'}runId{'}'}. La plantilla predeterminada incluye {'{'}runId{'}'} para un mejor aislamiento. Ejemplo: {'{'}schedule{'}'}/{'{'}date{'}'}/{'{'}timestamp{'}'}-{'{'}runId{'}'}",
runDirectoryPatternInvalid: "Use una ruta relativa sin segmentos . ni ..",
- compression: "Compresión",
+ backupFormat: "Formato de copia de seguridad",
compressionGzip: "Compresión Gzip (.sql.gz)",
+ formatSql: "SQL (.sql)",
+ formatNb3: "Copia de seguridad de Navicat (.nb3)",
+ formatNb3Hint: "Formato de copia de seguridad de Navicat para MySQL y PostgreSQL. DBX lo restaura como cualquier copia SQL.",
+ restoreFromFile: "Restaurar desde archivo",
+ restoreFromFileHint: "Restaura un archivo de copia de seguridad .sql, .sql.gz o .nb3 desde cualquier ubicación",
+ importBackup: "Importar copia de seguridad",
+ importBackupHint: "Añade al historial archivos de copia de seguridad creados fuera de DBX, como archivos .nb3 de Navicat",
+ importedTrigger: "Importada",
+ externalFile: "Archivo externo",
+ backupsImported: "Se añadieron {count} copias de seguridad al historial",
+ deleteImportedConfirm: "¿Quitar {count} copias de seguridad importadas del historial? Los archivos permanecen en el disco.",
+ importedFilesKept: "Las copias de seguridad importadas solo se quitan del historial; los archivos permanecen en el disco.",
searchConnections: "Buscar conexiones…",
noMatchingConnections: "No hay conexiones coincidentes",
connectionsSelected: "{count} conexiones seleccionadas",
diff --git a/apps/desktop/src/i18n/locales/id.ts b/apps/desktop/src/i18n/locales/id.ts
index 9fa73d672d..4a54ea3ea2 100644
--- a/apps/desktop/src/i18n/locales/id.ts
+++ b/apps/desktop/src/i18n/locales/id.ts
@@ -9945,8 +9945,20 @@ export default withEnglishFallback({
runDirectoryPattern: "Template direktori proses",
runDirectoryPatternHint: "Path relatif di bawah direktori tujuan. Gunakan {'{'}schedule{'}'}, {'{'}date{'}'}, {'{'}timestamp{'}'}, dan {'{'}runId{'}'}. Default menyertakan {'{'}runId{'}'} untuk isolasi tambahan. Contoh: {'{'}schedule{'}'}/{'{'}date{'}'}/{'{'}timestamp{'}'}-{'{'}runId{'}'}",
runDirectoryPatternInvalid: "Gunakan path relatif tanpa segmen . atau ..",
- compression: "Kompresi",
+ backupFormat: "Format cadangan",
compressionGzip: "Gzip (.sql.gz)",
+ formatSql: "SQL (.sql)",
+ formatNb3: "Cadangan Navicat (.nb3)",
+ formatNb3Hint: "Format cadangan Navicat untuk MySQL dan PostgreSQL. DBX memulihkannya seperti cadangan SQL lainnya.",
+ restoreFromFile: "Pulihkan dari file",
+ restoreFromFileHint: "Pulihkan file cadangan .sql, .sql.gz, atau .nb3 dari lokasi mana pun",
+ importBackup: "Impor cadangan",
+ importBackupHint: "Tambahkan file cadangan yang dibuat di luar DBX, seperti arsip Navicat .nb3, ke riwayat cadangan",
+ importedTrigger: "Diimpor",
+ externalFile: "File eksternal",
+ backupsImported: "{count} cadangan ditambahkan ke riwayat",
+ deleteImportedConfirm: "Hapus {count} cadangan yang diimpor dari riwayat? File tetap ada di disk.",
+ importedFilesKept: "Cadangan yang diimpor hanya dihapus dari riwayat; file tetap ada di disk.",
searchConnections: "Cari koneksi…",
noMatchingConnections: "Tidak ada koneksi yang cocok",
connectionsSelected: "{count} koneksi dipilih",
diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.ts
index 762ded5e9b..a9c81b500a 100644
--- a/apps/desktop/src/i18n/locales/it.ts
+++ b/apps/desktop/src/i18n/locales/it.ts
@@ -11480,8 +11480,20 @@ export default withEnglishFallback({
runDirectoryPatternHint:
"Percorso relativo nella directory di destinazione. Usa {'{'}schedule{'}'}, {'{'}date{'}'}, {'{'}timestamp{'}'} e {'{'}runId{'}'}. Il modello predefinito include {'{'}runId{'}'} per un maggiore isolamento. Esempio: {'{'}schedule{'}'}/{'{'}date{'}'}/{'{'}timestamp{'}'}-{'{'}runId{'}'}",
runDirectoryPatternInvalid: "Usa un percorso relativo senza segmenti . o ..",
- compression: "Compressione",
+ backupFormat: "Formato del backup",
compressionGzip: "Compressione Gzip (.sql.gz)",
+ formatSql: "SQL (.sql)",
+ formatNb3: "Backup Navicat (.nb3)",
+ formatNb3Hint: "Formato di backup di Navicat per MySQL e PostgreSQL. DBX lo ripristina come qualsiasi backup SQL.",
+ restoreFromFile: "Ripristina da file",
+ restoreFromFileHint: "Ripristina un file di backup .sql, .sql.gz o .nb3 da qualsiasi percorso",
+ importBackup: "Importa backup",
+ importBackupHint: "Aggiungi alla cronologia i file di backup creati fuori da DBX, come gli archivi .nb3 di Navicat",
+ importedTrigger: "Importato",
+ externalFile: "File esterno",
+ backupsImported: "Aggiunti {count} backup alla cronologia",
+ deleteImportedConfirm: "Rimuovere {count} backup importati dalla cronologia? I file restano sul disco.",
+ importedFilesKept: "I backup importati vengono solo rimossi dalla cronologia; i file restano sul disco.",
searchConnections: "Cerca connessioni…",
noMatchingConnections: "Nessuna connessione corrispondente",
connectionsSelected: "{count} connessioni selezionate",
diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.ts
index e29c5875b4..1a0617ea14 100644
--- a/apps/desktop/src/i18n/locales/ja.ts
+++ b/apps/desktop/src/i18n/locales/ja.ts
@@ -11527,8 +11527,20 @@ export default withEnglishFallback({
runDirectoryPatternHint:
"バックアップ先配下の相対パスです。{'{'}schedule{'}'}、{'{'}date{'}'}、{'{'}timestamp{'}'}、{'{'}runId{'}'} を使用できます。既定のテンプレートには、より確実に分離するため {'{'}runId{'}'} が含まれます。例:{'{'}schedule{'}'}/{'{'}date{'}'}/{'{'}timestamp{'}'}-{'{'}runId{'}'}",
runDirectoryPatternInvalid: ". または .. を含まない相対パスを入力してください。",
- compression: "圧縮",
+ backupFormat: "バックアップ形式",
compressionGzip: "Gzip 圧縮(.sql.gz)",
+ formatSql: "SQL(.sql)",
+ formatNb3: "Navicat バックアップ(.nb3)",
+ formatNb3Hint: "MySQL と PostgreSQL 向けの Navicat バックアップ形式です。DBX では通常の SQL バックアップと同様に復元できます。",
+ restoreFromFile: "ファイルから復元",
+ restoreFromFileHint: "任意の場所にある .sql、.sql.gz、.nb3 のバックアップファイルを復元します",
+ importBackup: "バックアップをインポート",
+ importBackupHint: "Navicat の .nb3 など、DBX 以外で作成したバックアップファイルを履歴に追加します",
+ importedTrigger: "インポート",
+ externalFile: "外部ファイル",
+ backupsImported: "{count} 件のバックアップを履歴に追加しました",
+ deleteImportedConfirm: "インポートした {count} 件のバックアップを履歴から削除しますか?ファイルはディスクに残ります。",
+ importedFilesKept: "インポートしたバックアップは履歴から削除されるだけで、ファイルはディスクに残ります。",
searchConnections: "接続を検索…",
noMatchingConnections: "一致する接続がありません",
connectionsSelected: "{count} 件の接続を選択中",
diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.ts
index 2c0d7cec5c..5d90cb7994 100644
--- a/apps/desktop/src/i18n/locales/ko.ts
+++ b/apps/desktop/src/i18n/locales/ko.ts
@@ -9821,8 +9821,20 @@ export default withEnglishFallback({
friday: "금요일",
saturday: "토요일",
},
- compression: "압축",
+ backupFormat: "백업 형식",
compressionGzip: "Gzip 압축(.sql.gz)",
+ formatSql: "SQL(.sql)",
+ formatNb3: "Navicat 백업(.nb3)",
+ formatNb3Hint: "MySQL 및 PostgreSQL용 Navicat 백업 형식입니다. DBX에서는 일반 SQL 백업처럼 복원할 수 있습니다.",
+ restoreFromFile: "파일에서 복원",
+ restoreFromFileHint: "어느 위치에 있든 .sql, .sql.gz, .nb3 백업 파일을 복원합니다",
+ importBackup: "백업 가져오기",
+ importBackupHint: "Navicat .nb3 아카이브처럼 DBX 외부에서 만든 백업 파일을 백업 기록에 추가합니다",
+ importedTrigger: "가져옴",
+ externalFile: "외부 파일",
+ backupsImported: "백업 {count}개를 기록에 추가했습니다",
+ deleteImportedConfirm: "가져온 백업 {count}개를 기록에서 제거할까요? 파일은 디스크에 그대로 남습니다.",
+ importedFilesKept: "가져온 백업은 기록에서만 제거되며 파일은 디스크에 남습니다.",
searchConnections: "연결 검색…",
noMatchingConnections: "일치하는 연결을 찾을 수 없습니다.",
connectionsSelected: "연결 {count}개 선택됨",
diff --git a/apps/desktop/src/i18n/locales/pl.ts b/apps/desktop/src/i18n/locales/pl.ts
index 45698f9c59..28f23f62e6 100644
--- a/apps/desktop/src/i18n/locales/pl.ts
+++ b/apps/desktop/src/i18n/locales/pl.ts
@@ -9972,8 +9972,20 @@ export default withEnglishFallback({
runDirectoryPattern: "Szablon katalogu uruchomienia",
runDirectoryPatternHint: "Ścieżka względna wewnątrz katalogu docelowego. Użyj {'{'}schedule{'}'}, {'{'}date{'}'}, {'{'}timestamp{'}'} i {'{'}runId{'}'}. Domyślnie zawiera {'{'}runId{'}'} dla izolacji. Przykład: {'{'}schedule{'}'}/{'{'}date{'}'}/{'{'}timestamp{'}'}-{'{'}runId{'}'}",
runDirectoryPatternInvalid: "Użyj ścieżki względnej bez segmentów . lub ..",
- compression: "Kompresja",
+ backupFormat: "Format kopii zapasowej",
compressionGzip: "Gzip (.sql.gz)",
+ formatSql: "SQL (.sql)",
+ formatNb3: "Kopia zapasowa Navicat (.nb3)",
+ formatNb3Hint: "Format kopii zapasowej Navicat dla MySQL i PostgreSQL. DBX przywraca go jak każdą kopię SQL.",
+ restoreFromFile: "Przywróć z pliku",
+ restoreFromFileHint: "Przywróć plik kopii zapasowej .sql, .sql.gz lub .nb3 z dowolnego miejsca",
+ importBackup: "Importuj kopię zapasową",
+ importBackupHint: "Dodaj do historii pliki kopii zapasowych utworzone poza DBX, np. archiwa .nb3 z Navicat",
+ importedTrigger: "Zaimportowana",
+ externalFile: "Plik zewnętrzny",
+ backupsImported: "Dodano {count} kopii zapasowych do historii",
+ deleteImportedConfirm: "Usunąć {count} zaimportowanych kopii zapasowych z historii? Pliki pozostaną na dysku.",
+ importedFilesKept: "Zaimportowane kopie zapasowe są tylko usuwane z historii; pliki pozostają na dysku.",
searchConnections: "Szukaj połączeń…",
noMatchingConnections: "Brak pasujących połączeń",
connectionsSelected: "Wybrane połączenia: {count}",
diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.ts
index 73981a30c8..d2c426b272 100644
--- a/apps/desktop/src/i18n/locales/pt-BR.ts
+++ b/apps/desktop/src/i18n/locales/pt-BR.ts
@@ -11499,8 +11499,20 @@ export default withEnglishFallback({
runDirectoryPatternHint:
"Um caminho relativo dentro do diretório de destino. Use {'{'}schedule{'}'}, {'{'}date{'}'}, {'{'}timestamp{'}'} e {'{'}runId{'}'}. O modelo padrão inclui {'{'}runId{'}'} para maior isolamento. Exemplo: {'{'}schedule{'}'}/{'{'}date{'}'}/{'{'}timestamp{'}'}-{'{'}runId{'}'}",
runDirectoryPatternInvalid: "Use um caminho relativo sem segmentos . ou ..",
- compression: "Compactação",
+ backupFormat: "Formato do backup",
compressionGzip: "Compactação Gzip (.sql.gz)",
+ formatSql: "SQL (.sql)",
+ formatNb3: "Backup do Navicat (.nb3)",
+ formatNb3Hint: "Formato de backup do Navicat para MySQL e PostgreSQL. O DBX o restaura como qualquer backup SQL.",
+ restoreFromFile: "Restaurar de arquivo",
+ restoreFromFileHint: "Restaure um arquivo de backup .sql, .sql.gz ou .nb3 de qualquer local",
+ importBackup: "Importar backup",
+ importBackupHint: "Adicione ao histórico arquivos de backup criados fora do DBX, como arquivos .nb3 do Navicat",
+ importedTrigger: "Importado",
+ externalFile: "Arquivo externo",
+ backupsImported: "{count} backups adicionados ao histórico",
+ deleteImportedConfirm: "Remover {count} backups importados do histórico? Os arquivos permanecem no disco.",
+ importedFilesKept: "Backups importados são apenas removidos do histórico; os arquivos permanecem no disco.",
searchConnections: "Pesquisar conexões…",
noMatchingConnections: "Nenhuma conexão correspondente",
connectionsSelected: "{count} conexões selecionadas",
diff --git a/apps/desktop/src/i18n/locales/ru.ts b/apps/desktop/src/i18n/locales/ru.ts
index 6e506b8887..d4428e4b04 100644
--- a/apps/desktop/src/i18n/locales/ru.ts
+++ b/apps/desktop/src/i18n/locales/ru.ts
@@ -11235,8 +11235,20 @@ export default withEnglishFallback({
runDirectoryPatternHint:
"Относительный путь внутри каталога назначения. Используйте {'{'}schedule{'}'}, {'{'}date{'}'}, {'{'}timestamp{'}'} и {'{'}runId{'}'}. По умолчанию добавляется {'{'}runId{'}'} для дополнительной изоляции. Пример: {'{'}schedule{'}'}/{'{'}date{'}'}/{'{'}timestamp{'}'}-{'{'}runId{'}'}",
runDirectoryPatternInvalid: "Используйте относительный путь без сегментов . или ..",
- compression: "Сжатие",
+ backupFormat: "Формат резервной копии",
compressionGzip: "Gzip (.sql.gz)",
+ formatSql: "SQL (.sql)",
+ formatNb3: "Резервная копия Navicat (.nb3)",
+ formatNb3Hint: "Формат резервной копии Navicat для MySQL и PostgreSQL. DBX восстанавливает его так же, как обычную SQL-копию.",
+ restoreFromFile: "Восстановить из файла",
+ restoreFromFileHint: "Восстановить резервную копию из файла .sql, .sql.gz или .nb3 в любом месте",
+ importBackup: "Импортировать копию",
+ importBackupHint: "Добавить в историю резервные копии, созданные вне DBX, например архивы Navicat .nb3",
+ importedTrigger: "Импортировано",
+ externalFile: "Внешний файл",
+ backupsImported: "Добавлено резервных копий в историю: {count}",
+ deleteImportedConfirm: "Удалить импортированные резервные копии из истории ({count})? Файлы останутся на диске.",
+ importedFilesKept: "Импортированные резервные копии только удаляются из истории; файлы остаются на диске.",
searchConnections: "Поиск подключений…",
noMatchingConnections: "Подходящие подключения не найдены",
connectionsSelected: "Выбрано подключений: {count}",
diff --git a/apps/desktop/src/i18n/locales/th.ts b/apps/desktop/src/i18n/locales/th.ts
index 1b5210eda2..437708ad7b 100644
--- a/apps/desktop/src/i18n/locales/th.ts
+++ b/apps/desktop/src/i18n/locales/th.ts
@@ -11653,8 +11653,20 @@ export default withEnglishFallback({
runDirectoryPattern: "เทมเพลตไดเรกทอรีการเรียกใช้",
runDirectoryPatternHint: "Path สัมพัทธ์ใต้ปลายทาง ใช้ {'{'}schedule{'}'}, {'{'}date{'}'}, {'{'}timestamp{'}'} และ {'{'}runId{'}'} ค่าเริ่มต้นรวม {'{'}runId{'}'} เพื่อแยกข้อมูลเพิ่มเติม ตัวอย่าง: {'{'}schedule{'}'}/{'{'}date{'}'}/{'{'}timestamp{'}'}-{'{'}runId{'}'}",
runDirectoryPatternInvalid: "ใช้ Path สัมพัทธ์โดยไม่มีส่วน . หรือ ..",
- compression: "การบีบอัด",
+ backupFormat: "รูปแบบการสำรองข้อมูล",
compressionGzip: "Gzip (.sql.gz)",
+ formatSql: "SQL (.sql)",
+ formatNb3: "ไฟล์สำรอง Navicat (.nb3)",
+ formatNb3Hint: "รูปแบบไฟล์สำรองของ Navicat สำหรับ MySQL และ PostgreSQL โดย DBX กู้คืนได้เหมือนไฟล์สำรอง SQL ทั่วไป",
+ restoreFromFile: "กู้คืนจากไฟล์",
+ restoreFromFileHint: "กู้คืนไฟล์สำรอง .sql, .sql.gz หรือ .nb3 จากตำแหน่งใดก็ได้",
+ importBackup: "นำเข้าไฟล์สำรอง",
+ importBackupHint: "เพิ่มไฟล์สำรองที่สร้างนอก DBX เช่น ไฟล์ .nb3 ของ Navicat ลงในประวัติการสำรอง",
+ importedTrigger: "นำเข้า",
+ externalFile: "ไฟล์ภายนอก",
+ backupsImported: "เพิ่มไฟล์สำรอง {count} รายการลงในประวัติแล้ว",
+ deleteImportedConfirm: "ลบไฟล์สำรองที่นำเข้า {count} รายการออกจากประวัติหรือไม่ ไฟล์จะยังอยู่บนดิสก์",
+ importedFilesKept: "ไฟล์สำรองที่นำเข้าจะถูกลบออกจากประวัติเท่านั้น ไฟล์ยังอยู่บนดิสก์",
searchConnections: "ค้นหาการเชื่อมต่อ…",
noMatchingConnections: "ไม่มีการเชื่อมต่อที่ตรงกัน",
connectionsSelected: "เลือกการเชื่อมต่อแล้ว {count} รายการ",
diff --git a/apps/desktop/src/i18n/locales/tr.ts b/apps/desktop/src/i18n/locales/tr.ts
index df0a96c339..3e013e1760 100644
--- a/apps/desktop/src/i18n/locales/tr.ts
+++ b/apps/desktop/src/i18n/locales/tr.ts
@@ -8992,8 +8992,20 @@ export default withEnglishFallback({
runDirectoryPattern: "Çalıştırma dizini şablonu",
runDirectoryPatternHint: "Hedef dizin altındaki göreli yol. {'{'}schedule{'}'}, {'{'}date{'}'}, {'{'}timestamp{'}'} ve {'{'}runId{'}'} kullanın. Varsayılan şablon daha iyi yalıtım için {'{'}runId{'}'} içerir. Örnek: {'{'}schedule{'}'}/{'{'}date{'}'}/{'{'}timestamp{'}'}-{'{'}runId{'}'}",
runDirectoryPatternInvalid: ". veya .. bölümleri içermeyen göreli bir yol kullanın.",
- compression: "Sıkıştırma",
+ backupFormat: "Yedek biçimi",
compressionGzip: "Gzip (.sql.gz)",
+ formatSql: "SQL (.sql)",
+ formatNb3: "Navicat yedeği (.nb3)",
+ formatNb3Hint: "MySQL ve PostgreSQL için Navicat yedek biçimi. DBX bunu herhangi bir SQL yedeği gibi geri yükler.",
+ restoreFromFile: "Dosyadan geri yükle",
+ restoreFromFileHint: "Herhangi bir konumdaki .sql, .sql.gz veya .nb3 yedek dosyasını geri yükleyin",
+ importBackup: "Yedeği içe aktar",
+ importBackupHint: "DBX dışında oluşturulan yedek dosyalarını (ör. Navicat .nb3 arşivleri) yedek geçmişine ekleyin",
+ importedTrigger: "İçe aktarıldı",
+ externalFile: "Harici dosya",
+ backupsImported: "Geçmişe {count} yedek eklendi",
+ deleteImportedConfirm: "İçe aktarılan {count} yedek geçmişten kaldırılsın mı? Dosyalar diskte kalır.",
+ importedFilesKept: "İçe aktarılan yedekler yalnızca geçmişten kaldırılır; dosyalar diskte kalır.",
searchConnections: "Bağlantılarda ara…",
noMatchingConnections: "Eşleşen bağlantı yok",
connectionsSelected: "{count} bağlantı seçildi",
diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.ts
index 7cc6e02c35..54f5cee867 100644
--- a/apps/desktop/src/i18n/locales/zh-CN.ts
+++ b/apps/desktop/src/i18n/locales/zh-CN.ts
@@ -11004,8 +11004,20 @@ export default withEnglishFallback({
runDirectoryPattern: "运行目录模板",
runDirectoryPatternHint: "相对于备份目录的路径。可使用 {'{'}schedule{'}'}、{'{'}date{'}'}、{'{'}timestamp{'}'} 和 {'{'}runId{'}'}。默认模板保留 {'{'}runId{'}'} 以获得更好的隔离性。例如:{'{'}schedule{'}'}/{'{'}date{'}'}/{'{'}timestamp{'}'}-{'{'}runId{'}'}",
runDirectoryPatternInvalid: "请输入不含 . 或 .. 路径段的相对路径。",
- compression: "压缩",
+ backupFormat: "备份格式",
compressionGzip: "Gzip 压缩(.sql.gz)",
+ formatSql: "SQL(.sql)",
+ formatNb3: "Navicat 备份(.nb3)",
+ formatNb3Hint: "适用于 MySQL 和 PostgreSQL 的 Navicat 备份格式,DBX 可像普通 SQL 备份一样恢复。",
+ restoreFromFile: "从文件恢复",
+ restoreFromFileHint: "从任意位置恢复 .sql、.sql.gz 或 .nb3 备份文件",
+ importBackup: "导入备份",
+ importBackupHint: "将在 DBX 之外创建的备份文件(如 Navicat .nb3 归档)添加到备份历史",
+ importedTrigger: "已导入",
+ externalFile: "外部文件",
+ backupsImported: "已将 {count} 个备份添加到历史",
+ deleteImportedConfirm: "要从历史中移除 {count} 个导入的备份吗?文件会保留在磁盘上。",
+ importedFilesKept: "导入的备份只会从历史中移除,文件仍保留在磁盘上。",
searchConnections: "搜索连接…",
noMatchingConnections: "未找到匹配的连接",
connectionsSelected: "已选择 {count} 个连接",
diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.ts
index 466235b88c..5ae3ee1266 100644
--- a/apps/desktop/src/i18n/locales/zh-TW.ts
+++ b/apps/desktop/src/i18n/locales/zh-TW.ts
@@ -11496,8 +11496,20 @@ export default withEnglishFallback({
runDirectoryPattern: "執行目錄範本",
runDirectoryPatternHint: "相對於備份目錄的路徑。可使用 {'{'}schedule{'}'}、{'{'}date{'}'}、{'{'}timestamp{'}'} 和 {'{'}runId{'}'}。預設範本保留 {'{'}runId{'}'} 以獲得更好的隔離性。例如:{'{'}schedule{'}'}/{'{'}date{'}'}/{'{'}timestamp{'}'}-{'{'}runId{'}'}",
runDirectoryPatternInvalid: "請輸入不含 . 或 .. 路徑段的相對路徑。",
- compression: "壓縮",
+ backupFormat: "備份格式",
compressionGzip: "Gzip 壓縮(.sql.gz)",
+ formatSql: "SQL(.sql)",
+ formatNb3: "Navicat 備份(.nb3)",
+ formatNb3Hint: "適用於 MySQL 與 PostgreSQL 的 Navicat 備份格式,DBX 可像一般 SQL 備份一樣還原。",
+ restoreFromFile: "從檔案還原",
+ restoreFromFileHint: "從任意位置還原 .sql、.sql.gz 或 .nb3 備份檔案",
+ importBackup: "匯入備份",
+ importBackupHint: "將在 DBX 之外建立的備份檔案(如 Navicat .nb3 封存檔)加入備份歷史",
+ importedTrigger: "已匯入",
+ externalFile: "外部檔案",
+ backupsImported: "已將 {count} 個備份加入歷史",
+ deleteImportedConfirm: "要從歷史中移除 {count} 個匯入的備份嗎?檔案會保留在磁碟上。",
+ importedFilesKept: "匯入的備份只會從歷史中移除,檔案仍保留在磁碟上。",
searchConnections: "搜尋連線…",
noMatchingConnections: "找不到相符的連線",
connectionsSelected: "已選取 {count} 個連線",
diff --git a/apps/desktop/src/lib/backend/tauri.ts b/apps/desktop/src/lib/backend/tauri.ts
index 788c932c6c..e580ae33ce 100644
--- a/apps/desktop/src/lib/backend/tauri.ts
+++ b/apps/desktop/src/lib/backend/tauri.ts
@@ -6420,7 +6420,7 @@ export interface DatabaseExportRequest {
preserveOriginalLanguage?: boolean;
failOnError?: boolean;
preventOverwrite?: boolean;
- outputCompression?: "none" | "gzip";
+ outputCompression?: "none" | "gzip" | "nb3";
insertDialect?: SqlInsertDialect;
insertMode?: "batch" | "single";
snapshotSessionId?: string;
diff --git a/apps/desktop/src/lib/backup/backgroundDatabaseBackup.ts b/apps/desktop/src/lib/backup/backgroundDatabaseBackup.ts
index 597f31747e..17cd2bddb8 100644
--- a/apps/desktop/src/lib/backup/backgroundDatabaseBackup.ts
+++ b/apps/desktop/src/lib/backup/backgroundDatabaseBackup.ts
@@ -17,7 +17,8 @@ export type DatabaseBackupCommand =
| { action: "run"; request: { scheduleId?: string; config?: DatabaseBackupExecutionConfig; displayName?: string; timeZone?: string } }
| { action: "cancel"; id: string }
| { action: "rename"; id: string; name: string }
- | { action: "deleteRuns"; ids: string[] };
+ | { action: "deleteRuns"; ids: string[] }
+ | { action: "import"; files: string[] };
export interface DatabaseBackupBackgroundStatus {
enabled: boolean;
diff --git a/apps/desktop/src/lib/backup/scheduledDatabaseBackup.ts b/apps/desktop/src/lib/backup/scheduledDatabaseBackup.ts
index 44b8308583..0773ac3449 100644
--- a/apps/desktop/src/lib/backup/scheduledDatabaseBackup.ts
+++ b/apps/desktop/src/lib/backup/scheduledDatabaseBackup.ts
@@ -13,9 +13,17 @@ export type DatabaseBackupFrequency = "hourly" | "daily" | "weekly";
export type DatabaseBackupExportStatus = "Running" | "Done" | "Error" | "Cancelled";
export type DatabaseBackupRunStatus = "running" | "success" | "failed" | "cancelled";
export type DatabaseBackupRunTrigger = "manual" | "scheduled";
-export type DatabaseBackupRunSource = "scheduled" | "one-shot";
+/** `imported` runs list backup files created outside DBX; DBX never deletes their files. */
+export type DatabaseBackupRunSource = "scheduled" | "one-shot" | "imported";
export type DatabaseBackupTableFilterMode = "all" | "include" | "exclude" | "selected";
-export type DatabaseBackupOutputCompression = "none" | "gzip";
+/** Output format of a backup file: plain SQL, gzipped SQL, or a Navicat `.nb3` archive. */
+export type DatabaseBackupOutputCompression = "none" | "gzip" | "nb3";
+
+const DATABASE_BACKUP_FILE_SUFFIXES: Record<DatabaseBackupOutputCompression, string> = { none: ".sql", gzip: ".sql.gz", nb3: ".nb3" };
+
+export function normalizeDatabaseBackupOutputCompression(value: unknown): DatabaseBackupOutputCompression {
+ return value === "gzip" || value === "nb3" ? value : "none";
+}
const CONSISTENT_BACKUP_DATABASE_TYPES = new Set(["mysql", "postgres"]);
@@ -308,7 +316,7 @@ export function normalizeDatabaseBackupSchedule(value: unknown, now = new Date()
includeData: booleanValue(input.includeData, true),
includeObjects: booleanValue(input.includeObjects, true),
dropTableIfExists: booleanValue(input.dropTableIfExists, false),
- outputCompression: input.outputCompression === "gzip" ? "gzip" : "none",
+ outputCompression: normalizeDatabaseBackupOutputCompression(input.outputCompression),
fileNamePattern: normalizeDatabaseBackupFileNamePattern(input.fileNamePattern),
retentionCount: normalizeDatabaseBackupRetention(input.retentionCount),
runDirectoryPattern: normalizeDatabaseBackupRunDirectoryPattern(input.runDirectoryPattern),
@@ -377,7 +385,7 @@ export function normalizeDatabaseBackupRun(value: unknown): DatabaseBackupRun |
connectionName: stringValue(input.connectionName).trim(),
destinationDirectory: stringValue(input.destinationDirectory).trim() || undefined,
trigger: input.trigger === "scheduled" ? "scheduled" : "manual",
- source: input.source === "one-shot" ? "one-shot" : "scheduled",
+ source: input.source === "one-shot" || input.source === "imported" ? input.source : "scheduled",
status,
startedAt,
completedAt: typeof input.completedAt === "string" && Number.isFinite(Date.parse(input.completedAt)) ? input.completedAt : undefined,
@@ -546,7 +554,7 @@ export function joinDatabaseBackupPath(directory: string, fileName: string): str
}
export function databaseBackupFilePath(directory: string, scheduleName: string, fileStem: string, startedAt: Date | string, runId: string, outputCompression: DatabaseBackupOutputCompression = "none", fileNamePattern?: string, timeZone?: string): string {
- const suffix = outputCompression === "gzip" ? ".sql.gz" : ".sql";
+ const suffix = DATABASE_BACKUP_FILE_SUFFIXES[outputCompression] ?? ".sql";
const fileName = `${renderDatabaseBackupFileNamePattern(fileNamePattern ?? DEFAULT_DATABASE_BACKUP_FILE_NAME_PATTERN, scheduleName, fileStem, startedAt, runId, timeZone)}${suffix}`;
return joinDatabaseBackupPath(directory, fileName);
}
diff --git a/apps/desktop/src/lib/settings/settingsSearch.ts b/apps/desktop/src/lib/settings/settingsSearch.ts
index 4605fdf091..91856f1fa9 100644
--- a/apps/desktop/src/lib/settings/settingsSearch.ts
+++ b/apps/desktop/src/lib/settings/settingsSearch.ts
@@ -529,8 +529,10 @@ export const SETTINGS_SEARCH_DEFINITIONS: readonly SettingsSearchDefinition[] =
"databaseBackup.outputPathTemplate",
"databaseBackup.runDirectoryPattern",
"databaseBackup.fileNamePattern",
- "databaseBackup.compression",
+ "databaseBackup.backupFormat",
+ "databaseBackup.formatSql",
"databaseBackup.compressionGzip",
+ "databaseBackup.formatNb3",
"databaseBackup.databases",
"databaseBackup.allDatabases",
"databaseBackup.tableScope",
diff --git a/crates/dbx-core/src/data/database_export.rs b/crates/dbx-core/src/data/database_export.rs
index 19e2584772..7cdc1d7cdd 100644
--- a/crates/dbx-core/src/data/database_export.rs
+++ b/crates/dbx-core/src/data/database_export.rs
@@ -76,6 +76,8 @@ pub enum DatabaseExportOutputCompression {
#[default]
None,
Gzip,
+ /// Navicat `.nb3` backup archive (MySQL and PostgreSQL only).
+ Nb3,
}
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
@@ -177,6 +179,7 @@ enum DatabaseExportWriter {
Plain(BufWriter<std::fs::File>),
Gzip(Box<GzEncoder<BufWriter<std::fs::File>>>),
SplitZip(Box<crate::export_split_zip::SplitZipExportWriter>),
+ Nb3(Box<crate::navicat_nb3::Nb3ExportWriter>),
}
impl DatabaseExportWriter {
@@ -185,6 +188,7 @@ impl DatabaseExportWriter {
Self::Plain(writer) => writer.write_all(unit),
Self::Gzip(writer) => writer.write_all(unit),
Self::SplitZip(writer) => writer.write_sql_unit(unit),
+ Self::Nb3(writer) => writer.write_all(unit),
}
}
}
@@ -195,6 +199,7 @@ impl Write for DatabaseExportWriter {
Self::Plain(writer) => writer.write(buffer),
Self::Gzip(writer) => writer.write(buffer),
Self::SplitZip(writer) => writer.write(buffer),
+ Self::Nb3(writer) => writer.write(buffer),
}
}
@@ -209,6 +214,7 @@ impl Write for DatabaseExportWriter {
Self::Plain(writer) => writer.flush(),
Self::Gzip(writer) => writer.flush(),
Self::SplitZip(writer) => writer.flush(),
+ Self::Nb3(writer) => writer.flush(),
}
}
}
@@ -224,6 +230,7 @@ impl DatabaseExportWriter {
.and_then(|mut output| output.flush())
.map_err(|error| format!("Failed to finalize export file: {error}")),
Self::SplitZip(writer) => writer.finish(source_file_name),
+ Self::Nb3(writer) => writer.finish(),
}
}
}
@@ -3791,6 +3798,20 @@ async fn create_database_export_writer(
}
return Ok(DatabaseExportWriter::SplitZip(Box::new(writer)));
}
+ // Reject unsupported connections before the destination is created or truncated.
+ let nb3_database_type = if request.output_compression == DatabaseExportOutputCompression::Nb3 {
+ let db_type = state
+ .configs
+ .read()
+ .await
+ .get(&request.connection_id)
+ .map(|config| config.db_type)
+ .ok_or_else(|| format!("Connection config not found: {}", request.connection_id))?;
+ crate::navicat_nb3::ensure_supported_database_type(db_type)?;
+ Some(db_type)
+ } else {
+ None
+ };
let file = std::fs::OpenOptions::new()
.write(true)
.create(true)
@@ -3835,6 +3856,20 @@ async fn create_database_export_writer(
DatabaseExportOutputCompression::Gzip => {
DatabaseExportWriter::Gzip(Box::new(GzEncoder::new(BufWriter::new(file), Compression::default())))
}
+ DatabaseExportOutputCompression::Nb3 => {
+ let db_type = nb3_database_type.expect("Navicat backup database type is validated before opening");
+ let writer = crate::navicat_nb3::Nb3ExportWriter::new(
+ file,
+ export_destination_parent_dir(&request.file_path),
+ db_type,
+ &request.database,
+ &request.schema,
+ )
+ .inspect_err(|_| {
+ let _ = std::fs::remove_file(&request.file_path);
+ })?;
+ DatabaseExportWriter::Nb3(Box::new(writer))
+ }
})
}
diff --git a/crates/dbx-core/src/data/mod.rs b/crates/dbx-core/src/data/mod.rs
index cf9ca1fd8b..95017e1043 100644
--- a/crates/dbx-core/src/data/mod.rs
+++ b/crates/dbx-core/src/data/mod.rs
@@ -9,6 +9,7 @@ pub mod export_runtime;
pub mod grid_clipboard_guard;
pub mod mongodb_dump;
pub mod mongodb_import_export;
+pub mod navicat_nb3;
pub mod query_result_export;
mod sample_pairing;
pub mod script_generator;
diff --git a/crates/dbx-core/src/data/navicat_nb3.rs b/crates/dbx-core/src/data/navicat_nb3.rs
new file mode 100644
index 0000000000..7569eaa51d
--- /dev/null
+++ b/crates/dbx-core/src/data/navicat_nb3.rs
@@ -0,0 +1,1997 @@
+//! Navicat `.nb3` backup archives.
+//!
+//! An `.nb3` file is a POSIX tar archive. `meta.json` lists every backed-up object;
+//! each object has a gzipped `<uuid>.meta.json.gz` holding its DDL, and a table also
+//! has gzipped `<uuid>.data.NNNNN.sql.gz` row chunks. A row chunk holds SQL value
+//! tuples (`(1, 'a', NULL)`) separated by `\x1e\n`. Every member referenced by the
+//! metadata carries the upper-case SHA-1 of its stored (compressed) bytes.
+//!
+//! DBX restores an archive by rendering it as a SQL script ([`Nb3SqlReader`]) and
+//! writes one by splitting its own SQL export into Navicat objects ([`Nb3ExportWriter`]).
+
+use std::collections::{HashMap, VecDeque};
+use std::fs::File;
+use std::io::{BufReader, BufWriter, Read, Seek, SeekFrom, Write};
+use std::path::{Path, PathBuf};
+use std::sync::atomic::{AtomicU64, Ordering};
+use std::sync::Arc;
+
+use flate2::{read::MultiGzDecoder, write::GzEncoder, Compression};
+use serde::{Deserialize, Serialize};
+use sha1::{Digest, Sha1};
+
+use crate::models::connection::DatabaseType;
+use crate::sql::{SqlParsingOptions, SqlStatementSplitter};
+
+const META_VERSION: &str = "30101";
+const MANIFEST_NAME: &str = "meta.json";
+const RECORD_SEPARATOR: &[u8] = b"\x1e\n";
+const METADATA_MAX_BYTES: u64 = 256 * 1024 * 1024;
+const DATA_CHUNK_MAX_BYTES: u64 = 16 * 1024 * 1024;
+/// Upper bound for a single row tuple while it is still being decompressed. The
+/// row stream only retains the unfinished tuple between reads, so without this
+/// cap a crafted gzip member that never closes a tuple grows memory without limit.
+const ROW_TUPLE_MAX_BYTES: usize = 64 * 1024 * 1024;
+const EXPORT_SPLIT_THRESHOLD_BYTES: usize = 64 * 1024;
+const RESTORE_INSERT_MAX_ROWS: usize = 1000;
+const RESTORE_INSERT_MAX_BYTES: usize = 1024 * 1024;
+
+pub fn ensure_supported_database_type(db_type: DatabaseType) -> Result<(), String> {
+ Nb3Dialect::from_database_type(db_type).map(|_| ())
+}
+
+pub fn is_nb3_path(path: &Path) -> bool {
+ path.extension()
+ .and_then(|extension| extension.to_str())
+ .is_some_and(|extension| extension.eq_ignore_ascii_case("nb3"))
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "PascalCase")]
+struct Nb3Manifest {
+ meta_version: String,
+ database_type: String,
+ #[serde(default)]
+ service_provider: String,
+ #[serde(default)]
+ catalog: String,
+ #[serde(default)]
+ schema: String,
+ #[serde(default)]
+ start_time: String,
+ #[serde(default)]
+ end_time: String,
+ #[serde(default)]
+ encryption: String,
+ #[serde(default)]
+ comment: String,
+ #[serde(default)]
+ objects: Vec<Nb3ObjectEntry>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "PascalCase")]
+struct Nb3ObjectEntry {
+ #[serde(rename = "UUID")]
+ uuid: String,
+ #[serde(rename = "Type")]
+ object_type: String,
+ name: String,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ rows: Option<String>,
+ metadata: Nb3MemberRef,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "PascalCase")]
+struct Nb3MemberRef {
+ filename: String,
+ #[serde(default)]
+ checksum: String,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "PascalCase")]
+struct Nb3ObjectMeta {
+ meta_version: String,
+ name: String,
+ #[serde(rename = "Type")]
+ object_type: String,
+ #[serde(rename = "DDL", default)]
+ ddl: String,
+ #[serde(rename = "SubDDL", default)]
+ sub_ddl: Vec<String>,
+ #[serde(default)]
+ auto_increment: String,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ fields: Option<Vec<String>>,
+ #[serde(rename = "TriggerDDL", default)]
+ trigger_ddl: Vec<String>,
+ #[serde(rename = "IndexDDL", default)]
+ index_ddl: Vec<String>,
+ #[serde(default)]
+ data: Vec<Nb3MemberRef>,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum Nb3Dialect {
+ Mysql,
+ Postgres,
+}
+
+impl Nb3Dialect {
+ fn from_archive(value: &str) -> Result<Self, String> {
+ match value.trim().to_ascii_uppercase().as_str() {
+ "MYSQL" | "MARIADB" => Ok(Self::Mysql),
+ "PGSQL" | "POSTGRESQL" => Ok(Self::Postgres),
+ other => Err(format!("Unsupported Navicat backup database type: {other}")),
+ }
+ }
+
+ fn from_database_type(db_type: DatabaseType) -> Result<Self, String> {
+ match db_type {
+ DatabaseType::Mysql => Ok(Self::Mysql),
+ DatabaseType::Postgres => Ok(Self::Postgres),
+ _ => Err("Navicat .nb3 backups support MySQL and PostgreSQL connections only".to_string()),
+ }
+ }
+
+ fn archive_name(self) -> &'static str {
+ match self {
+ Self::Mysql => "MYSQL",
+ Self::Postgres => "PGSQL",
+ }
+ }
+
+ fn database_type(self) -> DatabaseType {
+ match self {
+ Self::Mysql => DatabaseType::Mysql,
+ Self::Postgres => DatabaseType::Postgres,
+ }
+ }
+
+ fn quote(self, name: &str) -> String {
+ match self {
+ Self::Mysql => format!("`{}`", name.replace('`', "``")),
+ Self::Postgres => format!("\"{}\"", name.replace('"', "\"\"")),
+ }
+ }
+}
+
+/// Creation order of Navicat object types: dependencies first, views after tables.
+fn creation_rank(object_type: &str) -> u8 {
+ match object_type {
+ "Extension" => 0,
+ "Type" | "Domain" => 1,
+ "Sequence" => 2,
+ "Function" | "Procedure" => 3,
+ "Table" => 4,
+ "View" | "MaterializedView" => 5,
+ _ => 6,
+ }
+}
+
+fn is_routine_like(object_type: &str) -> bool {
+ matches!(object_type, "Function" | "Procedure" | "Event" | "Trigger")
+}
+
+fn sha1_hex(bytes: &[u8]) -> String {
+ Sha1::digest(bytes).iter().map(|byte| format!("{byte:02X}")).collect()
+}
+
+fn io_error(message: impl Into<String>) -> std::io::Error {
+ std::io::Error::new(std::io::ErrorKind::InvalidData, message.into())
+}
+
+/// Navicat writes CRLF-formatted, two-space indented JSON.
+fn navicat_json<T: Serialize>(value: &T) -> Result<Vec<u8>, String> {
+ let text = serde_json::to_string_pretty(value).map_err(|error| error.to_string())?;
+ Ok(text.replace('\n', "\r\n").into_bytes())
+}
+
+// ---------------------------------------------------------------------------
+// Value tuples
+// ---------------------------------------------------------------------------
+
+/// Finds top-level `( ... )` value tuples, skipping quoted text. MySQL strings always
+/// treat a backslash as an escape; PostgreSQL strings only do inside `E'...'`.
+struct TupleScanner {
+ dialect: Nb3Dialect,
+ depth: usize,
+ quote: Option<u8>,
+ backslash_escapes: bool,
+ escaped: bool,
+ start: usize,
+}
+
+enum TupleScan {
+ /// A complete tuple spans `start..end` of the scanned buffer.
+ Tuple { start: usize, end: usize },
+ /// The buffer ends inside a tuple, or between tuples.
+ Incomplete,
+}
+
+impl TupleScanner {
+ fn new(dialect: Nb3Dialect) -> Self {
+ Self { dialect, depth: 0, quote: None, backslash_escapes: false, escaped: false, start: 0 }
+ }
+
+ fn is_between_tuples(&self) -> bool {
+ self.depth == 0 && self.quote.is_none()
+ }
+
+ /// Scans `buffer[*pos..]` for the next complete tuple, advancing `pos`. State is
+ /// kept between calls, so the buffer may grow while a tuple is open.
+ fn next(&mut self, buffer: &[u8], pos: &mut usize) -> Result<TupleScan, String> {
+ while *pos < buffer.len() {
+ let index = *pos;
+ let byte = buffer[index];
+ *pos += 1;
+ if let Some(quote) = self.quote {
+ if self.escaped {
+ self.escaped = false;
+ } else if self.backslash_escapes && byte == b'\\' {
+ self.escaped = true;
+ } else if byte == quote {
+ self.quote = None;
+ }
+ continue;
+ }
+ if self.depth == 0 {
+ match byte {
+ b'(' => {
+ self.depth = 1;
+ self.start = index;
+ }
+ b',' | 0x1e => {}
+ _ if byte.is_ascii_whitespace() => {}
+ _ => return Err(format!("Unexpected character {:?} between value tuples", byte as char)),
+ }
+ continue;
+ }
+ match byte {
+ b'\'' | b'"' => {
+ self.quote = Some(byte);
+ self.backslash_escapes = match self.dialect {
+ Nb3Dialect::Mysql => true,
+ Nb3Dialect::Postgres => byte == b'\'' && is_escape_string_prefix(buffer, index),
+ };
+ }
+ b'(' => self.depth += 1,
+ b')' => {
+ self.depth -= 1;
+ if self.depth == 0 {
+ return Ok(TupleScan::Tuple { start: self.start, end: index + 1 });
+ }
+ }
+ _ => {}
+ }
+ }
+ Ok(TupleScan::Incomplete)
+ }
+}
+
+fn is_escape_string_prefix(buffer: &[u8], quote_index: usize) -> bool {
+ if quote_index == 0 || !matches!(buffer[quote_index - 1], b'E' | b'e') {
+ return false;
+ }
+ quote_index < 2 || !is_identifier_byte(buffer[quote_index - 2])
+}
+
+fn is_identifier_byte(byte: u8) -> bool {
+ byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'$' || byte >= 0x80
+}
+
+/// Splits the `VALUES` tail of an INSERT statement into its tuples. Returns `None`
+/// when anything other than tuples follows (for example `ON DUPLICATE KEY UPDATE`).
+fn split_value_tuples(dialect: Nb3Dialect, tail: &str) -> Option<Vec<&str>> {
+ let bytes = tail.as_bytes();
+ let mut scanner = TupleScanner::new(dialect);
+ let mut pos = 0;
+ let mut tuples = Vec::new();
+ while let TupleScan::Tuple { start, end } = scanner.next(bytes, &mut pos).ok()? {
+ tuples.push(&tail[start..end]);
+ }
+ (scanner.is_between_tuples() && !tuples.is_empty()).then_some(tuples)
+}
+
+// ---------------------------------------------------------------------------
+// Restore: archive -> SQL script
+// ---------------------------------------------------------------------------
+
+#[derive(Debug, Clone, Copy)]
+struct ArchiveMember {
+ offset: u64,
+ size: u64,
+}
+
+struct LoadedObject {
+ meta: Nb3ObjectMeta,
+}
+
+struct DataChunk {
+ name: String,
+ member: ArchiveMember,
+ checksum: String,
+}
+
+enum RestoreStep {
+ Sql(String),
+ Rows { insert_prefix: String, chunks: Vec<DataChunk> },
+}
+
+fn read_archive_member(file: &mut File, name: &str, member: ArchiveMember, checksum: &str) -> Result<Vec<u8>, String> {
+ if member.size > METADATA_MAX_BYTES {
+ return Err(format!("Navicat backup member {name} is too large"));
+ }
+ file.seek(SeekFrom::Start(member.offset)).map_err(|error| error.to_string())?;
+ let mut bytes = vec![0; member.size as usize];
+ file.read_exact(&mut bytes).map_err(|error| format!("Failed to read {name} from Navicat backup: {error}"))?;
+ if !checksum.is_empty() && !sha1_hex(&bytes).eq_ignore_ascii_case(checksum) {
+ return Err(format!("Navicat backup member {name} is corrupted (checksum mismatch)"));
+ }
+ Ok(bytes)
+}
+
+fn gunzip(name: &str, bytes: &[u8]) -> Result<Vec<u8>, String> {
+ let mut decoded = Vec::new();
+ MultiGzDecoder::new(bytes)
+ .take(METADATA_MAX_BYTES + 1)
+ .read_to_end(&mut decoded)
+ .map_err(|error| format!("Failed to decompress {name} from Navicat backup: {error}"))?;
+ if decoded.len() as u64 > METADATA_MAX_BYTES {
+ return Err(format!("Navicat backup member {name} exceeds the {METADATA_MAX_BYTES}-byte metadata limit"));
+ }
+ Ok(decoded)
+}
+
+fn index_archive_members(path: &Path) -> Result<HashMap<String, ArchiveMember>, String> {
+ let file = File::open(path).map_err(|error| error.to_string())?;
+ let mut archive = tar::Archive::new(BufReader::new(file));
+ let mut members = HashMap::new();
+ let entries = archive.entries_with_seek().map_err(|error| format!("Not a Navicat backup archive: {error}"))?;
+ for entry in entries {
+ let entry = entry.map_err(|error| format!("Not a Navicat backup archive: {error}"))?;
+ let name = entry.path().map_err(|error| error.to_string())?.to_string_lossy().into_owned();
+ members.insert(name, ArchiveMember { offset: entry.raw_file_position(), size: entry.size() });
+ }
+ Ok(members)
+}
+
+/// A parsed `.nb3` archive. Opening it reads the (small) metadata; row data stays in
+/// the archive until [`Nb3SqlReader`] streams it.
+pub struct Nb3Archive {
+ path: PathBuf,
+ manifest: Nb3Manifest,
+ dialect: Nb3Dialect,
+ objects: Vec<LoadedObject>,
+ members: HashMap<String, ArchiveMember>,
+}
+
+impl Nb3Archive {
+ pub fn open(path: &Path) -> Result<Self, String> {
+ let members = index_archive_members(path)?;
+ let mut file = File::open(path).map_err(|error| error.to_string())?;
+ let manifest_member =
+ *members.get(MANIFEST_NAME).ok_or("Not a Navicat backup archive: meta.json is missing")?;
+ let manifest_bytes = read_archive_member(&mut file, MANIFEST_NAME, manifest_member, "")?;
+ let manifest: Nb3Manifest = serde_json::from_slice(&manifest_bytes)
+ .map_err(|error| format!("Invalid Navicat backup metadata: {error}"))?;
+ if !manifest.encryption.is_empty() && !manifest.encryption.eq_ignore_ascii_case("None") {
+ return Err("Encrypted Navicat backups are not supported; create the backup without encryption".into());
+ }
+ let dialect = Nb3Dialect::from_archive(&manifest.database_type)?;
+ let mut objects = Vec::with_capacity(manifest.objects.len());
+ for entry in &manifest.objects {
+ let name = &entry.metadata.filename;
+ let member = *members.get(name).ok_or_else(|| format!("Navicat backup is missing {name}"))?;
+ let compressed = read_archive_member(&mut file, name, member, &entry.metadata.checksum)?;
+ let meta: Nb3ObjectMeta = serde_json::from_slice(&gunzip(name, &compressed)?)
+ .map_err(|error| format!("Invalid Navicat object metadata in {name}: {error}"))?;
+ for chunk in &meta.data {
+ if !members.contains_key(&chunk.filename) {
+ return Err(format!("Navicat backup is missing {}", chunk.filename));
+ }
+ }
+ objects.push(LoadedObject { meta });
+ }
+ Ok(Self { path: path.to_path_buf(), manifest, dialect, objects, members })
+ }
+
+ pub fn database_type(&self) -> DatabaseType {
+ self.dialect.database_type()
+ }
+
+ /// The source database and schema; a MySQL archive names its database as the schema.
+ pub fn source_database_and_schema(&self) -> (String, String) {
+ match self.dialect {
+ Nb3Dialect::Mysql => (self.manifest.schema.clone(), self.manifest.schema.clone()),
+ Nb3Dialect::Postgres => (self.manifest.catalog.clone(), self.manifest.schema.clone()),
+ }
+ }
+
+ /// When the backup started, in seconds since the Unix epoch.
+ pub fn started_at(&self) -> Option<i64> {
+ self.manifest.start_time.trim().parse().ok()
+ }
+
+ fn ordered_objects(&self) -> Vec<&LoadedObject> {
+ let mut objects = self.objects.iter().collect::<Vec<_>>();
+ objects.sort_by_key(|object| creation_rank(&object.meta.object_type));
+ objects
+ }
+
+ fn statement(&self, object_type: &str, ddl: &str) -> Option<String> {
+ let trimmed = ddl.trim();
+ if trimmed.is_empty() {
+ return None;
+ }
+ if self.dialect == Nb3Dialect::Mysql && is_routine_like(object_type) {
+ return Some(format!("{}\n\n", mysql_delimited_statement(trimmed)));
+ }
+ if trimmed.ends_with(';') {
+ Some(format!("{trimmed}\n\n"))
+ } else {
+ Some(format!("{trimmed};\n\n"))
+ }
+ }
+
+ fn drop_statement(&self, object: &LoadedObject) -> Option<String> {
+ if object.meta.ddl.trim().is_empty() {
+ // Data-only objects are loaded into the existing table, never replaced.
+ return None;
+ }
+ let name = self.dialect.quote(&object.meta.name);
+ let cascade = if self.dialect == Nb3Dialect::Postgres { " CASCADE" } else { "" };
+ let kind = match (self.dialect, object.meta.object_type.as_str()) {
+ (_, "Table") => "TABLE",
+ (_, "View") => "VIEW",
+ (Nb3Dialect::Postgres, "MaterializedView") => "MATERIALIZED VIEW",
+ (Nb3Dialect::Postgres, "Sequence") => "SEQUENCE",
+ (Nb3Dialect::Mysql, "Function") => "FUNCTION",
+ (Nb3Dialect::Mysql, "Procedure") => "PROCEDURE",
+ (Nb3Dialect::Mysql, "Event") => "EVENT",
+ _ => return None,
+ };
+ let cascade = if matches!(kind, "FUNCTION" | "PROCEDURE" | "EVENT") { "" } else { cascade };
+ Some(format!("DROP {kind} IF EXISTS {name}{cascade};\n"))
+ }
+
+ fn insert_prefix(&self, object: &LoadedObject) -> String {
+ let table = self.dialect.quote(&object.meta.name);
+ let columns = object
+ .meta
+ .fields
+ .as_deref()
+ .filter(|fields| !fields.is_empty())
+ .map(|fields| {
+ format!(" ({})", fields.iter().map(|field| self.dialect.quote(field)).collect::<Vec<_>>().join(", "))
+ })
+ .unwrap_or_default();
+ let overriding = if self.dialect == Nb3Dialect::Postgres
+ && object.meta.ddl.to_ascii_uppercase().contains("GENERATED ALWAYS AS IDENTITY")
+ {
+ " OVERRIDING SYSTEM VALUE"
+ } else {
+ ""
+ };
+ format!("INSERT INTO {table}{columns}{overriding} VALUES\n")
+ }
+
+ fn restore_steps(&self) -> Result<VecDeque<RestoreStep>, String> {
+ let objects = self.ordered_objects();
+ let mut steps = VecDeque::new();
+ let mut header = format!(
+ "-- Navicat backup restored by DBX\n-- Source: {} {}\n\n",
+ self.manifest.database_type,
+ [self.manifest.catalog.as_str(), self.manifest.schema.as_str()]
+ .into_iter()
+ .filter(|part| !part.is_empty())
+ .collect::<Vec<_>>()
+ .join(".")
+ );
+ match self.dialect {
+ Nb3Dialect::Mysql => header.push_str("SET NAMES utf8mb4;\nSET FOREIGN_KEY_CHECKS = 0;\n\n"),
+ Nb3Dialect::Postgres => {
+ header.push_str("SET check_function_bodies = false;\n");
+ // Navicat DDL is unqualified and DBX DDL may be schema-qualified, so the
+ // archived schema must exist and lead the search path for both to resolve.
+ // `CREATE SCHEMA IF NOT EXISTS` checks the CREATE privilege before existence,
+ // so only create the schema when it is really missing.
+ let schema = self.manifest.schema.trim();
+ if !schema.is_empty() {
+ let literal = schema.replace('\'', "''");
+ let quoted = self.dialect.quote(schema);
+ header.push_str(&format!(
+ "DO $nb3$ BEGIN IF NOT EXISTS (SELECT 1 FROM pg_namespace WHERE nspname = '{literal}') THEN CREATE SCHEMA {quoted}; END IF; END $nb3$;\n"
+ ));
+ if schema == "public" {
+ header.push_str("SET search_path TO \"public\";\n");
+ } else {
+ header.push_str(&format!("SET search_path TO {quoted}, public;\n"));
+ }
+ }
+ header.push('\n');
+ }
+ }
+ for object in objects.iter().rev() {
+ if let Some(drop) = self.drop_statement(object) {
+ header.push_str(&drop);
+ }
+ }
+ header.push('\n');
+ steps.push_back(RestoreStep::Sql(header));
+
+ let (before_views, after_tables): (Vec<&LoadedObject>, Vec<&LoadedObject>) =
+ objects.iter().partition(|object| creation_rank(&object.meta.object_type) <= creation_rank("Table"));
+ let mut structure = String::new();
+ for object in &before_views {
+ if let Some(statement) = self.statement(&object.meta.object_type, &object.meta.ddl) {
+ structure.push_str(&statement);
+ }
+ }
+ steps.push_back(RestoreStep::Sql(structure));
+
+ for object in &before_views {
+ if object.meta.data.is_empty() {
+ continue;
+ }
+ let chunks = object
+ .meta
+ .data
+ .iter()
+ .map(|chunk| DataChunk {
+ name: chunk.filename.clone(),
+ member: self.members[&chunk.filename],
+ checksum: chunk.checksum.clone(),
+ })
+ .collect();
+ steps.push_back(RestoreStep::Rows { insert_prefix: self.insert_prefix(object), chunks });
+ }
+
+ // Every primary key and unique index must exist before any foreign key, which
+ // may reference a table archived later.
+ let mut post_data = String::new();
+ let index_ddl = before_views.iter().flat_map(|object| &object.meta.index_ddl);
+ let sub_ddl = before_views.iter().flat_map(|object| &object.meta.sub_ddl);
+ for ddl in index_ddl.chain(sub_ddl) {
+ if let Some(statement) = self.statement("", ddl) {
+ post_data.push_str(&statement);
+ }
+ }
+ for object in &after_tables {
+ if let Some(statement) = self.statement(&object.meta.object_type, &object.meta.ddl) {
+ post_data.push_str(&statement);
+ }
+ for ddl in object.meta.index_ddl.iter().chain(&object.meta.sub_ddl) {
+ if let Some(statement) = self.statement("", ddl) {
+ post_data.push_str(&statement);
+ }
+ }
+ }
+ for object in &objects {
+ for ddl in &object.meta.trigger_ddl {
+ if let Some(statement) = self.statement("Trigger", ddl) {
+ post_data.push_str(&statement);
+ }
+ }
+ }
+ if self.dialect == Nb3Dialect::Mysql {
+ post_data.push_str("SET FOREIGN_KEY_CHECKS = 1;\n");
+ }
+ steps.push_back(RestoreStep::Sql(post_data));
+ Ok(steps)
+ }
+}
+
+fn mysql_delimited_statement(statement: &str) -> String {
+ if statement.get(..9).is_some_and(|prefix| prefix.eq_ignore_ascii_case("DELIMITER")) {
+ return statement.to_string();
+ }
+ let body = statement.trim_end_matches(';').trim_end();
+ let delimiter = ["//", "$$", ";;", "__DBX_DELIMITER__"]
+ .into_iter()
+ .find(|delimiter| !body.contains(delimiter))
+ .unwrap_or("__DBX_DELIMITER__");
+ format!("DELIMITER {delimiter}\n{body}{delimiter}\nDELIMITER ;")
+}
+
+/// Hashes the compressed bytes of a data chunk while it is decompressed.
+struct ChunkSource {
+ inner: std::io::Take<BufReader<File>>,
+ hasher: Sha1,
+ consumed: Arc<AtomicU64>,
+ bytes_read: Option<Arc<AtomicU64>>,
+}
+
+impl Read for ChunkSource {
+ fn read(&mut self, buffer: &mut [u8]) -> std::io::Result<usize> {
+ let read = self.inner.read(buffer)?;
+ self.hasher.update(&buffer[..read]);
+ self.consumed.fetch_add(read as u64, Ordering::Relaxed);
+ if let Some(bytes_read) = &self.bytes_read {
+ bytes_read.fetch_add(read as u64, Ordering::Relaxed);
+ }
+ Ok(read)
+ }
+}
+
+struct RowStream {
+ insert_prefix: String,
+ chunks: VecDeque<DataChunk>,
+ current: Option<(String, String, MultiGzDecoder<ChunkSource>)>,
+ buffer: Vec<u8>,
+ pos: usize,
+ scanner: TupleScanner,
+ eof: bool,
+}
+
+/// Renders an `.nb3` archive as a restore script: drops the archived objects, creates
+/// them, loads their rows, then adds indexes, constraints and triggers.
+pub struct Nb3SqlReader {
+ path: PathBuf,
+ dialect: Nb3Dialect,
+ steps: VecDeque<RestoreStep>,
+ rows: Option<RowStream>,
+ output: Vec<u8>,
+ output_pos: usize,
+ /// Shared import progress counter; it ends at the archive size once the
+ /// script is fully read, although only row chunks are counted while reading.
+ bytes_read: Option<Arc<AtomicU64>>,
+ consumed: Arc<AtomicU64>,
+ file_size: u64,
+ max_pending_row_bytes: usize,
+}
+
+impl Nb3SqlReader {
+ pub fn open(path: &Path, bytes_read: Option<Arc<AtomicU64>>) -> Result<Self, String> {
+ let archive = Nb3Archive::open(path)?;
+ let file_size = std::fs::metadata(path).map_err(|error| error.to_string())?.len();
+ Ok(Self {
+ path: archive.path.clone(),
+ dialect: archive.dialect,
+ steps: archive.restore_steps()?,
+ rows: None,
+ output: Vec::new(),
+ output_pos: 0,
+ bytes_read,
+ consumed: Arc::new(AtomicU64::new(0)),
+ file_size,
+ max_pending_row_bytes: ROW_TUPLE_MAX_BYTES,
+ })
+ }
+
+ fn open_chunk(&self, chunk: &DataChunk) -> std::io::Result<MultiGzDecoder<ChunkSource>> {
+ let mut file = File::open(&self.path)?;
+ file.seek(SeekFrom::Start(chunk.member.offset))?;
+ Ok(MultiGzDecoder::new(ChunkSource {
+ inner: BufReader::new(file).take(chunk.member.size),
+ hasher: Sha1::new(),
+ consumed: self.consumed.clone(),
+ bytes_read: self.bytes_read.clone(),
+ }))
+ }
+
+ /// Fills `output` with the next piece of the script; returns `false` at the end.
+ fn refill(&mut self) -> std::io::Result<bool> {
+ loop {
+ if self.rows.is_some() {
+ if let Some(statement) = self.next_insert()? {
+ self.output = statement.into_bytes();
+ self.output_pos = 0;
+ return Ok(true);
+ }
+ self.rows = None;
+ }
+ match self.steps.pop_front() {
+ Some(RestoreStep::Sql(sql)) => {
+ if sql.is_empty() {
+ continue;
+ }
+ self.output = sql.into_bytes();
+ self.output_pos = 0;
+ return Ok(true);
+ }
+ Some(RestoreStep::Rows { insert_prefix, chunks }) => {
+ self.rows = Some(RowStream {
+ insert_prefix,
+ chunks: chunks.into(),
+ current: None,
+ buffer: Vec::new(),
+ pos: 0,
+ scanner: TupleScanner::new(self.dialect),
+ eof: true,
+ });
+ }
+ None => {
+ if let Some(bytes_read) = &self.bytes_read {
+ let counted = self.consumed.swap(self.file_size, Ordering::Relaxed);
+ bytes_read.fetch_add(self.file_size.saturating_sub(counted), Ordering::Relaxed);
+ }
+ return Ok(false);
+ }
+ }
+ }
+ }
+
+ /// Builds the next multi-row INSERT for the current table, or `None` when its
+ /// chunks are exhausted.
+ fn next_insert(&mut self) -> std::io::Result<Option<String>> {
+ let mut statement = String::new();
+ let mut rows = 0;
+ while rows < RESTORE_INSERT_MAX_ROWS && statement.len() < RESTORE_INSERT_MAX_BYTES {
+ let Some(tuple) = self.next_tuple()? else {
+ break;
+ };
+ if rows == 0 {
+ statement.push_str(&self.rows.as_ref().expect("row stream is active").insert_prefix);
+ } else {
+ statement.push_str(",\n");
+ }
+ statement.push_str(&tuple);
+ rows += 1;
+ }
+ if rows == 0 {
+ return Ok(None);
+ }
+ statement.push_str(";\n");
+ Ok(Some(statement))
+ }
+
+ fn next_tuple(&mut self) -> std::io::Result<Option<String>> {
+ let max_pending_row_bytes = self.max_pending_row_bytes;
+ loop {
+ let opened_chunk = {
+ let stream = self.rows.as_mut().expect("row stream is active");
+ if stream.current.is_some() {
+ None
+ } else {
+ match stream.chunks.pop_front() {
+ Some(chunk) => Some(chunk),
+ None => return Ok(None),
+ }
+ }
+ };
+ if let Some(chunk) = opened_chunk {
+ let decoder = self.open_chunk(&chunk)?;
+ let stream = self.rows.as_mut().expect("row stream is active");
+ stream.current = Some((chunk.name, chunk.checksum, decoder));
+ stream.buffer.clear();
+ stream.pos = 0;
+ stream.scanner = TupleScanner::new(self.dialect);
+ stream.eof = false;
+ }
+
+ let stream = self.rows.as_mut().expect("row stream is active");
+ let scan = stream.scanner.next(&stream.buffer, &mut stream.pos).map_err(io_error)?;
+ if let TupleScan::Tuple { start, end } = scan {
+ let tuple = String::from_utf8(stream.buffer[start..end].to_vec())
+ .map_err(|_| io_error("Navicat backup data is not valid UTF-8"))?;
+ return Ok(Some(tuple));
+ }
+ if stream.eof {
+ let (name, checksum, decoder) = stream.current.take().expect("chunk is open");
+ if !stream.scanner.is_between_tuples() {
+ return Err(io_error(format!("Navicat backup data chunk {name} ends inside a row")));
+ }
+ let mut source = decoder.into_inner();
+ std::io::copy(&mut source, &mut std::io::sink())?;
+ let digest = source.hasher.finalize().iter().map(|byte| format!("{byte:02X}")).collect::<String>();
+ if !checksum.is_empty() && !digest.eq_ignore_ascii_case(&checksum) {
+ return Err(io_error(format!("Navicat backup data chunk {name} is corrupted (checksum mismatch)")));
+ }
+ continue;
+ }
+ // Keep the unfinished tuple (if any) and read more decompressed data.
+ let keep_from = if stream.scanner.is_between_tuples() { stream.pos } else { stream.scanner.start };
+ stream.buffer.drain(..keep_from);
+ stream.pos -= keep_from;
+ if !stream.scanner.is_between_tuples() {
+ stream.scanner.start = 0;
+ }
+ let (name, _, decoder) = stream.current.as_mut().expect("chunk is open");
+ let mut chunk = vec![0; 256 * 1024];
+ let read = decoder
+ .read(&mut chunk)
+ .map_err(|error| io_error(format!("Navicat backup data chunk {name} is corrupted: {error}")))?;
+ if read == 0 {
+ stream.eof = true;
+ } else {
+ stream.buffer.extend_from_slice(&chunk[..read]);
+ if stream.buffer.len() > max_pending_row_bytes {
+ return Err(io_error(format!(
+ "Navicat backup data chunk {name} contains a row larger than {max_pending_row_bytes} bytes"
+ )));
+ }
+ }
+ }
+ }
+}
+
+impl Read for Nb3SqlReader {
+ fn read(&mut self, buffer: &mut [u8]) -> std::io::Result<usize> {
+ if buffer.is_empty() {
+ return Ok(0);
+ }
+ while self.output_pos >= self.output.len() {
+ if !self.refill()? {
+ return Ok(0);
+ }
+ }
+ let available = &self.output[self.output_pos..];
+ let count = available.len().min(buffer.len());
+ buffer[..count].copy_from_slice(&available[..count]);
+ self.output_pos += count;
+ Ok(count)
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Backup: DBX SQL export -> archive
+// ---------------------------------------------------------------------------
+
+/// Minimal SQL head reader used to classify exported statements.
+struct Cursor<'a> {
+ text: &'a str,
+ pos: usize,
+ fold_unquoted: bool,
+}
+
+impl<'a> Cursor<'a> {
+ fn new(text: &'a str, fold_unquoted: bool) -> Self {
+ Self { text, pos: 0, fold_unquoted }
+ }
+
+ fn rest(&self) -> &'a str {
+ &self.text[self.pos..]
+ }
+
+ fn skip_space(&mut self) {
+ loop {
+ let rest = self.rest();
+ let trimmed = rest.trim_start();
+ self.pos += rest.len() - trimmed.len();
+ if trimmed.starts_with("--") || trimmed.starts_with('#') {
+ self.pos += trimmed.find('\n').map_or(trimmed.len(), |index| index + 1);
+ } else if trimmed.starts_with("/*") && !trimmed.starts_with("/*!") {
+ self.pos += trimmed.find("*/").map_or(trimmed.len(), |index| index + 2);
+ } else {
+ break;
+ }
+ }
+ }
+
+ fn keyword(&mut self, keyword: &str) -> bool {
+ self.skip_space();
+ let rest = self.rest();
+ let matches = rest.len() >= keyword.len()
+ && rest.is_char_boundary(keyword.len())
+ && rest[..keyword.len()].eq_ignore_ascii_case(keyword)
+ && !rest.as_bytes().get(keyword.len()).copied().is_some_and(is_identifier_byte);
+ if matches {
+ self.pos += keyword.len();
+ }
+ matches
+ }
+
+ fn keywords(&mut self, keywords: &[&str]) -> bool {
+ let saved = self.pos;
+ if keywords.iter().all(|keyword| self.keyword(keyword)) {
+ true
+ } else {
+ self.pos = saved;
+ false
+ }
+ }
+
+ fn any_keyword(&mut self, keywords: &[&str]) -> bool {
+ keywords.iter().any(|keyword| self.keyword(keyword))
+ }
+
+ fn identifier_part(&mut self) -> Option<String> {
+ self.skip_space();
+ let rest = self.rest();
+ let close = match rest.chars().next()? {
+ '`' => '`',
+ '"' => '"',
+ '[' => ']',
+ _ => {
+ let len = rest.bytes().take_while(|byte| is_identifier_byte(*byte)).count();
+ if len == 0 {
+ return None;
+ }
+ self.pos += len;
+ let raw = &rest[..len];
+ return Some(if self.fold_unquoted { raw.to_lowercase() } else { raw.to_string() });
+ }
+ };
+ let mut value = String::new();
+ let mut chars = rest.char_indices().skip(1).peekable();
+ while let Some((index, ch)) = chars.next() {
+ if ch == close {
+ if close != ']' && chars.peek().is_some_and(|(_, next)| *next == close) {
+ value.push(ch);
+ chars.next();
+ continue;
+ }
+ self.pos += index + ch.len_utf8();
+ return Some(value);
+ }
+ value.push(ch);
+ }
+ None
+ }
+
+ fn identifier_path(&mut self) -> Option<Vec<String>> {
+ let mut parts = vec![self.identifier_part()?];
+ loop {
+ let saved = self.pos;
+ self.skip_space();
+ if !self.rest().starts_with('.') {
+ self.pos = saved;
+ return Some(parts);
+ }
+ self.pos += 1;
+ match self.identifier_part() {
+ Some(part) => parts.push(part),
+ None => {
+ self.pos = saved;
+ return Some(parts);
+ }
+ }
+ }
+ }
+
+ fn name(&mut self) -> Option<String> {
+ self.identifier_path().and_then(|mut parts| parts.pop())
+ }
+
+ fn quoted_string(&mut self) -> bool {
+ self.skip_space();
+ let bytes = self.rest().as_bytes();
+ if bytes.first() != Some(&b'\'') {
+ return false;
+ }
+ let mut index = 1;
+ while index < bytes.len() {
+ match bytes[index] {
+ b'\\' => index += 2,
+ b'\'' if bytes.get(index + 1) == Some(&b'\'') => index += 2,
+ b'\'' => {
+ self.pos += index + 1;
+ return true;
+ }
+ _ => index += 1,
+ }
+ }
+ self.pos = self.text.len();
+ true
+ }
+
+ /// Skips a `KEY = value` clause such as MySQL ``DEFINER=`root`@`%` ``.
+ fn skip_assignment(&mut self, key: &str) -> bool {
+ if !self.keyword(key) {
+ return false;
+ }
+ self.skip_space();
+ if self.rest().starts_with('=') {
+ self.pos += 1;
+ }
+ loop {
+ if self.identifier_part().is_none() && !self.quoted_string() {
+ break;
+ }
+ if self.rest().starts_with("()") {
+ self.pos += 2;
+ }
+ if self.rest().starts_with('@') {
+ self.pos += 1;
+ continue;
+ }
+ break;
+ }
+ true
+ }
+
+ /// Advances past the next top-level occurrence of `keyword`.
+ fn seek_keyword(&mut self, keyword: &str) -> bool {
+ loop {
+ self.skip_space();
+ if self.rest().is_empty() {
+ return false;
+ }
+ if self.keyword(keyword) {
+ return true;
+ }
+ if self.quoted_string() || self.identifier_part().is_some() {
+ continue;
+ }
+ self.pos += self.rest().chars().next().map_or(1, char::len_utf8);
+ }
+ }
+}
+
+#[derive(Debug, PartialEq, Eq)]
+enum Classified {
+ Skip,
+ Object { object_type: &'static str, name: String },
+ Rows { table: String, columns: Vec<String>, values_at: usize },
+ Trigger { table: String },
+ TableIndex { table: String },
+ TableSub { table: String },
+ ObjectSub { object_type: &'static str, name: String },
+ Other,
+}
+
+const ALTERABLE_OBJECTS: &[(&[&str], &str)] = &[
+ (&["SEQUENCE"], "Sequence"),
+ (&["MATERIALIZED", "VIEW"], "MaterializedView"),
+ (&["VIEW"], "View"),
+ (&["FUNCTION"], "Function"),
+ (&["PROCEDURE"], "Procedure"),
+ (&["EVENT"], "Event"),
+ (&["TYPE"], "Type"),
+ (&["DOMAIN"], "Domain"),
+ (&["EXTENSION"], "Extension"),
+];
+
+fn classify_statement(dialect: Nb3Dialect, body: &str) -> Classified {
+ let mut cursor = Cursor::new(body, dialect == Nb3Dialect::Postgres);
+ if cursor.keyword("INSERT") {
+ return classify_insert(cursor);
+ }
+ if cursor.keyword("CREATE") {
+ return classify_create(cursor);
+ }
+ if cursor.keyword("ALTER") {
+ if cursor.keyword("TABLE") {
+ cursor.keywords(&["IF", "EXISTS"]);
+ cursor.keyword("ONLY");
+ let Some(table) = cursor.name() else {
+ return Classified::Other;
+ };
+ // Navicat keeps primary keys, unique constraints and indexes in IndexDDL and
+ // everything else (foreign keys, ownership) in SubDDL.
+ let index_like = cursor.keyword("ADD") && {
+ if cursor.keyword("CONSTRAINT") {
+ let constraint_name_at = cursor.pos;
+ if cursor.keywords(&["PRIMARY", "KEY"]) || cursor.keyword("UNIQUE") {
+ cursor.pos = constraint_name_at;
+ } else {
+ cursor.identifier_part();
+ }
+ }
+ cursor.keywords(&["PRIMARY", "KEY"])
+ || cursor.any_keyword(&["UNIQUE", "INDEX", "KEY", "FULLTEXT", "SPATIAL"])
+ };
+ return if index_like { Classified::TableIndex { table } } else { Classified::TableSub { table } };
+ }
+ return classify_object_reference(cursor);
+ }
+ if cursor.keywords(&["COMMENT", "ON"]) {
+ if cursor.keyword("COLUMN") {
+ return match cursor.identifier_path() {
+ Some(mut parts) if parts.len() >= 2 => {
+ parts.pop();
+ Classified::TableSub { table: parts.pop().unwrap_or_default() }
+ }
+ _ => Classified::Other,
+ };
+ }
+ if cursor.keyword("TABLE") {
+ return cursor.name().map_or(Classified::Other, |table| Classified::TableSub { table });
+ }
+ return classify_object_reference(cursor);
+ }
+ if cursor.keyword("SELECT") {
+ return classify_setval(dialect, cursor.rest());
+ }
+ if cursor.any_keyword(&[
+ "SET",
+ "USE",
+ "DROP",
+ "BEGIN",
+ "COMMIT",
+ "ROLLBACK",
+ "START",
+ "LOCK",
+ "UNLOCK",
+ "DELIMITER",
+ ]) {
+ return Classified::Skip;
+ }
+ Classified::Other
+}
+
+fn classify_insert(mut cursor: Cursor<'_>) -> Classified {
+ cursor.keyword("IGNORE");
+ if !cursor.keyword("INTO") {
+ return Classified::Other;
+ }
+ let Some(table) = cursor.name() else {
+ return Classified::Other;
+ };
+ let mut columns = Vec::new();
+ cursor.skip_space();
+ if cursor.rest().starts_with('(') {
+ cursor.pos += 1;
+ loop {
+ let Some(column) = cursor.identifier_part() else {
+ return Classified::Other;
+ };
+ columns.push(column);
+ cursor.skip_space();
+ if cursor.rest().starts_with(',') {
+ cursor.pos += 1;
+ } else if cursor.rest().starts_with(')') {
+ cursor.pos += 1;
+ break;
+ } else {
+ return Classified::Other;
+ }
+ }
+ }
+ if cursor.keyword("OVERRIDING") {
+ cursor.any_keyword(&["SYSTEM", "USER"]);
+ cursor.keyword("VALUE");
+ }
+ if !(cursor.keyword("VALUES") || cursor.keyword("VALUE")) {
+ return Classified::Other;
+ }
+ Classified::Rows { table, columns, values_at: cursor.pos }
+}
+
+fn classify_create(mut cursor: Cursor<'_>) -> Classified {
+ cursor.keywords(&["OR", "REPLACE"]);
+ loop {
+ if cursor.skip_assignment("DEFINER") || cursor.skip_assignment("ALGORITHM") {
+ continue;
+ }
+ if cursor.keywords(&["SQL", "SECURITY"]) {
+ cursor.identifier_part();
+ continue;
+ }
+ if cursor.any_keyword(&[
+ "GLOBAL",
+ "LOCAL",
+ "TEMPORARY",
+ "TEMP",
+ "UNLOGGED",
+ "UNIQUE",
+ "RECURSIVE",
+ "CONSTRAINT",
+ "AGGREGATE",
+ "TRUSTED",
+ "PROCEDURAL",
+ ]) {
+ continue;
+ }
+ break;
+ }
+ if cursor.keyword("TRIGGER") {
+ return if cursor.seek_keyword("ON") {
+ cursor.name().map_or(Classified::Other, |table| Classified::Trigger { table })
+ } else {
+ Classified::Other
+ };
+ }
+ if cursor.keyword("INDEX") {
+ if !cursor.seek_keyword("ON") {
+ return Classified::Other;
+ }
+ cursor.keyword("ONLY");
+ return cursor.name().map_or(Classified::Other, |table| Classified::TableIndex { table });
+ }
+ if cursor.any_keyword(&["DATABASE", "SCHEMA"]) {
+ return Classified::Skip;
+ }
+ let object_type = if cursor.keyword("TABLE") {
+ "Table"
+ } else if let Some((_, object_type)) = ALTERABLE_OBJECTS.iter().find(|(keywords, _)| cursor.keywords(keywords)) {
+ object_type
+ } else {
+ return Classified::Other;
+ };
+ cursor.keywords(&["IF", "NOT", "EXISTS"]);
+ cursor.name().map_or(Classified::Other, |name| Classified::Object { object_type, name })
+}
+
+fn classify_object_reference(mut cursor: Cursor<'_>) -> Classified {
+ let Some((_, object_type)) = ALTERABLE_OBJECTS.iter().find(|(keywords, _)| cursor.keywords(keywords)) else {
+ return Classified::Other;
+ };
+ cursor.keywords(&["IF", "EXISTS"]);
+ cursor.name().map_or(Classified::Other, |name| Classified::ObjectSub { object_type, name })
+}
+
+fn classify_setval(dialect: Nb3Dialect, rest: &str) -> Classified {
+ static SETVAL: std::sync::LazyLock<regex::Regex> = std::sync::LazyLock::new(|| {
+ regex::Regex::new(r"(?is)^\s*(?:pg_catalog\s*\.\s*)?setval\s*\(\s*'((?:[^']|'')*)'")
+ .expect("valid setval regex")
+ });
+ let Some(captures) = SETVAL.captures(rest) else {
+ return Classified::Other;
+ };
+ let reference = captures[1].replace("''", "'");
+ Cursor::new(&reference, dialect == Nb3Dialect::Postgres)
+ .name()
+ .map_or(Classified::Other, |name| Classified::ObjectSub { object_type: "Sequence", name })
+}
+
+struct ChunkWriter {
+ name: String,
+ path: PathBuf,
+ encoder: GzEncoder<BufWriter<File>>,
+ uncompressed: u64,
+ records: u64,
+}
+
+struct StagedChunk {
+ name: String,
+ path: PathBuf,
+ checksum: String,
+}
+
+struct PendingObject {
+ uuid: String,
+ object_type: &'static str,
+ name: String,
+ ddl: String,
+ sub_ddl: Vec<String>,
+ index_ddl: Vec<String>,
+ trigger_ddl: Vec<String>,
+ fields: Option<Vec<String>>,
+ rows: u64,
+ chunks: Vec<StagedChunk>,
+ writer: Option<ChunkWriter>,
+}
+
+impl PendingObject {
+ fn write_tuple(&mut self, staging: &Path, tuple: &str) -> Result<(), String> {
+ if self.writer.as_ref().is_some_and(|writer| writer.uncompressed >= DATA_CHUNK_MAX_BYTES) {
+ self.finish_chunk()?;
+ }
+ if self.writer.is_none() {
+ let name = format!("{}.data.{:05}.sql.gz", self.uuid, self.chunks.len());
+ let path = staging.join(&name);
+ let file = File::create(&path).map_err(|error| format!("Failed to stage Navicat backup data: {error}"))?;
+ self.writer = Some(ChunkWriter {
+ name,
+ path,
+ encoder: GzEncoder::new(BufWriter::new(file), Compression::default()),
+ uncompressed: 0,
+ records: 0,
+ });
+ }
+ let writer = self.writer.as_mut().expect("chunk writer is open");
+ let write = |encoder: &mut GzEncoder<BufWriter<File>>, bytes: &[u8]| {
+ encoder.write_all(bytes).map_err(|error| format!("Failed to stage Navicat backup data: {error}"))
+ };
+ if writer.records > 0 {
+ write(&mut writer.encoder, RECORD_SEPARATOR)?;
+ writer.uncompressed += RECORD_SEPARATOR.len() as u64;
+ }
+ write(&mut writer.encoder, tuple.as_bytes())?;
+ writer.uncompressed += tuple.len() as u64;
+ writer.records += 1;
+ self.rows += 1;
+ Ok(())
+ }
+
+ fn finish_chunk(&mut self) -> Result<(), String> {
+ let Some(writer) = self.writer.take() else {
+ return Ok(());
+ };
+ writer
+ .encoder
+ .finish()
+ .and_then(|mut file| file.flush())
+ .map_err(|error| format!("Failed to stage Navicat backup data: {error}"))?;
+ let mut hasher = Sha1::new();
+ let mut file = File::open(&writer.path).map_err(|error| error.to_string())?;
+ std::io::copy(&mut file, &mut hasher).map_err(|error| error.to_string())?;
+ let checksum = hasher.finalize().iter().map(|byte| format!("{byte:02X}")).collect();
+ self.chunks.push(StagedChunk { name: writer.name, path: writer.path, checksum });
+ Ok(())
+ }
+}
+
+fn append_member<R: Read, W: Write>(
+ builder: &mut tar::Builder<W>,
+ name: &str,
+ size: u64,
+ data: R,
+) -> Result<(), String> {
+ let mut header = tar::Header::new_ustar();
+ header.set_entry_type(tar::EntryType::Regular);
+ header.set_size(size);
+ header.set_mode(0o644);
+ header.set_uid(0);
+ header.set_gid(0);
+ header.set_mtime(0);
+ builder.append_data(&mut header, name, data).map_err(|error| format!("Failed to write Navicat backup: {error}"))
+}
+
+/// Receives a DBX SQL export and writes it as a Navicat `.nb3` archive on
+/// [`finish`](Self::finish). Row data is staged as compressed chunks next to the
+/// destination while the export runs; DDL is kept in memory.
+pub struct Nb3ExportWriter {
+ output: Option<File>,
+ dialect: Nb3Dialect,
+ catalog: String,
+ schema: String,
+ started_at: i64,
+ staging: tempfile::TempDir,
+ splitter: SqlStatementSplitter,
+ pending: Vec<u8>,
+ objects: Vec<PendingObject>,
+ index: HashMap<(&'static str, String), usize>,
+ last_object: Option<usize>,
+ orphans: Vec<String>,
+}
+
+impl Nb3ExportWriter {
+ pub fn new(
+ output: File,
+ staging_parent: Option<&Path>,
+ db_type: DatabaseType,
+ database: &str,
+ schema: &str,
+ ) -> Result<Self, String> {
+ let dialect = Nb3Dialect::from_database_type(db_type)?;
+ let staging = match staging_parent {
+ Some(parent) => tempfile::Builder::new().prefix(".dbx-nb3-").tempdir_in(parent),
+ None => tempfile::Builder::new().prefix("dbx-nb3-").tempdir(),
+ }
+ .map_err(|error| format!("Failed to create Navicat backup staging directory: {error}"))?;
+ let (catalog, schema) = match dialect {
+ Nb3Dialect::Mysql => (String::new(), database.to_string()),
+ Nb3Dialect::Postgres => (database.to_string(), schema.to_string()),
+ };
+ Ok(Self {
+ output: Some(output),
+ dialect,
+ catalog,
+ schema,
+ started_at: chrono::Utc::now().timestamp(),
+ staging,
+ splitter: SqlStatementSplitter::with_options(SqlParsingOptions::for_database_type(db_type)),
+ pending: Vec::new(),
+ objects: Vec::new(),
+ index: HashMap::new(),
+ last_object: None,
+ orphans: Vec::new(),
+ })
+ }
+
+ fn object(&mut self, object_type: &'static str, name: &str) -> usize {
+ if let Some(index) = self.index.get(&(object_type, name.to_string())) {
+ return *index;
+ }
+ let index = self.objects.len();
+ self.objects.push(PendingObject {
+ uuid: uuid::Uuid::new_v4().to_string(),
+ object_type,
+ name: name.to_string(),
+ ddl: String::new(),
+ sub_ddl: Vec::new(),
+ index_ddl: Vec::new(),
+ trigger_ddl: Vec::new(),
+ fields: None,
+ rows: 0,
+ chunks: Vec::new(),
+ writer: None,
+ });
+ self.index.insert((object_type, name.to_string()), index);
+ index
+ }
+
+ fn attach_to_last(&mut self, statement: &str) {
+ match self.last_object {
+ Some(index) => self.objects[index].sub_ddl.push(statement.to_string()),
+ None => self.orphans.push(statement.to_string()),
+ }
+ }
+
+ fn handle_statement(&mut self, sql: &str) -> Result<(), String> {
+ let mut cursor = Cursor::new(sql, false);
+ cursor.skip_space();
+ let body = cursor.rest().trim_end().trim_end_matches(';').trim_end();
+ if body.is_empty() {
+ return Ok(());
+ }
+ match classify_statement(self.dialect, body) {
+ Classified::Skip => {}
+ Classified::Object { object_type, name } => {
+ let index = self.object(object_type, &name);
+ let object = &mut self.objects[index];
+ if object.ddl.is_empty() {
+ object.ddl = body.to_string();
+ } else {
+ object.sub_ddl.push(body.to_string());
+ }
+ self.last_object = Some(index);
+ }
+ Classified::Rows { table, columns, values_at } => {
+ let index = self.object("Table", &table);
+ let staging = self.staging.path().to_path_buf();
+ let object = &mut self.objects[index];
+ let Some(tuples) = split_value_tuples(self.dialect, &body[values_at..]) else {
+ object.sub_ddl.push(body.to_string());
+ return Ok(());
+ };
+ if object.fields.is_none() && !columns.is_empty() {
+ object.fields = Some(columns);
+ }
+ for tuple in tuples {
+ object.write_tuple(&staging, tuple)?;
+ }
+ }
+ Classified::Trigger { table } => {
+ let index = self.object("Table", &table);
+ self.objects[index].trigger_ddl.push(body.to_string());
+ }
+ Classified::TableIndex { table } => {
+ let index = self.object("Table", &table);
+ self.objects[index].index_ddl.push(body.to_string());
+ }
+ Classified::TableSub { table } => {
+ let index = self.object("Table", &table);
+ self.objects[index].sub_ddl.push(body.to_string());
+ }
+ Classified::ObjectSub { object_type, name } => {
+ if let Some(index) = self.index.get(&(object_type, name.clone())).copied() {
+ self.objects[index].sub_ddl.push(body.to_string());
+ } else if object_type == "Sequence" {
+ // Sequences owned by a serial/identity column have no CREATE statement.
+ let index = self.object(object_type, &name);
+ self.objects[index].sub_ddl.push(body.to_string());
+ } else {
+ self.attach_to_last(body);
+ }
+ }
+ Classified::Other => self.attach_to_last(body),
+ }
+ Ok(())
+ }
+
+ fn split_pending(&mut self, final_chunk: bool) -> Result<(), String> {
+ let valid = match std::str::from_utf8(&self.pending) {
+ Ok(text) => text.len(),
+ Err(error) if error.error_len().is_none() && !final_chunk => error.valid_up_to(),
+ Err(_) => return Err("Navicat backups require a UTF-8 SQL export".to_string()),
+ };
+ if valid == 0 {
+ return Ok(());
+ }
+ let rest = self.pending.split_off(valid);
+ let text = String::from_utf8(std::mem::replace(&mut self.pending, rest)).expect("validated UTF-8");
+ for statement in self.splitter.push_chunk(&text) {
+ self.handle_statement(&statement)?;
+ }
+ Ok(())
+ }
+
+ pub fn finish(mut self) -> Result<(), String> {
+ self.split_pending(true)?;
+ for statement in std::mem::take(&mut self.splitter).finish_with_control() {
+ self.handle_statement(&statement.sql)?;
+ }
+ if !self.orphans.is_empty() {
+ if let Some(first) = self.objects.first_mut() {
+ log::warn!("[navicat-nb3] attaching {} unclassified statements to {}", self.orphans.len(), first.name);
+ first.sub_ddl.splice(0..0, std::mem::take(&mut self.orphans));
+ }
+ }
+ for object in &mut self.objects {
+ object.finish_chunk()?;
+ }
+ let mut order = (0..self.objects.len()).collect::<Vec<_>>();
+ order.sort_by_key(|index| creation_rank(self.objects[*index].object_type));
+
+ let output = self.output.take().expect("Navicat backup output is open");
+ let mut builder = tar::Builder::new(BufWriter::new(output));
+ let mut entries = Vec::with_capacity(order.len());
+ for index in order {
+ let object = &self.objects[index];
+ for chunk in &object.chunks {
+ let file = File::open(&chunk.path).map_err(|error| error.to_string())?;
+ let size = file.metadata().map_err(|error| error.to_string())?.len();
+ append_member(&mut builder, &chunk.name, size, file)?;
+ }
+ let is_table = object.object_type == "Table";
+ let meta = Nb3ObjectMeta {
+ meta_version: META_VERSION.to_string(),
+ name: object.name.clone(),
+ object_type: object.object_type.to_string(),
+ ddl: object.ddl.clone(),
+ sub_ddl: object.sub_ddl.clone(),
+ auto_increment: String::new(),
+ fields: is_table.then(|| object.fields.clone().unwrap_or_default()),
+ trigger_ddl: object.trigger_ddl.clone(),
+ index_ddl: object.index_ddl.clone(),
+ data: object
+ .chunks
+ .iter()
+ .map(|chunk| Nb3MemberRef { filename: chunk.name.clone(), checksum: chunk.checksum.clone() })
+ .collect(),
+ };
+ let mut encoder = GzEncoder::new(Vec::new(), Compression::default());
+ encoder.write_all(&navicat_json(&meta)?).map_err(|error| error.to_string())?;
+ let compressed = encoder.finish().map_err(|error| error.to_string())?;
+ let filename = format!("{}.meta.json.gz", object.uuid);
+ append_member(&mut builder, &filename, compressed.len() as u64, compressed.as_slice())?;
+ entries.push(Nb3ObjectEntry {
+ uuid: object.uuid.clone(),
+ object_type: object.object_type.to_string(),
+ name: object.name.clone(),
+ rows: is_table.then(|| object.rows.to_string()),
+ metadata: Nb3MemberRef { filename, checksum: sha1_hex(&compressed) },
+ });
+ }
+ let manifest = Nb3Manifest {
+ meta_version: META_VERSION.to_string(),
+ database_type: self.dialect.archive_name().to_string(),
+ service_provider: String::new(),
+ catalog: self.catalog.clone(),
+ schema: self.schema.clone(),
+ start_time: self.started_at.to_string(),
+ end_time: chrono::Utc::now().timestamp().to_string(),
+ encryption: "None".to_string(),
+ comment: String::new(),
+ objects: entries,
+ };
+ let manifest = navicat_json(&manifest)?;
+ append_member(&mut builder, MANIFEST_NAME, manifest.len() as u64, manifest.as_slice())?;
+ builder
+ .into_inner()
+ .and_then(|mut writer| writer.flush())
+ .map_err(|error| format!("Failed to write Navicat backup: {error}"))
+ }
+}
+
+impl Write for Nb3ExportWriter {
+ fn write(&mut self, buffer: &[u8]) -> std::io::Result<usize> {
+ self.pending.extend_from_slice(buffer);
+ if self.pending.len() >= EXPORT_SPLIT_THRESHOLD_BYTES {
+ self.split_pending(false).map_err(io_error)?;
+ }
+ Ok(buffer.len())
+ }
+
+ fn flush(&mut self) -> std::io::Result<()> {
+ Ok(())
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn tuples(dialect: Nb3Dialect, text: &str) -> Vec<String> {
+ let mut scanner = TupleScanner::new(dialect);
+ let mut pos = 0;
+ let mut found = Vec::new();
+ while let TupleScan::Tuple { start, end } = scanner.next(text.as_bytes(), &mut pos).unwrap() {
+ found.push(text[start..end].to_string());
+ }
+ assert!(scanner.is_between_tuples(), "scanner ended inside a tuple: {text}");
+ found
+ }
+
+ fn gzip(bytes: &[u8]) -> Vec<u8> {
+ let mut encoder = GzEncoder::new(Vec::new(), Compression::default());
+ encoder.write_all(bytes).unwrap();
+ encoder.finish().unwrap()
+ }
+
+ /// Builds an archive the way Navicat lays it out: per-object metadata, data
+ /// chunks, then `meta.json`.
+ fn navicat_archive(path: &Path, database_type: &str, objects: &[(serde_json::Value, Vec<&str>)]) {
+ let mut builder = tar::Builder::new(File::create(path).unwrap());
+ let mut entries = Vec::new();
+ for (index, (meta, chunks)) in objects.iter().enumerate() {
+ let uuid = format!("00000000-0000-0000-0000-{index:012}");
+ let mut meta = meta.clone();
+ let mut data = Vec::new();
+ for (chunk_index, chunk) in chunks.iter().enumerate() {
+ let name = format!("{uuid}.data.{chunk_index:05}.sql.gz");
+ let compressed = gzip(chunk.as_bytes());
+ data.push(serde_json::json!({ "Filename": name, "Checksum": sha1_hex(&compressed) }));
+ append_member(&mut builder, &name, compressed.len() as u64, compressed.as_slice()).unwrap();
+ }
+ meta["Data"] = serde_json::Value::Array(data);
+ let compressed = gzip(&navicat_json(&meta).unwrap());
+ let filename = format!("{uuid}.meta.json.gz");
+ append_member(&mut builder, &filename, compressed.len() as u64, compressed.as_slice()).unwrap();
+ entries.push(serde_json::json!({
+ "UUID": uuid,
+ "Type": meta["Type"],
+ "Name": meta["Name"],
+ "Metadata": { "Filename": filename, "Checksum": sha1_hex(&compressed) },
+ }));
+ }
+ let manifest = navicat_json(&serde_json::json!({
+ "MetaVersion": "30101",
+ "DatabaseType": database_type,
+ "ServiceProvider": "",
+ "Catalog": "app",
+ "Schema": "public",
+ "StartTime": "1765165827",
+ "EndTime": "1765165829",
+ "Encryption": "None",
+ "Comment": "",
+ "Objects": entries,
+ }))
+ .unwrap();
+ append_member(&mut builder, MANIFEST_NAME, manifest.len() as u64, manifest.as_slice()).unwrap();
+ builder.into_inner().unwrap();
+ }
+
+ fn restore_script(path: &Path) -> Result<String, String> {
+ let mut reader = Nb3SqlReader::open(path, None)?;
+ let mut script = String::new();
+ reader.read_to_string(&mut script).map_err(|error| error.to_string())?;
+ Ok(script)
+ }
+
+ fn position(script: &str, needle: &str) -> usize {
+ script.find(needle).unwrap_or_else(|| panic!("{needle:?} missing from restore script:\n{script}"))
+ }
+
+ fn split_statements(db_type: DatabaseType, script: &str) -> Vec<String> {
+ let mut splitter = SqlStatementSplitter::with_options(SqlParsingOptions::for_database_type(db_type));
+ let mut statements = splitter.push_chunk(script);
+ statements.extend(splitter.finish_with_control().into_iter().map(|statement| statement.sql));
+ statements
+ }
+
+ #[test]
+ fn tuple_scanner_respects_dialect_quoting() {
+ assert_eq!(
+ tuples(Nb3Dialect::Mysql, "(1, 'a\\'), (', NULL)\x1e\n(2, \"x)\", 0x41)"),
+ ["(1, 'a\\'), (', NULL)", "(2, \"x)\", 0x41)"]
+ );
+ assert_eq!(
+ tuples(Nb3Dialect::Postgres, "(1, 'it''s (fine)', E'a\\'b)')\x1e\n(2, '{\"a\",\"b\"}', 'C:\\')"),
+ ["(1, 'it''s (fine)', E'a\\'b)')", "(2, '{\"a\",\"b\"}', 'C:\\')"]
+ );
+ assert!(split_value_tuples(Nb3Dialect::Mysql, "(1) ON DUPLICATE KEY UPDATE id = 1").is_none());
+ }
+
+ #[test]
+ fn classifies_exported_statements() {
+ let mysql = |sql| classify_statement(Nb3Dialect::Mysql, sql);
+ let postgres = |sql| classify_statement(Nb3Dialect::Postgres, sql);
+ assert_eq!(
+ mysql("CREATE TABLE IF NOT EXISTS `app`.`users` (`id` int)"),
+ Classified::Object { object_type: "Table", name: "users".into() }
+ );
+ assert_eq!(
+ mysql("CREATE ALGORITHM = UNDEFINED DEFINER = `root`@`%` SQL SECURITY DEFINER VIEW `v` AS SELECT 1"),
+ Classified::Object { object_type: "View", name: "v".into() }
+ );
+ assert_eq!(
+ mysql(
+ "CREATE DEFINER=`root`@`localhost` TRIGGER `trg` BEFORE INSERT ON `users` FOR EACH ROW SET NEW.id = 1"
+ ),
+ Classified::Trigger { table: "users".into() }
+ );
+ assert_eq!(
+ postgres("CREATE UNIQUE INDEX \"users_email\" ON ONLY \"public\".\"users\" USING btree (email)"),
+ Classified::TableIndex { table: "users".into() }
+ );
+ assert_eq!(
+ postgres("ALTER TABLE \"public\".\"users\" ADD CONSTRAINT \"users_pkey\" PRIMARY KEY (\"id\")"),
+ Classified::TableIndex { table: "users".into() }
+ );
+ assert_eq!(
+ postgres("ALTER TABLE ONLY public.Orders ADD CONSTRAINT fk FOREIGN KEY (user_id) REFERENCES users (id)"),
+ Classified::TableSub { table: "orders".into() }
+ );
+ assert_eq!(
+ postgres("SELECT pg_catalog.setval('\"public\".\"users_id_seq\"', 42, true)"),
+ Classified::ObjectSub { object_type: "Sequence", name: "users_id_seq".into() }
+ );
+ assert_eq!(
+ postgres("COMMENT ON COLUMN \"public\".\"users\".\"email\" IS 'x'"),
+ Classified::TableSub { table: "users".into() }
+ );
+ assert_eq!(
+ mysql("INSERT INTO `users` (`id`, `name`) VALUES (1, 'a')"),
+ Classified::Rows {
+ table: "users".into(),
+ columns: vec!["id".into(), "name".into()],
+ values_at: "INSERT INTO `users` (`id`, `name`) VALUES".len()
+ }
+ );
+ assert_eq!(mysql("SET FOREIGN_KEY_CHECKS = 0"), Classified::Skip);
+ assert_eq!(mysql("DROP TABLE IF EXISTS `users`"), Classified::Skip);
+ assert_eq!(postgres("GRANT SELECT ON users TO app"), Classified::Other);
+ }
+
+ #[test]
+ fn mysql_export_round_trips_through_nb3() {
+ let directory = tempfile::tempdir().unwrap();
+ let path = directory.path().join("app.nb3");
+ let mut writer = Nb3ExportWriter::new(
+ File::create(&path).unwrap(),
+ Some(directory.path()),
+ DatabaseType::Mysql,
+ "app",
+ "app",
+ )
+ .unwrap();
+ let export = "-- Database export: app\n-- Generated by DBX\n\nSET NAMES utf8mb4;\nSET FOREIGN_KEY_CHECKS = 0;\n\n\
+ DROP TABLE IF EXISTS `users`;\n\
+ CREATE TABLE `users` (\n `id` int NOT NULL,\n `name` varchar(20),\n PRIMARY KEY (`id`)\n) ENGINE=InnoDB;\n\n\
+ INSERT INTO `users` (`id`, `name`) VALUES (1, 'semi;colon'), (2, 'it\\'s (ok)');\n\
+ INSERT INTO `users` (`id`, `name`) VALUES (3, NULL);\n\n\
+ CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`%` SQL SECURITY DEFINER VIEW `user_names` AS select `name` from `users`;\n\n\
+ DELIMITER //\nCREATE DEFINER=`root`@`%` TRIGGER `trim_name` BEFORE INSERT ON `users` FOR EACH ROW\nBEGIN\n SET NEW.name = TRIM(NEW.name);\nEND//\nDELIMITER ;\n\n\
+ DELIMITER //\nCREATE DEFINER=`root`@`%` PROCEDURE `touch`()\nBEGIN\n SELECT 1;\nEND//\nDELIMITER ;\n\n\
+ SET FOREIGN_KEY_CHECKS = 1;\n";
+ // Feed the export in small pieces, as the exporter writes it.
+ for piece in export.as_bytes().chunks(7) {
+ writer.write_all(piece).unwrap();
+ }
+ writer.finish().unwrap();
+ assert!(directory.path().read_dir().unwrap().all(|entry| !entry
+ .unwrap()
+ .file_name()
+ .to_string_lossy()
+ .starts_with(".dbx-nb3-")));
+
+ let archive = Nb3Archive::open(&path).unwrap();
+ assert_eq!(archive.manifest.database_type, "MYSQL");
+ assert_eq!(archive.manifest.schema, "app");
+ let objects = archive
+ .objects
+ .iter()
+ .map(|object| (object.meta.object_type.as_str(), object.meta.name.as_str()))
+ .collect::<Vec<_>>();
+ assert_eq!(objects, [("Procedure", "touch"), ("Table", "users"), ("View", "user_names")]);
+ let users = &archive.objects[1];
+ assert_eq!(archive.manifest.objects[1].rows.as_deref(), Some("3"));
+ assert_eq!(users.meta.fields.as_deref(), Some(&["id".to_string(), "name".to_string()][..]));
+ assert_eq!(users.meta.trigger_ddl.len(), 1);
+ assert!(users.meta.trigger_ddl[0].starts_with("CREATE DEFINER=`root`@`%` TRIGGER `trim_name`"));
+ assert!(users.meta.trigger_ddl[0].ends_with("END"));
+
+ let script = restore_script(&path).unwrap();
+ let drop_view = position(&script, "DROP VIEW IF EXISTS `user_names`;");
+ let drop_table = position(&script, "DROP TABLE IF EXISTS `users`;");
+ let create_procedure = position(&script, "PROCEDURE `touch`()");
+ let create_table = position(&script, "CREATE TABLE `users`");
+ let insert = position(
+ &script,
+ "INSERT INTO `users` (`id`, `name`) VALUES\n(1, 'semi;colon'),\n(2, 'it\\'s (ok)'),\n(3, NULL);",
+ );
+ let view = position(&script, "VIEW `user_names` AS");
+ let trigger = position(&script, "DELIMITER //\nCREATE DEFINER=`root`@`%` TRIGGER `trim_name`");
+ assert!(drop_view < drop_table && drop_table < create_procedure && create_procedure < create_table);
+ assert!(create_table < insert && insert < view && view < trigger);
+ assert!(script.trim_end().ends_with("SET FOREIGN_KEY_CHECKS = 1;"));
+
+ let statements = split_statements(DatabaseType::Mysql, &script);
+ assert!(statements.iter().any(|statement| statement.contains("SET NEW.name = TRIM(NEW.name);\nEND")));
+ }
+
+ #[test]
+ fn restores_navicat_postgres_archive_in_dependency_order() {
+ let directory = tempfile::tempdir().unwrap();
+ let path = directory.path().join("navicat.nb3");
+ navicat_archive(
+ &path,
+ "PGSQL",
+ &[
+ (
+ serde_json::json!({
+ "MetaVersion": "30101", "Name": "Users_id_seq", "Type": "Sequence",
+ "DDL": "CREATE SEQUENCE \"Users_id_seq\" \r\nINCREMENT 1\r\nCACHE 1",
+ "SubDDL": [
+ "ALTER SEQUENCE \"Users_id_seq\"\r\nOWNED BY \"Users\".\"id\"",
+ "SELECT setval('\"Users_id_seq\"', 3, true)"
+ ],
+ "AutoIncrement": "", "TriggerDDL": [], "IndexDDL": []
+ }),
+ vec![],
+ ),
+ (
+ // Archived before the table its foreign key references, as Navicat orders by name.
+ serde_json::json!({
+ "MetaVersion": "30101", "Name": "Approval", "Type": "Table",
+ "DDL": "CREATE TABLE \"Approval\" (\r\n \"approver_id\" int4 NOT NULL\r\n)",
+ "SubDDL": ["ALTER TABLE \"Approval\" ADD CONSTRAINT \"Approval_approver_id_fkey\" FOREIGN KEY (\"approver_id\") REFERENCES \"public\".\"Users\" (\"id\")"],
+ "AutoIncrement": "", "Fields": ["approver_id"], "TriggerDDL": [], "IndexDDL": []
+ }),
+ vec![],
+ ),
+ (
+ serde_json::json!({
+ "MetaVersion": "30101", "Name": "Users", "Type": "Table",
+ "DDL": "CREATE TABLE \"Users\" (\r\n \"id\" int4 NOT NULL DEFAULT nextval('\"Users_id_seq\"'::regclass),\r\n \"note\" text\r\n)\r\n;\r\nALTER TABLE \"Users\" OWNER TO \"postgres\"",
+ "SubDDL": ["ALTER TABLE \"Users\" ADD CONSTRAINT \"Users_parent_fkey\" FOREIGN KEY (\"id\") REFERENCES \"public\".\"Users\" (\"id\")"],
+ "AutoIncrement": "", "Fields": ["id", "note"], "TriggerDDL": [],
+ "IndexDDL": ["ALTER TABLE \"Users\" ADD CONSTRAINT \"Users_pkey\" PRIMARY KEY (\"id\")"]
+ }),
+ vec!["(1, 'a\x1e\nb')\x1e\n(2, 'it''s')", "(3, NULL)"],
+ ),
+ ],
+ );
+
+ let script = restore_script(&path).unwrap();
+ let drop_table = position(&script, "DROP TABLE IF EXISTS \"Users\" CASCADE;");
+ let drop_sequence = position(&script, "DROP SEQUENCE IF EXISTS \"Users_id_seq\" CASCADE;");
+ let create_sequence = position(&script, "CREATE SEQUENCE \"Users_id_seq\"");
+ let create_table = position(&script, "CREATE TABLE \"Users\"");
+ let first_insert = position(
+ &script,
+ "INSERT INTO \"Users\" (\"id\", \"note\") VALUES\n(1, 'a\x1e\nb'),\n(2, 'it''s'),\n(3, NULL);",
+ );
+ let primary_key = position(&script, "ADD CONSTRAINT \"Users_pkey\" PRIMARY KEY");
+ let foreign_key = position(&script, "ADD CONSTRAINT \"Users_parent_fkey\"");
+ let setval = position(&script, "SELECT setval('\"Users_id_seq\"', 3, true);");
+ assert!(drop_table < drop_sequence && drop_sequence < create_sequence && create_sequence < create_table);
+ assert!(create_table < first_insert && first_insert < primary_key && primary_key < foreign_key);
+ assert!(first_insert < setval);
+ assert!(primary_key < position(&script, "ADD CONSTRAINT \"Approval_approver_id_fkey\""));
+ // A dropped `public` schema is recreated, without requiring CREATE when it exists.
+ let create_schema =
+ position(&script, "WHERE nspname = 'public') THEN CREATE SCHEMA \"public\"; END IF; END $nb3$;");
+ assert!(create_schema < drop_table);
+ position(&script, "SET search_path TO \"public\";");
+ let statements = split_statements(DatabaseType::Postgres, &script);
+ assert!(statements
+ .iter()
+ .any(|statement| statement.starts_with("DO $nb3$") && statement.ends_with("END $nb3$")));
+ assert_eq!(
+ split_statements(DatabaseType::Postgres, &script).iter().filter(|s| s.contains("INSERT")).count(),
+ 1
+ );
+ }
+
+ #[test]
+ fn batches_large_tables_into_bounded_inserts() {
+ let directory = tempfile::tempdir().unwrap();
+ let path = directory.path().join("big.nb3");
+ let rows = (1..=2500).map(|id| format!("({id}, 'row {id}')")).collect::<Vec<_>>().join("\x1e\n");
+ navicat_archive(
+ &path,
+ "MYSQL",
+ &[(
+ serde_json::json!({
+ "MetaVersion": "30101", "Name": "items", "Type": "Table",
+ "DDL": "CREATE TABLE `items` (`id` int, `label` text)", "SubDDL": [], "AutoIncrement": "",
+ "Fields": ["id", "label"], "TriggerDDL": [], "IndexDDL": []
+ }),
+ vec![rows.as_str()],
+ )],
+ );
+ let script = restore_script(&path).unwrap();
+ assert_eq!(script.matches("INSERT INTO `items`").count(), 3);
+ assert!(script.contains("(2500, 'row 2500');"));
+ }
+
+ #[test]
+ fn rejects_corrupted_and_encrypted_archives() {
+ let directory = tempfile::tempdir().unwrap();
+ let path = directory.path().join("corrupt.nb3");
+ navicat_archive(
+ &path,
+ "MYSQL",
+ &[(
+ serde_json::json!({
+ "MetaVersion": "30101", "Name": "t", "Type": "Table", "DDL": "CREATE TABLE `t` (`id` int)",
+ "SubDDL": [], "AutoIncrement": "", "Fields": ["id"], "TriggerDDL": [], "IndexDDL": []
+ }),
+ vec!["(1)"],
+ )],
+ );
+ // Flip one byte of the data chunk's gzip payload without touching the metadata.
+ let members = index_archive_members(&path).unwrap();
+ let (_, chunk) = members.iter().find(|(name, _)| name.contains(".data.")).unwrap();
+ let mut bytes = std::fs::read(&path).unwrap();
+ bytes[(chunk.offset + chunk.size - 5) as usize] ^= 0xff;
+ std::fs::write(&path, bytes).unwrap();
+ assert!(restore_script(&path).unwrap_err().contains("corrupted"));
+
+ let encrypted = directory.path().join("encrypted.nb3");
+ let manifest = br#"{"MetaVersion":"30101","DatabaseType":"MYSQL","Encryption":"AES256","Objects":[]}"#;
+ let mut builder = tar::Builder::new(File::create(&encrypted).unwrap());
+ append_member(&mut builder, MANIFEST_NAME, manifest.len() as u64, manifest.as_slice()).unwrap();
+ builder.into_inner().unwrap();
+ assert!(Nb3SqlReader::open(&encrypted, None).err().unwrap().contains("Encrypted"));
+ }
+
+ #[test]
+ fn rejects_rows_that_exceed_the_pending_tuple_limit() {
+ let directory = tempfile::tempdir().unwrap();
+ let path = directory.path().join("huge-row.nb3");
+ let wide_row = format!("('{}')", "x".repeat(8 * 1024));
+ navicat_archive(
+ &path,
+ "MYSQL",
+ &[(
+ serde_json::json!({
+ "MetaVersion": "30101", "Name": "t", "Type": "Table", "DDL": "CREATE TABLE `t` (`v` text)",
+ "SubDDL": [], "AutoIncrement": "", "Fields": ["v"], "TriggerDDL": [], "IndexDDL": []
+ }),
+ vec![wide_row.as_str()],
+ )],
+ );
+ // The real limit is far above any legitimate row; lower it so the test does not
+ // have to build a multi-megabyte archive to exercise the guard.
+ let mut reader = Nb3SqlReader::open(&path, None).unwrap();
+ reader.max_pending_row_bytes = 1024;
+ let mut script = String::new();
+ let error = reader.read_to_string(&mut script).unwrap_err();
+ assert!(error.to_string().contains("larger than 1024 bytes"), "{error}");
+
+ // The same archive restores normally under the default limit.
+ assert!(restore_script(&path).unwrap().contains("INSERT INTO"));
+ }
+
+ /// Renders real Navicat archives listed in `DBX_NB3_SAMPLES` (path-separated):
+ /// `DBX_NB3_SAMPLES=a.nb3:b.nb3 cargo test -p dbx-core navicat_nb3 -- --ignored`.
+ #[test]
+ #[ignore = "needs Navicat sample archives"]
+ fn renders_navicat_sample_archives() {
+ let samples = std::env::var_os("DBX_NB3_SAMPLES").expect("DBX_NB3_SAMPLES is set");
+ for path in std::env::split_paths(&samples) {
+ let archive = Nb3Archive::open(&path).unwrap_or_else(|error| panic!("{}: {error}", path.display()));
+ let expected_rows = archive
+ .manifest
+ .objects
+ .iter()
+ .filter_map(|entry| entry.rows.as_deref()?.parse::<usize>().ok())
+ .sum::<usize>();
+ let script = restore_script(&path).unwrap_or_else(|error| panic!("{}: {error}", path.display()));
+ let statements = split_statements(archive.database_type(), &script);
+ let inserted_rows = statements
+ .iter()
+ .filter(|statement| statement.trim_start().starts_with("INSERT INTO"))
+ .map(|statement| {
+ let values = &statement[statement.find(" VALUES\n").expect("VALUES clause") + 8..];
+ split_value_tuples(archive.dialect, values).expect("value tuples").len()
+ })
+ .sum::<usize>();
+ println!(
+ "{}: {} objects, {} statements, {inserted_rows} rows",
+ path.display(),
+ archive.objects.len(),
+ statements.len()
+ );
+ assert_eq!(inserted_rows, expected_rows, "{}", path.display());
+ }
+ }
+
+ #[test]
+ fn postgres_identity_tables_override_generated_values() {
+ let directory = tempfile::tempdir().unwrap();
+ let path = directory.path().join("identity.nb3");
+ let mut writer =
+ Nb3ExportWriter::new(File::create(&path).unwrap(), None, DatabaseType::Postgres, "app", "drizzle").unwrap();
+ writer
+ .write_all(
+ b"CREATE SCHEMA IF NOT EXISTS \"drizzle\";\n\
+ CREATE TABLE \"drizzle\".\"events\" (\"id\" bigint GENERATED ALWAYS AS IDENTITY, \"name\" text);\n\
+ INSERT INTO \"drizzle\".\"events\" (\"id\", \"name\") OVERRIDING SYSTEM VALUE VALUES (1, E'tab\\there');\n",
+ )
+ .unwrap();
+ writer.finish().unwrap();
+ let script = restore_script(&path).unwrap();
+ // The unqualified DROP and INSERT must resolve in the archived schema, which may not exist yet.
+ let create_schema = position(
+ &script,
+ "WHERE nspname = 'drizzle') THEN CREATE SCHEMA \"drizzle\"; END IF; END $nb3$;\nSET search_path TO \"drizzle\", public;",
+ );
+ let drop = position(&script, "DROP TABLE IF EXISTS \"events\" CASCADE;");
+ let insert = position(
+ &script,
+ "INSERT INTO \"events\" (\"id\", \"name\") OVERRIDING SYSTEM VALUE VALUES\n(1, E'tab\\there');",
+ );
+ assert!(create_schema < drop && drop < insert);
+ assert!(Nb3ExportWriter::new(File::create(&path).unwrap(), None, DatabaseType::Sqlite, "app", "").is_err());
+ }
+}
diff --git a/crates/dbx-core/src/data/sql_file_import.rs b/crates/dbx-core/src/data/sql_file_import.rs
index 09fade90b9..7e67da4d8b 100644
--- a/crates/dbx-core/src/data/sql_file_import.rs
+++ b/crates/dbx-core/src/data/sql_file_import.rs
@@ -1360,6 +1360,8 @@ pub(crate) struct SqlFileStreamDecoder {
enum SqlFileByteReader {
Plain(BufReader<tokio::fs::File>, Option<Arc<AtomicU64>>),
Gzip(Arc<Mutex<flate2::read::GzDecoder<SqlFileCountingReader<std::io::BufReader<std::fs::File>>>>>),
+ /// Navicat `.nb3` archive rendered as a restore script.
+ Nb3(Arc<Mutex<crate::navicat_nb3::Nb3SqlReader>>),
}
impl SqlFileByteReader {
@@ -1368,6 +1370,13 @@ impl SqlFileByteReader {
}
async fn open_with_progress(file_path: &Path, bytes_read: Option<Arc<AtomicU64>>) -> Result<Self, String> {
+ if crate::navicat_nb3::is_nb3_path(file_path) {
+ let path = file_path.to_path_buf();
+ let reader = tokio::task::spawn_blocking(move || crate::navicat_nb3::Nb3SqlReader::open(&path, bytes_read))
+ .await
+ .map_err(|error| format!("Failed to open Navicat backup: {error}"))??;
+ return Ok(Self::Nb3(Arc::new(Mutex::new(reader))));
+ }
if is_gzip_sql_file_path(file_path) {
let path = file_path.to_path_buf();
let reader = tokio::task::spawn_blocking(move || {
@@ -1395,26 +1404,31 @@ impl SqlFileByteReader {
}
Ok(read)
}
- Self::Gzip(reader) => {
- let reader = reader.clone();
- let capacity = buffer.len();
- let (chunk, read) = tokio::task::spawn_blocking(move || {
- let mut chunk = vec![0; capacity];
- let mut reader =
- reader.lock().map_err(|_| "Compressed SQL reader lock was poisoned".to_string())?;
- let read =
- reader.read(&mut chunk).map_err(|error| format!("Failed to decompress SQL file: {error}"))?;
- Ok::<_, String>((chunk, read))
- })
- .await
- .map_err(|error| format!("Failed to read compressed SQL file: {error}"))??;
- buffer[..read].copy_from_slice(&chunk[..read]);
- Ok(read)
- }
+ Self::Gzip(reader) => read_blocking_sql_source(reader.clone(), buffer, "compressed SQL file").await,
+ Self::Nb3(reader) => read_blocking_sql_source(reader.clone(), buffer, "Navicat backup").await,
}
}
}
+/// Reads a synchronous decoder off the async worker threads.
+async fn read_blocking_sql_source<R: StdRead + Send + 'static>(
+ reader: Arc<Mutex<R>>,
+ buffer: &mut [u8],
+ label: &'static str,
+) -> Result<usize, String> {
+ let capacity = buffer.len();
+ let (chunk, read) = tokio::task::spawn_blocking(move || {
+ let mut chunk = vec![0; capacity];
+ let mut reader = reader.lock().map_err(|_| format!("Reader lock for {label} was poisoned"))?;
+ let read = reader.read(&mut chunk).map_err(|error| format!("Failed to read {label}: {error}"))?;
+ Ok::<_, String>((chunk, read))
+ })
+ .await
+ .map_err(|error| format!("Failed to read {label}: {error}"))??;
+ buffer[..read].copy_from_slice(&chunk[..read]);
+ Ok(read)
+}
+
/// 嗅探文件开头的字节序标记,存在时返回 BOM 对应的编码与长度。
///
/// 表导入显式选择编码时也优先按 BOM 解码:与非流式 `Encoding::decode`
diff --git a/crates/dbx-core/src/lib.rs b/crates/dbx-core/src/lib.rs
index b31aaba264..c63d4074bd 100644
--- a/crates/dbx-core/src/lib.rs
+++ b/crates/dbx-core/src/lib.rs
@@ -63,6 +63,7 @@ pub use data::docs;
pub use data::export_runtime;
pub use data::mongodb_dump;
pub use data::mongodb_import_export;
+pub use data::navicat_nb3;
pub use dbx_drivers::mongo_oidc;
pub use dbx_drivers::mongo_shell;
pub use dbx_drivers::salesforce_oauth;
diff --git a/crates/dbx-core/src/scheduled_backup/engine.rs b/crates/dbx-core/src/scheduled_backup/engine.rs
index b2d685b2f8..aee7487050 100644
--- a/crates/dbx-core/src/scheduled_backup/engine.rs
+++ b/crates/dbx-core/src/scheduled_backup/engine.rs
@@ -330,7 +330,11 @@ impl BackupService {
&job.time_zone,
false,
)?;
- let extension = if job.config.output_compression == "gzip" { "sql.gz" } else { "sql" };
+ let extension = match job.config.output_compression.as_str() {
+ "gzip" => "sql.gz",
+ "nb3" => "nb3",
+ _ => "sql",
+ };
let path = output.join(format!("{name}.{extension}"));
check_output_ancestors(&path, Path::new(&job.config.destination_directory))?;
if path.try_exists().map_err(|e| e.to_string())? {
@@ -366,10 +370,10 @@ impl BackupService {
preserve_original_language: false,
fail_on_error: true,
prevent_overwrite: true,
- output_compression: if job.config.output_compression == "gzip" {
- DatabaseExportOutputCompression::Gzip
- } else {
- DatabaseExportOutputCompression::None
+ output_compression: match job.config.output_compression.as_str() {
+ "gzip" => DatabaseExportOutputCompression::Gzip,
+ "nb3" => DatabaseExportOutputCompression::Nb3,
+ _ => DatabaseExportOutputCompression::None,
},
insert_dialect: Default::default(),
insert_mode: Default::default(),
diff --git a/crates/dbx-core/src/scheduled_backup/mod.rs b/crates/dbx-core/src/scheduled_backup/mod.rs
index 041c1ec943..8f4495fc25 100644
--- a/crates/dbx-core/src/scheduled_backup/mod.rs
+++ b/crates/dbx-core/src/scheduled_backup/mod.rs
@@ -7,7 +7,7 @@ mod store;
mod tests;
pub use models::{BackupConfig, BackupFile, BackupRun, BackupSchedule, BackupTableTarget, Migration, RunRequest};
-pub use service::{BackupCommand, BackupService};
+pub use service::{BackupCommand, BackupService, IMPORTED_SOURCE};
pub use store::{BackupSnapshot, BackupStore};
/// Metadata and export command chains nest very large async futures - a single
diff --git a/crates/dbx-core/src/scheduled_backup/models.rs b/crates/dbx-core/src/scheduled_backup/models.rs
index 9028059e02..eaf29619ed 100644
--- a/crates/dbx-core/src/scheduled_backup/models.rs
+++ b/crates/dbx-core/src/scheduled_backup/models.rs
@@ -152,7 +152,7 @@ impl BackupConfig {
if !self.include_structure && !self.include_data && !self.include_objects {
return Err("Select backup contents".into());
}
- if !matches!(self.output_compression.as_str(), "none" | "gzip") {
+ if !matches!(self.output_compression.as_str(), "none" | "gzip" | "nb3") {
return Err("Unsupported backup compression".into());
}
if !matches!(self.table_filter_mode.as_str(), "all" | "include" | "exclude" | "selected") {
diff --git a/crates/dbx-core/src/scheduled_backup/service.rs b/crates/dbx-core/src/scheduled_backup/service.rs
index 582664b5f0..dd5cdcc8b0 100644
--- a/crates/dbx-core/src/scheduled_backup/service.rs
+++ b/crates/dbx-core/src/scheduled_backup/service.rs
@@ -22,8 +22,12 @@ pub enum BackupCommand {
Rename { id: String, name: String },
DeleteRuns { ids: Vec<String> },
File { id: String, index: usize },
+ Import { files: Vec<String> },
}
+/// Source of history entries for backup files created outside DBX, such as Navicat `.nb3` archives.
+pub const IMPORTED_SOURCE: &str = "imported";
+
#[derive(Clone)]
pub struct BackupService {
pub(crate) state: Arc<AppState>,
@@ -100,9 +104,84 @@ impl BackupService {
self.delete_runs(ids).await?;
Ok(Value::Null)
}
+ BackupCommand::Import { files } => {
+ serde_json::to_value(self.import_files(files).await?).map_err(|e| e.to_string())
+ }
}
}
+ /// Lists backup files created outside DBX in the history so they can be restored later.
+ /// DBX never owns imported files: deleting the entry only removes it from the history.
+ async fn import_files(&self, files: Vec<String>) -> Result<Vec<BackupRun>, String> {
+ if files.is_empty() || files.len() > 100 {
+ return Err("Select between 1 and 100 backup files".into());
+ }
+ let known = self
+ .store
+ .snapshot()
+ .await?
+ .runs
+ .into_iter()
+ .flat_map(|run| run.files.into_iter().map(|file| file.file_path))
+ .collect::<std::collections::HashSet<_>>();
+ let mut runs = Vec::with_capacity(files.len());
+ for file in files {
+ bounded_text(&file, 4096, "Backup file")?;
+ let path = Path::new(&file);
+ let parent = path.parent().ok_or("Backup file has no parent directory")?;
+ let directory = self.validate_destination(&parent.to_string_lossy())?;
+ let metadata = std::fs::symlink_metadata(path).map_err(|e| format!("{file}: {e}"))?;
+ if !metadata.is_file() {
+ return Err(format!("Backup file is not a regular file: {file}"));
+ }
+ let resolved = path.canonicalize().map_err(|e| e.to_string())?;
+ let file_path = resolved.to_string_lossy().into_owned();
+ let name = resolved.file_name().unwrap_or_default().to_string_lossy().into_owned();
+ let lower = name.to_ascii_lowercase();
+ if !lower.ends_with(".sql") && !lower.ends_with(".sql.gz") && !lower.ends_with(".nb3") {
+ return Err(format!("Unsupported backup file (use .sql, .sql.gz or .nb3): {name}"));
+ }
+ if known.contains(&file_path) || runs.iter().any(|run: &BackupRun| run.files[0].file_path == file_path) {
+ return Err(format!("Backup file is already in the history: {name}"));
+ }
+ let modified = metadata.modified().ok().map(chrono::DateTime::<chrono::Utc>::from);
+ let (database, schema, started_at) = if crate::navicat_nb3::is_nb3_path(&resolved) {
+ let archive = crate::navicat_nb3::Nb3Archive::open(&resolved).map_err(|e| format!("{name}: {e}"))?;
+ let (database, schema) = archive.source_database_and_schema();
+ let started = archive.started_at().and_then(|seconds| chrono::DateTime::from_timestamp(seconds, 0));
+ (database, schema, started.or(modified))
+ } else {
+ (String::new(), String::new(), modified)
+ };
+ let display_name = match (database.is_empty(), schema.is_empty() || schema == database) {
+ (true, _) => name.clone(),
+ (false, true) => database.clone(),
+ (false, false) => format!("{database}.{schema}"),
+ };
+ record_export_destination_identity(&self.state, &directory).await?;
+ let now = chrono::Utc::now().to_rfc3339();
+ runs.push(BackupRun {
+ id: uuid::Uuid::new_v4().simple().to_string(),
+ schedule_id: None,
+ schedule_name: name,
+ display_name: None,
+ connection_id: String::new(),
+ connection_name: String::new(),
+ destination_directory: directory.to_string_lossy().into_owned(),
+ trigger: "manual".into(),
+ source: IMPORTED_SOURCE.into(),
+ status: "success".into(),
+ started_at: started_at.map(|time| time.to_rfc3339()).unwrap_or_else(|| now.clone()),
+ completed_at: Some(now),
+ files: vec![BackupFile { database, schema, display_name, file_path, owned: false }],
+ progress_percent: 100.0,
+ error: None,
+ });
+ }
+ self.store.insert_completed(runs.clone()).await?;
+ Ok(runs)
+ }
+
pub(crate) fn validate_destination(&self, path: &str) -> Result<PathBuf, String> {
let path = Path::new(path);
if !path.is_absolute() || path.components().any(|c| matches!(c, Component::ParentDir)) {
@@ -142,7 +221,7 @@ impl BackupService {
return Err("Backup file escaped its destination".into());
}
let name = resolved.file_name().unwrap_or_default().to_string_lossy().to_ascii_lowercase();
- if !name.ends_with(".sql") && !name.ends_with(".sql.gz") {
+ if !name.ends_with(".sql") && !name.ends_with(".sql.gz") && !name.ends_with(".nb3") {
return Err("Not a SQL backup file".into());
}
Ok(resolved)
@@ -200,6 +279,11 @@ impl BackupService {
}
let mut errors = Vec::new();
for mut run in self.store.mark_deleting(ids).await? {
+ if run.source == IMPORTED_SOURCE {
+ // Imported files belong to the user; only the history entry is removed.
+ self.store.remove_run(run.id).await?;
+ continue;
+ }
if let Err(error) = self.cleanup(&mut run).await {
run.error = Some(format!("Backup cleanup failed: {error}"));
self.store.deletion_failed(run).await?;
diff --git a/crates/dbx-core/src/scheduled_backup/store.rs b/crates/dbx-core/src/scheduled_backup/store.rs
index b97a2ed2b5..9963a30300 100644
--- a/crates/dbx-core/src/scheduled_backup/store.rs
+++ b/crates/dbx-core/src/scheduled_backup/store.rs
@@ -394,6 +394,22 @@ impl BackupStore {
.await
}
+ /// Records runs that are already complete, such as imported backup files.
+ pub(crate) async fn insert_completed(&self, runs: Vec<BackupRun>) -> Result<(), String> {
+ self.access(move |conn| {
+ let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate).map_err(sql_error)?;
+ for run in runs {
+ tx.execute(
+ "INSERT INTO runs(id,schedule_id,state,payload,job,created_at) VALUES(?,NULL,?,?,NULL,?)",
+ params![run.id, run.status, encode(&run)?, run.started_at],
+ )
+ .map_err(sql_error)?;
+ }
+ tx.commit().map_err(sql_error)
+ })
+ .await
+ }
+
pub async fn rename(&self, id: String, name: String) -> Result<(), String> {
bounded_text(&name, 256, "Backup name")?;
self.access(move |conn| {
diff --git a/crates/dbx-core/src/scheduled_backup/tests.rs b/crates/dbx-core/src/scheduled_backup/tests.rs
index 6575a90d10..3c5f6676dc 100644
--- a/crates/dbx-core/src/scheduled_backup/tests.rs
+++ b/crates/dbx-core/src/scheduled_backup/tests.rs
@@ -209,6 +209,76 @@ async fn deletion_only_removes_recorded_files_within_the_backup_root() {
assert!(service.store.snapshot().await.unwrap().runs.is_empty());
}
+#[tokio::test]
+async fn imported_backups_restore_from_their_folder_and_are_never_deleted() {
+ let dir = tempfile::tempdir().unwrap();
+ let service = service(dir.path(), None).await;
+ let downloads = dir.path().join("downloads");
+ std::fs::create_dir(&downloads).unwrap();
+ let dump = downloads.join("before-upgrade.sql.gz");
+ std::fs::write(&dump, "not inspected").unwrap();
+ let import = |path: &std::path::Path| BackupCommand::Import { files: vec![path.to_string_lossy().into_owned()] };
+
+ let imported = service.command(import(&dump)).await.unwrap();
+ let run: BackupRun = serde_json::from_value(imported[0].clone()).unwrap();
+ assert_eq!((run.source.as_str(), run.status.as_str()), (IMPORTED_SOURCE, "success"));
+ assert_eq!(run.files[0].display_name, "before-upgrade.sql.gz");
+ assert!(!run.files[0].owned);
+ assert_eq!(service.file(&run.id, 0).await.unwrap(), dump.canonicalize().unwrap());
+
+ assert!(service.command(import(&dump)).await.unwrap_err().contains("already in the history"));
+ let notes = downloads.join("notes.txt");
+ std::fs::write(&notes, "x").unwrap();
+ assert!(service.command(import(&notes)).await.unwrap_err().contains("Unsupported"));
+ assert!(service.command(import(&downloads)).await.is_err());
+
+ service.delete_runs(vec![run.id]).await.unwrap();
+ assert!(dump.exists());
+ assert!(service.store.snapshot().await.unwrap().runs.is_empty());
+}
+
+#[tokio::test]
+async fn imported_navicat_archives_record_their_source_and_web_imports_stay_in_the_root() {
+ use std::io::Write;
+ let dir = tempfile::tempdir().unwrap();
+ let root = dir.path().join("backups");
+ std::fs::create_dir(&root).unwrap();
+ let service = service(dir.path(), Some(root.clone())).await;
+ let write_archive = |path: &std::path::Path| {
+ let mut writer = crate::navicat_nb3::Nb3ExportWriter::new(
+ std::fs::File::create(path).unwrap(),
+ None,
+ crate::models::connection::DatabaseType::Postgres,
+ "shop",
+ "sales",
+ )
+ .unwrap();
+ writer.write_all(b"CREATE TABLE \"sales\".\"orders\" (\"id\" int);\n").unwrap();
+ writer.finish().unwrap();
+ };
+
+ let outside = dir.path().join("outside.nb3");
+ write_archive(&outside);
+ let files = vec![outside.to_string_lossy().into_owned()];
+ assert!(service
+ .command(BackupCommand::Import { files })
+ .await
+ .unwrap_err()
+ .contains("outside the server backup root"));
+
+ let archive = root.join("navicat.nb3");
+ write_archive(&archive);
+ let files = vec![archive.to_string_lossy().into_owned()];
+ let imported = service.command(BackupCommand::Import { files }).await.unwrap();
+ let run: BackupRun = serde_json::from_value(imported[0].clone()).unwrap();
+ let file = &run.files[0];
+ assert_eq!(
+ (file.database.as_str(), file.schema.as_str(), file.display_name.as_str()),
+ ("shop", "sales", "shop.sales")
+ );
+ assert_eq!(service.file(&run.id, 0).await.unwrap(), archive.canonicalize().unwrap());
+}
+
#[tokio::test]
async fn deletion_removes_emptied_run_directories_but_keeps_shared_ones_and_the_root() {
let dir = tempfile::tempdir().unwrap();
diff --git a/crates/dbx-web/src/routes/database_export.rs b/crates/dbx-web/src/routes/database_export.rs
index 7830a1271a..494c2f4e34 100644
--- a/crates/dbx-web/src/routes/database_export.rs
+++ b/crates/dbx-web/src/routes/database_export.rs
@@ -48,6 +48,8 @@ pub async fn start_database_export(
"zip"
} else if req.output_compression == DatabaseExportOutputCompression::Gzip {
"sql.gz"
+ } else if req.output_compression == DatabaseExportOutputCompression::Nb3 {
+ "nb3"
} else {
"sql"
};
@@ -180,6 +182,8 @@ pub async fn database_export_download(
"application/zip"
} else if export_file.format == "sql.gz" {
"application/gzip"
+ } else if export_file.format == "nb3" {
+ "application/x-tar"
} else {
"application/sql; charset=utf-8"
};
diff --git a/docs/content/docs/database-backup.cn.mdx b/docs/content/docs/database-backup.cn.mdx
index b3a23e4196..19890e4013 100644
--- a/docs/content/docs/database-backup.cn.mdx
+++ b/docs/content/docs/database-backup.cn.mdx
@@ -15,7 +15,8 @@ description: 在 DBX 桌面端为 MySQL 和 PostgreSQL 创建可手动运行或
| --- | --- |
| 数据库 | MySQL、PostgreSQL |
| 平台 | DBX 桌面端 |
-| 输出 | 默认模板为每次计划运行创建独立目录;目录内按数据库/Schema 生成 `.sql` 文件,且可通过模板自定义目录与文件名 |
+| 输出 | 默认模板为每次计划运行创建独立目录;目录内按数据库/Schema 生成备份文件,且可通过模板自定义目录与文件名 |
+| 格式 | 普通 SQL(`.sql`)、Gzip 压缩 SQL(`.sql.gz`)或 Navicat 备份归档(`.nb3`) |
| 频率 | 每隔若干小时、每天指定时间、每周指定星期和时间 |
| 内容 | 表结构、表数据、数据库对象、可选 `DROP TABLE IF EXISTS` |
| 表范围 | 全部、按模式包含、按模式排除 |
@@ -130,7 +131,7 @@ MySQL 兼容连接支持从单个 `.sql` 或 `.sql.gz` 备份中恢复指定表
指定表模式仅恢复所选表的结构、索引和数据,不恢复视图、存储过程、函数、触发器或事件。文件中的数据库上下文仍然生效,未显式指定数据库的表使用弹窗所选的目标数据库。现有外键或触发器可能影响恢复;需要完整恢复所有对象时选择**全部内容**。遇到无法确定作用范围的语句时,DBX 会在执行前拒绝选择性恢复。
-生成的 `.sql` 文件可以通过 [SQL 文件执行](/cn/docs/sql-file) 导入。建议定期在隔离环境验证:
+生成的 `.sql`、`.sql.gz` 和 `.nb3` 文件可以通过 [SQL 文件执行](/cn/docs/sql-file) 导入。建议定期在隔离环境验证:
- 文件可以完整读取和执行
- 表结构、索引、对象和数据量符合预期
@@ -139,6 +140,27 @@ MySQL 兼容连接支持从单个 `.sql` 或 `.sql.gz` 备份中恢复指定表
备份成功只代表文件生成完成,不代表已经验证可恢复。
+## DBX 之外创建的备份
+
+备份页面也可以处理非 DBX 创建的 `.sql`、`.sql.gz` 和 `.nb3` 文件,例如 Navicat 备份:
+
+- **从文件恢复**:选择任意备份文件并在 SQL 文件执行中打开,不会写入备份历史。
+- **导入备份**(DBX 桌面端):把一个或多个文件加入**备份历史**并标记为**已导入**,之后可以随时点击**恢复**。Navicat `.nb3` 记录会显示源数据库、Schema 以及备份创建时间。
+
+DBX 从不删除导入的文件。删除导入记录只会将其从历史中移除,保留数量策略也不会作用于导入记录。同一个文件不能重复导入。
+
+## Navicat 备份(.nb3)
+
+将备份格式选择为 **Navicat 备份(.nb3)** 时,DBX 会按 Navicat 用于 MySQL 和 PostgreSQL 的归档结构写出文件:一个包含 `meta.json` 索引、Gzip 压缩的对象元数据(DDL、索引、约束、触发器)以及 Gzip 压缩数据分块的 tar 归档,每个成员都带有 SHA-1 校验值。
+
+DBX 也可以恢复 `.nb3` 文件,包括由 Navicat 创建的备份。在 [SQL 文件执行](/cn/docs/sql-file) 中打开文件,或在备份历史中点击**恢复**。DBX 会把归档转换为恢复脚本,依次:
+
+1. 删除归档中的表、视图和序列(`DROP ... IF EXISTS`;PostgreSQL 使用 `CASCADE`)
+2. 创建序列、存储过程/函数和表,然后以批量 `INSERT` 写入数据
+3. 添加索引、约束、序列值、视图和触发器
+
+<Callout type="warn">恢复 `.nb3` 文件会替换目标库中归档包含的对象,请先恢复到空库或可丢弃的数据库中验证。不支持加密的 Navicat 备份,且归档只能恢复到生成它的同类数据库引擎中。</Callout>
+
## 选择定时备份还是数据库导出
| 功能 | 适合场景 |
diff --git a/docs/content/docs/database-backup.mdx b/docs/content/docs/database-backup.mdx
index c364b28684..a11acd8f40 100644
--- a/docs/content/docs/database-backup.mdx
+++ b/docs/content/docs/database-backup.mdx
@@ -15,7 +15,8 @@ For a backup that should run only once, use **Back up now** in Settings instead
| --- | --- |
| Databases | MySQL and PostgreSQL |
| Platform | DBX Desktop |
-| Output | The default template creates one directory per scheduled run, containing one `.sql` file per database/schema target; directory and file-name templates can be customized |
+| Output | The default template creates one directory per scheduled run, containing one file per database/schema target; directory and file-name templates can be customized |
+| Format | Plain SQL (`.sql`), gzip-compressed SQL (`.sql.gz`), or a Navicat backup archive (`.nb3`) |
| Frequency | Every N hours, daily at a time, or weekly on a weekday and time |
| Contents | Table structure, data, database objects, and optional `DROP TABLE IF EXISTS` |
| Table scope | All, include by pattern, or exclude by pattern |
@@ -130,7 +131,7 @@ For MySQL-compatible connections, restore individual tables from a single `.sql`
Selected-table mode restores table structure, indexes, and data, excluding views, routines, triggers, and events. Database context in the dump still applies; tables without an explicit database use the destination chosen in the dialog. Existing foreign keys or triggers can affect the restore. Choose **All contents** for a complete restore. Statements whose scope cannot be determined cause selective restore to fail before execution.
-Generated `.sql` files can be imported through [SQL File Execution](/en/docs/sql-file). Regularly verify in an isolated environment that:
+Generated `.sql`, `.sql.gz`, and `.nb3` files can be imported through [SQL File Execution](/en/docs/sql-file). Regularly verify in an isolated environment that:
- The complete file can be read and executed
- Schema, indexes, objects, and row counts are correct
@@ -139,6 +140,27 @@ Generated `.sql` files can be imported through [SQL File Execution](/en/docs/sql
A successful backup run means file generation completed; it does not prove restore readiness.
+## Backups Created Outside DBX
+
+The backup page also works with `.sql`, `.sql.gz`, and `.nb3` files that DBX did not create, such as Navicat backups:
+
+- **Restore from file** picks any backup file and opens it in SQL File Execution. Nothing is added to the history.
+- **Import backup** (DBX Desktop) adds one or more files to **Backup history**, labelled **Imported**, so they can be restored later with **Restore**. A Navicat `.nb3` entry shows its source database and schema and the time the backup was taken.
+
+DBX never deletes imported files. Deleting an imported entry only removes it from the history, and retention never applies to imported entries. The same file cannot be imported twice.
+
+## Navicat Backups (.nb3)
+
+Choose **Navicat backup (.nb3)** as the backup format to write the archive layout Navicat uses for MySQL and PostgreSQL: a tar archive with a `meta.json` index, gzipped per-object metadata (DDL, indexes, constraints, triggers), and gzipped row chunks, each protected by a SHA-1 checksum.
+
+DBX also restores `.nb3` files, including archives created by Navicat. Open the file in [SQL File Execution](/en/docs/sql-file) or click **Restore** in backup history. DBX turns the archive into a restore script that:
+
+1. Drops the archived tables, views, and sequences (`DROP ... IF EXISTS`; PostgreSQL uses `CASCADE`)
+2. Creates sequences, routines, and tables, then loads the rows in batched `INSERT` statements
+3. Adds indexes, constraints, sequence values, views, and triggers
+
+<Callout type="warn">Restoring an `.nb3` file replaces the archived objects in the destination. Restore into an empty or disposable database first. Encrypted Navicat backups are not supported, and an archive can only be restored into the same database engine that produced it.</Callout>
+
## Scheduled Backup vs. Database Export
| Feature | Best for |
diff --git a/packages/app-tests/scheduledDatabaseBackup.test.ts b/packages/app-tests/scheduledDatabaseBackup.test.ts
index 7850b916df..adeff6aaa5 100644
--- a/packages/app-tests/scheduledDatabaseBackup.test.ts
+++ b/packages/app-tests/scheduledDatabaseBackup.test.ts
@@ -140,6 +140,14 @@ test("backup file names retain the target suffix without an implicit run suffix"
assert.equal(path, "C:\\backups\\before-migration__app.sql.gz");
});
+test("Navicat backups use the .nb3 suffix and survive schedule normalization", () => {
+ const path = databaseBackupFilePath("/backups", "Nightly", "app", new Date(2026, 6, 16, 2, 3, 4), "12345678-abcd", "nb3", "before-migration");
+
+ assert.equal(path, "/backups/before-migration__app.nb3");
+ assert.equal(normalizeDatabaseBackupSchedule({ ...schedule(), outputCompression: "nb3" })?.outputCompression, "nb3");
+ assert.equal(normalizeDatabaseBackupSchedule({ ...schedule(), outputCompression: "zip" })?.outputCompression, "none");
+});
+
test("scheduled runs render a user-defined relative directory template", () => {
const directory = databaseBackupRunDirectory("C:\\backups", "archives/{schedule}/{date}/{timestamp}-{runId}", "Nightly: prod", new Date(2026, 6, 16, 2, 3, 4), "12345678-abcd");
diff --git a/src-tauri/src/commands/fs_open.rs b/src-tauri/src/commands/fs_open.rs
index 2087caeff5..eb4b38c9c9 100644
--- a/src-tauri/src/commands/fs_open.rs
+++ b/src-tauri/src/commands/fs_open.rs
@@ -106,8 +106,9 @@ fn validate_database_backup_file(raw: &str, allowed_roots: &[PathBuf]) -> Result
}
let file_name = path.file_name().and_then(|name| name.to_str()).unwrap_or_default();
let lower_file_name = file_name.to_ascii_lowercase();
- if !(lower_file_name.ends_with(".sql") || lower_file_name.ends_with(".sql.gz")) {
- return Err(format!("backup file must use the .sql or .sql.gz extension: {expanded}"));
+ if !(lower_file_name.ends_with(".sql") || lower_file_name.ends_with(".sql.gz") || lower_file_name.ends_with(".nb3"))
+ {
+ return Err(format!("backup file must use the .sql, .sql.gz or .nb3 extension: {expanded}"));
}
if file_name.chars().any(char::is_control) {
return Err(format!("backup file name contains control characters: {expanded}"));