feat(explain): add plan canvas with actual execution plans

This commit is contained in:
Fernando Possebon authored and GitHub committed 2026-08-03 03:06:36 +08:00
1 parent cc7b2b17c5
commit ed1e36912c
28 files changed
+2281 -43

No files matched your search

@@ -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");
});
});
@@ -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 });
});
});
+1 -1
View File
@@ -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", {
+3 -1
View File
@@ -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 {
@@ -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");
});
});
+91 -4
View File
@@ -29,8 +29,9 @@ export function supportsExplainPlan(databaseType?: DatabaseType): databaseType i
return !!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): Ex
const 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): Ex
cost: [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,
};
}
+164
View File
@@ -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));
}