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。

55.4 KB
Raw Blame
<script setup lang="ts">
import { computed, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import { Label } from "@/components/ui/label";
import { Button } from "@/components/ui/button";
import { Switch } from "@/components/ui/switch";
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 TableMultiSelect from "@/components/diff/TableMultiSelect.vue";
import { buildSchemaDiffTableMatches, availableSchemaDiffTargetTables, areSchemaDiffTableMappingsEqual, pruneSchemaDiffTableMappings, reconcileSchemaDiffTableMappings, updateSchemaDiffTableMapping, type SchemaDiffTableMatch } from "@/lib/schema/schemaDiffTableMapping";
import {
  areSchemaDiffRoutineMappingsEqual,
  buildSchemaDiffRoutineMatches,
  identitySchemaDiffRoutineMappings,
  isSchemaDiffUnrestrictedRoutineLoadTooLarge,
  pruneSchemaDiffRoutineMappings,
  reconcileSchemaDiffRoutineMappings,
  reconcileSchemaDiffSelectedRoutines,
  schemaDiffRoutineKey,
  schemaDiffRoutineKeyFromFunction,
  SCHEMA_DIFF_UNRESTRICTED_ROUTINE_LIMIT,
  type SchemaDiffRoutineMatch,
} from "@/lib/schema/schemaDiffRoutine";
import { createSchemaDiffTableListCoordinator, reconcileSchemaDiffSelectedTables, shouldLoadSchemaDiffTableList, type SchemaDiffTableIdentity, type SchemaDiffTableListLoader, type SchemaDiffTableSide } from "@/lib/schema/schemaDiffTableList";
import { schemaDiffRoutineObjectTypes, schemaDiffRoutineObjectTypesIntersection, supportsSchemaDiffRoutines, schemaDiffRoutineProductType } from "@/lib/database/databaseObjectCapabilities";
import { schemaDiffEngineDatabaseType } from "@/lib/schema/schemaDiff";
import { useConnectionStore } from "@/stores/connectionStore";
import DatabaseIcon from "@/components/icons/DatabaseIcon.vue";
import * as api from "@/lib/backend/api";
import { isSchemaAware } from "@/lib/database/databaseCapabilities";
import { fetchNamespaceOptionsForConnection } from "@/composables/useDatabaseOptions";
import { ArrowLeftRight, GitCompareArrows, Save, FolderOpen, Settings, Trash2, X } from "@lucide/vue";
import type { SchemaDiffConfig, SchemaDiffCompareOptions, FieldMappingEntry, SchemaDiffTableMapping, SchemaDiffRoutineMapping, OracleRoutineKind, OracleRoutineIdentity } from "@/types/schemaDiff";
import type { DatabaseType } from "@/types/database";

const { t } = useI18n();
const store = useConnectionStore();

const props = defineProps<{
  configs: SchemaDiffConfig[];
  activeConfigId: string;
  sourceConnectionId: string;
  sourceDatabase: string;
  sourceSchema: string;
  targetConnectionId: string;
  targetDatabase: string;
  targetSchema: string;
  ignoreComments: boolean;
  options: SchemaDiffCompareOptions;
  selectedTables?: string[];
  selectedRoutines?: string[];
  tableListLoader: SchemaDiffTableListLoader;
  loading: boolean;
  recentConfigs: SchemaDiffConfig[];
}>();

const emit = defineEmits<{
  (e: "update:sourceConnectionId", value: string): void;
  (e: "update:sourceDatabase", value: string): void;
  (e: "update:sourceSchema", value: string): void;
  (e: "update:targetConnectionId", value: string): void;
  (e: "update:targetDatabase", value: string): void;
  (e: "update:targetSchema", value: string): void;
  (e: "update:ignoreComments", value: boolean): void;
  (e: "update:fieldMappings", value: FieldMappingEntry[]): void;
  (e: "update:tableMappings", value: SchemaDiffTableMapping[]): void;
  (e: "update:routineMappings", value: SchemaDiffRoutineMapping[]): void;
  (e: "open-field-mapping"): void;
  (e: "compare"): void;
  (e: "saveConfig"): void;
  (e: "loadConfig"): void;
  (e: "showOptions"): void;
  (e: "swap"): void;
  (e: "loadHistoryConfig", config: SchemaDiffConfig): void;
  (e: "deleteHistoryConfig", configId: string): void;
  (e: "update:selectedTables", value?: string[]): void;
  (e: "update:selectedRoutines", value?: string[]): void;
  (e: "update:routineSelection", value: { objectKinds: OracleRoutineKind[]; selectedObjects?: Pick<OracleRoutineIdentity, "name" | "kind">[] }): void;
  (e: "update:compareScope", value: { tables?: boolean; views?: boolean; functions?: boolean }): void;
}>();

const sourceDatabases = ref<string[]>([]);
const sourceSchemas = ref<string[]>([]);
const targetDatabases = ref<string[]>([]);
const targetSchemas = ref<string[]>([]);
const sourceDbVersion = ref<string | null>(null);
const targetDbVersion = ref<string | null>(null);

const compareConnections = computed(() => store.connections.filter((connection) => supportsDatabaseCompare(connection, "schema")));

type MetadataScope = "connection" | "database" | "schema";
const metadataGenerations = {
  source: { connection: 0, database: 0, schema: 0 },
  target: { connection: 0, database: 0, schema: 0 },
};
for (const side of ["source", "target"] as const) {
  watch(
    () => (side === "source" ? [props.sourceConnectionId, props.sourceDatabase, props.sourceSchema] : [props.targetConnectionId, props.targetDatabase, props.targetSchema]),
    (current, previous) => {
      const connectionChanged = current[0] !== previous[0];
      const databaseChanged = connectionChanged || current[1] !== previous[1];
      if (connectionChanged) metadataGenerations[side].connection += 1;
      if (databaseChanged) metadataGenerations[side].database += 1;
      if (databaseChanged || current[2] !== previous[2]) metadataGenerations[side].schema += 1;
    },
    { flush: "sync" },
  );
}

// Only invalidate a request when its own inputs change. Selecting a schema
// must not discard an in-flight database or schema list for the same endpoint.
function metadataRequestIsCurrent(side: "source" | "target", scope: MetadataScope = "schema"): () => boolean {
  const generation = metadataGenerations[side][scope];
  const connectionId = side === "source" ? props.sourceConnectionId : props.targetConnectionId;
  return () => generation === metadataGenerations[side][scope] && supportsDatabaseCompare(store.getConfig(connectionId), "schema");
}

const sourceConfig = computed(() => store.getConfig(props.sourceConnectionId));
const targetConfig = computed(() => store.getConfig(props.targetConnectionId));

const sourceDbType = computed(() => sourceConfig.value?.db_type || "");
const targetDbType = computed(() => targetConfig.value?.db_type || "");
const showFieldMapping = computed(() => sourceDbType.value && targetDbType.value && sourceDbType.value !== targetDbType.value);
const activeFieldMappings = computed(() => props.options?.fieldMappings ?? []);

// ---- Visual (explicit) table selection ----
const sourceTableList = ref<string[]>([]);
const targetTableList = ref<string[]>([]);
const targetTableListLoaded = ref(false);
const restrictTables = ref(false);
const localSelectedTables = ref<string[]>([]);

const activeTableMappings = computed(() => props.options?.tableMappings ?? []);
const tableMatches = computed<SchemaDiffTableMatch[]>(() => buildSchemaDiffTableMatches(localSelectedTables.value, targetTableList.value, activeTableMappings.value, props.options.ignoreTableNameCase));
const matchedTableCount = computed(() => tableMatches.value.filter((match) => match.targetTable).length);
const missingTargetTables = computed(() => tableMatches.value.filter((match) => !match.targetTable).map((match) => match.sourceTable));
const tableMappingConflictSource = ref<string | null>(null);

function targetTableOptions(sourceTable: string): string[] {
  return availableSchemaDiffTargetTables(sourceTable, targetTableList.value, activeTableMappings.value, props.options.ignoreTableNameCase);
}

function handleTableMappingUpdate(sourceTable: string, targetTable: string) {
  const update = updateSchemaDiffTableMapping(activeTableMappings.value, sourceTable, targetTable, props.options.ignoreTableNameCase);
  if (update.accepted) {
    tableMappingConflictSource.value = null;
    emitTableMappings(update.mappings);
  } else {
    tableMappingConflictSource.value = update.conflictSource ?? sourceTable;
  }
}

function emitTableMappings(nextMappings: SchemaDiffTableMapping[]) {
  if (!areSchemaDiffTableMappingsEqual(nextMappings, activeTableMappings.value)) emit("update:tableMappings", nextMappings);
}

function reconcileTableMappings(selectedTables: string[], targetTables = targetTableList.value) {
  const nextMappings = targetTableListLoaded.value ? reconcileSchemaDiffTableMappings(selectedTables, targetTables, activeTableMappings.value, props.options.ignoreTableNameCase) : pruneSchemaDiffTableMappings(selectedTables, activeTableMappings.value);
  emitTableMappings(nextMappings);
}

// Keep the visual restriction in sync with the (persisted) config options.
// `undefined` = not restricted (compare all tables, then regex filter);
// an array = explicitly restricted to exactly those tables.
watch(
  () => props.selectedTables,
  (value) => {
    restrictTables.value = Array.isArray(value);
    localSelectedTables.value = value && Array.isArray(value) ? [...value] : [];
    if (!restrictTables.value) emitTableMappings([]);
    else if (targetTableListLoaded.value) reconcileTableMappings(localSelectedTables.value);
  },
  { immediate: true },
);

watch(
  () => props.options?.tableMappings,
  () => {
    if (restrictTables.value && targetTableListLoaded.value) reconcileTableMappings(localSelectedTables.value);
  },
  { deep: true },
);

function handleToggleRestrict(enabled: boolean) {
  restrictTables.value = enabled;
  emit("update:selectedTables", enabled ? [...localSelectedTables.value] : undefined);
  if (!enabled) emitTableMappings([]);
  else reconcileTableMappings(localSelectedTables.value);
}

function handleUpdateSelectedTables(value: string[]) {
  localSelectedTables.value = value;
  if (!restrictTables.value) return;
  emit("update:selectedTables", [...value]);
  reconcileTableMappings(value);
}

function handleRemoveSelectedTable(sourceTable: string) {
  handleUpdateSelectedTables(localSelectedTables.value.filter((table) => table !== sourceTable));
}

function matchStatusClass(kind: SchemaDiffTableMatch["kind"]): string {
  if (kind === "unmatched") return "text-destructive";
  if (kind === "manual") return "text-amber-600 dark:text-amber-400";
  return "text-muted-foreground";
}

function clearUnavailableTableSelection() {
  sourceTableList.value = [];
  targetTableList.value = [];
  targetTableListLoaded.value = false;
  if (props.selectedTables === undefined && !restrictTables.value && localSelectedTables.value.length === 0) {
    emitTableMappings([]);
    return;
  }
  restrictTables.value = false;
  localSelectedTables.value = [];
  emit("update:selectedTables", undefined);
  emitTableMappings([]);
}

function getTableIdentity(side: SchemaDiffTableSide): SchemaDiffTableIdentity {
  return side === "source" ? { connectionId: props.sourceConnectionId, database: props.sourceDatabase, schema: props.sourceSchema } : { connectionId: props.targetConnectionId, database: props.targetDatabase, schema: props.targetSchema };
}

function isTableIdentityReady(side: SchemaDiffTableSide): boolean {
  const identity = getTableIdentity(side);
  const config = side === "source" ? sourceConfig.value : targetConfig.value;
  return supportsDatabaseCompare(config, "schema") && !!identity.connectionId && !!identity.database && (!isSchemaAware(config?.db_type) || !!identity.schema);
}

function setTableList(side: SchemaDiffTableSide, tables: Array<{ name?: string }>) {
  const names = tables.map((entry) => entry.name ?? "").filter(Boolean);
  if (side === "source") sourceTableList.value = names;
  else {
    targetTableList.value = names;
    targetTableListLoaded.value = false;
  }
}

function reconcileSelectedTablesAfterSuccessfulLoad(tables: Array<{ name?: string }>) {
  const availableTables = tables.map((entry) => entry.name ?? "").filter(Boolean);
  let selectedTables = localSelectedTables.value;
  if (restrictTables.value && Array.isArray(props.selectedTables)) {
    const nextSelectedTables = reconcileSchemaDiffSelectedTables(props.selectedTables, availableTables);
    const changed = nextSelectedTables.length !== props.selectedTables.length || nextSelectedTables.some((table, index) => table !== props.selectedTables?.[index]);
    selectedTables = nextSelectedTables;
    localSelectedTables.value = nextSelectedTables;
    if (changed) emit("update:selectedTables", nextSelectedTables);
  }
  if (restrictTables.value) reconcileTableMappings(selectedTables);
}

function reconcileTargetTablesAfterSuccessfulLoad(tables: Array<{ name?: string }>) {
  targetTableListLoaded.value = true;
  reconcileTableMappings(localSelectedTables.value, tables.map((entry) => entry.name ?? "").filter(Boolean));
}

const tableListCoordinator = createSchemaDiffTableListCoordinator({
  loader: props.tableListLoader,
  getIdentity: getTableIdentity,
  setTables: setTableList,
  onSourceTablesLoaded: reconcileSelectedTablesAfterSuccessfulLoad,
  onTargetTablesLoaded: reconcileTargetTablesAfterSuccessfulLoad,
});

const canConfigureTableSelection = computed(() => isTableIdentityReady("source"));
const tablesCompareEnabled = computed(() => !!props.options.tables);
const routinesCompareEnabled = computed(() => !!props.options.functions);
const sourceRoutineType = computed(() => schemaDiffRoutineProductType(sourceDbType.value, schemaDiffEngineDatabaseType(sourceConfig.value)));
const targetRoutineType = computed(() => schemaDiffRoutineProductType(targetDbType.value, schemaDiffEngineDatabaseType(targetConfig.value)));
const availableRoutineKinds = computed(() => schemaDiffRoutineObjectTypesIntersection(sourceRoutineType.value, targetRoutineType.value, ["PROCEDURE", "FUNCTION", "PACKAGE", "PACKAGE_BODY"]));
const routineKinds = computed(() => props.options.routineObjectKinds ?? schemaDiffRoutineObjectTypesIntersection(sourceRoutineType.value, targetRoutineType.value));
const typedRoutines = computed(() => props.options.routineObjectKinds !== undefined);
const canEnableRoutinesCompare = computed(() => availableRoutineKinds.value.length > 0);
/** User preference AND supported pair — drives compare/canCompare/Switch display. */
const effectiveRoutinesEnabled = computed(() => routinesCompareEnabled.value && canEnableRoutinesCompare.value);

watch(
  () => [tablesCompareEnabled.value, restrictTables.value, props.sourceConnectionId, props.sourceDatabase, props.sourceSchema, sourceDbType.value],
  () => {
    const shouldLoad = tablesCompareEnabled.value && shouldLoadSchemaDiffTableList("source", restrictTables.value, localSelectedTables.value.length, isTableIdentityReady("source"));
    tableListCoordinator.refresh("source", shouldLoad).catch(() => {});
  },
  { immediate: true },
);

watch(
  () => [tablesCompareEnabled.value, restrictTables.value, localSelectedTables.value.length, props.targetConnectionId, props.targetDatabase, props.targetSchema, targetDbType.value],
  () => {
    const shouldLoad = tablesCompareEnabled.value && shouldLoadSchemaDiffTableList("target", restrictTables.value, localSelectedTables.value.length, isTableIdentityReady("target"));
    tableListCoordinator.refresh("target", shouldLoad).catch(() => {});
  },
  { immediate: true },
);

// ---- Visual (explicit) routine selection ----
const sourceRoutineList = ref<string[]>([]);
const targetRoutineList = ref<string[]>([]);
const targetRoutineListLoaded = ref(false);
const restrictRoutines = ref(false);
const localSelectedRoutines = ref<string[]>([]);
const loadingRoutines = ref(false);
type ProgramSelection = Pick<OracleRoutineIdentity, "name" | "kind">;
const routineIdentities = { source: ref<Record<string, ProgramSelection>>({}), target: ref<Record<string, ProgramSelection>>({}) };
const routineRequests = { source: 0, target: 0 };
for (const side of ["source", "target"] as const) {
  watch(
    () => [side === "source" ? props.sourceConnectionId : props.targetConnectionId, side === "source" ? props.sourceDatabase : props.targetDatabase, side === "source" ? props.sourceSchema : props.targetSchema, JSON.stringify(props.options.routineObjectKinds)],
    () => {
      routineRequests[side]++;
      routineIdentities[side].value = {};
      if (side === "source") sourceRoutineList.value = [];
      else {
        targetRoutineList.value = [];
        targetRoutineListLoaded.value = false;
      }
    },
    { flush: "sync" },
  );
}
const exactRoutineKey = (identity: ProgramSelection) => schemaDiffRoutineKeyFromFunction({ name: identity.name, function_type: identity.kind, arguments: "" }, true);
const selectedRoutineKeys = computed(() => (typedRoutines.value ? props.options.selectedRoutineObjects?.map(exactRoutineKey) : props.selectedRoutines));
const routineLabels = computed<Record<string, string>>(() => {
  if (!typedRoutines.value) return {};
  const identities = { ...routineIdentities.target.value, ...routineIdentities.source.value };
  for (const identity of props.options.selectedRoutineObjects ?? []) identities[exactRoutineKey(identity)] = identity;
  return Object.fromEntries(Object.entries(identities).map(([key, identity]) => [key, `${identity.kind.replaceAll("_", " ")} ${identity.name}`]));
});

function emitRoutineSelection(keys: string[] | undefined) {
  if (!typedRoutines.value) {
    emit("update:selectedRoutines", keys);
    return;
  }
  emit("update:routineSelection", {
    objectKinds: [...routineKinds.value],
    selectedObjects: keys?.flatMap((key) => {
      const identity = routineIdentities.source.value[key];
      return identity ? [{ ...identity }] : [];
    }),
  });
}

function toggleRoutineKind(kind: OracleRoutineKind, enabled: boolean) {
  const kinds = availableRoutineKinds.value.filter((candidate) => (candidate === kind ? enabled : routineKinds.value.includes(candidate)));
  const selectedObjects = restrictRoutines.value
    ? localSelectedRoutines.value.flatMap((key) => {
        const identity = routineIdentities.source.value[key];
        return identity && kinds.includes(identity.kind) ? [{ ...identity }] : [];
      })
    : undefined;
  emit("update:routineSelection", { objectKinds: kinds, selectedObjects });
}

const canConfigureRoutineSelection = computed(() => isTableIdentityReady("source") && supportsSchemaDiffRoutines(sourceRoutineType.value));
const activeRoutineMappings = computed(() => identitySchemaDiffRoutineMappings(props.options?.routineMappings ?? []));
const routineMatches = computed<SchemaDiffRoutineMatch[]>(() => buildSchemaDiffRoutineMatches(localSelectedRoutines.value, targetRoutineList.value, activeRoutineMappings.value));
const matchedRoutineCount = computed(() => routineMatches.value.filter((match) => match.targetRoutine).length);
const missingTargetRoutines = computed(() => routineMatches.value.filter((match) => !match.targetRoutine).map((match) => match.sourceRoutine));

function emitRoutineMappings(nextMappings: SchemaDiffRoutineMapping[]) {
  const identityOnly = identitySchemaDiffRoutineMappings(nextMappings);
  if (!areSchemaDiffRoutineMappingsEqual(identityOnly, activeRoutineMappings.value)) emit("update:routineMappings", identityOnly);
}

function reconcileRoutineMappings(selectedRoutines: string[], targetRoutines = targetRoutineList.value) {
  const nextMappings = targetRoutineListLoaded.value ? reconcileSchemaDiffRoutineMappings(selectedRoutines, targetRoutines, activeRoutineMappings.value) : pruneSchemaDiffRoutineMappings(selectedRoutines, activeRoutineMappings.value);
  emitRoutineMappings(nextMappings);
}

watch(
  () => selectedRoutineKeys.value,
  (value) => {
    restrictRoutines.value = Array.isArray(value);
    localSelectedRoutines.value = value && Array.isArray(value) ? [...value] : [];
    if (!restrictRoutines.value) emitRoutineMappings([]);
    else if (targetRoutineListLoaded.value) reconcileRoutineMappings(localSelectedRoutines.value);
  },
  { immediate: true },
);

watch(
  () => props.options?.routineMappings,
  () => {
    if (restrictRoutines.value && targetRoutineListLoaded.value) reconcileRoutineMappings(localSelectedRoutines.value);
  },
  { deep: true },
);

function handleToggleRestrictRoutines(enabled: boolean) {
  restrictRoutines.value = enabled;
  emitRoutineSelection(enabled ? [...localSelectedRoutines.value] : undefined);
  if (!enabled) emitRoutineMappings([]);
  else reconcileRoutineMappings(localSelectedRoutines.value);
}

function handleUpdateSelectedRoutines(value: string[]) {
  localSelectedRoutines.value = value;
  if (!restrictRoutines.value) return;
  emitRoutineSelection([...value]);
  reconcileRoutineMappings(value);
}

function handleRemoveSelectedRoutine(sourceRoutine: string) {
  handleUpdateSelectedRoutines(localSelectedRoutines.value.filter((routine) => routine !== sourceRoutine));
}

function clearUnavailableRoutineSelection() {
  routineRequests.source++;
  routineRequests.target++;
  routineIdentities.source.value = {};
  routineIdentities.target.value = {};
  sourceRoutineList.value = [];
  targetRoutineList.value = [];
  targetRoutineListLoaded.value = false;
  if (selectedRoutineKeys.value === undefined && !restrictRoutines.value && localSelectedRoutines.value.length === 0) {
    emitRoutineMappings([]);
    return;
  }
  restrictRoutines.value = false;
  localSelectedRoutines.value = [];
  emitRoutineSelection(undefined);
  emitRoutineMappings([]);
}

async function loadRoutineList(side: "source" | "target") {
  const request = ++routineRequests[side];
  const exactKinds = typedRoutines.value;
  const requestedKinds = exactKinds ? [...routineKinds.value] : undefined;
  const connectionId = side === "source" ? props.sourceConnectionId : props.targetConnectionId;
  const database = side === "source" ? props.sourceDatabase : props.targetDatabase;
  const schema = side === "source" ? props.sourceSchema : props.targetSchema;
  const dbType = side === "source" ? sourceRoutineType.value : targetRoutineType.value;
  if (!isTableIdentityReady(side) || !supportsSchemaDiffRoutines(dbType as DatabaseType)) {
    if (side === "source") sourceRoutineList.value = [];
    else {
      targetRoutineList.value = [];
      targetRoutineListLoaded.value = false;
    }
    return;
  }
  const endpointIsCurrent = metadataRequestIsCurrent(side);
  const isCurrent = () => endpointIsCurrent() && request === routineRequests[side] && JSON.stringify(requestedKinds) === JSON.stringify(typedRoutines.value ? routineKinds.value : undefined);
  try {
    loadingRoutines.value = true;
    await store.ensureConnected(connectionId);
    if (!isCurrent()) return;
    // Names/signatures only — avoid listFunctions N+1 source fetch on the config step.
    const kinds = schemaDiffRoutineObjectTypes(dbType as DatabaseType, requestedKinds);
    const objects = kinds.length === 0 ? [] : await api.listObjects(connectionId, database, schema, kinds);
    if (!isCurrent()) return;
    const identities: Record<string, ProgramSelection> = {};
    const keys = objects.map((object) => {
      const kind = (object.object_type ?? "").replaceAll(" ", "_").toUpperCase() as OracleRoutineKind;
      if (exactKinds && !kinds.includes(kind)) throw new Error("Program listing returned an unexpected object kind");
      const key = exactKinds ? exactRoutineKey({ name: object.name, kind }) : schemaDiffRoutineKey(object.name, object.signature ?? "");
      if (kinds.includes(kind)) identities[key] = { name: object.name, kind };
      return key;
    });
    routineIdentities[side].value = identities;
    if (side === "source") {
      sourceRoutineList.value = keys;
      if (restrictRoutines.value) {
        const next = reconcileSchemaDiffSelectedRoutines(localSelectedRoutines.value, keys);
        if (next.length !== localSelectedRoutines.value.length || next.some((key, index) => key !== localSelectedRoutines.value[index])) {
          localSelectedRoutines.value = next;
          emitRoutineSelection([...next]);
        }
      }
    } else {
      targetRoutineList.value = keys;
      targetRoutineListLoaded.value = true;
      if (restrictRoutines.value) reconcileRoutineMappings(localSelectedRoutines.value, keys);
    }
  } catch {
    if (!isCurrent()) return;
    if (side === "source") sourceRoutineList.value = [];
    else {
      targetRoutineList.value = [];
      targetRoutineListLoaded.value = false;
    }
  } finally {
    loadingRoutines.value = false;
  }
}

watch(
  () => [restrictRoutines.value, effectiveRoutinesEnabled.value, props.sourceConnectionId, props.sourceDatabase, props.sourceSchema, sourceRoutineType.value, JSON.stringify(props.options.routineObjectKinds)] as const,
  ([restrictEnabled, routinesEnabled]) => {
    if (!canConfigureRoutineSelection.value) {
      clearUnavailableRoutineSelection();
      return;
    }
    // Load names whenever routines are effectively on (count guard + restrict picker).
    if (routinesEnabled || restrictEnabled) void loadRoutineList("source");
  },
  { immediate: true },
);

watch(
  () => [restrictRoutines.value, localSelectedRoutines.value.length, props.targetConnectionId, props.targetDatabase, props.targetSchema, targetRoutineType.value, JSON.stringify(props.options.routineObjectKinds)] as const,
  ([enabled, selectedCount]) => {
    if (!enabled || selectedCount === 0 || !isTableIdentityReady("target") || !supportsSchemaDiffRoutines(targetRoutineType.value)) {
      if (!enabled) {
        targetRoutineList.value = [];
        targetRoutineListLoaded.value = false;
      }
      return;
    }
    void loadRoutineList("target");
  },
  { immediate: true },
);

watch(
  () => ({
    source: [props.sourceConnectionId, props.sourceDatabase, props.sourceSchema] as const,
    selectedRoutines: selectedRoutineKeys.value,
  }),
  (current, previous) => {
    if (!isTableIdentityReady("source") || !supportsSchemaDiffRoutines(sourceRoutineType.value)) {
      clearUnavailableRoutineSelection();
      return;
    }
    if (!previous) return;
    if (current.source.every((value, index) => value === previous.source[index])) return;
    if (current.selectedRoutines !== previous.selectedRoutines) return;
    if (current.selectedRoutines === undefined && !restrictRoutines.value) return;
    clearUnavailableRoutineSelection();
  },
  { immediate: true },
);

function handleTablesCompareEnabled(enabled: boolean) {
  if (enabled) emit("update:compareScope", { tables: true });
  else emit("update:compareScope", { tables: false, views: false });
}

function handleRoutinesCompareEnabled(enabled: boolean) {
  if (enabled && !canEnableRoutinesCompare.value) return;
  emit("update:compareScope", { functions: enabled });
}

const unrestrictedRoutineLoadTooLarge = computed(() => {
  if (!effectiveRoutinesEnabled.value || restrictRoutines.value) return false;
  return isSchemaDiffUnrestrictedRoutineLoadTooLarge(sourceRoutineList.value.length, selectedRoutineKeys.value);
});

const canCompare = computed(() => {
  const tablesEnabled = tablesCompareEnabled.value;
  const routinesEnabled = effectiveRoutinesEnabled.value;
  if (!tablesEnabled && !routinesEnabled) return false;
  if (unrestrictedRoutineLoadTooLarge.value) return false;
  const hasSelectedTables = !tablesEnabled || props.selectedTables === undefined || props.selectedTables.length > 0;
  const hasSelectedRoutines = !routinesEnabled || (routineKinds.value.length > 0 && (selectedRoutineKeys.value === undefined || selectedRoutineKeys.value.length > 0));
  // Unmapped source tables are not a blocker: they flow through the comparison as
  // source-only tables (CREATE TABLE in the target), matching the pre-mapping behavior.
  const hasValidTableMappings = !tablesEnabled || !restrictTables.value || localSelectedTables.value.length === 0 || isTableIdentityReady("target");
  const hasValidRoutineMappings = !routinesEnabled || !restrictRoutines.value || localSelectedRoutines.value.length === 0 || isTableIdentityReady("target");
  return (
    supportsDatabaseCompare(sourceConfig.value, "schema") &&
    supportsDatabaseCompare(targetConfig.value, "schema") &&
    props.sourceConnectionId &&
    props.targetConnectionId &&
    props.sourceDatabase &&
    props.targetDatabase &&
    hasSelectedTables &&
    hasSelectedRoutines &&
    hasValidTableMappings &&
    hasValidRoutineMappings &&
    (!isSchemaAware(sourceConfig.value?.db_type) || props.sourceSchema) &&
    (!isSchemaAware(targetConfig.value?.db_type) || props.targetSchema)
  );
});

async function loadDatabases(connectionId: string, side: "source" | "target") {
  if (!connectionId || !supportsDatabaseCompare(store.getConfig(connectionId), "schema")) return;
  const isCurrent = metadataRequestIsCurrent(side, "connection");
  try {
    await store.ensureConnected(connectionId);
    if (!isCurrent()) return;
    const config = store.getConfig(connectionId);
    const dbNames = config ? await fetchNamespaceOptionsForConnection(connectionId, config) : (await api.listDatabases(connectionId)).map((db) => db.name);
    if (!isCurrent()) return;
    if (side === "source") {
      sourceDatabases.value = dbNames;
      if (props.sourceDatabase) {
        await fetchDbVersion(connectionId, props.sourceDatabase, props.sourceSchema, "source");
        // Ensure schema list is loaded after databases are available (handles race with sourceDatabase watcher)
        if (isSchemaAware(sourceConfig.value?.db_type)) {
          await loadSchemas("source");
        }
      }
    } else {
      targetDatabases.value = dbNames;
      if (props.targetDatabase) {
        await fetchDbVersion(connectionId, props.targetDatabase, props.targetSchema, "target");
        // Ensure schema list is loaded after databases are available (handles race with targetDatabase watcher)
        if (isSchemaAware(targetConfig.value?.db_type)) {
          await loadSchemas("target");
        }
      }
    }
  } catch {
    if (!isCurrent()) return;
    if (side === "source") {
      sourceDatabases.value = [];
      sourceDbVersion.value = null;
    } else {
      targetDatabases.value = [];
      targetDbVersion.value = null;
    }
  }
}

async function loadSchemas(side: "source" | "target") {
  const connectionId = side === "source" ? props.sourceConnectionId : props.targetConnectionId;
  const database = side === "source" ? props.sourceDatabase : props.targetDatabase;
  const schema = side === "source" ? props.sourceSchema : props.targetSchema;
  if (!connectionId || !database || !supportsDatabaseCompare(store.getConfig(connectionId), "schema")) return;
  const isCurrent = metadataRequestIsCurrent(side, "database");

  try {
    await store.ensureConnected(connectionId);
    if (!isCurrent()) return;
    const schemas = await api.listSchemas(connectionId, database);
    if (!isCurrent()) return;
    if (side === "source") {
      sourceSchemas.value = schemas;
    } else {
      targetSchemas.value = schemas;
    }
    await fetchDbVersion(connectionId, database, schema, side);
  } catch {
    if (!isCurrent()) return;
    if (side === "source") {
      sourceSchemas.value = [];
    } else {
      targetSchemas.value = [];
    }
  }
}

watch(
  () => props.sourceConnectionId,
  async (id) => {
    sourceDatabases.value = [];
    sourceSchemas.value = [];
    sourceDbVersion.value = null;
    if (id) {
      await loadDatabases(id, "source");
    } else {
      sourceDatabases.value = [];
    }
  },
  { immediate: true },
);

watch(
  () => props.sourceDatabase,
  async (db) => {
    if (db && props.sourceConnectionId) {
      await loadSchemas("source");
    } else {
      sourceSchemas.value = [];
    }
  },
  { immediate: true },
);

watch(
  () => props.targetConnectionId,
  async (id) => {
    targetDatabases.value = [];
    targetSchemas.value = [];
    targetDbVersion.value = null;
    if (id) {
      await loadDatabases(id, "target");
    } else {
      targetDatabases.value = [];
    }
  },
  { immediate: true },
);

// A visual selection belongs to the current source connection/database/schema. Clear it
// when that identity changes so a saved table name cannot silently restrict a different
// source. If the source and selected tables change together, it is a saved-config load;
// let the selectedTables watcher restore that config instead of clearing it again.
watch(
  () => ({
    source: [props.sourceConnectionId, props.sourceDatabase, props.sourceSchema] as const,
    selectedTables: props.selectedTables,
  }),
  (current, previous) => {
    if (!isTableIdentityReady("source")) {
      clearUnavailableTableSelection();
      return;
    }
    if (!previous) return;
    if (current.source.every((value, index) => value === previous.source[index])) return;
    if (current.selectedTables !== previous.selectedTables) return;
    if (current.selectedTables === undefined && !restrictTables.value) return;
    clearUnavailableTableSelection();
  },
  { immediate: true },
);

watch(
  () => props.targetDatabase,
  async (db) => {
    if (db && props.targetConnectionId) {
      await loadSchemas("target");
    } else {
      targetSchemas.value = [];
    }
  },
  { immediate: true },
);

function connectionIconType(connectionId: string) {
  const c = store.getConfig(connectionId);
  return c?.driver_profile || c?.db_type || "mysql";
}

function getConnectionInfo(connectionId: string) {
  const c = store.getConfig(connectionId);
  if (!c) return null;
  return {
    name: c.name,
    dbType: c.db_type,
    host: c.host,
    port: c.port,
  };
}

async function fetchDbVersion(connectionId: string, database: string, schema: string, side: "source" | "target") {
  if (!supportsDatabaseCompare(store.getConfig(connectionId), "schema")) return;
  const isCurrent = metadataRequestIsCurrent(side);
  try {
    await store.ensureConnected(connectionId);
    const config = store.getConfig(connectionId);
    const dbType = config?.db_type;
    let sql = "";
    switch (dbType) {
      case "postgres":
      case "opengauss":
        sql = "SELECT version()";
        break;
      case "mysql":
        sql = "SELECT VERSION()";
        break;
      case "sqlite":
        sql = "SELECT sqlite_version()";
        break;
      default:
        return;
    }
    if (!isCurrent()) return;
    const result = await api.executeQuery(connectionId, database, sql, schema || undefined);
    if (!isCurrent()) return;
    if (result.rows && result.rows.length > 0) {
      const version = String(result.rows[0][0]);
      if (side === "source") {
        sourceDbVersion.value = version;
      } else {
        targetDbVersion.value = version;
      }
    }
  } catch (e) {
    if (!isCurrent()) return;
    console.error(`[fetchDbVersion] Failed to fetch version for ${side}:`, e);
    if (side === "source") {
      sourceDbVersion.value = null;
    } else {
      targetDbVersion.value = null;
    }
  }
}
</script>

<template>
  <div class="space-y-4">
    <!-- Header -->
    <div class="flex items-center justify-center gap-4 py-2">
      <div class="text-center">
        <div class="text-xs text-muted-foreground">{{ sourceConfig?.name || t("diff.source") }}</div>
        <div class="text-xs font-medium">{{ sourceDatabase }}{{ sourceSchema ? `.${sourceSchema}` : "" }}</div>
      </div>
      <div class="flex items-center gap-2">
        <DatabaseIcon v-if="sourceConnectionId" :db-type="connectionIconType(sourceConnectionId)" class="w-5 h-5" />
        <ArrowLeftRight class="w-4 h-4 text-muted-foreground" />
        <DatabaseIcon v-if="targetConnectionId" :db-type="connectionIconType(targetConnectionId)" class="w-5 h-5" />
      </div>
      <div class="text-center">
        <div class="text-xs text-muted-foreground">{{ targetConfig?.name || t("diff.target") }}</div>
        <div class="text-xs font-medium">{{ targetDatabase }}{{ targetSchema ? `.${targetSchema}` : "" }}</div>
      </div>
    </div>

    <!-- Source / Target Selection -->
    <div class="grid grid-cols-[1fr_auto_1fr] gap-4 items-start">
      <!-- Source Side -->
      <div class="space-y-3">
        <div class="text-sm font-medium text-blue-500">{{ t("diff.source") }}</div>

        <div class="space-y-1.5">
          <Label class="text-xs">{{ t("diff.connection") }}</Label>
          <CompareConnectionSelect :model-value="sourceConnectionId" @update:model-value="(v: string) => $emit('update:sourceConnectionId', v)" :connections="compareConnections" :layout="store.sidebarLayout" :disabled="loading" />
        </div>

        <div class="space-y-1.5">
          <Label class="text-xs">{{ t("diff.database") }}</Label>
          <SearchableSelect
            :model-value="sourceDatabase"
            @update:model-value="(v: string) => $emit('update:sourceDatabase', v)"
            :options="sourceDatabases"
            :placeholder="t('diff.selectDatabase')"
            :search-placeholder="t('diff.searchDatabase')"
            :empty-text="t('common.noResults')"
            :disabled="!sourceDatabases.length"
            trigger-variant="outline"
            trigger-class="h-8 w-full justify-between text-xs"
            content-class="w-[var(--reka-popover-trigger-width)]"
          />
        </div>

        <div v-if="isSchemaAware(sourceConfig?.db_type)" class="space-y-1.5">
          <Label class="text-xs">{{ t("diff.schema") }}</Label>
          <SearchableSelect
            :model-value="sourceSchema"
            @update:model-value="(v: string) => $emit('update:sourceSchema', v)"
            :options="sourceSchemas"
            :placeholder="t('diff.selectSchema')"
            :search-placeholder="t('diff.searchSchema')"
            :empty-text="t('common.noResults')"
            :disabled="!sourceSchemas.length"
            trigger-variant="outline"
            trigger-class="h-8 w-full justify-between text-xs"
            content-class="w-[var(--reka-popover-trigger-width)]"
          />
        </div>

        <!-- Source Info -->
        <div v-if="getConnectionInfo(sourceConnectionId)" class="mt-4 p-3 rounded-lg bg-muted/30 border space-y-1.5">
          <div class="text-xs font-medium text-blue-500">{{ t("diff.info") }}</div>
          <div class="grid grid-cols-[80px_1fr] gap-x-2 gap-y-0.5 text-xs">
            <span class="text-muted-foreground">{{ t("diff.connType") }}</span>
            <span>{{ getConnectionInfo(sourceConnectionId)?.dbType }}</span>
            <span class="text-muted-foreground">{{ t("diff.connName") }}</span>
            <span>{{ getConnectionInfo(sourceConnectionId)?.name }}</span>
            <span class="text-muted-foreground">{{ t("diff.host") }}</span>
            <span>{{ getConnectionInfo(sourceConnectionId)?.host }}</span>
            <span class="text-muted-foreground">{{ t("diff.port") }}</span>
            <span>{{ getConnectionInfo(sourceConnectionId)?.port }}</span>
            <span class="text-muted-foreground">{{ t("diff.serverVersion") }}</span>
            <span>{{ sourceDbVersion || "--" }}</span>
          </div>
        </div>
      </div>

      <!-- Swap Button -->
      <div class="pt-8">
        <Button variant="ghost" size="icon" class="h-8 w-8" @click="$emit('swap')">
          <ArrowLeftRight class="w-4 h-4" />
        </Button>
      </div>

      <!-- Target Side -->
      <div class="space-y-3">
        <div class="text-sm font-medium text-green-500">{{ t("diff.target") }}</div>

        <div class="space-y-1.5">
          <Label class="text-xs">{{ t("diff.connection") }}</Label>
          <CompareConnectionSelect :model-value="targetConnectionId" @update:model-value="(v: string) => $emit('update:targetConnectionId', v)" :connections="compareConnections" :layout="store.sidebarLayout" :disabled="loading" />
        </div>

        <div class="space-y-1.5">
          <Label class="text-xs">{{ t("diff.database") }}</Label>
          <SearchableSelect
            :model-value="targetDatabase"
            @update:model-value="(v: string) => $emit('update:targetDatabase', v)"
            :options="targetDatabases"
            :placeholder="t('diff.selectDatabase')"
            :search-placeholder="t('diff.searchDatabase')"
            :empty-text="t('common.noResults')"
            :disabled="!targetDatabases.length"
            trigger-variant="outline"
            trigger-class="h-8 w-full justify-between text-xs"
            content-class="w-[var(--reka-popover-trigger-width)]"
          />
        </div>

        <div v-if="isSchemaAware(targetConfig?.db_type)" class="space-y-1.5">
          <Label class="text-xs">{{ t("diff.schema") }}</Label>
          <SearchableSelect
            :model-value="targetSchema"
            @update:model-value="(v: string) => $emit('update:targetSchema', v)"
            :options="targetSchemas"
            :placeholder="t('diff.selectSchema')"
            :search-placeholder="t('diff.searchSchema')"
            :empty-text="t('common.noResults')"
            :disabled="!targetSchemas.length"
            trigger-variant="outline"
            trigger-class="h-8 w-full justify-between text-xs"
            content-class="w-[var(--reka-popover-trigger-width)]"
          />
        </div>

        <!-- Target Info -->
        <div v-if="getConnectionInfo(targetConnectionId)" class="mt-4 p-3 rounded-lg bg-muted/30 border space-y-1.5">
          <div class="text-xs font-medium text-green-500">{{ t("diff.info") }}</div>
          <div class="grid grid-cols-[80px_1fr] gap-x-2 gap-y-0.5 text-xs">
            <span class="text-muted-foreground">{{ t("diff.connType") }}</span>
            <span>{{ getConnectionInfo(targetConnectionId)?.dbType }}</span>
            <span class="text-muted-foreground">{{ t("diff.connName") }}</span>
            <span>{{ getConnectionInfo(targetConnectionId)?.name }}</span>
            <span class="text-muted-foreground">{{ t("diff.host") }}</span>
            <span>{{ getConnectionInfo(targetConnectionId)?.host }}</span>
            <span class="text-muted-foreground">{{ t("diff.port") }}</span>
            <span>{{ getConnectionInfo(targetConnectionId)?.port }}</span>
            <span class="text-muted-foreground">{{ t("diff.serverVersion") }}</span>
            <span>{{ targetDbVersion || "--" }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- Comparison Scope -->
    <div class="space-y-3 rounded-lg border bg-muted/20 p-3">
      <div class="space-y-1.5">
        <div class="flex items-center justify-between gap-2">
          <div class="flex min-w-0 items-center gap-2">
            <Switch size="sm" :model-value="tablesCompareEnabled" :aria-label="t('diff.compareTablesSwitch')" @update:model-value="handleTablesCompareEnabled(Boolean($event))" />
            <Label class="text-xs font-medium">{{ t("diff.tableSelection") }}</Label>
          </div>
          <Button v-if="tablesCompareEnabled && (restrictTables || canConfigureTableSelection)" variant="ghost" size="sm" class="h-6 px-2 text-xs" @click="handleToggleRestrict(!restrictTables)">
            {{ restrictTables ? t("diff.compareAllTables") : t("diff.chooseTables") }}
          </Button>
        </div>
        <div v-if="!tablesCompareEnabled" class="text-[11px] text-muted-foreground">
          {{ t("diff.tableCompareDisabled") }}
        </div>
        <template v-else>
          <div v-if="!restrictTables" class="text-[11px] text-muted-foreground">
            {{ t("diff.tableSelectionUnrestricted") }}
          </div>
          <TableMultiSelect
            v-if="restrictTables && canConfigureTableSelection"
            :key="`${sourceConnectionId}.${sourceDatabase}.${sourceSchema}`"
            :model-value="localSelectedTables"
            @update:model-value="handleUpdateSelectedTables"
            :tables="sourceTableList"
            :title="t('diff.sourceTables')"
            :empty-text="t('dataCompare.noTables')"
          />
        </template>
      </div>

      <!-- Target Same-Name Match -->
      <!-- Source → target table mapping -->
      <div v-if="tablesCompareEnabled && restrictTables && localSelectedTables.length && canConfigureTableSelection && isTableIdentityReady('target')" class="space-y-2 rounded-lg border p-3 text-xs">
        <div class="flex items-center justify-between gap-2">
          <div class="font-medium">{{ t("diff.targetTableMatching") }}</div>
          <div class="text-muted-foreground">
            {{ t("diff.matchedTables", { matched: matchedTableCount, total: localSelectedTables.length }) }}
          </div>
        </div>
        <div class="overflow-x-auto rounded border">
          <table class="w-full min-w-[520px]">
            <thead class="border-b bg-muted/30 text-muted-foreground">
              <tr>
                <th class="px-2 py-1.5 text-left font-medium">{{ t("diff.sourceTables") }}</th>
                <th class="px-2 py-1.5 text-left font-medium">{{ t("diff.targetTable") }}</th>
                <th class="w-28 px-2 py-1.5 text-left font-medium">{{ t("diff.status") }}</th>
                <th class="w-16 px-2 py-1.5 text-right font-medium">{{ t("common.actions") }}</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="match in tableMatches" :key="match.sourceTable" class="border-b last:border-b-0">
                <td class="max-w-[220px] truncate px-2 py-1.5 font-mono" :title="match.sourceTable">{{ match.sourceTable }}</td>
                <td class="px-2 py-1.5">
                  <SearchableSelect
                    :model-value="match.targetTable ?? ''"
                    @update:model-value="(value: string) => handleTableMappingUpdate(match.sourceTable, value)"
                    :options="targetTableOptions(match.sourceTable)"
                    :placeholder="t('diff.selectTargetTable')"
                    :search-placeholder="t('diff.searchTargetTable')"
                    :empty-text="t('diff.noTargetTables')"
                    :disabled="!targetTableListLoaded"
                    :clearable="true"
                    :clear-selected-option="true"
                    trigger-class="h-7 w-full text-xs"
                    content-class="w-[var(--reka-popover-trigger-width)]"
                  />
                </td>
                <td class="px-2 py-1.5" :class="matchStatusClass(match.kind)">
                  {{ t(`diff.tableMatchStatus.${match.kind}`) }}
                </td>
                <td class="px-2 py-1.5 text-right">
                  <Button variant="ghost" size="sm" class="h-7 w-7 p-0" :aria-label="t('common.delete')" @click="handleRemoveSelectedTable(match.sourceTable)">
                    <Trash2 class="h-3.5 w-3.5" />
                  </Button>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
        <div v-if="targetTableListLoaded && missingTargetTables.length" class="text-muted-foreground">
          {{ t("diff.unmatchedTableWarning", { count: missingTargetTables.length }) }}
        </div>
        <div v-if="tableMappingConflictSource" class="text-destructive">
          {{ t("diff.targetTableInUse") }}
        </div>
      </div>

      <div class="space-y-1.5 border-t border-border/60 pt-3">
        <div class="flex items-center justify-between gap-2">
          <div class="flex min-w-0 items-center gap-2">
            <Switch
              size="sm"
              :model-value="typedRoutines ? routinesCompareEnabled : effectiveRoutinesEnabled"
              :disabled="!canEnableRoutinesCompare && !(typedRoutines && routinesCompareEnabled)"
              :aria-label="t('diff.compareRoutinesSwitch')"
              @update:model-value="handleRoutinesCompareEnabled(Boolean($event))"
            />
            <Label class="text-xs font-medium" :class="!canEnableRoutinesCompare ? 'text-muted-foreground' : ''">{{ t("diff.routineSelection") }}</Label>
          </div>
          <Button v-if="effectiveRoutinesEnabled && (restrictRoutines || canConfigureRoutineSelection)" variant="ghost" size="sm" class="h-6 px-2 text-xs" :disabled="loadingRoutines" @click="handleToggleRestrictRoutines(!restrictRoutines)">
            {{ restrictRoutines ? t("diff.compareAllRoutines") : t("diff.chooseRoutines") }}
          </Button>
        </div>
        <div v-if="!canEnableRoutinesCompare" class="text-[11px] text-muted-foreground">
          {{ t("diff.routineSelectionUnsupported") }}
        </div>
        <div v-else-if="!routinesCompareEnabled" class="text-[11px] text-muted-foreground">
          {{ t("diff.routineCompareDisabled") }}
        </div>
        <template v-else>
          <div v-if="availableRoutineKinds.includes('PACKAGE')" class="flex flex-wrap gap-x-4 gap-y-2">
            <label v-for="kind in availableRoutineKinds" :key="kind" class="flex items-center gap-2 text-xs">
              <input type="checkbox" class="accent-primary" :data-program-kind="kind" :checked="routineKinds.includes(kind)" :disabled="loadingRoutines" @change="toggleRoutineKind(kind, ($event.target as HTMLInputElement).checked)" />
              {{ kind.replaceAll("_", " ") }}
            </label>
          </div>
          <div v-if="!restrictRoutines" class="text-[11px] text-muted-foreground">
            {{ !isTableIdentityReady("source") ? t("diff.routineSelectionNeedSource") : t("diff.routineSelectionUnrestricted") }}
          </div>
          <div v-if="unrestrictedRoutineLoadTooLarge" class="rounded-md border border-amber-500/40 bg-amber-500/10 px-2 py-1.5 text-[11px] text-amber-700 dark:text-amber-300">
            {{ t("diff.routineSelectionTooLarge", { count: sourceRoutineList.length, limit: SCHEMA_DIFF_UNRESTRICTED_ROUTINE_LIMIT }) }}
          </div>
          <TableMultiSelect
            v-if="restrictRoutines && canConfigureRoutineSelection"
            :key="`routines-${sourceConnectionId}.${sourceDatabase}.${sourceSchema}`"
            :model-value="localSelectedRoutines"
            @update:model-value="handleUpdateSelectedRoutines"
            :tables="sourceRoutineList"
            :disabled="loadingRoutines"
            :labels="typedRoutines ? routineLabels : undefined"
            :title="t('diff.sourceRoutines')"
            :search-placeholder="t('diff.searchSourceRoutines')"
            :empty-text="t('diff.noRoutines')"
          />
        </template>
      </div>

      <div v-if="effectiveRoutinesEnabled && restrictRoutines && localSelectedRoutines.length && canConfigureRoutineSelection && isTableIdentityReady('target')" class="space-y-2 rounded-lg border p-3 text-xs">
        <div class="flex items-center justify-between gap-2">
          <div class="font-medium">{{ t("diff.targetRoutineMatching") }}</div>
          <div class="text-muted-foreground">
            {{ t("diff.matchedRoutines", { matched: matchedRoutineCount, total: localSelectedRoutines.length }) }}
          </div>
        </div>
        <p class="text-[11px] text-muted-foreground">{{ t("diff.routineSameNameMatchingOnly") }}</p>
        <div class="overflow-x-auto rounded border">
          <table class="w-full min-w-[520px]">
            <thead class="border-b bg-muted/30 text-muted-foreground">
              <tr>
                <th class="px-2 py-1.5 text-left font-medium">{{ t("diff.sourceRoutines") }}</th>
                <th class="px-2 py-1.5 text-left font-medium">{{ t("diff.targetRoutine") }}</th>
                <th class="w-28 px-2 py-1.5 text-left font-medium">{{ t("diff.status") }}</th>
                <th class="w-16 px-2 py-1.5 text-right font-medium">{{ t("common.actions") }}</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="match in routineMatches" :key="match.sourceRoutine" class="border-b last:border-b-0">
                <td class="max-w-[220px] truncate px-2 py-1.5 font-mono" :title="routineLabels[match.sourceRoutine] ?? match.sourceRoutine">{{ routineLabels[match.sourceRoutine] ?? match.sourceRoutine }}</td>
                <td class="max-w-[220px] truncate px-2 py-1.5 font-mono" :title="match.targetRoutine ? (routineLabels[match.targetRoutine] ?? match.targetRoutine) : undefined">
                  <span v-if="match.targetRoutine">{{ routineLabels[match.targetRoutine] ?? match.targetRoutine }}</span>
                  <span v-else class="text-muted-foreground">—</span>
                </td>
                <td class="px-2 py-1.5" :class="matchStatusClass(match.kind)">
                  {{ t(`diff.tableMatchStatus.${match.kind}`) }}
                </td>
                <td class="px-2 py-1.5 text-right">
                  <Button variant="ghost" size="sm" class="h-7 w-7 p-0" :aria-label="t('common.delete')" @click="handleRemoveSelectedRoutine(match.sourceRoutine)">
                    <Trash2 class="h-3.5 w-3.5" />
                  </Button>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
        <div v-if="targetRoutineListLoaded && missingTargetRoutines.length" class="text-muted-foreground">
          {{ t("diff.unmatchedRoutineWarning", { count: missingTargetRoutines.length }) }}
        </div>
      </div>
    </div>

    <!-- Options -->
    <div class="flex items-center gap-2 p-3 rounded-lg border bg-muted/20">
      <input id="schema-diff-ignore-comments" :checked="ignoreComments" type="checkbox" class="accent-primary" @change="$emit('update:ignoreComments', ($event.target as HTMLInputElement).checked)" />
      <Label for="schema-diff-ignore-comments" class="cursor-pointer text-xs">
        {{ t("diff.ignoreComments") }}
      </Label>
    </div>

    <!-- Recent Configs Dropdown -->
    <div v-if="recentConfigs.length > 0" class="flex items-center gap-2">
      <Label class="text-xs text-muted-foreground">{{ t("diff.recentConfigs") }}</Label>
      <Select
        :model-value="''"
        @update:model-value="
          (v: any) => {
            const config = recentConfigs.find((c) => c.id === v);
            if (config) $emit('loadHistoryConfig', config);
          }
        "
      >
        <SelectTrigger class="h-8 text-xs w-[280px]">
          <SelectValue :placeholder="t('diff.selectRecentConfig')" />
        </SelectTrigger>
        <SelectContent>
          <SelectItem v-for="config in recentConfigs" :key="config.id" :value="config.id" class="pr-8">
            <div class="flex items-center justify-between w-full gap-2">
              <div class="flex flex-col gap-0.5 min-w-0">
                <span class="text-xs font-medium truncate">{{ config.name }}</span>
                <span class="text-[10px] text-muted-foreground truncate">
                  {{ store.getConfig(config.sourceConnectionId)?.name || config.sourceConnectionId }}
                  /{{ config.sourceDatabase }}{{ config.sourceSchema ? `.${config.sourceSchema}` : "" }}
                  →
                  {{ store.getConfig(config.targetConnectionId)?.name || config.targetConnectionId }}
                  /{{ config.targetDatabase }}{{ config.targetSchema ? `.${config.targetSchema}` : "" }}
                </span>
              </div>
              <button class="shrink-0 p-1 rounded hover:bg-destructive/10 hover:text-destructive transition-colors" @click.stop="$emit('deleteHistoryConfig', config.id)">
                <X class="w-3 h-3" />
              </button>
            </div>
          </SelectItem>
        </SelectContent>
      </Select>
    </div>

    <!-- Bottom Actions -->
    <div class="flex items-center justify-between pt-2">
      <div class="flex items-center gap-2">
        <Button variant="outline" size="sm" @click="$emit('saveConfig')">
          <Save class="w-3.5 h-3.5 mr-1" />
          {{ t("diff.saveConfig") }}
        </Button>
        <Button variant="outline" size="sm" @click="$emit('loadConfig')">
          <FolderOpen class="w-3.5 h-3.5 mr-1" />
          {{ t("diff.loadConfig") }}
        </Button>
        <Button variant="outline" size="sm" @click="$emit('showOptions')">
          <Settings class="w-3.5 h-3.5 mr-1" />
          {{ t("diff.options") }}
        </Button>
        <Button v-if="showFieldMapping" variant="outline" size="sm" @click="$emit('open-field-mapping')">
          <ArrowLeftRight class="w-3.5 h-3.5 mr-1" />
          {{ t("diff.openFieldMapping") }}
          <span v-if="activeFieldMappings.length > 0" class="ml-1 inline-flex items-center justify-center rounded-full bg-primary/10 px-1.5 py-0.5 text-[10px] font-medium text-primary">{{ activeFieldMappings.length }}</span>
        </Button>
      </div>
      <Button size="sm" :disabled="!canCompare || loading" @click="$emit('compare')">
        <GitCompareArrows class="w-3.5 h-3.5 mr-1" />
        {{ loading ? t("common.loading") : t("diff.compare") }}
      </Button>
    </div>
  </div>
</template>