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(diff): export data compare diffs to xlsx

HighBigSky14e9683aae55
diff --git a/apps/desktop/src/components/diff/DataCompareDialog.vue b/apps/desktop/src/components/diff/DataCompareDialog.vue
index 91bd7abb4f..bff7cd2b4e 100644
--- a/apps/desktop/src/components/diff/DataCompareDialog.vue
+++ b/apps/desktop/src/components/diff/DataCompareDialog.vue
@@ -36,8 +36,10 @@ import * as api from "@/lib/backend/api";
import { executeWithProductionSqlGuard } from "@/lib/database/productionExecutionGuard";
import { supportsTransaction } from "@/lib/database/databaseFeatureSupport";
import { formatError, isManualTransactionSessionExpired } from "@/lib/backend/errorUtils";
+import { isTauriRuntime } from "@/lib/backend/tauriRuntime";
+import { promptExportSavePath } from "@/lib/export/exportPath";
import TableMultiSelect from "@/components/diff/TableMultiSelect.vue";
-import { ArrowLeftRight, CheckSquare, ChevronDown, ChevronRight, Copy, GitCompareArrows, Loader2, Play, RotateCcw, Square } from "@lucide/vue";
+import { ArrowLeftRight, CheckSquare, ChevronDown, ChevronRight, Copy, Download, GitCompareArrows, Loader2, Play, RotateCcw, Square } from "@lucide/vue";
const PREVIEW_LIMIT_OPTIONS = [50, 100, 200, 500];
const SYNC_EXECUTE_BATCH_SIZE = 500;
@@ -92,6 +94,7 @@ const syncPlan = shallowRef<DataCompareSyncPlan>(emptyDataCompareSyncPlan());
const sqlPreview = computed(() => createBoundedTextPreview(syncPlan.value.syncSql, { maxCharacters: SQL_PREVIEW_MAX_CHARACTERS, maxLines: SQL_PREVIEW_MAX_LINES }));
const sqlPreviewText = computed(() => (sqlPreview.value.truncated ? `${sqlPreview.value.head}\n…\n${sqlPreview.value.tail}` : sqlPreview.value.head));
const comparing = ref(false);
+const exportingDiffs = ref(false);
const planningSync = ref(false);
const compareProgressCurrent = ref(0);
const compareProgressTotal = ref(0);
@@ -837,6 +840,70 @@ function toggleShowAll(table: DataCompareTableResult, kind: DiffKind) {
table.showAll[kind] = !table.showAll[kind];
}
+/** 是否存在可导出的差异:至少一张表比对成功且带有 added/removed/modified 行。 */
+const canExportDiffs = computed(() => batchResults.value.some((item) => item.status === "different" && item.columns.length > 0 && (item.diff.added.length > 0 || item.diff.removed.length > 0 || item.diff.modified.length > 0)));
+
+/**
+ * 按列名取差异行的单元格值:added/removed 行的整行值分散在 `values` 与
+ * `keyValues` 两个 Record 里(键列不进 values),取不到时回退键值,最后兜底
+ * null,保证导出行与列头逐列对齐。
+ */
+function compareRowCellValue(values: Record<string, DataCompareCellValue>, keyValues: Record<string, DataCompareCellValue>, column: string): DataCompareCellValue {
+ const value = values[column] ?? keyValues[column];
+ return value === undefined ? null : value;
+}
+
+/** modified 行导出源库整行;变更明细单独汇总在行尾的「变更明细」列。 */
+function compareModifiedRowCellValue(row: DataCompareModifiedRow, column: string): DataCompareCellValue {
+ const value = row.sourceValues[column] ?? row.keyValues[column];
+ return value === undefined ? null : value;
+}
+
+/** 变更明细文案:`列名: 源值 => 目标值`,多字段用分号连接,便于离线核对。 */
+function changedFieldsSummary(row: DataCompareModifiedRow): string {
+ return row.changes.map((change) => `${change.column}: ${String(change.source ?? "")} => ${String(change.target ?? "")}`).join("; ");
+}
+
+/**
+ * 把当前比对出的全部差异导出为 XLSX:每张有差异的表一个 worksheet,行首
+ * 「差异类型」列区分新增/缺失/修改(文案随界面语言);modified 行导出源库
+ * 整行。注意导出的仍是预算内已比对的行,被截断舍弃的范围不会因此补全。
+ * sheet 名交由写入端清洗去重(Tauri/Rust 与 Web 构建路径都有该逻辑)。
+ */
+async function exportDiffResultsXlsx() {
+ const tables = batchResults.value.filter((item) => item.status === "different" && item.columns.length > 0 && (item.diff.added.length > 0 || item.diff.removed.length > 0 || item.diff.modified.length > 0));
+ if (tables.length === 0) return;
+
+ const kindColumn = t("dataCompare.exportDiffKind");
+ const changedColumn = t("dataCompare.exportChangedFields");
+ const worksheets = tables.map((item) => ({
+ sheetName: item.sourceTable,
+ columns: [kindColumn, ...item.columns, changedColumn],
+ rows: [
+ ...item.diff.added.map((row) => [t("diff.added"), ...item.columns.map((column) => compareRowCellValue(row.values, row.keyValues, column)), ""]),
+ ...item.diff.removed.map((row) => [t("diff.removed"), ...item.columns.map((column) => compareRowCellValue(row.values, row.keyValues, column)), ""]),
+ ...item.diff.modified.map((row) => [t("diff.modified"), ...item.columns.map((column) => compareModifiedRowCellValue(row, column)), changedFieldsSummary(row)]),
+ ],
+ autoFilter: false,
+ }));
+
+ exportingDiffs.value = true;
+ try {
+ let outputPath = `data-compare-diffs-${new Date().toISOString().slice(0, 10)}.xlsx`;
+ if (isTauriRuntime()) {
+ const path = await promptExportSavePath({ defaultFileName: outputPath, filters: [{ name: "Excel", extensions: ["xlsx"] }] });
+ if (!path) return;
+ outputPath = path;
+ }
+ await api.exportQueryResultsXlsx(outputPath, worksheets, false, undefined);
+ toast(t("dataCompare.exportDiffSuccess", { path: outputPath }), 5000);
+ } catch (error: any) {
+ toast(formatError(error), 5000);
+ } finally {
+ exportingDiffs.value = false;
+ }
+}
+
function setDiffSelection(kind: DiffKind, selected: boolean) {
if (executionLocked.value) return;
batchResults.value.forEach((table) => {
@@ -1505,8 +1572,16 @@ onBeforeUnmount(() => {
<div v-if="hasResults" class="space-y-3">
<div class="rounded-lg border p-3 text-sm space-y-2">
- <div>{{ summary }}</div>
- <div class="text-xs text-muted-foreground">{{ selectedSummary }}</div>
+ <div class="flex flex-wrap items-start justify-between gap-2">
+ <div class="min-w-0 space-y-2">
+ <div>{{ summary }}</div>
+ <div class="text-xs text-muted-foreground">{{ selectedSummary }}</div>
+ </div>
+ <Button v-if="canExportDiffs" size="sm" variant="outline" class="h-7 shrink-0 text-xs" :disabled="exportingDiffs" @click="exportDiffResultsXlsx">
+ <Download class="h-3.5 w-3.5" />
+ {{ t("dataCompare.exportDiff") }}
+ </Button>
+ </div>
</div>
<div v-if="truncatedResults.length" class="rounded-lg border border-amber-500/40 bg-amber-500/10 p-3 text-xs text-amber-700 space-y-1 dark:text-amber-400">
diff --git a/apps/desktop/src/i18n/locales/az.ts b/apps/desktop/src/i18n/locales/az.ts
index 8b92656d81..ad91faa9c7 100644
--- a/apps/desktop/src/i18n/locales/az.ts
+++ b/apps/desktop/src/i18n/locales/az.ts
@@ -7382,6 +7382,10 @@ export default withEnglishFallback({
truncatedHint: "Bir müqayisənin oxuya biləcəyindən çox sətri olan cədvəllər yalnız ilk sətirlər üzrə müqayisə edildi, ona görə də bu nöqtədən sonrakı əlavə, dəyişdirilmiş və ya silinmiş sətirlər aşkarlanmır. Aralığı filtr ilə daraldıb hissə-hissə müqayisə edin.",
truncatedTable: "{table}: mənbə {source} sətir, hədəf {target} sətir; yalnız ilk {budget} sətir müqayisə edildi",
truncatedBadge: "Yalnız ilk {budget} sətir müqayisə edildi",
+ exportDiff: "Fərqləri ixrac et (XLSX)",
+ exportDiffKind: "Fərq növü",
+ exportChangedFields: "Dəyişən sahələr",
+ exportDiffSuccess: "Fərqlər ixrac edildi: {path}",
},
settings: {
historyRetentionLimit: "Sorğu tarixçəsinin saxlanma həddi",
diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.ts
index 9e7bdd21b3..6d1d8fe007 100644
--- a/apps/desktop/src/i18n/locales/en.ts
+++ b/apps/desktop/src/i18n/locales/en.ts
@@ -9788,6 +9788,10 @@ export default {
truncatedHint: "Tables above the single-compare limit were inspected only over a subset, so changes outside it are not reported. Synchronization SQL is disabled for these results; narrow the range and run complete comparisons in batches.",
truncatedTable: "{table}: {source} source rows, {target} target rows, compared the first {budget} rows only",
truncatedBadge: "Inspected a subset (up to {budget} rows per side); synchronization disabled",
+ exportDiff: "Export Diffs (XLSX)",
+ exportDiffKind: "Diff Type",
+ exportChangedFields: "Changed Fields",
+ exportDiffSuccess: "Diffs exported: {path}",
},
settings: {
historyRetentionLimit: "Query history retention",
diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.ts
index 569c853c7a..49ddbfd134 100644
--- a/apps/desktop/src/i18n/locales/es.ts
+++ b/apps/desktop/src/i18n/locales/es.ts
@@ -8598,6 +8598,10 @@ export default withEnglishFallback({
truncatedHint: "Las tablas con más filas de las que puede leer una sola comparación solo se compararon en sus primeras filas, por lo que las filas añadidas, modificadas o eliminadas a partir de ahí no se detectan. Acota el rango con un filtro y compara por lotes.",
truncatedTable: "{table}: {source} filas de origen, {target} de destino; solo se compararon las primeras {budget} filas",
truncatedBadge: "Solo se compararon las primeras {budget} filas",
+ exportDiff: "Exportar diferencias (XLSX)",
+ exportDiffKind: "Tipo de diferencia",
+ exportChangedFields: "Campos modificados",
+ exportDiffSuccess: "Diferencias exportadas: {path}",
},
settings: {
historyRetentionLimit: "Límite del historial de consultas",
diff --git a/apps/desktop/src/i18n/locales/id.ts b/apps/desktop/src/i18n/locales/id.ts
index 52d4643cf2..33cbbe7285 100644
--- a/apps/desktop/src/i18n/locales/id.ts
+++ b/apps/desktop/src/i18n/locales/id.ts
@@ -8124,6 +8124,10 @@ export default withEnglishFallback({
"Tabel dengan baris lebih banyak daripada yang dapat dibaca dalam satu kali perbandingan hanya dibandingkan sampai baris pertamanya, sehingga baris yang ditambahkan, diubah, atau dihapus setelah titik itu tidak dilaporkan. Persempit rentang dengan filter dan bandingkan secara bertahap.",
truncatedTable: "{table}: {source} baris sumber, {target} baris target, hanya {budget} baris pertama yang dibandingkan",
truncatedBadge: "Hanya {budget} baris pertama yang dibandingkan",
+ exportDiff: "Ekspor Perbedaan (XLSX)",
+ exportDiffKind: "Jenis Perbedaan",
+ exportChangedFields: "Kolom yang Berubah",
+ exportDiffSuccess: "Perbedaan diekspor: {path}",
},
settings: {
historyRetentionLimit: "Retensi riwayat kueri",
diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.ts
index 9c6c608fc4..b7729ee0c6 100644
--- a/apps/desktop/src/i18n/locales/it.ts
+++ b/apps/desktop/src/i18n/locales/it.ts
@@ -8376,6 +8376,10 @@ export default withEnglishFallback({
truncatedHint: "Le tabelle con più righe di quante ne possa leggere un singolo confronto sono state confrontate solo sulle prime righe, quindi le righe aggiunte, modificate o eliminate oltre quel punto non vengono rilevate. Restringi l'intervallo con un filtro e confronta a blocchi.",
truncatedTable: "{table}: {source} righe nell'origine, {target} nella destinazione; confrontate solo le prime {budget} righe",
truncatedBadge: "Confrontate solo le prime {budget} righe",
+ exportDiff: "Esporta differenze (XLSX)",
+ exportDiffKind: "Tipo di differenza",
+ exportChangedFields: "Campi modificati",
+ exportDiffSuccess: "Differenze esportate: {path}",
},
settings: {
historyRetentionLimit: "Limite della cronologia query",
diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.ts
index 0bcc9499ed..ecd6630808 100644
--- a/apps/desktop/src/i18n/locales/ja.ts
+++ b/apps/desktop/src/i18n/locales/ja.ts
@@ -8396,6 +8396,10 @@ export default withEnglishFallback({
truncatedHint: "1 回の比較で読み込める行数を超えたテーブルは先頭の行だけを比較しているため、それ以降の追加・変更・削除は検出されません。フィルターで範囲を絞り、分割して比較してください。",
truncatedTable: "{table}:ソース {source} 行、ターゲット {target} 行、先頭 {budget} 行のみ比較",
truncatedBadge: "先頭 {budget} 行のみ比較",
+ exportDiff: "差分をエクスポート (XLSX)",
+ exportDiffKind: "差分タイプ",
+ exportChangedFields: "変更フィールド",
+ exportDiffSuccess: "差分のエクスポートが完了しました:{path}",
},
settings: {
historyRetentionLimit: "クエリ履歴の保持件数",
diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.ts
index c31f2c02d6..263f4efe28 100644
--- a/apps/desktop/src/i18n/locales/ko.ts
+++ b/apps/desktop/src/i18n/locales/ko.ts
@@ -8492,6 +8492,10 @@ export default withEnglishFallback({
truncatedHint: "한 번의 비교로 읽을 수 있는 행 수를 초과한 테이블은 앞부분만 비교했기 때문에 그 이후의 추가·수정·삭제는 감지되지 않습니다. 필터로 범위를 좁혀 나누어 비교하세요.",
truncatedTable: "{table}: 원본 {source}행, 대상 {target}행, 앞 {budget}행만 비교",
truncatedBadge: "앞 {budget}행만 비교",
+ exportDiff: "차이 내보내기 (XLSX)",
+ exportDiffKind: "차이 유형",
+ exportChangedFields: "변경 필드",
+ exportDiffSuccess: "차이 내보내기 완료: {path}",
},
settings: {
historyRetentionLimit: "쿼리 기록 보관 개수",
diff --git a/apps/desktop/src/i18n/locales/pl.ts b/apps/desktop/src/i18n/locales/pl.ts
index 90c5bbe338..798b45c8ad 100644
--- a/apps/desktop/src/i18n/locales/pl.ts
+++ b/apps/desktop/src/i18n/locales/pl.ts
@@ -8186,6 +8186,10 @@ export default withEnglishFallback({
truncatedHint: "Tabele zawierające więcej wierszy niż pozwala pojedyncze porównanie zostały sprawdzone tylko w zakresie pierwszych wierszy; dodane, zmodyfikowane lub usunięte wiersze poza tym zakresem nie są raportowane. Zawęź zakres filtrem i porównuj partiami.",
truncatedTable: "{table}: {source} wierszy źródłowych, {target} wierszy docelowych, porównano tylko pierwsze {budget} wierszy",
truncatedBadge: "Porównano tylko pierwsze {budget} wierszy",
+ exportDiff: "Eksportuj różnice (XLSX)",
+ exportDiffKind: "Typ różnicy",
+ exportChangedFields: "Zmienione pola",
+ exportDiffSuccess: "Różnice wyeksportowane: {path}",
},
settings: {
historyRetentionLimit: "Okres przechowywania historii zapytań",
diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.ts
index 6a50e2bad4..32e897c738 100644
--- a/apps/desktop/src/i18n/locales/pt-BR.ts
+++ b/apps/desktop/src/i18n/locales/pt-BR.ts
@@ -8375,6 +8375,10 @@ export default withEnglishFallback({
truncatedHint: "Tabelas com mais linhas do que uma única comparação consegue ler foram comparadas apenas nas primeiras linhas, então linhas adicionadas, modificadas ou excluídas depois disso não são detectadas. Restrinja o intervalo com um filtro e compare em lotes.",
truncatedTable: "{table}: {source} linhas na origem, {target} no destino; apenas as primeiras {budget} linhas foram comparadas",
truncatedBadge: "Apenas as primeiras {budget} linhas comparadas",
+ exportDiff: "Exportar diferenças (XLSX)",
+ exportDiffKind: "Tipo de diferença",
+ exportChangedFields: "Campos alterados",
+ exportDiffSuccess: "Diferenças exportadas: {path}",
},
settings: {
historyRetentionLimit: "Limite do histórico de consultas",
diff --git a/apps/desktop/src/i18n/locales/ru.ts b/apps/desktop/src/i18n/locales/ru.ts
index 48707d6ce0..c7bf23fe10 100644
--- a/apps/desktop/src/i18n/locales/ru.ts
+++ b/apps/desktop/src/i18n/locales/ru.ts
@@ -9951,6 +9951,10 @@ export default withEnglishFallback({
truncatedHint: "Таблицы, в которых строк больше, чем может прочитать одно сравнение, сравнены только по первым строкам, поэтому добавленные, изменённые и удалённые строки после этого не обнаруживаются. Сузьте диапазон фильтром и сравнивайте по частям.",
truncatedTable: "{table}: строк в источнике {source}, в приёмнике {target}; сравнены только первые {budget} строк",
truncatedBadge: "Сравнены только первые {budget} строк",
+ exportDiff: "Экспорт различий (XLSX)",
+ exportDiffKind: "Тип различия",
+ exportChangedFields: "Изменённые поля",
+ exportDiffSuccess: "Различия экспортированы: {path}",
},
settings: {
historyRetentionLimit: "Хранение истории запросов",
diff --git a/apps/desktop/src/i18n/locales/th.ts b/apps/desktop/src/i18n/locales/th.ts
index c6554aaec0..d0293540a5 100644
--- a/apps/desktop/src/i18n/locales/th.ts
+++ b/apps/desktop/src/i18n/locales/th.ts
@@ -10331,6 +10331,10 @@ export default withEnglishFallback({
truncatedHint: "ตารางที่มีแถวมากกว่าที่การเปรียบเทียบครั้งเดียวอ่านได้จะถูกเปรียบเทียบเฉพาะแถวแรก จึงไม่รายงานแถวที่เพิ่ม แก้ไข หรือลบหลังจากนั้น จำกัดช่วงด้วยตัวกรองและเปรียบเทียบเป็นชุด",
truncatedTable: "{table}: แถวต้นทาง {source} แถว แถวปลายทาง {target} แถว เปรียบเทียบเฉพาะ {budget} แถวแรก",
truncatedBadge: "เปรียบเทียบเฉพาะ {budget} แถวแรก",
+ exportDiff: "ส่งออกความแตกต่าง (XLSX)",
+ exportDiffKind: "ประเภทความแตกต่าง",
+ exportChangedFields: "ฟิลด์ที่เปลี่ยนแปลง",
+ exportDiffSuccess: "ส่งออกความแตกต่างแล้ว: {path}",
},
settings: {
historyRetentionLimit: "จำนวนรายการประวัติ Query สูงสุด",
diff --git a/apps/desktop/src/i18n/locales/tr.ts b/apps/desktop/src/i18n/locales/tr.ts
index 682c35f54c..ba1008016f 100644
--- a/apps/desktop/src/i18n/locales/tr.ts
+++ b/apps/desktop/src/i18n/locales/tr.ts
@@ -7262,6 +7262,10 @@ export default withEnglishFallback({
truncatedHint: "Tek bir karşılaştırmanın okuyabileceğinden fazla satıra sahip tablolar yalnızca ilk satırları üzerinden karşılaştırıldı; bu noktadan sonraki eklenen, değişen veya silinen satırlar bildirilmez. Aralığı bir filtreyle daraltıp toplu olarak karşılaştırın.",
truncatedTable: "{table}: kaynak {source} satır, hedef {target} satır; yalnızca ilk {budget} satır karşılaştırıldı",
truncatedBadge: "Yalnızca ilk {budget} satır karşılaştırıldı",
+ exportDiff: "Farkları Dışa Aktar (XLSX)",
+ exportDiffKind: "Fark Türü",
+ exportChangedFields: "Değişen Alanlar",
+ exportDiffSuccess: "Farklar dışa aktarıldı: {path}",
},
settings: {
historyRetentionLimit: "Sorgu geçmişi saklama sınırı",
diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.ts
index 4ae67a6a82..41b8633a7a 100644
--- a/apps/desktop/src/i18n/locales/zh-CN.ts
+++ b/apps/desktop/src/i18n/locales/zh-CN.ts
@@ -9755,6 +9755,10 @@ export default withEnglishFallback({
truncatedHint: "行数超过单次比较上限的表只检查了部分数据,未检查范围内的新增、修改和删除不会被发现,因此不会生成或执行同步 SQL。建议缩小范围后分批完整比较。",
truncatedTable: "{table}:源 {source} 行、目标 {target} 行,仅比较前 {budget} 行",
truncatedBadge: "仅检查部分数据(单侧上限 {budget} 行),同步已禁用",
+ exportDiff: "导出差异 (XLSX)",
+ exportDiffKind: "差异类型",
+ exportChangedFields: "变更明细",
+ exportDiffSuccess: "差异导出成功:{path}",
},
settings: {
historyRetentionLimit: "查询历史保留条数",
diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.ts
index 14ba479378..c511c4f72e 100644
--- a/apps/desktop/src/i18n/locales/zh-TW.ts
+++ b/apps/desktop/src/i18n/locales/zh-TW.ts
@@ -7500,6 +7500,10 @@ export default withEnglishFallback({
truncatedHint: "資料筆數超過單次比較上限的表只比較了前幾筆,超出部分的新增、修改與刪除不會被發現。建議加上篩選條件縮小範圍後分批比較。",
truncatedTable: "{table}:來源 {source} 筆、目標 {target} 筆,僅比較前 {budget} 筆",
truncatedBadge: "僅比較前 {budget} 筆",
+ exportDiff: "匯出差異 (XLSX)",
+ exportDiffKind: "差異類型",
+ exportChangedFields: "變更明細",
+ exportDiffSuccess: "差異匯出成功:{path}",
},
settings: {
historyRetentionLimit: "查詢歷史保留筆數",