feat(export): add all-database export

This commit is contained in:
CSXFanMeng authored and GitHub committed 2026-07-02 21:16:56 +08:00
1 parent f16454a403
commit 82e9df1853
14 files changed
+418 -9

No files matched your search

@@ -9,9 +9,9 @@ import { useConnectionStore } from "@/stores/connectionStore";
import DatabaseIcon from "@/components/icons/DatabaseIcon.vue"; import DatabaseIcon from "@/components/icons/DatabaseIcon.vue";
import * as api from "@/lib/api"; import * as api from "@/lib/api";
import type { ExportProgress } from "@/lib/api"; import type { ExportProgress } from "@/lib/api";
import { isSchemaAware } from "@/lib/databaseCapabilities"; import { isSchemaAware } from "@/lib/databaseFeatureSupport";
import { databaseOptionsForConnection } from "@/composables/useDatabaseOptions"; import { databaseOptionsForConnection } from "@/composables/useDatabaseOptions";
import { generateDatabaseExportId } from "@/lib/databaseExport"; import { buildAllDatabaseExportPlan, generateDatabaseExportId, type AllDatabaseExportPlanItem } from "@/lib/databaseExport";
import { buildSelectedTablesPayload } from "@/lib/databaseExportSelection"; import { buildSelectedTablesPayload } from "@/lib/databaseExportSelection";
import { isTauriRuntime } from "@/lib/tauriRuntime"; import { isTauriRuntime } from "@/lib/tauriRuntime";
import { useToast } from "@/composables/useToast"; import { useToast } from "@/composables/useToast";
@@ -31,12 +31,15 @@ const props = defineProps<{
prefillSchema?: string; prefillSchema?: string;
prefillTable?: string; prefillTable?: string;
prefillTables?: string[]; prefillTables?: string[];
prefillAllDatabases?: boolean;
}>(); }>();
// Connection / Database / Schema selectors // Connection / Database / Schema selectors
const connectionId = ref(""); const connectionId = ref("");
const database = ref(""); const database = ref("");
const databases = ref<string[]>([]); const databases = ref<string[]>([]);
const selectedDatabases = ref<string[]>([]);
const databaseFilter = ref("");
const schema = ref(""); const schema = ref("");
const schemas = ref<string[]>([]); const schemas = ref<string[]>([]);
const loadingMeta = ref(false); const loadingMeta = ref(false);
@@ -66,18 +69,62 @@ const exportError = ref<string | null>(null);
const exportCancelled = ref(false); const exportCancelled = ref(false);
const pendingPrefillTable = ref(""); const pendingPrefillTable = ref("");
const pendingPrefillTables = ref<string[]>([]); const pendingPrefillTables = ref<string[]>([]);
const exportAllDatabases = ref(false);
const batchDatabaseIndex = ref(0);
const batchDatabaseTotal = ref(0);
const activeDatabaseExportId = ref("");
const sqlConnections = computed(() => store.connections.filter((c) => !["redis", "mongodb", "elasticsearch", "qdrant", "milvus", "weaviate", "chromadb", "etcd", "zookeeper", "mq", "nacos"].includes(c.db_type))); const sqlConnections = computed(() => store.connections.filter((c) => !["redis", "mongodb", "elasticsearch", "qdrant", "milvus", "weaviate", "chromadb", "etcd", "zookeeper", "mq", "nacos"].includes(c.db_type)));
const canExport = computed(() => connectionId.value && database.value && schema.value && !loadingTables.value && !tableError.value && (tables.value.length === 0 || selectedTables.value.length > 0) && (includeStructure.value || includeData.value || includeObjects.value) && !isExporting.value); const canExport = computed(() => {
const hasContent = includeStructure.value || includeData.value || includeObjects.value;
if (!connectionId.value || !hasContent || isExporting.value) return false;
if (exportAllDatabases.value) return selectedDatabases.value.length > 0 && !loadingMeta.value;
return database.value && schema.value && !loadingTables.value && !tableError.value && (tables.value.length === 0 || selectedTables.value.length > 0);
});
const selectedTableSet = computed(() => new Set(selectedTables.value)); const selectedTableSet = computed(() => new Set(selectedTables.value));
const selectedDatabaseSet = computed(() => new Set(selectedDatabases.value));
const filteredDatabases = computed(() => {
const q = databaseFilter.value.trim().toLowerCase();
if (!q) return databases.value;
return databases.value.filter((name) => name.toLowerCase().includes(q));
});
function connectionIconType(connId: string) { function connectionIconType(connId: string) {
const config = store.getConfig(connId); const config = store.getConfig(connId);
return config?.driver_profile || config?.db_type || "mysql"; return config?.driver_profile || config?.db_type || "mysql";
} }
function sanitizeFileName(value: string): string {
return (value || "database").replace(/[\\/:*?"<>|]+/g, "_").trim() || "database";
}
function joinExportPath(directory: string, fileName: string): string {
const separator = directory.includes("\\") ? "\\" : "/";
return `${directory.replace(/[\\/]+$/, "")}${separator}${fileName}`;
}
function currentRowsExported(): number {
const progress: ExportProgress | null = exportProgress.value;
return progress?.rowsExported ?? 0;
}
async function runDatabaseExportUntilTerminal(request: api.DatabaseExportRequest, onProgress: (progress: ExportProgress) => void): Promise<void> {
await new Promise<void>((resolve, reject) => {
api
.exportDatabaseSql(request, (progress) => {
onProgress(progress);
if (progress.status === "Done" || progress.status === "Cancelled") {
resolve();
} else if (progress.status === "Error") {
reject(new Error(progress.error || "Export failed"));
}
})
.catch(reject);
});
}
async function loadDatabases(connId: string) { async function loadDatabases(connId: string) {
if (!connId) return; if (!connId) return;
loadingMeta.value = true; loadingMeta.value = true;
@@ -90,6 +137,7 @@ async function loadDatabases(connId: string) {
); );
databases.value = names; databases.value = names;
database.value = names.length === 1 ? names[0] : ""; database.value = names.length === 1 ? names[0] : "";
selectedDatabases.value = exportAllDatabases.value ? [...names] : [];
schemas.value = []; schemas.value = [];
schema.value = ""; schema.value = "";
tables.value = []; tables.value = [];
@@ -156,8 +204,45 @@ function clearSelectedTables() {
selectedTables.value = selectedTables.value.filter((name) => !removing.has(name)); selectedTables.value = selectedTables.value.filter((name) => !removing.has(name));
} }
function toggleDatabase(db: string) {
const selected = new Set(selectedDatabases.value);
if (selected.has(db)) {
selected.delete(db);
} else {
selected.add(db);
}
selectedDatabases.value = databases.value.filter((name) => selected.has(name));
}
function selectAllDatabases() {
const selected = new Set(selectedDatabases.value);
for (const name of filteredDatabases.value) selected.add(name);
selectedDatabases.value = databases.value.filter((name) => selected.has(name));
}
function clearSelectedDatabases() {
const removing = new Set(filteredDatabases.value);
selectedDatabases.value = selectedDatabases.value.filter((name) => !removing.has(name));
}
async function buildExportPlanForDatabases(dbs: string[]): Promise<AllDatabaseExportPlanItem[]> {
const config = store.getConfig(connectionId.value);
const schemaAware = isSchemaAware(config?.db_type);
const schemasByDatabase: Record<string, string[]> = {};
if (schemaAware) {
for (const db of dbs) {
schemasByDatabase[db] = await api.listSchemas(connectionId.value, db);
}
}
return buildAllDatabaseExportPlan({ databases: dbs, schemaAware, schemasByDatabase });
}
async function startExport() { async function startExport() {
if (!canExport.value) return; if (!canExport.value) return;
if (exportAllDatabases.value) {
await startAllDatabasesExport();
return;
}
isExporting.value = true; isExporting.value = true;
exportDone.value = false; exportDone.value = false;
exportError.value = null; exportError.value = null;
@@ -171,7 +256,7 @@ async function startExport() {
if (isTauriRuntime()) { if (isTauriRuntime()) {
try { try {
const { save } = await import("@tauri-apps/plugin-dialog"); const { save } = await import("@tauri-apps/plugin-dialog");
const safeName = (database.value || "database").replace(/[\\/:*?"<>|]+/g, "_").trim(); const safeName = sanitizeFileName(database.value || "database");
const path = await save({ const path = await save({
defaultPath: `${safeName}.sql`, defaultPath: `${safeName}.sql`,
filters: [{ name: "SQL", extensions: ["sql"] }], filters: [{ name: "SQL", extensions: ["sql"] }],
@@ -241,9 +326,127 @@ async function startExport() {
} }
} }
async function startAllDatabasesExport() {
if (!canExport.value) return;
let directoryPath = "";
if (isTauriRuntime()) {
try {
const { open: openDialog } = await import("@tauri-apps/plugin-dialog");
const path = await openDialog({
directory: true,
multiple: false,
title: t("databaseExport.selectExportDirectory"),
});
if (!path || Array.isArray(path)) return;
directoryPath = path;
} catch (e: any) {
toast(e?.message || String(e), 5000);
return;
}
}
isExporting.value = true;
exportDone.value = false;
exportError.value = null;
exportCancelled.value = false;
exportProgress.value = null;
batchDatabaseIndex.value = 0;
const dbs = [...selectedDatabases.value];
const batchId = generateDatabaseExportId();
exportId.value = batchId;
addDatabaseExportTask(batchId, t("databaseExport.allDatabasesTask", { count: dbs.length }), directoryPath);
let exportPlan: AllDatabaseExportPlanItem[] = [];
try {
exportPlan = await buildExportPlanForDatabases(dbs);
batchDatabaseTotal.value = exportPlan.length;
for (let index = 0; index < exportPlan.length; index += 1) {
if (exportCancelled.value) break;
const item = exportPlan[index]!;
batchDatabaseIndex.value = index + 1;
const currentExportId = `${batchId}-${index + 1}`;
activeDatabaseExportId.value = currentExportId;
const filePath = isTauriRuntime() ? joinExportPath(directoryPath, `${sanitizeFileName(item.fileStem)}.sql`) : `__web_export_${currentExportId}.sql`;
const request: api.DatabaseExportRequest = {
exportId: currentExportId,
connectionId: connectionId.value,
database: item.database,
schema: item.schema,
filePath,
includeStructure: includeStructure.value,
includeData: includeData.value,
includeObjects: includeObjects.value,
dropTableIfExists: dropTableIfExists.value,
batchSize: 1000,
};
await runDatabaseExportUntilTerminal(request, (progress) => {
exportProgress.value = { ...progress, exportId: batchId, currentObject: `${item.displayName}: ${progress.currentObject || item.displayName}` };
updateDatabaseExportTask(batchId, {
...progress,
exportId: batchId,
currentObject: item.displayName,
objectIndex: index,
totalObjects: exportPlan.length,
});
if (progress.status === "Error") {
exportError.value = progress.error;
isExporting.value = false;
} else if (progress.status === "Cancelled") {
exportCancelled.value = true;
isExporting.value = false;
}
});
if (exportError.value || exportCancelled.value) break;
activeDatabaseExportId.value = "";
}
if (!exportError.value && !exportCancelled.value) {
exportDone.value = true;
isExporting.value = false;
updateDatabaseExportTask(batchId, {
exportId: batchId,
currentObject: t("databaseExport.allDatabasesTask", { count: dbs.length }),
objectIndex: exportPlan.length,
totalObjects: exportPlan.length,
rowsExported: currentRowsExported(),
totalRows: null,
status: "Done",
error: null,
});
toast(t("databaseExport.exportAllSuccess", { count: dbs.length }), 3000);
}
} catch (e: any) {
exportError.value = e?.message || String(e);
updateDatabaseExportTask(batchId, {
exportId: batchId,
currentObject: t("databaseExport.allDatabasesTask", { count: dbs.length }),
objectIndex: Math.max(0, batchDatabaseIndex.value - 1),
totalObjects: batchDatabaseTotal.value || dbs.length,
rowsExported: currentRowsExported(),
totalRows: null,
status: "Error",
error: exportError.value,
});
isExporting.value = false;
}
}
async function cancelExport() { async function cancelExport() {
if (exportId.value) { if (exportId.value) {
await api.cancelDatabaseExport(exportId.value); if (exportAllDatabases.value) {
exportCancelled.value = true;
isExporting.value = false;
if (activeDatabaseExportId.value) {
await api.cancelDatabaseExport(activeDatabaseExportId.value);
}
} else {
await api.cancelDatabaseExport(exportId.value);
}
} }
} }
@@ -258,6 +461,9 @@ function resetState() {
tableError.value = null; tableError.value = null;
pendingPrefillTable.value = ""; pendingPrefillTable.value = "";
pendingPrefillTables.value = []; pendingPrefillTables.value = [];
exportAllDatabases.value = false;
selectedDatabases.value = [];
databaseFilter.value = "";
includeStructure.value = true; includeStructure.value = true;
includeData.value = true; includeData.value = true;
includeObjects.value = true; includeObjects.value = true;
@@ -268,6 +474,9 @@ function resetState() {
exportError.value = null; exportError.value = null;
exportCancelled.value = false; exportCancelled.value = false;
exportId.value = ""; exportId.value = "";
batchDatabaseIndex.value = 0;
batchDatabaseTotal.value = 0;
activeDatabaseExportId.value = "";
} }
const progressPercent = computed(() => { const progressPercent = computed(() => {
@@ -285,6 +494,7 @@ watch(connectionId, (id) => {
} }
database.value = ""; database.value = "";
databases.value = []; databases.value = [];
selectedDatabases.value = [];
schemas.value = []; schemas.value = [];
schema.value = ""; schema.value = "";
tables.value = []; tables.value = [];
@@ -294,6 +504,7 @@ watch(connectionId, (id) => {
}); });
watch(database, (db) => { watch(database, (db) => {
if (exportAllDatabases.value) return;
schema.value = ""; schema.value = "";
schemas.value = []; schemas.value = [];
tables.value = []; tables.value = [];
@@ -303,6 +514,7 @@ watch(database, (db) => {
}); });
watch(schema, (value) => { watch(schema, (value) => {
if (exportAllDatabases.value) return;
tables.value = []; tables.value = [];
selectedTables.value = []; selectedTables.value = [];
tableError.value = null; tableError.value = null;
@@ -318,6 +530,7 @@ watch(
async (val) => { async (val) => {
if (val) { if (val) {
resetState(); resetState();
exportAllDatabases.value = props.prefillAllDatabases ?? false;
pendingPrefillTable.value = props.prefillTable ?? ""; pendingPrefillTable.value = props.prefillTable ?? "";
pendingPrefillTables.value = props.prefillTables ?? []; pendingPrefillTables.value = props.prefillTables ?? [];
if (props.prefillConnectionId) { if (props.prefillConnectionId) {
@@ -368,7 +581,37 @@ watch(
</Select> </Select>
</div> </div>
<div v-if="databases.length" class="space-y-1.5"> <div v-if="exportAllDatabases && databases.length" class="space-y-2">
<div class="flex items-center justify-between gap-2">
<Label class="text-xs">{{ t("databaseExport.databaseSelection") }}</Label>
<div class="text-[11px] text-muted-foreground">
{{ t("databaseExport.selectedDatabases", { selected: selectedDatabases.length, total: databases.length }) }}
</div>
</div>
<div class="space-y-2 rounded border border-border/60 p-2">
<div class="relative">
<Search class="absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground" />
<Input v-model="databaseFilter" class="h-7 pl-7 text-xs" :placeholder="t('databaseExport.filterDatabases')" />
</div>
<div class="flex items-center gap-2">
<Button variant="outline" size="sm" class="h-7 px-2 text-xs" @click="selectAllDatabases">
{{ t("databaseExport.selectAllDatabases") }}
</Button>
<Button variant="outline" size="sm" class="h-7 px-2 text-xs" @click="clearSelectedDatabases">
{{ t("databaseExport.clearDatabases") }}
</Button>
</div>
<div class="max-h-44 overflow-auto space-y-1 pr-1">
<button v-for="db in filteredDatabases" :key="db" type="button" class="flex w-full min-w-0 items-center gap-2 rounded px-1.5 py-1 text-left text-xs hover:bg-muted" @click="toggleDatabase(db)">
<CheckSquare v-if="selectedDatabaseSet.has(db)" class="w-3.5 h-3.5 text-primary shrink-0" />
<Square v-else class="w-3.5 h-3.5 text-muted-foreground/40 shrink-0" />
<span class="truncate">{{ db }}</span>
</button>
</div>
</div>
</div>
<div v-else-if="databases.length" class="space-y-1.5">
<Label class="text-xs">{{ t("transfer.sourceDatabase") }}</Label> <Label class="text-xs">{{ t("transfer.sourceDatabase") }}</Label>
<Select :model-value="database" @update:model-value="(v: any) => (database = String(v))"> <Select :model-value="database" @update:model-value="(v: any) => (database = String(v))">
<SelectTrigger class="h-8 text-xs"> <SelectTrigger class="h-8 text-xs">
@@ -380,7 +623,7 @@ watch(
</Select> </Select>
</div> </div>
<div v-if="schemas.length" class="space-y-1.5"> <div v-if="!exportAllDatabases && schemas.length" class="space-y-1.5">
<Label class="text-xs">{{ t("diff.selectSchema") }}</Label> <Label class="text-xs">{{ t("diff.selectSchema") }}</Label>
<Select :model-value="schema" @update:model-value="(v: any) => (schema = String(v))"> <Select :model-value="schema" @update:model-value="(v: any) => (schema = String(v))">
<SelectTrigger class="h-8 text-xs"> <SelectTrigger class="h-8 text-xs">
@@ -392,7 +635,7 @@ watch(
</Select> </Select>
</div> </div>
<div v-if="schema" class="space-y-2"> <div v-if="!exportAllDatabases && schema" class="space-y-2">
<div class="flex items-center justify-between gap-2"> <div class="flex items-center justify-between gap-2">
<Label class="text-xs">{{ t("databaseExport.tableSelection") }}</Label> <Label class="text-xs">{{ t("databaseExport.tableSelection") }}</Label>
<div v-if="tables.length" class="text-[11px] text-muted-foreground"> <div v-if="tables.length" class="text-[11px] text-muted-foreground">
@@ -462,6 +705,9 @@ watch(
<!-- Progress View --> <!-- Progress View -->
<div v-if="isExporting || exportDone || exportError || exportCancelled" class="py-3 space-y-3"> <div v-if="isExporting || exportDone || exportError || exportCancelled" class="py-3 space-y-3">
<div v-if="exportAllDatabases && batchDatabaseTotal" class="text-xs text-muted-foreground">
{{ t("databaseExport.currentDatabase", { current: batchDatabaseIndex, total: batchDatabaseTotal }) }}
</div>
<div v-if="exportProgress" class="space-y-2"> <div v-if="exportProgress" class="space-y-2">
<div class="text-xs text-muted-foreground"> <div class="text-xs text-muted-foreground">
{{ {{
@@ -502,7 +748,7 @@ watch(
</Button> </Button>
<Button size="sm" :disabled="!canExport" @click="startExport"> <Button size="sm" :disabled="!canExport" @click="startExport">
<Download class="w-3.5 h-3.5 mr-1.5" /> <Download class="w-3.5 h-3.5 mr-1.5" />
{{ t("databaseExport.export") }} {{ exportAllDatabases ? t("databaseExport.exportAllDatabases") : t("databaseExport.export") }}
</Button> </Button>
</template> </template>
<template v-else-if="isExporting"> <template v-else-if="isExporting">
@@ -183,6 +183,7 @@ watch(
:prefill-schema="dialogs.databaseExportPrefillSchema.value" :prefill-schema="dialogs.databaseExportPrefillSchema.value"
:prefill-table="dialogs.databaseExportPrefillTable.value" :prefill-table="dialogs.databaseExportPrefillTable.value"
:prefill-tables="dialogs.databaseExportPrefillTables.value" :prefill-tables="dialogs.databaseExportPrefillTables.value"
:prefill-all-databases="dialogs.databaseExportAllDatabases.value"
/> />
<ConfigPassphraseDialog <ConfigPassphraseDialog
v-if="dialogs.showConfigPassphraseDialog.value" v-if="dialogs.showConfigPassphraseDialog.value"
@@ -3409,6 +3409,16 @@ function openDatabaseExport() {
}; };
} }
function openAllDatabasesExport() {
const node = props.node;
if (node.type !== "connection" || !node.connectionId) return;
connectionStore.databaseExportSource = {
connectionId: node.connectionId,
database: "",
allDatabases: true,
};
}
function openTableImport() { function openTableImport() {
const node = props.node; const node = props.node;
if (node.type !== "table" || !node.connectionId || !node.database) return; if (node.type !== "table" || !node.connectionId || !node.database) return;
@@ -3449,6 +3459,11 @@ const canPin = computed(() => canTreeNodePin(props.node.type));
const canOpenSqlFileExecution = computed(() => { const canOpenSqlFileExecution = computed(() => {
return supportsSqlFileExecution(rawDatabaseType()); return supportsSqlFileExecution(rawDatabaseType());
}); });
const canExportAllDatabases = computed(() => {
if (props.node.type !== "connection" || !props.node.connectionId) return false;
const dbType = connectionStore.getConfig(props.node.connectionId)?.db_type;
return !["redis", "mongodb", "elasticsearch", "qdrant", "milvus", "weaviate", "chromadb", "etcd", "zookeeper", "mq", "nacos"].includes(dbType || "");
});
const canOpenDiagram = computed(() => { const canOpenDiagram = computed(() => {
return !!props.node.database && supportsSchemaDiagram(currentDatabaseType()); return !!props.node.database && supportsSchemaDiagram(currentDatabaseType());
}); });
@@ -3957,6 +3972,9 @@ function treeItemMenuItems(): ContextMenuItem[] {
if (canOpenSqlFileExecution.value) { if (canOpenSqlFileExecution.value) {
items.push({ label: t("sqlFile.title"), action: openSqlFileExecution, icon: FileCode }); items.push({ label: t("sqlFile.title"), action: openSqlFileExecution, icon: FileCode });
} }
if (canExportAllDatabases.value) {
items.push({ label: t("contextMenu.exportAllDatabases"), action: openAllDatabasesExport, icon: Upload });
}
if (canCreateDatabase.value) { if (canCreateDatabase.value) {
items.push({ items.push({
label: isDuckDbConnection.value ? t("contextMenu.createDuckDbFile") : t("contextMenu.createDatabase"), label: isDuckDbConnection.value ? t("contextMenu.createDuckDbFile") : t("contextMenu.createDatabase"),
@@ -57,6 +57,7 @@ const databaseExportPrefillDatabase = ref("");
const databaseExportPrefillSchema = ref(""); const databaseExportPrefillSchema = ref("");
const databaseExportPrefillTable = ref(""); const databaseExportPrefillTable = ref("");
const databaseExportPrefillTables = ref<string[]>([]); const databaseExportPrefillTables = ref<string[]>([]);
const databaseExportAllDatabases = ref(false);
let watchersRegistered = false; let watchersRegistered = false;
@@ -199,6 +200,7 @@ export function useDialogSources() {
databaseExportPrefillSchema.value = v.schema ?? ""; databaseExportPrefillSchema.value = v.schema ?? "";
databaseExportPrefillTable.value = v.tableName ?? ""; databaseExportPrefillTable.value = v.tableName ?? "";
databaseExportPrefillTables.value = v.tableNames ?? []; databaseExportPrefillTables.value = v.tableNames ?? [];
databaseExportAllDatabases.value = v.allDatabases ?? false;
showDatabaseExportDialog.value = true; showDatabaseExportDialog.value = true;
connectionStore.databaseExportSource = null; connectionStore.databaseExportSource = null;
} }
@@ -328,6 +330,7 @@ export function useDialogSources() {
databaseExportPrefillSchema, databaseExportPrefillSchema,
databaseExportPrefillTable, databaseExportPrefillTable,
databaseExportPrefillTables, databaseExportPrefillTables,
databaseExportAllDatabases,
onExportClick, onExportClick,
onExportConfirm, onExportConfirm,
onImportClick, onImportClick,
+11
View File
@@ -1269,6 +1269,7 @@ export default {
setDefaultDatabase: "Set as Default Database", setDefaultDatabase: "Set as Default Database",
clearDefaultDatabase: "Clear Default Database", clearDefaultDatabase: "Clear Default Database",
exportDatabase: "Export Database", exportDatabase: "Export Database",
exportAllDatabases: "Export All Databases",
exportDatabaseSuccess: "Exported {count} tables, up to {limit} rows each", exportDatabaseSuccess: "Exported {count} tables, up to {limit} rows each",
exportDatabaseFailed: "Failed to export database: {message}", exportDatabaseFailed: "Failed to export database: {message}",
backupSqliteDatabase: "Backup SQLite Database", backupSqliteDatabase: "Backup SQLite Database",
@@ -3053,6 +3054,11 @@ export default {
dropTableIfExists: "Add DROP TABLE IF EXISTS before DDL", dropTableIfExists: "Add DROP TABLE IF EXISTS before DDL",
includeData: "Table data (INSERT)", includeData: "Table data (INSERT)",
includeObjects: "Views / Procedures / Functions / Sequences", includeObjects: "Views / Procedures / Functions / Sequences",
databaseSelection: "Databases",
selectedDatabases: "{selected}/{total} selected",
selectAllDatabases: "Select all",
filterDatabases: "Search databases...",
clearDatabases: "Clear",
tableSelection: "Tables", tableSelection: "Tables",
selectedTables: "{selected}/{total} selected", selectedTables: "{selected}/{total} selected",
selectAllTables: "Select all", selectAllTables: "Select all",
@@ -3062,10 +3068,15 @@ export default {
tableLoadError: "Failed to load tables: {error}", tableLoadError: "Failed to load tables: {error}",
noTables: "No tables found", noTables: "No tables found",
export: "Export", export: "Export",
exportAllDatabases: "Export All Databases",
exporting: "Exporting...", exporting: "Exporting...",
selectExportDirectory: "Select export directory",
currentDatabase: "Database {current}/{total}",
currentTable: "Current: {table} ({current}/{total})", currentTable: "Current: {table} ({current}/{total})",
rowsExported: "{count} rows exported", rowsExported: "{count} rows exported",
exportSuccess: "Database exported successfully", exportSuccess: "Database exported successfully",
exportAllSuccess: "{count} databases exported successfully",
allDatabasesTask: "All databases ({count})",
exportError: "Export failed: {error}", exportError: "Export failed: {error}",
exportCancelled: "Export cancelled", exportCancelled: "Export cancelled",
runInBackground: "Run in background", runInBackground: "Run in background",
+11
View File
@@ -1272,6 +1272,7 @@ export default withEnglishFallback({
setDefaultDatabase: "Establecer como base de datos predeterminada", setDefaultDatabase: "Establecer como base de datos predeterminada",
clearDefaultDatabase: "Limpiar base de datos predeterminada", clearDefaultDatabase: "Limpiar base de datos predeterminada",
exportDatabase: "Exportar base de datos", exportDatabase: "Exportar base de datos",
exportAllDatabases: "Exportar todas las bases de datos",
exportDatabaseSuccess: "Se exportaron {count} tablas, hasta {limit} filas cada una", exportDatabaseSuccess: "Se exportaron {count} tablas, hasta {limit} filas cada una",
exportDatabaseFailed: "Error al exportar la base de datos: {message}", exportDatabaseFailed: "Error al exportar la base de datos: {message}",
backupSqliteDatabase: "Backup SQLite Database", backupSqliteDatabase: "Backup SQLite Database",
@@ -3056,6 +3057,11 @@ export default withEnglishFallback({
dropTableIfExists: "Agregar DROP TABLE IF EXISTS antes del DDL", dropTableIfExists: "Agregar DROP TABLE IF EXISTS antes del DDL",
includeData: "Datos de tablas (INSERT)", includeData: "Datos de tablas (INSERT)",
includeObjects: "Vistas / Procedimientos / Funciones / Secuencias", includeObjects: "Vistas / Procedimientos / Funciones / Secuencias",
databaseSelection: "Bases de datos",
selectedDatabases: "{selected}/{total} seleccionadas",
selectAllDatabases: "Seleccionar todo",
filterDatabases: "Buscar bases de datos...",
clearDatabases: "Limpiar",
tableSelection: "Tablas", tableSelection: "Tablas",
selectedTables: "{selected}/{total} seleccionadas", selectedTables: "{selected}/{total} seleccionadas",
selectAllTables: "Seleccionar todo", selectAllTables: "Seleccionar todo",
@@ -3064,10 +3070,15 @@ export default withEnglishFallback({
tableLoadError: "Error al cargar tablas: {error}", tableLoadError: "Error al cargar tablas: {error}",
noTables: "No se encontraron tablas", noTables: "No se encontraron tablas",
export: "Exportar", export: "Exportar",
exportAllDatabases: "Exportar todas las bases de datos",
exporting: "Exportando...", exporting: "Exportando...",
selectExportDirectory: "Seleccionar directorio de exportación",
currentDatabase: "Base de datos {current}/{total}",
currentTable: "Actual: {table} ({current}/{total})", currentTable: "Actual: {table} ({current}/{total})",
rowsExported: "{count} filas exportadas", rowsExported: "{count} filas exportadas",
exportSuccess: "Base de datos exportada exitosamente", exportSuccess: "Base de datos exportada exitosamente",
exportAllSuccess: "{count} bases de datos exportadas exitosamente",
allDatabasesTask: "Todas las bases de datos ({count})",
exportError: "Error al exportar: {error}", exportError: "Error al exportar: {error}",
exportCancelled: "Exportación cancelada", exportCancelled: "Exportación cancelada",
filterTables: "Buscar tablas...", filterTables: "Buscar tablas...",
+11
View File
@@ -1270,6 +1270,7 @@ export default withEnglishFallback({
setDefaultDatabase: "Imposta come Database Predefinito", setDefaultDatabase: "Imposta come Database Predefinito",
clearDefaultDatabase: "Cancella Database Predefinito", clearDefaultDatabase: "Cancella Database Predefinito",
exportDatabase: "Esporta Database", exportDatabase: "Esporta Database",
exportAllDatabases: "Esporta tutti i database",
exportDatabaseSuccess: "Esportate {count} tabelle, fino a {limit} righe ciascuna", exportDatabaseSuccess: "Esportate {count} tabelle, fino a {limit} righe ciascuna",
exportDatabaseFailed: "Impossibile esportare il database: {message}", exportDatabaseFailed: "Impossibile esportare il database: {message}",
backupSqliteDatabase: "Backup SQLite Database", backupSqliteDatabase: "Backup SQLite Database",
@@ -3054,6 +3055,11 @@ export default withEnglishFallback({
dropTableIfExists: "Aggiungi DROP TABLE IF EXISTS prima del DDL", dropTableIfExists: "Aggiungi DROP TABLE IF EXISTS prima del DDL",
includeData: "Dati tabella (INSERT)", includeData: "Dati tabella (INSERT)",
includeObjects: "Viste / Procedure / Funzioni / Sequenze", includeObjects: "Viste / Procedure / Funzioni / Sequenze",
databaseSelection: "Database",
selectedDatabases: "{selected}/{total} selezionati",
selectAllDatabases: "Seleziona tutti",
filterDatabases: "Cerca database...",
clearDatabases: "Cancella",
tableSelection: "Tabelle", tableSelection: "Tabelle",
selectedTables: "{selected}/{total} selezionate", selectedTables: "{selected}/{total} selezionate",
selectAllTables: "Seleziona tutte", selectAllTables: "Seleziona tutte",
@@ -3063,10 +3069,15 @@ export default withEnglishFallback({
tableLoadError: "Caricamento tabelle non riuscito: {error}", tableLoadError: "Caricamento tabelle non riuscito: {error}",
noTables: "Nessuna tabella trovata", noTables: "Nessuna tabella trovata",
export: "Esporta", export: "Esporta",
exportAllDatabases: "Esporta tutti i database",
exporting: "Esportazione in corso...", exporting: "Esportazione in corso...",
selectExportDirectory: "Seleziona directory di esportazione",
currentDatabase: "Database {current}/{total}",
currentTable: "Corrente: {table} ({current}/{total})", currentTable: "Corrente: {table} ({current}/{total})",
rowsExported: "{count} righe esportate", rowsExported: "{count} righe esportate",
exportSuccess: "Database esportato con successo", exportSuccess: "Database esportato con successo",
exportAllSuccess: "{count} database esportati con successo",
allDatabasesTask: "Tutti i database ({count})",
exportError: "Esportazione non riuscita: {error}", exportError: "Esportazione non riuscita: {error}",
exportCancelled: "Esportazione annullata", exportCancelled: "Esportazione annullata",
runInBackground: "Esegui in background", runInBackground: "Esegui in background",
+11
View File
@@ -1268,6 +1268,7 @@ export default withEnglishFallback({
setDefaultDatabase: "デフォルトデータベースに設定", setDefaultDatabase: "デフォルトデータベースに設定",
clearDefaultDatabase: "デフォルトデータベースをクリア", clearDefaultDatabase: "デフォルトデータベースをクリア",
exportDatabase: "データベースをエクスポート", exportDatabase: "データベースをエクスポート",
exportAllDatabases: "すべてのデータベースをエクスポート",
exportDatabaseSuccess: "{count}テーブルをエクスポートしました(各{limit}行まで)", exportDatabaseSuccess: "{count}テーブルをエクスポートしました(各{limit}行まで)",
exportDatabaseFailed: "データベースのエクスポートに失敗しました: {message}", exportDatabaseFailed: "データベースのエクスポートに失敗しました: {message}",
backupSqliteDatabase: "SQLiteデータベースをバックアップ", backupSqliteDatabase: "SQLiteデータベースをバックアップ",
@@ -3055,6 +3056,11 @@ export default withEnglishFallback({
dropTableIfExists: "DDLの前にDROP TABLE IF EXISTSを追加", dropTableIfExists: "DDLの前にDROP TABLE IF EXISTSを追加",
includeData: "テーブルデータ (INSERT)", includeData: "テーブルデータ (INSERT)",
includeObjects: "ビュー / プロシージャ / 関数 / シーケンス", includeObjects: "ビュー / プロシージャ / 関数 / シーケンス",
databaseSelection: "データベース",
selectedDatabases: "{selected}/{total}件選択中",
selectAllDatabases: "すべて選択",
filterDatabases: "データベースを検索...",
clearDatabases: "クリア",
tableSelection: "テーブル", tableSelection: "テーブル",
selectedTables: "{selected}/{total}件選択中", selectedTables: "{selected}/{total}件選択中",
selectAllTables: "すべて選択", selectAllTables: "すべて選択",
@@ -3064,10 +3070,15 @@ export default withEnglishFallback({
tableLoadError: "テーブルの読み込みに失敗しました: {error}", tableLoadError: "テーブルの読み込みに失敗しました: {error}",
noTables: "テーブルが見つかりません", noTables: "テーブルが見つかりません",
export: "エクスポート", export: "エクスポート",
exportAllDatabases: "すべてのデータベースをエクスポート",
exporting: "エクスポート中...", exporting: "エクスポート中...",
selectExportDirectory: "エクスポート先ディレクトリを選択",
currentDatabase: "データベース {current}/{total}",
currentTable: "現在: {table} ({current}/{total})", currentTable: "現在: {table} ({current}/{total})",
rowsExported: "{count}行をエクスポートしました", rowsExported: "{count}行をエクスポートしました",
exportSuccess: "データベースを正常にエクスポートしました", exportSuccess: "データベースを正常にエクスポートしました",
exportAllSuccess: "{count}個のデータベースを正常にエクスポートしました",
allDatabasesTask: "すべてのデータベース ({count})",
exportError: "エクスポートに失敗しました: {error}", exportError: "エクスポートに失敗しました: {error}",
exportCancelled: "エクスポートがキャンセルされました", exportCancelled: "エクスポートがキャンセルされました",
}, },
+11
View File
@@ -1271,6 +1271,7 @@ export default withEnglishFallback({
setDefaultDatabase: "Definir como Banco de Dados Padrão", setDefaultDatabase: "Definir como Banco de Dados Padrão",
clearDefaultDatabase: "Limpar Banco de Dados Padrão", clearDefaultDatabase: "Limpar Banco de Dados Padrão",
exportDatabase: "Exportar Banco de Dados", exportDatabase: "Exportar Banco de Dados",
exportAllDatabases: "Exportar todos os bancos de dados",
exportDatabaseSuccess: "{count} tabelas exportadas, até {limit} linhas cada", exportDatabaseSuccess: "{count} tabelas exportadas, até {limit} linhas cada",
exportDatabaseFailed: "Falha ao exportar banco de dados: {message}", exportDatabaseFailed: "Falha ao exportar banco de dados: {message}",
backupSqliteDatabase: "Backup SQLite Database", backupSqliteDatabase: "Backup SQLite Database",
@@ -3055,6 +3056,11 @@ export default withEnglishFallback({
dropTableIfExists: "Adicionar DROP TABLE IF EXISTS antes do DDL", dropTableIfExists: "Adicionar DROP TABLE IF EXISTS antes do DDL",
includeData: "Dados da tabela (INSERT)", includeData: "Dados da tabela (INSERT)",
includeObjects: "Views / Procedures / Funções / Sequências", includeObjects: "Views / Procedures / Funções / Sequências",
databaseSelection: "Bancos de dados",
selectedDatabases: "{selected}/{total} selecionados",
selectAllDatabases: "Selecionar todos",
filterDatabases: "Pesquisar bancos de dados...",
clearDatabases: "Limpar",
runInBackground: "Executar em segundo plano", runInBackground: "Executar em segundo plano",
tableSelection: "Tabelas", tableSelection: "Tabelas",
selectedTables: "{selected}/{total} selecionadas", selectedTables: "{selected}/{total} selecionadas",
@@ -3065,10 +3071,15 @@ export default withEnglishFallback({
tableLoadError: "Falha ao carregar tabelas: {error}", tableLoadError: "Falha ao carregar tabelas: {error}",
noTables: "Nenhuma tabela encontrada", noTables: "Nenhuma tabela encontrada",
export: "Exportar", export: "Exportar",
exportAllDatabases: "Exportar todos os bancos de dados",
exporting: "Exportando...", exporting: "Exportando...",
selectExportDirectory: "Selecionar diretório de exportação",
currentDatabase: "Banco de dados {current}/{total}",
currentTable: "Atual: {table} ({current}/{total})", currentTable: "Atual: {table} ({current}/{total})",
rowsExported: "{count} linhas exportadas", rowsExported: "{count} linhas exportadas",
exportSuccess: "Banco de dados exportado com sucesso", exportSuccess: "Banco de dados exportado com sucesso",
exportAllSuccess: "{count} bancos de dados exportados com sucesso",
allDatabasesTask: "Todos os bancos de dados ({count})",
exportError: "Falha na exportação: {error}", exportError: "Falha na exportação: {error}",
exportCancelled: "Exportação cancelada", exportCancelled: "Exportação cancelada",
}, },
+11
View File
@@ -1271,6 +1271,7 @@ export default withEnglishFallback({
setDefaultDatabase: "设为默认数据库", setDefaultDatabase: "设为默认数据库",
clearDefaultDatabase: "取消默认数据库", clearDefaultDatabase: "取消默认数据库",
exportDatabase: "导出数据库", exportDatabase: "导出数据库",
exportAllDatabases: "导出全部数据库",
exportDatabaseSuccess: "已导出 {count} 张表,每表最多 {limit} 行", exportDatabaseSuccess: "已导出 {count} 张表,每表最多 {limit} 行",
exportDatabaseFailed: "导出数据库失败:{message}", exportDatabaseFailed: "导出数据库失败:{message}",
backupSqliteDatabase: "备份 SQLite 数据库", backupSqliteDatabase: "备份 SQLite 数据库",
@@ -3055,6 +3056,11 @@ export default withEnglishFallback({
dropTableIfExists: "导出前添加 DROP TABLE IF EXISTS", dropTableIfExists: "导出前添加 DROP TABLE IF EXISTS",
includeData: "表数据 (INSERT)", includeData: "表数据 (INSERT)",
includeObjects: "视图 / 存储过程 / 函数 / 序列", includeObjects: "视图 / 存储过程 / 函数 / 序列",
databaseSelection: "选择数据库",
selectedDatabases: "已选择 {selected}/{total}",
selectAllDatabases: "全选",
filterDatabases: "搜索数据库...",
clearDatabases: "清空",
tableSelection: "选择表", tableSelection: "选择表",
selectedTables: "已选择 {selected}/{total}", selectedTables: "已选择 {selected}/{total}",
selectAllTables: "全选", selectAllTables: "全选",
@@ -3064,10 +3070,15 @@ export default withEnglishFallback({
tableLoadError: "加载表失败:{error}", tableLoadError: "加载表失败:{error}",
noTables: "未找到表", noTables: "未找到表",
export: "导出", export: "导出",
exportAllDatabases: "导出全部数据库",
exporting: "正在导出...", exporting: "正在导出...",
selectExportDirectory: "选择导出目录",
currentDatabase: "数据库 {current}/{total}",
currentTable: "当前: {table} ({current}/{total})", currentTable: "当前: {table} ({current}/{total})",
rowsExported: "已导出 {count} 行", rowsExported: "已导出 {count} 行",
exportSuccess: "数据库导出成功", exportSuccess: "数据库导出成功",
exportAllSuccess: "已成功导出 {count} 个数据库",
allDatabasesTask: "全部数据库({count})",
exportError: "导出失败: {error}", exportError: "导出失败: {error}",
exportCancelled: "导出已取消", exportCancelled: "导出已取消",
runInBackground: "后台运行", runInBackground: "后台运行",
+11
View File
@@ -1271,6 +1271,7 @@ export default withEnglishFallback({
setDefaultDatabase: "設為預設資料庫", setDefaultDatabase: "設為預設資料庫",
clearDefaultDatabase: "取消預設資料庫", clearDefaultDatabase: "取消預設資料庫",
exportDatabase: "匯出資料庫", exportDatabase: "匯出資料庫",
exportAllDatabases: "匯出全部資料庫",
exportDatabaseSuccess: "已匯出 {count} 張資料表,每張最多 {limit} 行", exportDatabaseSuccess: "已匯出 {count} 張資料表,每張最多 {limit} 行",
exportDatabaseFailed: "匯出資料庫失敗:{message}", exportDatabaseFailed: "匯出資料庫失敗:{message}",
backupSqliteDatabase: "備份 SQLite 資料庫", backupSqliteDatabase: "備份 SQLite 資料庫",
@@ -2958,6 +2959,11 @@ export default withEnglishFallback({
dropTableIfExists: "匯出前新增 DROP TABLE IF EXISTS", dropTableIfExists: "匯出前新增 DROP TABLE IF EXISTS",
includeData: "資料表資料 (INSERT)", includeData: "資料表資料 (INSERT)",
includeObjects: "檢視 / 預存程序 / 函式 / 序列", includeObjects: "檢視 / 預存程序 / 函式 / 序列",
databaseSelection: "選擇資料庫",
selectedDatabases: "已選擇 {selected}/{total}",
selectAllDatabases: "全選",
filterDatabases: "搜尋資料庫...",
clearDatabases: "清空",
tableSelection: "資料表", tableSelection: "資料表",
selectedTables: "已選擇 {selected}/{total}", selectedTables: "已選擇 {selected}/{total}",
selectAllTables: "全選", selectAllTables: "全選",
@@ -2967,10 +2973,15 @@ export default withEnglishFallback({
tableLoadError: "載入資料表失敗:{error}", tableLoadError: "載入資料表失敗:{error}",
noTables: "找不到資料表", noTables: "找不到資料表",
export: "匯出", export: "匯出",
exportAllDatabases: "匯出全部資料庫",
exporting: "正在匯出……", exporting: "正在匯出……",
selectExportDirectory: "選擇匯出目錄",
currentDatabase: "資料庫 {current}/{total}",
currentTable: "目前: {table} ({current}/{total})", currentTable: "目前: {table} ({current}/{total})",
rowsExported: "已匯出 {count} 列", rowsExported: "已匯出 {count} 列",
exportSuccess: "資料庫匯出成功", exportSuccess: "資料庫匯出成功",
exportAllSuccess: "已成功匯出 {count} 個資料庫",
allDatabasesTask: "全部資料庫({count})",
exportError: "匯出失敗: {error}", exportError: "匯出失敗: {error}",
exportCancelled: "匯出已取消", exportCancelled: "匯出已取消",
runInBackground: "背景執行", runInBackground: "背景執行",
+28
View File
@@ -52,6 +52,19 @@ export interface BuildExportPageSqlOptions {
offset?: number; offset?: number;
} }
export interface AllDatabaseExportPlanInput {
databases: string[];
schemaAware: boolean;
schemasByDatabase?: Record<string, string[]>;
}
export interface AllDatabaseExportPlanItem {
database: string;
schema: string;
fileStem: string;
displayName: string;
}
export function buildInsertStatements(options: BuildExportInsertStatementsOptions): Promise<string[]> { export function buildInsertStatements(options: BuildExportInsertStatementsOptions): Promise<string[]> {
return api.buildExportInsertStatements(options); return api.buildExportInsertStatements(options);
} }
@@ -70,6 +83,21 @@ export function generateDatabaseExportId(): string {
return uuid(); return uuid();
} }
export function buildAllDatabaseExportPlan(options: AllDatabaseExportPlanInput): AllDatabaseExportPlanItem[] {
return options.databases.flatMap((database) => {
const schemas = options.schemaAware ? (options.schemasByDatabase?.[database] ?? []).filter((schema) => schema.trim()) : [database];
const exportSchemas = schemas.length > 0 ? schemas : [database];
const includeSchemaInFileName = options.schemaAware && exportSchemas.length > 1;
return exportSchemas.map((schema) => ({
database,
schema,
fileStem: includeSchemaInFileName ? `${database}.${schema}` : database,
displayName: includeSchemaInFileName ? `${database}.${schema}` : database,
}));
});
}
export function buildDatabaseSqlExport(options: BuildDatabaseSqlExportOptions): Promise<string> { export function buildDatabaseSqlExport(options: BuildDatabaseSqlExportOptions): Promise<string> {
return api.buildDatabaseSqlExport({ return api.buildDatabaseSqlExport({
...options, ...options,
@@ -257,6 +257,7 @@ export const useConnectionStore = defineStore("connection", () => {
schema?: string; schema?: string;
tableName?: string; tableName?: string;
tableNames?: string[]; tableNames?: string[];
allDatabases?: boolean;
} | null>(null); } | null>(null);
const sidebarLayout = ref<SidebarLayout>(emptyLayout()); const sidebarLayout = ref<SidebarLayout>(emptyLayout());
let layoutPersistTimer: ReturnType<typeof setTimeout> | null = null; let layoutPersistTimer: ReturnType<typeof setTimeout> | null = null;
@@ -0,0 +1,35 @@
import assert from "node:assert/strict";
import { test } from "vitest";
import { buildAllDatabaseExportPlan } from "../../apps/desktop/src/lib/databaseExport.ts";
test("all-database export includes every schema for schema-aware databases", () => {
const plan = buildAllDatabaseExportPlan({
databases: ["app", "analytics"],
schemaAware: true,
schemasByDatabase: {
app: ["public", "private"],
analytics: ["reporting"],
},
});
assert.deepEqual(plan, [
{ database: "app", schema: "public", fileStem: "app.public", displayName: "app.public" },
{ database: "app", schema: "private", fileStem: "app.private", displayName: "app.private" },
{ database: "analytics", schema: "reporting", fileStem: "analytics", displayName: "analytics" },
]);
});
test("all-database export uses the database as schema for non-schema-aware databases", () => {
const plan = buildAllDatabaseExportPlan({
databases: ["app", "analytics"],
schemaAware: false,
schemasByDatabase: {
app: ["ignored"],
},
});
assert.deepEqual(plan, [
{ database: "app", schema: "app", fileStem: "app", displayName: "app" },
{ database: "analytics", schema: "analytics", fileStem: "analytics", displayName: "analytics" },
]);
});