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。

fix(diff): filter comparison connections by type

二丫讲梵262a53831013
diff --git a/apps/desktop/src/components/diff/CompareConnectionSelect.vue b/apps/desktop/src/components/diff/CompareConnectionSelect.vue
new file mode 100644
index 0000000000..94402380c2
--- /dev/null
+++ b/apps/desktop/src/components/diff/CompareConnectionSelect.vue
@@ -0,0 +1,82 @@
+<script setup lang="ts">
+import { computed, ref, watch } from "vue";
+import { useI18n } from "vue-i18n";
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
+import ConnectionTreeSelect from "@/components/connection/ConnectionTreeSelect.vue";
+import { compareConnectionType } from "@/lib/database/databaseCompareCapabilities";
+import type { ConnectionConfig, SidebarLayout } from "@/types/database";
+
+const props = withDefaults(
+ defineProps<{
+ modelValue: string;
+ connections: ConnectionConfig[];
+ layout: SidebarLayout;
+ disabled?: boolean;
+ }>(),
+ { disabled: false },
+);
+const emit = defineEmits<{ "update:modelValue": [value: string] }>();
+const { t } = useI18n();
+const ALL_TYPES = "all";
+const selectedType = ref(ALL_TYPES);
+const selectedConnection = computed(() => props.connections.find((connection) => connection.id === props.modelValue));
+const typeOptions = computed(() => {
+ const options = new Map<string, { value: string; label: string }>();
+ for (const connection of props.connections) {
+ const type = compareConnectionType(connection);
+ if (!options.has(type.value)) options.set(type.value, type);
+ }
+ return [...options.values()].sort((left, right) => left.label.localeCompare(right.label));
+});
+const filteredConnections = computed(() => props.connections.filter((connection) => selectedType.value === ALL_TYPES || compareConnectionType(connection).value === selectedType.value));
+
+// Programmatic changes (config restore, prefill, swap) follow the connection.
+// Clearing a connection preserves the filter the user just selected.
+watch(
+ () => selectedConnection.value && compareConnectionType(selectedConnection.value).value,
+ (type) => {
+ if (type) selectedType.value = type;
+ },
+ { immediate: true },
+);
+watch(typeOptions, (options) => {
+ if (selectedType.value !== ALL_TYPES && !options.some((option) => option.value === selectedType.value)) selectedType.value = ALL_TYPES;
+});
+
+function selectType(value: unknown) {
+ if (props.disabled || typeof value !== "string") return;
+ selectedType.value = value;
+ if (props.modelValue && value !== ALL_TYPES && (!selectedConnection.value || compareConnectionType(selectedConnection.value).value !== value)) {
+ emit("update:modelValue", "");
+ }
+}
+</script>
+
+<template>
+ <div class="@container min-w-0 space-y-1">
+ <div class="grid grid-cols-1 gap-2 @min-[300px]:grid-cols-[minmax(0,1fr)_minmax(0,2fr)]">
+ <Select :model-value="selectedType" :disabled="disabled || !typeOptions.length" @update:model-value="selectType">
+ <SelectTrigger class="h-8 w-full min-w-0 text-xs" :aria-label="t('diff.connType')">
+ <SelectValue class="min-w-0 truncate" :placeholder="t('diff.allConnectionTypes')" />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem :value="ALL_TYPES">{{ t("diff.allConnectionTypes") }}</SelectItem>
+ <SelectItem v-for="option in typeOptions" :key="option.value" :value="option.value">{{ option.label }}</SelectItem>
+ </SelectContent>
+ </Select>
+ <ConnectionTreeSelect
+ :model-value="selectedConnection ? modelValue : ''"
+ :connections="filteredConnections"
+ :layout="layout"
+ :disabled="disabled || !connections.length"
+ :placeholder="t('diff.selectConnection')"
+ :search-placeholder="t('diff.searchConnection')"
+ :empty-text="t('common.noResults')"
+ trigger-class="dbx-diff-connection-trigger h-8 w-full max-w-none justify-between gap-1.5 rounded-md border border-input bg-transparent px-2.5 text-xs shadow-none hover:bg-muted/40 focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 dark:bg-input/30 dark:hover:bg-input/50"
+ list-class="min-w-64 w-[var(--reka-popover-trigger-width)]"
+ @update:model-value="(value) => emit('update:modelValue', value)"
+ />
+ </div>
+ <p v-if="modelValue && !selectedConnection" class="text-xs text-muted-foreground">{{ t("diff.unsupportedCompareConnection") }}</p>
+ </div>
+</template>
diff --git a/apps/desktop/src/components/diff/DataCompareDialog.vue b/apps/desktop/src/components/diff/DataCompareDialog.vue
index 1e43fdaca4..30203edc10 100644
--- a/apps/desktop/src/components/diff/DataCompareDialog.vue
+++ b/apps/desktop/src/components/diff/DataCompareDialog.vue
@@ -6,7 +6,8 @@ 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 ConnectionTreeSelect from "@/components/connection/ConnectionTreeSelect.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";
@@ -129,7 +130,34 @@ let configSaveTimer: ReturnType<typeof setTimeout> | undefined;
let componentUnmounted = false;
let shownSessionError = "";
-const sqlConnections = computed(() => store.connections.filter((connection) => !["redis", "mongodb", "elasticsearch", "easysearch", "meilisearch", "solr", "qdrant", "milvus", "weaviate", "chromadb", "etcd", "zookeeper", "consul", "mq", "nacos", "salesforce"].includes(connection.db_type)));
+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.
@@ -195,7 +223,19 @@ const singleTableNeedsKeyColumns = computed(() => {
if (!isTableColumnsKnown(row.table)) return false;
return row.columns.length === 0;
});
-const canCompare = computed(() => sourceConnectionId.value && sourceDatabase.value && sourceSchema.value && selectedSourceTableNames.value.length > 0 && targetConnectionId.value && targetDatabase.value && targetSchema.value && !singleTableNeedsKeyColumns.value);
+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);
@@ -299,7 +339,7 @@ async function fetchTableColumns(table: string): Promise<CompareKeyColumnOption[
const connectionId = sourceConnectionId.value;
const database = sourceDatabase.value;
const schema = sourceSchema.value;
- if (!connectionId || !database || !schema || !table) return [];
+ if (!connectionId || !database || !schema || !table || !supportsDatabaseCompare(store.getConfig(connectionId), "data")) return [];
const generation = columnMetadataGeneration;
loadingColumnTables.value = [...loadingColumnTables.value, table];
try {
@@ -503,15 +543,24 @@ async function applyDataCompareConfig(config: DataCompareConfig): Promise<void>
shownSessionError = "";
try {
sourceConnectionId.value = config.sourceConnectionId;
- if (!config.sourceConnectionId) return;
- 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;
-
targetConnectionId.value = config.targetConnectionId;
- if (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;
@@ -591,7 +640,9 @@ function applyDataCompareSession(session: DataCompareSession | undefined): void
}
function swapSourceTarget() {
- if (executionLocked.value) return;
+ 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;
@@ -620,7 +671,15 @@ function swapSourceTarget() {
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> {
@@ -636,78 +695,101 @@ async function resolveSchema(connectionId: string, database: string, preferredSc
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) return;
- const config = store.getConfig(connectionId);
- if (!isSchemaAware(config?.db_type)) {
+ 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 = [];
- sourceSchema.value = database;
+ sourceSchemas.value = schemas;
+ sourceSchema.value = schema;
} else {
- targetSchemas.value = [];
- targetSchema.value = database;
+ targetSchemas.value = schemas;
+ targetSchema.value = schema;
}
- await loadTables(side);
- return;
- }
-
- const schemas = await api.listSchemas(connectionId, database);
- 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) return;
- await store.ensureConnected(connectionId);
- const config = store.getConfig(connectionId);
- const names = config
- ? await fetchNamespaceOptionsForConnection(connectionId, config)
- : databaseOptionsForConnection(
- (await api.listDatabases(connectionId)).map((database) => database.name),
- config,
- );
- 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 = "";
+ 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) return;
- const schema = side === "source" ? sourceSchema.value || (await resolveSchema(connectionId, database, props.prefillSchema)) : targetSchema.value || (await resolveSchema(connectionId, database));
- const tables = (await api.listTables(connectionId, database, schema)).filter((table) => table.table_type !== "VIEW" && table.table_type !== "MATERIALIZED_VIEW").map((table) => table.name);
-
- 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;
+ 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;
}
}
@@ -1035,6 +1117,7 @@ function formatModifiedSummary(row: SelectableDataCompareModifiedRow): string {
watch(sourceConnectionId, (id) => {
if (initializingPrefill) return;
clearResult();
+ sourceDatabases.value = [];
sourceDatabase.value = "";
sourceSchema.value = "";
sourceSchemas.value = [];
@@ -1048,6 +1131,7 @@ watch(sourceConnectionId, (id) => {
watch(targetConnectionId, (id) => {
if (initializingPrefill) return;
clearResult();
+ targetDatabases.value = [];
targetDatabase.value = "";
targetSchema.value = "";
targetSchemas.value = [];
@@ -1158,6 +1242,13 @@ watch(
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);
@@ -1231,17 +1322,7 @@ onBeforeUnmount(() => {
<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>
- <ConnectionTreeSelect
- v-model="sourceConnectionId"
- :disabled="comparing || executionLocked"
- :connections="sqlConnections"
- :layout="store.sidebarLayout"
- :placeholder="t('diff.selectConnection')"
- :search-placeholder="t('diff.searchConnection')"
- :empty-text="t('common.noResults')"
- trigger-class="dbx-diff-connection-trigger h-8 w-full max-w-none justify-between gap-1.5 rounded-md border border-input bg-transparent px-2.5 text-xs shadow-none hover:bg-muted/40 focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 dark:bg-input/30 dark:hover:bg-input/50"
- list-class="w-[var(--reka-popover-trigger-width)]"
- />
+ <CompareConnectionSelect v-model="sourceConnectionId" :disabled="comparing || executionLocked" :connections="compareConnections" :layout="store.sidebarLayout" />
<SearchableSelect
v-model="sourceDatabase"
:options="sourceDatabases"
@@ -1277,7 +1358,7 @@ onBeforeUnmount(() => {
</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" @click="swapSourceTarget">
+ <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>
@@ -1287,17 +1368,7 @@ onBeforeUnmount(() => {
<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>
- <ConnectionTreeSelect
- v-model="targetConnectionId"
- :disabled="comparing || executionLocked"
- :connections="sqlConnections"
- :layout="store.sidebarLayout"
- :placeholder="t('diff.selectConnection')"
- :search-placeholder="t('diff.searchConnection')"
- :empty-text="t('common.noResults')"
- trigger-class="dbx-diff-connection-trigger h-8 w-full max-w-none justify-between gap-1.5 rounded-md border border-input bg-transparent px-2.5 text-xs shadow-none hover:bg-muted/40 focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 dark:bg-input/30 dark:hover:bg-input/50"
- list-class="w-[var(--reka-popover-trigger-width)]"
- />
+ <CompareConnectionSelect v-model="targetConnectionId" :disabled="comparing || executionLocked" :connections="compareConnections" :layout="store.sidebarLayout" />
<SearchableSelect
v-model="targetDatabase"
:options="targetDatabases"
diff --git a/apps/desktop/src/components/diff/SchemaDiffConfigStep.vue b/apps/desktop/src/components/diff/SchemaDiffConfigStep.vue
index 551072969f..52f4049182 100644
--- a/apps/desktop/src/components/diff/SchemaDiffConfigStep.vue
+++ b/apps/desktop/src/components/diff/SchemaDiffConfigStep.vue
@@ -6,7 +6,8 @@ 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 ConnectionTreeSelect from "@/components/connection/ConnectionTreeSelect.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 {
@@ -84,7 +85,34 @@ const targetSchemas = ref<string[]>([]);
const sourceDbVersion = ref<string | null>(null);
const targetDbVersion = ref<string | null>(null);
-const sqlConnections = computed(() => store.connections.filter((c: any) => !["mongodb", "redis", "elasticsearch", "easysearch", "meilisearch", "solr", "etcd", "zookeeper", "consul", "mq", "nacos", "salesforce"].includes(c.db_type)));
+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));
@@ -197,7 +225,7 @@ function getTableIdentity(side: SchemaDiffTableSide): SchemaDiffTableIdentity {
function isTableIdentityReady(side: SchemaDiffTableSide): boolean {
const identity = getTableIdentity(side);
const config = side === "source" ? sourceConfig.value : targetConfig.value;
- return !!identity.connectionId && !!identity.database && (!isSchemaAware(config?.db_type) || !!identity.schema);
+ return supportsDatabaseCompare(config, "schema") && !!identity.connectionId && !!identity.database && (!isSchemaAware(config?.db_type) || !!identity.schema);
}
function setTableList(side: SchemaDiffTableSide, tables: Array<{ name?: string }>) {
@@ -340,7 +368,7 @@ async function loadRoutineList(side: "source" | "target") {
const database = side === "source" ? props.sourceDatabase : props.targetDatabase;
const schema = side === "source" ? props.sourceSchema : props.targetSchema;
const dbType = side === "source" ? sourceDbType.value : targetDbType.value;
- if (!connectionId || !database || !supportsSchemaDiffRoutines(dbType as DatabaseType)) {
+ if (!isTableIdentityReady(side) || !supportsSchemaDiffRoutines(dbType as DatabaseType)) {
if (side === "source") sourceRoutineList.value = [];
else {
targetRoutineList.value = [];
@@ -348,12 +376,15 @@ async function loadRoutineList(side: "source" | "target") {
}
return;
}
+ const isCurrent = metadataRequestIsCurrent(side);
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);
const objects = kinds.length === 0 ? [] : await api.listObjects(connectionId, database, schema, kinds);
+ if (!isCurrent()) return;
const keys = objects.map((object) => schemaDiffRoutineKey(object.name, object.signature ?? ""));
if (side === "source") {
sourceRoutineList.value = keys;
@@ -370,6 +401,7 @@ async function loadRoutineList(side: "source" | "target") {
if (restrictRoutines.value) reconcileRoutineMappings(localSelectedRoutines.value, keys);
}
} catch {
+ if (!isCurrent()) return;
if (side === "source") sourceRoutineList.value = [];
else {
targetRoutineList.value = [];
@@ -454,6 +486,8 @@ const canCompare = computed(() => {
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 &&
@@ -468,11 +502,14 @@ const canCompare = computed(() => {
});
async function loadDatabases(connectionId: string, side: "source" | "target") {
- if (!connectionId) return;
+ 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) {
@@ -493,6 +530,7 @@ async function loadDatabases(connectionId: string, side: "source" | "target") {
}
}
} catch {
+ if (!isCurrent()) return;
if (side === "source") {
sourceDatabases.value = [];
sourceDbVersion.value = null;
@@ -507,11 +545,14 @@ 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) return;
+ 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 {
@@ -519,6 +560,7 @@ async function loadSchemas(side: "source" | "target") {
}
await fetchDbVersion(connectionId, database, schema, side);
} catch {
+ if (!isCurrent()) return;
if (side === "source") {
sourceSchemas.value = [];
} else {
@@ -530,6 +572,9 @@ async function loadSchemas(side: "source" | "target") {
watch(
() => props.sourceConnectionId,
async (id) => {
+ sourceDatabases.value = [];
+ sourceSchemas.value = [];
+ sourceDbVersion.value = null;
if (id) {
await loadDatabases(id, "source");
} else {
@@ -554,6 +599,9 @@ watch(
watch(
() => props.targetConnectionId,
async (id) => {
+ targetDatabases.value = [];
+ targetSchemas.value = [];
+ targetDbVersion.value = null;
if (id) {
await loadDatabases(id, "target");
} else {
@@ -615,6 +663,8 @@ function getConnectionInfo(connectionId: string) {
}
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);
@@ -634,7 +684,9 @@ async function fetchDbVersion(connectionId: string, database: string, schema: st
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") {
@@ -644,6 +696,7 @@ async function fetchDbVersion(connectionId: string, database: string, schema: st
}
}
} catch (e) {
+ if (!isCurrent()) return;
console.error(`[fetchDbVersion] Failed to fetch version for ${side}:`, e);
if (side === "source") {
sourceDbVersion.value = null;
@@ -681,17 +734,7 @@ async function fetchDbVersion(connectionId: string, database: string, schema: st
<div class="space-y-1.5">
<Label class="text-xs">{{ t("diff.connection") }}</Label>
- <ConnectionTreeSelect
- :model-value="sourceConnectionId"
- @update:model-value="(v: string) => $emit('update:sourceConnectionId', v)"
- :connections="sqlConnections"
- :layout="store.sidebarLayout"
- :placeholder="t('diff.selectConnection')"
- :search-placeholder="t('diff.searchConnection')"
- :empty-text="t('common.noResults')"
- trigger-class="dbx-diff-connection-trigger h-8 w-full max-w-none justify-between gap-1.5 rounded-md border border-input bg-transparent px-2.5 text-xs shadow-none hover:bg-muted/40 focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 dark:bg-input/30 dark:hover:bg-input/50"
- list-class="w-[var(--reka-popover-trigger-width)]"
- />
+ <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">
@@ -757,17 +800,7 @@ async function fetchDbVersion(connectionId: string, database: string, schema: st
<div class="space-y-1.5">
<Label class="text-xs">{{ t("diff.connection") }}</Label>
- <ConnectionTreeSelect
- :model-value="targetConnectionId"
- @update:model-value="(v: string) => $emit('update:targetConnectionId', v)"
- :connections="sqlConnections"
- :layout="store.sidebarLayout"
- :placeholder="t('diff.selectConnection')"
- :search-placeholder="t('diff.searchConnection')"
- :empty-text="t('common.noResults')"
- trigger-class="dbx-diff-connection-trigger h-8 w-full max-w-none justify-between gap-1.5 rounded-md border border-input bg-transparent px-2.5 text-xs shadow-none hover:bg-muted/40 focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 dark:bg-input/30 dark:hover:bg-input/50"
- list-class="w-[var(--reka-popover-trigger-width)]"
- />
+ <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">
diff --git a/apps/desktop/src/components/diff/SchemaDiffDialog.vue b/apps/desktop/src/components/diff/SchemaDiffDialog.vue
index 0ef81e662e..dfa91a7fbe 100644
--- a/apps/desktop/src/components/diff/SchemaDiffDialog.vue
+++ b/apps/desktop/src/components/diff/SchemaDiffDialog.vue
@@ -9,6 +9,7 @@ import { GitCompareArrows, ArrowLeft, Play, Loader2, Maximize2, Minimize2, Alert
import * as api from "@/lib/backend/api";
import { executeWithProductionSqlGuard } from "@/lib/database/productionExecutionGuard";
import { isSchemaAware } from "@/lib/database/databaseCapabilities";
+import { supportsDatabaseCompare } from "@/lib/database/databaseCompareCapabilities";
import { useSchemaDiffConfig } from "@/composables/useSchemaDiffConfig";
import SchemaDiffConfigStep from "@/components/diff/SchemaDiffConfigStep.vue";
import SchemaDiffConfigSelector from "@/components/diff/SchemaDiffConfigSelector.vue";
@@ -587,6 +588,14 @@ function runWithoutTargetIdentityReset(action: () => void): void {
}
}
+function handleSourceConnectionChange(connectionId: string): void {
+ if (connectionId === sourceConnectionId.value) return;
+ sourceConnectionId.value = connectionId;
+ sourceDatabase.value = "";
+ sourceSchema.value = "";
+ clearCompareObjectSelection();
+}
+
function clearCompareObjectSelection(): void {
if (!activeConfig.value) return;
updateActiveConfigOptions(
@@ -729,6 +738,7 @@ function handleFieldMappingsUpdate(mappings: FieldMappingEntry[]) {
function handleCompare(): void {
const sourceConfig = store.getConfig(sourceConnectionId.value);
const targetConfig = store.getConfig(targetConnectionId.value);
+ if (!supportsDatabaseCompare(sourceConfig, "schema") || !supportsDatabaseCompare(targetConfig, "schema")) return;
const targetDbType = (targetConfig?.db_type || "mysql") as DatabaseType;
const sourceDbType = sourceConfig?.db_type || targetDbType;
const options = normalizeSchemaDiffCompareOptions(activeConfig.value?.options, targetDbType);
@@ -1193,6 +1203,7 @@ function handleDeleteHistoryConfig(configId: string) {
}
async function fetchDbVersion(connectionId: string, database: string, schema: string) {
+ if (!supportsDatabaseCompare(store.getConfig(connectionId), "schema")) return;
try {
await store.ensureConnected(connectionId);
const config = store.getConfig(connectionId);
@@ -1307,7 +1318,8 @@ const targetConnectionInfo = computed(() => {
<SchemaDiffConfigStep
v-if="step === 'config'"
class="shrink-0"
- v-model:source-connection-id="sourceConnectionId"
+ :source-connection-id="sourceConnectionId"
+ @update:source-connection-id="handleSourceConnectionChange"
v-model:source-database="sourceDatabase"
v-model:source-schema="sourceSchema"
v-model:target-connection-id="targetConnectionId"
diff --git a/apps/desktop/src/components/diff/__tests__/DataCompareDialog.swap.spec.ts b/apps/desktop/src/components/diff/__tests__/DataCompareDialog.swap.spec.ts
new file mode 100644
index 0000000000..3c208e10d5
--- /dev/null
+++ b/apps/desktop/src/components/diff/__tests__/DataCompareDialog.swap.spec.ts
@@ -0,0 +1,220 @@
+// @vitest-environment happy-dom
+
+import { createApp, defineComponent, h, nextTick, type App } from "vue";
+import { afterEach, beforeEach, expect, it, vi } from "vitest";
+import i18n from "@/i18n";
+import DataCompareDialog from "@/components/diff/DataCompareDialog.vue";
+import type { DataCompareSession } from "@/composables/useDataCompareSession";
+
+const mocks = vi.hoisted(() => ({
+ session: null as DataCompareSession | null,
+ ensureConnected: vi.fn(),
+ listDatabases: vi.fn(),
+ listSchemas: vi.fn(),
+ listTables: vi.fn(),
+ getColumns: vi.fn(),
+ toast: vi.fn(),
+}));
+
+vi.mock("@/composables/useToast", () => ({ useToast: () => ({ toast: mocks.toast }) }));
+vi.mock("@/composables/useDataCompareSession", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@/composables/useDataCompareSession")>()),
+ getDataCompareSession: (id: string | null | undefined) => (id === mocks.session?.id ? mocks.session : undefined),
+}));
+vi.mock("@/stores/connectionStore", () => {
+ const connections = [1, 2, 3].map((index) => ({ id: `pg-${index}`, name: `PostgreSQL ${index}`, db_type: "postgres" }));
+ return {
+ useConnectionStore: () => ({
+ connections,
+ sidebarLayout: { groups: [], order: connections.map(({ id }) => ({ type: "connection", id })) },
+ getConfig: (id: string) => connections.find((connection) => connection.id === id),
+ ensureConnected: mocks.ensureConnected,
+ }),
+ };
+});
+vi.mock("@/lib/backend/api", () => ({
+ listDatabases: mocks.listDatabases,
+ listSchemas: mocks.listSchemas,
+ listTables: mocks.listTables,
+ getColumns: mocks.getColumns,
+}));
+
+const mountedApps: App[] = [];
+const tables = [
+ { name: "orders", table_type: "TABLE" },
+ { name: "invoices", table_type: "TABLE" },
+];
+
+beforeEach(() => {
+ mocks.ensureConnected.mockReset().mockResolvedValue(undefined);
+ mocks.listDatabases.mockReset().mockResolvedValue([{ name: "app" }]);
+ mocks.listSchemas.mockReset().mockResolvedValue(["public", "analytics"]);
+ mocks.listTables.mockReset().mockResolvedValue(tables);
+ mocks.getColumns.mockReset().mockResolvedValue([{ name: "id", data_type: "integer", is_primary_key: true }]);
+ mocks.toast.mockReset();
+});
+
+afterEach(() => {
+ for (const app of mountedApps.splice(0)) app.unmount();
+ document.body.textContent = "";
+ mocks.session = null;
+});
+
+async function flushAsyncSetup() {
+ for (let index = 0; index < 8; index += 1) {
+ await nextTick();
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ }
+}
+
+async function mountLoadedDialog() {
+ mocks.session = {
+ id: "loaded-compare",
+ version: 1,
+ status: "completed",
+ config: {
+ sourceConnectionId: "pg-1",
+ sourceDatabase: "app",
+ sourceSchema: "public",
+ sourceDatabases: ["app", "reporting"],
+ sourceSchemas: ["public", "analytics"],
+ sourceTables: ["orders", "invoices"],
+ selectedSourceTables: ["orders"],
+ targetConnectionId: "pg-2",
+ targetDatabase: "reporting",
+ targetSchema: "analytics",
+ targetDatabases: ["app", "reporting"],
+ targetSchemas: ["public", "analytics"],
+ targetTables: ["orders", "invoices"],
+ targetTable: "invoices",
+ keyColumnsByTable: {},
+ label: "Loaded comparison",
+ },
+ progress: null,
+ batchResults: [],
+ syncPlan: { insertCount: 0, updateCount: 0, deleteCount: 0, statementCount: 0, syncStatements: [], syncSql: "" },
+ error: null,
+ startedAt: 1,
+ finishedAt: 2,
+ };
+ const container = document.createElement("div");
+ document.body.append(container);
+ const app = createApp(defineComponent({ setup: () => () => h(DataCompareDialog, { open: true, sessionId: "loaded-compare" }) }));
+ mountedApps.push(app);
+ app.use(i18n);
+ app.mount(container);
+ await flushAsyncSetup();
+}
+
+function panel(side: "source" | "target"): HTMLDivElement {
+ const color = side === "source" ? "blue" : "emerald";
+ return [...document.querySelectorAll<HTMLDivElement>("div")].find((element) => element.classList.contains(`border-${color}-500/35`))!;
+}
+
+function namespaceTriggers(side: "source" | "target") {
+ return [...panel(side).querySelectorAll<HTMLButtonElement>("button.dbx-searchable-select-trigger")];
+}
+
+function swapButton() {
+ return [...document.querySelectorAll<HTMLButtonElement>("button")].find((button) => button.title === i18n.global.t("diff.swap"))!;
+}
+
+async function chooseConnection(side: "source" | "target", id: string) {
+ panel(side).querySelector<HTMLButtonElement>("button.dbx-diff-connection-trigger")!.click();
+ await flushAsyncSetup();
+ document.querySelector<HTMLButtonElement>(`[data-picker-connection="${id}"]`)!.click();
+ await flushAsyncSetup();
+}
+
+async function chooseOption(trigger: HTMLButtonElement, value: string) {
+ trigger.click();
+ await flushAsyncSetup();
+ [...document.querySelectorAll<HTMLButtonElement>(".dbx-searchable-select-list button")].find((button) => button.textContent?.trim() === value)!.click();
+ await flushAsyncSetup();
+}
+
+const stages = ["databases", "schemas", "tables"] as const;
+type Stage = (typeof stages)[number];
+
+async function beginMetadataLoad(side: "source" | "target", stage: Stage) {
+ if (stage === "databases") await chooseConnection(side, "pg-3");
+ else if (stage === "schemas") await chooseOption(namespaceTriggers(side)[0], side === "source" ? "reporting" : "app");
+ else await chooseOption(namespaceTriggers(side)[1], side === "source" ? "analytics" : "public");
+}
+
+function deferredMetadata(stage: Stage) {
+ const request = stage === "databases" ? mocks.listDatabases : stage === "schemas" ? mocks.listSchemas : mocks.listTables;
+ let resolve!: (value: unknown) => void;
+ let reject!: (error: Error) => void;
+ request.mockReturnValueOnce(
+ new Promise((onResolve, onReject) => {
+ resolve = onResolve;
+ reject = onReject;
+ }),
+ );
+ return {
+ resolve: () => resolve(stage === "databases" ? [{ name: "app" }] : stage === "schemas" ? ["public", "analytics"] : tables),
+ reject,
+ };
+}
+
+it.each(["source", "target"].flatMap((side) => stages.map((stage) => [side as "source" | "target", stage] as const)))("waits for pending %s %s before allowing swap", async (side, stage) => {
+ await mountLoadedDialog();
+ const pending = deferredMetadata(stage);
+ await beginMetadataLoad(side, stage);
+ expect(swapButton().disabled).toBe(true);
+ swapButton().click();
+ expect(panel(side).querySelector<HTMLButtonElement>("button.dbx-diff-connection-trigger")!.title).toBe(stage === "databases" ? "PostgreSQL 3" : side === "source" ? "PostgreSQL 1" : "PostgreSQL 2");
+
+ pending.resolve();
+ await flushAsyncSetup();
+ expect(swapButton().disabled).toBe(false);
+ const previousDatabase = namespaceTriggers(side)[0].title;
+ expect(namespaceTriggers(side)[0].disabled).toBe(false);
+ swapButton().click();
+ await flushAsyncSetup();
+ const destination = side === "source" ? "target" : "source";
+ expect(namespaceTriggers(destination)[0].title).toBe(previousDatabase);
+ expect(namespaceTriggers(destination)[0].disabled).toBe(false);
+});
+
+it.each(stages)("releases the swap lock after a %s request fails", async (stage) => {
+ await mountLoadedDialog();
+ const pending = deferredMetadata(stage);
+ await beginMetadataLoad("source", stage);
+ expect(swapButton().disabled).toBe(true);
+ pending.reject(new Error("metadata unavailable"));
+ await flushAsyncSetup();
+ expect(swapButton().disabled).toBe(false);
+ expect(mocks.toast).toHaveBeenCalledWith("Error: metadata unavailable", 5000);
+});
+
+it("waits for both endpoints when their requests overlap", async () => {
+ await mountLoadedDialog();
+ const source = deferredMetadata("databases");
+ const target = deferredMetadata("databases");
+ await chooseConnection("source", "pg-3");
+ await chooseConnection("target", "pg-1");
+ source.resolve();
+ await flushAsyncSetup();
+ expect(swapButton().disabled).toBe(true);
+ target.resolve();
+ await flushAsyncSetup();
+ expect(swapButton().disabled).toBe(false);
+});
+
+it("preserves loaded databases, schemas and table selections after swap", async () => {
+ await mountLoadedDialog();
+ expect(swapButton().disabled).toBe(false);
+ swapButton().click();
+ await flushAsyncSetup();
+ expect(panel("source").querySelector<HTMLButtonElement>("button.dbx-diff-connection-trigger")!.title).toBe("PostgreSQL 2");
+ expect(panel("target").querySelector<HTMLButtonElement>("button.dbx-diff-connection-trigger")!.title).toBe("PostgreSQL 1");
+ expect(namespaceTriggers("source").map((button) => button.title)).toEqual(["reporting", "analytics"]);
+ expect(namespaceTriggers("target").map((button) => button.title)).toEqual(["app", "public", "orders"]);
+ expect(panel("source").querySelector('[data-table-name="invoices"] svg')?.classList.contains("text-primary")).toBe(true);
+ expect(panel("source").querySelector('[data-table-name="orders"] svg')?.classList.contains("text-primary")).toBe(false);
+ expect(mocks.listDatabases).not.toHaveBeenCalled();
+ expect(mocks.listSchemas).not.toHaveBeenCalled();
+ expect(mocks.listTables).not.toHaveBeenCalled();
+});
diff --git a/apps/desktop/src/components/diff/__tests__/SchemaDiffConfigStep.namespace.spec.ts b/apps/desktop/src/components/diff/__tests__/SchemaDiffConfigStep.namespace.spec.ts
index 5649de8b3e..be35de13a1 100644
--- a/apps/desktop/src/components/diff/__tests__/SchemaDiffConfigStep.namespace.spec.ts
+++ b/apps/desktop/src/components/diff/__tests__/SchemaDiffConfigStep.namespace.spec.ts
@@ -1,7 +1,7 @@
// @vitest-environment happy-dom
-import { createApp, defineComponent, h, nextTick, type App } from "vue";
-import { afterEach, expect, it, vi } from "vitest";
+import { createApp, defineComponent, h, nextTick, reactive, type App } from "vue";
+import { afterEach, beforeEach, expect, it, vi } from "vitest";
import i18n from "@/i18n";
import { getDefaultOptionsForDbType } from "@/types/schemaDiff";
import SchemaDiffConfigStep from "@/components/diff/SchemaDiffConfigStep.vue";
@@ -10,15 +10,17 @@ const mocks = vi.hoisted(() => ({
ensureConnected: vi.fn().mockResolvedValue(undefined),
listDatabases: vi.fn().mockResolvedValue([]),
listSchemas: vi.fn().mockResolvedValue(["APP", "REPORTING"]),
+ executeQuery: vi.fn().mockResolvedValue({ rows: [] }),
}));
vi.mock("@/stores/connectionStore", () => {
const connection = { id: "oracle-11g", name: "Oracle 11g", db_type: "oracle", driver_profile: "oracle", database: "XE" };
+ const connections = [connection, { id: "pg-1", name: "PostgreSQL 1", db_type: "postgres" }, { id: "pg-2", name: "PostgreSQL 2", db_type: "postgres" }];
return {
useConnectionStore: () => ({
- connections: [connection],
- sidebarLayout: { groups: [], order: [{ type: "connection", id: connection.id }] },
- getConfig: (id: string) => (id === connection.id ? connection : undefined),
+ connections,
+ sidebarLayout: { groups: [], order: connections.map(({ id }) => ({ type: "connection", id })) },
+ getConfig: (id: string) => connections.find((item) => item.id === id),
ensureConnected: mocks.ensureConnected,
}),
};
@@ -27,10 +29,63 @@ vi.mock("@/stores/connectionStore", () => {
vi.mock("@/lib/backend/api", () => ({
listDatabases: mocks.listDatabases,
listSchemas: mocks.listSchemas,
+ executeQuery: mocks.executeQuery,
}));
const mountedApps: App[] = [];
+beforeEach(() => {
+ mocks.ensureConnected.mockReset().mockResolvedValue(undefined);
+ mocks.listDatabases.mockReset().mockResolvedValue([]);
+ mocks.listSchemas.mockReset().mockResolvedValue(["APP", "REPORTING"]);
+ mocks.executeQuery.mockReset().mockResolvedValue({ rows: [] });
+});
+
+function mountPostgresEndpoint(side: "source" | "target") {
+ const endpoints = reactive({
+ sourceConnectionId: "",
+ sourceDatabase: "",
+ sourceSchema: "",
+ targetConnectionId: "",
+ targetDatabase: "",
+ targetSchema: "",
+ });
+ endpoints[`${side}ConnectionId`] = "pg-1";
+ endpoints[`${side}Database`] = "app";
+ endpoints[`${side}Schema`] = "public";
+ const container = document.createElement("div");
+ document.body.append(container);
+ const app = createApp(
+ defineComponent({
+ setup: () => () =>
+ h(SchemaDiffConfigStep, {
+ ...endpoints,
+ configs: [],
+ activeConfigId: "",
+ ignoreComments: false,
+ options: { ...getDefaultOptionsForDbType("postgres"), functions: false },
+ tableListLoader: { load: vi.fn().mockResolvedValue([]) },
+ loading: false,
+ recentConfigs: [],
+ "onUpdate:sourceSchema": (value: string) => {
+ endpoints.sourceSchema = value;
+ },
+ "onUpdate:targetSchema": (value: string) => {
+ endpoints.targetSchema = value;
+ },
+ }),
+ }),
+ );
+ mountedApps.push(app);
+ app.use(i18n);
+ app.mount(container);
+ return { endpoints, container };
+}
+
+function selectOptions() {
+ return [...document.querySelectorAll<HTMLButtonElement>(".dbx-searchable-select-list button")];
+}
+
async function flushAsyncSetup() {
for (let index = 0; index < 8; index += 1) {
await nextTick();
@@ -82,3 +137,62 @@ it("offers Oracle schemas as schema-diff database choices", async () => {
expect(mocks.listDatabases).not.toHaveBeenCalled();
expect(mocks.listSchemas).toHaveBeenCalledWith("oracle-11g", "XE", true);
});
+
+it.each(["source", "target"] as const)("keeps pending %s database choices when the user selects another schema", async (side) => {
+ let resolveDatabases!: (value: Array<{ name: string }>) => void;
+ mocks.listDatabases.mockReturnValueOnce(
+ new Promise((resolve) => {
+ resolveDatabases = resolve;
+ }),
+ );
+ mocks.listSchemas.mockResolvedValue(["public", "analytics"]);
+ const { endpoints, container } = mountPostgresEndpoint(side);
+ await flushAsyncSetup();
+
+ const triggers = [...container.querySelectorAll<HTMLButtonElement>("button.dbx-searchable-select-trigger")];
+ const database = triggers.find((button) => button.textContent?.trim() === "app")!;
+ const schema = triggers.find((button) => button.textContent?.trim() === "public")!;
+ expect(database.disabled).toBe(true);
+ expect(schema.disabled).toBe(false);
+ schema.click();
+ await flushAsyncSetup();
+ selectOptions()
+ .find((button) => button.textContent?.trim() === "analytics")!
+ .click();
+ await flushAsyncSetup();
+ expect(endpoints[`${side}Schema`]).toBe("analytics");
+
+ resolveDatabases([{ name: "app" }, { name: "reporting" }]);
+ await flushAsyncSetup();
+ expect(database.disabled).toBe(false);
+ database.click();
+ await flushAsyncSetup();
+ expect(selectOptions().map((button) => button.textContent?.trim())).toEqual(expect.arrayContaining(["app", "reporting"]));
+});
+
+it.each(["source", "target"] as const)("rejects stale %s database choices after switching away and back", async (side) => {
+ let resolveOldDatabases!: (value: Array<{ name: string }>) => void;
+ mocks.listDatabases
+ .mockReturnValueOnce(
+ new Promise((resolve) => {
+ resolveOldDatabases = resolve;
+ }),
+ )
+ .mockResolvedValue([{ name: "app" }]);
+ mocks.listSchemas.mockResolvedValue(["public", "analytics"]);
+ const { endpoints, container } = mountPostgresEndpoint(side);
+ await flushAsyncSetup();
+ endpoints[`${side}ConnectionId`] = "pg-2";
+ await flushAsyncSetup();
+ endpoints[`${side}ConnectionId`] = "pg-1";
+ await flushAsyncSetup();
+
+ resolveOldDatabases([{ name: "obsolete" }]);
+ await flushAsyncSetup();
+ const database = [...container.querySelectorAll<HTMLButtonElement>("button.dbx-searchable-select-trigger")].find((button) => button.textContent?.trim() === "app")!;
+ expect(database.disabled).toBe(false);
+ database.click();
+ await flushAsyncSetup();
+ expect(selectOptions().map((button) => button.textContent?.trim())).toEqual(["app"]);
+ expect(mocks.listDatabases.mock.calls.map(([id]) => id)).toEqual(["pg-1", "pg-2", "pg-1"]);
+});
diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.ts
index 56fe6be645..eeb5e92376 100644
--- a/apps/desktop/src/i18n/locales/en.ts
+++ b/apps/desktop/src/i18n/locales/en.ts
@@ -7685,6 +7685,8 @@ export default {
serverVersion: "Server Version",
info: "Info",
connType: "Connection type",
+ allConnectionTypes: "All types",
+ unsupportedCompareConnection: "This connection is unavailable or does not support comparison. Please select another connection.",
connName: "Connection name",
host: "Host",
addHost: "Add Host",
diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.ts
index c0f694a151..f734942d16 100644
--- a/apps/desktop/src/i18n/locales/es.ts
+++ b/apps/desktop/src/i18n/locales/es.ts
@@ -6978,6 +6978,8 @@ export default withEnglishFallback({
serverVersion: "Versión del servidor",
info: "Información",
connType: "Tipo de conexión",
+ allConnectionTypes: "Todos los tipos",
+ unsupportedCompareConnection: "Esta conexión no está disponible o no admite comparaciones. Selecciona otra conexión.",
connName: "Nombre de conexión",
host: "Host",
addHost: "Añadir Host",
diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.ts
index 21d2a216b9..0ca0da565c 100644
--- a/apps/desktop/src/i18n/locales/it.ts
+++ b/apps/desktop/src/i18n/locales/it.ts
@@ -6761,6 +6761,8 @@ export default withEnglishFallback({
serverVersion: "Versione Server",
info: "Info",
connType: "Tipo connessione",
+ allConnectionTypes: "Tutti i tipi",
+ unsupportedCompareConnection: "Questa connessione non è disponibile o non supporta il confronto. Seleziona un'altra connessione.",
connName: "Nome connessione",
host: "Host",
port: "Porta",
diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.ts
index 61bd2acb58..2aee310871 100644
--- a/apps/desktop/src/i18n/locales/ja.ts
+++ b/apps/desktop/src/i18n/locales/ja.ts
@@ -6792,6 +6792,8 @@ export default withEnglishFallback({
restore: "復元",
info: "情報",
connType: "接続タイプ",
+ allConnectionTypes: "すべてのタイプ",
+ unsupportedCompareConnection: "この接続は利用できないか、比較に対応していません。別の接続を選択してください。",
connName: "接続名",
host: "ホスト",
port: "ポート",
diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.ts
index bb1bac8e94..4104a29430 100644
--- a/apps/desktop/src/i18n/locales/ko.ts
+++ b/apps/desktop/src/i18n/locales/ko.ts
@@ -6572,6 +6572,8 @@ export default withEnglishFallback({
serverVersion: "서버 버전",
info: "정보",
connType: "연결 유형",
+ allConnectionTypes: "모든 유형",
+ unsupportedCompareConnection: "이 연결은 사용할 수 없거나 비교를 지원하지 않습니다. 다른 연결을 선택하세요.",
connName: "연결 이름",
host: "호스트",
port: "포트",
diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.ts
index 73b718f948..19a95e1453 100644
--- a/apps/desktop/src/i18n/locales/pt-BR.ts
+++ b/apps/desktop/src/i18n/locales/pt-BR.ts
@@ -6762,6 +6762,8 @@ export default withEnglishFallback({
serverVersion: "Versão do Servidor",
info: "Informações",
connType: "Tipo de conexão",
+ allConnectionTypes: "Todos os tipos",
+ unsupportedCompareConnection: "Esta conexão não está disponível ou não oferece suporte à comparação. Selecione outra conexão.",
connName: "Nome da conexão",
host: "Host",
port: "Porta",
diff --git a/apps/desktop/src/i18n/locales/ru.ts b/apps/desktop/src/i18n/locales/ru.ts
index ac5ffed04c..5e3aa61df8 100644
--- a/apps/desktop/src/i18n/locales/ru.ts
+++ b/apps/desktop/src/i18n/locales/ru.ts
@@ -8008,6 +8008,8 @@ export default withEnglishFallback({
serverVersion: "Версия сервера",
info: "Информация",
connType: "Тип подключения",
+ allConnectionTypes: "Все типы",
+ unsupportedCompareConnection: "Это подключение недоступно или не поддерживает сравнение. Выберите другое подключение.",
connName: "Имя подключения",
host: "Хост",
addHost: "Добавить хост",
diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.ts
index c9c6bb1f12..59608d7f65 100644
--- a/apps/desktop/src/i18n/locales/zh-CN.ts
+++ b/apps/desktop/src/i18n/locales/zh-CN.ts
@@ -7598,6 +7598,8 @@ export default withEnglishFallback({
close: "关闭",
info: "信息",
connType: "连接类型",
+ allConnectionTypes: "全部类型",
+ unsupportedCompareConnection: "该连接不可用或不支持比较,请重新选择连接。",
connName: "连接名称",
host: "主机",
addHost: "添加主机",
diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.ts
index d9df6f7015..5e74bad07b 100644
--- a/apps/desktop/src/i18n/locales/zh-TW.ts
+++ b/apps/desktop/src/i18n/locales/zh-TW.ts
@@ -6096,6 +6096,8 @@ export default withEnglishFallback({
serverVersion: "伺服器版本",
info: "資訊",
connType: "連線類型",
+ allConnectionTypes: "全部類型",
+ unsupportedCompareConnection: "此連線無法使用或不支援比較,請重新選擇連線。",
connName: "連線名稱",
port: "連接埠",
saveConfigPrompt: "請輸入配置名稱:",
diff --git a/apps/desktop/src/lib/database/databaseCompareCapabilities.ts b/apps/desktop/src/lib/database/databaseCompareCapabilities.ts
new file mode 100644
index 0000000000..8e5ed12a40
--- /dev/null
+++ b/apps/desktop/src/lib/database/databaseCompareCapabilities.ts
@@ -0,0 +1,101 @@
+import type { ConnectionConfig, DatabaseType } from "@/types/database";
+import { CONNECTION_PROFILES, type ConnectionProfileDefinition } from "@/types/generated/connectionProfiles";
+import { databaseManifestEntry } from "@/lib/database/databaseDriverManifest";
+import { effectiveDatabaseTypeForConnection } from "@/lib/database/jdbcDialect";
+
+export type DatabaseCompareMode = "schema" | "data";
+
+// Comparison loads relational metadata and, for data, generates COUNT/SELECT
+// statements. Unknown providers must opt in here rather than pass a blacklist.
+const SQL_COMPARE_TYPES = new Set<DatabaseType>([
+ "mysql",
+ "postgres",
+ "sqlite",
+ "rqlite",
+ "turso",
+ "cloudflare-d1",
+ "duckdb",
+ "clickhouse",
+ "sqlserver",
+ "oracle",
+ "doris",
+ "starrocks",
+ "manticoresearch",
+ "redshift",
+ "dameng",
+ "kingbase",
+ "highgo",
+ "uxdb",
+ "vastbase",
+ "goldendb",
+ "databend",
+ "gaussdb",
+ "kwdb",
+ "yashandb",
+ "databricks",
+ "saphana",
+ "teradata",
+ "vertica",
+ "firebird",
+ "exasol",
+ "opengauss",
+ "questdb",
+ "oceanbase-oracle",
+ "gbase",
+ "access",
+ "h2",
+ "snowflake",
+ "trino",
+ "prestosql",
+ "hive",
+ "argo",
+ "transwarp",
+ "kyuubi",
+ "impala",
+ "db2",
+ "informix",
+ "bigquery",
+ "spanner",
+ "kylin",
+ "ignite",
+ "ignite3",
+ "sundb",
+ "oscar",
+ "tdengine",
+ "xugu",
+ "iotdb",
+ "iris",
+ "influxdb3",
+ "spark",
+]);
+
+export function supportsDatabaseCompare(connection: ConnectionConfig | undefined, mode: DatabaseCompareMode): boolean {
+ if (!connection) return false;
+ const type = effectiveDatabaseTypeForConnection(connection);
+ // Keep the two paths explicit: a future driver may support metadata compare
+ // without supporting the generated data comparison SQL (or vice versa).
+ switch (mode) {
+ case "schema":
+ case "data":
+ return !!type && SQL_COMPARE_TYPES.has(type);
+ }
+}
+
+const profiles: Readonly<Record<string, ConnectionProfileDefinition>> = CONNECTION_PROFILES;
+
+export function compareConnectionType(connection: ConnectionConfig): { value: string; label: string } {
+ const profile = connection.driver_profile;
+ const definition = profile ? profiles[profile] : undefined;
+ if (profile && definition && definition.type === connection.db_type) {
+ return { value: profile, label: definition.label };
+ }
+ // JDBC remains a distinct connection type, with a product-specific profile
+ // when present. Native legacy configs without a profile fall back to db_type.
+ if (connection.db_type === "jdbc" && profile) {
+ return {
+ value: `jdbc:${profile}`,
+ label: connection.driver_label || `${databaseManifestEntry(effectiveDatabaseTypeForConnection(connection))?.label || profile} (JDBC)`,
+ };
+ }
+ return { value: connection.db_type, label: databaseManifestEntry(connection.db_type)?.label || connection.driver_label || connection.db_type };
+}