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): export explain plans to files
Satrio Ponco Sushadi45c23b1521f7
diff --git a/apps/desktop/src/components/explain/ExplainPlanDiagram.vue b/apps/desktop/src/components/explain/ExplainPlanDiagram.vueindex 690e43dec9..49bcc2ef07 100644--- a/apps/desktop/src/components/explain/ExplainPlanDiagram.vue+++ b/apps/desktop/src/components/explain/ExplainPlanDiagram.vue@@ -6,7 +6,7 @@ import { Button } from "@/components/ui/button";import type { ExplainPlanNode } from "@/lib/diagram/explainPlan";import { formatExplainPlanDetails } 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";+import { buildPlanCanvas, edgeStrokeWidth, formatPlanRows, heatLevel, PLAN_CATEGORY_COLORS, PLAN_CANVAS_GAP_X, PLAN_CANVAS_NODE_H, PLAN_CANVAS_NODE_W } from "@/lib/diagram/planCanvas";const props = defineProps<{nodes: ExplainPlanNode[];@@ -15,16 +15,7 @@ const props = defineProps<{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",+ ...PLAN_CATEGORY_COLORS,other: "var(--muted-foreground)",};diff --git a/apps/desktop/src/components/explain/ExplainPlanViewer.vue b/apps/desktop/src/components/explain/ExplainPlanViewer.vueindex 6702135d27..2904644b9f 100644--- a/apps/desktop/src/components/explain/ExplainPlanViewer.vue+++ b/apps/desktop/src/components/explain/ExplainPlanViewer.vue@@ -1,11 +1,15 @@<script setup lang="ts">import { computed, ref, watch } from "vue";import { useI18n } from "vue-i18n";-import { AlertCircle, Braces, GitBranch, Table2, FileText, Workflow } from "@lucide/vue";+import { AlertCircle, Braces, Download, GitBranch, Table2, FileText, Workflow } from "@lucide/vue";import type { ParsedExplainPlan, ExplainPlanNode } from "@/lib/diagram/explainPlan";import { flattenExplainPlanNodes, formatExplainPlanDetails } from "@/lib/diagram/explainPlan";import { extractActualRows } from "@/lib/diagram/planCanvas";import { Button } from "@/components/ui/button";+import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";+import { useToast } from "@/composables/useToast";+import { translateBackendError } from "@/i18n/backend-errors";+import { EXPLAIN_PLAN_EXPORT_COLUMN_KEYS, saveExplainPlanExport, type ExplainPlanExportFormat } from "@/lib/export/explainPlanExport";import type { QueryResult } from "@/types/database";import type { DefaultExplainView } from "@/stores/settingsStore";import ExplainPlanNodeTree from "./ExplainPlanNodeTree.vue";@@ -25,6 +29,41 @@ const props = defineProps<{}>();const { t } = useI18n();+const { toast } = useToast();+const exporting = ref(false);+const exportFormats: { format: ExplainPlanExportFormat; label: string }[] = [+ { format: "svg", label: "diagram.exportSvg" },+ { format: "png", label: "diagram.exportPng" },+ { format: "html", label: "grid.exportHtml" },+ { format: "csv", label: "grid.exportCsv" },+ { format: "xlsx", label: "grid.exportXlsx" },+];++async function exportPlan(format: ExplainPlanExportFormat) {+ if (exporting.value || props.loading || props.error || !props.plan?.nodes.length) return;+ exporting.value = true;+ try {+ const saved = await saveExplainPlanExport(+ props.plan,+ format,+ EXPLAIN_PLAN_EXPORT_COLUMN_KEYS.map((key) => t(key)),+ t("explain.estimatedTime"),+ `${t("explain.title")} · ${props.plan.databaseType.toUpperCase()}`,+ {+ cost: t("explain.cost"),+ estimatedRows: t("explain.estRows"),+ legendHeat: t("explain.legendHeat"),+ legendEdge: t("explain.legendEdge"),+ },+ );+ if (saved) toast(t("grid.exported"));+ } catch (error) {+ toast(t("grid.exportFailed", { message: translateBackendError(t, error) }), 5000);+ } finally {+ exporting.value = false;+ }+}+const userSelectedView = ref<ExplainView | null>(null);const activeView = ref<ExplainView>("canvas");const hasTableView = computed(() => !!props.tableResult || !!props.tableError);@@ -121,6 +160,19 @@ function tableCellText(value: unknown): string {><span v-if="measuredRowsLabel" class="shrink-0 whitespace-nowrap 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 min-w-2" />+ <DropdownMenu v-if="plan">+ <DropdownMenuTrigger as-child>+ <Button size="sm" variant="ghost" class="h-6 shrink-0 gap-1 px-2 text-xs" :disabled="loading || !!error || exporting || !plan.nodes.length">+ <Download class="h-3.5 w-3.5" />+ {{ t("grid.export") }}+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end">+ <DropdownMenuItem v-for="item in exportFormats" :key="item.format" :disabled="exporting" @select="exportPlan(item.format)">+ {{ t(item.label) }}+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu><div v-if="plan || hasTableView" class="shrink-0 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="selectView('canvas')"><Workflow class="h-3.5 w-3.5" />diff --git a/apps/desktop/src/components/explain/__tests__/ExplainPlanViewer.export.spec.ts b/apps/desktop/src/components/explain/__tests__/ExplainPlanViewer.export.spec.tsnew file mode 100644index 0000000000..5791852e0b--- /dev/null+++ b/apps/desktop/src/components/explain/__tests__/ExplainPlanViewer.export.spec.ts@@ -0,0 +1,132 @@+// @vitest-environment happy-dom+// oxlint-disable-next-line typescript/triple-slash-reference -- Test specs are excluded from the app tsconfig, so the editor needs the Vue declaration explicitly.+/// <reference path="../../../env.d.ts" />++import { createApp, defineComponent, h, nextTick, type Component } from "vue";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++const mocks = vi.hoisted(() => ({+ save: vi.fn(),+ toast: vi.fn(),+}));++function passthrough(tag: string): Component {+ return defineComponent({+ inheritAttrs: false,+ setup(_, { attrs, slots }) {+ return () => h(tag, attrs, slots.default?.());+ },+ });+}++vi.mock("vue-i18n", () => ({+ useI18n: () => ({ t: (key: string) => key }),+}));+vi.mock("@lucide/vue", () => ({+ AlertCircle: passthrough("span"),+ Braces: passthrough("span"),+ Download: passthrough("span"),+ FileText: passthrough("span"),+ GitBranch: passthrough("span"),+ Table2: passthrough("span"),+ Workflow: passthrough("span"),+}));+vi.mock("@/components/ui/button", () => ({ Button: passthrough("button") }));+vi.mock("@/components/ui/dropdown-menu", () => ({+ DropdownMenu: passthrough("div"),+ DropdownMenuContent: passthrough("div"),+ DropdownMenuItem: passthrough("button"),+ DropdownMenuTrigger: passthrough("div"),+}));+vi.mock("@/components/explain/ExplainPlanDiagram.vue", () => ({ default: passthrough("div") }));+vi.mock("@/components/explain/ExplainPlanNodeTree.vue", () => ({ default: passthrough("div") }));+vi.mock("@/composables/useToast", () => ({ useToast: () => ({ toast: mocks.toast }) }));+vi.mock("@/i18n/backend-errors", () => ({ translateBackendError: () => "translated error" }));+vi.mock("@/lib/export/explainPlanExport", () => ({+ EXPLAIN_PLAN_EXPORT_COLUMN_KEYS: ["explain.node", "explain.relation", "explain.index", "explain.cost", "explain.rows", "explain.details"],+ saveExplainPlanExport: mocks.save,+}));++import ExplainPlanViewer from "../ExplainPlanViewer.vue";++const plan = {+ databaseType: "oracle",+ raw: "raw plan",+ nodes: [{ id: "0", title: "SELECT STATEMENT", nodeType: "SELECT STATEMENT", details: [], children: [] }],+};++let app: ReturnType<typeof createApp> | undefined;+let root: HTMLDivElement | undefined;++async function mountViewer(props: Record<string, unknown> = {}) {+ root = document.createElement("div");+ document.body.append(root);+ app = createApp(ExplainPlanViewer, { plan, ...props });+ app.mount(root);+ await nextTick();+}++function exportItem(label: string): HTMLButtonElement {+ const item = Array.from(root!.querySelectorAll("button")).find((button) => button.textContent?.trim() === label);+ if (!item) throw new Error(`Missing export item: ${label}`);+ return item;+}++beforeEach(() => {+ mocks.save.mockResolvedValue(true);+});++afterEach(() => {+ app?.unmount();+ root?.remove();+ app = undefined;+ root = undefined;+ vi.clearAllMocks();+});++describe("ExplainPlanViewer export", () => {+ it.each([+ ["diagram.exportSvg", "svg"],+ ["diagram.exportPng", "png"],+ ["grid.exportHtml", "html"],+ ["grid.exportCsv", "csv"],+ ["grid.exportXlsx", "xlsx"],+ ] as const)("exports through %s", async (label, format) => {+ await mountViewer();+ exportItem(label).dispatchEvent(new Event("select", { bubbles: true }));++ await vi.waitFor(() => expect(mocks.save).toHaveBeenCalledTimes(1));+ expect(mocks.save).toHaveBeenCalledWith(plan, format, ["explain.node", "explain.relation", "explain.index", "explain.cost", "explain.rows", "explain.details"], "explain.estimatedTime", "explain.title · ORACLE", {+ cost: "explain.cost",+ estimatedRows: "explain.estRows",+ legendHeat: "explain.legendHeat",+ legendEdge: "explain.legendEdge",+ });+ expect(mocks.toast).toHaveBeenCalledWith("grid.exported");+ });++ it("does not report success when the save dialog is canceled", async () => {+ mocks.save.mockResolvedValueOnce(false);+ await mountViewer();+ exportItem("grid.exportCsv").dispatchEvent(new Event("select", { bubbles: true }));++ await vi.waitFor(() => expect(mocks.save).toHaveBeenCalledTimes(1));+ expect(mocks.toast).not.toHaveBeenCalled();+ });++ it("reports writer failures and disables export when no parsed nodes exist", async () => {+ mocks.save.mockRejectedValueOnce(new Error("disk full"));+ await mountViewer();+ exportItem("grid.exportXlsx").dispatchEvent(new Event("select", { bubbles: true }));++ await vi.waitFor(() => expect(mocks.toast).toHaveBeenCalledWith("grid.exportFailed", 5000));+ app?.unmount();++ const emptyPlan = { ...plan, nodes: [] };+ app = createApp(ExplainPlanViewer, { plan: emptyPlan });+ app.mount(root!);+ await nextTick();+ const trigger = Array.from(root!.querySelectorAll("button")).find((button) => button.textContent?.trim() === "grid.export");+ expect(trigger?.disabled).toBe(true);+ });+});diff --git a/apps/desktop/src/lib/diagram/planCanvas.ts b/apps/desktop/src/lib/diagram/planCanvas.tsindex e8f7ec377d..b441fbec18 100644--- a/apps/desktop/src/lib/diagram/planCanvas.ts+++ b/apps/desktop/src/lib/diagram/planCanvas.ts@@ -2,6 +2,21 @@ import type { ExplainPlanDatabaseType, ExplainPlanNode } from "./explainPlan";export type PlanCanvasCategory = "result" | "sort" | "join" | "tscan" | "iscan" | "lookup" | "mat" | "agg" | "xchg" | "mod" | "other";+/** Single source for plan-node category colors; the live canvas overrides `other` with a CSS variable. */+export const PLAN_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: "#71717a",+};+export const PLAN_CANVAS_NODE_W = 212;export const PLAN_CANVAS_NODE_H = 76;export const PLAN_CANVAS_GAP_X = 84;diff --git a/apps/desktop/src/lib/export/__tests__/explainPlanExport.spec.ts b/apps/desktop/src/lib/export/__tests__/explainPlanExport.spec.tsnew file mode 100644index 0000000000..9fa497f201--- /dev/null+++ b/apps/desktop/src/lib/export/__tests__/explainPlanExport.spec.ts@@ -0,0 +1,157 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import en from "../../../i18n/locales/en";+import type { ParsedExplainPlan } from "../../diagram/explainPlan";+import { EXPLAIN_PLAN_EXPORT_COLUMN_KEYS, explainPlanExportRows, saveExplainPlanExport } from "../explainPlanExport";++const mocks = vi.hoisted(() => ({+ desktop: vi.fn(() => false),+ save: vi.fn<() => Promise<string | null>>(),+ csv: vi.fn(),+ xlsx: vi.fn(),+ html: vi.fn(),+ raster: vi.fn(),+ saveText: vi.fn(),+ saveBinary: vi.fn(),+}));+vi.mock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: mocks.desktop }));+vi.mock("../exportPath", () => ({ promptExportSavePath: mocks.save }));+vi.mock("@/lib/backend/api", () => ({ exportQueryResultCsv: mocks.csv, exportQueryResultXlsx: mocks.xlsx, exportQueryResultHtml: mocks.html }));+vi.mock("@/stores/settingsStore", () => ({ useSettingsStore: () => ({ editorSettings: { csvQuoteMode: "all", csvNullMode: "marker" } }) }));+vi.mock("../diagramFormats", () => ({ svgToPngBlob: mocks.raster }));+vi.mock("../saveDiagramExport", () => ({ saveDiagramTextExport: mocks.saveText, saveDiagramBinaryExport: mocks.saveBinary }));++function fixture(): ParsedExplainPlan {+ return {+ databaseType: "oracle",+ raw: "raw plan",+ nodes: [+ {+ id: "0",+ title: "SELECT STATEMENT",+ nodeType: "SELECT STATEMENT",+ cost: "148 (0)",+ rows: "0",+ details: [],+ children: [+ {+ id: "1",+ title: "INDEX RANGE SCAN",+ nodeType: "INDEX RANGE SCAN",+ relation: "用户",+ index: "IDX_USERS",+ cost: "0.29..1830.12",+ rows: "96M",+ estimatedTimeUs: "12",+ details: ["Predicate: name = 'a,\"b\"' AND x < 4", "Time: 00:00:01\nActual Rows: 0"],+ children: [],+ },+ ],+ },+ ],+ };+}++const columns = EXPLAIN_PLAN_EXPORT_COLUMN_KEYS.map((key) => en.explain[key.slice("explain.".length) as keyof typeof en.explain]);+const diagramLabels = {+ cost: "Cost",+ estimatedRows: "Estimated rows",+ legendHeat: "Cost heat",+ legendEdge: "Edge thickness = estimated rows",+};++beforeEach(() => {+ vi.clearAllMocks();+ mocks.desktop.mockReturnValue(false);+ mocks.raster.mockResolvedValue(new Blob(["png"], { type: "image/png" }));+ mocks.saveText.mockResolvedValue(true);+ mocks.saveBinary.mockResolvedValue(true);+});++describe("Explain Plan Summary export", () => {+ it("preserves all six Summary columns, hierarchy, native values and full details", () => {+ expect(columns).toEqual(["Node", "Table", "Index", "Cost", "Rows", "Details"]);+ const plan = fixture();+ plan.nodes.push({ id: "0", title: "SECOND ROOT", nodeType: "RESULT", details: [], children: [] });+ expect(explainPlanExportRows(plan.nodes, "Estimated time")).toEqual([+ ["SELECT STATEMENT", "-", "-", "148 (0)", "0", "-"],+ [" INDEX RANGE SCAN", "用户", "IDX_USERS", "0.29..1830.12", "96M", "Estimated time: 12 µs; Predicate: name = 'a,\"b\"' AND x < 4; Time: 00:00:01\nActual Rows: 0"],+ ["SECOND ROOT", "-", "-", "-", "-", "-"],+ ]);+ });++ it.each(["html", "csv", "xlsx"] as const)("sends the same complete Summary to the %s writer in the web runtime", async (format) => {+ const plan = fixture();+ const rows = explainPlanExportRows(plan.nodes, "Estimated time");+ expect(await saveExplainPlanExport(plan, format, columns, "Estimated time", "Explain Plan")).toBe(true);+ expect(mocks.save).not.toHaveBeenCalled();+ if (format === "html") expect(mocks.html).toHaveBeenCalledWith("explain-plan-oracle.html", "Explain Plan", columns, rows);+ if (format === "csv") expect(mocks.csv).toHaveBeenCalledWith("explain-plan-oracle.csv", columns, rows, "all", "\\N");+ if (format === "xlsx") expect(mocks.xlsx).toHaveBeenCalledWith("explain-plan-oracle.xlsx", "Explain Plan", columns, Array(6).fill("TEXT"), undefined, rows);+ });++ it("saves a complete standalone SVG diagram", async () => {+ expect(await saveExplainPlanExport(fixture(), "svg", columns, "Estimated time", "Explain Plan · ORACLE", diagramLabels)).toBe(true);++ expect(mocks.saveText).toHaveBeenCalledTimes(1);+ const [path, svg, format] = mocks.saveText.mock.calls[0] as [string, string, string];+ expect(path).toBe("explain-plan-oracle.svg");+ expect(format).toBe("svg");+ expect(svg).toContain('class="plan-node"');+ expect(svg).toContain("INDEX RANGE SCAN");+ expect(svg).toContain("Estimated rows");+ });++ it("rasterizes the same complete SVG before saving PNG", async () => {+ const png = new Blob(["png"], { type: "image/png" });+ mocks.raster.mockResolvedValueOnce(png);+ expect(await saveExplainPlanExport(fixture(), "png", columns, "Estimated time", "Explain Plan · ORACLE", diagramLabels)).toBe(true);++ expect(mocks.raster).toHaveBeenCalledTimes(1);+ expect(mocks.raster.mock.calls[0][0]).toContain('class="plan-node"');+ expect(mocks.raster).toHaveBeenCalledWith(expect.any(String), 2);+ expect(mocks.saveBinary).toHaveBeenCalledWith("explain-plan-oracle.png", png, "png");+ });++ it("does not report a saved SVG when its save dialog is canceled", async () => {+ mocks.saveText.mockResolvedValueOnce(false);+ expect(await saveExplainPlanExport(fixture(), "svg", columns, "Estimated time", "Explain Plan", diagramLabels)).toBe(false);+ });++ it("does not write a file when the desktop save dialog is canceled", async () => {+ mocks.desktop.mockReturnValue(true);+ mocks.save.mockResolvedValueOnce(null);+ expect(await saveExplainPlanExport(fixture(), "csv", columns, "Estimated time", "Explain Plan")).toBe(false);+ expect(mocks.csv).not.toHaveBeenCalled();+ });++ it("keeps the original snapshot when the plan changes while choosing a path", async () => {+ mocks.desktop.mockReturnValue(true);+ const plan = fixture();+ mocks.save.mockImplementationOnce(async () => {+ plan.nodes[0].title = "NEW QUERY";+ plan.nodes[0].children = [];+ return "C:\\exports\\plan.html";+ });+ await saveExplainPlanExport(plan, "html", columns, "Estimated time", "Explain Plan");+ const exportedRows = mocks.html.mock.calls[0][3];+ expect(exportedRows).toHaveLength(2);+ expect(exportedRows[0][0]).toBe("SELECT STATEMENT");+ expect(mocks.html.mock.calls[0][0]).toBe("C:\\exports\\plan.html");+ });++ it("propagates writer failures for the viewer to report", async () => {+ mocks.xlsx.mockRejectedValueOnce(new Error("Disk full"));+ await expect(saveExplainPlanExport(fixture(), "xlsx", columns, "Estimated time", "Explain Plan")).rejects.toThrow("Disk full");++ mocks.raster.mockRejectedValueOnce(new Error("Canvas unsupported"));+ await expect(saveExplainPlanExport(fixture(), "png", columns, "Estimated time", "Explain Plan", diagramLabels)).rejects.toThrow("Canvas unsupported");+ });++ it("does not export an empty parsed plan", async () => {+ expect(await saveExplainPlanExport({ databaseType: "oracle", raw: "unparsed", nodes: [] }, "html", columns, "Estimated time", "Explain Plan")).toBe(false);+ expect(mocks.html).not.toHaveBeenCalled();+ expect(mocks.save).not.toHaveBeenCalled();+ expect(mocks.saveText).not.toHaveBeenCalled();+ expect(mocks.saveBinary).not.toHaveBeenCalled();+ });+});diff --git a/apps/desktop/src/lib/export/__tests__/explainPlanSvgExport.spec.ts b/apps/desktop/src/lib/export/__tests__/explainPlanSvgExport.spec.tsnew file mode 100644index 0000000000..899f7e36fa--- /dev/null+++ b/apps/desktop/src/lib/export/__tests__/explainPlanSvgExport.spec.ts@@ -0,0 +1,82 @@+import { DOMParser } from "@xmldom/xmldom";+import { describe, expect, it } from "vitest";+import type { ExplainPlanNode } from "@/lib/diagram/explainPlan";+import { buildPlanCanvas } from "@/lib/diagram/planCanvas";+import { buildExplainPlanSvg } from "../explainPlanSvgExport";++function planNode(node: Partial<ExplainPlanNode> & { id: string; nodeType: string }): ExplainPlanNode {+ return { title: node.nodeType, details: [], children: [], ...node };+}++function fixture(): ExplainPlanNode[] {+ return [+ planNode({+ id: "0",+ nodeType: "SELECT <STATEMENT>",+ title: "SELECT <STATEMENT>",+ cost: "148 (0)",+ rows: "10",+ children: [+ planNode({+ id: "1",+ nodeType: "INDEX RANGE SCAN",+ relation: "users & roles",+ index: 'IDX_"USERS"',+ cost: "0.29..1830.12",+ rows: "96M",+ details: ["Predicate: name = 'A&B'"],+ }),+ ],+ }),+ planNode({ id: "0", nodeType: "SECOND ROOT", cost: "2", rows: "1" }),+ ];+}++const labels = {+ title: "Explain Plan · ORACLE",+ cost: "Cost",+ estimatedRows: "Estimated rows",+ legendHeat: "Cost heat",+ legendEdge: "Edge thickness = estimated rows",+};++describe("buildExplainPlanSvg", () => {+ it("renders every root, child and edge into a standalone SVG", () => {+ const nodes = fixture();+ const layout = buildPlanCanvas(nodes);+ const svg = buildExplainPlanSvg(nodes, labels);+ const document = new DOMParser().parseFromString(svg, "image/svg+xml");+ const root = document.documentElement;++ expect(root.tagName).toBe("svg");+ expect(root.getAttribute("xmlns")).toBe("http://www.w3.org/2000/svg");+ expect(Number(root.getAttribute("width"))).toBeGreaterThanOrEqual(layout.width);+ expect(Number(root.getAttribute("height"))).toBeGreaterThan(layout.height);+ expect(document.getElementsByTagName("parsererror")).toHaveLength(0);+ expect(svg.match(/class="plan-node"/g)).toHaveLength(3);+ expect(svg.match(/<path d="M .* H .* V .* H /g)).toHaveLength(1);+ expect(svg).toContain("Explain Plan · ORACLE");+ expect(svg).toContain("Estimated rows");+ expect(svg).toContain("Edge thickness = estimated rows");+ });++ it("escapes engine text and uses only rasterizable SVG primitives", () => {+ const svg = buildExplainPlanSvg(fixture(), labels);++ expect(svg).toContain("SELECT <STATEMENT>");+ expect(svg).toContain("users & roles");+ expect(svg).toContain("IDX_"USERS"");+ expect(svg).toContain("A&B");+ expect(svg).not.toContain("<foreignObject");+ expect(svg).not.toContain("var(--");+ });++ it("preserves engine-native values in node tooltips", () => {+ const svg = buildExplainPlanSvg(fixture(), labels);++ expect(svg).toContain("148 (0)");+ expect(svg).toContain("0.29..1830.12");+ expect(svg).toContain("96M");+ expect(svg).toContain("Predicate: name = 'A&B'");+ });+});diff --git a/apps/desktop/src/lib/export/diagramSvgExport.ts b/apps/desktop/src/lib/export/diagramSvgExport.tsindex ccc118e571..3433e82721 100644--- a/apps/desktop/src/lib/export/diagramSvgExport.ts+++ b/apps/desktop/src/lib/export/diagramSvgExport.ts@@ -3,6 +3,7 @@ import { isDroppedColumn, type DiagramPosition, type DiagramRelationship, type Dimport { pickHandles } from "@/lib/diagram/vue-flow-adapter";import { pointAlongPolyline, pointsToSvgPath, type Point } from "@/lib/diagram/edge-obstacle-router";import { CARD_WIDTH, COMMENT_LINE_HEIGHT, MARGIN, diagramTableCardHeight, tableCardHeight, type DiagramCardMetrics } from "@/lib/diagram/diagram-constants";+import { escapeXml, svgNumber, svgText } from "./svgPrimitives";const SOURCE_CARDINALITY_T = 0.18;const TARGET_CARDINALITY_T = 0.82;@@ -66,14 +67,6 @@ export interface TableDiagramSvgOptions {layers?: DiagramSvgLayer[];}-function escapeXml(value: string | number): string {- return String(value).replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");-}--function svgNumber(value: number): string {- return Number.isInteger(value) ? String(value) : value.toFixed(2).replace(/\.?0+$/, "");-}-function svgHeader(canvas: DiagramCanvas): string {// Always viewBox 0 0 — callers that use non-zero canvas.origin must translate content (see buildTableDiagramSvg).return [@@ -82,26 +75,6 @@ function svgHeader(canvas: DiagramCanvas): string {].join("");}-function svgText(- label: string,- x: number,- y: number,- options: {- size?: number;- fill?: string;- weight?: string;- anchor?: "start" | "middle" | "end";- family?: string;- decoration?: string;- } = {},-): string {- const attrs = [`x="${svgNumber(x)}"`, `y="${svgNumber(y)}"`, `fill="${options.fill ?? "#18181b"}"`, `font-size="${options.size ?? 12}"`, `font-family="${options.family ?? "Arial, Helvetica, sans-serif"}"`, 'dominant-baseline="middle"'];- if (options.weight) attrs.push(`font-weight="${options.weight}"`);- if (options.anchor) attrs.push(`text-anchor="${options.anchor}"`);- if (options.decoration) attrs.push(`text-decoration="${options.decoration}"`);- return `<text ${attrs.join(" ")}>${escapeXml(label)}</text>`;-}-function isForeignKeyColumn(table: DiagramTable, columnName: string): boolean {return table.foreignKeys.some((fk) => fk.column === columnName);}diff --git a/apps/desktop/src/lib/export/explainPlanExport.ts b/apps/desktop/src/lib/export/explainPlanExport.tsnew file mode 100644index 0000000000..5c616f04ec--- /dev/null+++ b/apps/desktop/src/lib/export/explainPlanExport.ts@@ -0,0 +1,74 @@+import type { ExplainPlanNode, ParsedExplainPlan } from "@/lib/diagram/explainPlan";+import { formatExplainPlanDetails } from "@/lib/diagram/explainPlan";+import * as api from "@/lib/backend/api";+import { isTauriRuntime } from "@/lib/backend/tauriRuntime";+import { useSettingsStore } from "@/stores/settingsStore";+import { csvNullLiteralForMode } from "./csvNullMode";+import { svgToPngBlob } from "./diagramFormats";+import { buildExplainPlanSvg, type ExplainPlanSvgLabels } from "./explainPlanSvgExport";+import { promptExportSavePath } from "./exportPath";+import { saveDiagramBinaryExport, saveDiagramTextExport } from "./saveDiagramExport";++export type ExplainPlanExportFormat = "svg" | "png" | "html" | "csv" | "xlsx";++export type ExplainPlanDiagramExportLabels = Omit<ExplainPlanSvgLabels, "title">;++export const EXPLAIN_PLAN_EXPORT_COLUMN_KEYS = ["explain.node", "explain.relation", "explain.index", "explain.cost", "explain.rows", "explain.details"] as const;++/** Export the complete Summary, including children hidden by the current view. */+export function explainPlanExportRows(nodes: ExplainPlanNode[], estimatedTimeLabel: string): string[][] {+ const rows: string[][] = [];+ function visit(node: ExplainPlanNode, depth: number) {+ rows.push([`${" ".repeat(depth)}${node.title}`, node.relation || "-", node.index || "-", node.cost || "-", node.rows || "-", formatExplainPlanDetails(node, estimatedTimeLabel).join("; ") || "-"]);+ node.children.forEach((child) => visit(child, depth + 1));+ }+ nodes.forEach((node) => visit(node, 0));+ return rows;+}++export async function saveExplainPlanExport(plan: ParsedExplainPlan, format: ExplainPlanExportFormat, columns: string[], estimatedTimeLabel: string, title: string, diagramLabels?: ExplainPlanDiagramExportLabels): Promise<boolean> {+ // Materialize before awaiting the save dialog: another query may replace the plan.+ const rows = explainPlanExportRows(plan.nodes, estimatedTimeLabel);+ if (!rows.length) return false;+ const defaultPath = `explain-plan-${plan.databaseType}.${format}`;+ if (format === "svg" || format === "png") {+ const svg = buildExplainPlanSvg(plan.nodes, {+ title,+ cost: diagramLabels?.cost ?? "Cost",+ estimatedRows: diagramLabels?.estimatedRows ?? "Estimated rows",+ legendHeat: diagramLabels?.legendHeat ?? "Cost heat",+ legendEdge: diagramLabels?.legendEdge ?? "Edge thickness = estimated rows",+ });+ if (format === "svg") return saveDiagramTextExport(defaultPath, svg, "svg");+ const png = await svgToPngBlob(svg, 2);+ return saveDiagramBinaryExport(defaultPath, png, "png");+ }++ const { csvQuoteMode, csvNullMode } = useSettingsStore().editorSettings;+ let path = defaultPath;+ if (isTauriRuntime()) {+ const selectedPath = await promptExportSavePath({+ defaultFileName: path,+ filters: [{ name: format.toUpperCase(), extensions: [format] }],+ });+ if (!selectedPath) return false;+ path = selectedPath;+ }++ if (format === "csv") {+ await api.exportQueryResultCsv(path, columns, rows, csvQuoteMode, csvNullLiteralForMode(csvNullMode));+ } else if (format === "xlsx") {+ // Keep engine-native costs/rows (e.g. "148 (0)" and "0.29..1830.12") as text.+ await api.exportQueryResultXlsx(+ path,+ "Explain Plan",+ columns,+ columns.map(() => "TEXT"),+ undefined,+ rows,+ );+ } else {+ await api.exportQueryResultHtml(path, title, columns, rows);+ }+ return true;+}diff --git a/apps/desktop/src/lib/export/explainPlanSvgExport.ts b/apps/desktop/src/lib/export/explainPlanSvgExport.tsnew file mode 100644index 0000000000..f0965f5360--- /dev/null+++ b/apps/desktop/src/lib/export/explainPlanSvgExport.ts@@ -0,0 +1,112 @@+import type { ExplainPlanNode } from "@/lib/diagram/explainPlan";+import type { PlanCanvasCategory } from "@/lib/diagram/planCanvas";+import { buildPlanCanvas, edgeStrokeWidth, formatPlanRows, heatLevel, PLAN_CATEGORY_COLORS, PLAN_CANVAS_GAP_X, PLAN_CANVAS_NODE_H, PLAN_CANVAS_NODE_W } from "@/lib/diagram/planCanvas";+import { escapeXml, svgNumber, svgText } from "./svgPrimitives";++const HEADER_HEIGHT = 36;+const LEGEND_HEIGHT = 42;+const MIN_EXPORT_WIDTH = 600;++const CATEGORY_COLORS: Record<PlanCanvasCategory, string> = PLAN_CATEGORY_COLORS;++const HEAT_COLORS = {+ none: "#71717a",+ cool: "#22c55e",+ warm: "#f59e0b",+ hot: "#ef4444",+} as const;++export interface ExplainPlanSvgLabels {+ title: string;+ cost: string;+ estimatedRows: string;+ legendHeat: string;+ legendEdge: string;+}++function truncate(value: string, limit: number): string {+ const characters = Array.from(value);+ return characters.length <= limit ? value : `${characters.slice(0, Math.max(1, limit - 1)).join("")}…`;+}++function nodeTooltip(node: ExplainPlanNode, labels: ExplainPlanSvgLabels): string {+ return [node.title, node.relation ?? "", node.index ?? "", node.cost ? `${labels.cost}: ${node.cost}` : "", node.rows ? `${labels.estimatedRows}: ${node.rows}` : "", ...node.details].filter(Boolean).join("\n");+}++/** Build a standalone, theme-independent SVG for the complete Explain Plan. */+export function buildExplainPlanSvg(nodes: ExplainPlanNode[], labels: ExplainPlanSvgLabels): string {+ const layout = buildPlanCanvas(nodes);+ const width = Math.max(layout.width, MIN_EXPORT_WIDTH);+ const height = HEADER_HEIGHT + layout.height + LEGEND_HEIGHT;+ const parts: string[] = [+ `<svg xmlns="http://www.w3.org/2000/svg" width="${svgNumber(width)}" height="${svgNumber(height)}" viewBox="0 0 ${svgNumber(width)} ${svgNumber(height)}">`,+ `<title>${escapeXml(labels.title)}</title>`,+ '<defs><pattern id="explain-plan-grid" width="28" height="28" patternUnits="userSpaceOnUse"><path d="M 28 0 L 0 0 0 28" fill="none" stroke="#e4e4e7" stroke-width="1"/></pattern></defs>',+ `<rect width="${svgNumber(width)}" height="${svgNumber(height)}" fill="#fafafa"/>`,+ `<rect y="${HEADER_HEIGHT}" width="${svgNumber(width)}" height="${svgNumber(layout.height)}" fill="url(#explain-plan-grid)"/>`,+ svgText(labels.title, 18, HEADER_HEIGHT / 2, { size: 13, weight: "700" }),+ `<path d="M 0 ${HEADER_HEIGHT} H ${svgNumber(width)}" stroke="#d4d4d8"/>`,+ `<g transform="translate(0 ${HEADER_HEIGHT})">`,+ '<g class="plan-edges" fill="none" stroke="#71717a" stroke-linejoin="round" stroke-linecap="round">',+ ];++ for (const edge of layout.edges) {+ 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;+ const path = `M ${svgNumber(startX)} ${svgNumber(startY)} H ${svgNumber(elbowX)} V ${svgNumber(endY)} H ${svgNumber(edge.to.x)}`;+ const edgeLabel = formatPlanRows(edge.rows);+ parts.push(`<path d="${path}" stroke-width="${svgNumber(edgeStrokeWidth(edge.rows))}"><title>${escapeXml(`${edge.from.node.title} → ${edge.to.node.title}: ${edgeLabel}`)}</title></path>`);+ parts.push(`<text x="${svgNumber(edge.to.x - 8)}" y="${svgNumber(endY - 8)}" text-anchor="end" fill="#52525b" stroke="#fafafa" stroke-width="3" paint-order="stroke" font-size="10" font-family="Menlo, Consolas, monospace">${escapeXml(edgeLabel)}</text>`);+ }+ parts.push("</g>");++ layout.nodes.forEach((item, index) => {+ const { node } = item;+ const heat = heatLevel(item.costShare);+ const heatColor = HEAT_COLORS[heat];+ const categoryColor = CATEGORY_COLORS[item.category];+ const operation = node.nodeType || node.title;+ const objectName = [node.relation, node.index ? `[${node.index}]` : ""].filter(Boolean).join(" ");+ const share = item.costShare === undefined ? "" : `${(item.costShare * 100).toFixed(1)}%`;+ const titleLimit = share ? 21 : 28;+ const x = item.x;+ const y = item.y;++ parts.push(`<g class="plan-node" data-node-index="${index}" transform="translate(${svgNumber(x)} ${svgNumber(y)})">`);+ parts.push(`<title>${escapeXml(nodeTooltip(node, labels))}</title>`);+ parts.push(`<rect width="${PLAN_CANVAS_NODE_W}" height="${PLAN_CANVAS_NODE_H}" rx="8" fill="#ffffff" stroke="#d4d4d8"/>`);+ parts.push(`<path d="M 3 8 V ${PLAN_CANVAS_NODE_H - 8}" stroke="${heatColor}" stroke-width="3" stroke-linecap="round"/>`);+ parts.push(`<rect x="12" y="9" width="20" height="20" rx="5" fill="${categoryColor}" fill-opacity="0.18"/>`);+ parts.push(`<circle cx="22" cy="19" r="4" fill="${categoryColor}"/>`);+ parts.push(svgText(truncate(operation, titleLimit), 39, 19, { size: 12, weight: "700" }));+ if (share) {+ parts.push(`<rect x="166" y="10" width="36" height="18" rx="4" fill="${heatColor}" fill-opacity="0.14"/>`);+ parts.push(svgText(share, 184, 19, { size: 9, fill: heatColor, weight: "700", anchor: "middle", family: "Menlo, Consolas, monospace" }));+ }+ parts.push(svgText(objectName ? truncate(objectName, 32) : " ", 12, 43, { size: 10, fill: "#52525b", family: "Menlo, Consolas, monospace" }));+ parts.push(svgText(`${truncate(labels.estimatedRows, 15)} ${formatPlanRows(item.rows)}`, 12, 62, { size: 10, fill: "#52525b", family: "Menlo, Consolas, monospace" }));+ parts.push(svgText(`${truncate(labels.cost, 8)} ${truncate(node.cost || "—", 13)}`, 202, 62, { size: 10, fill: "#52525b", anchor: "end", family: "Menlo, Consolas, monospace" }));+ parts.push("</g>");+ });++ parts.push("</g>");+ const legendY = HEADER_HEIGHT + layout.height + LEGEND_HEIGHT / 2;+ parts.push(`<path d="M 0 ${HEADER_HEIGHT + layout.height} H ${svgNumber(width)}" stroke="#d4d4d8"/>`);+ parts.push(svgText(labels.legendHeat, 18, legendY, { size: 10, fill: "#52525b" }));+ let legendX = 18 + Math.min(150, Math.max(65, Array.from(labels.legendHeat).length * 6));+ for (const [color, label] of [+ [HEAT_COLORS.cool, "< 5%"],+ [HEAT_COLORS.warm, "5–20%"],+ [HEAT_COLORS.hot, "> 20%"],+ ] as const) {+ parts.push(`<rect x="${svgNumber(legendX)}" y="${svgNumber(legendY - 5)}" width="10" height="10" rx="2" fill="${color}"/>`);+ parts.push(svgText(label, legendX + 15, legendY, { size: 10, fill: "#52525b" }));+ legendX += 65;+ }+ parts.push(svgText(labels.legendEdge, legendX + 8, legendY, { size: 10, fill: "#52525b" }));+ parts.push(`<path d="M ${svgNumber(legendX + 8 + Math.min(120, Array.from(labels.legendEdge).length * 6) + 10)} ${svgNumber(legendY)} h 28" stroke="#71717a" stroke-width="4" stroke-linecap="round"/>`);+ parts.push("</svg>");+ return parts.join("");+}diff --git a/apps/desktop/src/lib/export/svgPrimitives.ts b/apps/desktop/src/lib/export/svgPrimitives.tsnew file mode 100644index 0000000000..e557230c15--- /dev/null+++ b/apps/desktop/src/lib/export/svgPrimitives.ts@@ -0,0 +1,29 @@+/** Shared low-level SVG string primitives for diagram-style exports. */++export function escapeXml(value: string | number): string {+ return String(value).replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");+}++export function svgNumber(value: number): string {+ return Number.isInteger(value) ? String(value) : value.toFixed(2).replace(/\.?0+$/, "");+}++export function svgText(+ label: string,+ x: number,+ y: number,+ options: {+ size?: number;+ fill?: string;+ weight?: string;+ anchor?: "start" | "middle" | "end";+ family?: string;+ decoration?: string;+ } = {},+): string {+ const attrs = [`x="${svgNumber(x)}"`, `y="${svgNumber(y)}"`, `fill="${options.fill ?? "#18181b"}"`, `font-size="${options.size ?? 12}"`, `font-family="${options.family ?? "Arial, Helvetica, sans-serif"}"`, 'dominant-baseline="middle"'];+ if (options.weight) attrs.push(`font-weight="${options.weight}"`);+ if (options.anchor) attrs.push(`text-anchor="${options.anchor}"`);+ if (options.decoration) attrs.push(`text-decoration="${options.decoration}"`);+ return `<text ${attrs.join(" ")}>${escapeXml(label)}</text>`;+}