feat(editor): merge multi-database query results into one view
This commit is contained in:
1 parent
9d07708617
commit
8b822e974b
31 files changed
+3085
-87
No files matched your search
@@ -1,7 +1,7 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, onMounted, ref, watch } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { AlertTriangle, Check, CheckSquare, ChevronDown, ChevronRight, FolderOpen, Layers, Loader2, MinusSquare, Pencil, Play, RefreshCw, Search, Settings2, Square, Trash2, X } from "@lucide/vue";
|
||||
import { AlertTriangle, Check, CheckSquare, ChevronDown, ChevronRight, Download, FolderOpen, Layers, Loader2, MinusSquare, Pencil, Play, RefreshCw, Search, Settings2, Square, Trash2, X } from "@lucide/vue";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
@@ -9,11 +9,13 @@ import { Input } from "@/components/ui/input";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { ScrollArea } from "@/components/ui/scroll-area";
|
||||
import DatabaseIcon from "@/components/icons/DatabaseIcon.vue";
|
||||
import MultiSourceMergeView from "@/components/editor/MultiSourceMergeView.vue";
|
||||
import { useToast } from "@/composables/useToast";
|
||||
import { useMultiDbExecution, type MultiDbExecutionAdapter, type MultiDbExecutionMode } from "@/composables/useMultiDbExecution";
|
||||
import { formatDataTransferDuration, useExportTracker } from "@/composables/useExportTracker";
|
||||
import { useMultiDbTargetSelection, type MultiDbTargetCatalogOption, type SqlExecutionTargetValidationReason } from "@/composables/useMultiDbTargetSelection";
|
||||
import { useSqlExecutionTargetGroupStore } from "@/stores/sqlExecutionTargetGroupStore";
|
||||
import { useSqlExecutionDangerStore } from "@/stores/sqlExecutionDangerStore";
|
||||
import { dedupeMultiDbExecutionTargets, multiDbExecutionTargetKey, type MultiDbExecutionTarget, type MultiDbExecutionItemStatus, type SqlExecutionTargetGroup, type SqlExecutionTargetValidation } from "@/types/sqlExecution";
|
||||
import type { ConnectionConfig, DatabaseType } from "@/types/database";
|
||||
import { effectiveDatabaseTypeForConnection } from "@/lib/database/jdbcDialect";
|
||||
@@ -40,6 +42,7 @@ const { t } = useI18n();
|
||||
const { toast } = useToast();
|
||||
const { addMultiDbExecutionTask, updateMultiDbExecutionTask, registerTaskCancelHandler, unregisterTaskCancelHandler } = useExportTracker();
|
||||
const targetGroupStore = useSqlExecutionTargetGroupStore();
|
||||
const sqlExecutionDangerStore = useSqlExecutionDangerStore();
|
||||
const targetSelection = useMultiDbTargetSelection(computed(() => props.databaseType));
|
||||
const compatibleConnections = targetSelection.compatibleConnections;
|
||||
|
||||
@@ -123,11 +126,137 @@ const progressCounts = computed(() => {
|
||||
pendingCommit: items.filter((item) => item.status === "pending_commit").length,
|
||||
};
|
||||
});
|
||||
const elapsedMs = computed(() => {
|
||||
/**
|
||||
* A target parked on the danger confirmation is waiting for the operator, not
|
||||
* executing: that wait must not count as batch time or as target time.
|
||||
*/
|
||||
const awaitingConfirmation = computed(() => {
|
||||
const pending = sqlExecutionDangerStore.pending;
|
||||
return pending !== undefined && pending.scopeId !== undefined && pending.scopeId === batch.value?.id;
|
||||
});
|
||||
const confirmationWaitMs = ref(0);
|
||||
/** Value shown while a prompt is on screen, so the clock visibly stands still. */
|
||||
const frozenElapsedMs = ref<number>();
|
||||
let confirmationWaitStartedAt: number | undefined;
|
||||
/** Batch time with every answered prompt already taken out. */
|
||||
function elapsedWithoutWaits(): number {
|
||||
const current = batch.value;
|
||||
if (!current) return 0;
|
||||
return current.durationMs ?? Math.max(0, (current.completedAt ?? currentTime.value) - current.startedAt);
|
||||
});
|
||||
const total = current.durationMs ?? Math.max(0, (current.completedAt ?? currentTime.value) - current.startedAt);
|
||||
return Math.max(0, total - confirmationWaitMs.value);
|
||||
}
|
||||
watch(
|
||||
() => [batch.value?.id, awaitingConfirmation.value] as const,
|
||||
([batchId, waiting], [previousBatchId, wasWaiting]) => {
|
||||
if (batchId !== previousBatchId) {
|
||||
confirmationWaitMs.value = 0;
|
||||
confirmationWaitStartedAt = undefined;
|
||||
frozenElapsedMs.value = undefined;
|
||||
}
|
||||
if (waiting) {
|
||||
confirmationWaitStartedAt = Date.now();
|
||||
frozenElapsedMs.value = elapsedWithoutWaits();
|
||||
return;
|
||||
}
|
||||
if (wasWaiting && confirmationWaitStartedAt !== undefined) {
|
||||
confirmationWaitMs.value += Date.now() - confirmationWaitStartedAt;
|
||||
confirmationWaitStartedAt = undefined;
|
||||
frozenElapsedMs.value = undefined;
|
||||
}
|
||||
},
|
||||
{ flush: "sync" },
|
||||
);
|
||||
/** Label of the target whose confirmation is on screen, when one is parked. */
|
||||
const awaitingTargetLabel = computed(() => (awaitingConfirmation.value ? sqlExecutionDangerStore.pending?.targetLabel : undefined));
|
||||
function isAwaitingTarget(item: { target: MultiDbExecutionTarget; status: MultiDbExecutionItemStatus }): boolean {
|
||||
if (item.status !== "running" || awaitingTargetLabel.value === undefined) return false;
|
||||
return targetLabel(item.target) === awaitingTargetLabel.value;
|
||||
}
|
||||
const elapsedMs = computed(() => (awaitingConfirmation.value && frozenElapsedMs.value !== undefined ? frozenElapsedMs.value : elapsedWithoutWaits()));
|
||||
|
||||
/** Merged multi-source view over the results this batch produced. */
|
||||
const mergeViewOpen = ref(false);
|
||||
const mergeViewRef = ref<InstanceType<typeof MultiSourceMergeView>>();
|
||||
const mergeItems = computed(() =>
|
||||
(batch.value?.items ?? []).map((item) => ({
|
||||
key: item.id,
|
||||
label: targetLabel(item.target),
|
||||
result: item.result,
|
||||
status: item.status,
|
||||
durationMs: item.durationMs,
|
||||
errorMessage: item.errorMessage,
|
||||
...(item.transaction ? { transaction: { canCommit: item.transaction.canCommit, settling: item.settling === true } } : {}),
|
||||
})),
|
||||
);
|
||||
/** Targets whose result is worth merging, settled or still inside a transaction. */
|
||||
const mergedResultCount = computed(() => (batch.value?.items ?? []).filter((item) => item.status === "success" || item.status === "pending_commit").length);
|
||||
/** Merging needs more than one source; the view also reports failed targets. */
|
||||
const canShowMergedResults = computed(() => !isExecuting.value && (batch.value?.items.length ?? 0) >= 2);
|
||||
const batchSettled = computed(() => batch.value !== undefined && batch.value.status !== "running" && batch.value.status !== "cancelling");
|
||||
/** The batch opened a transaction per target, so writes stay reviewable. */
|
||||
const mergeBatchIsTransactional = computed(() => batch.value?.context.manualTransaction === true || (batch.value?.items ?? []).some((item) => item.transaction !== undefined || item.status === "pending_commit" || item.status === "rolled_back"));
|
||||
|
||||
/**
|
||||
* Settles one target's transaction through the batch's own state machine.
|
||||
* `commit` writes the changes of that target only; a target that errored has
|
||||
* nothing to commit and is rolled back by the executor instead.
|
||||
*/
|
||||
async function settleMergeTargetTransaction(itemId: string, action: "commit" | "rollback"): Promise<void> {
|
||||
const item = batch.value?.items.find((candidate) => candidate.id === itemId);
|
||||
if (!item?.transaction || item.settling) return;
|
||||
const settled = await execution.finishTransaction(itemId, action);
|
||||
if (!settled) toast(item.errorMessage ? t("multiDbExecute.txnActionFailed", { message: item.errorMessage }) : t("common.failed"), 5000);
|
||||
}
|
||||
|
||||
/** Commits every target that succeeded, leaving errored ones for a decision. */
|
||||
async function commitAllMergeTargets(): Promise<void> {
|
||||
const targets = (batch.value?.items ?? []).filter((item) => item.transaction?.canCommit === true);
|
||||
for (const item of targets) await settleMergeTargetTransaction(item.id, "commit");
|
||||
}
|
||||
|
||||
/** Discards every still-open transaction of the batch. */
|
||||
async function rollbackAllMergeTargets(): Promise<void> {
|
||||
const targets = (batch.value?.items ?? []).filter((item) => item.transaction !== undefined);
|
||||
for (const item of targets) await settleMergeTargetTransaction(item.id, "rollback");
|
||||
}
|
||||
|
||||
function revealMergedView(): void {
|
||||
mergeViewOpen.value = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-runs the batch's statement on one target only — the merged view uses it to
|
||||
* retry a target that failed without redoing the ones that succeeded.
|
||||
*/
|
||||
async function rerunMergeTarget(itemId: string): Promise<void> {
|
||||
await execution.retry(itemId);
|
||||
}
|
||||
|
||||
/**
|
||||
* A finished batch that produced data on several targets is worth looking at,
|
||||
* so reopening the dialog lands directly in the merged view instead of making
|
||||
* the user click through the progress list again.
|
||||
*/
|
||||
function revealMergedViewWhenSettled(): void {
|
||||
if (mergeViewOpen.value || !canShowMergedResults.value || !batchSettled.value) return;
|
||||
revealMergedView();
|
||||
}
|
||||
|
||||
/**
|
||||
* The batch may finish while the dialog is minimized to the background task
|
||||
* list. Announce it with an action that jumps straight into the merged view.
|
||||
*/
|
||||
function announceMergedViewInBackground(current: NonNullable<typeof batch.value>): void {
|
||||
if (open.value || current.cancelRequested) return;
|
||||
if (current.status !== "completed" || mergedResultCount.value < 2) return;
|
||||
toast(t("multiDbExecute.backgroundBatchDone", { count: mergedResultCount.value }), 8000, {
|
||||
label: t("multiDbExecute.mergeResults"),
|
||||
onClick: () => {
|
||||
open.value = true;
|
||||
revealMergedView();
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function syncBackgroundTask(current: NonNullable<typeof batch.value>): void {
|
||||
const items = current.items;
|
||||
@@ -169,10 +298,14 @@ watch(
|
||||
addMultiDbExecutionTask(current.id, t("multiDbExecute.title"), current.sourceTabId, () => {
|
||||
open.value = true;
|
||||
});
|
||||
registerTaskCancelHandler(current.id, () => execution.cancel());
|
||||
}
|
||||
syncBackgroundTask(current);
|
||||
if (current.status === "completed" || current.status === "cancelled") unregisterTaskCancelHandler(current.id);
|
||||
if (current.status === "running") {
|
||||
registerTaskCancelHandler(current.id, () => execution.cancel());
|
||||
} else if (current.status === "completed" || current.status === "cancelled") {
|
||||
unregisterTaskCancelHandler(current.id);
|
||||
announceMergedViewInBackground(current);
|
||||
}
|
||||
},
|
||||
{ deep: true, flush: "sync" },
|
||||
);
|
||||
@@ -675,6 +808,7 @@ function openForNewBatch(): void {
|
||||
executionMode.value = "serial";
|
||||
manualTransaction.value = props.initialManualTransaction === true && supportsManualTransaction.value;
|
||||
trackedBatchId = undefined;
|
||||
mergeViewOpen.value = false;
|
||||
manageGroups.value = false;
|
||||
selectedGroupId.value = undefined;
|
||||
searchText.value = "";
|
||||
@@ -733,10 +867,15 @@ watch(
|
||||
watch(
|
||||
() => [open.value, props.launchId] as const,
|
||||
([value, launchId]) => {
|
||||
if (value && launchId !== initializedLaunchId) {
|
||||
if (!value) return;
|
||||
if (launchId !== initializedLaunchId) {
|
||||
initializedLaunchId = launchId;
|
||||
openForNewBatch();
|
||||
return;
|
||||
}
|
||||
// Reopened from the background task list: skip the progress list when the
|
||||
// batch already has results worth merging.
|
||||
revealMergedViewWhenSettled();
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
@@ -756,22 +895,38 @@ watch(
|
||||
<DialogHeader class="shrink-0 border-b px-5 py-3">
|
||||
<DialogTitle class="flex items-center gap-2">
|
||||
<Layers class="h-5 w-5 text-primary" />
|
||||
{{ executionStarted ? t("multiDbExecute.progress", { completed: progressCompleted, total: batch?.items.length ?? 0 }) : t("multiDbExecute.title") }}
|
||||
{{ mergeViewOpen ? t("multiDbExecute.mergeResults") : executionStarted ? t("multiDbExecute.progress", { completed: progressCompleted, total: batch?.items.length ?? 0 }) : t("multiDbExecute.title") }}
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<div v-if="executionStarted && batch" class="flex min-h-0 flex-1 flex-col">
|
||||
<div class="flex shrink-0 flex-wrap items-center gap-2 border-b bg-muted/20 px-5 py-3 text-xs text-muted-foreground tabular-nums">
|
||||
<div class="flex shrink-0 flex-wrap items-center gap-2 border-b bg-muted/20 px-5 py-3 text-xs text-muted-foreground tabular-nums" :data-multi-db-batch-id="batch.id">
|
||||
<span>{{ t("multiDbExecute.progress", { completed: progressCompleted, total: batch.items.length }) }}</span>
|
||||
<Badge variant="secondary">{{ executionModeLabel() }}</Badge>
|
||||
<span class="tabular-nums">{{ t("multiDbExecute.elapsed", { duration: formatDataTransferDuration(elapsedMs) }) }}</span>
|
||||
<span class="tabular-nums" data-multi-db-elapsed>{{ t("multiDbExecute.elapsed", { duration: formatDataTransferDuration(elapsedMs) }) }}</span>
|
||||
<Badge variant="outline">{{ t("multiDbExecute.success") }} {{ progressCounts.success }}</Badge>
|
||||
<Badge variant="outline">{{ t("multiDbExecute.failed") }} {{ progressCounts.failed }}</Badge>
|
||||
<Badge variant="outline">{{ t("multiDbExecute.skipped") }} {{ progressCounts.skipped }}</Badge>
|
||||
<Badge variant="outline">{{ t("multiDbExecute.notExecuted") }} {{ progressCounts.notExecuted }}</Badge>
|
||||
<Badge v-if="progressCounts.pendingCommit" variant="outline">{{ t("multiDbExecute.pendingCommit") }} {{ progressCounts.pendingCommit }}</Badge>
|
||||
</div>
|
||||
<div class="min-h-0 flex-1 overflow-y-auto px-5 py-4">
|
||||
<MultiSourceMergeView
|
||||
v-if="mergeViewOpen"
|
||||
ref="mergeViewRef"
|
||||
:items="mergeItems"
|
||||
:sql="batch.sql"
|
||||
:duration-ms="elapsedMs"
|
||||
:executed-at="batch.startedAt"
|
||||
:show-export-actions="false"
|
||||
:rerun-disabled="isExecuting"
|
||||
:transactional="mergeBatchIsTransactional"
|
||||
@rerun-target="rerunMergeTarget"
|
||||
@commit-target="(key: string) => settleMergeTargetTransaction(key, 'commit')"
|
||||
@rollback-target="(key: string) => settleMergeTargetTransaction(key, 'rollback')"
|
||||
@commit-all="commitAllMergeTargets"
|
||||
@rollback-all="rollbackAllMergeTargets"
|
||||
/>
|
||||
<div v-else class="min-h-0 flex-1 overflow-y-auto px-5 py-4">
|
||||
<div class="space-y-2">
|
||||
<div v-for="item in batch.items" :key="item.id" class="flex min-w-0 items-start gap-3 rounded-md border px-3 py-2">
|
||||
<Loader2 v-if="item.status === 'running'" class="mt-0.5 h-4 w-4 shrink-0 animate-spin text-primary" />
|
||||
@@ -781,7 +936,7 @@ watch(
|
||||
<div v-else class="mt-0.5 h-4 w-4 shrink-0 rounded-full border border-muted-foreground/40" />
|
||||
<div class="min-w-0 flex-1">
|
||||
<div class="truncate text-sm" :class="statusClass(item.status)">{{ targetLabel(item.target) }}</div>
|
||||
<div class="text-xs text-muted-foreground">{{ statusLabel(item.status) }}</div>
|
||||
<div class="text-xs text-muted-foreground">{{ isAwaitingTarget(item) ? t("multiDbExecute.awaitingConfirmation") : statusLabel(item.status) }}</div>
|
||||
<div v-if="item.durationMs !== undefined" class="text-xs tabular-nums text-muted-foreground">{{ t("multiDbExecute.elapsed", { duration: formatDataTransferDuration(item.durationMs) }) }}</div>
|
||||
<div v-if="item.errorMessage" class="mt-1 whitespace-pre-wrap break-words text-xs text-destructive">{{ item.errorMessage }}</div>
|
||||
</div>
|
||||
@@ -793,12 +948,30 @@ watch(
|
||||
</div>
|
||||
</div>
|
||||
<DialogFooter class="mx-0 mb-0 shrink-0 border-t px-5 py-3">
|
||||
<Button v-if="isExecuting" variant="destructive" class="gap-1.5" @click="execution.cancel()">
|
||||
<X class="h-4 w-4" />
|
||||
{{ t("multiDbExecute.cancelBatch") }}
|
||||
</Button>
|
||||
<Button v-if="isExecuting && !batch.context.manualTransaction" variant="outline" @click="requestClose">{{ t("exportProgress.minimize") }}</Button>
|
||||
<Button v-else @click="requestClose">{{ t("common.close") }}</Button>
|
||||
<template v-if="mergeViewOpen">
|
||||
<Button variant="outline" data-multi-db-merge-back @click="mergeViewOpen = false">{{ t("multiDbExecute.mergeResultsBack") }}</Button>
|
||||
<Button variant="outline" data-multi-db-merge-export-page @click="mergeViewRef?.exportMergedRows('page')">
|
||||
<Download class="h-4 w-4" />
|
||||
{{ t("multiDbExecute.exportCurrentPage") }}
|
||||
</Button>
|
||||
<Button variant="outline" data-multi-db-merge-export-all @click="mergeViewRef?.exportMergedRows('all')">
|
||||
<Download class="h-4 w-4" />
|
||||
{{ t("multiDbExecute.exportAllRows") }}
|
||||
</Button>
|
||||
<Button @click="requestClose">{{ t("common.close") }}</Button>
|
||||
</template>
|
||||
<template v-else>
|
||||
<Button v-if="isExecuting" variant="destructive" class="gap-1.5" @click="execution.cancel()">
|
||||
<X class="h-4 w-4" />
|
||||
{{ t("multiDbExecute.cancelBatch") }}
|
||||
</Button>
|
||||
<Button v-if="isExecuting && !batch.context.manualTransaction" variant="outline" @click="requestClose">{{ t("exportProgress.minimize") }}</Button>
|
||||
<Button v-if="canShowMergedResults" variant="outline" class="gap-1.5" data-multi-db-merge @click="mergeViewOpen = true">
|
||||
<Layers class="h-4 w-4" />
|
||||
{{ t("multiDbExecute.mergeResults") }}
|
||||
</Button>
|
||||
<Button v-if="!isExecuting" @click="requestClose">{{ t("common.close") }}</Button>
|
||||
</template>
|
||||
</DialogFooter>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -0,0 +1,385 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { Check, Download, RefreshCw, Undo2 } from "@lucide/vue";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import * as api from "@/lib/backend/api";
|
||||
import { isTauriRuntime } from "@/lib/backend/tauriRuntime";
|
||||
import { useToast } from "@/composables/useToast";
|
||||
import { translateBackendError } from "@/i18n/backend-errors";
|
||||
import { formatSelectionAggregate } from "@/lib/dataGrid/gridSelection";
|
||||
import { formatLocalTimestamp } from "@/lib/backend/debugLog";
|
||||
import { buildXlsxSqlWorksheet } from "@/lib/export/xlsxSqlSheet";
|
||||
import { MULTI_SOURCE_MAX_ROWS_PER_SOURCE, MULTI_SOURCE_MERGE_MAX_ROWS, mergeMultiSourceResults } from "@/lib/query/multiSourceResult";
|
||||
import type { QueryResult } from "@/types/database";
|
||||
|
||||
/**
|
||||
* Quick inspection view for one multi-database execution. When the statement
|
||||
* returns result sets, every target's result is unioned by column name into one
|
||||
* table (first column names the row's source, all-numeric columns get a SUM
|
||||
* footer, rows can be exported as Excel). When it returns no result set — an
|
||||
* UPDATE/DELETE/DDL batch — the view lists one row per target with its affected
|
||||
* row count, status and error, and a failed target can be re-run on its own.
|
||||
*/
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
items: Array<{
|
||||
key: string;
|
||||
label: string;
|
||||
result?: QueryResult;
|
||||
status?: "pending" | "running" | "pending_commit" | "rolled_back" | "success" | "failed" | "skipped" | "cancelled" | "not_executed";
|
||||
durationMs?: number;
|
||||
errorMessage?: string;
|
||||
/** Present while this target still owns an unsettled transaction session. */
|
||||
transaction?: { canCommit: boolean; settling?: boolean };
|
||||
}>;
|
||||
/** Hidden when the host dialog renders its own export button group. */
|
||||
showExportActions?: boolean;
|
||||
/** Set while the owning batch is still running, so re-running is blocked. */
|
||||
rerunDisabled?: boolean;
|
||||
/** True when the batch ran inside per-target transactions. */
|
||||
transactional?: boolean;
|
||||
/** Statement the batch executed, shown in the header and written into the export. */
|
||||
sql?: string;
|
||||
/** How long the batch took, shown in the header and written into the export. */
|
||||
durationMs?: number;
|
||||
/** When the batch started (epoch ms), shown in the header and exported. */
|
||||
executedAt?: number;
|
||||
}>(),
|
||||
{ showExportActions: true },
|
||||
);
|
||||
|
||||
const emit = defineEmits<{
|
||||
rerunTarget: [key: string];
|
||||
commitTarget: [key: string];
|
||||
rollbackTarget: [key: string];
|
||||
commitAll: [];
|
||||
rollbackAll: [];
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
const { toast } = useToast();
|
||||
|
||||
/** Rendering cap; the merged statistics always cover every merged row. */
|
||||
const RENDERED_ROW_LIMIT = 1000;
|
||||
|
||||
const merged = computed(() =>
|
||||
mergeMultiSourceResults(
|
||||
props.items.map((item) => ({ key: item.key, label: item.label, result: item.result })),
|
||||
{ sourceColumnLabel: t("multiDbExecute.mergedSourceColumn") },
|
||||
),
|
||||
);
|
||||
/** False for write statements: no target returned columns to union. */
|
||||
const hasTabularResults = computed(() => merged.value.sources.length > 0);
|
||||
const summaryByColumnIndex = computed(() => new Map(merged.value.summaries.map((summary) => [summary.columnIndex, summary])));
|
||||
const renderedRows = computed(() => merged.value.rows.slice(0, RENDERED_ROW_LIMIT));
|
||||
const hiddenRowCount = computed(() => Math.max(0, merged.value.rows.length - renderedRows.value.length));
|
||||
|
||||
/** Sources whose row count reached the per-source fetch cap, so more may exist. */
|
||||
const cappedSourceCount = computed(() => merged.value.sources.filter((source) => source.rowCount >= MULTI_SOURCE_MAX_ROWS_PER_SOURCE).length);
|
||||
const perSourceCap = MULTI_SOURCE_MAX_ROWS_PER_SOURCE;
|
||||
const mergeCap = MULTI_SOURCE_MERGE_MAX_ROWS;
|
||||
|
||||
function statusLabel(status: (typeof props.items)[number]["status"]): string {
|
||||
switch (status) {
|
||||
case "running":
|
||||
return t("multiDbExecute.running");
|
||||
case "success":
|
||||
return t("multiDbExecute.success");
|
||||
case "pending_commit":
|
||||
return t("multiDbExecute.pendingCommit");
|
||||
case "rolled_back":
|
||||
return t("toolbar.rollback");
|
||||
case "failed":
|
||||
return t("multiDbExecute.failed");
|
||||
case "skipped":
|
||||
return t("multiDbExecute.skipped");
|
||||
case "cancelled":
|
||||
return t("multiDbExecute.cancelled");
|
||||
case "not_executed":
|
||||
return t("multiDbExecute.notExecuted");
|
||||
default:
|
||||
return t("multiDbExecute.pending");
|
||||
}
|
||||
}
|
||||
|
||||
function statusClass(status: (typeof props.items)[number]["status"]): string {
|
||||
if (status === "success") return "text-emerald-600 dark:text-emerald-300";
|
||||
if (status === "pending_commit") return "text-amber-600 dark:text-amber-300";
|
||||
if (status === "failed") return "text-destructive";
|
||||
if (status === "running") return "text-primary";
|
||||
if (status === "skipped" || status === "cancelled" || status === "not_executed" || status === "rolled_back") return "text-amber-600 dark:text-amber-300";
|
||||
return "text-muted-foreground";
|
||||
}
|
||||
|
||||
/** A statement that ran, whether or not its transaction is still open. */
|
||||
function hasWrittenRows(item: (typeof props.items)[number]): boolean {
|
||||
return item.status === "success" || item.status === "pending_commit";
|
||||
}
|
||||
|
||||
/** Affected rows are only meaningful for a statement that actually ran. The
|
||||
* column already names them, so the cell carries the bare count. */
|
||||
function affectedRowsText(item: (typeof props.items)[number]): string {
|
||||
if (!hasWrittenRows(item)) return "—";
|
||||
return String(item.result?.affected_rows ?? 0);
|
||||
}
|
||||
|
||||
/** Rows the batch wrote in total, summarized in the header for write statements. */
|
||||
const totalAffectedRows = computed(() => props.items.reduce((sum, item) => sum + (hasWrittenRows(item) ? (item.result?.affected_rows ?? 0) : 0), 0));
|
||||
|
||||
function canRerun(item: (typeof props.items)[number]): boolean {
|
||||
// A target that still owns a session has to be settled before it is re-run.
|
||||
if (item.transaction) return false;
|
||||
return item.status !== undefined && !hasWrittenRows(item) && item.status !== "running" && item.status !== "pending";
|
||||
}
|
||||
|
||||
/** Targets whose changes are still pending in their own transaction. */
|
||||
const openTransactionCount = computed(() => props.items.filter((item) => item.transaction !== undefined).length);
|
||||
/** Committing skips the targets that errored: they have nothing to write. */
|
||||
const committableCount = computed(() => props.items.filter((item) => item.transaction?.canCommit === true).length);
|
||||
|
||||
function isTransactionOpen(item: (typeof props.items)[number]): boolean {
|
||||
return props.transactional === true && item.transaction !== undefined;
|
||||
}
|
||||
|
||||
function txnStateLabel(item: (typeof props.items)[number]): string {
|
||||
if (item.transaction) return t("multiDbExecute.txnOpen");
|
||||
if (item.status === "rolled_back") return t("multiDbExecute.txnRolledBack");
|
||||
if (hasWrittenRows(item)) return t("multiDbExecute.txnCommitted");
|
||||
return "—";
|
||||
}
|
||||
|
||||
function durationText(durationMs: number | undefined): string {
|
||||
if (durationMs === undefined) return "";
|
||||
return durationMs >= 1000 ? `${(durationMs / 1000).toFixed(1)} s` : `${Math.round(durationMs)} ms`;
|
||||
}
|
||||
|
||||
/** Local execution timestamp, sharing the app's timezone-explicit format. */
|
||||
function timestampText(executedAt: number | undefined): string {
|
||||
if (executedAt === undefined) return "";
|
||||
return formatLocalTimestamp(new Date(executedAt)).replace("T", " ").replace(/\.\d+/, "");
|
||||
}
|
||||
|
||||
/** Rows of the write-statement export: one line per target, no result set. */
|
||||
function writeStatementExport(): { columns: string[]; rows: (string | number)[][] } {
|
||||
const columns = [t("multiDbExecute.mergedSourceColumn"), t("multiDbExecute.statusColumn")];
|
||||
if (props.transactional) columns.push(t("multiDbExecute.txnColumn"));
|
||||
columns.push(t("multiDbExecute.affectedRowsColumn"), t("multiDbExecute.durationColumn"), t("multiDbExecute.errorColumn"));
|
||||
const rows = props.items.map((item) => {
|
||||
const row: (string | number)[] = [item.label, statusLabel(item.status)];
|
||||
if (props.transactional) row.push(txnStateLabel(item));
|
||||
row.push(hasWrittenRows(item) ? (item.result?.affected_rows ?? 0) : "", durationText(item.durationMs), item.errorMessage ?? "");
|
||||
return row;
|
||||
});
|
||||
return { columns, rows };
|
||||
}
|
||||
|
||||
function cellText(value: string | number | boolean | null): string {
|
||||
return value === null ? "" : String(value);
|
||||
}
|
||||
|
||||
function summaryCellText(columnIndex: number): string {
|
||||
const summary = summaryByColumnIndex.value.get(columnIndex);
|
||||
return summary ? formatSelectionAggregate(summary.sum) : "";
|
||||
}
|
||||
|
||||
function summaryCellTitle(columnIndex: number): string | undefined {
|
||||
const summary = summaryByColumnIndex.value.get(columnIndex);
|
||||
return summary ? t("multiDbExecute.mergedSummaryCellHint", { count: summary.count }) : undefined;
|
||||
}
|
||||
|
||||
function exportFileName(scope: "page" | "all"): string {
|
||||
const timestamp = new Date().toISOString().slice(0, 19).replace(/[:T]/g, "-");
|
||||
return ["dbx-merged-result", scope === "page" ? "page" : "all", timestamp].join("_") + ".xlsx";
|
||||
}
|
||||
|
||||
/** SQL + timing worksheet: mirrors the grid export's "include SQL sheet" pattern. */
|
||||
function buildSqlWorksheet() {
|
||||
const entries: Array<{ resultName: string; sql: string }> = [];
|
||||
const executedAt = timestampText(props.executedAt);
|
||||
if (executedAt) entries.push({ resultName: t("multiDbExecute.executedAtColumn"), sql: executedAt });
|
||||
const duration = durationText(props.durationMs);
|
||||
if (duration) entries.push({ resultName: t("multiDbExecute.durationColumn"), sql: duration });
|
||||
if (props.sql?.trim()) entries.push({ resultName: "SQL", sql: props.sql });
|
||||
return buildXlsxSqlWorksheet(entries);
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes one Excel workbook for the merged view.
|
||||
*
|
||||
* A statement with a result set exports the merged table (`page` = the rows on
|
||||
* screen, `all` = every merged row). A write statement without a result set
|
||||
* exports the per-target list instead —?status, transaction state, affected
|
||||
* rows, elapsed time and error. Both get a second "SQL" sheet carrying the
|
||||
* executed statement and the batch duration.
|
||||
*
|
||||
* The web build assembles the workbook in the browser and downloads it, the
|
||||
* desktop build asks for a path and writes it through the backend.
|
||||
*/
|
||||
async function exportMergedRows(scope: "page" | "all"): Promise<void> {
|
||||
const tabular = hasTabularResults.value;
|
||||
const rows = scope === "page" ? renderedRows.value : merged.value.rows;
|
||||
if (tabular && rows.length === 0) {
|
||||
toast(t("multiDbExecute.mergedEmpty"), 3000);
|
||||
return;
|
||||
}
|
||||
if (!tabular && props.items.length === 0) {
|
||||
toast(t("multiDbExecute.mergedEmpty"), 3000);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
let outputPath = exportFileName(scope);
|
||||
if (isTauriRuntime()) {
|
||||
const { save } = await import("@tauri-apps/plugin-dialog");
|
||||
const path = await save({ defaultPath: outputPath, filters: [{ name: "Excel", extensions: ["xlsx"] }] });
|
||||
if (!path) return;
|
||||
outputPath = String(path);
|
||||
}
|
||||
const writeExport = tabular ? undefined : writeStatementExport();
|
||||
const dataSheet = {
|
||||
sheetName: t("multiDbExecute.mergedSheetName"),
|
||||
columns: tabular ? [...merged.value.columns] : (writeExport?.columns ?? []),
|
||||
columnTypes: (tabular ? merged.value.columns : (writeExport?.columns ?? [])).map(() => ""),
|
||||
rows: tabular ? rows : (writeExport?.rows ?? []),
|
||||
numericColumnRightAlign: true,
|
||||
autoFilter: true,
|
||||
};
|
||||
const sqlWorksheet = buildSqlWorksheet();
|
||||
if (sqlWorksheet) {
|
||||
await api.exportQueryResultsXlsx(outputPath, [dataSheet, sqlWorksheet], true);
|
||||
} else {
|
||||
await api.exportQueryResultXlsx(outputPath, dataSheet.sheetName, dataSheet.columns, dataSheet.columnTypes, undefined, dataSheet.rows, true, true);
|
||||
}
|
||||
const exportedRows = tabular ? rows.length : props.items.length;
|
||||
toast(cappedSourceCount.value > 0 && tabular ? t("multiDbExecute.exportedRowsCapped", { rows: exportedRows, count: cappedSourceCount.value, limit: perSourceCap }) : t("multiDbExecute.exportedRows", { rows: exportedRows }), 4000);
|
||||
} catch (error) {
|
||||
toast(t("grid.exportFailed", { message: translateBackendError(t, error) }), 5000);
|
||||
}
|
||||
}
|
||||
|
||||
defineExpose({ exportMergedRows });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex min-h-0 flex-1 flex-col" data-multi-source-merge-view>
|
||||
<div class="flex shrink-0 flex-wrap items-center gap-2 border-b bg-muted/20 px-5 py-2 text-xs text-muted-foreground">
|
||||
<!-- A write batch has no rows to merge: report what it touched instead of
|
||||
the merged-source statistics, which would all read zero. -->
|
||||
<span v-if="hasTabularResults">{{ t("multiDbExecute.mergedSources", { count: merged.sources.length, rows: merged.rowCount }) }}</span>
|
||||
<span v-if="hasTabularResults">{{ t("multiDbExecute.mergedSourceRowCap", { count: perSourceCap }) }}</span>
|
||||
<span v-else data-merge-write-summary>{{ t("multiDbExecute.mergedWriteSummary", { targets: items.length, rows: totalAffectedRows }) }}</span>
|
||||
<span v-if="hasTabularResults && cappedSourceCount > 0" class="font-medium text-amber-600 dark:text-amber-300" data-merge-source-cap-reached>
|
||||
{{ t("multiDbExecute.mergedSourceCapReached", { count: cappedSourceCount, limit: perSourceCap }) }}
|
||||
</span>
|
||||
<span v-if="hasTabularResults && merged.truncated" class="font-medium text-amber-600 dark:text-amber-300" data-merge-truncated>
|
||||
{{ t("multiDbExecute.mergedTruncated", { count: mergeCap }) }}
|
||||
</span>
|
||||
<span v-if="hasTabularResults && hiddenRowCount > 0">{{ t("multiDbExecute.mergedRowLimit", { count: renderedRows.length, rows: merged.rowCount }) }}</span>
|
||||
<span v-if="executedAt !== undefined" class="tabular-nums" data-merge-executed-at>{{ t("multiDbExecute.executedAtChip", { time: timestampText(executedAt) }) }}</span>
|
||||
<span v-if="durationMs !== undefined" class="tabular-nums" data-merge-duration>{{ t("multiDbExecute.elapsedColumn", { duration: durationText(durationMs) }) }}</span>
|
||||
<span v-if="sql" class="min-w-0 max-w-[420px] truncate font-mono" :title="sql" data-merge-sql>{{ sql }}</span>
|
||||
<span v-if="transactional && openTransactionCount > 0" class="font-medium text-amber-600 dark:text-amber-300" data-merge-txn-open>
|
||||
{{ t("multiDbExecute.txnOpenHint", { count: openTransactionCount }) }}
|
||||
</span>
|
||||
<span v-if="showExportActions || transactional" class="ml-auto flex shrink-0 items-center gap-1">
|
||||
<template v-if="transactional">
|
||||
<Button variant="outline" size="sm" class="h-6 gap-1 px-2 text-xs" data-merge-commit-all :disabled="committableCount === 0 || rerunDisabled" @click="emit('commitAll')">
|
||||
<Check class="h-3.5 w-3.5" />
|
||||
{{ t("multiDbExecute.commitAllTargets", { count: committableCount }) }}
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" class="h-6 gap-1 px-2 text-xs" data-merge-rollback-all :disabled="openTransactionCount === 0 || rerunDisabled" @click="emit('rollbackAll')">
|
||||
<Undo2 class="h-3.5 w-3.5" />
|
||||
{{ t("multiDbExecute.rollbackAllTargets", { count: openTransactionCount }) }}
|
||||
</Button>
|
||||
</template>
|
||||
<template v-if="showExportActions">
|
||||
<Button variant="outline" size="sm" class="h-6 gap-1 px-2 text-xs" data-merge-export-page @click="exportMergedRows('page')">
|
||||
<Download class="h-3.5 w-3.5" />
|
||||
{{ t("multiDbExecute.exportCurrentPage") }}
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" class="h-6 gap-1 px-2 text-xs" data-merge-export-all @click="exportMergedRows('all')">
|
||||
<Download class="h-3.5 w-3.5" />
|
||||
{{ t("multiDbExecute.exportAllRows") }}
|
||||
</Button>
|
||||
</template>
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="min-h-0 flex-1 overflow-auto">
|
||||
<!-- Write statements (UPDATE / DELETE / DDL) return no result set: report
|
||||
one row per target instead of an empty merged table. -->
|
||||
<table v-if="!hasTabularResults" class="w-full border-collapse text-xs" data-merge-target-results>
|
||||
<thead class="sticky top-0 z-10 bg-muted text-left">
|
||||
<tr>
|
||||
<th class="border-r border-b px-2 py-1 font-medium whitespace-nowrap">{{ t("multiDbExecute.mergedSourceColumn") }}</th>
|
||||
<th class="border-r border-b px-2 py-1 font-medium whitespace-nowrap">{{ t("multiDbExecute.statusColumn") }}</th>
|
||||
<th v-if="transactional" class="border-r border-b px-2 py-1 font-medium whitespace-nowrap">{{ t("multiDbExecute.txnColumn") }}</th>
|
||||
<th class="border-r border-b px-2 py-1 font-medium whitespace-nowrap">{{ t("multiDbExecute.affectedRowsColumn") }}</th>
|
||||
<th class="border-r border-b px-2 py-1 font-medium whitespace-nowrap">{{ t("multiDbExecute.durationColumn") }}</th>
|
||||
<th class="border-r border-b px-2 py-1 font-medium whitespace-nowrap">{{ t("multiDbExecute.errorColumn") }}</th>
|
||||
<th class="border-b px-2 py-1" />
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="item in items" :key="item.key" class="border-b align-top hover:bg-muted/40">
|
||||
<td class="max-w-[280px] truncate border-r px-2 py-1 whitespace-nowrap" :title="item.label">{{ item.label }}</td>
|
||||
<td class="border-r px-2 py-1 whitespace-nowrap" :class="statusClass(item.status)">{{ statusLabel(item.status) }}</td>
|
||||
<td v-if="transactional" class="border-r px-2 py-1 whitespace-nowrap" :class="{ 'text-amber-600 dark:text-amber-300': item.transaction !== undefined }" data-merge-txn-state>
|
||||
{{ txnStateLabel(item) }}
|
||||
</td>
|
||||
<td class="border-r px-2 py-1 text-right tabular-nums whitespace-nowrap">{{ affectedRowsText(item) }}</td>
|
||||
<td class="border-r px-2 py-1 text-right tabular-nums whitespace-nowrap">{{ durationText(item.durationMs) }}</td>
|
||||
<td class="max-w-[360px] border-r px-2 py-1 text-destructive">
|
||||
<span class="line-clamp-3 break-words whitespace-pre-wrap">{{ item.errorMessage ?? "" }}</span>
|
||||
</td>
|
||||
<td class="px-2 py-1 text-right whitespace-nowrap">
|
||||
<template v-if="isTransactionOpen(item) && item.transaction">
|
||||
<Button variant="outline" size="sm" class="h-6 gap-1 px-2 text-xs" data-merge-commit :disabled="rerunDisabled || item.transaction.settling === true || !item.transaction.canCommit" @click="emit('commitTarget', item.key)">
|
||||
<Check class="h-3.5 w-3.5" />
|
||||
{{ t("toolbar.commit") }}
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" class="ml-1 h-6 gap-1 px-2 text-xs" data-merge-rollback :disabled="rerunDisabled || item.transaction.settling === true" @click="emit('rollbackTarget', item.key)">
|
||||
<Undo2 class="h-3.5 w-3.5" />
|
||||
{{ t("toolbar.rollback") }}
|
||||
</Button>
|
||||
</template>
|
||||
<Button v-else-if="canRerun(item)" variant="outline" size="sm" class="h-6 gap-1 px-2 text-xs" data-merge-rerun :disabled="rerunDisabled" @click="emit('rerunTarget', item.key)">
|
||||
<RefreshCw class="h-3.5 w-3.5" />
|
||||
{{ t("multiDbExecute.rerunTarget") }}
|
||||
</Button>
|
||||
</td>
|
||||
</tr>
|
||||
<tr v-if="items.length === 0">
|
||||
<td :colspan="transactional ? 7 : 6" class="px-2 py-6 text-center text-muted-foreground">{{ t("multiDbExecute.mergedEmpty") }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<table v-else class="w-full border-collapse text-xs">
|
||||
<thead class="sticky top-0 z-10 bg-muted text-left">
|
||||
<tr>
|
||||
<th v-for="(column, columnIndex) in merged.columns" :key="`head-${columnIndex}`" class="border-r border-b px-2 py-1 font-medium whitespace-nowrap">{{ column }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="(row, rowIndex) in renderedRows" :key="`row-${rowIndex}`" class="border-b hover:bg-muted/40">
|
||||
<td v-for="(cell, columnIndex) in row" :key="`cell-${rowIndex}-${columnIndex}`" class="max-w-[320px] truncate border-r px-2 py-1 whitespace-nowrap" :class="{ 'text-muted-foreground': cell === null }" :title="cellText(cell)">
|
||||
{{ cellText(cell) }}
|
||||
</td>
|
||||
</tr>
|
||||
<tr v-if="renderedRows.length === 0">
|
||||
<td :colspan="merged.columns.length" class="px-2 py-6 text-center text-muted-foreground">{{ t("multiDbExecute.mergedEmpty") }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
<tfoot v-if="merged.summaries.length > 0" class="sticky bottom-0 z-10 bg-muted">
|
||||
<tr>
|
||||
<td class="border-r border-t px-2 py-1 text-center font-medium text-muted-foreground">{{ t("multiDbExecute.mergedSummaryLabel") }}</td>
|
||||
<td v-for="columnIndex in merged.columns.length - 1" :key="`sum-${columnIndex}`" class="border-r border-t px-2 py-1 text-right tabular-nums" :title="summaryCellTitle(columnIndex)">
|
||||
{{ summaryCellText(columnIndex) }}
|
||||
</td>
|
||||
</tr>
|
||||
</tfoot>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
+386
@@ -0,0 +1,386 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { computed, createApp, h, nextTick, ref, type App, type Ref } from "vue";
|
||||
import { createPinia } from "pinia";
|
||||
import MultiDbExecuteDialog from "../MultiDbExecuteDialog.vue";
|
||||
import { useSqlExecutionDangerStore } from "@/stores/sqlExecutionDangerStore";
|
||||
import type { MultiDbExecutionAdapter } from "@/composables/useMultiDbExecution";
|
||||
import type { QueryResult } from "@/types/database";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
toast: vi.fn(),
|
||||
exportQueryResultsXlsx: vi.fn().mockResolvedValue(undefined),
|
||||
exportQueryResultXlsx: vi.fn().mockResolvedValue(undefined),
|
||||
registerTaskCancelHandler: vi.fn(),
|
||||
unregisterTaskCancelHandler: vi.fn(),
|
||||
}));
|
||||
|
||||
// Parameters are rendered so a call that forgot them is visible in the DOM.
|
||||
vi.mock("vue-i18n", () => ({
|
||||
useI18n: () => ({ t: (key: string, params?: Record<string, unknown>) => (params ? `${key}(${Object.values(params).join("/")})` : key) }),
|
||||
}));
|
||||
// Web runtime: exports skip the save dialog and manual transactions are unavailable.
|
||||
vi.mock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
|
||||
vi.mock("@/lib/backend/api", () => ({
|
||||
exportQueryResultsXlsx: mocks.exportQueryResultsXlsx,
|
||||
exportQueryResultXlsx: mocks.exportQueryResultXlsx,
|
||||
}));
|
||||
vi.mock("@/composables/useToast", () => ({ useToast: () => ({ toast: mocks.toast }) }));
|
||||
vi.mock("@/stores/sqlExecutionTargetGroupStore", () => ({ useSqlExecutionTargetGroupStore: () => ({ getGroupsByDatabaseType: () => [], getGroup: () => undefined }) }));
|
||||
vi.mock("@/composables/useExportTracker", () => ({
|
||||
formatDataTransferDuration: String,
|
||||
useExportTracker: () => ({ addMultiDbExecutionTask: vi.fn(), updateMultiDbExecutionTask: vi.fn(), registerTaskCancelHandler: mocks.registerTaskCancelHandler, unregisterTaskCancelHandler: mocks.unregisterTaskCancelHandler }),
|
||||
}));
|
||||
vi.mock("@/composables/useMultiDbTargetSelection", () => ({
|
||||
useMultiDbTargetSelection: () => ({
|
||||
compatibleConnections: computed(() => []),
|
||||
connection: () => ({ id: "test", name: "Test", db_type: "oceanbase-oracle" }),
|
||||
loadConnection: vi.fn().mockResolvedValue(undefined),
|
||||
validateTarget: async () => ({ state: "valid" }),
|
||||
validateTargets: async (targets: unknown[]) => targets.map((target) => ({ target, state: "valid" })),
|
||||
}),
|
||||
}));
|
||||
|
||||
const SQL = "SELECT id, amount FROM t";
|
||||
const TWO_TARGETS = [
|
||||
{ connectionId: "test", database: "db-a" },
|
||||
{ connectionId: "test", database: "db-b" },
|
||||
];
|
||||
|
||||
function table(rows: (string | number)[][]): QueryResult {
|
||||
return { columns: ["id", "amount"], rows, affected_rows: rows.length, execution_time_ms: 1 };
|
||||
}
|
||||
|
||||
function write(affectedRows: number): QueryResult {
|
||||
return { columns: [], rows: [], affected_rows: affectedRows, execution_time_ms: 1 };
|
||||
}
|
||||
|
||||
function resultFor(database: string): QueryResult {
|
||||
return database === "db-a" ? table([[1, 10]]) : table([[2, 20]]);
|
||||
}
|
||||
|
||||
let app: App | undefined;
|
||||
|
||||
afterEach(() => {
|
||||
app?.unmount();
|
||||
app = undefined;
|
||||
document.body.innerHTML = "";
|
||||
mocks.toast.mockClear();
|
||||
mocks.exportQueryResultsXlsx.mockClear();
|
||||
mocks.registerTaskCancelHandler.mockClear();
|
||||
mocks.unregisterTaskCancelHandler.mockClear();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
async function flushPromises() {
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
await nextTick();
|
||||
}
|
||||
|
||||
function button(label: string): HTMLButtonElement {
|
||||
const found = [...document.querySelectorAll<HTMLButtonElement>("button")].find((candidate) => candidate.textContent?.trim() === label);
|
||||
if (!found) throw new Error(`Missing button ${label}`);
|
||||
return found;
|
||||
}
|
||||
|
||||
/** Mounts with a reactive `open` so minimizing and reopening can be observed. */
|
||||
interface DialogOptions {
|
||||
open: Ref<boolean>;
|
||||
targets?: Array<{ connectionId: string; database: string }>;
|
||||
launchId?: Ref<number>;
|
||||
cancelTarget?: MultiDbExecutionAdapter["cancelTarget"];
|
||||
cancelPending?: MultiDbExecutionAdapter["cancelPending"];
|
||||
}
|
||||
|
||||
function mountDialog(executeTarget: MultiDbExecutionAdapter["executeTarget"], options: DialogOptions) {
|
||||
const root = document.createElement("div");
|
||||
document.body.append(root);
|
||||
app = createApp({
|
||||
render: () =>
|
||||
h(MultiDbExecuteDialog, {
|
||||
open: options.open.value,
|
||||
"onUpdate:open": (value: boolean) => (options.open.value = value),
|
||||
sql: SQL,
|
||||
sourceTabId: "source",
|
||||
databaseType: "oceanbase-oracle",
|
||||
initialTargets: options.targets ?? TWO_TARGETS,
|
||||
launchId: options.launchId?.value ?? 1,
|
||||
executeTarget,
|
||||
cancelTarget: options.cancelTarget,
|
||||
cancelPending: options.cancelPending,
|
||||
}),
|
||||
});
|
||||
app.use(createPinia());
|
||||
app.mount(root);
|
||||
}
|
||||
|
||||
async function executeBatch(executeTarget: MultiDbExecutionAdapter["executeTarget"], options: DialogOptions) {
|
||||
mountDialog(executeTarget, options);
|
||||
await flushPromises();
|
||||
button("multiDbExecute.execute").click();
|
||||
await flushPromises();
|
||||
}
|
||||
|
||||
describe("multi-database merged view reveal paths", () => {
|
||||
it("unions every source and labels the rows, the statement and the batch timings", async () => {
|
||||
const open = ref(true);
|
||||
const executeTarget = vi.fn<MultiDbExecutionAdapter["executeTarget"]>(async (input) => ({ status: "success" as const, durationMs: 3, result: resultFor(input.target.database) }));
|
||||
await executeBatch(executeTarget, { open });
|
||||
|
||||
button("multiDbExecute.mergeResults").click();
|
||||
await nextTick();
|
||||
|
||||
const view = document.querySelector("[data-multi-source-merge-view]");
|
||||
expect(view).not.toBeNull();
|
||||
const rows = [...(view?.querySelectorAll("tbody tr") ?? [])].map((row) => [...row.querySelectorAll("td")].map((cell) => cell.textContent?.trim()));
|
||||
expect(rows).toEqual([
|
||||
["Test / db-a", "1", "10"],
|
||||
["Test / db-b", "2", "20"],
|
||||
]);
|
||||
|
||||
// The statement, the elapsed time and the start time come from the batch.
|
||||
expect(document.querySelector("[data-merge-sql]")?.textContent?.trim()).toBe(SQL);
|
||||
expect(document.querySelector("[data-merge-duration]")?.textContent?.trim()).not.toBe("");
|
||||
expect(document.querySelector("[data-merge-executed-at]")?.textContent?.trim()).not.toBe("");
|
||||
});
|
||||
|
||||
it("names the merged view in the title instead of the bar's parametrized progress", async () => {
|
||||
const open = ref(true);
|
||||
const executeTarget = vi.fn<MultiDbExecutionAdapter["executeTarget"]>(async (input) => ({ status: "success" as const, durationMs: 3, result: resultFor(input.target.database) }));
|
||||
await executeBatch(executeTarget, { open });
|
||||
|
||||
const title = () => document.querySelector('[data-slot="dialog-title"]')?.textContent?.trim() ?? "";
|
||||
expect(title()).toContain("multiDbExecute.progress(");
|
||||
|
||||
button("multiDbExecute.mergeResults").click();
|
||||
await nextTick();
|
||||
|
||||
expect(title()).toBe("multiDbExecute.mergeResults");
|
||||
expect(document.body.textContent).toContain("multiDbExecute.progress(2/2)");
|
||||
});
|
||||
|
||||
it("exports the merged rows and the statement through the dialog footer", async () => {
|
||||
const open = ref(true);
|
||||
const executeTarget = vi.fn<MultiDbExecutionAdapter["executeTarget"]>(async (input) => ({ status: "success" as const, durationMs: 3, result: resultFor(input.target.database) }));
|
||||
await executeBatch(executeTarget, { open });
|
||||
|
||||
button("multiDbExecute.mergeResults").click();
|
||||
await nextTick();
|
||||
(document.querySelector("[data-multi-db-merge-export-all]") as HTMLButtonElement).click();
|
||||
await vi.waitFor(() => expect(mocks.exportQueryResultsXlsx).toHaveBeenCalledTimes(1));
|
||||
|
||||
const sheets = (mocks.exportQueryResultsXlsx.mock.calls[0] as [string, Array<{ sheetName: string; rows: unknown[][] }>])[1];
|
||||
expect(sheets[0]?.rows).toHaveLength(2);
|
||||
expect(sheets[1]?.rows.flat().join("\n")).toContain(SQL);
|
||||
});
|
||||
|
||||
it("re-runs only the failed target from the per-target list", async () => {
|
||||
const open = ref(true);
|
||||
const executeTarget = vi.fn<MultiDbExecutionAdapter["executeTarget"]>(async (input) => (input.target.database === "db-a" ? { status: "success" as const, durationMs: 4, result: write(3) } : { status: "failed" as const, durationMs: 2, errorMessage: "boom" }));
|
||||
await executeBatch(executeTarget, { open });
|
||||
|
||||
button("multiDbExecute.mergeResults").click();
|
||||
await nextTick();
|
||||
expect(document.body.textContent).toContain("boom");
|
||||
|
||||
executeTarget.mockImplementation(async (input) => (input.target.database === "db-a" ? { status: "success" as const, durationMs: 4, result: write(3) } : { status: "success" as const, durationMs: 6, result: write(1) }));
|
||||
(document.querySelector("[data-merge-rerun]") as HTMLButtonElement).click();
|
||||
await flushPromises();
|
||||
|
||||
// The adapter ran for the retried target only, and the row shows the retry's own outcome.
|
||||
expect(executeTarget).toHaveBeenCalledTimes(3);
|
||||
expect(executeTarget.mock.calls[2]?.[0].target.database).toBe("db-b");
|
||||
expect(document.querySelector("[data-merge-rerun]")).toBeNull();
|
||||
expect(document.body.textContent).not.toContain("boom");
|
||||
});
|
||||
|
||||
it("keeps deferred retries cancellable across reopen and rolls back their late transactions on unmount", async () => {
|
||||
const open = ref(true);
|
||||
const launchId = ref(1);
|
||||
const cancelTarget = vi.fn().mockResolvedValue(undefined);
|
||||
const cancelPending = vi.fn();
|
||||
const finish = vi.fn().mockResolvedValue(undefined);
|
||||
let release!: () => void;
|
||||
const gate = new Promise<void>((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
const executeTarget = vi.fn<MultiDbExecutionAdapter["executeTarget"]>().mockResolvedValue({ status: "failed", errorMessage: "boom" });
|
||||
await executeBatch(executeTarget, { open, launchId, cancelTarget, cancelPending });
|
||||
const batchId = document.querySelector("[data-multi-db-batch-id]")?.getAttribute("data-multi-db-batch-id");
|
||||
button("multiDbExecute.mergeResults").click();
|
||||
await nextTick();
|
||||
mocks.registerTaskCancelHandler.mockClear();
|
||||
executeTarget.mockImplementationOnce(async () => {
|
||||
await gate;
|
||||
return { status: "pending_commit", transaction: { canCommit: true, finish } };
|
||||
});
|
||||
(document.querySelector("[data-merge-rerun]") as HTMLButtonElement).click();
|
||||
await flushPromises();
|
||||
|
||||
expect(document.querySelector<HTMLButtonElement>("[data-merge-rerun]")?.disabled).toBe(true);
|
||||
expect(mocks.registerTaskCancelHandler).toHaveBeenLastCalledWith(batchId, expect.any(Function));
|
||||
const cancel = mocks.registerTaskCancelHandler.mock.calls.at(-1)![1] as () => Promise<void>;
|
||||
open.value = false;
|
||||
await flushPromises();
|
||||
launchId.value += 1;
|
||||
open.value = true;
|
||||
await flushPromises();
|
||||
expect(document.querySelector("[data-multi-db-batch-id]")?.getAttribute("data-multi-db-batch-id")).toBe(batchId);
|
||||
expect(executeTarget).toHaveBeenCalledTimes(3);
|
||||
await cancel();
|
||||
expect(cancelTarget).toHaveBeenCalledExactlyOnceWith("source", batchId);
|
||||
expect(cancelPending).toHaveBeenCalledExactlyOnceWith(batchId);
|
||||
expect(executeTarget.mock.calls[2]![0].isCancellationRequested()).toBe(true);
|
||||
|
||||
app?.unmount();
|
||||
app = undefined;
|
||||
expect(finish).not.toHaveBeenCalled();
|
||||
release();
|
||||
await vi.waitFor(() => expect(finish).toHaveBeenCalledExactlyOnceWith("rollback"));
|
||||
});
|
||||
|
||||
it.each([0, 5000])("resets confirmation timing for a new batch with %i ms wait but preserves same-batch reopen", async (secondWaitMs) => {
|
||||
let now = 1000;
|
||||
vi.spyOn(Date, "now").mockImplementation(() => now);
|
||||
const open = ref(true);
|
||||
const launchId = ref(1);
|
||||
let release!: () => void;
|
||||
let gate = new Promise<void>((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
const executeTarget = vi.fn<MultiDbExecutionAdapter["executeTarget"]>(async (input) => {
|
||||
if (input.target.database === "db-a") await gate;
|
||||
return { status: "success", result: resultFor(input.target.database) };
|
||||
});
|
||||
await executeBatch(executeTarget, { open, launchId });
|
||||
const firstBatchId = document.querySelector("[data-multi-db-batch-id]")?.getAttribute("data-multi-db-batch-id");
|
||||
const dangerStore = useSqlExecutionDangerStore();
|
||||
dangerStore.pending = { sql: SQL, kind: "sql", scopeId: firstBatchId ?? undefined, targetLabel: "Test / db-a" };
|
||||
await nextTick();
|
||||
now = 11_000;
|
||||
dangerStore.pending = undefined;
|
||||
await nextTick();
|
||||
now = 11_100;
|
||||
release();
|
||||
await flushPromises();
|
||||
expect(document.querySelector("[data-multi-db-elapsed]")?.textContent).toBe("multiDbExecute.elapsed(100)");
|
||||
|
||||
open.value = false;
|
||||
await flushPromises();
|
||||
open.value = true;
|
||||
await flushPromises();
|
||||
expect(document.querySelector("[data-multi-db-elapsed]")?.textContent).toBe("multiDbExecute.elapsed(100)");
|
||||
expect(executeTarget).toHaveBeenCalledTimes(2);
|
||||
|
||||
now = 20_000;
|
||||
gate = new Promise<void>((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
launchId.value += 1;
|
||||
await flushPromises();
|
||||
button("multiDbExecute.execute").click();
|
||||
await flushPromises();
|
||||
const secondBatchId = document.querySelector("[data-multi-db-batch-id]")?.getAttribute("data-multi-db-batch-id");
|
||||
expect(secondBatchId).not.toBe(firstBatchId);
|
||||
if (secondWaitMs > 0) {
|
||||
dangerStore.pending = { sql: SQL, kind: "sql", scopeId: secondBatchId ?? undefined, targetLabel: "Test / db-a" };
|
||||
await nextTick();
|
||||
now += secondWaitMs;
|
||||
dangerStore.pending = undefined;
|
||||
await nextTick();
|
||||
}
|
||||
now += 250;
|
||||
release();
|
||||
await flushPromises();
|
||||
expect(document.querySelector("[data-multi-db-elapsed]")?.textContent).toBe("multiDbExecute.elapsed(250)");
|
||||
button("multiDbExecute.mergeResults").click();
|
||||
await nextTick();
|
||||
button("multiDbExecute.exportAllRows").click();
|
||||
await flushPromises();
|
||||
const sheets = mocks.exportQueryResultsXlsx.mock.calls[0]?.[1] as Array<{ sheetName: string; rows: string[][] }>;
|
||||
expect(
|
||||
sheets
|
||||
.find((sheet) => sheet.sheetName === "SQL")
|
||||
?.rows.flat()
|
||||
.join("\n"),
|
||||
).toContain("250 ms");
|
||||
});
|
||||
|
||||
it("keeps merging out of a single-target batch", async () => {
|
||||
const open = ref(true);
|
||||
const executeTarget = vi.fn<MultiDbExecutionAdapter["executeTarget"]>(async (input) => ({ status: "success" as const, durationMs: 3, result: resultFor(input.target.database) }));
|
||||
await executeBatch(executeTarget, { open, targets: [{ connectionId: "test", database: "db-a" }] });
|
||||
|
||||
expect(document.querySelector("[data-multi-db-merge]")).toBeNull();
|
||||
});
|
||||
|
||||
it("parks the clock and labels the target while its confirmation is on screen", async () => {
|
||||
const open = ref(true);
|
||||
const releases: Array<() => void> = [];
|
||||
const executeTarget = vi.fn<MultiDbExecutionAdapter["executeTarget"]>(async (input) => {
|
||||
await new Promise<void>((resolve) => releases.push(resolve));
|
||||
return { status: "success" as const, durationMs: 3, result: resultFor(input.target.database) };
|
||||
});
|
||||
await executeBatch(executeTarget, { open });
|
||||
|
||||
const batchId = document.querySelector("[data-multi-db-batch-id]")?.getAttribute("data-multi-db-batch-id");
|
||||
expect(batchId).toBeTruthy();
|
||||
// The prompt the batch is waiting for, as the danger store publishes it.
|
||||
useSqlExecutionDangerStore().pending = { sql: SQL, kind: "sql", scopeId: batchId ?? undefined, targetLabel: "Test / db-a" };
|
||||
await nextTick();
|
||||
|
||||
// The parked target is waiting for the operator, not running.
|
||||
expect(document.body.textContent).toContain("multiDbExecute.awaitingConfirmation");
|
||||
const elapsedBefore = document.querySelector("[data-multi-db-elapsed]")?.textContent;
|
||||
expect(elapsedBefore).toBeTruthy();
|
||||
await new Promise((resolve) => setTimeout(resolve, 1_200));
|
||||
await nextTick();
|
||||
expect(document.querySelector("[data-multi-db-elapsed]")?.textContent).toBe(elapsedBefore);
|
||||
|
||||
releases.splice(0).forEach((release) => release());
|
||||
});
|
||||
|
||||
it("announces a batch that finished while minimized with an action into the merged view", async () => {
|
||||
const open = ref(true);
|
||||
const releases: Array<() => void> = [];
|
||||
const executeTarget = vi.fn<MultiDbExecutionAdapter["executeTarget"]>(async (input) => {
|
||||
await new Promise<void>((resolve) => releases.push(resolve));
|
||||
return { status: "success" as const, durationMs: 3, result: resultFor(input.target.database) };
|
||||
});
|
||||
await executeBatch(executeTarget, { open });
|
||||
|
||||
// Minimize while the targets are still running, then let them finish.
|
||||
open.value = false;
|
||||
await nextTick();
|
||||
for (let round = 0; round < 4; round += 1) {
|
||||
releases.splice(0).forEach((release) => release());
|
||||
await flushPromises();
|
||||
}
|
||||
|
||||
const announcement = mocks.toast.mock.calls.at(-1) as [string, number, { label: string; onClick: () => void }];
|
||||
expect(announcement[0]).toBe("multiDbExecute.backgroundBatchDone(2)");
|
||||
expect(announcement[1]).toBe(8000);
|
||||
expect(announcement[2].label).toBe("multiDbExecute.mergeResults");
|
||||
|
||||
announcement[2].onClick();
|
||||
await nextTick();
|
||||
expect(open.value).toBe(true);
|
||||
expect(document.querySelector("[data-multi-source-merge-view]")).not.toBeNull();
|
||||
});
|
||||
|
||||
it("reopens a settled batch straight in the merged view without re-running it", async () => {
|
||||
const open = ref(true);
|
||||
const executeTarget = vi.fn<MultiDbExecutionAdapter["executeTarget"]>(async (input) => ({ status: "success" as const, durationMs: 3, result: resultFor(input.target.database) }));
|
||||
await executeBatch(executeTarget, { open });
|
||||
|
||||
button("common.close").click();
|
||||
await flushPromises();
|
||||
expect(open.value).toBe(false);
|
||||
|
||||
open.value = true;
|
||||
await flushPromises();
|
||||
|
||||
expect(document.querySelector("[data-multi-source-merge-view]")).not.toBeNull();
|
||||
expect(executeTarget).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,7 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { computed, createApp, nextTick, type App } from "vue";
|
||||
import { createPinia } from "pinia";
|
||||
import MultiDbExecuteDialog from "../MultiDbExecuteDialog.vue";
|
||||
import type { MultiDbExecutionAdapter } from "@/composables/useMultiDbExecution";
|
||||
|
||||
@@ -37,6 +38,7 @@ async function openDialog(executeTarget: MultiDbExecutionAdapter["executeTarget"
|
||||
const root = document.createElement("div");
|
||||
document.body.append(root);
|
||||
app = createApp(MultiDbExecuteDialog, { open: true, "onUpdate:open": onOpenChange, sql: "INSERT INTO t VALUES (1)", sourceTabId: "source", databaseType: "oceanbase-oracle", initialTargets: [{ connectionId: "test", database: "test" }], launchId: 1, initialManualTransaction: true, executeTarget });
|
||||
app.use(createPinia());
|
||||
app.mount(root);
|
||||
await flushPromises();
|
||||
const checkbox = document.querySelector<HTMLInputElement>('input[type="checkbox"]');
|
||||
|
||||
+209
@@ -0,0 +1,209 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { createApp, h, nextTick, type App } from "vue";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import i18n from "@/i18n";
|
||||
import MultiSourceMergeView from "@/components/editor/MultiSourceMergeView.vue";
|
||||
import type { QueryResult } from "@/types/database";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
exportQueryResultsXlsx: vi.fn().mockResolvedValue(undefined),
|
||||
exportQueryResultXlsx: vi.fn().mockResolvedValue(undefined),
|
||||
toast: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/backend/api", () => ({
|
||||
exportQueryResultsXlsx: mocks.exportQueryResultsXlsx,
|
||||
exportQueryResultXlsx: mocks.exportQueryResultXlsx,
|
||||
}));
|
||||
// The web build assembles the workbook in the browser; the desktop build would
|
||||
// first ask for a path, which is covered by the shared export code instead.
|
||||
vi.mock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
|
||||
vi.mock("@/composables/useToast", () => ({ useToast: () => ({ toast: mocks.toast }) }));
|
||||
|
||||
interface Sheet {
|
||||
sheetName: string;
|
||||
columns: string[];
|
||||
rows: Array<Array<string | number>>;
|
||||
}
|
||||
|
||||
function result(columns: string[], rows: (string | number | null)[][], affectedRows = rows.length): QueryResult {
|
||||
return { columns, rows, affected_rows: affectedRows, execution_time_ms: 1 };
|
||||
}
|
||||
|
||||
function mountView(props: Record<string, unknown>) {
|
||||
const host = document.createElement("div");
|
||||
document.body.appendChild(host);
|
||||
const app = createApp({ render: () => h(MultiSourceMergeView, props) });
|
||||
app.use(i18n);
|
||||
app.mount(host);
|
||||
return { host, app };
|
||||
}
|
||||
|
||||
let mounted: { host: HTMLElement; app: App } | undefined;
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.exportQueryResultsXlsx.mockClear();
|
||||
mocks.exportQueryResultXlsx.mockClear();
|
||||
mocks.toast.mockClear();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
mounted?.app.unmount();
|
||||
mounted?.host.remove();
|
||||
mounted = undefined;
|
||||
});
|
||||
|
||||
function exportButton(selector: string): HTMLButtonElement {
|
||||
const button = mounted?.host.querySelector<HTMLButtonElement>(selector);
|
||||
if (!button) throw new Error(`Missing export button ${selector}`);
|
||||
return button;
|
||||
}
|
||||
|
||||
describe("merged view export", () => {
|
||||
it.each(["page", "all"])("omits hidden middle columns from the display, summaries and %s export", async (scope) => {
|
||||
mounted = mountView({
|
||||
items: [
|
||||
{ key: "a", label: "conn-a", status: "success", result: { ...result(["name", "__DBX_PK_0", "amount"], [["Alice", 987654, 10]]), hidden_column_indexes: [1] } },
|
||||
{ key: "b", label: "conn-b", status: "success", result: result(["amount", "name"], [[20, "Bob"]]) },
|
||||
],
|
||||
sql: "SELECT name, amount FROM t",
|
||||
});
|
||||
await nextTick();
|
||||
|
||||
expect([...mounted.host.querySelectorAll("thead th")].map((cell) => cell.textContent?.trim())).toEqual([i18n.global.t("multiDbExecute.mergedSourceColumn"), "name", "amount"]);
|
||||
expect([...mounted.host.querySelectorAll("tbody tr")].map((row) => [...row.querySelectorAll("td")].map((cell) => cell.textContent?.trim()))).toEqual([
|
||||
["conn-a", "Alice", "10"],
|
||||
["conn-b", "Bob", "20"],
|
||||
]);
|
||||
expect(mounted.host.querySelector("tfoot")?.textContent).toContain("30");
|
||||
expect(mounted.host.textContent).not.toContain("__DBX_PK_0");
|
||||
expect(mounted.host.textContent).not.toContain("987654");
|
||||
|
||||
exportButton(`[data-merge-export-${scope}]`).click();
|
||||
await vi.waitFor(() => expect(mocks.exportQueryResultsXlsx).toHaveBeenCalledTimes(1));
|
||||
const sheet = (mocks.exportQueryResultsXlsx.mock.calls[0] as [string, Sheet[]])[1][0];
|
||||
expect(sheet?.columns).toEqual([i18n.global.t("multiDbExecute.mergedSourceColumn"), "name", "amount"]);
|
||||
expect(sheet?.rows).toEqual([
|
||||
["conn-a", "Alice", 10],
|
||||
["conn-b", "Bob", 20],
|
||||
]);
|
||||
});
|
||||
|
||||
it("exports every merged row plus a SQL sheet carrying the statement, the start time and the duration", async () => {
|
||||
mounted = mountView({
|
||||
items: [
|
||||
{ key: "a", label: "conn-a", status: "success", result: result(["id", "amount"], [[1, 10]]) },
|
||||
{ key: "b", label: "conn-b", status: "success", result: result(["id", "amount"], [[2, 20]]) },
|
||||
],
|
||||
sql: "SELECT id, amount FROM t",
|
||||
durationMs: 1234,
|
||||
executedAt: Date.UTC(2026, 0, 2, 3, 4, 5),
|
||||
});
|
||||
await nextTick();
|
||||
|
||||
exportButton("[data-merge-export-all]").click();
|
||||
await vi.waitFor(() => expect(mocks.exportQueryResultsXlsx).toHaveBeenCalledTimes(1));
|
||||
|
||||
const [outputPath, sheets, ...rest] = mocks.exportQueryResultsXlsx.mock.calls[0] as [string, Sheet[], boolean];
|
||||
expect(outputPath).toMatch(/^dbx-merged-result_all_\d{4}-\d{2}-\d{2}-\d{2}-\d{2}-\d{2}\.xlsx$/);
|
||||
expect(rest).toEqual([true]);
|
||||
|
||||
const [dataSheet, sqlSheet] = sheets;
|
||||
expect(dataSheet?.columns).toEqual([i18n.global.t("multiDbExecute.mergedSourceColumn"), "id", "amount"]);
|
||||
expect(dataSheet?.rows).toEqual([
|
||||
["conn-a", 1, 10],
|
||||
["conn-b", 2, 20],
|
||||
]);
|
||||
// The statement and the batch timings travel in their own sheet.
|
||||
expect(sqlSheet?.sheetName).toBe("SQL");
|
||||
const sqlCells = (sqlSheet?.rows ?? []).flat().join("\n");
|
||||
expect(sqlCells).toContain("SELECT id, amount FROM t");
|
||||
expect(sqlCells).toContain(i18n.global.t("multiDbExecute.durationColumn"));
|
||||
expect(sqlCells).toContain("1.2 s");
|
||||
expect(String(sqlCells)).toMatch(/20\d\d-\d\d-\d\d/);
|
||||
});
|
||||
|
||||
it("exports only the rows on screen for the current page", async () => {
|
||||
const rows = Array.from({ length: 1200 }, (_, index) => [index, index * 2]);
|
||||
mounted = mountView({
|
||||
items: [{ key: "a", label: "conn-a", status: "success", result: result(["id", "amount"], rows) }],
|
||||
sql: "SELECT id, amount FROM big",
|
||||
durationMs: 10,
|
||||
});
|
||||
await nextTick();
|
||||
|
||||
exportButton("[data-merge-export-page]").click();
|
||||
await vi.waitFor(() => expect(mocks.exportQueryResultsXlsx).toHaveBeenCalledTimes(1));
|
||||
const pageSheet = (mocks.exportQueryResultsXlsx.mock.calls[0] as [string, Sheet[]])[1][0];
|
||||
expect(pageSheet?.rows).toHaveLength(1000);
|
||||
|
||||
exportButton("[data-merge-export-all]").click();
|
||||
await vi.waitFor(() => expect(mocks.exportQueryResultsXlsx).toHaveBeenCalledTimes(2));
|
||||
const allSheet = (mocks.exportQueryResultsXlsx.mock.calls[1] as [string, Sheet[]])[1][0];
|
||||
expect(allSheet?.rows).toHaveLength(1200);
|
||||
});
|
||||
|
||||
it("exports the per-target list when the batch returned no result set", async () => {
|
||||
mounted = mountView({
|
||||
items: [
|
||||
{ key: "a", label: "conn-a", status: "success", durationMs: 12, result: result([], [], 3) },
|
||||
{ key: "b", label: "conn-b", status: "failed", durationMs: 9, errorMessage: "syntax error" },
|
||||
{ key: "c", label: "conn-c", status: "pending_commit", durationMs: 5, result: result([], [], 7), transaction: { canCommit: true } },
|
||||
],
|
||||
transactional: true,
|
||||
sql: "UPDATE t SET amount = 0",
|
||||
durationMs: 40,
|
||||
});
|
||||
await nextTick();
|
||||
|
||||
exportButton("[data-merge-export-all]").click();
|
||||
await vi.waitFor(() => expect(mocks.exportQueryResultsXlsx).toHaveBeenCalledTimes(1));
|
||||
|
||||
const sheet = (mocks.exportQueryResultsXlsx.mock.calls[0] as [string, Sheet[]])[1][0];
|
||||
expect(sheet?.columns).toEqual([
|
||||
i18n.global.t("multiDbExecute.mergedSourceColumn"),
|
||||
i18n.global.t("multiDbExecute.statusColumn"),
|
||||
i18n.global.t("multiDbExecute.txnColumn"),
|
||||
i18n.global.t("multiDbExecute.affectedRowsColumn"),
|
||||
i18n.global.t("multiDbExecute.durationColumn"),
|
||||
i18n.global.t("multiDbExecute.errorColumn"),
|
||||
]);
|
||||
expect(sheet?.rows.map((row) => row[0])).toEqual(["conn-a", "conn-b", "conn-c"]);
|
||||
// A statement that ran inside a transaction still reports its row count.
|
||||
expect(sheet?.rows[0]?.[3]).toBe(3);
|
||||
expect(sheet?.rows[2]?.[3]).toBe(7);
|
||||
expect(sheet?.rows[1]?.[3]).toBe("");
|
||||
expect(String(sheet?.rows[1]?.[5])).toBe("syntax error");
|
||||
expect(sheet?.rows[0]?.[2]).toBe(i18n.global.t("multiDbExecute.txnCommitted"));
|
||||
expect(sheet?.rows[2]?.[2]).toBe(i18n.global.t("multiDbExecute.txnOpen"));
|
||||
});
|
||||
|
||||
it("keeps a single-sheet workbook when the batch carries no SQL context", async () => {
|
||||
mounted = mountView({
|
||||
items: [{ key: "a", label: "conn-a", status: "success", result: result(["id"], [[1]]) }],
|
||||
});
|
||||
await nextTick();
|
||||
|
||||
exportButton("[data-merge-export-all]").click();
|
||||
await vi.waitFor(() => expect(mocks.exportQueryResultXlsx).toHaveBeenCalledTimes(1));
|
||||
|
||||
const [outputPath, sheetName, columns, , , rows] = mocks.exportQueryResultXlsx.mock.calls[0] as [string, string, string[], string[], unknown, unknown[][]];
|
||||
expect(outputPath).toMatch(/\.xlsx$/);
|
||||
expect(sheetName).toBe(i18n.global.t("multiDbExecute.mergedSheetName"));
|
||||
expect(columns).toEqual([i18n.global.t("multiDbExecute.mergedSourceColumn"), "id"]);
|
||||
expect(rows).toEqual([["conn-a", 1]]);
|
||||
expect(mocks.exportQueryResultsXlsx).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("refuses to export an empty merged table", async () => {
|
||||
mounted = mountView({ items: [{ key: "a", label: "conn-a", status: "success", result: result(["id"], []) }] });
|
||||
await nextTick();
|
||||
|
||||
exportButton("[data-merge-export-all]").click();
|
||||
await nextTick();
|
||||
|
||||
expect(mocks.exportQueryResultsXlsx).not.toHaveBeenCalled();
|
||||
expect(mocks.exportQueryResultXlsx).not.toHaveBeenCalled();
|
||||
expect(mocks.toast).toHaveBeenCalledWith(i18n.global.t("multiDbExecute.mergedEmpty"), 3000);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,225 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { createApp, h, nextTick } from "vue";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import i18n from "@/i18n";
|
||||
import MultiSourceMergeView from "@/components/editor/MultiSourceMergeView.vue";
|
||||
import { buildXlsxWorkbook } from "@/lib/export/xlsxExport";
|
||||
import { MULTI_SOURCE_MAX_ROWS_PER_SOURCE, mergeMultiSourceResults } from "@/lib/query/multiSourceResult";
|
||||
import type { QueryResult } from "@/types/database";
|
||||
|
||||
function result(columns: string[], rows: (string | number | null)[][]): QueryResult {
|
||||
return { columns, rows, affected_rows: rows.length, execution_time_ms: 1 };
|
||||
}
|
||||
|
||||
function mountView(items: Array<{ key: string; label: string; result?: QueryResult; status?: "success" | "failed" | "skipped" | "cancelled" | "not_executed" | "running" | "pending"; durationMs?: number; errorMessage?: string }>, props: Record<string, unknown> = {}) {
|
||||
const host = document.createElement("div");
|
||||
document.body.appendChild(host);
|
||||
const app = createApp({ render: () => h(MultiSourceMergeView, { items, ...props }) });
|
||||
app.use(i18n);
|
||||
app.mount(host);
|
||||
return { host, app };
|
||||
}
|
||||
|
||||
let mounted: ReturnType<typeof mountView> | undefined;
|
||||
|
||||
afterEach(() => {
|
||||
mounted?.app.unmount();
|
||||
mounted?.host.remove();
|
||||
mounted = undefined;
|
||||
});
|
||||
|
||||
describe("MultiSourceMergeView", () => {
|
||||
it("unions source columns, labels every row with its source and pads missing columns", async () => {
|
||||
mounted = mountView([
|
||||
{ key: "a", label: "conn-a", result: result(["id", "amount"], [[1, 10]]) },
|
||||
{ key: "b", label: "conn-b", result: result(["amount", "region"], [[20, "north"]]) },
|
||||
]);
|
||||
await nextTick();
|
||||
|
||||
const headers = [...mounted.host.querySelectorAll("thead th")].map((cell) => cell.textContent?.trim());
|
||||
expect(headers.slice(1)).toEqual(["id", "amount", "region"]);
|
||||
|
||||
const rows = [...mounted.host.querySelectorAll("tbody tr")].map((row) => [...row.querySelectorAll("td")].map((cell) => cell.textContent?.trim()));
|
||||
expect(rows).toHaveLength(2);
|
||||
expect(rows[0]?.slice(1)).toEqual(["1", "10", ""]);
|
||||
expect(rows[1]?.slice(1)).toEqual(["", "20", "north"]);
|
||||
expect(rows[0]?.[0]).toContain("conn-a");
|
||||
expect(rows[1]?.[0]).toContain("conn-b");
|
||||
});
|
||||
|
||||
it("sums only all-numeric columns in the footer", async () => {
|
||||
mounted = mountView([
|
||||
{ key: "a", label: "conn-a", result: result(["id", "amount", "note"], [[1, 10, "x"]]) },
|
||||
{ key: "b", label: "conn-b", result: result(["id", "amount", "note"], [[2, "n/a", "y"]]) },
|
||||
]);
|
||||
await nextTick();
|
||||
|
||||
const footer = [...(mounted.host.querySelector("tfoot")?.querySelectorAll("td") ?? [])].map((cell) => cell.textContent?.trim());
|
||||
// First cell is the SUM label, then one cell per data column.
|
||||
expect(footer).toHaveLength(4);
|
||||
expect(footer[1]).toBe("3");
|
||||
// `amount` mixes 10 and "n/a", so its column is not a total.
|
||||
expect(footer[2]).toBe("");
|
||||
expect(footer[3]).toBe("");
|
||||
});
|
||||
|
||||
it("reports the merged source count and row count", async () => {
|
||||
mounted = mountView([
|
||||
{ key: "a", label: "conn-a", result: result(["id"], [[1]]) },
|
||||
{ key: "b", label: "conn-b", result: result(["id"], [[2]]) },
|
||||
]);
|
||||
await nextTick();
|
||||
|
||||
const legend = mounted.host.querySelector("[data-multi-source-merge-view]")?.textContent ?? "";
|
||||
expect(legend).toContain("2");
|
||||
});
|
||||
|
||||
it("states the per-source row cap and warns explicitly when a source hit it", async () => {
|
||||
const cappedRows = Array.from({ length: MULTI_SOURCE_MAX_ROWS_PER_SOURCE }, (_, index) => [index, index]);
|
||||
mounted = mountView([
|
||||
{ key: "a", label: "conn-a", result: result(["id", "amount"], cappedRows) },
|
||||
{ key: "b", label: "conn-b", result: result(["id", "amount"], [[1, 2]]) },
|
||||
]);
|
||||
await nextTick();
|
||||
|
||||
const legend = mounted.host.querySelector("[data-multi-source-merge-view]")?.textContent ?? "";
|
||||
// The cap is always stated, and reaching it is called out in amber.
|
||||
expect(legend).toContain(String(MULTI_SOURCE_MAX_ROWS_PER_SOURCE));
|
||||
expect(mounted.host.querySelector("[data-merge-source-cap-reached]")?.textContent).toContain(String(MULTI_SOURCE_MAX_ROWS_PER_SOURCE));
|
||||
});
|
||||
|
||||
it("does not warn about the per-source cap while every source stays below it", async () => {
|
||||
mounted = mountView([
|
||||
{ key: "a", label: "conn-a", result: result(["id"], [[1], [2]]) },
|
||||
{ key: "b", label: "conn-b", result: result(["id"], [[3]]) },
|
||||
]);
|
||||
await nextTick();
|
||||
|
||||
expect(mounted.host.querySelector("[data-merge-source-cap-reached]")).toBeNull();
|
||||
expect(mounted.host.querySelector("[data-merge-truncated]")).toBeNull();
|
||||
});
|
||||
|
||||
it("feeds the Excel writer a workbook-ready payload", () => {
|
||||
const merged = mergeMultiSourceResults(
|
||||
[
|
||||
{ key: "a", label: "conn-a", result: result(["id", "amount", "note"], [[1, 10, "x"]]) },
|
||||
{ key: "b", label: "conn-b", result: result(["amount"], [[2.5]]) },
|
||||
],
|
||||
{ sourceColumnLabel: "来源" },
|
||||
);
|
||||
|
||||
// Same call shape the export action uses (no column types available).
|
||||
const workbook = buildXlsxWorkbook({
|
||||
sheetName: "合并结果",
|
||||
columns: merged.columns,
|
||||
columnTypes: merged.columns.map(() => ""),
|
||||
rows: merged.rows,
|
||||
numericColumnRightAlign: true,
|
||||
autoFilter: true,
|
||||
});
|
||||
|
||||
expect(workbook.byteLength).toBeGreaterThan(0);
|
||||
// XLSX is a zip container; the local file header magic proves the writer
|
||||
// accepted the merged rows (nulls and mixed types included).
|
||||
expect(String.fromCharCode(...workbook.subarray(0, 2))).toBe("PK");
|
||||
});
|
||||
|
||||
it("shows the executed statement and the batch duration in the header", async () => {
|
||||
mounted = mountView([{ key: "a", label: "conn-a", result: result(["id"], [[1]]) }], { sql: "SELECT id FROM sales", durationMs: 1250 });
|
||||
await nextTick();
|
||||
|
||||
const header = mounted.host.querySelector("[data-multi-source-merge-view]")?.textContent ?? "";
|
||||
expect(header).toContain("SELECT id FROM sales");
|
||||
expect(header).toContain("1.3 s");
|
||||
expect(mounted.host.querySelector("[data-merge-sql]")?.getAttribute("title")).toBe("SELECT id FROM sales");
|
||||
});
|
||||
|
||||
it("shows the local execution timestamp of the batch", async () => {
|
||||
const executedAt = new Date(2026, 8, 21, 14, 32, 5).getTime();
|
||||
mounted = mountView([{ key: "a", label: "conn-a", result: result(["id"], [[1]]) }], { executedAt });
|
||||
await nextTick();
|
||||
|
||||
const chip = mounted.host.querySelector("[data-merge-executed-at]")?.textContent ?? "";
|
||||
expect(chip).toContain("2026-09-21 14:32:05");
|
||||
// Timezone stays explicit, like the app's other local timestamps.
|
||||
expect(chip).toMatch(/[+-]\d{2}:\d{2}/);
|
||||
});
|
||||
|
||||
it("omits the SQL and duration chips when the host does not provide them", async () => {
|
||||
mounted = mountView([{ key: "a", label: "conn-a", result: result(["id"], [[1]]) }]);
|
||||
await nextTick();
|
||||
|
||||
expect(mounted.host.querySelector("[data-merge-sql]")).toBeNull();
|
||||
expect(mounted.host.querySelector("[data-merge-duration]")).toBeNull();
|
||||
expect(mounted.host.querySelector("[data-merge-executed-at]")).toBeNull();
|
||||
});
|
||||
|
||||
describe("write statements without a result set", () => {
|
||||
function writeItems() {
|
||||
return [
|
||||
{
|
||||
key: "a",
|
||||
label: "conn-a",
|
||||
status: "success" as const,
|
||||
durationMs: 41,
|
||||
result: { columns: [], rows: [], affected_rows: 12, execution_time_ms: 41 },
|
||||
},
|
||||
{
|
||||
key: "b",
|
||||
label: "conn-b",
|
||||
status: "failed" as const,
|
||||
durationMs: 17,
|
||||
errorMessage: "no such table: t_order",
|
||||
result: { columns: ["Error"], rows: [["no such table: t_order"]], affected_rows: 0, execution_time_ms: 17, execution_error: true as const },
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
it("lists one row per target with status, affected rows and the error", async () => {
|
||||
mounted = mountView(writeItems());
|
||||
await nextTick();
|
||||
|
||||
const table = mounted.host.querySelector("[data-merge-target-results]");
|
||||
expect(table).not.toBeNull();
|
||||
const rows = [...(table?.querySelectorAll("tbody tr") ?? [])].map((row) => [...row.querySelectorAll("td")].map((cell) => cell.textContent?.replace(/\s+/g, " ").trim()));
|
||||
expect(rows).toHaveLength(2);
|
||||
expect(rows[0]?.[0]).toBe("conn-a");
|
||||
expect(rows[0]?.[2]).toContain("12");
|
||||
expect(rows[1]?.[0]).toBe("conn-b");
|
||||
expect(rows[1]?.[2]).toBe("—");
|
||||
expect(rows[1]?.[4]).toContain("no such table");
|
||||
});
|
||||
|
||||
it("summarizes the batch by targets and affected rows instead of read statistics", async () => {
|
||||
mounted = mountView(writeItems());
|
||||
await nextTick();
|
||||
|
||||
expect(mounted.host.querySelector("[data-merge-write-summary]")?.textContent?.trim()).toBe(i18n.global.t("multiDbExecute.mergedWriteSummary", { targets: 2, rows: 12 }));
|
||||
// A write batch must not advertise the per-source read cap it never uses.
|
||||
expect(mounted.host.textContent).not.toContain(i18n.global.t("multiDbExecute.mergedSourceRowCap", { count: MULTI_SOURCE_MAX_ROWS_PER_SOURCE }));
|
||||
// The column already names the count, so the cell carries the bare number.
|
||||
const affected = [...(mounted.host.querySelectorAll("[data-merge-target-results] tbody tr") ?? [])].map((row) => [...row.querySelectorAll("td")][2]?.textContent?.trim());
|
||||
expect(affected).toEqual(["12", "—"]);
|
||||
});
|
||||
|
||||
it("offers a re-run only for targets that did not succeed", async () => {
|
||||
const rerun: string[] = [];
|
||||
mounted = mountView(writeItems(), { onRerunTarget: (key: string) => rerun.push(key) });
|
||||
await nextTick();
|
||||
|
||||
const buttons = [...mounted.host.querySelectorAll("[data-merge-rerun]")];
|
||||
expect(buttons).toHaveLength(1);
|
||||
(buttons[0] as HTMLButtonElement).click();
|
||||
await nextTick();
|
||||
expect(rerun).toEqual(["b"]);
|
||||
});
|
||||
|
||||
it("blocks re-running while the batch is still busy", async () => {
|
||||
mounted = mountView(writeItems(), { rerunDisabled: true });
|
||||
await nextTick();
|
||||
|
||||
const rerunButton = mounted.host.querySelector("[data-merge-rerun]") as HTMLButtonElement | null;
|
||||
expect(rerunButton?.disabled).toBe(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
+110
@@ -0,0 +1,110 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { createApp, h, nextTick } from "vue";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import i18n from "@/i18n";
|
||||
import MultiSourceMergeView from "@/components/editor/MultiSourceMergeView.vue";
|
||||
import type { QueryResult } from "@/types/database";
|
||||
|
||||
function writeResult(affectedRows: number): QueryResult {
|
||||
return { columns: [], rows: [], affected_rows: affectedRows, execution_time_ms: 7 };
|
||||
}
|
||||
|
||||
/** One batch that ran inside per-target transactions. */
|
||||
function items() {
|
||||
return [
|
||||
{ key: "a", label: "conn-a", status: "pending_commit" as const, durationMs: 12, result: writeResult(3), transaction: { canCommit: true } },
|
||||
// A target whose session survived a rollback failure: it can still be rolled back.
|
||||
{ key: "b", label: "conn-b", status: "failed" as const, durationMs: 9, errorMessage: "syntax error", transaction: { canCommit: false } },
|
||||
{ key: "c", label: "conn-c", status: "success" as const, durationMs: 5, result: writeResult(0) },
|
||||
{ key: "d", label: "conn-d", status: "rolled_back" as const, durationMs: 4 },
|
||||
];
|
||||
}
|
||||
|
||||
function mountView(props: Record<string, unknown>) {
|
||||
const host = document.createElement("div");
|
||||
document.body.appendChild(host);
|
||||
const app = createApp({ render: () => h(MultiSourceMergeView, props) });
|
||||
app.use(i18n);
|
||||
app.mount(host);
|
||||
return { host, app };
|
||||
}
|
||||
|
||||
let mounted: ReturnType<typeof mountView> | undefined;
|
||||
|
||||
afterEach(() => {
|
||||
mounted?.app.unmount();
|
||||
mounted?.host.remove();
|
||||
mounted = undefined;
|
||||
});
|
||||
|
||||
describe("MultiSourceMergeView transactions", () => {
|
||||
it("shows the transaction state per target and offers commit/rollback only while open", async () => {
|
||||
mounted = mountView({ items: items(), transactional: true });
|
||||
await nextTick();
|
||||
|
||||
const states = [...mounted.host.querySelectorAll("[data-merge-txn-state]")].map((cell) => cell.textContent?.trim());
|
||||
expect(states).toEqual([i18n.global.t("multiDbExecute.txnOpen"), i18n.global.t("multiDbExecute.txnOpen"), i18n.global.t("multiDbExecute.txnCommitted"), i18n.global.t("multiDbExecute.txnRolledBack")]);
|
||||
|
||||
// Two open sessions: each offers one commit and one rollback button.
|
||||
expect(mounted.host.querySelectorAll("[data-merge-commit]")).toHaveLength(2);
|
||||
expect(mounted.host.querySelectorAll("[data-merge-rollback]")).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("blocks committing a target that errored and counts only committable targets", async () => {
|
||||
mounted = mountView({ items: items(), transactional: true });
|
||||
await nextTick();
|
||||
|
||||
const commitButtons = [...mounted.host.querySelectorAll("[data-merge-commit]")] as HTMLButtonElement[];
|
||||
expect(commitButtons[0]?.disabled).toBe(false);
|
||||
// conn-b failed, so its transaction has nothing to write but can be discarded.
|
||||
expect(commitButtons[1]?.disabled).toBe(true);
|
||||
|
||||
const commitAll = mounted.host.querySelector("[data-merge-commit-all]") as HTMLButtonElement;
|
||||
expect(commitAll.textContent).toContain("1");
|
||||
});
|
||||
|
||||
it("blocks every transaction control while one of them is settling", async () => {
|
||||
const settling = items();
|
||||
settling[0] = { ...settling[0]!, transaction: { canCommit: true, settling: true } } as (typeof settling)[number];
|
||||
mounted = mountView({ items: settling, transactional: true });
|
||||
await nextTick();
|
||||
|
||||
const commitButtons = [...mounted.host.querySelectorAll("[data-merge-commit]")] as HTMLButtonElement[];
|
||||
const rollbackButtons = [...mounted.host.querySelectorAll("[data-merge-rollback]")] as HTMLButtonElement[];
|
||||
expect(commitButtons[0]?.disabled).toBe(true);
|
||||
expect(rollbackButtons[0]?.disabled).toBe(true);
|
||||
});
|
||||
|
||||
it("emits per-target and batch transaction actions", async () => {
|
||||
const events: string[] = [];
|
||||
mounted = mountView({
|
||||
items: items(),
|
||||
transactional: true,
|
||||
onCommitTarget: (key: string) => events.push(`commit:${key}`),
|
||||
onRollbackTarget: (key: string) => events.push(`rollback:${key}`),
|
||||
onCommitAll: () => events.push("commit-all"),
|
||||
onRollbackAll: () => events.push("rollback-all"),
|
||||
});
|
||||
await nextTick();
|
||||
|
||||
(mounted.host.querySelectorAll("[data-merge-commit]")[0] as HTMLButtonElement).click();
|
||||
(mounted.host.querySelectorAll("[data-merge-rollback]")[1] as HTMLButtonElement).click();
|
||||
(mounted.host.querySelector("[data-merge-commit-all]") as HTMLButtonElement).click();
|
||||
(mounted.host.querySelector("[data-merge-rollback-all]") as HTMLButtonElement).click();
|
||||
await nextTick();
|
||||
|
||||
expect(events).toEqual(["commit:a", "rollback:b", "commit-all", "rollback-all"]);
|
||||
});
|
||||
|
||||
it("hides every transaction control for an auto-commit batch", async () => {
|
||||
const autoCommit = items().map(({ transaction: _transaction, ...item }) => ({ ...item, status: item.status === "pending_commit" ? ("success" as const) : item.status }));
|
||||
mounted = mountView({ items: autoCommit, transactional: false });
|
||||
await nextTick();
|
||||
|
||||
expect(mounted.host.querySelector("[data-merge-txn-state]")).toBeNull();
|
||||
expect(mounted.host.querySelector("[data-merge-commit-all]")).toBeNull();
|
||||
expect(mounted.host.querySelector("[data-merge-rollback-all]")).toBeNull();
|
||||
// A failed target without a session keeps its re-run affordance instead.
|
||||
expect(mounted.host.querySelector("[data-merge-rerun]")).not.toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -5,6 +5,7 @@ import { Button } from "@/components/ui/button";
|
||||
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
|
||||
const ConnectionDialog = defineAsyncComponent(() => import("@/components/connection/ConnectionDialog.vue"));
|
||||
const DangerConfirmDialog = defineAsyncComponent(() => import("@/components/editor/DangerConfirmDialog.vue"));
|
||||
const MultiDbDangerConfirmDialog = defineAsyncComponent(() => import("@/components/layout/MultiDbDangerConfirmDialog.vue"));
|
||||
const SqlParameterDialog = defineAsyncComponent(() => import("@/components/editor/SqlParameterDialog.vue"));
|
||||
const DataTransferDialog = defineAsyncComponent(() => import("@/components/transfer/DataTransferDialog.vue"));
|
||||
const SchemaDiffDialog = defineAsyncComponent(() => import("@/components/diff/SchemaDiffDialog.vue"));
|
||||
@@ -126,16 +127,6 @@ watch(
|
||||
if (pending) unlockDuration.value = WRITE_UNLOCK_ONE_MINUTE_SECS;
|
||||
},
|
||||
);
|
||||
const multiDbDangerDetails = computed(() => {
|
||||
const request = sqlExecutionDangerStore.pending;
|
||||
if (!request) return "";
|
||||
return [request.targetLabel || request.connectionName, request.database].filter(Boolean).join("\n");
|
||||
});
|
||||
const multiDbDangerMessage = computed(() => {
|
||||
const request = sqlExecutionDangerStore.pending;
|
||||
return request?.kind === "redis" ? t("dangerDialog.redisCommandMessage") : t("dangerDialog.message");
|
||||
});
|
||||
|
||||
const editConfig = computed(() => {
|
||||
const id = connectionStore.editingConnectionId;
|
||||
if (!id) return undefined;
|
||||
@@ -230,19 +221,7 @@ watch(
|
||||
</fieldset>
|
||||
</template>
|
||||
</DangerConfirmDialog>
|
||||
<DangerConfirmDialog
|
||||
v-if="sqlExecutionDangerStore.pending"
|
||||
:open="true"
|
||||
:title="t('multiDbExecute.dangerTitle')"
|
||||
:message="multiDbDangerMessage"
|
||||
:details-text="multiDbDangerDetails"
|
||||
:sql="sqlExecutionDangerStore.pending.sql"
|
||||
:confirm-label="t('multiDbExecute.dangerConfirm')"
|
||||
:show-suppress-toggle="false"
|
||||
:close-on-confirm="false"
|
||||
@update:open="(open) => !open && sqlExecutionDangerStore.cancel()"
|
||||
@confirm="sqlExecutionDangerStore.confirm()"
|
||||
/>
|
||||
<MultiDbDangerConfirmDialog v-if="sqlExecutionDangerStore.pending" :request="sqlExecutionDangerStore.pending" @confirm="sqlExecutionDangerStore.confirm()" @cancel="sqlExecutionDangerStore.cancel()" />
|
||||
<SqlParameterDialog
|
||||
v-if="showSqlParameterDialog"
|
||||
:open="showSqlParameterDialog"
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, watch } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { Check, Copy } from "@lucide/vue";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import DangerConfirmDialog from "@/components/editor/DangerConfirmDialog.vue";
|
||||
import { copyToClipboard } from "@/lib/common/clipboard";
|
||||
import { createExecutionConfirmCode, matchesExecutionConfirmCode } from "@/lib/query/executionConfirmCode";
|
||||
import type { SqlExecutionDangerRequest } from "@/stores/sqlExecutionDangerStore";
|
||||
|
||||
/**
|
||||
* Confirmation for one multi-database batch. A batch runs the same statement
|
||||
* against every data source, so the operator retypes a code that is generated
|
||||
* per prompt: a stray click or a held Enter cannot fan a destructive statement
|
||||
* out to all connections.
|
||||
*/
|
||||
const props = defineProps<{ request: SqlExecutionDangerRequest }>();
|
||||
const emit = defineEmits<{ confirm: []; cancel: [] }>();
|
||||
|
||||
const { t } = useI18n();
|
||||
|
||||
const details = computed(() => {
|
||||
const headline = [props.request.targetLabel || props.request.connectionName, props.request.database].filter(Boolean).join(" · ");
|
||||
const targets = props.request.targets ?? [];
|
||||
if (targets.length <= 1) return headline;
|
||||
return [headline, "", t("multiDbExecute.dangerTargets", { count: targets.length }), ...targets.map((target) => `• ${target}`)].join("\n");
|
||||
});
|
||||
|
||||
const message = computed(() => (props.request.kind === "redis" ? t("dangerDialog.redisCommandMessage") : t("dangerDialog.message")));
|
||||
|
||||
const code = ref("");
|
||||
const codeInput = ref("");
|
||||
const codeCopied = ref(false);
|
||||
const confirmDisabled = computed(() => !matchesExecutionConfirmCode(codeInput.value, code.value));
|
||||
|
||||
// Every prompt gets its own code, and the previous attempt is cleared.
|
||||
watch(
|
||||
() => props.request,
|
||||
() => {
|
||||
code.value = createExecutionConfirmCode();
|
||||
codeInput.value = "";
|
||||
codeCopied.value = false;
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
|
||||
async function copyCode(): Promise<void> {
|
||||
await copyToClipboard(code.value);
|
||||
codeCopied.value = true;
|
||||
window.setTimeout(() => {
|
||||
codeCopied.value = false;
|
||||
}, 1500);
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<DangerConfirmDialog
|
||||
:open="true"
|
||||
:title="t('multiDbExecute.dangerTitle')"
|
||||
:message="message"
|
||||
:details-text="details"
|
||||
:sql="request.sql"
|
||||
:confirm-label="t('multiDbExecute.dangerConfirm')"
|
||||
:confirm-disabled="confirmDisabled"
|
||||
:show-suppress-toggle="false"
|
||||
:close-on-confirm="false"
|
||||
@update:open="(open) => !open && emit('cancel')"
|
||||
@confirm="emit('confirm')"
|
||||
>
|
||||
<template #options>
|
||||
<div class="mb-3 space-y-1.5 rounded-md border bg-muted/20 px-3 py-2.5">
|
||||
<div class="flex items-center justify-between gap-2">
|
||||
<Label for="multi-db-danger-code" class="text-xs leading-5 text-muted-foreground">{{ t("multiDbExecute.dangerConfirmCodePrompt") }}</Label>
|
||||
<Button variant="ghost" size="icon-xs" class="h-6 w-6 text-muted-foreground" :title="t('multiDbExecute.dangerConfirmCodeCopy')" data-multi-db-danger-code-copy @click="copyCode">
|
||||
<Check v-if="codeCopied" class="h-3.5 w-3.5 text-emerald-600" />
|
||||
<Copy v-else class="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
<p class="font-mono text-lg leading-6 tracking-[0.3em] text-foreground" data-multi-db-danger-code-value>{{ code }}</p>
|
||||
<Input id="multi-db-danger-code" v-model="codeInput" data-multi-db-danger-code class="h-8 font-mono tracking-widest" autocomplete="off" spellcheck="false" :placeholder="t('multiDbExecute.dangerConfirmCodePlaceholder')" />
|
||||
<!-- The whole batch is answered by this one code, so the instruction
|
||||
has to stand out next to the input instead of blending into it. -->
|
||||
<p class="text-xs leading-4 font-semibold text-destructive" data-multi-db-danger-code-once>{{ t("multiDbExecute.dangerConfirmCodeOnce") }}</p>
|
||||
</div>
|
||||
</template>
|
||||
</DangerConfirmDialog>
|
||||
</template>
|
||||
+171
@@ -0,0 +1,171 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { createApp, h, nextTick, type App } from "vue";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import i18n from "@/i18n";
|
||||
import MultiDbDangerConfirmDialog from "@/components/layout/MultiDbDangerConfirmDialog.vue";
|
||||
import type { SqlExecutionDangerRequest } from "@/stores/sqlExecutionDangerStore";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ copyToClipboard: vi.fn().mockResolvedValue(undefined) }));
|
||||
|
||||
vi.mock("@/lib/common/clipboard", () => ({ copyToClipboard: mocks.copyToClipboard }));
|
||||
|
||||
function request(overrides: Partial<SqlExecutionDangerRequest> = {}): SqlExecutionDangerRequest {
|
||||
return {
|
||||
sql: "UPDATE accounts SET balance = 0",
|
||||
kind: "sql",
|
||||
connectionName: "prod-a",
|
||||
database: "shop",
|
||||
targetLabel: "prod-a / shop",
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function mountDialog(props: Record<string, unknown>) {
|
||||
const host = document.createElement("div");
|
||||
document.body.appendChild(host);
|
||||
const app = createApp({ render: () => h(MultiDbDangerConfirmDialog, props) });
|
||||
app.use(i18n);
|
||||
app.mount(host);
|
||||
return { host, app };
|
||||
}
|
||||
|
||||
let mounted: { host: HTMLElement; app: App } | undefined;
|
||||
|
||||
afterEach(() => {
|
||||
mounted?.app.unmount();
|
||||
mounted?.host.remove();
|
||||
mounted = undefined;
|
||||
mocks.copyToClipboard.mockClear();
|
||||
});
|
||||
|
||||
/** The dialog content is portaled to the document body. */
|
||||
function codeValue(): string {
|
||||
return document.body.querySelector("[data-multi-db-danger-code-value]")?.textContent?.trim() ?? "";
|
||||
}
|
||||
|
||||
function codeInput(): HTMLInputElement {
|
||||
const input = document.body.querySelector<HTMLInputElement>("[data-multi-db-danger-code]");
|
||||
if (!input) throw new Error("Missing code input");
|
||||
return input;
|
||||
}
|
||||
|
||||
function confirmButton(): HTMLButtonElement {
|
||||
const button = [...document.body.querySelectorAll("button")].find((candidate) => candidate.textContent?.trim() === i18n.global.t("multiDbExecute.dangerConfirm"));
|
||||
if (!button) throw new Error("Missing confirm button");
|
||||
return button;
|
||||
}
|
||||
|
||||
async function typeCode(value: string) {
|
||||
const input = codeInput();
|
||||
input.value = value;
|
||||
input.dispatchEvent(new Event("input"));
|
||||
await nextTick();
|
||||
}
|
||||
|
||||
describe("multi-database batch confirmation", () => {
|
||||
it("lists every data source of the batch next to the target that prompted", async () => {
|
||||
mounted = mountDialog({ request: request({ targets: ["prod-a / shop", "prod-b / shop", "prod-c / shop"] }) });
|
||||
await nextTick();
|
||||
|
||||
const text = document.body.textContent ?? "";
|
||||
expect(text).toContain("prod-a / shop");
|
||||
expect(text).toContain(i18n.global.t("multiDbExecute.dangerTargets", { count: 3 }));
|
||||
expect(text).toContain("• prod-b / shop");
|
||||
expect(text).toContain("• prod-c / shop");
|
||||
expect(document.body.textContent).toContain("UPDATE accounts SET balance = 0");
|
||||
});
|
||||
|
||||
it("keeps the headline only when the statement touches a single source", async () => {
|
||||
mounted = mountDialog({ request: request({ targets: ["prod-a / shop"] }) });
|
||||
await nextTick();
|
||||
|
||||
expect(document.body.textContent).not.toContain(i18n.global.t("multiDbExecute.dangerTargets", { count: 1 }));
|
||||
expect(document.body.textContent).toContain("prod-a / shop");
|
||||
});
|
||||
|
||||
it("unlocks the confirm button only for the code of this prompt", async () => {
|
||||
mounted = mountDialog({ request: request() });
|
||||
await nextTick();
|
||||
|
||||
const code = codeValue();
|
||||
expect(code).toHaveLength(6);
|
||||
expect(confirmButton().disabled).toBe(true);
|
||||
|
||||
await typeCode("WRONG1");
|
||||
expect(confirmButton().disabled).toBe(true);
|
||||
|
||||
await typeCode(code);
|
||||
expect(confirmButton().disabled).toBe(false);
|
||||
});
|
||||
|
||||
it("accepts a code typed in lower case", async () => {
|
||||
mounted = mountDialog({ request: request() });
|
||||
await nextTick();
|
||||
|
||||
await typeCode(codeValue().toLowerCase());
|
||||
expect(confirmButton().disabled).toBe(false);
|
||||
});
|
||||
|
||||
it("copies the displayed code and clears the typed attempt for a new prompt", async () => {
|
||||
mounted = mountDialog({ request: request() });
|
||||
await nextTick();
|
||||
|
||||
const firstCode = codeValue();
|
||||
await typeCode(firstCode);
|
||||
(document.body.querySelector("[data-multi-db-danger-code-copy]") as HTMLButtonElement).click();
|
||||
await vi.waitFor(() => expect(mocks.copyToClipboard).toHaveBeenCalledWith(firstCode));
|
||||
|
||||
// The next prompt is a fresh confirmation, not the previous one re-armed.
|
||||
mounted.app.unmount();
|
||||
mounted.host.remove();
|
||||
mounted = mountDialog({ request: request({ sql: "DELETE FROM accounts" }) });
|
||||
await nextTick();
|
||||
const nextCode = codeValue();
|
||||
expect(nextCode).toHaveLength(6);
|
||||
expect(codeInput().value).toBe("");
|
||||
expect(confirmButton().disabled).toBe(true);
|
||||
});
|
||||
|
||||
it("reports confirm and cancel back to the batch", async () => {
|
||||
const events: string[] = [];
|
||||
mounted = mountDialog({
|
||||
request: request(),
|
||||
onConfirm: () => events.push("confirm"),
|
||||
onCancel: () => events.push("cancel"),
|
||||
});
|
||||
await nextTick();
|
||||
|
||||
// Cancelling the prompt answers the batch without running it.
|
||||
const cancel = [...document.body.querySelectorAll("button")].find((candidate) => candidate.textContent?.trim() === i18n.global.t("dangerDialog.cancel"));
|
||||
cancel?.click();
|
||||
await nextTick();
|
||||
expect(events).toEqual(["cancel"]);
|
||||
|
||||
await typeCode(codeValue());
|
||||
confirmButton().click();
|
||||
await nextTick();
|
||||
expect(events).toEqual(["cancel", "confirm"]);
|
||||
});
|
||||
|
||||
it("still confirms the single-connection danger dialog without any code", async () => {
|
||||
const { default: DangerConfirmDialog } = await import("@/components/editor/DangerConfirmDialog.vue");
|
||||
const host = document.createElement("div");
|
||||
document.body.appendChild(host);
|
||||
const confirms: number[] = [];
|
||||
const app = createApp({ render: () => h(DangerConfirmDialog, { open: true, title: "Drop table", message: "This cannot be undone", onConfirm: () => confirms.push(1) }) });
|
||||
app.use(i18n);
|
||||
app.mount(host);
|
||||
try {
|
||||
await nextTick();
|
||||
expect(document.body.querySelector("[data-multi-db-danger-code]")).toBeNull();
|
||||
const confirm = [...document.body.querySelectorAll("button")].find((candidate) => candidate.textContent?.trim() === i18n.global.t("dangerDialog.confirm"));
|
||||
expect(confirm).toBeDefined();
|
||||
confirm?.click();
|
||||
await nextTick();
|
||||
expect(confirms).toEqual([1]);
|
||||
} finally {
|
||||
app.unmount();
|
||||
host.remove();
|
||||
}
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user