fix(diff): filter comparison connections by type
This commit is contained in:
16 files changed
+780
-129
No files matched your search
@@ -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>
|
||||||
@@ -6,7 +6,8 @@ import { Button } from "@/components/ui/button";
|
|||||||
import { Label } from "@/components/ui/label";
|
import { Label } from "@/components/ui/label";
|
||||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||||
import SearchableSelect from "@/components/ui/searchable-select/SearchableSelect.vue";
|
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 { useConnectionStore } from "@/stores/connectionStore";
|
||||||
import { useToast } from "@/composables/useToast";
|
import { useToast } from "@/composables/useToast";
|
||||||
import { databaseOptionsForConnection, fetchNamespaceOptionsForConnection } from "@/composables/useDatabaseOptions";
|
import { databaseOptionsForConnection, fetchNamespaceOptionsForConnection } from "@/composables/useDatabaseOptions";
|
||||||
@@ -129,7 +130,34 @@ let configSaveTimer: ReturnType<typeof setTimeout> | undefined;
|
|||||||
let componentUnmounted = false;
|
let componentUnmounted = false;
|
||||||
let shownSessionError = "";
|
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 selectedSourceTableNames = computed(() => sourceTables.value.filter((table) => selectedSourceTables.value.has(table)));
|
||||||
const isBatchCompare = computed(() => selectedSourceTableNames.value.length > 1);
|
const isBatchCompare = computed(() => selectedSourceTableNames.value.length > 1);
|
||||||
// Bridge the shared TableMultiSelect `string[]` v-model with the Set-based selection store.
|
// 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;
|
if (!isTableColumnsKnown(row.table)) return false;
|
||||||
return row.columns.length === 0;
|
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 detailPreviewLimitNumber = computed(() => Number(detailPreviewLimit.value) || PREVIEW_LIMIT_OPTIONS[1]);
|
||||||
|
|
||||||
const sameTableCount = computed(() => batchResults.value.filter((item) => item.status === "same").length);
|
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 connectionId = sourceConnectionId.value;
|
||||||
const database = sourceDatabase.value;
|
const database = sourceDatabase.value;
|
||||||
const schema = sourceSchema.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;
|
const generation = columnMetadataGeneration;
|
||||||
loadingColumnTables.value = [...loadingColumnTables.value, table];
|
loadingColumnTables.value = [...loadingColumnTables.value, table];
|
||||||
try {
|
try {
|
||||||
@@ -503,15 +543,24 @@ async function applyDataCompareConfig(config: DataCompareConfig): Promise<void>
|
|||||||
shownSessionError = "";
|
shownSessionError = "";
|
||||||
try {
|
try {
|
||||||
sourceConnectionId.value = config.sourceConnectionId;
|
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;
|
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");
|
await loadDatabases(config.targetConnectionId, "target");
|
||||||
if (generation !== initializingPrefillGeneration) return;
|
if (generation !== initializingPrefillGeneration) return;
|
||||||
if (config.targetDatabase) targetDatabase.value = config.targetDatabase;
|
if (config.targetDatabase) targetDatabase.value = config.targetDatabase;
|
||||||
@@ -591,7 +640,9 @@ function applyDataCompareSession(session: DataCompareSession | undefined): void
|
|||||||
}
|
}
|
||||||
|
|
||||||
function swapSourceTarget() {
|
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 previousSelectedTables = [...selectedSourceTableNames.value];
|
||||||
const nextSingleTarget = previousSelectedTables.length === 1 ? (previousSelectedTables[0] ?? "") : "";
|
const nextSingleTarget = previousSelectedTables.length === 1 ? (previousSelectedTables[0] ?? "") : "";
|
||||||
const nextSourceSelection = previousSelectedTables.length <= 1 ? [targetTable.value].filter(Boolean) : previousSelectedTables;
|
const nextSourceSelection = previousSelectedTables.length <= 1 ? [targetTable.value].filter(Boolean) : previousSelectedTables;
|
||||||
@@ -620,7 +671,15 @@ function swapSourceTarget() {
|
|||||||
targetTable.value = nextSingleTarget;
|
targetTable.value = nextSingleTarget;
|
||||||
|
|
||||||
sourceTable.value = selectedSourceTableNames.value.length === 1 ? selectedSourceTableNames.value[0] : "";
|
sourceTable.value = selectedSourceTableNames.value.length === 1 ? selectedSourceTableNames.value[0] : "";
|
||||||
|
keyColumnOverrides.value = {};
|
||||||
|
resetTableColumnMetadata();
|
||||||
clearResult();
|
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> {
|
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 = "") {
|
async function loadSchemas(side: "source" | "target", preferredSchema = "") {
|
||||||
const connectionId = side === "source" ? sourceConnectionId.value : targetConnectionId.value;
|
const connectionId = side === "source" ? sourceConnectionId.value : targetConnectionId.value;
|
||||||
const database = side === "source" ? sourceDatabase.value : targetDatabase.value;
|
const database = side === "source" ? sourceDatabase.value : targetDatabase.value;
|
||||||
if (!connectionId || !database) return;
|
if (!connectionId || !database || !supportsDatabaseCompare(store.getConfig(connectionId), "data")) return;
|
||||||
const config = store.getConfig(connectionId);
|
pendingMetadataRequests.value += 1;
|
||||||
if (!isSchemaAware(config?.db_type)) {
|
try {
|
||||||
if (side === "source") {
|
const isCurrent = metadataRequestIsCurrent(side);
|
||||||
sourceSchemas.value = [];
|
const config = store.getConfig(connectionId);
|
||||||
sourceSchema.value = database;
|
if (!isSchemaAware(config?.db_type)) {
|
||||||
} else {
|
if (side === "source") {
|
||||||
targetSchemas.value = [];
|
sourceSchemas.value = [];
|
||||||
targetSchema.value = database;
|
sourceSchema.value = database;
|
||||||
|
} else {
|
||||||
|
targetSchemas.value = [];
|
||||||
|
targetSchema.value = database;
|
||||||
|
}
|
||||||
|
await loadTables(side);
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
await loadTables(side);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const schemas = await api.listSchemas(connectionId, database);
|
const schemas = await api.listSchemas(connectionId, database);
|
||||||
const schema = preferredSchema && schemas.includes(preferredSchema) ? preferredSchema : schemas.includes("public") ? "public" : (schemas[0] ?? "");
|
if (!isCurrent()) return;
|
||||||
if (side === "source") {
|
const schema = preferredSchema && schemas.includes(preferredSchema) ? preferredSchema : schemas.includes("public") ? "public" : (schemas[0] ?? "");
|
||||||
sourceSchemas.value = schemas;
|
if (side === "source") {
|
||||||
sourceSchema.value = schema;
|
sourceSchemas.value = schemas;
|
||||||
} else {
|
sourceSchema.value = schema;
|
||||||
targetSchemas.value = schemas;
|
} else {
|
||||||
targetSchema.value = schema;
|
targetSchemas.value = schemas;
|
||||||
|
targetSchema.value = schema;
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
pendingMetadataRequests.value -= 1;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function loadDatabases(connectionId: string, side: "source" | "target") {
|
async function loadDatabases(connectionId: string, side: "source" | "target") {
|
||||||
if (!connectionId) return;
|
if (!connectionId || !supportsDatabaseCompare(store.getConfig(connectionId), "data")) return;
|
||||||
await store.ensureConnected(connectionId);
|
pendingMetadataRequests.value += 1;
|
||||||
const config = store.getConfig(connectionId);
|
try {
|
||||||
const names = config
|
const isCurrent = metadataRequestIsCurrent(side);
|
||||||
? await fetchNamespaceOptionsForConnection(connectionId, config)
|
await store.ensureConnected(connectionId);
|
||||||
: databaseOptionsForConnection(
|
if (!isCurrent()) return;
|
||||||
(await api.listDatabases(connectionId)).map((database) => database.name),
|
const config = store.getConfig(connectionId);
|
||||||
config,
|
const names = config
|
||||||
);
|
? await fetchNamespaceOptionsForConnection(connectionId, config)
|
||||||
if (side === "source") {
|
: databaseOptionsForConnection(
|
||||||
sourceDatabases.value = names;
|
(await api.listDatabases(connectionId)).map((database) => database.name),
|
||||||
sourceDatabase.value = names.length === 1 ? names[0] : "";
|
config,
|
||||||
sourceSchemas.value = [];
|
);
|
||||||
sourceSchema.value = "";
|
if (!isCurrent()) return;
|
||||||
sourceTables.value = [];
|
if (side === "source") {
|
||||||
sourceTable.value = "";
|
sourceDatabases.value = names;
|
||||||
resetSelectedSourceTables([]);
|
sourceDatabase.value = names.length === 1 ? names[0] : "";
|
||||||
} else {
|
sourceSchemas.value = [];
|
||||||
targetDatabases.value = names;
|
sourceSchema.value = "";
|
||||||
targetDatabase.value = names.length === 1 ? names[0] : "";
|
sourceTables.value = [];
|
||||||
targetSchemas.value = [];
|
sourceTable.value = "";
|
||||||
targetSchema.value = "";
|
resetSelectedSourceTables([]);
|
||||||
targetTables.value = [];
|
} else {
|
||||||
targetTable.value = "";
|
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") {
|
async function loadTables(side: "source" | "target") {
|
||||||
const connectionId = side === "source" ? sourceConnectionId.value : targetConnectionId.value;
|
const connectionId = side === "source" ? sourceConnectionId.value : targetConnectionId.value;
|
||||||
const database = side === "source" ? sourceDatabase.value : targetDatabase.value;
|
const database = side === "source" ? sourceDatabase.value : targetDatabase.value;
|
||||||
if (!connectionId || !database) return;
|
if (!connectionId || !database || !supportsDatabaseCompare(store.getConfig(connectionId), "data")) return;
|
||||||
const schema = side === "source" ? sourceSchema.value || (await resolveSchema(connectionId, database, props.prefillSchema)) : targetSchema.value || (await resolveSchema(connectionId, database));
|
pendingMetadataRequests.value += 1;
|
||||||
const tables = (await api.listTables(connectionId, database, schema)).filter((table) => table.table_type !== "VIEW" && table.table_type !== "MATERIALIZED_VIEW").map((table) => table.name);
|
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") {
|
if (side === "source") {
|
||||||
const preferredSelection = props.prefillTable && tables.includes(props.prefillTable) ? [props.prefillTable] : [...selectedSourceTables.value].filter((table) => tables.includes(table));
|
const preferredSelection = props.prefillTable && tables.includes(props.prefillTable) ? [props.prefillTable] : [...selectedSourceTables.value].filter((table) => tables.includes(table));
|
||||||
sourceSchema.value = schema;
|
sourceSchema.value = schema;
|
||||||
sourceTables.value = tables;
|
sourceTables.value = tables;
|
||||||
resetSelectedSourceTables(preferredSelection);
|
resetSelectedSourceTables(preferredSelection);
|
||||||
sourceTable.value = preferredSelection.length === 1 ? preferredSelection[0] : "";
|
sourceTable.value = preferredSelection.length === 1 ? preferredSelection[0] : "";
|
||||||
} else {
|
} else {
|
||||||
targetSchema.value = schema;
|
targetSchema.value = schema;
|
||||||
targetTables.value = tables;
|
targetTables.value = tables;
|
||||||
const singleSourceTable = selectedSourceTableNames.value.length === 1 ? selectedSourceTableNames.value[0] : "";
|
const singleSourceTable = selectedSourceTableNames.value.length === 1 ? selectedSourceTableNames.value[0] : "";
|
||||||
const preferred = targetTable.value && tables.includes(targetTable.value) ? targetTable.value : singleSourceTable && tables.includes(singleSourceTable) ? singleSourceTable : "";
|
const preferred = targetTable.value && tables.includes(targetTable.value) ? targetTable.value : singleSourceTable && tables.includes(singleSourceTable) ? singleSourceTable : "";
|
||||||
targetTable.value = preferred;
|
targetTable.value = preferred;
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
pendingMetadataRequests.value -= 1;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1035,6 +1117,7 @@ function formatModifiedSummary(row: SelectableDataCompareModifiedRow): string {
|
|||||||
watch(sourceConnectionId, (id) => {
|
watch(sourceConnectionId, (id) => {
|
||||||
if (initializingPrefill) return;
|
if (initializingPrefill) return;
|
||||||
clearResult();
|
clearResult();
|
||||||
|
sourceDatabases.value = [];
|
||||||
sourceDatabase.value = "";
|
sourceDatabase.value = "";
|
||||||
sourceSchema.value = "";
|
sourceSchema.value = "";
|
||||||
sourceSchemas.value = [];
|
sourceSchemas.value = [];
|
||||||
@@ -1048,6 +1131,7 @@ watch(sourceConnectionId, (id) => {
|
|||||||
watch(targetConnectionId, (id) => {
|
watch(targetConnectionId, (id) => {
|
||||||
if (initializingPrefill) return;
|
if (initializingPrefill) return;
|
||||||
clearResult();
|
clearResult();
|
||||||
|
targetDatabases.value = [];
|
||||||
targetDatabase.value = "";
|
targetDatabase.value = "";
|
||||||
targetSchema.value = "";
|
targetSchema.value = "";
|
||||||
targetSchemas.value = [];
|
targetSchemas.value = [];
|
||||||
@@ -1158,6 +1242,13 @@ watch(
|
|||||||
suppressConfigSave = true;
|
suppressConfigSave = true;
|
||||||
try {
|
try {
|
||||||
sourceConnectionId.value = props.prefillConnectionId;
|
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");
|
await loadDatabases(props.prefillConnectionId, "source");
|
||||||
if (props.prefillDatabase) sourceDatabase.value = props.prefillDatabase;
|
if (props.prefillDatabase) sourceDatabase.value = props.prefillDatabase;
|
||||||
if (props.prefillDatabase) await loadSchemas("source", props.prefillSchema);
|
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>
|
<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") }}
|
{{ t("diff.source") }}
|
||||||
</div>
|
</div>
|
||||||
<ConnectionTreeSelect
|
<CompareConnectionSelect v-model="sourceConnectionId" :disabled="comparing || executionLocked" :connections="compareConnections" :layout="store.sidebarLayout" />
|
||||||
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)]"
|
|
||||||
/>
|
|
||||||
<SearchableSelect
|
<SearchableSelect
|
||||||
v-model="sourceDatabase"
|
v-model="sourceDatabase"
|
||||||
:options="sourceDatabases"
|
:options="sourceDatabases"
|
||||||
@@ -1277,7 +1358,7 @@ onBeforeUnmount(() => {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="flex items-center pt-6">
|
<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" />
|
<ArrowLeftRight class="w-3.5 h-3.5" />
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</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>
|
<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") }}
|
{{ t("diff.target") }}
|
||||||
</div>
|
</div>
|
||||||
<ConnectionTreeSelect
|
<CompareConnectionSelect v-model="targetConnectionId" :disabled="comparing || executionLocked" :connections="compareConnections" :layout="store.sidebarLayout" />
|
||||||
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)]"
|
|
||||||
/>
|
|
||||||
<SearchableSelect
|
<SearchableSelect
|
||||||
v-model="targetDatabase"
|
v-model="targetDatabase"
|
||||||
:options="targetDatabases"
|
:options="targetDatabases"
|
||||||
|
|||||||
@@ -6,7 +6,8 @@ import { Button } from "@/components/ui/button";
|
|||||||
import { Switch } from "@/components/ui/switch";
|
import { Switch } from "@/components/ui/switch";
|
||||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||||
import SearchableSelect from "@/components/ui/searchable-select/SearchableSelect.vue";
|
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 TableMultiSelect from "@/components/diff/TableMultiSelect.vue";
|
||||||
import { buildSchemaDiffTableMatches, availableSchemaDiffTargetTables, areSchemaDiffTableMappingsEqual, pruneSchemaDiffTableMappings, reconcileSchemaDiffTableMappings, updateSchemaDiffTableMapping, type SchemaDiffTableMatch } from "@/lib/schema/schemaDiffTableMapping";
|
import { buildSchemaDiffTableMatches, availableSchemaDiffTargetTables, areSchemaDiffTableMappingsEqual, pruneSchemaDiffTableMappings, reconcileSchemaDiffTableMappings, updateSchemaDiffTableMapping, type SchemaDiffTableMatch } from "@/lib/schema/schemaDiffTableMapping";
|
||||||
import {
|
import {
|
||||||
@@ -84,7 +85,34 @@ const targetSchemas = ref<string[]>([]);
|
|||||||
const sourceDbVersion = ref<string | null>(null);
|
const sourceDbVersion = ref<string | null>(null);
|
||||||
const targetDbVersion = 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 sourceConfig = computed(() => store.getConfig(props.sourceConnectionId));
|
||||||
const targetConfig = computed(() => store.getConfig(props.targetConnectionId));
|
const targetConfig = computed(() => store.getConfig(props.targetConnectionId));
|
||||||
@@ -197,7 +225,7 @@ function getTableIdentity(side: SchemaDiffTableSide): SchemaDiffTableIdentity {
|
|||||||
function isTableIdentityReady(side: SchemaDiffTableSide): boolean {
|
function isTableIdentityReady(side: SchemaDiffTableSide): boolean {
|
||||||
const identity = getTableIdentity(side);
|
const identity = getTableIdentity(side);
|
||||||
const config = side === "source" ? sourceConfig.value : targetConfig.value;
|
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 }>) {
|
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 database = side === "source" ? props.sourceDatabase : props.targetDatabase;
|
||||||
const schema = side === "source" ? props.sourceSchema : props.targetSchema;
|
const schema = side === "source" ? props.sourceSchema : props.targetSchema;
|
||||||
const dbType = side === "source" ? sourceDbType.value : targetDbType.value;
|
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 = [];
|
if (side === "source") sourceRoutineList.value = [];
|
||||||
else {
|
else {
|
||||||
targetRoutineList.value = [];
|
targetRoutineList.value = [];
|
||||||
@@ -348,12 +376,15 @@ async function loadRoutineList(side: "source" | "target") {
|
|||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
const isCurrent = metadataRequestIsCurrent(side);
|
||||||
try {
|
try {
|
||||||
loadingRoutines.value = true;
|
loadingRoutines.value = true;
|
||||||
await store.ensureConnected(connectionId);
|
await store.ensureConnected(connectionId);
|
||||||
|
if (!isCurrent()) return;
|
||||||
// Names/signatures only — avoid listFunctions N+1 source fetch on the config step.
|
// Names/signatures only — avoid listFunctions N+1 source fetch on the config step.
|
||||||
const kinds = schemaDiffRoutineObjectTypes(dbType as DatabaseType);
|
const kinds = schemaDiffRoutineObjectTypes(dbType as DatabaseType);
|
||||||
const objects = kinds.length === 0 ? [] : await api.listObjects(connectionId, database, schema, kinds);
|
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 ?? ""));
|
const keys = objects.map((object) => schemaDiffRoutineKey(object.name, object.signature ?? ""));
|
||||||
if (side === "source") {
|
if (side === "source") {
|
||||||
sourceRoutineList.value = keys;
|
sourceRoutineList.value = keys;
|
||||||
@@ -370,6 +401,7 @@ async function loadRoutineList(side: "source" | "target") {
|
|||||||
if (restrictRoutines.value) reconcileRoutineMappings(localSelectedRoutines.value, keys);
|
if (restrictRoutines.value) reconcileRoutineMappings(localSelectedRoutines.value, keys);
|
||||||
}
|
}
|
||||||
} catch {
|
} catch {
|
||||||
|
if (!isCurrent()) return;
|
||||||
if (side === "source") sourceRoutineList.value = [];
|
if (side === "source") sourceRoutineList.value = [];
|
||||||
else {
|
else {
|
||||||
targetRoutineList.value = [];
|
targetRoutineList.value = [];
|
||||||
@@ -454,6 +486,8 @@ const canCompare = computed(() => {
|
|||||||
const hasValidTableMappings = !tablesEnabled || !restrictTables.value || localSelectedTables.value.length === 0 || isTableIdentityReady("target");
|
const hasValidTableMappings = !tablesEnabled || !restrictTables.value || localSelectedTables.value.length === 0 || isTableIdentityReady("target");
|
||||||
const hasValidRoutineMappings = !routinesEnabled || !restrictRoutines.value || localSelectedRoutines.value.length === 0 || isTableIdentityReady("target");
|
const hasValidRoutineMappings = !routinesEnabled || !restrictRoutines.value || localSelectedRoutines.value.length === 0 || isTableIdentityReady("target");
|
||||||
return (
|
return (
|
||||||
|
supportsDatabaseCompare(sourceConfig.value, "schema") &&
|
||||||
|
supportsDatabaseCompare(targetConfig.value, "schema") &&
|
||||||
props.sourceConnectionId &&
|
props.sourceConnectionId &&
|
||||||
props.targetConnectionId &&
|
props.targetConnectionId &&
|
||||||
props.sourceDatabase &&
|
props.sourceDatabase &&
|
||||||
@@ -468,11 +502,14 @@ const canCompare = computed(() => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
async function loadDatabases(connectionId: string, side: "source" | "target") {
|
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 {
|
try {
|
||||||
await store.ensureConnected(connectionId);
|
await store.ensureConnected(connectionId);
|
||||||
|
if (!isCurrent()) return;
|
||||||
const config = store.getConfig(connectionId);
|
const config = store.getConfig(connectionId);
|
||||||
const dbNames = config ? await fetchNamespaceOptionsForConnection(connectionId, config) : (await api.listDatabases(connectionId)).map((db) => db.name);
|
const dbNames = config ? await fetchNamespaceOptionsForConnection(connectionId, config) : (await api.listDatabases(connectionId)).map((db) => db.name);
|
||||||
|
if (!isCurrent()) return;
|
||||||
if (side === "source") {
|
if (side === "source") {
|
||||||
sourceDatabases.value = dbNames;
|
sourceDatabases.value = dbNames;
|
||||||
if (props.sourceDatabase) {
|
if (props.sourceDatabase) {
|
||||||
@@ -493,6 +530,7 @@ async function loadDatabases(connectionId: string, side: "source" | "target") {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch {
|
} catch {
|
||||||
|
if (!isCurrent()) return;
|
||||||
if (side === "source") {
|
if (side === "source") {
|
||||||
sourceDatabases.value = [];
|
sourceDatabases.value = [];
|
||||||
sourceDbVersion.value = null;
|
sourceDbVersion.value = null;
|
||||||
@@ -507,11 +545,14 @@ async function loadSchemas(side: "source" | "target") {
|
|||||||
const connectionId = side === "source" ? props.sourceConnectionId : props.targetConnectionId;
|
const connectionId = side === "source" ? props.sourceConnectionId : props.targetConnectionId;
|
||||||
const database = side === "source" ? props.sourceDatabase : props.targetDatabase;
|
const database = side === "source" ? props.sourceDatabase : props.targetDatabase;
|
||||||
const schema = side === "source" ? props.sourceSchema : props.targetSchema;
|
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 {
|
try {
|
||||||
await store.ensureConnected(connectionId);
|
await store.ensureConnected(connectionId);
|
||||||
|
if (!isCurrent()) return;
|
||||||
const schemas = await api.listSchemas(connectionId, database);
|
const schemas = await api.listSchemas(connectionId, database);
|
||||||
|
if (!isCurrent()) return;
|
||||||
if (side === "source") {
|
if (side === "source") {
|
||||||
sourceSchemas.value = schemas;
|
sourceSchemas.value = schemas;
|
||||||
} else {
|
} else {
|
||||||
@@ -519,6 +560,7 @@ async function loadSchemas(side: "source" | "target") {
|
|||||||
}
|
}
|
||||||
await fetchDbVersion(connectionId, database, schema, side);
|
await fetchDbVersion(connectionId, database, schema, side);
|
||||||
} catch {
|
} catch {
|
||||||
|
if (!isCurrent()) return;
|
||||||
if (side === "source") {
|
if (side === "source") {
|
||||||
sourceSchemas.value = [];
|
sourceSchemas.value = [];
|
||||||
} else {
|
} else {
|
||||||
@@ -530,6 +572,9 @@ async function loadSchemas(side: "source" | "target") {
|
|||||||
watch(
|
watch(
|
||||||
() => props.sourceConnectionId,
|
() => props.sourceConnectionId,
|
||||||
async (id) => {
|
async (id) => {
|
||||||
|
sourceDatabases.value = [];
|
||||||
|
sourceSchemas.value = [];
|
||||||
|
sourceDbVersion.value = null;
|
||||||
if (id) {
|
if (id) {
|
||||||
await loadDatabases(id, "source");
|
await loadDatabases(id, "source");
|
||||||
} else {
|
} else {
|
||||||
@@ -554,6 +599,9 @@ watch(
|
|||||||
watch(
|
watch(
|
||||||
() => props.targetConnectionId,
|
() => props.targetConnectionId,
|
||||||
async (id) => {
|
async (id) => {
|
||||||
|
targetDatabases.value = [];
|
||||||
|
targetSchemas.value = [];
|
||||||
|
targetDbVersion.value = null;
|
||||||
if (id) {
|
if (id) {
|
||||||
await loadDatabases(id, "target");
|
await loadDatabases(id, "target");
|
||||||
} else {
|
} else {
|
||||||
@@ -615,6 +663,8 @@ function getConnectionInfo(connectionId: string) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function fetchDbVersion(connectionId: string, database: string, schema: string, side: "source" | "target") {
|
async function fetchDbVersion(connectionId: string, database: string, schema: string, side: "source" | "target") {
|
||||||
|
if (!supportsDatabaseCompare(store.getConfig(connectionId), "schema")) return;
|
||||||
|
const isCurrent = metadataRequestIsCurrent(side);
|
||||||
try {
|
try {
|
||||||
await store.ensureConnected(connectionId);
|
await store.ensureConnected(connectionId);
|
||||||
const config = store.getConfig(connectionId);
|
const config = store.getConfig(connectionId);
|
||||||
@@ -634,7 +684,9 @@ async function fetchDbVersion(connectionId: string, database: string, schema: st
|
|||||||
default:
|
default:
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
if (!isCurrent()) return;
|
||||||
const result = await api.executeQuery(connectionId, database, sql, schema || undefined);
|
const result = await api.executeQuery(connectionId, database, sql, schema || undefined);
|
||||||
|
if (!isCurrent()) return;
|
||||||
if (result.rows && result.rows.length > 0) {
|
if (result.rows && result.rows.length > 0) {
|
||||||
const version = String(result.rows[0][0]);
|
const version = String(result.rows[0][0]);
|
||||||
if (side === "source") {
|
if (side === "source") {
|
||||||
@@ -644,6 +696,7 @@ async function fetchDbVersion(connectionId: string, database: string, schema: st
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
if (!isCurrent()) return;
|
||||||
console.error(`[fetchDbVersion] Failed to fetch version for ${side}:`, e);
|
console.error(`[fetchDbVersion] Failed to fetch version for ${side}:`, e);
|
||||||
if (side === "source") {
|
if (side === "source") {
|
||||||
sourceDbVersion.value = null;
|
sourceDbVersion.value = null;
|
||||||
@@ -681,17 +734,7 @@ async function fetchDbVersion(connectionId: string, database: string, schema: st
|
|||||||
|
|
||||||
<div class="space-y-1.5">
|
<div class="space-y-1.5">
|
||||||
<Label class="text-xs">{{ t("diff.connection") }}</Label>
|
<Label class="text-xs">{{ t("diff.connection") }}</Label>
|
||||||
<ConnectionTreeSelect
|
<CompareConnectionSelect :model-value="sourceConnectionId" @update:model-value="(v: string) => $emit('update:sourceConnectionId', v)" :connections="compareConnections" :layout="store.sidebarLayout" :disabled="loading" />
|
||||||
: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)]"
|
|
||||||
/>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="space-y-1.5">
|
<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">
|
<div class="space-y-1.5">
|
||||||
<Label class="text-xs">{{ t("diff.connection") }}</Label>
|
<Label class="text-xs">{{ t("diff.connection") }}</Label>
|
||||||
<ConnectionTreeSelect
|
<CompareConnectionSelect :model-value="targetConnectionId" @update:model-value="(v: string) => $emit('update:targetConnectionId', v)" :connections="compareConnections" :layout="store.sidebarLayout" :disabled="loading" />
|
||||||
: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)]"
|
|
||||||
/>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="space-y-1.5">
|
<div class="space-y-1.5">
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import { GitCompareArrows, ArrowLeft, Play, Loader2, Maximize2, Minimize2, Alert
|
|||||||
import * as api from "@/lib/backend/api";
|
import * as api from "@/lib/backend/api";
|
||||||
import { executeWithProductionSqlGuard } from "@/lib/database/productionExecutionGuard";
|
import { executeWithProductionSqlGuard } from "@/lib/database/productionExecutionGuard";
|
||||||
import { isSchemaAware } from "@/lib/database/databaseCapabilities";
|
import { isSchemaAware } from "@/lib/database/databaseCapabilities";
|
||||||
|
import { supportsDatabaseCompare } from "@/lib/database/databaseCompareCapabilities";
|
||||||
import { useSchemaDiffConfig } from "@/composables/useSchemaDiffConfig";
|
import { useSchemaDiffConfig } from "@/composables/useSchemaDiffConfig";
|
||||||
import SchemaDiffConfigStep from "@/components/diff/SchemaDiffConfigStep.vue";
|
import SchemaDiffConfigStep from "@/components/diff/SchemaDiffConfigStep.vue";
|
||||||
import SchemaDiffConfigSelector from "@/components/diff/SchemaDiffConfigSelector.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 {
|
function clearCompareObjectSelection(): void {
|
||||||
if (!activeConfig.value) return;
|
if (!activeConfig.value) return;
|
||||||
updateActiveConfigOptions(
|
updateActiveConfigOptions(
|
||||||
@@ -729,6 +738,7 @@ function handleFieldMappingsUpdate(mappings: FieldMappingEntry[]) {
|
|||||||
function handleCompare(): void {
|
function handleCompare(): void {
|
||||||
const sourceConfig = store.getConfig(sourceConnectionId.value);
|
const sourceConfig = store.getConfig(sourceConnectionId.value);
|
||||||
const targetConfig = store.getConfig(targetConnectionId.value);
|
const targetConfig = store.getConfig(targetConnectionId.value);
|
||||||
|
if (!supportsDatabaseCompare(sourceConfig, "schema") || !supportsDatabaseCompare(targetConfig, "schema")) return;
|
||||||
const targetDbType = (targetConfig?.db_type || "mysql") as DatabaseType;
|
const targetDbType = (targetConfig?.db_type || "mysql") as DatabaseType;
|
||||||
const sourceDbType = sourceConfig?.db_type || targetDbType;
|
const sourceDbType = sourceConfig?.db_type || targetDbType;
|
||||||
const options = normalizeSchemaDiffCompareOptions(activeConfig.value?.options, 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) {
|
async function fetchDbVersion(connectionId: string, database: string, schema: string) {
|
||||||
|
if (!supportsDatabaseCompare(store.getConfig(connectionId), "schema")) return;
|
||||||
try {
|
try {
|
||||||
await store.ensureConnected(connectionId);
|
await store.ensureConnected(connectionId);
|
||||||
const config = store.getConfig(connectionId);
|
const config = store.getConfig(connectionId);
|
||||||
@@ -1307,7 +1318,8 @@ const targetConnectionInfo = computed(() => {
|
|||||||
<SchemaDiffConfigStep
|
<SchemaDiffConfigStep
|
||||||
v-if="step === 'config'"
|
v-if="step === 'config'"
|
||||||
class="shrink-0"
|
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-database="sourceDatabase"
|
||||||
v-model:source-schema="sourceSchema"
|
v-model:source-schema="sourceSchema"
|
||||||
v-model:target-connection-id="targetConnectionId"
|
v-model:target-connection-id="targetConnectionId"
|
||||||
|
|||||||
@@ -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();
|
||||||
|
});
|
||||||
+119
-5
@@ -1,7 +1,7 @@
|
|||||||
// @vitest-environment happy-dom
|
// @vitest-environment happy-dom
|
||||||
|
|
||||||
import { createApp, defineComponent, h, nextTick, type App } from "vue";
|
import { createApp, defineComponent, h, nextTick, reactive, type App } from "vue";
|
||||||
import { afterEach, expect, it, vi } from "vitest";
|
import { afterEach, beforeEach, expect, it, vi } from "vitest";
|
||||||
import i18n from "@/i18n";
|
import i18n from "@/i18n";
|
||||||
import { getDefaultOptionsForDbType } from "@/types/schemaDiff";
|
import { getDefaultOptionsForDbType } from "@/types/schemaDiff";
|
||||||
import SchemaDiffConfigStep from "@/components/diff/SchemaDiffConfigStep.vue";
|
import SchemaDiffConfigStep from "@/components/diff/SchemaDiffConfigStep.vue";
|
||||||
@@ -10,15 +10,17 @@ const mocks = vi.hoisted(() => ({
|
|||||||
ensureConnected: vi.fn().mockResolvedValue(undefined),
|
ensureConnected: vi.fn().mockResolvedValue(undefined),
|
||||||
listDatabases: vi.fn().mockResolvedValue([]),
|
listDatabases: vi.fn().mockResolvedValue([]),
|
||||||
listSchemas: vi.fn().mockResolvedValue(["APP", "REPORTING"]),
|
listSchemas: vi.fn().mockResolvedValue(["APP", "REPORTING"]),
|
||||||
|
executeQuery: vi.fn().mockResolvedValue({ rows: [] }),
|
||||||
}));
|
}));
|
||||||
|
|
||||||
vi.mock("@/stores/connectionStore", () => {
|
vi.mock("@/stores/connectionStore", () => {
|
||||||
const connection = { id: "oracle-11g", name: "Oracle 11g", db_type: "oracle", driver_profile: "oracle", database: "XE" };
|
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 {
|
return {
|
||||||
useConnectionStore: () => ({
|
useConnectionStore: () => ({
|
||||||
connections: [connection],
|
connections,
|
||||||
sidebarLayout: { groups: [], order: [{ type: "connection", id: connection.id }] },
|
sidebarLayout: { groups: [], order: connections.map(({ id }) => ({ type: "connection", id })) },
|
||||||
getConfig: (id: string) => (id === connection.id ? connection : undefined),
|
getConfig: (id: string) => connections.find((item) => item.id === id),
|
||||||
ensureConnected: mocks.ensureConnected,
|
ensureConnected: mocks.ensureConnected,
|
||||||
}),
|
}),
|
||||||
};
|
};
|
||||||
@@ -27,10 +29,63 @@ vi.mock("@/stores/connectionStore", () => {
|
|||||||
vi.mock("@/lib/backend/api", () => ({
|
vi.mock("@/lib/backend/api", () => ({
|
||||||
listDatabases: mocks.listDatabases,
|
listDatabases: mocks.listDatabases,
|
||||||
listSchemas: mocks.listSchemas,
|
listSchemas: mocks.listSchemas,
|
||||||
|
executeQuery: mocks.executeQuery,
|
||||||
}));
|
}));
|
||||||
|
|
||||||
const mountedApps: App[] = [];
|
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() {
|
async function flushAsyncSetup() {
|
||||||
for (let index = 0; index < 8; index += 1) {
|
for (let index = 0; index < 8; index += 1) {
|
||||||
await nextTick();
|
await nextTick();
|
||||||
@@ -82,3 +137,62 @@ it("offers Oracle schemas as schema-diff database choices", async () => {
|
|||||||
expect(mocks.listDatabases).not.toHaveBeenCalled();
|
expect(mocks.listDatabases).not.toHaveBeenCalled();
|
||||||
expect(mocks.listSchemas).toHaveBeenCalledWith("oracle-11g", "XE", true);
|
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"]);
|
||||||
|
});
|
||||||
@@ -7685,6 +7685,8 @@ export default {
|
|||||||
serverVersion: "Server Version",
|
serverVersion: "Server Version",
|
||||||
info: "Info",
|
info: "Info",
|
||||||
connType: "Connection type",
|
connType: "Connection type",
|
||||||
|
allConnectionTypes: "All types",
|
||||||
|
unsupportedCompareConnection: "This connection is unavailable or does not support comparison. Please select another connection.",
|
||||||
connName: "Connection name",
|
connName: "Connection name",
|
||||||
host: "Host",
|
host: "Host",
|
||||||
addHost: "Add Host",
|
addHost: "Add Host",
|
||||||
|
|||||||
@@ -6978,6 +6978,8 @@ export default withEnglishFallback({
|
|||||||
serverVersion: "Versión del servidor",
|
serverVersion: "Versión del servidor",
|
||||||
info: "Información",
|
info: "Información",
|
||||||
connType: "Tipo de conexió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",
|
connName: "Nombre de conexión",
|
||||||
host: "Host",
|
host: "Host",
|
||||||
addHost: "Añadir Host",
|
addHost: "Añadir Host",
|
||||||
|
|||||||
@@ -6761,6 +6761,8 @@ export default withEnglishFallback({
|
|||||||
serverVersion: "Versione Server",
|
serverVersion: "Versione Server",
|
||||||
info: "Info",
|
info: "Info",
|
||||||
connType: "Tipo connessione",
|
connType: "Tipo connessione",
|
||||||
|
allConnectionTypes: "Tutti i tipi",
|
||||||
|
unsupportedCompareConnection: "Questa connessione non è disponibile o non supporta il confronto. Seleziona un'altra connessione.",
|
||||||
connName: "Nome connessione",
|
connName: "Nome connessione",
|
||||||
host: "Host",
|
host: "Host",
|
||||||
port: "Porta",
|
port: "Porta",
|
||||||
|
|||||||
@@ -6792,6 +6792,8 @@ export default withEnglishFallback({
|
|||||||
restore: "復元",
|
restore: "復元",
|
||||||
info: "情報",
|
info: "情報",
|
||||||
connType: "接続タイプ",
|
connType: "接続タイプ",
|
||||||
|
allConnectionTypes: "すべてのタイプ",
|
||||||
|
unsupportedCompareConnection: "この接続は利用できないか、比較に対応していません。別の接続を選択してください。",
|
||||||
connName: "接続名",
|
connName: "接続名",
|
||||||
host: "ホスト",
|
host: "ホスト",
|
||||||
port: "ポート",
|
port: "ポート",
|
||||||
|
|||||||
@@ -6572,6 +6572,8 @@ export default withEnglishFallback({
|
|||||||
serverVersion: "서버 버전",
|
serverVersion: "서버 버전",
|
||||||
info: "정보",
|
info: "정보",
|
||||||
connType: "연결 유형",
|
connType: "연결 유형",
|
||||||
|
allConnectionTypes: "모든 유형",
|
||||||
|
unsupportedCompareConnection: "이 연결은 사용할 수 없거나 비교를 지원하지 않습니다. 다른 연결을 선택하세요.",
|
||||||
connName: "연결 이름",
|
connName: "연결 이름",
|
||||||
host: "호스트",
|
host: "호스트",
|
||||||
port: "포트",
|
port: "포트",
|
||||||
|
|||||||
@@ -6762,6 +6762,8 @@ export default withEnglishFallback({
|
|||||||
serverVersion: "Versão do Servidor",
|
serverVersion: "Versão do Servidor",
|
||||||
info: "Informações",
|
info: "Informações",
|
||||||
connType: "Tipo de conexão",
|
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",
|
connName: "Nome da conexão",
|
||||||
host: "Host",
|
host: "Host",
|
||||||
port: "Porta",
|
port: "Porta",
|
||||||
|
|||||||
@@ -8008,6 +8008,8 @@ export default withEnglishFallback({
|
|||||||
serverVersion: "Версия сервера",
|
serverVersion: "Версия сервера",
|
||||||
info: "Информация",
|
info: "Информация",
|
||||||
connType: "Тип подключения",
|
connType: "Тип подключения",
|
||||||
|
allConnectionTypes: "Все типы",
|
||||||
|
unsupportedCompareConnection: "Это подключение недоступно или не поддерживает сравнение. Выберите другое подключение.",
|
||||||
connName: "Имя подключения",
|
connName: "Имя подключения",
|
||||||
host: "Хост",
|
host: "Хост",
|
||||||
addHost: "Добавить хост",
|
addHost: "Добавить хост",
|
||||||
|
|||||||
@@ -7598,6 +7598,8 @@ export default withEnglishFallback({
|
|||||||
close: "关闭",
|
close: "关闭",
|
||||||
info: "信息",
|
info: "信息",
|
||||||
connType: "连接类型",
|
connType: "连接类型",
|
||||||
|
allConnectionTypes: "全部类型",
|
||||||
|
unsupportedCompareConnection: "该连接不可用或不支持比较,请重新选择连接。",
|
||||||
connName: "连接名称",
|
connName: "连接名称",
|
||||||
host: "主机",
|
host: "主机",
|
||||||
addHost: "添加主机",
|
addHost: "添加主机",
|
||||||
|
|||||||
@@ -6096,6 +6096,8 @@ export default withEnglishFallback({
|
|||||||
serverVersion: "伺服器版本",
|
serverVersion: "伺服器版本",
|
||||||
info: "資訊",
|
info: "資訊",
|
||||||
connType: "連線類型",
|
connType: "連線類型",
|
||||||
|
allConnectionTypes: "全部類型",
|
||||||
|
unsupportedCompareConnection: "此連線無法使用或不支援比較,請重新選擇連線。",
|
||||||
connName: "連線名稱",
|
connName: "連線名稱",
|
||||||
port: "連接埠",
|
port: "連接埠",
|
||||||
saveConfigPrompt: "請輸入配置名稱:",
|
saveConfigPrompt: "請輸入配置名稱:",
|
||||||
|
|||||||
@@ -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 };
|
||||||
|
}
|
||||||
Reference in new issue
Block a user