25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。
TypeScript aicliclickhousedatabasedatabase-clientdatabase-managementdockerguimcpmongodbmysqlpostgresqlredisrustsql-serversqlitetaurivue
feat(explain): add plan canvas with actual execution plans
Fernando Posseboned1e36912c7b
diff --git a/apps/desktop/src/components/explain/ExplainPlanDiagram.vue b/apps/desktop/src/components/explain/ExplainPlanDiagram.vuenew file mode 100644index 0000000000..3bf4623a8b--- /dev/null+++ b/apps/desktop/src/components/explain/ExplainPlanDiagram.vue@@ -0,0 +1,327 @@+<script setup lang="ts">+import { computed, nextTick, onBeforeUnmount, ref, watch } from "vue";+import { useI18n } from "vue-i18n";+import { ArrowDownWideNarrow, CircleHelp, GitMerge, KeyRound, Layers, ListTree, Maximize2, MonitorCheck, Pencil, Sigma, Split, Table2, ZoomIn, ZoomOut } from "@lucide/vue";+import { Button } from "@/components/ui/button";+import type { ExplainPlanNode } from "@/lib/diagram/explainPlan";+import type { PlanCanvasCategory, PlanCanvasNode } from "@/lib/diagram/planCanvas";+import { buildPlanCanvas, edgeStrokeWidth, formatPlanRows, heatLevel, PLAN_CANVAS_GAP_X, PLAN_CANVAS_NODE_H, PLAN_CANVAS_NODE_W } from "@/lib/diagram/planCanvas";++const props = defineProps<{+ nodes: ExplainPlanNode[];+}>();++const { t } = useI18n();++const CATEGORY_COLORS: Record<PlanCanvasCategory, string> = {+ result: "#a78bfa",+ sort: "#38bdf8",+ join: "#f472b6",+ tscan: "#fb923c",+ iscan: "#34d399",+ lookup: "#2dd4bf",+ mat: "#94a3b8",+ agg: "#c084fc",+ xchg: "#facc15",+ mod: "#f87171",+ other: "var(--muted-foreground)",+};++const CATEGORY_ICONS = {+ result: MonitorCheck,+ sort: ArrowDownWideNarrow,+ join: GitMerge,+ tscan: Table2,+ iscan: ListTree,+ lookup: KeyRound,+ mat: Layers,+ agg: Sigma,+ xchg: Split,+ mod: Pencil,+ other: CircleHelp,+} as const;++const CATEGORY_LABEL_KEYS: Record<PlanCanvasCategory, string> = {+ result: "explain.catResult",+ sort: "explain.catSort",+ join: "explain.catJoin",+ tscan: "explain.catTscan",+ iscan: "explain.catIscan",+ lookup: "explain.catLookup",+ mat: "explain.catMat",+ agg: "explain.catAgg",+ xchg: "explain.catXchg",+ mod: "explain.catMod",+ other: "explain.catOther",+};++const HEAT_COLORS = {+ none: "var(--muted-foreground)",+ cool: "#22c55e",+ warm: "#f59e0b",+ hot: "#ef4444",+} as const;++const HEAT_BADGE_CLASSES = {+ none: "bg-muted text-muted-foreground",+ cool: "bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-300",+ warm: "bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-300",+ hot: "bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-300",+} as const;++const MIN_ZOOM = 0.5;+const MAX_ZOOM = 1.6;+const FIT_ZOOM = 1.3;++const layout = computed(() => buildPlanCanvas(props.nodes));+const viewport = ref<HTMLElement>();+const zoom = ref(1);+const selectedIndex = ref(-1);++const hottest = computed(() => {+ let best: PlanCanvasNode | undefined;+ for (const node of layout.value.nodes) {+ if (best === undefined || (node.costShare ?? -1) > (best.costShare ?? -1)) best = node;+ }+ return best;+});+const selected = computed(() => layout.value.nodes[selectedIndex.value] ?? hottest.value);++const edges = computed(() =>+ layout.value.edges.map((edge) => {+ const startX = edge.from.x + PLAN_CANVAS_NODE_W;+ const startY = edge.from.y + PLAN_CANVAS_NODE_H / 2;+ const endY = edge.to.y + PLAN_CANVAS_NODE_H / 2;+ const elbowX = edge.to.x - PLAN_CANVAS_GAP_X / 2;+ return {+ key: `${edge.from.node.id}->${edge.to.node.id}`,+ path: `M ${startX} ${startY} H ${elbowX} V ${endY} H ${edge.to.x}`,+ width: edgeStrokeWidth(edge.rows),+ label: formatPlanRows(edge.rows),+ labelX: edge.to.x - 8,+ labelY: endY - 8,+ };+ }),+);++interface DetailEntry {+ label?: string;+ value: string;+}++const selectedDetails = computed<DetailEntry[]>(() =>+ (selected.value?.node.details ?? [])+ .map((detail): DetailEntry => {+ const separatorIndex = detail.indexOf(":");+ if (separatorIndex === -1) return { value: detail.trim() };+ const label = detail.slice(0, separatorIndex).trim();+ return { label: label || undefined, value: detail.slice(separatorIndex + 1).trim() };+ })+ .filter((detail) => detail.label || detail.value),+);++function categoryColor(category: PlanCanvasCategory): string {+ return CATEGORY_COLORS[category];+}++function iconTint(category: PlanCanvasCategory): string {+ return `color-mix(in srgb, ${categoryColor(category)} 18%, transparent)`;+}++function costPercent(share?: number): string {+ return share === undefined ? "" : `${(share * 100).toFixed(1)}%`;+}++/** Flags a node whose measured rows are at least 2x off the estimate. */+function rowMismatch(node: PlanCanvasNode): string | undefined {+ if (node.actualRows === undefined || !node.rows) return undefined;+ const ratio = node.actualRows / node.rows;+ return ratio >= 2 || ratio <= 0.5 ? `×${ratio.toFixed(1)}` : undefined;+}++function select(index: number) {+ selectedIndex.value = index;+}++function setZoom(value: number) {+ zoom.value = Math.min(MAX_ZOOM, Math.max(MIN_ZOOM, Number(value.toFixed(2))));+}++function zoomIn() {+ setZoom(zoom.value + 0.15);+}++function zoomOut() {+ setZoom(zoom.value - 0.15);+}++function fit() {+ const element = viewport.value;+ const { width, height } = layout.value;+ if (!element || !width || !height || !element.clientWidth || !element.clientHeight) return;+ setZoom(Math.min(element.clientWidth / width, element.clientHeight / height, FIT_ZOOM));+}++let panOrigin: { x: number; y: number; left: number; top: number } | undefined;++function stopPan() {+ panOrigin = undefined;+ window.removeEventListener("mousemove", onPanMove);+ window.removeEventListener("mouseup", stopPan);+}++function onPanMove(event: MouseEvent) {+ const element = viewport.value;+ if (!panOrigin || !element) return;+ element.scrollLeft = panOrigin.left - (event.clientX - panOrigin.x);+ element.scrollTop = panOrigin.top - (event.clientY - panOrigin.y);+}++function startPan(event: MouseEvent) {+ const element = viewport.value;+ if (!element || (event.target as HTMLElement | null)?.closest("[data-plan-node]")) return;+ panOrigin = { x: event.clientX, y: event.clientY, left: element.scrollLeft, top: element.scrollTop };+ window.addEventListener("mousemove", onPanMove);+ window.addEventListener("mouseup", stopPan);+}++onBeforeUnmount(stopPan);++watch(+ () => props.nodes,+ () => {+ selectedIndex.value = -1;+ void nextTick(fit);+ },+ { immediate: true },+);+</script>++<template>+ <div class="flex h-full min-h-0 min-w-0">+ <div class="flex min-h-0 min-w-0 flex-1 flex-col">+ <div class="flex h-8 shrink-0 items-center gap-1 border-b px-2">+ <span class="flex-1" />+ <Button variant="ghost" size="xs" class="h-6 px-1.5" :aria-label="t('explain.zoomOut')" :title="t('explain.zoomOut')" @click="zoomOut">+ <ZoomOut class="h-3.5 w-3.5" aria-hidden="true" />+ </Button>+ <Button variant="ghost" size="xs" class="h-6 px-1.5" :aria-label="t('explain.zoomFit')" :title="t('explain.zoomFit')" @click="fit">+ <Maximize2 class="h-3.5 w-3.5" aria-hidden="true" />+ </Button>+ <Button variant="ghost" size="xs" class="h-6 px-1.5" :aria-label="t('explain.zoomIn')" :title="t('explain.zoomIn')" @click="zoomIn">+ <ZoomIn class="h-3.5 w-3.5" aria-hidden="true" />+ </Button>+ <span class="ml-1 w-10 text-right font-mono text-[11px] tabular-nums text-muted-foreground">{{ Math.round(zoom * 100) }}%</span>+ </div>++ <div+ ref="viewport"+ class="relative min-h-0 flex-1 cursor-grab overflow-auto active:cursor-grabbing"+ :style="{+ backgroundImage: 'linear-gradient(color-mix(in srgb, var(--border) 70%, transparent) 1px, transparent 1px), linear-gradient(90deg, color-mix(in srgb, var(--border) 70%, transparent) 1px, transparent 1px)',+ backgroundSize: '28px 28px, 28px 28px',+ }"+ @mousedown="startPan"+ >+ <div :style="{ width: `${layout.width * zoom}px`, height: `${layout.height * zoom}px` }">+ <div class="relative origin-top-left" :style="{ width: `${layout.width}px`, height: `${layout.height}px`, transform: `scale(${zoom})` }">+ <svg data-plan-edges class="pointer-events-none absolute inset-0 overflow-visible text-muted-foreground/70" :width="layout.width" :height="layout.height" aria-hidden="true">+ <path v-for="edge in edges" :key="edge.key" :d="edge.path" fill="none" stroke="currentColor" stroke-linejoin="round" stroke-linecap="round" :stroke-width="edge.width" />+ <text v-for="edge in edges" :key="`${edge.key}-label`" :x="edge.labelX" :y="edge.labelY" text-anchor="end" class="fill-muted-foreground font-mono text-[10px]">{{ edge.label }}</text>+ </svg>++ <button+ v-for="(item, index) in layout.nodes"+ :key="`${item.node.id}-${index}`"+ type="button"+ data-plan-node+ :aria-pressed="selected === item"+ class="absolute flex flex-col overflow-hidden rounded-lg border bg-card py-1.5 pr-2.5 pl-3 text-left transition-shadow hover:shadow-md"+ :class="selected === item ? 'border-ring ring-2 ring-ring/30' : ''"+ :style="{ left: `${item.x}px`, top: `${item.y}px`, width: `${PLAN_CANVAS_NODE_W}px`, height: `${PLAN_CANVAS_NODE_H}px` }"+ @click="select(index)"+ >+ <span class="absolute inset-y-0 left-0 w-[3px] rounded-l-lg" :style="{ background: HEAT_COLORS[heatLevel(item.costShare)] }" aria-hidden="true" />++ <span class="flex min-w-0 items-center gap-1.5">+ <span class="flex h-5 w-5 shrink-0 items-center justify-center rounded" :style="{ background: iconTint(item.category), color: categoryColor(item.category) }">+ <component :is="CATEGORY_ICONS[item.category]" class="h-3 w-3" aria-hidden="true" />+ </span>+ <span class="min-w-0 flex-1 truncate text-xs font-semibold">{{ item.node.nodeType || item.node.title }}</span>+ <span v-if="item.costShare !== undefined" class="shrink-0 rounded px-1 font-mono text-[10px] font-semibold tabular-nums" :class="HEAT_BADGE_CLASSES[heatLevel(item.costShare)]">+ {{ costPercent(item.costShare) }}+ </span>+ </span>++ <span class="mt-1 truncate font-mono text-[10px] text-muted-foreground">+ {{ item.node.relation || " " }}+ <span v-if="item.node.index" :style="{ color: CATEGORY_COLORS.iscan }">[{{ item.node.index }}]</span>+ </span>++ <span class="mt-1 flex items-center gap-1.5 font-mono text-[10px] text-muted-foreground">+ <span class="truncate">{{ t("explain.estRows") }} {{ formatPlanRows(item.rows) }}</span>+ <span v-if="rowMismatch(item)" class="ml-auto shrink-0 font-semibold text-amber-600 dark:text-amber-400">{{ rowMismatch(item) }}</span>+ </span>+ </button>+ </div>+ </div>+ </div>++ <div class="flex shrink-0 flex-wrap items-center gap-x-3 gap-y-1 border-t px-3 py-1 text-[11px] text-muted-foreground">+ <span>{{ t("explain.legendHeat") }}</span>+ <span class="inline-flex items-center gap-1"><span class="h-2 w-2 rounded-[2px]" :style="{ background: HEAT_COLORS.cool }" />< 5%</span>+ <span class="inline-flex items-center gap-1"><span class="h-2 w-2 rounded-[2px]" :style="{ background: HEAT_COLORS.warm }" />5–20%</span>+ <span class="inline-flex items-center gap-1"><span class="h-2 w-2 rounded-[2px]" :style="{ background: HEAT_COLORS.hot }" />> 20%</span>+ <span class="ml-2">{{ t("explain.legendEdge") }}</span>+ </div>+ </div>++ <aside class="hidden w-72 shrink-0 flex-col overflow-auto border-l md:flex">+ <template v-if="selected">+ <div class="border-b p-3">+ <div class="flex items-center gap-2">+ <span class="flex h-6 w-6 shrink-0 items-center justify-center rounded" :style="{ background: iconTint(selected.category), color: categoryColor(selected.category) }">+ <component :is="CATEGORY_ICONS[selected.category]" class="h-3.5 w-3.5" aria-hidden="true" />+ </span>+ <div class="min-w-0">+ <div class="truncate text-sm font-semibold">{{ selected.node.nodeType || selected.node.title }}</div>+ <div class="text-[11px] font-medium" :style="{ color: categoryColor(selected.category) }">{{ t(CATEGORY_LABEL_KEYS[selected.category]) }}</div>+ </div>+ </div>+ <div v-if="selected.node.relation || selected.node.index" class="mt-2 truncate font-mono text-[11px] text-muted-foreground">+ {{ selected.node.relation }}<template v-if="selected.node.index"> [{{ selected.node.index }}]</template>+ </div>+ </div>++ <div class="grid grid-cols-2 border-b text-xs">+ <div class="border-r border-b p-2">+ <div class="text-[10px] uppercase tracking-wide text-muted-foreground">{{ t("explain.costShare") }}</div>+ <div class="font-mono font-semibold tabular-nums" :style="{ color: HEAT_COLORS[heatLevel(selected.costShare)] }">{{ costPercent(selected.costShare) || "—" }}</div>+ </div>+ <div class="border-b p-2">+ <div class="text-[10px] uppercase tracking-wide text-muted-foreground">{{ t("explain.cost") }}</div>+ <div class="truncate font-mono font-semibold tabular-nums">{{ selected.node.cost || "—" }}</div>+ </div>+ <div class="border-r p-2">+ <div class="text-[10px] uppercase tracking-wide text-muted-foreground">{{ t("explain.estRows") }}</div>+ <div class="font-mono font-semibold tabular-nums">{{ formatPlanRows(selected.rows) }}</div>+ </div>+ <div class="p-2">+ <div class="text-[10px] uppercase tracking-wide text-muted-foreground">{{ t("explain.actualRows") }}</div>+ <div class="font-mono font-semibold tabular-nums" :class="rowMismatch(selected) ? 'text-amber-600 dark:text-amber-400' : ''">{{ formatPlanRows(selected.actualRows) }}</div>+ </div>+ </div>++ <div v-if="selectedDetails.length" class="min-h-0 flex-1 overflow-auto p-3">+ <div class="mb-2 text-[10px] uppercase tracking-wide text-muted-foreground">{{ t("explain.details") }}</div>+ <div v-for="(detail, index) in selectedDetails" :key="index" class="space-y-1 border-b py-2 first:pt-0 last:border-b-0 last:pb-0">+ <div v-if="detail.label" class="text-[11px] font-medium">{{ detail.label }}</div>+ <div class="select-text whitespace-pre-wrap break-words font-mono text-[11px] leading-5 text-muted-foreground">{{ detail.value }}</div>+ </div>+ </div>+ </template>++ <div v-else class="flex flex-1 items-center justify-center p-3 text-xs text-muted-foreground">{{ t("explain.inspectorEmpty") }}</div>+ </aside>+ </div>+</template>diff --git a/apps/desktop/src/components/explain/ExplainPlanViewer.vue b/apps/desktop/src/components/explain/ExplainPlanViewer.vueindex e12630319c..1bd46b08f5 100644--- a/apps/desktop/src/components/explain/ExplainPlanViewer.vue+++ b/apps/desktop/src/components/explain/ExplainPlanViewer.vue@@ -1,12 +1,14 @@<script setup lang="ts">import { computed, ref, watch } from "vue";import { useI18n } from "vue-i18n";-import { AlertCircle, Braces, GitBranch, Table2, FileText } from "@lucide/vue";+import { AlertCircle, Braces, GitBranch, Table2, FileText, Workflow } from "@lucide/vue";import type { ParsedExplainPlan, ExplainPlanNode } from "@/lib/diagram/explainPlan";import { flattenExplainPlanNodes } from "@/lib/diagram/explainPlan";+import { extractActualRows } from "@/lib/diagram/planCanvas";import { Button } from "@/components/ui/button";import type { QueryResult } from "@/types/database";import ExplainPlanNodeTree from "./ExplainPlanNodeTree.vue";+import ExplainPlanDiagram from "./ExplainPlanDiagram.vue";const props = defineProps<{plan?: ParsedExplainPlan;@@ -19,13 +21,13 @@ const props = defineProps<{}>();const { t } = useI18n();-const activeView = ref<"tree" | "summary" | "raw" | "table">("tree");+const activeView = ref<"canvas" | "tree" | "summary" | "raw" | "table">("canvas");const hasTableView = computed(() => !!props.tableResult || !!props.tableError);watch([hasTableView, () => !!props.tableResult, () => !!props.plan, () => props.loading],([available, hasTableResult, hasPlan, loading]) => {- if (!available && activeView.value === "table") activeView.value = "tree";+ if (!available && activeView.value === "table") activeView.value = "canvas";// Wait for JSON EXPLAIN to finish so regular MySQL still defaults to its visual tree.if (!loading && hasTableResult && !hasPlan) activeView.value = "table";},@@ -53,6 +55,14 @@ const rawContent = computed(() => {const isRawString = computed(() => typeof props.plan?.raw === "string");const rawFormatLabel = computed(() => (props.plan?.databaseType === "sqlserver" ? "XML" : isRawString.value ? "TEXT" : "JSON"));const nodeCount = computed(() => (props.plan ? flattenExplainPlanNodes(props.plan.nodes).length : 0));+// Measured rows exist only when the plan was produced by a mode that ran the query:+// EXPLAIN ANALYZE on Postgres, SET STATISTICS XML on SQL Server.+const measuredRowsLabel = computed(() => {+ const databaseType = props.plan?.databaseType;+ if (databaseType !== "postgres" && databaseType !== "sqlserver") return undefined;+ if (!flattenExplainPlanNodes(props.plan!.nodes).some((node) => extractActualRows(node) !== undefined)) return undefined;+ return databaseType === "sqlserver" ? "ACTUAL" : "ANALYZE";+});function tableCellText(value: unknown): string {if (value === null) return "NULL";@@ -71,8 +81,13 @@ function tableCellText(value: unknown): string {{{ plan?.databaseType.toUpperCase() || "MYSQL" }}<template v-if="plan"> · {{ t("explain.nodeCount", { count: nodeCount }) }}</template></span><span v-if="plan?.databaseType === 'dameng' && isRawString && rawContent.includes('->')" class="ml-1 inline-flex items-center gap-1 rounded bg-green-100 px-1.5 py-0.5 font-semibold text-green-700 dark:bg-green-900/30 dark:text-green-300" style="font-size: 10px">A-TRACE</span>+ <span v-if="measuredRowsLabel" class="ml-1 inline-flex items-center gap-1 rounded bg-green-100 px-1.5 py-0.5 font-semibold text-green-700 dark:bg-green-900/30 dark:text-green-300" style="font-size: 10px">{{ measuredRowsLabel }}</span><span class="flex-1" /><div v-if="plan || hasTableView" class="inline-flex rounded-md border bg-muted/40 p-0.5">+ <Button v-if="plan" size="sm" :variant="activeView === 'canvas' ? 'secondary' : 'ghost'" class="h-6 px-2 text-xs gap-1" @click="activeView = 'canvas'">+ <Workflow class="h-3.5 w-3.5" />+ {{ t("explain.canvas") }}+ </Button><Button v-if="plan" size="sm" :variant="activeView === 'tree' ? 'secondary' : 'ghost'" class="h-6 px-2 text-xs gap-1" @click="activeView = 'tree'"><GitBranch class="h-3.5 w-3.5" />{{ t("explain.tree") }}@@ -136,6 +151,10 @@ function tableCellText(value: unknown): string {{{ t("explain.empty") }}</div>+ <div v-else-if="activeView === 'canvas'" class="flex-1 min-h-0">+ <ExplainPlanDiagram :nodes="plan.nodes" />+ </div>+<div v-else class="flex-1 min-h-0 overflow-auto"><div v-if="activeView === 'tree'" class="mx-auto max-w-5xl space-y-px p-2"><ExplainPlanNodeTree v-for="node in plan.nodes" :key="node.id" :node="node" />diff --git a/apps/desktop/src/components/explain/__tests__/ExplainPlanDiagram.spec.ts b/apps/desktop/src/components/explain/__tests__/ExplainPlanDiagram.spec.tsnew file mode 100644index 0000000000..72ece92f6e--- /dev/null+++ b/apps/desktop/src/components/explain/__tests__/ExplainPlanDiagram.spec.ts@@ -0,0 +1,238 @@+// @vitest-environment happy-dom++import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { createApp, defineComponent, h, nextTick, type App } from "vue";+import i18n from "@/i18n";+import type { ExplainPlanNode } from "@/lib/diagram/explainPlan";+import { parseExplainResult } from "@/lib/diagram/explainPlan";+import type { QueryResult } from "@/types/database";+import ExplainPlanDiagram from "@/components/explain/ExplainPlanDiagram.vue";++function planNode(node: Partial<ExplainPlanNode> & { id: string; nodeType: string }): ExplainPlanNode {+ return { title: node.nodeType, details: [], children: [], ...node };+}++// root(Limit) → Sort → Hash Join → [Seq Scan, Hash → Index Scan]+function postgresPlan(): ExplainPlanNode[] {+ return [+ planNode({+ id: "0",+ nodeType: "Limit",+ cost: "24102.11..24180.37",+ rows: "100",+ children: [+ planNode({+ id: "0.0",+ nodeType: "Sort",+ cost: "24000.00..24102.11",+ rows: "42000",+ details: ["Sort: o.created_at DESC", "Actual Rows: 84000"],+ children: [+ planNode({+ id: "0.0.0",+ nodeType: "Hash Join",+ cost: "0.29..23800.00",+ rows: "42000",+ details: ["Join: Inner"],+ children: [+ planNode({ id: "0.0.0.0", nodeType: "Seq Scan", relation: "orders", cost: "0.00..18000.00", rows: "1200000", details: ["Filter: created_at >= '2026-01-01'"] }),+ planNode({+ id: "0.0.0.1",+ nodeType: "Hash",+ cost: "0.29..1200.00",+ rows: "18500",+ children: [planNode({ id: "0.0.0.1.0", nodeType: "Index Scan", relation: "customers", index: "idx_customers_region", cost: "0.29..1100.00", rows: "18500" })],+ }),+ ],+ }),+ ],+ }),+ ],+ }),+ ];+}++const mountedApps: App[] = [];++beforeEach(() => {+ i18n.global.locale.value = "en";+});++afterEach(() => {+ for (const app of mountedApps.splice(0)) app.unmount();+ document.body.innerHTML = "";+});++async function mountDiagram(nodes: ExplainPlanNode[] = postgresPlan()) {+ const container = document.createElement("div");+ document.body.append(container);+ const app = createApp(+ defineComponent({+ setup() {+ return () => h(ExplainPlanDiagram, { nodes });+ },+ }),+ );+ mountedApps.push(app);+ app.use(i18n);+ app.mount(container);+ await nextTick();+}++function cards(): HTMLElement[] {+ return [...document.querySelectorAll<HTMLElement>("[data-plan-node]")];+}++function cardFor(operator: string): HTMLElement {+ const card = cards().find((element) => element.textContent?.includes(operator));+ if (!card) throw new Error(`No card rendered for ${operator}`);+ return card;+}++function inspectorText(): string {+ return document.querySelector("aside")?.textContent ?? "";+}++describe("ExplainPlanDiagram", () => {+ it("renders one card per plan node and one edge per parent-child link", async () => {+ await mountDiagram();++ expect(cards()).toHaveLength(6);+ expect(document.querySelectorAll("[data-plan-edges] path")).toHaveLength(5);+ expect(document.querySelectorAll("[data-plan-edges] text")).toHaveLength(5);+ });++ it("shows the cost share badge on nodes with a numeric cost", async () => {+ await mountDiagram();++ // Self-cost of the sequential scan is 18000 of the plan's 24180.37 total.+ expect(cardFor("Seq Scan").textContent).toContain("74.4%");+ expect(cardFor("Seq Scan").textContent).toContain("orders");+ expect(cardFor("Index Scan").textContent).toContain("idx_customers_region");+ });++ it("omits the cost badge when the engine reports no cost", async () => {+ await mountDiagram([planNode({ id: "0", nodeType: "Plan", details: ["explain plan text"] })]);++ expect(cards()).toHaveLength(1);+ expect(cards()[0].textContent).not.toContain("%");+ });++ it("flags a node whose actual rows are at least twice the estimate", async () => {+ await mountDiagram();++ expect(cardFor("Sort").textContent).toContain("×2.0");+ expect(cardFor("Index Scan").textContent).not.toContain("×");+ });++ it("preselects the costliest node and follows a click to another card", async () => {+ await mountDiagram();++ expect(inspectorText()).toContain("Seq Scan");+ expect(inspectorText()).toContain("Table scan");+ expect(inspectorText()).toContain("created_at >= '2026-01-01'");++ cardFor("Index Scan").click();+ await nextTick();++ expect(inspectorText()).toContain("Index Scan");+ expect(inspectorText()).toContain("Index scan");+ expect(inspectorText()).toContain("idx_customers_region");+ expect(inspectorText()).not.toContain("Table scan");+ });++ it("flags the mismatch on a plan parsed from real EXPLAIN ANALYZE output", async () => {+ const analyzePlan = [+ {+ Plan: {+ "Node Type": "Sort",+ "Startup Cost": 24000.0,+ "Total Cost": 24102.11,+ "Plan Rows": 42000,+ "Actual Rows": 96000,+ "Actual Loops": 1,+ "Actual Startup Time": 812.44,+ "Actual Total Time": 851.09,+ Plans: [{ "Node Type": "Seq Scan", "Relation Name": "orders", "Startup Cost": 0.0, "Total Cost": 18000.0, "Plan Rows": 1200000, "Actual Rows": 1187423, "Actual Loops": 1 }],+ },+ "Planning Time": 0.482,+ "Execution Time": 862.104,+ },+ ];+ const result: QueryResult = { columns: ["QUERY PLAN"], rows: [[JSON.stringify(analyzePlan)]], affected_rows: 0, execution_time_ms: 1 };++ await mountDiagram(parseExplainResult("postgres", result).nodes);++ // 96000 measured against 42000 estimated is a 2.3x overrun.+ expect(cardFor("Sort").textContent).toContain("×2.3");+ // The scan landed within 1% of its estimate, so it stays unflagged.+ expect(cardFor("Seq Scan").textContent).not.toContain("×");++ // Planning/Execution time live on the root node, which is not the costliest one.+ cardFor("Sort").click();+ await nextTick();+ expect(inspectorText()).toContain("Planning Time");+ expect(inspectorText()).toContain("862.104 ms");+ });++ // Detail strings mirror what parseSqlServerRelOp emits for SET STATISTICS XML;+ // see lib/__tests__/query/sqlserverActualPlan.spec.ts for the parser contract.+ it("does not flag a SQL Server node whose cumulative rows only look like an overrun", async () => {+ await mountDiagram([+ planNode({+ id: "0",+ nodeType: "Nested Loops",+ cost: "1.2",+ rows: "1000",+ details: ["Actual Rows: 1000", "Actual Threads: 3", "Actual Executions: 3"],+ children: [+ planNode({+ id: "1",+ nodeType: "Index Seek",+ relation: "dbo.orders",+ cost: "0.85",+ rows: "10",+ // 1000 cumulative rows over 100 executions is 10 per execution, exactly+ // the estimate. Comparing the raw total would report a bogus x100.+ details: ["Actual Rows: 1000", "Actual Threads: 3", "Actual Executions: 100", "Actual Rows Per Execution: 10"],+ }),+ ],+ }),+ ]);++ expect(cardFor("Index Seek").textContent).not.toContain("×");+ expect(cardFor("Nested Loops").textContent).not.toContain("×");+ });++ it("still flags a SQL Server node that misestimates per execution", async () => {+ await mountDiagram([+ planNode({+ id: "0",+ nodeType: "Index Seek",+ relation: "dbo.orders",+ cost: "0.85",+ rows: "10",+ details: ["Actual Rows: 5000", "Actual Executions: 100", "Actual Rows Per Execution: 50"],+ }),+ ]);++ expect(cardFor("Index Seek").textContent).toContain("×5.0");+ });++ it("keeps the zoom controls inside their range", async () => {+ await mountDiagram();++ const zoomOut = document.querySelector<HTMLButtonElement>('button[aria-label="Zoom out"]');+ const zoomIn = document.querySelector<HTMLButtonElement>('button[aria-label="Zoom in"]');+ expect(zoomOut && zoomIn).toBeTruthy();+ expect(document.body.textContent).toContain("100%");++ for (let step = 0; step < 10; step += 1) zoomOut?.click();+ await nextTick();+ expect(document.body.textContent).toContain("50%");++ for (let step = 0; step < 20; step += 1) zoomIn?.click();+ await nextTick();+ expect(document.body.textContent).toContain("160%");+ });+});diff --git a/apps/desktop/src/components/explain/__tests__/ExplainPlanViewer.spec.ts b/apps/desktop/src/components/explain/__tests__/ExplainPlanViewer.spec.tsindex da41ee61cc..54a5bb702c 100644--- a/apps/desktop/src/components/explain/__tests__/ExplainPlanViewer.spec.ts+++ b/apps/desktop/src/components/explain/__tests__/ExplainPlanViewer.spec.ts@@ -11,8 +11,36 @@ describe("ExplainPlanViewer MySQL fallback", () => {expect(viewerSource).toContain("{ immediate: true },");});- it("keeps the regular tree default when the visual plan arrives", () => {+ it("keeps the canvas default when the visual plan arrives", () => {expect(viewerSource).toContain('if (!loading && hasTableResult && !hasPlan) activeView.value = "table";');- expect(viewerSource).toContain('if (!available && activeView.value === "table") activeView.value = "tree";');+ expect(viewerSource).toContain('if (!available && activeView.value === "table") activeView.value = "canvas";');+ });+});++describe("ExplainPlanViewer canvas view", () => {+ it("opens on the canvas and keeps the other views reachable", () => {+ expect(viewerSource).toContain('const activeView = ref<"canvas" | "tree" | "summary" | "raw" | "table">("canvas");');+ expect(viewerSource).toContain('<ExplainPlanDiagram :nodes="plan.nodes" />');+ expect(viewerSource).toContain('import ExplainPlanDiagram from "./ExplainPlanDiagram.vue";');+ for (const view of ["canvas", "tree", "summary", "raw", "table"]) {+ expect(viewerSource, view).toContain(`activeView = '${view}'`);+ }+ });++ it("derives the measured-rows chip from parsed nodes, not the raw plan text", () => {+ expect(viewerSource).toContain('import { extractActualRows } from "@/lib/diagram/planCanvas";');+ expect(viewerSource).toContain("const measuredRowsLabel = computed(() => {");+ expect(viewerSource).toContain('if (databaseType !== "postgres" && databaseType !== "sqlserver") return undefined;');+ expect(viewerSource).toContain("if (!flattenExplainPlanNodes(props.plan!.nodes).some((node) => extractActualRows(node) !== undefined)) return undefined;");+ expect(viewerSource).toContain('return databaseType === "sqlserver" ? "ACTUAL" : "ANALYZE";');+ expect(viewerSource).toContain('<span v-if="measuredRowsLabel"');+ expect(viewerSource).toContain("{{ measuredRowsLabel }}</span>");+ // The Dameng A-TRACE chip keeps its own raw-text condition.+ expect(viewerSource).toContain("plan?.databaseType === 'dameng' && isRawString && rawContent.includes('->')");+ });++ it("puts the canvas tab first in the view switcher", () => {+ const tabOrder = [...viewerSource.matchAll(/@click="activeView = '(\w+)'"/g)].map((match) => match[1]);+ expect(tabOrder).toEqual(["canvas", "tree", "summary", "raw", "table"]);});});diff --git a/apps/desktop/src/components/layout/EditorToolbar.vue b/apps/desktop/src/components/layout/EditorToolbar.vueindex dc7ecd1fa8..9fc8044903 100644--- a/apps/desktop/src/components/layout/EditorToolbar.vue+++ b/apps/desktop/src/components/layout/EditorToolbar.vue@@ -104,6 +104,18 @@ const supportsTransaction = computed(() => supportsTransactionFeature(props.acticonst hasDefaultDatabaseOption = computed(() => activeDatabaseOptions.value.includes(""));const schemaDatabaseKey = computed(() => props.activeTab.database || (isSingleDb.value ? "_" : ""));const saveTooltip = computed(() => (props.activeTab.objectSource ? t("objects.saveSource") : t("toolbar.saveSql")));+// DM calls it autotrace, Postgres EXPLAIN ANALYZE, SQL Server the actual execution+// plan (SET STATISTICS XML); all three execute the statement.+const supportsExplainAnalyze = computed(() => {+ const dbType = props.activeConnection?.db_type;+ return dbType === "dameng" || dbType === "postgres" || dbType === "sqlserver";+});+const explainAnalyzeTooltip = computed(() => {+ const dbType = props.activeConnection?.db_type;+ if (dbType === "postgres") return t("toolbar.explainAnalyze");+ if (dbType === "sqlserver") return t("toolbar.actualPlan");+ return t("toolbar.autotrace");+});const canSaveSql = computed(() => !!props.activeTab.externalSqlPath || !!props.activeTab.sql.trim());const keywordCaseIsLower = computed(() => props.sqlKeywordCase === "lower");const keywordCaseToggleTooltip = computed(() => (keywordCaseIsLower.value ? t("toolbar.keywordCaseUpper") : t("toolbar.keywordCaseLower")));@@ -242,18 +254,24 @@ async function changeCatalog(selectedCatalog: string) {</TooltipTrigger><TooltipContent>{{ activeTab.isExplaining ? t("toolbar.stopExplain") : t("toolbar.explainPlan") }}</TooltipContent></Tooltip>- <!-- Autotrace toggle (only for DM) -->- <Button- v-if="activeConnection?.db_type === 'dameng'"- variant="ghost"- size="icon"- class="h-6 w-6"- :class="props.explainMode === 'autotrace' ? 'text-green-600 bg-green-100 dark:text-green-300 dark:bg-green-900/30' : 'text-muted-foreground/50'"- :disabled="activeTab.isExecuting"- @click="emit('update:explainMode', props.explainMode === 'autotrace' ? 'explain' : 'autotrace')"- >- <span class="font-bold" style="font-size: 9px">A</span>- </Button>+ <!-- Autotrace (DM) / EXPLAIN ANALYZE (Postgres) / actual plan (SQL Server) toggle -->+ <Tooltip v-if="supportsExplainAnalyze">+ <TooltipTrigger as-child>+ <Button+ variant="ghost"+ size="icon"+ class="h-6 w-6"+ :class="props.explainMode === 'autotrace' ? 'text-green-600 bg-green-100 dark:text-green-300 dark:bg-green-900/30' : 'text-muted-foreground/50'"+ :disabled="activeTab.isExecuting"+ :aria-label="explainAnalyzeTooltip"+ :aria-pressed="props.explainMode === 'autotrace'"+ @click="emit('update:explainMode', props.explainMode === 'autotrace' ? 'explain' : 'autotrace')"+ >+ <span class="font-bold" style="font-size: 9px">A</span>+ </Button>+ </TooltipTrigger>+ <TooltipContent>{{ explainAnalyzeTooltip }}</TooltipContent>+ </Tooltip><!-- Transaction toggle --><Tooltip v-if="supportsTransaction"><TooltipTrigger as-child>diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.tsindex b58aff6e3b..3a829c7f64 100644--- a/apps/desktop/src/i18n/locales/en.ts+++ b/apps/desktop/src/i18n/locales/en.ts@@ -31,6 +31,9 @@ export default {stopQuery: "Stop query",explainPlan: "Explain plan",stopExplain: "Stop explain",+ autotrace: "Autotrace (executes the query)",+ explainAnalyze: "EXPLAIN ANALYZE (executes the query)",+ actualPlan: "Actual execution plan (SET STATISTICS XML)",formatSql: "Format SQL",formatSqlFailed: "Failed to format SQL",formatAutoDetectFailed: "Cannot recognize or format the selected content",@@ -1622,6 +1625,27 @@ export default {cost: "Cost",rows: "Rows",details: "Details",+ canvas: "Canvas",+ costShare: "Cost share",+ estRows: "Est. rows",+ actualRows: "Actual rows",+ zoomIn: "Zoom in",+ zoomOut: "Zoom out",+ zoomFit: "Fit",+ legendHeat: "Heat = % of total cost",+ legendEdge: "Edge width = rows",+ inspectorEmpty: "Select a node",+ catResult: "Result",+ catSort: "Sort",+ catJoin: "Join",+ catTscan: "Table scan",+ catIscan: "Index scan",+ catLookup: "Row lookup",+ catMat: "Materialize",+ catAgg: "Aggregate",+ catXchg: "Parallelism",+ catMod: "Modify",+ catOther: "Other",unsupported: "Explain plan is not supported for this database yet",emptySql: "No SQL to explain",unsafe: "This first version only explains SELECT / WITH / TABLE / VALUES statements",diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.tsindex 4940690aa3..8de78bfe1e 100644--- a/apps/desktop/src/i18n/locales/es.ts+++ b/apps/desktop/src/i18n/locales/es.ts@@ -33,6 +33,9 @@ export default withEnglishFallback({stopQuery: "Detener consulta",explainPlan: "Plan de ejecución",stopExplain: "Detener análisis",+ autotrace: "Autotrace (ejecuta la consulta)",+ explainAnalyze: "EXPLAIN ANALYZE (ejecuta la consulta)",+ actualPlan: "Plan de ejecución real (SET STATISTICS XML)",formatSql: "Formatear SQL",formatSqlFailed: "Error al formatear el SQL",formatAutoDetectFailed: "No se pudo reconocer ni formatear el contenido seleccionado",@@ -1564,6 +1567,27 @@ export default withEnglishFallback({cost: "Costo",rows: "Filas",details: "Detalles",+ canvas: "Canvas",+ costShare: "Costo (%)",+ estRows: "Filas est.",+ actualRows: "Filas reales",+ zoomIn: "Acercar",+ zoomOut: "Alejar",+ zoomFit: "Ajustar",+ legendHeat: "Color = % del costo total",+ legendEdge: "Grosor = filas",+ inspectorEmpty: "Selecciona un nodo",+ catResult: "Resultado",+ catSort: "Ordenación",+ catJoin: "Join",+ catTscan: "Escaneo de tabla",+ catIscan: "Escaneo de índice",+ catLookup: "Búsqueda de fila",+ catMat: "Materialización",+ catAgg: "Agregación",+ catXchg: "Paralelismo",+ catMod: "Modificación",+ catOther: "Otro",unsupported: "El plan de ejecución aún no está disponible para esta base de datos",emptySql: "No hay SQL para analizar",unsafe: "Esta versión solo analiza sentencias SELECT / WITH / TABLE / VALUES",diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.tsindex 0cd2856568..d7f307f509 100644--- a/apps/desktop/src/i18n/locales/it.ts+++ b/apps/desktop/src/i18n/locales/it.ts@@ -32,6 +32,9 @@ export default withEnglishFallback({stopQuery: "Interrompi query",explainPlan: "Spiega piano",stopExplain: "Interrompi spiegazione",+ autotrace: "Autotrace (esegue la query)",+ explainAnalyze: "EXPLAIN ANALYZE (esegue la query)",+ actualPlan: "Piano di esecuzione effettivo (SET STATISTICS XML)",formatSql: "Formatta SQL",formatSqlFailed: "Impossibile formattare SQL",formatAutoDetectFailed: "Impossibile riconoscere o formattare il contenuto selezionato",@@ -1562,6 +1565,27 @@ export default withEnglishFallback({cost: "Costo",rows: "Righe",details: "Dettagli",+ canvas: "Canvas",+ costShare: "Costo (%)",+ estRows: "Righe stim.",+ actualRows: "Righe effettive",+ zoomIn: "Ingrandisci",+ zoomOut: "Riduci",+ zoomFit: "Adatta",+ legendHeat: "Colore = % del costo totale",+ legendEdge: "Spessore = righe",+ inspectorEmpty: "Seleziona un nodo",+ catResult: "Risultato",+ catSort: "Ordinamento",+ catJoin: "Join",+ catTscan: "Scansione tabella",+ catIscan: "Scansione indice",+ catLookup: "Lookup riga",+ catMat: "Materializzazione",+ catAgg: "Aggregazione",+ catXchg: "Parallelismo",+ catMod: "Modifica",+ catOther: "Altro",unsupported: "Il piano di spiegazione non è ancora supportato per questo database",emptySql: "Nessun SQL da spiegare",unsafe: "Questa prima versione spiega solo istruzioni SELECT / WITH / TABLE / VALUES",diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.tsindex 0243f95bea..22af552d9a 100644--- a/apps/desktop/src/i18n/locales/ja.ts+++ b/apps/desktop/src/i18n/locales/ja.ts@@ -33,6 +33,9 @@ export default withEnglishFallback({stopQuery: "クエリを停止",explainPlan: "実行計画を表示",stopExplain: "実行計画の表示を停止",+ autotrace: "オートトレース (クエリを実行します)",+ explainAnalyze: "EXPLAIN ANALYZE (クエリを実行します)",+ actualPlan: "実際の実行プラン (SET STATISTICS XML)",formatSql: "SQLをフォーマット",formatSqlFailed: "SQLのフォーマットに失敗しました",formatAutoDetectFailed: "選択内容を認識またはフォーマットできません",@@ -1589,6 +1592,27 @@ export default withEnglishFallback({cost: "コスト",rows: "行数",details: "詳細",+ canvas: "キャンバス",+ costShare: "コスト比率",+ estRows: "推定行数",+ actualRows: "実際の行数",+ zoomIn: "拡大",+ zoomOut: "縮小",+ zoomFit: "全体表示",+ legendHeat: "色 = 総コストに占める割合",+ legendEdge: "線の太さ = 行数",+ inspectorEmpty: "ノードを選択してください",+ catResult: "結果",+ catSort: "ソート",+ catJoin: "結合",+ catTscan: "テーブルスキャン",+ catIscan: "インデックススキャン",+ catLookup: "行ルックアップ",+ catMat: "マテリアライズ",+ catAgg: "集約",+ catXchg: "並列処理",+ catMod: "更新",+ catOther: "その他",unsupported: "このデータベースではまだ実行計画をサポートしていません",emptySql: "実行計画を表示するSQLがありません",unsafe: "この最初のバージョンではSELECT / WITH / TABLE / VALUES文のみの実行計画を表示します",diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.tsindex 3f54ab7b36..f035d3c56c 100644--- a/apps/desktop/src/i18n/locales/ko.ts+++ b/apps/desktop/src/i18n/locales/ko.ts@@ -33,6 +33,9 @@ export default withEnglishFallback({stopQuery: "쿼리 중지",explainPlan: "실행 계획",stopExplain: "실행 계획 중지",+ autotrace: "자동 추적 (쿼리를 실행합니다)",+ explainAnalyze: "EXPLAIN ANALYZE (쿼리를 실행합니다)",+ actualPlan: "실제 실행 계획 (SET STATISTICS XML)",formatSql: "SQL 정렬",formatSqlFailed: "SQL 정렬에 실패했습니다",formatAutoDetectFailed: "선택한 내용을 인식하거나 포맷할 수 없습니다",@@ -1590,6 +1593,27 @@ export default withEnglishFallback({cost: "비용",rows: "행",details: "상세",+ canvas: "캔버스",+ costShare: "비용 비율",+ estRows: "예상 행",+ actualRows: "실제 행",+ zoomIn: "확대",+ zoomOut: "축소",+ zoomFit: "맞춤",+ legendHeat: "색상 = 전체 비용 대비 비율",+ legendEdge: "선 굵기 = 행 수",+ inspectorEmpty: "노드를 선택하세요",+ catResult: "결과",+ catSort: "정렬",+ catJoin: "조인",+ catTscan: "테이블 스캔",+ catIscan: "인덱스 스캔",+ catLookup: "행 조회",+ catMat: "구체화",+ catAgg: "집계",+ catXchg: "병렬 처리",+ catMod: "변경",+ catOther: "기타",unsupported: "이 데이터베이스에서는 아직 실행 계획을 지원하지 않습니다",emptySql: "실행 계획을 볼 SQL이 없습니다",unsafe: "이 첫 번째 버전은 SELECT / WITH / TABLE / VALUES 구문만 지원합니다",diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.tsindex 32717933e6..88e3b5a125 100644--- a/apps/desktop/src/i18n/locales/pt-BR.ts+++ b/apps/desktop/src/i18n/locales/pt-BR.ts@@ -33,6 +33,9 @@ export default withEnglishFallback({stopQuery: "Parar consulta",explainPlan: "Explicar plano",stopExplain: "Parar explicação",+ autotrace: "Autotrace (executa a query)",+ explainAnalyze: "EXPLAIN ANALYZE (executa a query)",+ actualPlan: "Plano de execução real (SET STATISTICS XML)",formatSql: "Formatar SQL",formatSqlFailed: "Falha ao formatar SQL",formatAutoDetectFailed: "Não foi possível reconhecer ou formatar o conteúdo selecionado",@@ -1564,6 +1567,27 @@ export default withEnglishFallback({cost: "Custo",rows: "Linhas",details: "Detalhes",+ canvas: "Canvas",+ costShare: "Custo (%)",+ estRows: "Linhas est.",+ actualRows: "Linhas reais",+ zoomIn: "Aumentar zoom",+ zoomOut: "Diminuir zoom",+ zoomFit: "Ajustar",+ legendHeat: "Cor = % do custo total",+ legendEdge: "Espessura = linhas",+ inspectorEmpty: "Selecione um nó",+ catResult: "Resultado",+ catSort: "Sort",+ catJoin: "Join",+ catTscan: "Table scan",+ catIscan: "Index scan",+ catLookup: "Row lookup",+ catMat: "Materialização",+ catAgg: "Agregação",+ catXchg: "Paralelismo",+ catMod: "Modificação",+ catOther: "Outro",unsupported: "O plano de execução ainda não é suportado para este banco de dados",emptySql: "Nenhum SQL para explicar",unsafe: "Esta primeira versão explica apenas instruções SELECT / WITH / TABLE / VALUES",diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.tsindex cb5ff19cb5..7b755bf6f8 100644--- a/apps/desktop/src/i18n/locales/zh-CN.ts+++ b/apps/desktop/src/i18n/locales/zh-CN.ts@@ -33,6 +33,9 @@ export default withEnglishFallback({stopQuery: "停止执行",explainPlan: "执行计划",stopExplain: "停止执行计划",+ autotrace: "Autotrace (会执行查询)",+ explainAnalyze: "EXPLAIN ANALYZE (会执行查询)",+ actualPlan: "实际执行计划 (SET STATISTICS XML)",formatSql: "格式化 SQL",formatSqlFailed: "SQL 格式化失败",formatAutoDetectFailed: "无法识别或格式化所选内容",@@ -1623,6 +1626,27 @@ export default withEnglishFallback({cost: "Cost",rows: "行数",details: "详情",+ canvas: "画布",+ costShare: "成本占比",+ estRows: "预估行数",+ actualRows: "实际行数",+ zoomIn: "放大",+ zoomOut: "缩小",+ zoomFit: "适应窗口",+ legendHeat: "颜色 = 占总成本比例",+ legendEdge: "线宽 = 行数",+ inspectorEmpty: "请选择一个节点",+ catResult: "结果",+ catSort: "排序",+ catJoin: "连接",+ catTscan: "全表扫描",+ catIscan: "索引扫描",+ catLookup: "行查找",+ catMat: "物化",+ catAgg: "聚合",+ catXchg: "并行",+ catMod: "写入",+ catOther: "其他",unsupported: "当前数据库暂不支持执行计划",emptySql: "当前没有可分析的 SQL",unsafe: "第一版执行计划仅支持 SELECT / WITH / TABLE / VALUES",diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.tsindex 5aa56eabf1..e71fba0b11 100644--- a/apps/desktop/src/i18n/locales/zh-TW.ts+++ b/apps/desktop/src/i18n/locales/zh-TW.ts@@ -33,6 +33,9 @@ export default withEnglishFallback({stopQuery: "停止執行",explainPlan: "執行計畫",stopExplain: "停止執行計畫",+ autotrace: "Autotrace (會執行查詢)",+ explainAnalyze: "EXPLAIN ANALYZE (會執行查詢)",+ actualPlan: "實際執行計畫 (SET STATISTICS XML)",formatSql: "格式化 SQL",formatSqlFailed: "SQL 格式化失敗",formatAutoDetectFailed: "無法識別或格式化所選內容",@@ -1563,6 +1566,27 @@ export default withEnglishFallback({cost: "成本",rows: "筆數",details: "詳情",+ canvas: "畫布",+ costShare: "成本佔比",+ estRows: "預估筆數",+ actualRows: "實際筆數",+ zoomIn: "放大",+ zoomOut: "縮小",+ zoomFit: "符合視窗",+ legendHeat: "顏色 = 佔總成本比例",+ legendEdge: "線寬 = 筆數",+ inspectorEmpty: "請選擇一個節點",+ catResult: "結果",+ catSort: "排序",+ catJoin: "連結",+ catTscan: "全表掃描",+ catIscan: "索引掃描",+ catLookup: "資料列查找",+ catMat: "具體化",+ catAgg: "彙總",+ catXchg: "平行處理",+ catMod: "寫入",+ catOther: "其他",unsupported: "目前資料庫暫不支援執行計畫",emptySql: "目前沒有可分析的 SQL",unsafe: "第一版執行計畫僅支援 SELECT / WITH / TABLE / VALUES",diff --git a/apps/desktop/src/lib/__tests__/query/postgresExplainPlan.spec.ts b/apps/desktop/src/lib/__tests__/query/postgresExplainPlan.spec.tsnew file mode 100644index 0000000000..2bc38e756d--- /dev/null+++ b/apps/desktop/src/lib/__tests__/query/postgresExplainPlan.spec.ts@@ -0,0 +1,141 @@+import { describe, expect, it } from "vitest";+import { flattenExplainPlanNodes, parseExplainResult } from "@/lib/diagram/explainPlan";+import { extractActualRows } from "@/lib/diagram/planCanvas";+import type { QueryResult } from "@/types/database";++function explainResult(plan: unknown): QueryResult {+ return { columns: ["QUERY PLAN"], rows: [[JSON.stringify(plan)]], affected_rows: 0, execution_time_ms: 1 };+}++const ANALYZE_PLAN = [+ {+ Plan: {+ "Node Type": "Sort",+ "Startup Cost": 24000.0,+ "Total Cost": 24102.11,+ "Plan Rows": 42000,+ "Plan Width": 96,+ "Actual Startup Time": 812.44,+ "Actual Total Time": 851.09,+ "Actual Rows": 84000,+ "Actual Loops": 1,+ "Sort Key": ["o.created_at DESC"],+ Plans: [+ {+ "Node Type": "Hash Join",+ "Join Type": "Inner",+ "Startup Cost": 0.29,+ "Total Cost": 23800.0,+ "Plan Rows": 42000,+ "Actual Startup Time": 12.5,+ "Actual Total Time": 700.25,+ "Actual Rows": 84000,+ "Actual Loops": 1,+ Plans: [+ {+ "Node Type": "Seq Scan",+ "Relation Name": "orders",+ "Startup Cost": 0.0,+ "Total Cost": 18000.0,+ "Plan Rows": 1200000,+ Filter: "(created_at >= '2026-01-01'::date)",+ "Actual Startup Time": 0.011,+ "Actual Total Time": 402.9,+ "Actual Rows": 1187423,+ "Actual Loops": 1,+ },+ {+ "Node Type": "Index Scan",+ "Relation Name": "customers",+ "Index Name": "idx_customers_region",+ "Startup Cost": 0.29,+ "Total Cost": 1100.0,+ "Plan Rows": 18500,+ "Actual Startup Time": 0.02,+ "Actual Total Time": 0.31,+ "Actual Rows": 5,+ "Actual Loops": 3700,+ },+ ],+ },+ ],+ },+ "Planning Time": 0.482,+ "Execution Time": 862.104,+ },+];++const PLAIN_PLAN = [+ {+ Plan: {+ "Node Type": "Seq Scan",+ "Relation Name": "orders",+ "Startup Cost": 0.0,+ "Total Cost": 18000.0,+ "Plan Rows": 1200000,+ "Plan Width": 96,+ },+ },+];++describe("PostgreSQL EXPLAIN ANALYZE parsing", () => {+ const parsed = parseExplainResult("postgres", explainResult(ANALYZE_PLAN));+ const nodes = flattenExplainPlanNodes(parsed.nodes);+ const byType = new Map(nodes.map((node) => [node.nodeType, node]));++ it("keeps the existing tree shape and cost/rows fields", () => {+ expect(parsed.databaseType).toBe("postgres");+ expect(nodes).toHaveLength(4);+ expect(byType.get("Sort")?.cost).toBe("24000..24102.11");+ expect(byType.get("Seq Scan")?.relation).toBe("orders");+ expect(byType.get("Index Scan")?.index).toBe("idx_customers_region");+ });++ it("records measured rows in the shared 'Actual Rows' detail convention", () => {+ expect(byType.get("Sort")?.details).toContain("Actual Rows: 84000");+ expect(byType.get("Seq Scan")?.details).toContain("Actual Rows: 1187423");+ expect(byType.get("Index Scan")?.details).toContain("Actual Rows: 5");+ });++ it("reports loops only when the node ran more than once", () => {+ expect(byType.get("Index Scan")?.details).toContain("Actual Loops: 3700");+ expect(byType.get("Sort")?.details.some((detail) => detail.startsWith("Actual Loops"))).toBe(false);+ expect(byType.get("Seq Scan")?.details.some((detail) => detail.startsWith("Actual Loops"))).toBe(false);+ });++ it("records the per-node timing range", () => {+ expect(byType.get("Sort")?.details).toContain("Actual Time: 812.44..851.09 ms");+ expect(byType.get("Seq Scan")?.details).toContain("Actual Time: 0.011..402.9 ms");+ });++ it("puts planning and execution time on the root node only", () => {+ expect(parsed.nodes[0].details).toContain("Planning Time: 0.482 ms");+ expect(parsed.nodes[0].details).toContain("Execution Time: 862.104 ms");+ expect(byType.get("Seq Scan")?.details.some((detail) => detail.startsWith("Execution Time"))).toBe(false);+ });++ it("keeps the engine-native details ahead of the measured ones", () => {+ expect(byType.get("Hash Join")?.details[0]).toBe("Join: Inner");+ expect(byType.get("Seq Scan")?.details[0]).toBe("Filter: (created_at >= '2026-01-01'::date)");+ });++ it("feeds the plan canvas mismatch detection", () => {+ const sort = byType.get("Sort")!;+ expect(extractActualRows(sort)).toBe(84000);+ // 84000 measured against 42000 estimated is exactly the 2x mismatch threshold.+ expect(extractActualRows(sort)! / Number(sort.rows)).toBe(2);+ expect(extractActualRows(byType.get("Index Scan")!)).toBe(5);+ });+});++describe("PostgreSQL plain EXPLAIN parsing", () => {+ it("adds no ANALYZE details when the plan has no measured fields", () => {+ const parsed = parseExplainResult("postgres", explainResult(PLAIN_PLAN));+ const [root] = parsed.nodes;++ expect(root.details).toEqual([]);+ expect(extractActualRows(root)).toBeUndefined();+ expect(root.cost).toBe("0..18000");+ expect(root.rows).toBe("1200000");+ });+});diff --git a/apps/desktop/src/lib/__tests__/query/sqlserverActualPlan.spec.ts b/apps/desktop/src/lib/__tests__/query/sqlserverActualPlan.spec.tsnew file mode 100644index 0000000000..004d0e2051--- /dev/null+++ b/apps/desktop/src/lib/__tests__/query/sqlserverActualPlan.spec.ts@@ -0,0 +1,154 @@+import { DOMParser } from "@xmldom/xmldom";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { flattenExplainPlanNodes, parseExplainResult, sqlServerExplainResult } from "@/lib/diagram/explainPlan";+import { extractActualRows } from "@/lib/diagram/planCanvas";+import type { QueryResult } from "@/types/database";++// SET STATISTICS XML output: the SHOWPLAN_XML schema plus <RunTimeInformation>.+// Gather Streams and its subtree run on 3 worker threads; the nested loop inner+// seek runs 100 times in total and returns 10 rows per execution against a+// 10-row estimate, so its cumulative 1000 rows are a 100x apparent overrun.+const STATISTICS_XML = `<ShowPlanXML xmlns="http://schemas.microsoft.com/sqlserver/2004/07/showplan">+ <BatchSequence><Batch><Statements><StmtSimple StatementText="SELECT * FROM dbo.customers c JOIN dbo.orders o ON o.customer_id = c.id">+ <QueryPlan DegreeOfParallelism="3">+ <RelOp NodeId="0" PhysicalOp="Parallelism" LogicalOp="Gather Streams" EstimateRows="1000" EstimatedTotalSubtreeCost="1.24" AvgRowSize="24">+ <RunTimeInformation>+ <RunTimeCountersPerThread Thread="1" ActualRows="400" ActualExecutions="1" ActualElapsedms="118" ActualCPUms="40" />+ <RunTimeCountersPerThread Thread="2" ActualRows="350" ActualExecutions="1" ActualElapsedms="121" ActualCPUms="38" />+ <RunTimeCountersPerThread Thread="3" ActualRows="250" ActualExecutions="1" ActualElapsedms="119" ActualCPUms="36" />+ </RunTimeInformation>+ <Parallelism>+ <RelOp NodeId="1" PhysicalOp="Nested Loops" LogicalOp="Inner Join" EstimateRows="1000" EstimatedTotalSubtreeCost="1.2" AvgRowSize="24">+ <RunTimeInformation>+ <RunTimeCountersPerThread Thread="1" ActualRows="400" ActualExecutions="1" ActualElapsedms="110" ActualCPUms="30" />+ <RunTimeCountersPerThread Thread="2" ActualRows="350" ActualExecutions="1" ActualElapsedms="112" ActualCPUms="28" />+ <RunTimeCountersPerThread Thread="3" ActualRows="250" ActualExecutions="1" ActualElapsedms="109" ActualCPUms="26" />+ </RunTimeInformation>+ <NestedLoops>+ <RelOp NodeId="2" PhysicalOp="Index Scan" LogicalOp="Index Scan" EstimateRows="100" EstimatedTotalSubtreeCost="0.3" AvgRowSize="16">+ <RunTimeInformation>+ <RunTimeCountersPerThread Thread="1" ActualRows="40" ActualExecutions="1" ActualElapsedms="8" ActualCPUms="3" />+ <RunTimeCountersPerThread Thread="2" ActualRows="35" ActualExecutions="1" ActualElapsedms="9" ActualCPUms="4" />+ <RunTimeCountersPerThread Thread="3" ActualRows="25" ActualExecutions="1" ActualElapsedms="7" ActualCPUms="2" />+ </RunTimeInformation>+ <IndexScan>+ <Object Database="[shop]" Schema="[dbo]" Table="[customers]" Index="[ix_customers_region]" />+ </IndexScan>+ </RelOp>+ <RelOp NodeId="3" PhysicalOp="Index Seek" LogicalOp="Index Seek" EstimateRows="10" EstimatedRowsRead="12" EstimatedTotalSubtreeCost="0.85" AvgRowSize="20">+ <RunTimeInformation>+ <RunTimeCountersPerThread Thread="1" ActualRows="400" ActualRowsRead="420" ActualExecutions="40" ActualElapsedms="95" ActualCPUms="24" />+ <RunTimeCountersPerThread Thread="2" ActualRows="350" ActualRowsRead="360" ActualExecutions="35" ActualElapsedms="97" ActualCPUms="22" />+ <RunTimeCountersPerThread Thread="3" ActualRows="250" ActualRowsRead="260" ActualExecutions="25" ActualElapsedms="93" ActualCPUms="20" />+ </RunTimeInformation>+ <IndexScan>+ <Object Database="[shop]" Schema="[dbo]" Table="[orders]" Index="[ix_orders_customer]" />+ <SeekPredicates><SeekPredicateNew><SeekKeys><Prefix>+ <RangeExpressions><ScalarOperator ScalarString="[orders].[customer_id]=[customers].[id]" /></RangeExpressions>+ </Prefix></SeekKeys></SeekPredicateNew></SeekPredicates>+ </IndexScan>+ </RelOp>+ </NestedLoops>+ </RelOp>+ </Parallelism>+ </RelOp>+ </QueryPlan>+ </StmtSimple></Statements></Batch></BatchSequence>+</ShowPlanXML>`;++// A serial statement: one thread, one execution, no normalization to apply.+const SERIAL_STATISTICS_XML = `<ShowPlanXML xmlns="http://schemas.microsoft.com/sqlserver/2004/07/showplan">+ <BatchSequence><Batch><Statements><StmtSimple><QueryPlan>+ <RelOp NodeId="0" PhysicalOp="Clustered Index Scan" LogicalOp="Clustered Index Scan" EstimateRows="500" EstimatedTotalSubtreeCost="0.12" AvgRowSize="18">+ <RunTimeInformation>+ <RunTimeCountersPerThread Thread="0" ActualRows="1200" ActualRowsRead="1200" ActualExecutions="1" ActualElapsedms="14" ActualCPUms="12" />+ </RunTimeInformation>+ <IndexScan><Object Database="[shop]" Schema="[dbo]" Table="[orders]" Index="[pk_orders]" /></IndexScan>+ </RelOp>+ </QueryPlan></StmtSimple></Statements></Batch></BatchSequence>+</ShowPlanXML>`;++function result(columns: string[], rows: unknown[][]): QueryResult {+ return { columns, rows, affected_rows: 0, execution_time_ms: 1 };+}++describe("SQL Server actual execution plan", () => {+ beforeEach(() => {+ vi.stubGlobal("DOMParser", DOMParser);+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ });++ // Parsed lazily: the DOMParser stub only exists once beforeEach has run.+ const parse = (xml: string) => flattenExplainPlanNodes(parseExplainResult("sqlserver", result(["Microsoft SQL Server 2005 XML Showplan"], [[xml]])).nodes);+ const node = (id: string) => parse(STATISTICS_XML).find((candidate) => candidate.id === id)!;+ const gatherStreams = () => node("0");+ const innerSeek = () => node("3");++ it("keeps the operator hierarchy the estimated plan already produced", () => {+ expect(parse(STATISTICS_XML).map((relOp) => relOp.nodeType)).toEqual(["Parallelism", "Nested Loops", "Index Scan", "Index Seek"]);+ expect(innerSeek()).toMatchObject({ relation: "dbo.orders", index: "ix_orders_customer", rows: "10", cost: "0.85" });+ expect(innerSeek().details).toContain("Expression: [orders].[customer_id]=[customers].[id]");+ });++ it("sums measured rows across every worker thread", () => {+ expect(gatherStreams().details).toContain("Actual Rows: 1000");+ expect(node("2").details).toContain("Actual Rows: 100");+ expect(innerSeek().details).toContain("Actual Rows: 1000");+ });++ it("reports the slowest thread as elapsed time and the summed CPU work", () => {+ expect(gatherStreams().details).toContain("Actual Time: 121 ms");+ expect(gatherStreams().details).toContain("Actual CPU: 114 ms");+ expect(innerSeek().details).toContain("Actual Time: 97 ms");+ expect(innerSeek().details).toContain("Actual CPU: 66 ms");+ });++ it("normalizes the repeated inner side of the nested loop to a per-execution figure", () => {+ expect(innerSeek().details).toContain("Actual Threads: 3");+ expect(innerSeek().details).toContain("Actual Executions: 100");+ expect(innerSeek().details).toContain("Actual Rows Per Execution: 10");+ // The estimate is per execution, so this is what a mismatch check must read.+ expect(extractActualRows(innerSeek())).toBe(10);+ expect(Number(innerSeek().rows)).toBe(10);+ });++ it("leaves parallel operators unnormalized, one execution per thread is still one execution", () => {+ for (const id of ["0", "1", "2"]) {+ expect(node(id).details.some((detail) => detail.startsWith("Actual Rows Per Execution"))).toBe(false);+ }+ expect(gatherStreams().details).toContain("Actual Threads: 3");+ expect(gatherStreams().details).toContain("Actual Executions: 3");+ expect(extractActualRows(gatherStreams())).toBe(1000);+ expect(extractActualRows(node("2"))).toBe(100);+ });++ it("keeps a serial single-execution operator on the plain measured total", () => {+ const [root] = parseExplainResult("sqlserver", result(["Microsoft SQL Server 2005 XML Showplan"], [[SERIAL_STATISTICS_XML]])).nodes;++ expect(root.details).toContain("Actual Rows: 1200");+ expect(root.details.some((detail) => detail.startsWith("Actual Threads"))).toBe(false);+ expect(root.details.some((detail) => detail.startsWith("Actual Executions"))).toBe(false);+ expect(root.details.some((detail) => detail.startsWith("Actual Rows Per Execution"))).toBe(false);+ expect(extractActualRows(root)).toBe(1200);+ });++ it("adds no measured details to an estimated SHOWPLAN plan", () => {+ const estimated = STATISTICS_XML.replaceAll(/<RunTimeInformation>[\s\S]*?<\/RunTimeInformation>/g, "");+ const parsed = parseExplainResult("sqlserver", result(["Microsoft SQL Server 2005 XML Showplan"], [[estimated]]));++ for (const node of flattenExplainPlanNodes(parsed.nodes)) {+ expect(node.details.some((detail) => detail.startsWith("Actual"))).toBe(false);+ expect(extractActualRows(node)).toBeUndefined();+ }+ });++ it("finds the plan when STATISTICS XML returns the query result set first", () => {+ const rowsResult = result(["id", "total"], [[1, "12.50"]]);+ const planResult = result(["Microsoft SQL Server 2005 XML Showplan"], [[STATISTICS_XML]]);++ expect(sqlServerExplainResult([rowsResult, planResult])).toEqual({ result: planResult });+ });+});diff --git a/apps/desktop/src/lib/backend/http.ts b/apps/desktop/src/lib/backend/http.tsindex 68bf690190..64fa30d32d 100644--- a/apps/desktop/src/lib/backend/http.ts+++ b/apps/desktop/src/lib/backend/http.ts@@ -843,7 +843,7 @@ export async function executeQuery(resultSessionId?: string;clientSessionId?: string;timeoutSecs?: number;- executionMode?: "simple";+ executionMode?: "simple" | "postgres_read_only_transaction";},): Promise<QueryResult> {return post("/api/query/execute", {diff --git a/apps/desktop/src/lib/backend/tauri.ts b/apps/desktop/src/lib/backend/tauri.tsindex fd8691d5dc..61334bd448 100644--- a/apps/desktop/src/lib/backend/tauri.ts+++ b/apps/desktop/src/lib/backend/tauri.ts@@ -321,6 +321,8 @@ export interface BuildExplainSqlOptions {sql: string;/** MySQL can return either the existing JSON plan or its native tabular plan. */format?: "json" | "standard";+ /** PostgreSQL only: run the statement so the plan carries measured rows and timings. */+ analyze?: boolean;}export interface ExplainSqlBuildResult {@@ -1058,7 +1060,7 @@ export async function executeQuery(resultSessionId?: string;clientSessionId?: string;timeoutSecs?: number;- executionMode?: "simple";+ executionMode?: "simple" | "postgres_read_only_transaction";},): Promise<QueryResult> {try {diff --git a/apps/desktop/src/lib/diagram/__tests__/planCanvas.spec.ts b/apps/desktop/src/lib/diagram/__tests__/planCanvas.spec.tsnew file mode 100644index 0000000000..7d0f24921a--- /dev/null+++ b/apps/desktop/src/lib/diagram/__tests__/planCanvas.spec.ts@@ -0,0 +1,245 @@+import { describe, expect, it } from "vitest";+import type { ExplainPlanNode } from "@/lib/diagram/explainPlan";+import { buildPlanCanvas, categorizePlanNode, edgeStrokeWidth, extractActualRows, formatPlanRows, heatLevel, parsePlanNumber, PLAN_CANVAS_NODE_H, PLAN_CANVAS_NODE_W, PLAN_CANVAS_PAD } from "@/lib/diagram/planCanvas";++function planNode(node: Partial<ExplainPlanNode> & { id: string; nodeType: string }): ExplainPlanNode {+ return { title: node.nodeType, details: [], children: [], ...node };+}++describe("categorizePlanNode", () => {+ const expectations: Array<[string, string[]]> = [+ ["tscan", ["Seq Scan", "ALL", "Full Table Scan", "Table Scan", "Clustered Index Scan", "TABLE ACCESS FULL", "CSCN2"]],+ ["iscan", ["Index Scan", "Index Only Scan", "Bitmap Index Scan", "Bitmap Heap Scan", "Index Seek", "INDEX RANGE SCAN", "INDEX UNIQUE SCAN", "INDEX FULL SCAN", "range", "ref", "SSEK2", "CSEK2", "Clustered Index Seek"]],+ ["lookup", ["Key Lookup", "RID Lookup", "TABLE ACCESS BY INDEX ROWID", "eq_ref", "Unique Key Lookup"]],+ ["join", ["Nested Loop", "Nested Loops", "Hash Join", "Merge Join", "Hash Match", "HASH JOIN", "NESTED LOOPS", "HASH2", "NEST LOOP", "hash join"]],+ ["sort", ["Sort", "Incremental Sort", "filesort", "Filesort", "ordering_operation", "SORT ORDER BY"]],+ ["agg", ["Aggregate", "HashAggregate", "GroupAggregate", "Partial Aggregate", "Stream Aggregate", "grouping_operation", "HASH GROUP BY", "SORT AGGREGATE", "HAGR2", "SAGR2"]],+ ["mat", ["Hash", "Materialize", "CTE Scan", "Table Spool", "Index Spool", "materialized_from_subquery", "TEMP TABLE TRANSFORMATION"]],+ ["xchg", ["Gather", "Gather Merge", "Parallelism", "PX SEND", "PX RECEIVE", "Exchange"]],+ ["mod", ["Insert", "Update", "Delete", "Merge", "Table Insert", "Clustered Index Update"]],+ ["result", ["Result", "Limit", "SELECT", "SELECT STATEMENT", "query_block", "NSET2", "PRJT2", "union_result"]],+ ];++ for (const [category, operators] of expectations) {+ it(`maps every engine's ${category} operators`, () => {+ for (const operator of operators) {+ expect(categorizePlanNode(operator), operator).toBe(category);+ }+ });+ }++ it("falls back to other for unknown operators", () => {+ expect(categorizePlanNode("Compute Scalar")).toBe("other");+ expect(categorizePlanNode("")).toBe("other");+ expect(categorizePlanNode(" ")).toBe("other");+ });++ it("resolves the operators whose names overlap across categories", () => {+ expect(categorizePlanNode("Merge Join")).toBe("join");+ expect(categorizePlanNode("Merge")).toBe("mod");+ expect(categorizePlanNode("Merge Append")).toBe("other");+ expect(categorizePlanNode("Gather Merge")).toBe("xchg");+ expect(categorizePlanNode("Clustered Index Scan")).toBe("tscan");+ expect(categorizePlanNode("Index Scan")).toBe("iscan");+ expect(categorizePlanNode("Index Spool")).toBe("mat");+ expect(categorizePlanNode("eq_ref")).toBe("lookup");+ expect(categorizePlanNode("ref")).toBe("iscan");+ expect(categorizePlanNode("SORT AGGREGATE")).toBe("agg");+ expect(categorizePlanNode("SORT ORDER BY")).toBe("sort");+ expect(categorizePlanNode("HashAggregate")).toBe("agg");+ expect(categorizePlanNode("Hash")).toBe("mat");+ expect(categorizePlanNode("TABLE ACCESS FULL")).toBe("tscan");+ expect(categorizePlanNode("TABLE ACCESS BY INDEX ROWID")).toBe("lookup");+ });+});++describe("parsePlanNumber", () => {+ it("reads plain, grouped and ranged numbers", () => {+ expect(parsePlanNumber("12.34")).toBe(12.34);+ expect(parsePlanNumber("1,234")).toBe(1234);+ expect(parsePlanNumber("42000")).toBe(42000);+ expect(parsePlanNumber("0.29..1830.12")).toBe(1830.12);+ });++ it("applies Oracle-style magnitude suffixes", () => {+ expect(parsePlanNumber("1200K")).toBe(1_200_000);+ expect(parsePlanNumber("96M")).toBe(96_000_000);+ expect(parsePlanNumber("4032K")).toBe(4_032_000);+ });++ it("ignores trailing engine annotations", () => {+ expect(parsePlanNumber("5842 (1)")).toBe(5842);+ });++ it("returns undefined for missing or non-numeric values", () => {+ expect(parsePlanNumber(undefined)).toBeUndefined();+ expect(parsePlanNumber("")).toBeUndefined();+ expect(parsePlanNumber(" ")).toBeUndefined();+ expect(parsePlanNumber("N/A")).toBeUndefined();+ expect(parsePlanNumber("Good Enough Plan Found")).toBeUndefined();+ });+});++describe("extractActualRows", () => {+ it("reads the actual row count out of the detail list", () => {+ expect(extractActualRows(planNode({ id: "1", nodeType: "Sort", details: ["Sort: a", "Actual Rows: 83,911"] }))).toBe(83911);+ expect(extractActualRows(planNode({ id: "1", nodeType: "Sort", details: ["Sort: a"] }))).toBeUndefined();+ });+});++// root(Limit) → Sort → Hash Join → [Seq Scan, Hash → Index Scan]+function postgresPlan(): ExplainPlanNode[] {+ return [+ planNode({+ id: "0",+ nodeType: "Limit",+ cost: "24102.11..24180.37",+ rows: "100",+ children: [+ planNode({+ id: "0.0",+ nodeType: "Sort",+ cost: "24000.00..24102.11",+ rows: "42000",+ details: ["Sort: o.created_at DESC", "Actual Rows: 83911"],+ children: [+ planNode({+ id: "0.0.0",+ nodeType: "Hash Join",+ cost: "0.29..23800.00",+ rows: "42000",+ children: [+ planNode({ id: "0.0.0.0", nodeType: "Seq Scan", relation: "orders", cost: "0.00..18000.00", rows: "1200000" }),+ planNode({+ id: "0.0.0.1",+ nodeType: "Hash",+ cost: "0.29..1200.00",+ rows: "18500",+ children: [planNode({ id: "0.0.0.1.0", nodeType: "Index Scan", relation: "customers", index: "idx_customers_region", cost: "0.29..1100.00", rows: "18500" })],+ }),+ ],+ }),+ ],+ }),+ ],+ }),+ ];+}++describe("buildPlanCanvas", () => {+ const layout = buildPlanCanvas(postgresPlan());++ it("places every node once and connects each non-root to its parent", () => {+ expect(layout.nodes).toHaveLength(6);+ expect(layout.edges).toHaveLength(layout.nodes.length - 1);+ expect(layout.edges.every((edge) => edge.from !== edge.to)).toBe(true);+ });++ it("grows to the right and centers a parent between its children", () => {+ const byType = new Map(layout.nodes.map((node) => [node.node.nodeType, node]));+ const root = byType.get("Limit")!;+ const join = byType.get("Hash Join")!;+ const seqScan = byType.get("Seq Scan")!;+ const hash = byType.get("Hash")!;++ expect(root.x).toBe(PLAN_CANVAS_PAD);+ expect(root.x).toBeLessThan(byType.get("Sort")!.x);+ expect(byType.get("Sort")!.x).toBeLessThan(join.x);+ expect(join.y).toBe((seqScan.y + hash.y) / 2);+ expect(hash.y).toBe(byType.get("Index Scan")!.y);+ });++ it("keeps every card clear of every other card", () => {+ for (const first of layout.nodes) {+ for (const second of layout.nodes) {+ if (first === second) continue;+ const overlaps = Math.abs(first.x - second.x) < PLAN_CANVAS_NODE_W && Math.abs(first.y - second.y) < PLAN_CANVAS_NODE_H;+ expect(overlaps, `${first.node.nodeType} overlaps ${second.node.nodeType}`).toBe(false);+ }+ }+ });++ it("sizes the canvas so it covers every card", () => {+ for (const node of layout.nodes) {+ expect(node.x + PLAN_CANVAS_NODE_W).toBeLessThanOrEqual(layout.width);+ expect(node.y + PLAN_CANVAS_NODE_H).toBeLessThanOrEqual(layout.height);+ }+ });++ it("splits the cumulative cost into self-cost shares that sum to one", () => {+ const shares = layout.nodes.map((node) => node.costShare);+ expect(shares.every((share) => share !== undefined)).toBe(true);+ expect(shares.reduce((total, share) => total + (share ?? 0), 0)).toBeCloseTo(1, 10);+ });++ it("clamps a self-cost below zero when a child reports more than its parent", () => {+ const clamped = buildPlanCanvas([+ planNode({+ id: "0",+ nodeType: "Limit",+ cost: "10",+ children: [planNode({ id: "0.0", nodeType: "Seq Scan", cost: "40" })],+ }),+ ]);+ const [root, child] = clamped.nodes;+ expect(root.costShare).toBe(0);+ expect(child.costShare).toBe(1);+ });++ it("leaves the cost share undefined when no node reports a numeric cost", () => {+ const costless = buildPlanCanvas([planNode({ id: "0", nodeType: "Plan", children: [planNode({ id: "0.0", nodeType: "Plan" })] })]);+ expect(costless.nodes.every((node) => node.costShare === undefined)).toBe(true);+ });++ it("stacks multiple roots vertically", () => {+ const twoRoots = buildPlanCanvas([planNode({ id: "0", nodeType: "Limit" }), planNode({ id: "1", nodeType: "Limit" })]);+ expect(twoRoots.nodes[0].x).toBe(twoRoots.nodes[1].x);+ expect(twoRoots.nodes[1].y - twoRoots.nodes[0].y).toBeGreaterThanOrEqual(PLAN_CANVAS_NODE_H);+ });++ it("returns an empty canvas for an empty plan", () => {+ expect(buildPlanCanvas([])).toEqual({ nodes: [], edges: [], width: 0, height: 0 });+ });++ it("carries the parsed row counts onto nodes and edges", () => {+ const seqScan = layout.nodes.find((node) => node.node.nodeType === "Seq Scan")!;+ expect(seqScan.rows).toBe(1_200_000);+ expect(layout.edges.find((edge) => edge.to === seqScan)?.rows).toBe(1_200_000);+ expect(layout.nodes.find((node) => node.node.nodeType === "Sort")!.actualRows).toBe(83911);+ });+});++describe("heatLevel", () => {+ it("maps a share onto the four heat steps", () => {+ expect(heatLevel(undefined)).toBe("none");+ expect(heatLevel(0)).toBe("cool");+ expect(heatLevel(0.049)).toBe("cool");+ expect(heatLevel(0.05)).toBe("warm");+ expect(heatLevel(0.2)).toBe("warm");+ expect(heatLevel(0.201)).toBe("hot");+ expect(heatLevel(1)).toBe("hot");+ });+});++describe("edgeStrokeWidth", () => {+ it("scales with the row count inside a fixed range", () => {+ expect(edgeStrokeWidth(undefined)).toBe(1.6);+ expect(edgeStrokeWidth(0)).toBe(1.6);+ expect(edgeStrokeWidth(100)).toBeCloseTo(1.6 + Math.log10(101) * 1.05, 10);+ expect(edgeStrokeWidth(1e12)).toBe(8);+ expect(edgeStrokeWidth(1e6)).toBeGreaterThan(edgeStrokeWidth(1e3));+ });+});++describe("formatPlanRows", () => {+ it("shortens large counts and marks unknown ones", () => {+ expect(formatPlanRows(undefined)).toBe("—");+ expect(formatPlanRows(Number.NaN)).toBe("—");+ expect(formatPlanRows(100)).toBe("100");+ expect(formatPlanRows(999)).toBe("999");+ expect(formatPlanRows(84_200)).toBe("84.2K");+ expect(formatPlanRows(1_000)).toBe("1K");+ expect(formatPlanRows(1_200_000)).toBe("1.2M");+ expect(formatPlanRows(1_000_000)).toBe("1M");+ });+});diff --git a/apps/desktop/src/lib/diagram/explainPlan.ts b/apps/desktop/src/lib/diagram/explainPlan.tsindex 4c72ba4bc6..a024d06e2e 100644--- a/apps/desktop/src/lib/diagram/explainPlan.ts+++ b/apps/desktop/src/lib/diagram/explainPlan.ts@@ -29,8 +29,9 @@ export function supportsExplainPlan(databaseType?: DatabaseType): databaseType ireturn !!databaseType && supportsDatabaseFeature(databaseType, "sqlExplain") && SUPPORTED_EXPLAIN_TYPES.has(databaseType);}-export function buildExplainSql(databaseType: DatabaseType | undefined, sql: string, format: "json" | "standard" = "json"): Promise<BuildExplainSqlResult> {- return api.buildExplainSql({ databaseType, sql, format }) as Promise<BuildExplainSqlResult>;+/** `analyze` is honored by PostgreSQL only; every other engine ignores it server-side. */+export function buildExplainSql(databaseType: DatabaseType | undefined, sql: string, format: "json" | "standard" = "json", analyze?: boolean): Promise<BuildExplainSqlResult> {+ return api.buildExplainSql({ databaseType, sql, format, analyze }) as Promise<BuildExplainSqlResult>;}export function parseExplainResult(databaseType: "mysql" | "postgres" | "dameng" | "questdb" | "sqlserver", result: QueryResult): ParsedExplainPlan {@@ -454,6 +455,7 @@ function parseSqlServerRelOp(element: Element): ExplainPlanNode {element.getAttribute("EstimateIO") ? `Estimated I/O: ${element.getAttribute("EstimateIO")}` : "",element.getAttribute("EstimateCPU") ? `Estimated CPU: ${element.getAttribute("EstimateCPU")}` : "",...expressions.slice(0, 3).map((expression) => `Expression: ${expression}`),+ ...sqlServerRuntimeDetails(sqlServerRuntimeCounters(element)),].filter(Boolean);return {@@ -470,6 +472,71 @@ function parseSqlServerRelOp(element: Element): ExplainPlanNode {};}+interface SqlServerRuntimeCounters {+ rows: number;+ executions: number;+ threads: number;+ /** Set only when the operator was genuinely invoked more than once per thread. */+ rowsPerExecution?: number;+ elapsedMs?: number;+ cpuMs?: number;+}++/**+ * Aggregates the `SET STATISTICS XML` runtime counters of one operator across its+ * threads: rows and executions are summed, elapsed time is wall clock per thread so+ * the slowest thread is the operator duration, and CPU time is additive work so it+ * is summed. Estimated plans carry no RunTimeInformation and yield undefined.+ */+function sqlServerRuntimeCounters(element: Element): SqlServerRuntimeCounters | undefined {+ const perThread = planRegionElements(element, "RunTimeCountersPerThread");+ if (perThread.length === 0) return undefined;++ const counters: SqlServerRuntimeCounters = { rows: 0, executions: 0, threads: perThread.length };+ let activeThreads = 0;+ for (const thread of perThread) {+ const executions = xmlNumberAttribute(thread, "ActualExecutions") ?? 0;+ counters.rows += xmlNumberAttribute(thread, "ActualRows") ?? 0;+ counters.executions += executions;+ if (executions > 0) activeThreads += 1;+ const elapsed = xmlNumberAttribute(thread, "ActualElapsedms");+ if (elapsed !== undefined) counters.elapsedMs = Math.max(counters.elapsedMs ?? 0, elapsed);+ const cpu = xmlNumberAttribute(thread, "ActualCPUms");+ if (cpu !== undefined) counters.cpuMs = (counters.cpuMs ?? 0) + cpu;+ }++ // ActualRows is cumulative over executions while EstimateRows stays per execution,+ // so repeated invocations (a nested loop inner side) need normalizing. A parallel+ // operator reports one execution per worker thread, which is still one logical+ // execution: dividing there would understate every parallel node instead.+ const executionsPerThread = counters.executions / (activeThreads || counters.threads);+ if (executionsPerThread > 1) counters.rowsPerExecution = counters.rows / counters.executions;+ return counters;+}++function sqlServerRuntimeDetails(counters?: SqlServerRuntimeCounters): string[] {+ if (!counters) return [];++ const details = [`Actual Rows: ${counters.rows}`];+ if (counters.threads > 1) details.push(`Actual Threads: ${counters.threads}`);+ if (counters.executions > 1) details.push(`Actual Executions: ${counters.executions}`);+ if (counters.rowsPerExecution !== undefined) details.push(`Actual Rows Per Execution: ${formatPlanMetric(counters.rowsPerExecution)}`);+ if (counters.elapsedMs !== undefined) details.push(`Actual Time: ${formatPlanMetric(counters.elapsedMs)} ms`);+ if (counters.cpuMs !== undefined) details.push(`Actual CPU: ${formatPlanMetric(counters.cpuMs)} ms`);+ return details;+}++function formatPlanMetric(value: number): string {+ return String(Number(value.toFixed(2)));+}++function xmlNumberAttribute(element: Element, attribute: string): number | undefined {+ const raw = element.getAttribute(attribute);+ if (raw === null || raw.trim() === "") return undefined;+ const value = Number(raw);+ return Number.isFinite(value) ? value : undefined;+}+function planRegionElements(root: Element, localName: string): Element[] {const matches: Element[] = [];const visit = (element: Element) => {@@ -662,7 +729,15 @@ function parsePostgresExplain(raw: unknown): ExplainPlanNode[] {const root = objectValue(item);if (!root) return null;const plan = objectValue(root.Plan) || root;- return parsePostgresNode(plan, String(index));+ const node = parsePostgresNode(plan, String(index));+ if (!node) return null;++ // EXPLAIN ANALYZE reports these next to "Plan", not inside it.+ const planningTime = numberLike(root["Planning Time"]);+ const executionTime = numberLike(root["Execution Time"]);+ if (planningTime !== undefined) node.details.push(`Planning Time: ${planningTime} ms`);+ if (executionTime !== undefined) node.details.push(`Execution Time: ${executionTime} ms`);+ return node;}).filter((node): node is ExplainPlanNode => !!node);}@@ -679,6 +754,11 @@ function parsePostgresNode(plan: Record<string, unknown> | null, id: string): Exconst filter = stringValue(plan.Filter);const joinType = stringValue(plan["Join Type"]);const sortKey = arrayValue(plan["Sort Key"])?.map(String).join(", ");+ // EXPLAIN ANALYZE only. Actual Rows is per loop, matching Plan Rows.+ const actualRows = numberLike(plan["Actual Rows"]);+ const actualLoops = numberLike(plan["Actual Loops"]);+ const actualStartupTime = numberLike(plan["Actual Startup Time"]);+ const actualTotalTime = numberLike(plan["Actual Total Time"]);const children =arrayValue(plan.Plans)@@ -694,7 +774,14 @@ function parsePostgresNode(plan: Record<string, unknown> | null, id: string): Excost: [startupCost, totalCost].every(Boolean) ? `${startupCost}..${totalCost}` : totalCost,rows,width,- details: [joinType ? `Join: ${joinType}` : "", filter ? `Filter: ${filter}` : "", sortKey ? `Sort: ${sortKey}` : ""].filter(Boolean),+ details: [+ joinType ? `Join: ${joinType}` : "",+ filter ? `Filter: ${filter}` : "",+ sortKey ? `Sort: ${sortKey}` : "",+ actualRows !== undefined ? `Actual Rows: ${actualRows}` : "",+ actualLoops !== undefined && Number(actualLoops) > 1 ? `Actual Loops: ${actualLoops}` : "",+ actualStartupTime !== undefined && actualTotalTime !== undefined ? `Actual Time: ${actualStartupTime}..${actualTotalTime} ms` : "",+ ].filter(Boolean),children,};}diff --git a/apps/desktop/src/lib/diagram/planCanvas.ts b/apps/desktop/src/lib/diagram/planCanvas.tsnew file mode 100644index 0000000000..1303b353e1--- /dev/null+++ b/apps/desktop/src/lib/diagram/planCanvas.ts@@ -0,0 +1,164 @@+import type { ExplainPlanNode } from "./explainPlan";++export type PlanCanvasCategory = "result" | "sort" | "join" | "tscan" | "iscan" | "lookup" | "mat" | "agg" | "xchg" | "mod" | "other";++export const PLAN_CANVAS_NODE_W = 212;+export const PLAN_CANVAS_NODE_H = 76;+export const PLAN_CANVAS_GAP_X = 84;+export const PLAN_CANVAS_GAP_Y = 26;+export const PLAN_CANVAS_PAD = 36;++/**+ * Ordered because operator names overlap across engines: "Merge Join" is a join+ * while a bare "Merge" is DML, "Clustered Index Scan" reads a whole table while+ * "Index Scan" does not, and "SORT AGGREGATE" is an aggregate, not a sort.+ */+const CATEGORY_RULES: Array<[RegExp, PlanCanvasCategory]> = [+ // MySQL access types are single ambiguous words, so they only match exactly.+ [/^(?:eq_ref|const|system)$/, "lookup"],+ [/^(?:ref|range|index|index_merge|ref_or_null|fulltext)$/, "iscan"],+ [/^all$/, "tscan"],++ [/(?:key|rid|row|rowid|heap)\s+lookup|table access by .*rowid/, "lookup"],+ [/hash join|hash match|merge join|nested loops?|nest loop|hash2|cartesian/, "join"],+ [/aggregate|group by|grouping_operation|hagr\d*|sagr\d*|\bagg\b/, "agg"],+ [/sort|ordering_operation/, "sort"],+ [/gather|parallelism|px send|px receive|px block|exchange|repartition|distribute/, "xchg"],+ [/^(?:insert|update|delete|replace)\b|^merge$|modifytable|table (?:insert|update|delete|merge)|clustered index (?:insert|update|delete|merge)|load table|\bdml\b/, "mod"],+ [/materiali[sz]|spool|\bhash\b|\bcte\b|temp table transformation|worktable/, "mat"],+ [/clustered index scan|seq scan|sequential scan|table scan|table access full|table access storage full|cscn\d*/, "tscan"],+ [/index.*(?:scan|seek)|bitmap heap scan|ssek\d*|csek\d*|bmsk\d*/, "iscan"],+ [/result|^select\b|select statement|limit|query_block|nset\d*|prjt\d*|union|\btop\b/, "result"],+];++export function categorizePlanNode(nodeType: string): PlanCanvasCategory {+ const normalized = nodeType.trim().toLowerCase();+ if (!normalized) return "other";+ for (const [pattern, category] of CATEGORY_RULES) {+ if (pattern.test(normalized)) return category;+ }+ return "other";+}++/** Reads the numeric part of an engine-native cost/rows string ("0.29..1830.12", "1,234", "96M"). */+export function parsePlanNumber(value?: string): number | undefined {+ if (value == null) return undefined;+ let text = String(value).trim();+ if (!text) return undefined;++ // PostgreSQL reports "startup..total"; the total is what matters.+ const rangeIndex = text.lastIndexOf("..");+ if (rangeIndex >= 0) text = text.slice(rangeIndex + 2).trim();++ const match = text.match(/^([+-]?[\d,]*\.?\d+)\s*(?:([kmgt])\b)?/i);+ if (!match) return undefined;+ const base = Number(match[1].replaceAll(",", ""));+ if (!Number.isFinite(base)) return undefined;++ const scales: Record<string, number> = { k: 1e3, m: 1e6, g: 1e9, t: 1e12 };+ return base * (scales[match[2]?.toLowerCase() ?? ""] ?? 1);+}++export function extractActualRows(node: ExplainPlanNode): number | undefined {+ // Estimates are per execution, so the per-execution detail wins when the engine+ // reports cumulative actuals (SQL Server). PostgreSQL never emits that key.+ let total: number | undefined;+ for (const detail of node.details) {+ const perExecution = detail.match(/Actual Rows Per Execution:\s*(\S+)/i);+ if (perExecution) return parsePlanNumber(perExecution[1]);+ if (total !== undefined) continue;+ const match = detail.match(/Actual Rows:\s*(\S+)/i);+ if (match) total = parsePlanNumber(match[1]);+ }+ return total;+}++export interface PlanCanvasNode {+ node: ExplainPlanNode;+ category: PlanCanvasCategory;+ x: number;+ y: number;+ costShare?: number;+ rows?: number;+ actualRows?: number;+}++export interface PlanCanvasEdge {+ from: PlanCanvasNode;+ to: PlanCanvasNode;+ rows?: number;+}++export interface PlanCanvasLayout {+ nodes: PlanCanvasNode[];+ edges: PlanCanvasEdge[];+ width: number;+ height: number;+}++export function buildPlanCanvas(roots: ExplainPlanNode[]): PlanCanvasLayout {+ const nodes: PlanCanvasNode[] = [];+ const edges: PlanCanvasEdge[] = [];+ const selfCosts = new Map<PlanCanvasNode, number>();+ let leafOffset = 0;++ function place(node: ExplainPlanNode, depth: number, parent?: PlanCanvasNode): PlanCanvasNode {+ const placed: PlanCanvasNode = {+ node,+ category: categorizePlanNode(node.nodeType),+ x: PLAN_CANVAS_PAD + depth * (PLAN_CANVAS_NODE_W + PLAN_CANVAS_GAP_X),+ y: 0,+ rows: parsePlanNumber(node.rows),+ actualRows: extractActualRows(node),+ };+ nodes.push(placed);+ if (parent) edges.push({ from: parent, to: placed, rows: placed.rows });++ const children = node.children.map((child) => place(child, depth + 1, placed));+ if (children.length === 0) {+ placed.y = PLAN_CANVAS_PAD + leafOffset;+ leafOffset += PLAN_CANVAS_NODE_H + PLAN_CANVAS_GAP_Y;+ } else {+ placed.y = (children[0].y + children[children.length - 1].y) / 2;+ }++ const cost = parsePlanNumber(node.cost);+ if (cost !== undefined) {+ // Costs are cumulative over the subtree in PG / SQL Server / Oracle.+ const childCost = node.children.reduce((total, child) => total + (parsePlanNumber(child.cost) ?? 0), 0);+ selfCosts.set(placed, Math.max(0, cost - childCost));+ }+ return placed;+ }++ roots.forEach((root) => place(root, 0));++ const totalSelfCost = [...selfCosts.values()].reduce((total, cost) => total + cost, 0);+ if (totalSelfCost > 0) {+ for (const [placed, cost] of selfCosts) placed.costShare = cost / totalSelfCost;+ }++ const width = nodes.reduce((max, placed) => Math.max(max, placed.x + PLAN_CANVAS_NODE_W), 0) + PLAN_CANVAS_PAD;+ const height = nodes.reduce((max, placed) => Math.max(max, placed.y + PLAN_CANVAS_NODE_H), 0) + PLAN_CANVAS_PAD;+ return { nodes, edges, width: nodes.length ? width : 0, height: nodes.length ? height : 0 };+}++export function heatLevel(share?: number): "none" | "cool" | "warm" | "hot" {+ if (share === undefined) return "none";+ if (share > 0.2) return "hot";+ return share >= 0.05 ? "warm" : "cool";+}++export function edgeStrokeWidth(rows?: number): number {+ if (rows === undefined || !Number.isFinite(rows)) return 1.6;+ return Math.min(8, Math.max(1.6, 1.6 + Math.log10(Math.max(0, rows) + 1) * 1.05));+}++export function formatPlanRows(rows?: number): string {+ if (rows === undefined || !Number.isFinite(rows)) return "—";+ const trim = (value: string) => value.replace(/\.0$/, "");+ const magnitude = Math.abs(rows);+ if (magnitude >= 1e6) return `${trim((rows / 1e6).toFixed(1))}M`;+ if (magnitude >= 1e3) return `${trim((rows / 1e3).toFixed(1))}K`;+ return String(Math.round(rows));+}diff --git a/apps/desktop/src/stores/__tests__/queryStore.postgresExplain.spec.ts b/apps/desktop/src/stores/__tests__/queryStore.postgresExplain.spec.tsnew file mode 100644index 0000000000..6078d79122--- /dev/null+++ b/apps/desktop/src/stores/__tests__/queryStore.postgresExplain.spec.ts@@ -0,0 +1,154 @@+import { createPinia, setActivePinia } from "pinia";+import { beforeEach, describe, expect, it, vi } from "vitest";++const mocks = vi.hoisted(() => ({+ buildExplainSql: vi.fn(),+ parseExplainResult: vi.fn(),+ executeQuery: vi.fn(),+ closeClientSession: vi.fn(),+ saveOpenTabsState: vi.fn(),+ getConfig: vi.fn(),+}));++vi.mock("@/lib/diagram/explainPlan", () => ({+ buildExplainSql: mocks.buildExplainSql,+ parseExplainResult: mocks.parseExplainResult,+ parseDamengExplainText: vi.fn(),+ parseOracleExplainText: vi.fn(),+ sqlServerExplainResult: vi.fn(),+}));++vi.mock("@/lib/backend/api", () => ({+ executeQuery: mocks.executeQuery,+ closeClientConnectionSession: mocks.closeClientSession,+ saveOpenTabsState: mocks.saveOpenTabsState,+}));++vi.mock("@/stores/connectionStore", () => ({+ useConnectionStore: () => ({+ getConfig: mocks.getConfig,+ recordConnectionLostError: vi.fn(),+ }),+}));++vi.mock("@/stores/settingsStore", () => ({+ useSettingsStore: () => ({+ editorSettings: { pageSize: 100, openTabsRestoreMode: "all", confirmUnsavedSqlClose: false },+ }),+}));++function installLocalStorage() {+ const data = new Map<string, string>();+ vi.stubGlobal("localStorage", {+ getItem: vi.fn((key: string) => data.get(key) ?? null),+ setItem: vi.fn((key: string, value: string) => data.set(key, value)),+ removeItem: vi.fn((key: string) => data.delete(key)),+ });+}++const SOURCE_SQL = "SELECT * FROM orders";++async function explain(explainMode?: string) {+ const { useQueryStore } = await import("@/stores/queryStore");+ const store = useQueryStore();+ const tabId = store.createTab("pg-1", "shop", "Query", "query", "public");+ await store.explainTabSql(tabId, SOURCE_SQL, "postgres", explainMode);+ return { store, tabId };+}++describe("queryStore PostgreSQL EXPLAIN ANALYZE", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ vi.unstubAllGlobals();+ installLocalStorage();+ setActivePinia(createPinia());+ mocks.getConfig.mockReturnValue({ id: "pg-1", name: "Postgres", db_type: "postgres" });+ mocks.buildExplainSql.mockResolvedValue({ ok: true, sql: "EXPLAIN (FORMAT JSON) SELECT * FROM orders" });+ mocks.executeQuery.mockResolvedValue({ columns: ["QUERY PLAN"], rows: [["[]"]], affected_rows: 0, execution_time_ms: 1 });+ mocks.parseExplainResult.mockReturnValue({ databaseType: "postgres", raw: [], nodes: [] });+ mocks.saveOpenTabsState.mockResolvedValue(undefined);+ });++ it("requests ANALYZE when the autotrace toggle is on", async () => {+ await explain("autotrace");++ expect(mocks.buildExplainSql).toHaveBeenCalledTimes(1);+ expect(mocks.buildExplainSql).toHaveBeenCalledWith("postgres", SOURCE_SQL, "json", true);+ });++ it("leaves the plain explain call untouched in the default mode", async () => {+ const { tabId } = await explain();++ expect(mocks.buildExplainSql).toHaveBeenCalledWith("postgres", SOURCE_SQL);+ expect(mocks.executeQuery.mock.calls[0][5]).toMatchObject({ clientSessionId: `${tabId}:explain` });+ expect(mocks.executeQuery.mock.calls[0][5].executionMode).toBeUndefined();+ });++ it("leaves the plain explain call untouched when the toggle is explicitly off", async () => {+ await explain("explain");++ expect(mocks.buildExplainSql).toHaveBeenCalledWith("postgres", SOURCE_SQL);+ });++ it("runs the analyzed statement the backend built and parses its plan", async () => {+ mocks.buildExplainSql.mockResolvedValue({ ok: true, sql: "EXPLAIN (ANALYZE, FORMAT JSON) SELECT * FROM orders" });+ const parsedPlan = { databaseType: "postgres", raw: [], nodes: [{ id: "0", title: "Sort", nodeType: "Sort", details: ["Actual Rows: 84000"], children: [] }] };+ mocks.parseExplainResult.mockReturnValue(parsedPlan);++ const { store, tabId } = await explain("autotrace");++ expect(mocks.executeQuery).toHaveBeenCalledTimes(1);+ expect(mocks.executeQuery.mock.calls[0][2]).toBe("EXPLAIN (ANALYZE, FORMAT JSON) SELECT * FROM orders");+ expect(mocks.executeQuery.mock.calls[0][5]).toMatchObject({+ clientSessionId: expect.stringMatching(new RegExp(`^${tabId}:explain:`)),+ executionMode: "postgres_read_only_transaction",+ });+ expect(mocks.closeClientSession).toHaveBeenCalledWith("pg-1", "shop", mocks.executeQuery.mock.calls[0][5].clientSessionId);+ expect(store.tabs.find((tab) => tab.id === tabId)).toMatchObject({+ isExplaining: false,+ explainClientSessionId: undefined,+ explainPlan: parsedPlan,+ explainSql: "EXPLAIN (ANALYZE, FORMAT JSON) SELECT * FROM orders",+ explainError: undefined,+ });+ });++ it("surfaces a backend rejection of the analyzed statement", async () => {+ mocks.buildExplainSql.mockResolvedValue({ ok: false, reason: "unsafe" });++ const { store, tabId } = await explain("autotrace");++ expect(mocks.executeQuery).not.toHaveBeenCalled();+ expect(store.tabs.find((tab) => tab.id === tabId)).toMatchObject({+ isExplaining: false,+ explainPlan: undefined,+ explainError: "unsafe",+ });+ });++ it("closes the isolated session after an analyzed query error", async () => {+ mocks.buildExplainSql.mockResolvedValue({ ok: true, sql: "EXPLAIN (ANALYZE, FORMAT JSON) SELECT * FROM orders" });+ mocks.executeQuery.mockRejectedValue(new Error("query failed"));++ const { store, tabId } = await explain("autotrace");+ const clientSessionId = mocks.executeQuery.mock.calls[0][5].clientSessionId;++ expect(mocks.closeClientSession).toHaveBeenCalledWith("pg-1", "shop", clientSessionId);+ expect(store.tabs.find((tab) => tab.id === tabId)).toMatchObject({+ isExplaining: false,+ explainClientSessionId: undefined,+ explainPlan: undefined,+ explainError: "query failed",+ });+ });++ it("does not send the analyze flag for other engines sharing this path", async () => {+ const { useQueryStore } = await import("@/stores/queryStore");+ const store = useQueryStore();+ const tabId = store.createTab("pg-1", "shop", "Query", "query", "public");++ await store.explainTabSql(tabId, SOURCE_SQL, "questdb", "autotrace");++ expect(mocks.buildExplainSql).toHaveBeenCalledWith("questdb", SOURCE_SQL);+ });+});diff --git a/apps/desktop/src/stores/__tests__/queryStore.sqlserverExplain.spec.ts b/apps/desktop/src/stores/__tests__/queryStore.sqlserverExplain.spec.tsindex b53b9b68ed..bd3f68c40c 100644--- a/apps/desktop/src/stores/__tests__/queryStore.sqlserverExplain.spec.ts+++ b/apps/desktop/src/stores/__tests__/queryStore.sqlserverExplain.spec.ts@@ -110,6 +110,42 @@ describe("queryStore SQL Server explain", () => {await vi.waitFor(() => expect(mocks.closeClientConnectionSession).toHaveBeenCalledWith("sqlserver-1", "dbx_explain_plan_test", clientSessionId));});+ it("switches to STATISTICS XML when the autotrace toggle is on", async () => {+ const actualPlanSql = `SET STATISTICS XML ON;\nGO\n${sourceSql}\nGO\nSET STATISTICS XML OFF;`;+ // STATISTICS XML runs the statement, so the row set precedes the plan.+ const rowsResult: QueryResult = { columns: ["id"], rows: [[1]], affected_rows: 0, execution_time_ms: 3 };+ mocks.buildExplainSql.mockResolvedValue({ ok: true, sql: actualPlanSql });+ mocks.executeMulti.mockResolvedValue([rowsResult, planResult]);+ const { useQueryStore } = await import("@/stores/queryStore");+ const store = useQueryStore();+ const tabId = store.createTab("sqlserver-1", "dbx_explain_plan_test", "Query", "query", "dbo");++ await store.explainTabSql(tabId, sourceSql, "sqlserver", "autotrace");++ const tab = store.tabs.find((item) => item.id === tabId)!;+ expect(mocks.buildExplainSql).toHaveBeenCalledWith("sqlserver", sourceSql, "json", true);+ expect(mocks.executeQuery.mock.calls[0]?.[2]).toBe("SET STATISTICS XML ON;");+ expect(mocks.executeQuery.mock.calls[1]?.[2]).toBe("SET STATISTICS XML OFF;");+ expect(mocks.executeQuery.mock.calls[1]?.[5]).toMatchObject({ timeoutSecs: 5, executionMode: "simple" });+ expect(mocks.executeMulti.mock.calls[0]?.[2]).toBe(sourceSql);+ expect(mocks.sqlServerExplainResult).toHaveBeenCalledWith([rowsResult, planResult]);+ expect(tab.explainSql).toBe(actualPlanSql);+ expect(tab.explainPlan).toEqual(visualPlan);+ expect(tab.explainError).toBeUndefined();+ });++ it("keeps SHOWPLAN when the autotrace toggle is off", async () => {+ const { useQueryStore } = await import("@/stores/queryStore");+ const store = useQueryStore();+ const tabId = store.createTab("sqlserver-1", "dbx_explain_plan_test", "Query", "query", "dbo");++ await store.explainTabSql(tabId, sourceSql, "sqlserver", "explain");++ expect(mocks.buildExplainSql).toHaveBeenCalledWith("sqlserver", sourceSql);+ expect(mocks.executeQuery.mock.calls[0]?.[2]).toBe("SET SHOWPLAN_XML ON;");+ expect(mocks.executeQuery.mock.calls[1]?.[2]).toBe("SET SHOWPLAN_XML OFF;");+ });+it("shows an execution error and still closes the SHOWPLAN session", async () => {mocks.sqlServerExplainResult.mockReturnValue({ error: "Invalid object name 'missing_table'" });const { useQueryStore } = await import("@/stores/queryStore");diff --git a/apps/desktop/src/stores/queryStore.ts b/apps/desktop/src/stores/queryStore.tsindex 91dcc4dd50..19e8f9ede3 100644--- a/apps/desktop/src/stores/queryStore.ts+++ b/apps/desktop/src/stores/queryStore.ts@@ -4469,9 +4469,15 @@ export const useQueryStore = defineStore("query", () => {}if (databaseType === "sqlserver") {+ // SQL Server reuses the autotrace toggle to ask for the actual execution plan:+ // STATISTICS XML runs the statement and adds runtime counters to the same+ // ShowPlanXML document, while SHOWPLAN_XML only estimates.+ const actualPlan = explainMode === "autotrace";+ const planCaptureOn = actualPlan ? "SET STATISTICS XML ON;" : "SET SHOWPLAN_XML ON;";+ const planCaptureOff = actualPlan ? "SET STATISTICS XML OFF;" : "SET SHOWPLAN_XML OFF;";let built: BuildExplainSqlResult;try {- built = await buildExplainSql(databaseType, sql);+ built = actualPlan ? await buildExplainSql(databaseType, sql, "json", true) : await buildExplainSql(databaseType, sql);} catch (e: any) {tab.isExplaining = false;tab.explainExecutionId = undefined;@@ -4488,14 +4494,14 @@ export const useQueryStore = defineStore("query", () => {tab.explainSql = built.sql;const clientSessionId = `${tabClientSessionId(tab, "explain")}:${executionId}`;tab.explainClientSessionId = clientSessionId;- let showplanEnabled = false;+ let planCaptureEnabled = false;try {- await api.executeQuery(tab.connectionId, tab.database, "SET SHOWPLAN_XML ON;", tab.schema, executionId, {+ await api.executeQuery(tab.connectionId, tab.database, planCaptureOn, tab.schema, executionId, {clientSessionId,timeoutSecs: queryTimeoutSecs,executionMode: "simple",});- showplanEnabled = true;+ planCaptureEnabled = true;if (tabs.value.find((t) => t.id === id)?.explainExecutionId !== executionId) {return { ok: true as const, sql: built.sql };}@@ -4526,9 +4532,9 @@ export const useQueryStore = defineStore("query", () => {current.explainError = String(e?.message || e);}} finally {- if (showplanEnabled) {+ if (planCaptureEnabled) {try {- await api.executeQuery(tab.connectionId, tab.database, "SET SHOWPLAN_XML OFF;", tab.schema, undefined, {+ await api.executeQuery(tab.connectionId, tab.database, planCaptureOff, tab.schema, undefined, {clientSessionId,timeoutSecs: queryTimeoutSecs > 0 ? Math.min(queryTimeoutSecs, 5) : 5,executionMode: "simple",@@ -4548,7 +4554,8 @@ export const useQueryStore = defineStore("query", () => {return { ok: true as const, sql: built.sql };}- const built = await buildExplainSql(databaseType, sql);+ const postgresAnalyze = databaseType === "postgres" && explainMode === "autotrace";+ const built = postgresAnalyze ? await buildExplainSql(databaseType, sql, "json", true) : await buildExplainSql(databaseType, sql);if (!built.ok) {tab.explainPlan = undefined;tab.explainError = built.reason;@@ -4558,12 +4565,14 @@ export const useQueryStore = defineStore("query", () => {}tab.explainSql = built.sql;- const clientSessionId = tabClientSessionId(tab, "explain");+ const clientSessionId = postgresAnalyze ? `${tabClientSessionId(tab, "explain")}:${executionId}` : tabClientSessionId(tab, "explain");+ if (postgresAnalyze) tab.explainClientSessionId = clientSessionId;try {const result = await api.executeQuery(tab.connectionId, tab.database, built.sql, tab.schema, executionId, {clientSessionId,catalog: tab.catalog,timeoutSecs: queryTimeoutSecs,+ executionMode: postgresAnalyze ? "postgres_read_only_transaction" : undefined,});const current = tabs.value.find((t) => t.id === id);if (current?.explainExecutionId === executionId) {@@ -4582,7 +4591,10 @@ export const useQueryStore = defineStore("query", () => {current.isExplaining = false;current.explainExecutionId = undefined;}- void closeClientSessionId(tab.connectionId, tab.database, clientSessionId, tab.catalog, { tabId: tab.id });+ if (current?.explainClientSessionId === clientSessionId) current.explainClientSessionId = undefined;+ const closePromise = closeClientSessionId(tab.connectionId, tab.database, clientSessionId, tab.catalog, { tabId: tab.id, explainExecutionId: executionId });+ if (postgresAnalyze) await closePromise;+ else void closePromise;}return { ok: true as const, sql: built.sql };}diff --git a/crates/dbx-core/src/agent_tools.rs b/crates/dbx-core/src/agent_tools.rsindex cffa8089c4..014de5dbb1 100644--- a/crates/dbx-core/src/agent_tools.rs+++ b/crates/dbx-core/src/agent_tools.rs@@ -776,8 +776,12 @@ async fn execute_explain_query(}// Build the database-specific EXPLAIN SQL- let explain_result =- build_explain_sql(ExplainSqlOptions { database_type: Some(*db_type), format: None, sql: sql.to_string() });+ let explain_result = build_explain_sql(ExplainSqlOptions {+ database_type: Some(*db_type),+ format: None,+ analyze: None,+ sql: sql.to_string(),+ });let explain_sql = match (explain_result.ok, explain_result.sql) {(true, Some(sql)) => sql,diff --git a/crates/dbx-core/src/db/postgres.rs b/crates/dbx-core/src/db/postgres.rsindex 494fd169dd..2411d47d18 100644--- a/crates/dbx-core/src/db/postgres.rs+++ b/crates/dbx-core/src/db/postgres.rs@@ -3132,6 +3132,7 @@ pub(crate) enum PostgresSearchPathContext {Query,Transaction,LocalTransaction,+ LocalQueryTransaction,}pub(crate) fn postgres_set_search_path_sql(schema: &str, context: PostgresSearchPathContext) -> String {@@ -3141,6 +3142,7 @@ pub(crate) fn postgres_set_search_path_sql(schema: &str, context: PostgresSearchPostgresSearchPathContext::Query => ("", ", pg_catalog, public"),PostgresSearchPathContext::Transaction => ("", ", pg_catalog"),PostgresSearchPathContext::LocalTransaction => (" LOCAL", ", pg_catalog"),+ PostgresSearchPathContext::LocalQueryTransaction => (" LOCAL", ", pg_catalog, public"),};// PostgreSQL otherwise searches pg_catalog before every explicit path item.format!("SET{scope} search_path TO {}{suffix}", pg_quote_ident(schema))@@ -3305,6 +3307,88 @@ pub async fn execute_query_with_max_rows_and_cancel(.await}+fn postgres_read_only_transaction_setup(schema: Option<&str>) -> Vec<(String, &'static str)> {+ let mut statements = vec![("BEGIN READ ONLY".to_string(), "explain_analyze.begin")];+ if let Some(schema) = schema.map(str::trim).filter(|schema| !schema.is_empty()) {+ statements.push((+ postgres_set_search_path_sql(schema, PostgresSearchPathContext::LocalQueryTransaction),+ "explain_analyze.schema",+ ));+ }+ statements+}++fn postgres_read_only_transaction_cleanup_error(error: String) -> String {+ format!("PostgreSQL read-only transaction cleanup failed: {error}")+}++fn merge_postgres_operation_and_rollback_result<T>(+ operation_result: Result<T, String>,+ rollback_result: Result<(), String>,+) -> Result<T, String> {+ match (operation_result, rollback_result) {+ (Ok(result), Ok(())) => Ok(result),+ (Err(operation_error), Ok(())) => Err(operation_error),+ (Ok(_), Err(rollback_error)) => Err(postgres_read_only_transaction_cleanup_error(rollback_error)),+ (Err(operation_error), Err(rollback_error)) => {+ Err(format!("{operation_error}; {}", postgres_read_only_transaction_cleanup_error(rollback_error)))+ }+ }+}++async fn run_postgres_operation_with_rollback<T, Operation, OperationFuture, Rollback, RollbackFuture>(+ operation: Operation,+ rollback: Rollback,+) -> Result<T, String>+where+ Operation: FnOnce() -> OperationFuture,+ OperationFuture: Future<Output = Result<T, String>>,+ Rollback: FnOnce() -> RollbackFuture,+ RollbackFuture: Future<Output = Result<(), String>>,+{+ let operation_result = operation().await;+ let rollback_result = rollback().await;+ merge_postgres_operation_and_rollback_result(operation_result, rollback_result)+}++pub async fn execute_query_in_read_only_transaction_with_rollback(+ pool: &Pool,+ schema: Option<&str>,+ sql: &str,+ max_rows: Option<usize>,+ cancel_token: Option<CancellationToken>,+ budget: DbOperationBudget,+ cancel_context: Option<PostgresCancelContext>,+) -> Result<QueryResult, String> {+ let client = checkout_postgres_client(pool, cancel_token.as_ref(), budget.checkout_timeout).await?;+ let setup = postgres_read_only_transaction_setup(schema);++ run_postgres_operation_with_rollback(+ || async {+ for (statement, stage) in setup {+ execute_postgres_infra_statement(&client, &statement, budget.recycle_timeout, stage).await?;+ }++ let pg_cancel_token = client.cancel_token();+ wait_postgres_query(+ pg_cancel_token,+ cancel_context,+ cancel_token,+ budget.query_timeout,+ budget.cancel_timeout,+ execute_query_with_max_rows_inner(&client, sql, max_rows, false),+ )+ .await+ },+ || async {+ execute_postgres_infra_statement(&client, "ROLLBACK", budget.cleanup_timeout, "explain_analyze.rollback")+ .await+ .map(|_| ())+ },+ )+ .await+}+pub async fn stream_select_query_with_cancel(pool: &Pool,schema: Option<&str>,@@ -4487,6 +4571,7 @@ pub async fn copy_in(pool: &Pool, sql: &str, data: &[u8]) -> Result<(), String>#[cfg(test)]mod tests {use super::*;+ use std::cell::Cell;use std::process::Command;use std::time::Instant;use tokio_postgres::types::FromSql;@@ -4578,6 +4663,65 @@ mod tests {assert!(!Vec::<Option<serde_json::Value>>::accepts(&Type::INT4_ARRAY));}+ #[test]+ fn postgres_explain_analyze_uses_read_only_transaction_local_schema() {+ assert_eq!(+ postgres_read_only_transaction_setup(Some("sales")),+ vec![+ ("BEGIN READ ONLY".to_string(), "explain_analyze.begin"),+ ("SET LOCAL search_path TO \"sales\", pg_catalog, public".to_string(), "explain_analyze.schema"),+ ]+ );+ assert_eq!(+ postgres_read_only_transaction_setup(None),+ vec![("BEGIN READ ONLY".to_string(), "explain_analyze.begin")]+ );+ }++ #[tokio::test]+ async fn postgres_explain_analyze_rolls_back_after_success_and_query_failures() {+ let rollback_calls = Cell::new(0);+ let result = run_postgres_operation_with_rollback(+ || async { Ok::<_, String>(7) },+ || async {+ rollback_calls.set(rollback_calls.get() + 1);+ Ok(())+ },+ )+ .await;+ assert_eq!(result, Ok(7));+ assert_eq!(rollback_calls.get(), 1);++ for operation_error in ["query failed", crate::query::QUERY_CANCELED, "Query timed out after 30 seconds"] {+ let rollback_calls = Cell::new(0);+ let result = run_postgres_operation_with_rollback(+ || async { Err::<(), _>(operation_error.to_string()) },+ || async {+ rollback_calls.set(rollback_calls.get() + 1);+ Ok(())+ },+ )+ .await;++ assert_eq!(result, Err(operation_error.to_string()));+ assert_eq!(rollback_calls.get(), 1);+ }+ }++ #[tokio::test]+ async fn postgres_explain_analyze_marks_rollback_failure_as_pool_pollution() {+ let result = run_postgres_operation_with_rollback(+ || async { Err::<(), _>("query failed".to_string()) },+ || async { Err("PostgreSQL explain_analyze.rollback timed out after 3 seconds".to_string()) },+ )+ .await;++ assert_eq!(+ result,+ Err("query failed; PostgreSQL read-only transaction cleanup failed: PostgreSQL explain_analyze.rollback timed out after 3 seconds".to_string())+ );+ }+fn pg_interval_bytes(microseconds: i64, days: i32, months: i32) -> [u8; 16] {let mut raw = [0_u8; 16];raw[0..8].copy_from_slice(µseconds.to_be_bytes());@@ -4692,6 +4836,10 @@ mod tests {postgres_set_search_path_sql("application", PostgresSearchPathContext::LocalTransaction),"SET LOCAL search_path TO \"application\", pg_catalog");+ assert_eq!(+ postgres_set_search_path_sql("application", PostgresSearchPathContext::LocalQueryTransaction),+ "SET LOCAL search_path TO \"application\", pg_catalog, public"+ );}#[test]diff --git a/crates/dbx-core/src/db/sqlserver.rs b/crates/dbx-core/src/db/sqlserver.rsindex de7f89d200..dad6f01fad 100644--- a/crates/dbx-core/src/db/sqlserver.rs+++ b/crates/dbx-core/src/db/sqlserver.rs@@ -2605,8 +2605,8 @@ pub async fn execute_batch_with_max_rows(/// Execute a SQL Server batch directly through TDS simple-query mode.////// This intentionally bypasses result-set type probing and SQL rewriting. It is-/// required while `SHOWPLAN_XML` is enabled because any probe issued on the same-/// session is itself affected by SHOWPLAN state.+/// required while `SHOWPLAN_XML` or `STATISTICS XML` is enabled because any probe+/// issued on the same session is itself affected by the plan-capture state.pub async fn execute_simple_batch_with_max_rows(client: &mut SqlServerClient,sql: &str,@@ -2748,6 +2748,13 @@ fn requires_simple_query_batch(sql: &str) -> bool {if tokens.len() >= 2 && tokens[0].eq_ignore_ascii_case("SET") && tokens[1].eq_ignore_ascii_case("SHOWPLAN_XML") {return true;}+ if tokens.len() >= 3+ && tokens[0].eq_ignore_ascii_case("SET")+ && tokens[1].eq_ignore_ascii_case("STATISTICS")+ && tokens[2].eq_ignore_ascii_case("XML")+ {+ return true;+ }if tokens.len() >= 2 && tokens[0].eq_ignore_ascii_case("CREATE") && tokens[1].eq_ignore_ascii_case("SCHEMA") {return true;}@@ -3012,6 +3019,9 @@ mod tests {fn sqlserver_module_definitions_require_simple_query_batch() {assert!(requires_simple_query_batch("SET SHOWPLAN_XML ON;"));assert!(requires_simple_query_batch("SET SHOWPLAN_XML OFF;"));+ assert!(requires_simple_query_batch("SET STATISTICS XML ON;"));+ assert!(requires_simple_query_batch("SET STATISTICS XML OFF;"));+ assert!(!requires_simple_query_batch("SET STATISTICS IO ON;"));assert!(requires_simple_query_batch("CREATE SCHEMA [analytics];"));assert!(requires_simple_query_batch("CREATE FUNCTION dbo.fn_demo() RETURNS INT AS BEGIN RETURN 1; END;"));assert!(requires_simple_query_batch("ALTER PROCEDURE dbo.usp_demo AS SELECT 1;"));diff --git a/crates/dbx-core/src/query.rs b/crates/dbx-core/src/query.rsindex 61c896c699..5118c48170 100644--- a/crates/dbx-core/src/query.rs+++ b/crates/dbx-core/src/query.rs@@ -540,6 +540,7 @@ pub enum QueryExecutionMode {#[default]Standard,Simple,+ PostgresReadOnlyTransaction,}#[derive(Clone, Debug, Default)]@@ -564,9 +565,31 @@ pub struct QueryExecutionOptions {pub continue_on_error: bool,/// Explicit low-level execution path. `Simple` is currently used by SQL Server/// SHOWPLAN so the source SQL bypasses result-set probing and query rewriting.+ /// `PostgresReadOnlyTransaction` executes on an isolated client session and+ /// always rolls the transaction back after the result is collected.pub execution_mode: QueryExecutionMode,}+fn validate_query_execution_mode(+ db_type: Option<DatabaseType>,+ sql: &str,+ options: &QueryExecutionOptions,+) -> Result<(), String> {+ if options.execution_mode != QueryExecutionMode::PostgresReadOnlyTransaction {+ return Ok(());+ }+ if db_type != Some(DatabaseType::Postgres) {+ return Err("PostgreSQL read-only transaction mode requires a PostgreSQL connection".to_string());+ }+ if options.client_session_id.as_deref().is_none_or(|session_id| session_id.trim().is_empty()) {+ return Err("PostgreSQL read-only transaction mode requires an isolated client session".to_string());+ }+ if crate::sql::split_sql_statements_for_database(sql, DatabaseType::Postgres).len() != 1 {+ return Err("PostgreSQL read-only transaction mode requires exactly one statement".to_string());+ }+ Ok(())+}+fn query_result_row_limit(max_rows: Option<usize>) -> usize {max_rows.unwrap_or(MAX_ROWS).max(1)}@@ -701,6 +724,10 @@ fn is_schema_reset_cleanup_error(lower: &str) -> bool {lower.contains("schema.reset cleanup failed")}+fn is_postgres_transaction_cleanup_error(lower: &str) -> bool {+ lower.contains("postgresql read-only transaction cleanup failed")+}+fn should_discard_agent_pool_after_error(err: &str) -> bool {crate::db::agent_driver::agent_recovery_decision(err, RecoveryScope::UserOperation).discards_session()}@@ -719,6 +746,7 @@ pub fn pool_error_action(db_type: Option<DatabaseType>, err: &str) -> PoolErrorAif db::sqlserver::is_driver_panic_error(err)|| (is_dbx_query_timeout_error(&lower) && should_discard_pool_after_query_timeout(db_type))|| is_schema_reset_cleanup_error(&lower)+ || is_postgres_transaction_cleanup_error(&lower){return PoolErrorAction::Discard;}@@ -1284,9 +1312,21 @@ async fn do_execute_typed(let schema = schema.map(|s| s.to_string());let max_rows = options.max_rows;let prefer_text_protocol = postgres_prefers_text_protocol(pool_db_type);+ let execution_mode = options.execution_mode;let cancel_context = state.get_postgres_cancel_context(pool_key).await;drop(connections);- if let Some(schema) = schema {+ if execution_mode == QueryExecutionMode::PostgresReadOnlyTransaction {+ db::postgres::execute_query_in_read_only_transaction_with_rollback(+ &p,+ schema.as_deref(),+ sql,+ max_rows,+ cancel_token,+ operation_budget.clone(),+ cancel_context,+ )+ .await+ } else if let Some(schema) = schema {db::postgres::execute_query_with_schema_and_max_rows_and_cancel(&p,&schema,@@ -1700,6 +1740,7 @@ pub async fn execute_sql_statement_with_options_typed(}let db_type = connection_database_type(state, connection_id).await;+ validate_query_execution_mode(db_type, sql, &options)?;let has_executable_sql = db_type.map_or_else(|| crate::sql::has_executable_sql(sql),|db_type| crate::sql::has_executable_sql_for_database(sql, db_type),@@ -2007,6 +2048,15 @@ pub async fn execute_multi_core_with_options_for_client_and_progress_typed(return Err(MONGO_SHELL_COMMAND_HINT.into());}+ let db_type = connection_database_type(state, connection_id).await;+ validate_query_execution_mode(db_type, sql, &options)?;+ if options.execution_mode == QueryExecutionMode::PostgresReadOnlyTransaction {+ let result =+ execute_sql_statement_with_options(state, connection_id, database, sql, schema, cancel_token, options)+ .await?;+ return Ok(vec![result.into()]);+ }+let pool_key = state.get_or_create_pool_for_session(connection_id, pool_database, options.client_session_id.as_deref()).await@@ -2050,7 +2100,6 @@ pub async fn execute_multi_core_with_options_for_client_and_progress_typed();}- let db_type = connection_database_type(state, connection_id).await;let statements = db_type.map_or_else(|| split_sql_statements(sql),|db_type| crate::sql::split_sql_statements_for_database(sql, db_type),@@ -4251,6 +4300,28 @@ for line in sys.stdin:assert_eq!(QueryExecutionMode::default(), QueryExecutionMode::Standard);}+ #[test]+ fn query_execution_mode_deserializes_postgres_read_only_transaction() {+ let mode: QueryExecutionMode = serde_json::from_str("\"postgres_read_only_transaction\"").unwrap();++ assert_eq!(mode, QueryExecutionMode::PostgresReadOnlyTransaction);+ }++ #[test]+ fn postgres_read_only_transaction_requires_postgres_and_isolated_session() {+ let mut options = QueryExecutionOptions {+ execution_mode: QueryExecutionMode::PostgresReadOnlyTransaction,+ ..Default::default()+ };++ assert!(validate_query_execution_mode(Some(DatabaseType::Mysql), "SELECT 1", &options).is_err());+ assert!(validate_query_execution_mode(Some(DatabaseType::Postgres), "SELECT 1", &options).is_err());++ options.client_session_id = Some("tab:explain:execution".to_string());+ assert_eq!(validate_query_execution_mode(Some(DatabaseType::Postgres), "SELECT 1", &options), Ok(()));+ assert!(validate_query_execution_mode(Some(DatabaseType::Postgres), "SELECT 1; SELECT 2", &options).is_err());+ }+fn test_connection_config(db_type: DatabaseType) -> ConnectionConfig {ConnectionConfig {id: "conn-1".to_string(),@@ -5492,6 +5563,14 @@ for line in sys.stdin:assert!(should_discard_pool_after_error(Some(DatabaseType::Postgres), err));}+ #[test]+ fn pool_error_action_discards_postgres_read_only_transaction_cleanup_without_retry() {+ let err = "PostgreSQL read-only transaction cleanup failed: PostgreSQL explain_analyze.rollback timed out after 3 seconds";++ assert_eq!(pool_error_action(Some(DatabaseType::Postgres), err), PoolErrorAction::Discard);+ assert!(should_discard_pool_after_error(Some(DatabaseType::Postgres), err));+ }+#[test]fn pool_error_action_reconnects_non_agent_errors_but_never_replays_agent_operations() {let err = "connection reset by peer";diff --git a/crates/dbx-core/src/query_execution_sql.rs b/crates/dbx-core/src/query_execution_sql.rsindex ce3c41ed92..ffff8e1b88 100644--- a/crates/dbx-core/src/query_execution_sql.rs+++ b/crates/dbx-core/src/query_execution_sql.rs@@ -20,6 +20,10 @@ pub struct ExplainSqlOptions {/// Omitted formats retain the existing JSON behavior.#[serde(default, skip_serializing_if = "Option::is_none")]pub format: Option<ExplainFormat>,+ /// PostgreSQL and SQL Server only: run the statement and report measured+ /// rows/timings. Every other engine ignores the flag.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub analyze: Option<bool>,pub sql: String,}@@ -53,11 +57,24 @@ pub fn build_explain_sql(options: ExplainSqlOptions) -> ExplainSqlBuildResult {if !is_safe_explain_sql(&source) {return explain_err("unsafe");}+ if options.analyze == Some(true)+ && options.database_type.is_some_and(|database_type| {+ matches!(database_type, DatabaseType::Postgres | DatabaseType::SqlServer)+ && is_write_sql_for_database(&source, database_type)+ })+ {+ return explain_err("unsafe");+ }if options.database_type == Some(DatabaseType::SqlServer) && crate::sql::split_sql_batches(&source).len() != 1 {return explain_err("unsafe");}let sql = match options.database_type {+ // ANALYZE executes the statement; is_safe_explain_sql has already limited+ // the source to SELECT/WITH/TABLE/VALUES. MongoDb shares the plain arm only.+ Some(DatabaseType::Postgres) if options.analyze == Some(true) => {+ format!("EXPLAIN (ANALYZE, FORMAT JSON) {source}")+ }Some(DatabaseType::Postgres | DatabaseType::MongoDb) => {format!("EXPLAIN (FORMAT JSON) {source}")}@@ -65,6 +82,11 @@ pub fn build_explain_sql(options: ExplainSqlOptions) -> ExplainSqlBuildResult {format!("EXPLAIN {source}")}Some(DatabaseType::Oracle) => format!("EXPLAIN PLAN FOR {source}"),+ // STATISTICS XML returns the same ShowPlanXML document plus per-operator+ // runtime counters, at the price of actually running the statement.+ Some(DatabaseType::SqlServer) if options.analyze == Some(true) => {+ format!("SET STATISTICS XML ON;\nGO\n{source}\nGO\nSET STATISTICS XML OFF;")+ }Some(DatabaseType::SqlServer) => {format!("SET SHOWPLAN_XML ON;\nGO\n{source}\nGO\nSET SHOWPLAN_XML OFF;")}@@ -288,7 +310,7 @@ fn strip_leading_search_engine_comments(input: &str) -> &str {}fn is_write_sql_with_database_type(sql: &str, database_type: Option<DatabaseType>) -> bool {- if database_type == Some(DatabaseType::SqlServer) && is_sqlserver_showplan_xml_set(sql) {+ if database_type == Some(DatabaseType::SqlServer) && is_sqlserver_plan_capture_set(sql) {return false;}if database_type.is_some_and(|database_type| has_dialect_specific_write(sql, database_type)) {@@ -309,12 +331,15 @@ fn is_write_sql_with_database_type(sql: &str, database_type: Option<DatabaseType.any(|statement| is_write_sql_statement(statement, detect_mysql_executable_comments, detect_select_into))}-fn is_sqlserver_showplan_xml_set(sql: &str) -> bool {+/// The explain flows toggle plan capture with a standalone SET statement:+/// `SHOWPLAN_XML` for the estimated plan, `STATISTICS XML` for the actual one.+fn is_sqlserver_plan_capture_set(sql: &str) -> bool {let normalized = strip_sql_comments(sql).split_whitespace().map(|part| part.trim_end_matches(';').to_ascii_uppercase()).collect::<Vec<_>>();- matches!(normalized.as_slice(), [set, showplan, value] if set == "SET" && showplan == "SHOWPLAN_XML" && matches!(value.as_str(), "ON" | "OFF"))+ let tokens = normalized.iter().map(String::as_str).collect::<Vec<_>>();+ matches!(tokens.as_slice(), ["SET", "SHOWPLAN_XML", "ON" | "OFF"] | ["SET", "STATISTICS", "XML", "ON" | "OFF"])}fn is_mysql_compatible_database(database_type: DatabaseType) -> bool {@@ -765,6 +790,7 @@ mod tests {let result = build_explain_sql(ExplainSqlOptions {database_type: Some(DatabaseType::Postgres),format: None,+ analyze: None,sql: " select * from users where id = 1; ".to_string(),});@@ -778,11 +804,148 @@ mod tests {);}+ #[test]+ fn builds_postgres_analyze_explain_sql() {+ let result = build_explain_sql(ExplainSqlOptions {+ database_type: Some(DatabaseType::Postgres),+ format: None,+ analyze: Some(true),+ sql: " select * from users where id = 1; ".to_string(),+ });++ assert_eq!(+ result,+ ExplainSqlBuildResult {+ ok: true,+ sql: Some("EXPLAIN (ANALYZE, FORMAT JSON) select * from users where id = 1".to_string()),+ reason: None,+ }+ );++ // analyze: Some(false) must behave exactly like the omitted flag.+ assert_eq!(+ build_explain_sql(ExplainSqlOptions {+ database_type: Some(DatabaseType::Postgres),+ format: None,+ analyze: Some(false),+ sql: "SELECT 1".to_string(),+ })+ .sql,+ Some("EXPLAIN (FORMAT JSON) SELECT 1".to_string())+ );+ }++ #[test]+ fn builds_sqlserver_actual_plan_explain_sql() {+ let result = build_explain_sql(ExplainSqlOptions {+ database_type: Some(DatabaseType::SqlServer),+ format: None,+ analyze: Some(true),+ sql: " select * from dbo.orders where id = 1; ".to_string(),+ });++ assert_eq!(+ result,+ ExplainSqlBuildResult {+ ok: true,+ sql: Some(+ "SET STATISTICS XML ON;\nGO\nselect * from dbo.orders where id = 1\nGO\nSET STATISTICS XML OFF;"+ .to_string()+ ),+ reason: None,+ }+ );++ // analyze: Some(false) must keep the estimated SHOWPLAN plan.+ assert_eq!(+ build_explain_sql(ExplainSqlOptions {+ database_type: Some(DatabaseType::SqlServer),+ format: None,+ analyze: Some(false),+ sql: "SELECT 1".to_string(),+ })+ .sql,+ Some("SET SHOWPLAN_XML ON;\nGO\nSELECT 1\nGO\nSET SHOWPLAN_XML OFF;".to_string())+ );+ }++ #[test]+ fn refuses_sqlserver_analyze_on_non_select_sources() {+ // STATISTICS XML runs the statement, so the safety gate stays load-bearing.+ for sql in [+ "delete from dbo.orders",+ "update dbo.orders set name = 'x'",+ "SELECT * INTO dbo.orders_copy FROM dbo.orders",+ "SELECT 1\nGO\nDROP TABLE dbo.orders",+ ] {+ assert_eq!(+ build_explain_sql(ExplainSqlOptions {+ database_type: Some(DatabaseType::SqlServer),+ format: None,+ analyze: Some(true),+ sql: sql.to_string(),+ }),+ ExplainSqlBuildResult { ok: false, sql: None, reason: Some("unsafe".to_string()) },+ "{sql}"+ );+ }+ }++ #[test]+ fn ignores_analyze_for_every_engine_but_postgres_and_sqlserver() {+ for (db_type, expected) in [+ (DatabaseType::MongoDb, "EXPLAIN (FORMAT JSON) SELECT 1"),+ (DatabaseType::Mysql, "EXPLAIN FORMAT=JSON SELECT 1"),+ (DatabaseType::Dameng, "EXPLAIN SELECT 1"),+ (DatabaseType::Questdb, "EXPLAIN SELECT 1"),+ (DatabaseType::Oracle, "EXPLAIN PLAN FOR SELECT 1"),+ ] {+ let analyzed = build_explain_sql(ExplainSqlOptions {+ database_type: Some(db_type),+ format: None,+ analyze: Some(true),+ sql: "SELECT 1".to_string(),+ });+ let plain = build_explain_sql(ExplainSqlOptions {+ database_type: Some(db_type),+ format: None,+ analyze: None,+ sql: "SELECT 1".to_string(),+ });++ assert_eq!(analyzed, plain, "{db_type:?} must ignore the analyze flag");+ // MongoDb is rejected earlier by supports_explain_plan, so it never+ // reaches the match arm it nominally shares with Postgres.+ if db_type != DatabaseType::MongoDb {+ assert_eq!(analyzed.sql, Some(expected.to_string()), "{db_type:?}");+ } else {+ assert_eq!(analyzed.reason, Some("unsupported".to_string()));+ }+ }+ }++ #[test]+ fn refuses_analyze_on_non_select_sources() {+ for sql in ["delete from users", "update users set name = 'x'", "SELECT 1; DROP TABLE users"] {+ assert_eq!(+ build_explain_sql(ExplainSqlOptions {+ database_type: Some(DatabaseType::Postgres),+ format: None,+ analyze: Some(true),+ sql: sql.to_string(),+ }),+ ExplainSqlBuildResult { ok: false, sql: None, reason: Some("unsafe".to_string()) },+ "{sql}"+ );+ }+ }+#[test]fn builds_dameng_explain_sql() {let result = build_explain_sql(ExplainSqlOptions {database_type: Some(DatabaseType::Dameng),format: None,+ analyze: None,sql: "SELECT * FROM t1 WHERE id = 1".to_string(),});@@ -801,6 +964,7 @@ mod tests {let result = build_explain_sql(ExplainSqlOptions {database_type: Some(DatabaseType::Oracle),format: None,+ analyze: None,sql: "WITH rows AS (SELECT 1 AS id FROM dual) SELECT * FROM rows;".to_string(),});@@ -819,6 +983,7 @@ mod tests {let result = build_explain_sql(ExplainSqlOptions {database_type: Some(DatabaseType::SqlServer),format: None,+ analyze: None,sql: "WITH rows AS (SELECT 1 AS id) SELECT * FROM rows;".to_string(),});@@ -838,6 +1003,7 @@ mod tests {build_explain_sql(ExplainSqlOptions {database_type: Some(DatabaseType::SqlServer),format: None,+ analyze: None,sql: "SELECT 1\nGO\nSELECT 2".to_string(),}),ExplainSqlBuildResult { ok: false, sql: None, reason: Some("unsafe".to_string()) }@@ -846,6 +1012,7 @@ mod tests {build_explain_sql(ExplainSqlOptions {database_type: Some(DatabaseType::SqlServer),format: None,+ analyze: None,sql: "SELECT 'first line\nGO\nlast line' AS text".to_string(),}).ok@@ -868,6 +1035,7 @@ mod tests {build_explain_sql(ExplainSqlOptions {database_type: Some(DatabaseType::Mysql),format: None,+ analyze: None,sql: "SELECT * FROM users;".to_string(),}),ExplainSqlBuildResult {@@ -881,6 +1049,7 @@ mod tests {build_explain_sql(ExplainSqlOptions {database_type: Some(DatabaseType::Mysql),format: None,+ analyze: None,sql: "delete from users".to_string(),}),ExplainSqlBuildResult { ok: false, sql: None, reason: Some("unsafe".to_string()) }@@ -890,6 +1059,7 @@ mod tests {build_explain_sql(ExplainSqlOptions {database_type: Some(DatabaseType::Mysql),format: None,+ analyze: None,sql: "SELECT * FROM users; DELETE FROM users".to_string(),}),ExplainSqlBuildResult { ok: false, sql: None, reason: Some("unsafe".to_string()) }@@ -899,6 +1069,7 @@ mod tests {build_explain_sql(ExplainSqlOptions {database_type: Some(DatabaseType::Mysql),format: Some(ExplainFormat::Standard),+ analyze: None,sql: "SELECT * FROM users;".to_string(),}),ExplainSqlBuildResult {@@ -1281,13 +1452,22 @@ mod tests {}#[test]- fn check_read_only_allows_only_sqlserver_showplan_xml_session_switches() {- for sql in ["SET SHOWPLAN_XML ON;", "-- explain\nSET SHOWPLAN_XML OFF"] {+ fn check_read_only_allows_only_sqlserver_plan_capture_session_switches() {+ for sql in [+ "SET SHOWPLAN_XML ON;",+ "-- explain\nSET SHOWPLAN_XML OFF",+ "SET STATISTICS XML ON;",+ "-- actual plan\nSET STATISTICS XML OFF",+ ] {assert_eq!(check_read_only(sql, "readonly", DatabaseType::SqlServer), Ok(()));}assert!(check_read_only("SET SHOWPLAN_ALL ON", "readonly", DatabaseType::SqlServer).is_err());+ assert!(check_read_only("SET STATISTICS IO ON", "readonly", DatabaseType::SqlServer).is_err());assert!(check_read_only("SET SHOWPLAN_XML ON; SELECT 1", "readonly", DatabaseType::SqlServer).is_err());assert!(check_read_only("SET SHOWPLAN_XML OFF; DROP TABLE users", "readonly", DatabaseType::SqlServer).is_err());+ assert!(+ check_read_only("SET STATISTICS XML OFF; DROP TABLE users", "readonly", DatabaseType::SqlServer).is_err()+ );}#[test]