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。

85.5 KB
Raw Blame
<script setup lang="ts">
import { computed, nextTick, onBeforeUnmount, ref, shallowRef, watch } from "vue";
import { DynamicScroller, DynamicScrollerItem } from "vue-virtual-scroller";
import { createBoundedTextPreview } from "@/lib/common/boundedTextPreview";
import { countCompareSelection, isCompareRowSelected, setCompareSelection, toggleCompareSelection } from "@/lib/dataGrid/dataCompareSelection";
import { useI18n } from "vue-i18n";
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import SearchableSelect from "@/components/ui/searchable-select/SearchableSelect.vue";
import CompareConnectionSelect from "@/components/diff/CompareConnectionSelect.vue";
import { supportsDatabaseCompare } from "@/lib/database/databaseCompareCapabilities";
import { useConnectionStore } from "@/stores/connectionStore";
import { useToast } from "@/composables/useToast";
import { databaseOptionsForConnection, fetchNamespaceOptionsForConnection } from "@/composables/useDatabaseOptions";
import { isSchemaAware } from "@/lib/database/databaseCapabilities";
import { copyToClipboard } from "@/lib/common/clipboard";
import { inferCompareKeyColumns, normalizeKeyColumns, sameKeyColumns, type CompareKeyColumnOption, type DataCompareCellValue, type DataCompareRow, type DataCompareModifiedRow, type DataCompareSyncPlan } from "@/lib/dataGrid/dataCompare";
import {
  buildDataCompareSyncPlanTables,
  emptyDataCompareSyncPlan,
  getDataCompareSession,
  normalizeKeyColumnOverrides,
  startDataCompareSession,
  type DataCompareSession,
  type DataCompareTableResult,
  type DataCompareTableStatus,
  type DataCompareTableTask,
  type DiffKind,
} from "@/composables/useDataCompareSession";
import CompareKeyColumnsSelect from "@/components/diff/CompareKeyColumnsSelect.vue";
import DataCompareConfigSelector from "@/components/diff/DataCompareConfigSelector.vue";
import { useDataCompareConfig, type DataCompareConfig, type DataCompareConfigSnapshot } from "@/composables/useDataCompareConfig";
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, Download, GitCompareArrows, Loader2, Play, RotateCcw, Square } from "@lucide/vue";

const PREVIEW_LIMIT_OPTIONS = [50, 100, 200, 500];
const SYNC_EXECUTE_BATCH_SIZE = 500;
const DIFF_ROW_MIN_HEIGHT = 64;
const DIFF_LIST_MAX_HEIGHT = 288;
const SQL_PREVIEW_MAX_CHARACTERS = 8192;
const SQL_PREVIEW_MAX_LINES = 200;

const { t } = useI18n();
const { toast } = useToast();
const store = useConnectionStore();
const {
  configs: dataCompareConfigs,
  activeConfigId: dataCompareConfigId,
  activeConfig: activeDataCompareConfig,
  createConfig: createDataCompareConfig,
  updateConfig: updateDataCompareConfig,
  renameConfig: renameDataCompareConfig,
  deleteConfig: deleteDataCompareConfig,
  duplicateConfig: duplicateDataCompareConfig,
} = useDataCompareConfig();
const open = defineModel<boolean>("open", { default: false });

const props = defineProps<{
  prefillConnectionId?: string;
  prefillDatabase?: string;
  prefillSchema?: string;
  prefillTable?: string;
  sessionId?: string | null;
}>();

const sourceConnectionId = ref("");
const sourceDatabase = ref("");
const sourceSchema = ref("");
const sourceTable = ref("");
const sourceDatabases = ref<string[]>([]);
const sourceSchemas = ref<string[]>([]);
const sourceTables = ref<string[]>([]);
const selectedSourceTables = ref<Set<string>>(new Set());

const targetConnectionId = ref("");
const targetDatabase = ref("");
const targetSchema = ref("");
const targetTable = ref("");
const targetDatabases = ref<string[]>([]);
const targetSchemas = ref<string[]>([]);
const targetTables = ref<string[]>([]);

const detailPreviewLimit = ref(String(PREVIEW_LIMIT_OPTIONS[1]));
const batchResults = shallowRef<DataCompareTableResult[]>([]);
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);
const compareProgressTable = ref("");
const executing = ref(false);
const manualTransaction = ref(false);
const txnSessionId = ref<string>();
let commitUncertain = false;
const resolvingTransaction = ref(false);
const transactionFailed = ref(false);
let executionInterrupted = false;
const executionLocked = computed(() => executing.value || resolvingTransaction.value || !!txnSessionId.value);
const canUseManualTransaction = computed(() => supportsTransaction(store.getConfig(targetConnectionId.value)?.db_type));
const executedCount = ref(0);
const executeTotal = ref(0);
const syncErrors = ref<{ sql: string; error: string }[]>([]);
const showAdded = ref(true);
const showRemoved = ref(true);
const showModified = ref(true);

/**
 * Explicit match columns per source table. An absent entry means "auto": the
 * primary key of that table is inferred, so a batch compare never shares one
 * global key column list across different tables.
 */
const keyColumnOverrides = ref<Record<string, string[]>>({});
/** Column metadata per source table, keyed by table name; cleared with the source endpoint. */
const tableColumns = ref<Record<string, CompareKeyColumnOption[]>>({});
const tableColumnErrors = ref<Record<string, string>>({});
const loadingColumnTables = ref<string[]>([]);
const expandedKeyColumnTable = ref("");
let columnRequests = new Map<string, Promise<CompareKeyColumnOption[]>>();
/** Invalidates in-flight metadata responses after a source endpoint change. */
let columnMetadataGeneration = 0;

const activeSessionId = ref<string | null>(props.sessionId ?? null);
let syncPlanRequestId = 0;
let initializingPrefill = false;
let initializingPrefillGeneration = 0;
/** Set while a saved config is being applied so programmatic form writes are not re-saved. */
let suppressConfigSave = false;
let configSaveTimer: ReturnType<typeof setTimeout> | undefined;
let componentUnmounted = false;
let shownSessionError = "";

const compareConnections = computed(() => store.connections.filter((connection) => supportsDatabaseCompare(connection, "data")));
// Swapping copies the loaded lists and suppresses their reload watchers. Wait
// until all namespace/table requests settle so no unfinished list is stranded.
const pendingMetadataRequests = ref(0);
// Invalidate metadata responses when the user switches either endpoint, even
// when they switch back before the previous request finishes.
const metadataGenerations = { source: 0, target: 0 };
watch(
  [sourceConnectionId, sourceDatabase, sourceSchema],
  () => {
    metadataGenerations.source += 1;
  },
  { flush: "sync" },
);
watch(
  [targetConnectionId, targetDatabase, targetSchema],
  () => {
    metadataGenerations.target += 1;
  },
  { flush: "sync" },
);

function metadataRequestIsCurrent(side: "source" | "target"): () => boolean {
  const generation = metadataGenerations[side];
  const connectionId = side === "source" ? sourceConnectionId.value : targetConnectionId.value;
  return () => generation === metadataGenerations[side] && supportsDatabaseCompare(store.getConfig(connectionId), "data");
}

const selectedSourceTableNames = computed(() => sourceTables.value.filter((table) => selectedSourceTables.value.has(table)));
const isBatchCompare = computed(() => selectedSourceTableNames.value.length > 1);
// Bridge the shared TableMultiSelect `string[]` v-model with the Set-based selection store.
const sourceTableSelection = computed<string[]>({
  get: () => [...selectedSourceTables.value],
  set: (value: string[]) => resetSelectedSourceTables(value),
});
const compareTasksPreview = computed(() =>
  selectedSourceTableNames.value.map((table) => {
    const target = isBatchCompare.value ? table : targetTable.value || table;
    const matched = !!target && targetTables.value.includes(target);
    return {
      sourceTable: table,
      targetTable: target,
      matched,
    };
  }),
);
const matchedTaskCount = computed(() => compareTasksPreview.value.filter((task) => task.matched).length);
const missingTargetTables = computed(() => compareTasksPreview.value.filter((task) => !task.matched).map((task) => task.targetTable || task.sourceTable));

interface KeyColumnRow {
  table: string;
  matched: boolean;
  manual: boolean;
  columns: string[];
  loading: boolean;
  hint: string;
  /** Set when the column metadata of this table could not be loaded. */
  error?: string;
  /** `missing` means neither a primary key nor a manual selection is available yet. */
  status: "auto" | "manual" | "missing";
}

const keyColumnRows = computed<KeyColumnRow[]>(() =>
  selectedSourceTableNames.value.map((table) => {
    const matched = !!compareTasksPreview.value.find((task) => task.sourceTable === table)?.matched;
    const manual = hasKeyColumnOverride(table);
    const columns = effectiveKeyColumns(table);
    const error = tableColumnErrors.value[table];
    return {
      table,
      matched,
      manual,
      columns,
      loading: isTableColumnsLoading(table),
      hint: error || keyColumnHint(table, { matched, manual, columns }),
      error,
      status: manual ? "manual" : columns.length > 0 ? "auto" : "missing",
    };
  }),
);
const singleKeyColumnRow = computed(() => (selectedSourceTableNames.value.length === 1 ? keyColumnRows.value[0] : undefined));
/**
 * A single-table compare whose target table exists but whose match columns are
 * unknown: primary key inference found nothing and the user has not picked
 * columns yet. Blocking here is safe because no other table depends on it.
 * Unloaded metadata is deliberately not treated as "no primary key".
 */
const singleTableNeedsKeyColumns = computed(() => {
  const row = singleKeyColumnRow.value;
  if (!row || !row.matched) return false;
  if (!isTableColumnsKnown(row.table)) return false;
  return row.columns.length === 0;
});
const canCompare = computed(
  () =>
    supportsDatabaseCompare(store.getConfig(sourceConnectionId.value), "data") &&
    supportsDatabaseCompare(store.getConfig(targetConnectionId.value), "data") &&
    sourceConnectionId.value &&
    sourceDatabase.value &&
    sourceSchema.value &&
    selectedSourceTableNames.value.length > 0 &&
    targetConnectionId.value &&
    targetDatabase.value &&
    targetSchema.value &&
    !singleTableNeedsKeyColumns.value,
);
const detailPreviewLimitNumber = computed(() => Number(detailPreviewLimit.value) || PREVIEW_LIMIT_OPTIONS[1]);

const sameTableCount = computed(() => batchResults.value.filter((item) => item.status === "same").length);
const differentTableCount = computed(() => batchResults.value.filter((item) => item.status === "different").length);
const failedTableCount = computed(() => batchResults.value.filter((item) => item.status === "error").length);
const totalAdded = computed(() => batchResults.value.reduce((sum, item) => sum + item.added, 0));
const totalRemoved = computed(() => batchResults.value.reduce((sum, item) => sum + item.removed, 0));
const totalModified = computed(() => batchResults.value.reduce((sum, item) => sum + item.modified, 0));
const hasResults = computed(() => batchResults.value.length > 0);
// A compare reads both sides up to a fixed row budget, so a table larger than that budget
// is reported through `*Truncated`. Surfacing it here keeps a partial diff from looking
// like a complete one.
const truncatedResults = computed(() => batchResults.value.filter((item) => item.sourceTruncated || item.targetTruncated));
const visibleKinds = computed(() => [...(showAdded.value ? (["added"] as DiffKind[]) : []), ...(showRemoved.value ? (["removed"] as DiffKind[]) : []), ...(showModified.value ? (["modified"] as DiffKind[]) : [])]);
const selectedAddedCount = computed(() => selectedDiffCount("added"));
const selectedRemovedCount = computed(() => selectedDiffCount("removed"));
const selectedModifiedCount = computed(() => selectedDiffCount("modified"));
const summary = computed(() => {
  if (!hasResults.value) return "";
  if (batchResults.value.length === 1 && batchResults.value[0]?.status !== "error") {
    const item = batchResults.value[0];
    return t("dataCompare.summary", {
      added: item.added,
      removed: item.removed,
      modified: item.modified,
    });
  }
  return t("dataCompare.batchSummary", {
    tables: batchResults.value.length,
    different: differentTableCount.value,
    same: sameTableCount.value,
    failed: failedTableCount.value,
    added: totalAdded.value,
    removed: totalRemoved.value,
    modified: totalModified.value,
  });
});
const selectedSummary = computed(() =>
  t("dataCompare.selectedSummary", {
    added: selectedAddedCount.value,
    removed: selectedRemovedCount.value,
    modified: selectedModifiedCount.value,
  }),
);
const compareProgressLabel = computed(() => {
  if (!comparing.value || compareProgressTotal.value === 0) return "";
  return t("dataCompare.comparingTable", {
    current: compareProgressCurrent.value,
    total: compareProgressTotal.value,
    table: compareProgressTable.value,
  });
});

function resetSelectedSourceTables(nextTables: Iterable<string>) {
  selectedSourceTables.value = new Set(nextTables);
}

// --- Match columns (key columns) -------------------------------------------------
//
// Every selected source table owns its match columns: the primary key is the
// default, and a manual picker selection is stored as a per-table override in
// `keyColumnOverrides`. The session receives the same per-table shape, so a
// batch compare is never forced to share one global key column list.

function resetTableColumnMetadata() {
  columnMetadataGeneration += 1;
  columnRequests = new Map();
  tableColumns.value = {};
  tableColumnErrors.value = {};
  loadingColumnTables.value = [];
  expandedKeyColumnTable.value = "";
}

function columnsForTable(table: string): CompareKeyColumnOption[] {
  return tableColumns.value[table] ?? [];
}

function isTableColumnsKnown(table: string): boolean {
  return tableColumns.value[table] !== undefined;
}

function isTableColumnsLoading(table: string): boolean {
  return loadingColumnTables.value.includes(table);
}

function hasKeyColumnOverride(table: string): boolean {
  return keyColumnOverrides.value[table] !== undefined;
}

function inferredKeyColumns(table: string): string[] {
  return inferCompareKeyColumns(columnsForTable(table));
}

/** Effective match columns of a table: the manual override, otherwise the inferred primary key. */
function effectiveKeyColumns(table: string): string[] {
  const override = keyColumnOverrides.value[table];
  return override === undefined ? inferredKeyColumns(table) : override;
}

async function fetchTableColumns(table: string): Promise<CompareKeyColumnOption[]> {
  const connectionId = sourceConnectionId.value;
  const database = sourceDatabase.value;
  const schema = sourceSchema.value;
  if (!connectionId || !database || !schema || !table || !supportsDatabaseCompare(store.getConfig(connectionId), "data")) return [];
  const generation = columnMetadataGeneration;
  loadingColumnTables.value = [...loadingColumnTables.value, table];
  try {
    const columns = (await api.getColumns(connectionId, database, schema, table)) as CompareKeyColumnOption[];
    if (generation !== columnMetadataGeneration) return [];
    tableColumns.value = { ...tableColumns.value, [table]: columns };
    delete tableColumnErrors.value[table];
    return columns;
  } catch (error: any) {
    if (generation === columnMetadataGeneration) tableColumnErrors.value = { ...tableColumnErrors.value, [table]: error?.message || String(error) };
    return [];
  } finally {
    if (generation === columnMetadataGeneration) loadingColumnTables.value = loadingColumnTables.value.filter((item) => item !== table);
  }
}

function loadTableColumns(table: string): Promise<CompareKeyColumnOption[]> {
  const cached = tableColumns.value[table];
  if (cached) return Promise.resolve(cached);
  const pending = columnRequests.get(table);
  if (pending) return pending;
  const request = fetchTableColumns(table).finally(() => columnRequests.delete(table));
  columnRequests.set(table, request);
  return request;
}

/** Loads metadata for the selected tables with bounded concurrency, so a wide selection cannot flood the backend. */
async function prefetchSelectedTableColumns(tables: string[]): Promise<void> {
  const pending = tables.filter((table) => !tableColumns.value[table]);
  if (pending.length === 0) return;
  let cursor = 0;
  const workers = Array.from({ length: Math.min(4, pending.length) }, async () => {
    while (cursor < pending.length) await loadTableColumns(pending[cursor++]);
  });
  await Promise.all(workers);
}

function setTableKeyColumns(table: string, columns: string[]) {
  const normalized = normalizeKeyColumns(columns);
  const next = { ...keyColumnOverrides.value };
  if (sameKeyColumns(normalized, inferredKeyColumns(table))) delete next[table];
  else next[table] = normalized;
  keyColumnOverrides.value = next;
}

function clearTableKeyColumnsOverride(table: string) {
  if (keyColumnOverrides.value[table] === undefined) return;
  const next = { ...keyColumnOverrides.value };
  delete next[table];
  keyColumnOverrides.value = next;
}

/** Drops overrides and metadata of tables that are no longer selected. */
function pruneKeyColumnState(tables: string[]) {
  const keep = new Set(tables);
  const nextOverrides: Record<string, string[]> = {};
  let overridesChanged = false;
  for (const [table, columns] of Object.entries(keyColumnOverrides.value)) {
    if (keep.has(table)) nextOverrides[table] = columns;
    else overridesChanged = true;
  }
  if (overridesChanged) keyColumnOverrides.value = nextOverrides;

  const nextColumns: Record<string, CompareKeyColumnOption[]> = {};
  const nextErrors: Record<string, string> = {};
  let columnsChanged = false;
  for (const [table, columns] of Object.entries(tableColumns.value)) {
    if (keep.has(table)) {
      nextColumns[table] = columns;
      if (tableColumnErrors.value[table]) nextErrors[table] = tableColumnErrors.value[table];
    } else {
      columnsChanged = true;
    }
  }
  if (columnsChanged) {
    tableColumns.value = nextColumns;
    tableColumnErrors.value = nextErrors;
  }
  if (expandedKeyColumnTable.value && !keep.has(expandedKeyColumnTable.value)) expandedKeyColumnTable.value = "";
}

function toggleKeyColumnTable(table: string) {
  expandedKeyColumnTable.value = expandedKeyColumnTable.value === table ? "" : table;
  if (expandedKeyColumnTable.value) void loadTableColumns(table);
}

function keyColumnHint(table: string, state: { matched: boolean; manual: boolean; columns: string[] }): string {
  if (!state.matched) return t("dataCompare.keyColumnsTargetMissingHint");
  if (state.manual) return t("dataCompare.keyColumnsManualHint", { columns: state.columns.length > 0 ? state.columns.join(", ") : t("dataCompare.keyColumnsNoneSelected") });
  if (state.columns.length > 0) return t("dataCompare.keyColumnsAutoSummary", { columns: state.columns.join(", ") });
  if (!isTableColumnsKnown(table)) return t("dataCompare.keyColumnsStatusAuto");
  return t("dataCompare.keyColumnsNoPrimaryKey");
}

/** Only the selected tables are sent, so a deselected table can never leak a stale override. */
function buildSessionKeyColumnsByTable(): Record<string, string[]> {
  const overrides: Record<string, string[]> = {};
  for (const table of selectedSourceTableNames.value) {
    const override = keyColumnOverrides.value[table];
    if (override !== undefined) overrides[table] = [...override];
  }
  return overrides;
}

function buildCompareTasks(): DataCompareTableTask[] {
  if (!selectedSourceTableNames.value.length) return [];
  if (!isBatchCompare.value) {
    const table = selectedSourceTableNames.value[0];
    return table ? [{ sourceTable: table, targetTable: targetTable.value || table }] : [];
  }
  return selectedSourceTableNames.value.map((table) => ({
    sourceTable: table,
    targetTable: table,
  }));
}

function clearResult() {
  batchResults.value = [];
  syncPlan.value = emptyDataCompareSyncPlan();
  syncErrors.value = [];
  compareProgressCurrent.value = 0;
  compareProgressTotal.value = 0;
  compareProgressTable.value = "";
  executedCount.value = 0;
  executeTotal.value = 0;
  planningSync.value = false;
  syncPlanRequestId++;
}

function comparisonEndpointLabel(connectionId: string, database: string, schema: string): string {
  const connection = store.getConfig(connectionId);
  return [connection?.name || connectionId, database, schema].filter(Boolean).join(" / ");
}

async function restoreDataCompareSession(session: DataCompareSession): Promise<void> {
  const config = session.config;
  const generation = ++initializingPrefillGeneration;
  initializingPrefill = true;
  try {
    sourceConnectionId.value = config.sourceConnectionId;
    sourceDatabase.value = config.sourceDatabase;
    sourceSchema.value = config.sourceSchema;
    sourceDatabases.value = [...config.sourceDatabases];
    sourceSchemas.value = [...config.sourceSchemas];
    sourceTables.value = [...config.sourceTables];
    resetSelectedSourceTables(config.selectedSourceTables);
    sourceTable.value = config.selectedSourceTables.length === 1 ? (config.selectedSourceTables[0] ?? "") : "";
    targetConnectionId.value = config.targetConnectionId;
    targetDatabase.value = config.targetDatabase;
    targetSchema.value = config.targetSchema;
    targetDatabases.value = [...config.targetDatabases];
    targetSchemas.value = [...config.targetSchemas];
    targetTables.value = [...config.targetTables];
    targetTable.value = config.targetTable;
    // Restore the per-table match columns so a reopened session keeps every
    // table's own selection instead of collapsing back to one global list.
    keyColumnOverrides.value = normalizeKeyColumnOverrides(config.keyColumnsByTable);
    resetTableColumnMetadata();
    batchResults.value = session.batchResults;
    syncPlan.value = session.syncPlan;
    syncErrors.value = [];
    compareProgressCurrent.value = session.progress?.current ?? 0;
    compareProgressTotal.value = session.progress?.total ?? 0;
    compareProgressTable.value = session.progress?.table ?? "";
    comparing.value = session.status === "running";
    void prefetchSelectedTableColumns(selectedSourceTableNames.value);
  } finally {
    await nextTick();
    if (generation === initializingPrefillGeneration) initializingPrefill = false;
  }
}

/** Selection-only snapshot persisted by the config selector. */
function dataCompareConfigSnapshot(): DataCompareConfigSnapshot {
  return {
    sourceConnectionId: sourceConnectionId.value,
    sourceDatabase: sourceDatabase.value,
    sourceSchema: sourceSchema.value,
    selectedSourceTables: [...selectedSourceTables.value],
    targetConnectionId: targetConnectionId.value,
    targetDatabase: targetDatabase.value,
    targetSchema: targetSchema.value,
    targetTable: targetTable.value,
    detailPreviewLimit: detailPreviewLimit.value,
    keyColumnsByTable: buildSessionKeyColumnsByTable(),
  };
}

/**
 * Rebuild the dialog selection from a saved config. Option lists are re-read
 * from the live connection (never restored from storage) so a config can not
 * resurrect a table that no longer exists; the saved table selection is then
 * intersected with what the connection actually returns.
 */
async function applyDataCompareConfig(config: DataCompareConfig): Promise<void> {
  if (comparing.value || executionLocked.value) return;
  const generation = ++initializingPrefillGeneration;
  initializingPrefill = true;
  suppressConfigSave = true;
  clearResult();
  shownSessionError = "";
  try {
    sourceConnectionId.value = config.sourceConnectionId;
    targetConnectionId.value = config.targetConnectionId;
    sourceDatabase.value = targetDatabase.value = "";
    sourceSchema.value = targetSchema.value = "";
    sourceDatabases.value = targetDatabases.value = [];
    sourceSchemas.value = targetSchemas.value = [];
    sourceTables.value = targetTables.value = [];
    sourceTable.value = targetTable.value = "";
    resetSelectedSourceTables([]);
    resetTableColumnMetadata();
    if (supportsDatabaseCompare(store.getConfig(config.sourceConnectionId), "data")) {
      await loadDatabases(config.sourceConnectionId, "source");
      if (generation !== initializingPrefillGeneration) return;
      if (config.sourceDatabase) sourceDatabase.value = config.sourceDatabase;
      if (config.sourceDatabase) await loadSchemas("source", config.sourceSchema);
      if (generation !== initializingPrefillGeneration) return;
    }

    if (supportsDatabaseCompare(store.getConfig(config.targetConnectionId), "data")) {
      await loadDatabases(config.targetConnectionId, "target");
      if (generation !== initializingPrefillGeneration) return;
      if (config.targetDatabase) targetDatabase.value = config.targetDatabase;
      if (config.targetDatabase) await loadSchemas("target", config.targetSchema);
      if (generation !== initializingPrefillGeneration) return;
    }

    resetSelectedSourceTables(config.selectedSourceTables);
    if (sourceSchema.value) await loadTables("source");
    if (targetSchema.value) await loadTables("target");
    if (generation !== initializingPrefillGeneration) return;
    // loadTables prefers the dialog's prefill table when present; the saved
    // config must win, so re-apply the selection and drop tables that vanished.
    const availableTables = config.selectedSourceTables.filter((table) => sourceTables.value.includes(table));
    resetSelectedSourceTables(availableTables);
    sourceTable.value = availableTables.length === 1 ? (availableTables[0] ?? "") : "";
    if (config.targetTable && targetTables.value.includes(config.targetTable)) targetTable.value = config.targetTable;
    keyColumnOverrides.value = normalizeKeyColumnOverrides(config.keyColumnsByTable);
    resetTableColumnMetadata();
    if (config.detailPreviewLimit) detailPreviewLimit.value = config.detailPreviewLimit;
    void prefetchSelectedTableColumns(selectedSourceTableNames.value);
  } catch (error) {
    toast(String(error), 5000);
  } finally {
    await nextTick();
    if (generation === initializingPrefillGeneration) initializingPrefill = false;
    suppressConfigSave = false;
  }
}

function handleDataCompareConfigSelect(id: string) {
  dataCompareConfigId.value = id;
  const config = dataCompareConfigs.value.find((item) => item.id === id);
  if (config) void applyDataCompareConfig(config);
}

function handleSaveDataCompareConfig() {
  createDataCompareConfig(t("dataCompare.defaultConfigName"), dataCompareConfigSnapshot());
  toast(t("dataCompare.configSaved"), 3000);
}

function handleRenameDataCompareConfig(id: string, name: string) {
  renameDataCompareConfig(id, name);
}

function handleDuplicateDataCompareConfig() {
  const id = dataCompareConfigId.value;
  if (id) duplicateDataCompareConfig(id);
}

function handleDeleteDataCompareConfig() {
  const id = dataCompareConfigId.value;
  // The form keeps the current selection; only the saved entry is removed so a
  // delete can never clear what the user is looking at.
  if (id) deleteDataCompareConfig(id);
}

function applyDataCompareSession(session: DataCompareSession | undefined): void {
  if (!session) return;
  batchResults.value = session.batchResults;
  syncPlan.value = session.syncPlan;
  if (session.status === "running") {
    comparing.value = true;
    compareProgressCurrent.value = session.progress?.current ?? 0;
    compareProgressTotal.value = session.progress?.total ?? 0;
    compareProgressTable.value = session.progress?.table ?? "";
    return;
  }
  comparing.value = false;
  compareProgressCurrent.value = 0;
  compareProgressTotal.value = 0;
  compareProgressTable.value = "";
  if (session.status === "failed" && session.error && shownSessionError !== session.error) {
    shownSessionError = session.error;
    toast(session.error, 5000);
  }
}

function swapSourceTarget() {
  if (comparing.value || executionLocked.value || initializingPrefill || pendingMetadataRequests.value > 0) return;
  const generation = ++initializingPrefillGeneration;
  initializingPrefill = true;
  const previousSelectedTables = [...selectedSourceTableNames.value];
  const nextSingleTarget = previousSelectedTables.length === 1 ? (previousSelectedTables[0] ?? "") : "";
  const nextSourceSelection = previousSelectedTables.length <= 1 ? [targetTable.value].filter(Boolean) : previousSelectedTables;

  const tmpConnId = sourceConnectionId.value;
  const tmpDb = sourceDatabase.value;
  const tmpDbs = sourceDatabases.value;
  const tmpSchema = sourceSchema.value;
  const tmpSchemas = sourceSchemas.value;
  const tmpTables = sourceTables.value;

  sourceConnectionId.value = targetConnectionId.value;
  sourceDatabase.value = targetDatabase.value;
  sourceDatabases.value = targetDatabases.value;
  sourceSchema.value = targetSchema.value;
  sourceSchemas.value = targetSchemas.value;
  sourceTables.value = targetTables.value;
  resetSelectedSourceTables(nextSourceSelection.filter((table) => targetTables.value.includes(table)));

  targetConnectionId.value = tmpConnId;
  targetDatabase.value = tmpDb;
  targetDatabases.value = tmpDbs;
  targetSchema.value = tmpSchema;
  targetSchemas.value = tmpSchemas;
  targetTables.value = tmpTables;
  targetTable.value = nextSingleTarget;

  sourceTable.value = selectedSourceTableNames.value.length === 1 ? selectedSourceTableNames.value[0] : "";
  keyColumnOverrides.value = {};
  resetTableColumnMetadata();
  clearResult();
  void nextTick(() => {
    if (generation !== initializingPrefillGeneration) return;
    initializingPrefill = false;
    if (dataCompareConfigId.value && !suppressConfigSave) updateDataCompareConfig(dataCompareConfigId.value, dataCompareConfigSnapshot());
    void prefetchSelectedTableColumns(selectedSourceTableNames.value);
  });
}

async function resolveSchema(connectionId: string, database: string, preferredSchema = ""): Promise<string> {
  const config = store.getConfig(connectionId);
  if (isSchemaAware(config?.db_type)) {
    const schemas = await api.listSchemas(connectionId, database);
    if (preferredSchema && schemas.includes(preferredSchema)) return preferredSchema;
    return schemas.includes("public") ? "public" : (schemas[0] ?? "");
  }
  return database;
}

async function loadSchemas(side: "source" | "target", preferredSchema = "") {
  const connectionId = side === "source" ? sourceConnectionId.value : targetConnectionId.value;
  const database = side === "source" ? sourceDatabase.value : targetDatabase.value;
  if (!connectionId || !database || !supportsDatabaseCompare(store.getConfig(connectionId), "data")) return;
  pendingMetadataRequests.value += 1;
  try {
    const isCurrent = metadataRequestIsCurrent(side);
    const config = store.getConfig(connectionId);
    if (!isSchemaAware(config?.db_type)) {
      if (side === "source") {
        sourceSchemas.value = [];
        sourceSchema.value = database;
      } else {
        targetSchemas.value = [];
        targetSchema.value = database;
      }
      await loadTables(side);
      return;
    }

    const schemas = await api.listSchemas(connectionId, database);
    if (!isCurrent()) return;
    const schema = preferredSchema && schemas.includes(preferredSchema) ? preferredSchema : schemas.includes("public") ? "public" : (schemas[0] ?? "");
    if (side === "source") {
      sourceSchemas.value = schemas;
      sourceSchema.value = schema;
    } else {
      targetSchemas.value = schemas;
      targetSchema.value = schema;
    }
  } finally {
    pendingMetadataRequests.value -= 1;
  }
}

async function loadDatabases(connectionId: string, side: "source" | "target") {
  if (!connectionId || !supportsDatabaseCompare(store.getConfig(connectionId), "data")) return;
  pendingMetadataRequests.value += 1;
  try {
    const isCurrent = metadataRequestIsCurrent(side);
    await store.ensureConnected(connectionId);
    if (!isCurrent()) return;
    const config = store.getConfig(connectionId);
    const names = config
      ? await fetchNamespaceOptionsForConnection(connectionId, config)
      : databaseOptionsForConnection(
          (await api.listDatabases(connectionId)).map((database) => database.name),
          config,
        );
    if (!isCurrent()) return;
    if (side === "source") {
      sourceDatabases.value = names;
      sourceDatabase.value = names.length === 1 ? names[0] : "";
      sourceSchemas.value = [];
      sourceSchema.value = "";
      sourceTables.value = [];
      sourceTable.value = "";
      resetSelectedSourceTables([]);
    } else {
      targetDatabases.value = names;
      targetDatabase.value = names.length === 1 ? names[0] : "";
      targetSchemas.value = [];
      targetSchema.value = "";
      targetTables.value = [];
      targetTable.value = "";
    }
  } finally {
    pendingMetadataRequests.value -= 1;
  }
}

async function loadTables(side: "source" | "target") {
  const connectionId = side === "source" ? sourceConnectionId.value : targetConnectionId.value;
  const database = side === "source" ? sourceDatabase.value : targetDatabase.value;
  if (!connectionId || !database || !supportsDatabaseCompare(store.getConfig(connectionId), "data")) return;
  pendingMetadataRequests.value += 1;
  try {
    const isCurrent = metadataRequestIsCurrent(side);
    const schema = side === "source" ? sourceSchema.value || (await resolveSchema(connectionId, database, props.prefillSchema)) : targetSchema.value || (await resolveSchema(connectionId, database));
    if (!isCurrent()) return;
    const tables = (await api.listTables(connectionId, database, schema)).filter((table) => table.table_type !== "VIEW" && table.table_type !== "MATERIALIZED_VIEW").map((table) => table.name);
    if (!isCurrent()) return;

    if (side === "source") {
      const preferredSelection = props.prefillTable && tables.includes(props.prefillTable) ? [props.prefillTable] : [...selectedSourceTables.value].filter((table) => tables.includes(table));
      sourceSchema.value = schema;
      sourceTables.value = tables;
      resetSelectedSourceTables(preferredSelection);
      sourceTable.value = preferredSelection.length === 1 ? preferredSelection[0] : "";
    } else {
      targetSchema.value = schema;
      targetTables.value = tables;
      const singleSourceTable = selectedSourceTableNames.value.length === 1 ? selectedSourceTableNames.value[0] : "";
      const preferred = targetTable.value && tables.includes(targetTable.value) ? targetTable.value : singleSourceTable && tables.includes(singleSourceTable) ? singleSourceTable : "";
      targetTable.value = preferred;
    }
  } finally {
    pendingMetadataRequests.value -= 1;
  }
}

function resultStatusLabel(status: DataCompareTableStatus): string {
  if (status === "different") return t("dataCompare.statusDifferent");
  if (status === "same") return t("dataCompare.statusSame");
  return t("dataCompare.statusError");
}

function resultStatusClass(status: DataCompareTableStatus): string {
  if (status === "different") return "bg-amber-500/15 text-amber-700";
  if (status === "same") return "bg-emerald-500/15 text-emerald-700";
  return "bg-destructive/15 text-destructive";
}

function hasDiffRows(table: DataCompareTableResult, kind: DiffKind): boolean {
  return table.diff[kind].length > 0;
}

function selectedRows(table: DataCompareTableResult, kind: DiffKind): number {
  return countCompareSelection(table.selection[kind], table.diff[kind].length);
}

function rowsForDisplay(table: DataCompareTableResult, kind: DiffKind) {
  const rows = table.diff[kind];
  return table.showAll[kind] ? rows : rows.slice(0, detailPreviewLimitNumber.value);
}

function remainingRows(table: DataCompareTableResult, kind: DiffKind) {
  return Math.max(0, table.diff[kind].length - rowsForDisplay(table, kind).length);
}

function toggleTableExpanded(table: DataCompareTableResult) {
  table.expanded = !table.expanded;
}

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) => {
    if (table.syncEligible) setCompareSelection(table.selection[kind], selected);
  });
  rebuildSyncPlan().catch((e) => toast(String(e), 5000));
}

function setTableDiffSelection(table: DataCompareTableResult, kind: DiffKind, selected: boolean) {
  if (executionLocked.value || !table.syncEligible) return;
  setCompareSelection(table.selection[kind], selected);
  rebuildSyncPlan().catch((e) => toast(String(e), 5000));
}

function clearAllSelections() {
  if (executionLocked.value) return;
  batchResults.value.forEach((table) => {
    for (const kind of ["added", "removed", "modified"] as DiffKind[]) setCompareSelection(table.selection[kind], false);
  });
  rebuildSyncPlan().catch((e) => toast(String(e), 5000));
}

// Diff arrays retain their order. A missing target can have duplicate match keys,
// so both virtual items and selection use row positions instead of SQL keys.
function diffRowKey(_row: DataCompareRow | DataCompareModifiedRow, index: number): number {
  return index;
}

function toggleRowSelection(table: DataCompareTableResult, kind: DiffKind, index: number) {
  if (executionLocked.value || !table.syncEligible) return;
  toggleCompareSelection(table.selection[kind], index);
  rebuildSyncPlan().catch((e) => toast(String(e), 5000));
}

function selectedDiffCount(kind: DiffKind) {
  return batchResults.value.reduce((sum, table) => sum + selectedRows(table, kind), 0);
}

function buildSyncPlanTables() {
  return buildDataCompareSyncPlanTables(batchResults.value, targetSchema.value);
}

function updateSyncPlan(nextPlan: DataCompareSyncPlan, sessionId = activeSessionId.value): void {
  if (!componentUnmounted) syncPlan.value = nextPlan;
  const session = getDataCompareSession(sessionId);
  if (session?.status === "completed") {
    session.syncPlan = nextPlan;
    session.batchResults = batchResults.value;
  }
}

async function rebuildSyncPlan() {
  if (componentUnmounted) return;
  const requestId = ++syncPlanRequestId;
  const sessionId = activeSessionId.value;
  const tables = buildSyncPlanTables();
  if (tables.length === 0) {
    updateSyncPlan(emptyDataCompareSyncPlan(), sessionId);
    planningSync.value = false;
    return;
  }
  planningSync.value = true;
  try {
    const plan = await api.buildDataCompareSyncPlan({ tables });
    if (requestId !== syncPlanRequestId) return;
    updateSyncPlan(plan, sessionId);
  } catch (e: any) {
    if (requestId !== syncPlanRequestId) return;
    updateSyncPlan(emptyDataCompareSyncPlan(), sessionId);
    if (!componentUnmounted) toast(e?.message || String(e), 5000);
  } finally {
    if (!componentUnmounted && requestId === syncPlanRequestId) planningSync.value = false;
  }
}

function startCompare(): void {
  if (!canCompare.value || comparing.value || executionLocked.value) return;
  const tasks = buildCompareTasks();
  if (tasks.length === 0) {
    toast(t("dataCompare.noComparableTables"), 5000);
    return;
  }

  clearResult();
  shownSessionError = "";
  const session = startDataCompareSession(
    {
      sourceConnectionId: sourceConnectionId.value,
      sourceDatabase: sourceDatabase.value,
      sourceSchema: sourceSchema.value,
      sourceDatabases: [...sourceDatabases.value],
      sourceSchemas: [...sourceSchemas.value],
      sourceTables: [...sourceTables.value],
      selectedSourceTables: [...selectedSourceTables.value],
      targetConnectionId: targetConnectionId.value,
      targetDatabase: targetDatabase.value,
      targetSchema: targetSchema.value,
      targetDatabases: [...targetDatabases.value],
      targetSchemas: [...targetSchemas.value],
      targetTables: [...targetTables.value],
      targetTable: targetTable.value,
      keyColumnsByTable: buildSessionKeyColumnsByTable(),
      label: `${comparisonEndpointLabel(sourceConnectionId.value, sourceDatabase.value, sourceSchema.value)} → ${comparisonEndpointLabel(targetConnectionId.value, targetDatabase.value, targetSchema.value)}`,
    },
    tasks,
    {
      ensureConnected: (connectionId) => store.ensureConnected(connectionId),
      getConfig: (connectionId) => store.getConfig(connectionId),
      formatError: (kind, columns) => {
        if (kind === "missingKeyColumns") return t("dataCompare.missingKeyColumns", { columns: columns ?? "" });
        return kind === "noCommonColumns" ? t("dataCompare.noCommonColumns") : t("dataCompare.noKeyColumns");
      },
    },
  );
  activeSessionId.value = session.id;
  applyDataCompareSession(session);
}

async function copySql() {
  try {
    await copyToClipboard(syncPlan.value.syncSql);
    toast(t("grid.copied"));
  } catch (e: any) {
    toast(t("grid.copyFailed", { message: e?.message || String(e) }), 5000);
  }
}

async function executeSql() {
  if (!syncPlan.value.syncSql.trim() || syncPlan.value.syncStatements.length === 0 || planningSync.value || comparing.value || executionLocked.value) return;
  const connectionId = targetConnectionId.value;
  const database = targetDatabase.value;
  const schema = targetSchema.value;
  const statements = [...syncPlan.value.syncStatements];
  const useTransaction = manualTransaction.value && canUseManualTransaction.value;
  const targetConnection = store.getConfig(connectionId);
  executing.value = true;
  executionInterrupted = false;
  transactionFailed.value = false;
  try {
    const failed = await executeWithProductionSqlGuard({
      connection: targetConnection,
      database,
      sql: syncPlan.value.syncSql,
      source: t("production.sourceDataCompare"),
      analyzeInBackground: true,
      execute: async () => {
        if (componentUnmounted || executionInterrupted) return undefined;
        syncErrors.value = [];
        executeTotal.value = statements.length;
        executedCount.value = 0;
        await store.ensureConnected(connectionId);
        if (useTransaction && (componentUnmounted || executionInterrupted)) return undefined;
        if (useTransaction) {
          txnSessionId.value = await api.beginManualTransaction(connectionId, database, schema);
          commitUncertain = false;
        }
        for (let index = 0; index < statements.length; index += SYNC_EXECUTE_BATCH_SIZE) {
          if (useTransaction && (componentUnmounted || executionInterrupted)) return undefined;
          const batch = statements.slice(index, index + SYNC_EXECUTE_BATCH_SIZE);
          try {
            if (useTransaction) await api.executeInManualTransaction(txnSessionId.value!, batch.join(";\n"), database, schema);
            else await api.executeBatch(connectionId, database, batch, schema);
            executedCount.value += batch.length;
          } catch (e: any) {
            // A failed manual transaction is rolled back by the backend. Never
            // replay its statements on an ordinary connection.
            if (useTransaction) throw e;
            for (const stmt of batch) {
              try {
                await api.executeBatch(connectionId, database, [stmt], schema);
              } catch (singleError: any) {
                syncErrors.value.push({ sql: stmt, error: singleError?.message || String(singleError) });
              }
              executedCount.value++;
            }
          }
        }
        return syncErrors.value.length;
      },
    });
    if (failed === undefined) return;
    if (failed === 0 && !txnSessionId.value) {
      toast(t("dataCompare.syncSuccess"), 2000);
    } else if (failed > 0) {
      toast(t("diff.syncSummary", { success: statements.length - failed, failed }), 5000);
    }
  } catch (e: any) {
    transactionFailed.value = true;
    toast(e?.message || String(e), 5000);
  } finally {
    if (txnSessionId.value && (transactionFailed.value || componentUnmounted || executionInterrupted)) await finishTransaction(false);
    executing.value = false;
  }
}

async function finishTransaction(commit: boolean): Promise<boolean> {
  const sessionId = txnSessionId.value;
  if (!sessionId || resolvingTransaction.value || (commit && (executing.value || transactionFailed.value))) return false;
  resolvingTransaction.value = true;
  try {
    let committed = false;
    let outcomeUnknown = false;
    try {
      if (commit) {
        await api.commitManualTransaction(sessionId);
        committed = true;
      } else await api.rollbackManualTransaction(sessionId);
    } catch (error) {
      if (!isManualTransactionSessionExpired(error) && formatError(error) !== "Transaction session not found") {
        if (commit) {
          commitUncertain = true;
          transactionFailed.value = true;
        }
        throw error;
      }
      outcomeUnknown = commitUncertain;
      if (outcomeUnknown) toast(t("toolbar.commitOutcomeUnknown"), 5000);
      else if (commit) toast(t("dataCompare.transactionEnded"), 5000);
    }
    txnSessionId.value = undefined;
    if (committed || outcomeUnknown) {
      const session = getDataCompareSession(activeSessionId.value);
      if (session) {
        session.batchResults = [];
        session.syncPlan = emptyDataCompareSyncPlan();
        session.version++;
      }
      clearResult();
      if (committed) toast(t("dataCompare.syncSuccess"), 2000);
    }
    return true;
  } catch (error) {
    toast(formatError(error), 5000);
    return false;
  } finally {
    resolvingTransaction.value = false;
  }
}

async function handleOpenChange(value: boolean) {
  if (!value && ((executing.value && manualTransaction.value) || resolvingTransaction.value)) return;
  if (!value && txnSessionId.value) {
    if (!window.confirm(t("dataCompare.rollbackBeforeClose")) || !(await finishTransaction(false))) return;
  }
  open.value = value;
}

watch(canUseManualTransaction, (supported) => {
  if (!supported && !executionLocked.value) manualTransaction.value = false;
});

function formatValue(value: DataCompareCellValue): string {
  if (value == null) return "NULL";
  if (typeof value === "string") return value;
  if (typeof value === "number" || typeof value === "boolean") return String(value);
  try {
    return JSON.stringify(value);
  } catch {
    return String(value);
  }
}

function truncateText(text: string, limit = 160): string {
  return text.length > limit ? `${text.slice(0, limit - 3)}...` : text;
}

function formatKeyValues(values: Record<string, DataCompareCellValue>): string {
  return Object.entries(values)
    .map(([column, value]) => `${column}=${formatValue(value)}`)
    .join(", ");
}

function formatRowValues(values: Record<string, DataCompareCellValue>): string {
  return truncateText(
    Object.entries(values)
      .map(([column, value]) => `${column}=${formatValue(value)}`)
      .join(", "),
  );
}

function formatModifiedSummary(row: DataCompareModifiedRow): string {
  return truncateText(row.changes.map((change) => `${change.column}: ${formatValue(change.target)} -> ${formatValue(change.source)}`).join(", "), 220);
}

watch(sourceConnectionId, (id) => {
  if (initializingPrefill) return;
  clearResult();
  sourceDatabases.value = [];
  sourceDatabase.value = "";
  sourceSchema.value = "";
  sourceSchemas.value = [];
  sourceTables.value = [];
  sourceTable.value = "";
  resetSelectedSourceTables([]);
  // Column metadata and match columns belong to the previous source endpoint.
  resetTableColumnMetadata();
  loadDatabases(id, "source").catch((e) => toast(String(e), 5000));
});
watch(targetConnectionId, (id) => {
  if (initializingPrefill) return;
  clearResult();
  targetDatabases.value = [];
  targetDatabase.value = "";
  targetSchema.value = "";
  targetSchemas.value = [];
  targetTables.value = [];
  targetTable.value = "";
  loadDatabases(id, "target").catch((e) => toast(String(e), 5000));
});
watch(sourceDatabase, () => {
  if (initializingPrefill) return;
  clearResult();
  sourceSchema.value = "";
  sourceSchemas.value = [];
  sourceTables.value = [];
  sourceTable.value = "";
  resetSelectedSourceTables([]);
  resetTableColumnMetadata();
  loadSchemas("source", props.prefillSchema).catch((e) => toast(String(e), 5000));
});
watch(targetDatabase, () => {
  if (initializingPrefill) return;
  clearResult();
  targetSchema.value = "";
  targetSchemas.value = [];
  targetTables.value = [];
  targetTable.value = "";
  loadSchemas("target").catch((e) => toast(String(e), 5000));
});
watch(sourceSchema, () => {
  if (initializingPrefill) return;
  clearResult();
  sourceTables.value = [];
  sourceTable.value = "";
  resetSelectedSourceTables([]);
  resetTableColumnMetadata();
  if (sourceSchema.value) loadTables("source").catch((e) => toast(String(e), 5000));
});
watch(targetSchema, () => {
  if (initializingPrefill) return;
  clearResult();
  targetTables.value = [];
  targetTable.value = "";
  if (targetSchema.value) loadTables("target").catch((e) => toast(String(e), 5000));
});
watch(selectedSourceTableNames, (tables, previous) => {
  if (initializingPrefill) return;
  clearResult();
  // Drop the match columns and metadata of tables that are no longer compared,
  // so a table that is selected again starts from its own primary key.
  pruneKeyColumnState(tables);
  sourceTable.value = tables.length === 1 ? tables[0] : "";
  if (tables.length !== 1) {
    void prefetchSelectedTableColumns(tables);
    return;
  }
  const table = tables[0];
  if (targetTables.value.includes(table)) {
    targetTable.value = table;
  } else if (previous?.length === 1 && targetTable.value === previous[0]) {
    targetTable.value = "";
  }
  void prefetchSelectedTableColumns(tables);
});
watch(targetTable, () => {
  if (initializingPrefill) return;
  clearResult();
});
// Keep the selected config in sync with the form so "saved" really means the
// current selection. Debounced because table multi-select toggles fire rapidly.
watch(
  () => [sourceConnectionId.value, sourceDatabase.value, sourceSchema.value, sourceTableSelection.value.join("\u0000"), targetConnectionId.value, targetDatabase.value, targetSchema.value, targetTable.value, detailPreviewLimit.value, JSON.stringify(keyColumnOverrides.value)],
  () => {
    if (suppressConfigSave || initializingPrefill || !dataCompareConfigId.value) return;
    if (configSaveTimer) clearTimeout(configSaveTimer);
    const configId = dataCompareConfigId.value;
    configSaveTimer = setTimeout(() => {
      configSaveTimer = undefined;
      if (componentUnmounted || configId !== dataCompareConfigId.value) return;
      updateDataCompareConfig(configId, dataCompareConfigSnapshot());
    }, 400);
  },
);
watch(
  [() => open.value, () => props.sessionId],
  async ([value, sessionId]) => {
    if (!value) {
      executionInterrupted = true;
      if (!executing.value && txnSessionId.value) void finishTransaction(false);
      return;
    }
    if (executionLocked.value) return;
    clearResult();
    shownSessionError = "";
    const session = getDataCompareSession(sessionId);
    if (session) {
      activeSessionId.value = session.id;
      await restoreDataCompareSession(session);
      applyDataCompareSession(session);
      return;
    }

    activeSessionId.value = null;
    if (props.prefillConnectionId) {
      const generation = ++initializingPrefillGeneration;
      initializingPrefill = true;
      // A prefill is an ad-hoc compare started from another screen; it must not
      // be silently written into whichever config happened to be selected.
      dataCompareConfigId.value = "";
      suppressConfigSave = true;
      try {
        sourceConnectionId.value = props.prefillConnectionId;
        if (!supportsDatabaseCompare(store.getConfig(props.prefillConnectionId), "data")) {
          sourceDatabase.value = sourceSchema.value = sourceTable.value = "";
          sourceDatabases.value = sourceSchemas.value = sourceTables.value = [];
          resetSelectedSourceTables([]);
          resetTableColumnMetadata();
          return;
        }
        await loadDatabases(props.prefillConnectionId, "source");
        if (props.prefillDatabase) sourceDatabase.value = props.prefillDatabase;
        if (props.prefillDatabase) await loadSchemas("source", props.prefillSchema);
        if (props.prefillTable) {
          await loadTables("source");
          if (sourceTables.value.includes(props.prefillTable)) {
            resetSelectedSourceTables([props.prefillTable]);
            sourceTable.value = props.prefillTable;
            await loadTableColumns(props.prefillTable);
          }
        }
      } finally {
        await nextTick();
        if (generation === initializingPrefillGeneration) initializingPrefill = false;
        suppressConfigSave = false;
      }
      return;
    }
    const savedConfig = activeDataCompareConfig.value;
    if (savedConfig) {
      await applyDataCompareConfig(savedConfig);
    }
  },
  { immediate: true },
);
watch(
  () => {
    const session = getDataCompareSession(activeSessionId.value);
    return session ? { id: session.id, version: session.version } : null;
  },
  () => {
    if (!componentUnmounted) applyDataCompareSession(getDataCompareSession(activeSessionId.value));
  },
  { immediate: true },
);
onBeforeUnmount(() => {
  componentUnmounted = true;
  if (configSaveTimer) clearTimeout(configSaveTimer);
  if (!executing.value && txnSessionId.value) void finishTransaction(false);
});
</script>

<template>
  <Dialog :open="open" @update:open="handleOpenChange">
    <DialogContent class="sm:max-w-5xl max-h-[85vh] flex flex-col overflow-hidden" @interact-outside.prevent>
      <DialogHeader>
        <DialogTitle class="flex items-center gap-2">
          <GitCompareArrows class="w-4 h-4" />
          {{ t("dataCompare.title") }}
        </DialogTitle>
      </DialogHeader>

      <div class="flex flex-wrap items-center gap-2 border-b pb-2">
        <DataCompareConfigSelector
          :configs="dataCompareConfigs"
          :active-config-id="dataCompareConfigId"
          :disabled="comparing || executionLocked"
          @update:active-config-id="handleDataCompareConfigSelect"
          @create="handleSaveDataCompareConfig"
          @rename="handleRenameDataCompareConfig"
          @duplicate="handleDuplicateDataCompareConfig"
          @delete="handleDeleteDataCompareConfig"
        />
      </div>

      <div class="flex-1 min-h-0 min-w-0 overflow-auto">
        <fieldset :disabled="executionLocked" class="space-y-4 py-2">
          <div class="grid grid-cols-[1fr_auto_1fr] gap-4 items-start">
            <div class="space-y-2 rounded-lg border border-blue-500/35 bg-blue-500/5 p-3">
              <div class="flex items-center gap-2 text-sm font-medium text-blue-600 dark:text-blue-400">
                <span class="inline-flex h-5 w-5 items-center justify-center rounded-full bg-blue-500/15 text-[11px] font-semibold">S</span>
                {{ t("diff.source") }}
              </div>
              <CompareConnectionSelect v-model="sourceConnectionId" :disabled="comparing || executionLocked" :connections="compareConnections" :layout="store.sidebarLayout" />
              <SearchableSelect
                v-model="sourceDatabase"
                :options="sourceDatabases"
                :placeholder="t('diff.selectDatabase')"
                :search-placeholder="t('diff.searchDatabase')"
                :empty-text="t('common.noResults')"
                :disabled="comparing || executionLocked || !sourceDatabases.length"
                trigger-variant="outline"
                trigger-class="h-8 w-full justify-between text-xs"
                content-class="w-[var(--reka-popover-trigger-width)]"
              />
              <SearchableSelect
                v-if="sourceSchemas.length"
                v-model="sourceSchema"
                :options="sourceSchemas"
                :disabled="comparing || executionLocked"
                :placeholder="t('diff.selectSchema')"
                :search-placeholder="t('diff.searchSchema')"
                :empty-text="t('common.noResults')"
                trigger-variant="outline"
                trigger-class="h-8 w-full justify-between text-xs"
                content-class="w-[var(--reka-popover-trigger-width)]"
              />

              <TableMultiSelect
                :key="`${sourceConnectionId}.${sourceDatabase}.${sourceSchema}`"
                v-model="sourceTableSelection"
                :tables="sourceTables"
                :title="t('dataCompare.sourceTables')"
                :empty-text="!sourceConnectionId || !sourceDatabase ? t('dataCompare.selectSourceTables') : t('dataCompare.noTables')"
                :disabled="comparing || executionLocked"
              />
            </div>

            <div class="flex items-center pt-6">
              <Button variant="ghost" size="icon" class="h-7 w-7" :title="t('diff.swap')" :disabled="comparing || executionLocked || pendingMetadataRequests > 0" @click="swapSourceTarget">
                <ArrowLeftRight class="w-3.5 h-3.5" />
              </Button>
            </div>

            <div class="space-y-2 rounded-lg border border-emerald-500/35 bg-emerald-500/5 p-3">
              <div class="flex items-center gap-2 text-sm font-medium text-emerald-600 dark:text-emerald-400">
                <span class="inline-flex h-5 w-5 items-center justify-center rounded-full bg-emerald-500/15 text-[11px] font-semibold">T</span>
                {{ t("diff.target") }}
              </div>
              <CompareConnectionSelect v-model="targetConnectionId" :disabled="comparing || executionLocked" :connections="compareConnections" :layout="store.sidebarLayout" />
              <SearchableSelect
                v-model="targetDatabase"
                :options="targetDatabases"
                :placeholder="t('diff.selectDatabase')"
                :search-placeholder="t('diff.searchDatabase')"
                :empty-text="t('common.noResults')"
                :disabled="comparing || executionLocked || !targetDatabases.length"
                trigger-variant="outline"
                trigger-class="h-8 w-full justify-between text-xs"
                content-class="w-[var(--reka-popover-trigger-width)]"
              />
              <SearchableSelect
                v-if="targetSchemas.length"
                v-model="targetSchema"
                :options="targetSchemas"
                :disabled="comparing || executionLocked"
                :placeholder="t('diff.selectSchema')"
                :search-placeholder="t('diff.searchSchema')"
                :empty-text="t('common.noResults')"
                trigger-variant="outline"
                trigger-class="h-8 w-full justify-between text-xs"
                content-class="w-[var(--reka-popover-trigger-width)]"
              />

              <div v-if="!isBatchCompare" class="space-y-1">
                <Label class="text-xs font-medium">{{ t("dataCompare.targetTable") }}</Label>
                <SearchableSelect
                  v-model="targetTable"
                  :options="targetTables"
                  :placeholder="t('dataCompare.selectTable')"
                  :search-placeholder="t('dataCompare.searchTable')"
                  :empty-text="t('common.noResults')"
                  :disabled="comparing || executionLocked"
                  trigger-variant="outline"
                  trigger-class="h-8 w-full justify-between text-xs"
                  content-class="w-[var(--reka-popover-trigger-width)]"
                />
              </div>
              <div v-else class="space-y-2 rounded-lg border p-3 text-xs">
                <div class="font-medium">{{ t("dataCompare.autoMatchHint") }}</div>
                <div class="text-muted-foreground">
                  {{ t("dataCompare.matchedTables", { matched: matchedTaskCount, total: selectedSourceTableNames.length }) }}
                </div>
                <div v-if="missingTargetTables.length" class="text-destructive">
                  {{ t("dataCompare.missingTargetTables", { tables: missingTargetTables.join(", ") }) }}
                </div>
                <div v-if="compareTasksPreview.length" class="max-h-36 overflow-auto rounded border bg-muted/20">
                  <div v-for="task in compareTasksPreview" :key="`${task.sourceTable}:${task.targetTable}`" class="flex items-center justify-between gap-2 border-b px-2 py-1 last:border-b-0">
                    <span class="truncate font-mono">{{ task.sourceTable }}</span>
                    <span class="text-muted-foreground">→</span>
                    <span class="truncate font-mono" :class="task.matched ? '' : 'text-destructive'">
                      {{ task.targetTable || t("dataCompare.targetTableMissing", { table: task.sourceTable }) }}
                    </span>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <div class="space-y-1">
            <div class="flex flex-wrap items-center gap-2">
              <Label class="text-xs font-medium">{{ t("dataCompare.keyColumns") }}</Label>
              <span v-if="singleKeyColumnRow" class="inline-flex items-center rounded px-1.5 py-0.5 text-[10px] font-medium" :class="singleKeyColumnRow.manual ? 'bg-primary/15 text-primary' : 'bg-muted text-muted-foreground'">
                {{ singleKeyColumnRow.manual ? t("dataCompare.keyColumnsStatusManual") : t("dataCompare.keyColumnsStatusAuto") }}
              </span>
              <Button v-if="singleKeyColumnRow?.manual" size="sm" variant="ghost" class="h-6 px-1.5 text-[11px]" :disabled="comparing || executionLocked" @click="clearTableKeyColumnsOverride(singleKeyColumnRow.table)">
                {{ t("dataCompare.keyColumnsResetAuto") }}
              </Button>
            </div>

            <div v-if="!selectedSourceTableNames.length" class="text-[11px] text-muted-foreground">
              {{ t("dataCompare.keyColumnsSelectTableHint") }}
            </div>

            <!-- Single table: pick match columns straight from the real database columns. -->
            <div v-else-if="singleKeyColumnRow" class="space-y-1">
              <CompareKeyColumnsSelect
                :model-value="singleKeyColumnRow.columns"
                :columns="columnsForTable(singleKeyColumnRow.table)"
                :loading="singleKeyColumnRow.loading"
                :disabled="comparing || executionLocked"
                @update:model-value="(columns) => setTableKeyColumns(singleKeyColumnRow!.table, columns)"
              />
              <div class="text-[11px]" data-key-column-hint :class="singleKeyColumnRow.error || singleKeyColumnRow.status === 'missing' ? 'text-destructive' : 'text-muted-foreground'">
                {{ singleKeyColumnRow.hint }}
              </div>
            </div>

            <!-- Batch compare: every table keeps its own match columns. -->
            <div v-else class="space-y-1">
              <div class="rounded-lg border">
                <div class="border-b bg-muted/20 px-2 py-1 text-[11px] text-muted-foreground">
                  {{ t("dataCompare.keyColumnsPerTableHint") }}
                </div>
                <div class="max-h-56 divide-y overflow-auto">
                  <div v-for="row in keyColumnRows" :key="row.table">
                    <button type="button" class="dbx-compare-key-table-row flex w-full items-center gap-2 px-2 py-1.5 text-left text-xs hover:bg-muted/40" :data-key-column-table="row.table" @click="toggleKeyColumnTable(row.table)">
                      <ChevronDown v-if="expandedKeyColumnTable === row.table" class="h-3.5 w-3.5 shrink-0" />
                      <ChevronRight v-else class="h-3.5 w-3.5 shrink-0" />
                      <span class="min-w-0 flex-1 truncate font-mono">{{ row.table }}</span>
                      <span class="min-w-0 max-w-[45%] shrink-0 truncate font-mono" :class="row.columns.length > 0 ? (row.manual ? 'text-foreground' : 'text-muted-foreground') : 'text-destructive'">
                        {{ row.loading ? t("dataCompare.keyColumnsLoading") : row.columns.length > 0 ? row.columns.join(", ") : t("dataCompare.keyColumnsNeedsSelection") }}
                      </span>
                      <span class="shrink-0 rounded px-1.5 py-0.5 text-[10px] font-medium" :class="row.status === 'manual' ? 'bg-primary/15 text-primary' : row.status === 'auto' ? 'bg-muted text-muted-foreground' : 'bg-destructive/15 text-destructive'">
                        {{ row.status === "manual" ? t("dataCompare.keyColumnsStatusManual") : row.status === "auto" ? t("dataCompare.keyColumnsStatusAuto") : t("dataCompare.keyColumnsNeedsSelection") }}
                      </span>
                    </button>
                    <div v-if="expandedKeyColumnTable === row.table" class="space-y-1 border-t bg-muted/10 px-2 py-2">
                      <CompareKeyColumnsSelect :model-value="row.columns" :columns="columnsForTable(row.table)" :loading="row.loading" :disabled="comparing || executionLocked" @update:model-value="(columns) => setTableKeyColumns(row.table, columns)" />
                      <div class="flex flex-wrap items-center gap-2 text-[11px]">
                        <span data-key-column-hint :class="row.error || (row.status === 'missing' && row.matched) ? 'text-destructive' : 'text-muted-foreground'">{{ row.hint }}</span>
                        <Button v-if="row.manual" size="sm" variant="ghost" class="h-6 px-1.5 text-[11px]" :disabled="comparing || executionLocked" @click="clearTableKeyColumnsOverride(row.table)">
                          {{ t("dataCompare.keyColumnsResetAuto") }}
                        </Button>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <div v-if="comparing" class="flex items-center gap-2 rounded-lg border border-primary/30 bg-primary/5 px-3 py-2 text-xs text-muted-foreground">
            <Loader2 class="h-3.5 w-3.5 animate-spin text-primary" />
            <span>{{ compareProgressLabel || t("diff.progress.comparing") }}</span>
          </div>

          <div v-if="hasResults" class="space-y-3">
            <div class="rounded-lg border p-3 text-sm space-y-2">
              <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">
              <div class="text-sm font-medium">{{ t("dataCompare.truncatedTitle") }}</div>
              <div>{{ t("dataCompare.truncatedHint") }}</div>
              <ul class="list-disc space-y-0.5 pl-4">
                <li v-for="item in truncatedResults" :key="`truncated-${item.sourceTable}:${item.targetTable}`">
                  {{
                    t("dataCompare.truncatedTable", {
                      table: item.sourceTable,
                      source: item.sourceRowCount,
                      target: item.targetRowCount,
                      budget: item.rowBudget,
                    })
                  }}
                </li>
              </ul>
            </div>

            <div class="rounded-lg border p-3 space-y-3">
              <div class="flex flex-wrap items-center gap-2">
                <Button size="sm" variant="outline" class="h-7 text-xs" :class="showAdded ? 'border-primary' : ''" @click="showAdded = !showAdded"> {{ t("diff.added") }} · {{ totalAdded }} </Button>
                <Button size="sm" variant="outline" class="h-7 text-xs" :class="showRemoved ? 'border-primary' : ''" @click="showRemoved = !showRemoved"> {{ t("diff.removed") }} · {{ totalRemoved }} </Button>
                <Button size="sm" variant="outline" class="h-7 text-xs" :class="showModified ? 'border-primary' : ''" @click="showModified = !showModified"> {{ t("diff.modified") }} · {{ totalModified }} </Button>
                <span class="flex-1" />
                <Select v-model="detailPreviewLimit">
                  <SelectTrigger class="h-7 w-32 text-xs">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem v-for="limit in PREVIEW_LIMIT_OPTIONS" :key="limit" :value="String(limit)">
                      {{ t("dataCompare.previewLimitOption", { count: limit }) }}
                    </SelectItem>
                  </SelectContent>
                </Select>
              </div>

              <div class="flex flex-wrap items-center gap-2">
                <Button size="sm" variant="outline" class="h-7 text-xs" @click="setDiffSelection('added', true)">
                  {{ t("dataCompare.selectAllKind", { kind: t("diff.added") }) }}
                </Button>
                <Button size="sm" variant="outline" class="h-7 text-xs" @click="setDiffSelection('removed', true)">
                  {{ t("dataCompare.selectAllKind", { kind: t("diff.removed") }) }}
                </Button>
                <Button size="sm" variant="outline" class="h-7 text-xs" @click="setDiffSelection('modified', true)">
                  {{ t("dataCompare.selectAllKind", { kind: t("diff.modified") }) }}
                </Button>
                <Button size="sm" variant="outline" class="h-7 text-xs" @click="clearAllSelections">
                  {{ t("dataCompare.clearSelection") }}
                </Button>
              </div>
            </div>

            <div class="rounded-lg border overflow-hidden">
              <div class="max-h-64 overflow-auto">
                <table class="w-full text-xs">
                  <thead class="bg-muted sticky top-0 z-10">
                    <tr>
                      <th class="px-3 py-2 text-left font-medium">{{ t("diff.table") }}</th>
                      <th class="px-3 py-2 text-left font-medium">{{ t("dataCompare.targetTable") }}</th>
                      <th class="px-3 py-2 text-left font-medium">{{ t("diff.status") }}</th>
                      <th class="px-3 py-2 text-left font-medium">{{ t("diff.details") }}</th>
                    </tr>
                  </thead>
                  <tbody>
                    <tr v-for="item in batchResults" :key="`${item.sourceTable}:${item.targetTable}`" class="border-t">
                      <td class="px-3 py-2 align-top font-mono">{{ item.sourceTable }}</td>
                      <td class="px-3 py-2 align-top font-mono text-muted-foreground">{{ item.targetTable }}</td>
                      <td class="px-3 py-2 align-top">
                        <span class="inline-flex rounded px-2 py-0.5 text-[11px]" :class="resultStatusClass(item.status)">
                          {{ resultStatusLabel(item.status) }}
                        </span>
                      </td>
                      <td class="px-3 py-2 align-top text-muted-foreground">
                        <div v-if="item.status === 'error'" class="text-destructive">{{ item.error }}</div>
                        <template v-else>
                          <div>
                            {{
                              t("dataCompare.summary", {
                                added: item.added,
                                removed: item.removed,
                                modified: item.modified,
                              })
                            }}
                          </div>
                          <div class="mt-1">
                            {{
                              t("dataCompare.rowCounts", {
                                source: item.sourceRowCount,
                                target: item.targetRowCount,
                              })
                            }}
                          </div>
                          <div v-if="item.sourceTruncated || item.targetTruncated" class="mt-1 text-amber-700 dark:text-amber-400">
                            {{ t("dataCompare.truncatedBadge", { budget: item.rowBudget }) }}
                          </div>
                          <div class="mt-1">
                            {{ t("dataCompare.keyColumnsInline", { columns: item.keyColumns.join(", ") }) }}
                          </div>
                          <div v-if="item.status === 'different'" class="mt-1">
                            {{
                              t("dataCompare.selectedInline", {
                                selected: selectedRows(item, "added") + selectedRows(item, "removed") + selectedRows(item, "modified"),
                                total: item.added + item.removed + item.modified,
                              })
                            }}
                          </div>
                        </template>
                      </td>
                    </tr>
                  </tbody>
                </table>
              </div>
            </div>

            <div class="space-y-3">
              <div v-for="item in batchResults.filter((entry) => entry.status === 'different')" :key="`details-${item.sourceTable}:${item.targetTable}`" class="rounded-lg border overflow-hidden">
                <button type="button" class="flex w-full items-center gap-2 border-b bg-muted/30 px-3 py-2 text-left text-sm font-medium" @click="toggleTableExpanded(item)">
                  <ChevronDown v-if="item.expanded" class="h-4 w-4 shrink-0" />
                  <ChevronRight v-else class="h-4 w-4 shrink-0" />
                  <span class="font-mono">{{ item.sourceTable }}</span>
                  <span class="text-muted-foreground">→</span>
                  <span class="font-mono text-muted-foreground">{{ item.targetTable }}</span>
                </button>

                <div v-if="item.expanded" class="space-y-3 p-3">
                  <div v-for="kind in visibleKinds" :key="`${item.sourceTable}:${kind}`" class="rounded-lg border" v-show="hasDiffRows(item, kind)">
                    <div class="flex flex-wrap items-center gap-2 border-b bg-muted/20 px-3 py-2 text-xs">
                      <span class="font-medium">{{ t(`diff.${kind}`) }}</span>
                      <span class="text-muted-foreground">{{ selectedRows(item, kind) }}/{{ item.diff[kind].length }}</span>
                      <span class="flex-1" />
                      <Button size="sm" variant="ghost" class="h-6 px-2 text-xs" :disabled="!item.syncEligible" @click="setTableDiffSelection(item, kind, true)">
                        {{ t("dataCompare.selectAllKind", { kind: t(`diff.${kind}`) }) }}
                      </Button>
                      <Button size="sm" variant="ghost" class="h-6 px-2 text-xs" :disabled="!item.syncEligible" @click="setTableDiffSelection(item, kind, false)">
                        {{ t("dataCompare.clearKind", { kind: t(`diff.${kind}`) }) }}
                      </Button>
                      <Button v-if="item.diff[kind].length > detailPreviewLimitNumber" size="sm" variant="ghost" class="h-6 px-2 text-xs" @click="toggleShowAll(item, kind)">
                        {{ item.showAll[kind] ? t("dataCompare.showLessRows") : t("dataCompare.showAllRows", { count: item.diff[kind].length }) }}
                      </Button>
                    </div>

                    <DynamicScroller :items="rowsForDisplay(item, kind)" :min-item-size="DIFF_ROW_MIN_HEIGHT" :key-field="diffRowKey" class="max-h-72 overflow-auto" :style="{ height: `${Math.min(rowsForDisplay(item, kind).length * DIFF_ROW_MIN_HEIGHT, DIFF_LIST_MAX_HEIGHT)}px` }">
                      <template #default="{ item: row, active, index }">
                        <DynamicScrollerItem :item="row" :index="index" :active="active" :data-index="index">
                          <button type="button" class="flex w-full items-start gap-3 px-3 py-2 text-left text-xs hover:bg-muted/40 disabled:cursor-not-allowed disabled:opacity-60" :disabled="!item.syncEligible" @click="toggleRowSelection(item, kind, index)">
                            <CheckSquare v-if="isCompareRowSelected(item.selection[kind], index)" class="mt-0.5 h-3.5 w-3.5 shrink-0 text-primary" />
                            <Square v-else class="mt-0.5 h-3.5 w-3.5 shrink-0 text-muted-foreground/40" />
                            <div class="min-w-0 flex-1">
                              <div class="font-mono">{{ formatKeyValues(row.keyValues) }}</div>
                              <div class="mt-1 text-muted-foreground break-words">
                                {{ kind === "modified" ? formatModifiedSummary(row as DataCompareModifiedRow) : formatRowValues((row as DataCompareRow).values) }}
                              </div>
                            </div>
                          </button>
                        </DynamicScrollerItem>
                      </template>
                    </DynamicScroller>

                    <div v-if="remainingRows(item, kind) > 0 && !item.showAll[kind]" class="border-t px-3 py-2 text-xs text-muted-foreground">
                      {{ t("dataCompare.remainingRows", { count: remainingRows(item, kind) }) }}
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <div v-if="planningSync" class="text-sm text-muted-foreground">
              {{ t("dataCompare.planningSync") }}
            </div>
            <div v-else-if="syncPlan.syncSql.trim()" class="space-y-1">
              <p v-if="sqlPreview.truncated" class="text-xs text-muted-foreground">{{ t("dangerDialog.previewTruncated", { lines: sqlPreview.omittedLines.toLocaleString(), characters: sqlPreview.omittedCharacters.toLocaleString() }) }}</p>
              <Label class="text-xs font-medium">{{ t("diff.generatedSql") }}</Label>
              <textarea :value="sqlPreviewText" readonly class="w-full h-48 rounded-[6px] border bg-muted/20 p-3 font-mono text-xs resize-none focus:outline-none focus:ring-1 focus:ring-ring" />
            </div>
            <div v-else-if="differentTableCount === 0 && failedTableCount === 0" class="text-sm text-muted-foreground">
              {{ t("dataCompare.noDifferences") }}
            </div>
            <div v-else class="text-sm text-muted-foreground">
              {{ t("dataCompare.noSelectedDifferences") }}
            </div>
          </div>

          <div v-if="syncErrors.length > 0" class="space-y-1">
            <Label class="text-xs font-medium text-destructive">
              {{ t("diff.syncSummary", { success: executeTotal - syncErrors.length, failed: syncErrors.length }) }}
            </Label>
            <div class="max-h-32 overflow-auto border rounded-lg bg-destructive/5 p-2 space-y-1">
              <div v-for="(err, i) in syncErrors" :key="i" class="text-xs font-mono">
                <span class="text-destructive">{{ err.error }}</span>
                <span class="text-muted-foreground ml-1">— {{ err.sql.slice(0, 80) }}{{ err.sql.length > 80 ? "..." : "" }}</span>
              </div>
            </div>
          </div>
        </fieldset>
      </div>

      <DialogFooter v-if="!hasResults">
        <Button variant="outline" size="sm" @click="handleOpenChange(false)">{{ t("common.close") }}</Button>
        <span v-if="compareProgressLabel" class="text-xs text-muted-foreground self-center">{{ compareProgressLabel }}</span>
        <Button size="sm" :disabled="!canCompare || comparing" @click="startCompare">
          <Loader2 v-if="comparing" class="w-3.5 h-3.5 animate-spin mr-1" />
          <GitCompareArrows v-else class="w-3.5 h-3.5 mr-1" />
          {{ t("dataCompare.compare") }}
        </Button>
      </DialogFooter>

      <DialogFooter v-else class="flex items-center gap-2">
        <Button variant="outline" size="sm" :disabled="(executing && manualTransaction) || resolvingTransaction" @click="handleOpenChange(false)">{{ t("common.close") }}</Button>
        <Button variant="outline" size="sm" :disabled="comparing || executionLocked || !canCompare" @click="startCompare">
          <Loader2 v-if="comparing" class="w-3 h-3 animate-spin mr-1" />
          <RotateCcw v-else class="w-3 h-3 mr-1" />
          {{ t("dataCompare.recompare") }}
        </Button>
        <span v-if="comparing" class="text-xs text-muted-foreground mr-auto">{{ compareProgressLabel || t("diff.progress.comparing") }}</span>
        <span v-else-if="executing" class="text-xs text-muted-foreground mr-auto">
          {{ t("diff.syncProgress", { current: executedCount, total: executeTotal }) }}
        </span>
        <span v-else-if="planningSync" class="text-xs text-muted-foreground mr-auto">
          {{ t("dataCompare.planningSync") }}
        </span>
        <span v-else class="text-xs text-muted-foreground mr-auto">
          {{
            t("dataCompare.planSummary", {
              inserts: syncPlan.insertCount,
              updates: syncPlan.updateCount,
              deletes: syncPlan.deleteCount,
              statements: syncPlan.statementCount,
            })
          }}
        </span>
        <Button variant="outline" size="sm" :disabled="!syncPlan.syncSql.trim()" @click="copySql"> <Copy class="w-3 h-3 mr-1" /> {{ t("diff.copySql") }} </Button>
        <template v-if="txnSessionId && !executing">
          <span class="text-xs text-muted-foreground">{{ t("dataCompare.pendingTransaction") }}</span>
          <Button variant="outline" size="sm" :disabled="resolvingTransaction" @click="finishTransaction(false)">{{ t("toolbar.rollback") }}</Button>
          <Button size="sm" :disabled="resolvingTransaction || transactionFailed" @click="finishTransaction(true)">{{ t("toolbar.commit") }}</Button>
        </template>
        <label v-else-if="canUseManualTransaction" class="flex items-center gap-2 text-xs" :title="t('dataCompare.manualTransactionHint')">
          <input v-model="manualTransaction" type="checkbox" :disabled="executionLocked" />
          {{ t("toolbar.manualTransaction") }}
        </label>
        <Button v-if="!txnSessionId" size="sm" :disabled="planningSync || comparing || executionLocked || syncPlan.statementCount === 0" @click="executeSql">
          <Loader2 v-if="executing" class="w-3 h-3 animate-spin mr-1" />
          <Play v-else class="w-3 h-3 mr-1" />
          {{ t("diff.executeSync") }}
        </Button>
      </DialogFooter>
    </DialogContent>
  </Dialog>
</template>