Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

feat(sql-editor): open query plans on the costliest operator (#21652)

Danny Xu3bfc536da788
diff --git a/docs/design/query-plan-visualizer.md b/docs/design/query-plan-visualizer.md
index 8be5087cce..2bd2ccce9f 100644
--- a/docs/design/query-plan-visualizer.md
+++ b/docs/design/query-plan-visualizer.md
@@ -239,7 +239,7 @@ twice. There, Plan shows the plan as text, and nothing else.
includes its children and is reported per loop, so ranking the raw number
just finds the root. Subtract the children and multiply out the loops, per
engine — which is what the model already does for estimates by ranking
- `selfCost` (`plan-model.ts:467-468`), and the measured side has to match it
+ `selfCost` (`planCostliestNodes`), and the measured side has to match it
before any percentage or opening zoom is shown.
2. **Graph** — opens zoomed on the costliest operator, not the root; long
single-child chains fold into one box with a count. Nodes show their share of
@@ -266,23 +266,24 @@ twice. There, Plan shows the plan as text, and nothing else.
The pane is already big enough: [#21459](https://github.com/bytebase/bytebase/pull/21459)
shipped Maximize, a remembered height and the sidebar stepping aside.
-**What changes from today's viewer.** The pop-up page offers five tabs —
-Diagram, Grid, Summary, Raw plan, Query. Five tabs for one plan is three too
-many: Summary is the answer most readers want and should not be hidden behind a
-tab, and Query duplicates the editor they came from.
+**What changes from the pop-up viewer.** The pop-up page offered five tabs —
+Diagram, Grid, Summary, Raw plan, Query. Five tabs for one plan is two too many:
+Summary is the answer most readers want and should not be hidden behind a tab,
+and Query duplicates what the result pane already shows.
-| Today | Becomes |
+| Pop-up | Becomes |
|---|---|
-| Diagram | **Graph**, opening on the costliest operator instead of the root |
+| Diagram | **Diagram**, the tab the viewer opens on, centered on the costliest operator instead of the root, which starts selected |
| Grid | **Table** |
-| Summary (tab, only when the plan has costs) | **always-visible panel** beside the graph |
-| Raw plan | the **Text** tab, beside Plan |
-| Query | becomes a **View SQL** disclosure in the Plan view |
+| Summary (tab, only when the plan has costs) | the three costliest operators, ranked, at the top of the **side panel** beside the diagram and the table; the cost timeline and per-operation table are dropped |
+| Raw plan | the **Text** tab |
+| Query | dropped: the result pane's status bar shows the statement that ran, limit and all, with a copy control |
-View SQL is not a tooltip. The editor may have moved on since the result was
-produced, so the statement a plan belongs to has to be readable somewhere — and
-selectable and copyable, which a hover tooltip is not, least of all for a long
-statement.
+The statement a plan belongs to still has to be readable, selectable and
+copyable, because the editor may have moved on since the result was produced.
+The status bar under the Plan view already does that, so the viewer does not
+repeat it. What the diagram's bars and edges encode is a hover away on the
+totals line rather than a line of its own, since the result pane is short.
The view switch's choice — Table, Vertical, Plan or Text — is remembered per
editor tab, like the result pane's height, so comparing two runs does not mean
@@ -350,7 +351,7 @@ ordinary query with the result limit but skips that wrapper on the explain path
(`pg.go:801-809`), so explaining the original text would plan an unbounded query
when the user ran a bounded one — and PostgreSQL plans for `LIMIT`, so the two
differ, not just in cost but in shape. The plan request and its cache carry the
-executed statement and its connection context, and View SQL shows that statement,
+executed statement and its connection context, and the status bar shows that statement,
limit and all. The estimate badge is about statistics moving; it must not quietly
cover a different query.
@@ -391,8 +392,8 @@ would fail queries the user is authorized to run. Profiling only when asked
requires a control that says so before the run, which is a second explain action
on the Run button for a case **Explain analyze** already covers. Out of scope.
-Once the Plan view matches the pop-up page, delete the page, its token hand-off
-and the old link.
+The pop-up page, its token hand-off and the old link are deleted
+([#21652](https://github.com/bytebase/bytebase/pull/21652)).
### 3.5 Permissions, masking and limits
@@ -521,7 +522,7 @@ live servers, September 2026.
## 6. Status
-Checked against `main` on 2026-10-23.
+Checked against `main` on 2026-10-23, after [#21652](https://github.com/bytebase/bytebase/pull/21652).
**Landed**
@@ -553,12 +554,16 @@ Checked against `main` on 2026-10-23.
choice remembered per editor tab
([#21646](https://github.com/bytebase/bytebase/pull/21646)).
+- §3.3/§3.4 — the viewer opens on the diagram, centered on the costliest
+ operator; three tabs (Diagram, Table, Text) instead of five; the costliest
+ operators ranked in the side panel; the legend on hover; the pop-up page
+ deleted ([#21652](https://github.com/bytebase/bytebase/pull/21652)). The
+ ranking and the opening view use estimated cost and say so; ranking a
+ measured plan by measured time waits for measured plans, item 2 below.
+
**Not yet, in the order to do them**
1. §3.1 — Explain and Explain analyze in the Run dropdown, planning the limited
statement; today every driver's explain path skips the limit.
-2. §3.3 — the reading changes: summary panel always visible, graph opening on
- the costliest operator, View SQL, warning relevance, measured plans with
- planned vs actual rows, cost share on the tab label.
-3. §3.4 — delete the pop-up page (`frontend/explain-visualizer.html`), which
- nothing links to any more.
+2. §3.3 — the rest of the reading changes: warning relevance, measured plans
+ with planned vs actual rows, cost share on the tab label.
diff --git a/frontend/AGENTS.md b/frontend/AGENTS.md
index 8fc3d2869e..4c9e456df6 100644
--- a/frontend/AGENTS.md
+++ b/frontend/AGENTS.md
@@ -13,7 +13,7 @@ This file provides additional guidance to AI coding assistants working under `./
- All user-facing UI text belongs in `src/locales/` and is consumed through `useTranslation()` from `react-i18next`.
- Locale files must not contain empty JSON objects; remove them when encountered.
-- `src/apps/explain-visualizer/` is exempt and writes its text inline: the entry never initializes i18n, and doing so would pull every locale bundle into a standalone page that today ships 208 KB. Number formatting there is pinned to `en-US` for the same reason. Text in the main app that merely refers to the visualizer, such as the SQL editor's failure toasts, still belongs in `src/locales/`.
+- The query plan viewer in `src/apps/explain-visualizer/` takes its text through a `translate` prop, which the SQL Editor fills from `sql-editor.query-plan-viewer.*` in `src/locales/`; `plan-i18n.tsx` holds the English defaults. Number formatting there is pinned to `en-US`.
## UX contract
@@ -42,7 +42,7 @@ Use route ownership as the primary organization axis. Do not add a generic `feat
| `src/hooks/` and `src/lib/` | Cross-cutting hooks and framework-neutral helpers only |
| `src/types/` and `src/utils/` | Existing cross-module contracts and compatibility utilities; prefer owner-local code for new work |
| `src/types/proto-es/` | Generated protobuf output; do not edit manually |
-| `src/apps/explain-visualizer/` | Isolated secondary entrypoint for the query-plan viewer opened in its own tab |
+| `src/apps/explain-visualizer/` | The query plan viewer the SQL Editor result pane renders |
### Placement and dependency rules
@@ -52,7 +52,6 @@ Use route ownership as the primary organization axis. Do not add a generic `feat
- Put a large reusable workflow in `src/modules/<name>/`; do not spread one subsystem across `components` and `stores`.
- Shared code and modules must not import from `src/routes/`. Move the shared implementation to its actual owner instead.
- Prefer direct owner imports such as `@/modules/sql-editor/store` over broad barrels when the owner is known.
-- `src/apps/explain-visualizer/` must not use primitives backed by `styles.stylex.ts`. The build appends StyleX's rules to the main app's CSS asset only (`cssInjectionTarget` in `vite.config.ts`), so a StyleX-sized control renders unstyled in that entry.
- Historical migration plans under `docs/` describe old paths and are not current architecture guidance.
- `CLAUDE.md` files only import their adjacent `AGENTS.md`; update `AGENTS.md` as the source of truth.
diff --git a/frontend/explain-visualizer.html b/frontend/explain-visualizer.html
deleted file mode 100644
index 4a1c5c7ea0..0000000000
--- a/frontend/explain-visualizer.html
+++ /dev/null
@@ -1,18 +0,0 @@
-<!DOCTYPE html>
-<html lang="en">
- <head>
- <meta charset="UTF-8" />
- <link rel="icon" type="image/*" href="/favicon.ico" />
- <meta name="viewport" content="width=device-width, initial-scale=1.0" />
- <meta name="color-scheme" content="light only" />
- <title>Bytebase - Query Plan</title>
- </head>
-
- <body class="text-base">
- <div id="app"></div>
- <script
- type="module"
- src="/src/apps/explain-visualizer/main.tsx"
- ></script>
- </body>
-</html>
diff --git a/frontend/scripts/check-ui-guideline.mjs b/frontend/scripts/check-ui-guideline.mjs
index 9751a129df..fbe6d0a0ef 100644
--- a/frontend/scripts/check-ui-guideline.mjs
+++ b/frontend/scripts/check-ui-guideline.mjs
@@ -18,7 +18,6 @@ const sharedPrimitivePrefix = "src/components/ui/";
const lifecycleStampPath =
"src/routes/project/plan-detail/components/lifecycle/LifecycleStamp.tsx";
-const legacyIgnoredPrefixes = ["src/apps/explain-visualizer/"];
const generatedPrefixes = ["src/types/proto-es/"];
const nativeControls = new Set(["button", "input", "select", "textarea"]);
const rawColorFamilies = [
@@ -78,9 +77,6 @@ const cssRadiusPropertyPattern = /^border(?:-[a-z]+)*-radius$/;
const inlineRadiusPropertyPattern = /^border(?:[A-Z][a-z]*)*Radius$/;
const dashedInlineRadiusPropertyPattern = /^border(?:-[a-z]+)*-radius$/;
-const isLegacyIgnoredPath = (path) =>
- legacyIgnoredPrefixes.some((prefix) => path.startsWith(prefix));
-
const isGeneratedPath = (path) =>
generatedPrefixes.some((prefix) => path.startsWith(prefix));
@@ -304,9 +300,6 @@ export function scanSource(source, path) {
const scanTokenValue = (value) => {
for (const token of classTokens(value)) {
for (const rule of rulesForToken(token)) {
- if (isLegacyIgnoredPath(path) && rule !== "no-off-scale-radius") {
- continue;
- }
addViolation(counts, path, rule, token);
}
}
diff --git a/frontend/src/apps/explain-visualizer/ExplainVisualizerApp.test.tsx b/frontend/src/apps/explain-visualizer/ExplainVisualizerApp.test.tsx
deleted file mode 100644
index 95f2b01ee2..0000000000
--- a/frontend/src/apps/explain-visualizer/ExplainVisualizerApp.test.tsx
+++ /dev/null
@@ -1,120 +0,0 @@
-import { render, screen } from "@testing-library/react";
-import type { ReactNode } from "react";
-import { beforeEach, describe, expect, test, vi } from "vitest";
-import { Engine } from "@/types/proto-es/v1/common_pb";
-import { createExplainToken } from "@/utils/explainToken";
-import { ExplainVisualizerApp } from "./ExplainVisualizerApp";
-import { MSSQL_PLAN_INVALID_XML_MESSAGE } from "./mssql-plan";
-import {
- POSTGRES_PLAN_EMPTY_MESSAGE,
- POSTGRES_PLAN_INVALID_JSON_MESSAGE,
-} from "./postgres-plan";
-import indexSeekKeyLookup from "./test-data/mssql/index-seek-key-lookup.xml?raw";
-import cteNestedLoopInitplan from "./test-data/postgres/cte-nested-loop-initplan.json";
-import spannerHashJoin from "./test-data/spanner/hash-join.json";
-
-vi.mock("react-resizable-panels", () => ({
- Group: ({ children }: { children: ReactNode }) => <div>{children}</div>,
- Panel: ({ children }: { children: ReactNode }) => <div>{children}</div>,
- Separator: () => <div />,
-}));
-
-/** Opens the page the way the SQL editor does: a stored plan and its token. */
-const openPlan = (engine: Engine, explain: string, statement = "SELECT 1") => {
- const token = createExplainToken({ engine, explain, statement });
- history.replaceState(null, "", `/explain-visualizer.html?token=${token}`);
- return render(<ExplainVisualizerApp />);
-};
-
-const card = (name: RegExp) =>
- screen
- .getAllByTestId("plan-node-card")
- .find((entry) => name.test(entry.getAttribute("aria-label") ?? ""));
-
-describe("ExplainVisualizerApp", () => {
- beforeEach(() => {
- sessionStorage.clear();
- // jsdom's window exposes no matchMedia under vitest; the viewer queries it
- // to decide whether to stack the detail pane.
- window.matchMedia = ((query: string) => ({
- matches: false,
- media: query,
- onchange: null,
- addEventListener: () => {},
- removeEventListener: () => {},
- addListener: () => {},
- removeListener: () => {},
- dispatchEvent: () => true,
- })) as unknown as typeof window.matchMedia;
- });
-
- test("draws a PostgreSQL plan", () => {
- openPlan(Engine.POSTGRES, JSON.stringify(cteNestedLoopInitplan));
-
- for (const nodeType of [/^Limit/, /^Nested Loop/, /^Index Scan/]) {
- expect(card(nodeType)).toBeDefined();
- }
- expect(screen.getByText("InitPlan 1")).toBeInTheDocument();
- });
-
- test("draws a SQL Server plan in the same viewer", () => {
- openPlan(Engine.MSSQL, indexSeekKeyLookup);
-
- for (const nodeType of [/^SELECT/, /^Index Seek/, /^Key Lookup/]) {
- expect(card(nodeType)).toBeDefined();
- }
- expect(screen.getByRole("tab", { name: "Summary" })).toBeInTheDocument();
- });
-
- test("draws a Spanner plan in the same viewer", () => {
- openPlan(Engine.SPANNER, JSON.stringify(spannerHashJoin));
-
- for (const nodeType of [/^Hash Join/, /^Table Scan/, /^Index Scan/]) {
- expect(card(nodeType)).toBeDefined();
- }
- expect(screen.getByRole("tab", { name: "Diagram" })).toBeInTheDocument();
- });
-
- test("explains a plan it cannot read and still shows what the server returned", () => {
- openPlan(Engine.POSTGRES, "Seq Scan on customers");
-
- expect(screen.getByRole("alert")).toHaveTextContent(
- POSTGRES_PLAN_INVALID_JSON_MESSAGE
- );
- expect(screen.getByText("Seq Scan on customers")).toBeInTheDocument();
- expect(screen.queryByTestId("plan-diagram-viewport")).toBeNull();
- });
-
- test("reads each engine's plan with that engine's parser", () => {
- // Valid JSON, but SQL Server's plan is XML.
- openPlan(Engine.MSSQL, JSON.stringify(cteNestedLoopInitplan));
-
- expect(screen.getByRole("alert")).toHaveTextContent(
- MSSQL_PLAN_INVALID_XML_MESSAGE
- );
- });
-
- test("explains an empty plan without echoing an empty block", () => {
- const { container } = openPlan(Engine.POSTGRES, "");
-
- expect(screen.getByRole("alert")).toHaveTextContent(
- POSTGRES_PLAN_EMPTY_MESSAGE
- );
- expect(container.querySelector("pre")).toBeNull();
- });
-
- test("says the session expired when the plan is no longer stored", () => {
- history.replaceState(null, "", "/explain-visualizer.html?token=explain-gone");
- render(<ExplainVisualizerApp />);
-
- expect(screen.getByRole("alert")).toHaveTextContent("Session expired");
- });
-
- test("turns away an engine the visualizer cannot draw", () => {
- openPlan(Engine.MYSQL, "-> Table scan on t");
-
- expect(screen.getByRole("alert")).toHaveTextContent(
- "Unsupported database engine"
- );
- });
-});
diff --git a/frontend/src/apps/explain-visualizer/ExplainVisualizerApp.tsx b/frontend/src/apps/explain-visualizer/ExplainVisualizerApp.tsx
deleted file mode 100644
index e0af74636a..0000000000
--- a/frontend/src/apps/explain-visualizer/ExplainVisualizerApp.tsx
+++ /dev/null
@@ -1,49 +0,0 @@
-import { parse } from "qs";
-import { useMemo } from "react";
-import { Alert } from "@/components/ui/alert";
-import { isVisualizerEngine, readExplainFromToken } from "@/utils/explainToken";
-import { QueryPlanView } from "./QueryPlanView";
-
-const STATUS_CLASS =
- "flex h-full min-h-0 w-full flex-col gap-4 overflow-auto bg-background p-4";
-
-// Legacy standalone entry; the SQL Editor renders QueryPlanView inline.
-export function ExplainVisualizerApp() {
- const storedQuery = useMemo(() => {
- const query = location.search.replace(/^\?/, "");
- const token = (parse(query).token as string) || "";
- return readExplainFromToken(token);
- }, []);
-
- if (!storedQuery) {
- return (
- <div className={STATUS_CLASS}>
- <Alert
- variant="warning"
- title="Session expired"
- description="Run the statement again to open a fresh query plan."
- />
- </div>
- );
- }
-
- if (!isVisualizerEngine(storedQuery.engine)) {
- return (
- <div className={STATUS_CLASS}>
- <Alert
- variant="warning"
- title="Unsupported database engine"
- description="Query plan visualization is not available for this database engine."
- />
- </div>
- );
- }
-
- return (
- <QueryPlanView
- engine={storedQuery.engine}
- planSource={storedQuery.explain}
- planQuery={storedQuery.statement}
- />
- );
-}
diff --git a/frontend/src/apps/explain-visualizer/PlanCopyButton.tsx b/frontend/src/apps/explain-visualizer/PlanCopyButton.tsx
index 22b883f01a..77b3099dfc 100644
--- a/frontend/src/apps/explain-visualizer/PlanCopyButton.tsx
+++ b/frontend/src/apps/explain-visualizer/PlanCopyButton.tsx
@@ -5,13 +5,7 @@ import { writeTextToClipboard } from "@/lib/clipboard";
import { cn } from "@/lib/utils";
import { useQueryPlanTranslation } from "./plan-i18n";
-/**
- * A copy control that reports the result on itself.
- *
- * The shared `CopyButton` confirms through `useTranslation` and the app store's
- * notifications; this entry initializes neither, so a local button is the whole
- * dependency rather than the app's stores.
- */
+/** A copy control that reports the result on itself. */
interface Props {
/** What to put on the clipboard. */
readonly content: string;
diff --git a/frontend/src/apps/explain-visualizer/QueryPlanDiagram.test.tsx b/frontend/src/apps/explain-visualizer/QueryPlanDiagram.test.tsx
index fb4a55c2d8..88ff995c59 100644
--- a/frontend/src/apps/explain-visualizer/QueryPlanDiagram.test.tsx
+++ b/frontend/src/apps/explain-visualizer/QueryPlanDiagram.test.tsx
@@ -5,7 +5,11 @@ import hashJoinAggregateSort from "./test-data/postgres/hash-join-aggregate-sort
import seqScanFilter from "./test-data/postgres/seq-scan-filter.json";
import spannerHashJoin from "./test-data/spanner/hash-join.json";
import { parseMssqlPlan } from "./mssql-plan";
-import { PLAN_READABLE_SCALE } from "./plan-layout";
+import {
+ layoutPlan,
+ PLAN_READABLE_SCALE,
+ planOpeningViewport,
+} from "./plan-layout";
import {
PLAN_EDGE_MAX_WIDTH,
PLAN_EDGE_MIN_WIDTH,
@@ -345,13 +349,14 @@ describe("QueryPlanDiagram", () => {
expect(screen.getAllByTestId("plan-node-card")).toHaveLength(3);
});
- test("opens a plan too deep to read whole at a readable scale, from its root down", () => {
+ test("opens a plan too deep to read whole at a readable scale, on its costliest operator", () => {
sizeViewport(600, 400);
renderDiagram();
- // Shown whole, this plan would open at about half size.
+ // Shown whole, this plan would open at about half size. Its costliest
+ // operator is below the root, so the view starts scrolled down to it.
expect(scaleNow()).toBe(PLAN_READABLE_SCALE);
- expect(canvasTransform()).toMatch(/translate\([\d.]+px, 0px\)/);
+ expect(canvasTransform()).toMatch(/translate\([\d.-]+px, -[\d.]+px\)/);
expect(screen.getByTestId("plan-mini-map")).toBeInTheDocument();
});
@@ -363,6 +368,32 @@ describe("QueryPlanDiagram", () => {
expect(screen.queryByTestId("plan-mini-map")).toBeNull();
});
+ test("opens on the collapsed card that hides the costliest operator", () => {
+ sizeViewport(300, 150);
+ const plan = tree();
+ const { rerender } = renderDiagram({ tree: plan });
+ // The orders scan, 0.0.0.0, is the costliest; fold its parent away.
+ const collapsed = new Set(["0.0.0"]);
+ rerender(
+ <QueryPlanDiagram
+ tree={plan}
+ selectedId="0.0.0"
+ onSelect={() => undefined}
+ highlight="off"
+ collapsedIds={collapsed}
+ onToggleCollapse={() => undefined}
+ />
+ );
+
+ const layout = layoutPlan(plan.root, collapsed);
+ const size = { width: 300, height: 150 };
+ const onCard = planOpeningViewport(layout, size, "0.0.0");
+ expect(onCard).not.toEqual(planOpeningViewport(layout, size));
+ expect(canvasTransform()).toBe(
+ `translate(${onCard.x}px, ${onCard.y}px) scale(${onCard.scale})`
+ );
+ });
+
test("keeps showing the whole plan after Fit to view when it re-lays out", () => {
sizeViewport(600, 400);
const plan = tree();
diff --git a/frontend/src/apps/explain-visualizer/QueryPlanDiagram.tsx b/frontend/src/apps/explain-visualizer/QueryPlanDiagram.tsx
index 839f6661cb..a664434e51 100644
--- a/frontend/src/apps/explain-visualizer/QueryPlanDiagram.tsx
+++ b/frontend/src/apps/explain-visualizer/QueryPlanDiagram.tsx
@@ -17,8 +17,6 @@ import {
import { Button } from "@/components/ui/button";
import { Tooltip } from "@/components/ui/tooltip";
import { cn } from "@/lib/utils";
-// Deep import: `@/utils` (the barrel) transitively pulls in Monaco, which this
-// standalone entry never loads. `minmax` itself is a leaf math helper.
import { minmax } from "@/utils/math";
import { PLAN_MINI_MAP_BOX, PlanMiniMap } from "./PlanMiniMap";
import { type QueryPlanTranslate, useQueryPlanTranslation } from "./plan-i18n";
@@ -45,6 +43,8 @@ import {
type PlanHighlightMode,
type PlanNode,
type PlanTree,
+ planCollapsedAncestor,
+ planCostliestNodes,
planDescendantCount,
planEdgeWidth,
planHighlightIntensity,
@@ -270,6 +270,14 @@ export function QueryPlanDiagram({
[zoomAt]
);
+ // The diagram opens on the operator that adds the most cost, which is where
+ // reading a slow plan starts. A collapse that hides it takes its place, as it
+ // takes the selection.
+ const costliestId = useMemo(() => planCostliestNodes(tree, 1)[0]?.id, [tree]);
+ const focusId =
+ planCollapsedAncestor(tree.root, collapsedIds, costliestId)?.id ??
+ costliestId;
+
const placeView = useCallback(
(placed: PlacedView) => {
placedViewRef.current = placed;
@@ -277,10 +285,10 @@ export function QueryPlanDiagram({
setView(
placed === "whole"
? planFitViewport(layout, measured)
- : planOpeningViewport(layout, measured)
+ : planOpeningViewport(layout, measured, focusId)
);
},
- [layout, measure]
+ [layout, measure, focusId]
);
const panTo = useCallback((point: { x: number; y: number }) => {
diff --git a/frontend/src/apps/explain-visualizer/QueryPlanGrid.test.tsx b/frontend/src/apps/explain-visualizer/QueryPlanGrid.test.tsx
index 83a36e97d7..ba6b2dfaa9 100644
--- a/frontend/src/apps/explain-visualizer/QueryPlanGrid.test.tsx
+++ b/frontend/src/apps/explain-visualizer/QueryPlanGrid.test.tsx
@@ -246,6 +246,102 @@ describe("QueryPlanGrid", () => {
expect(guideCells(0)).toHaveLength(1);
});
+ test("lines a deep row's guides up with its ancestors' at every depth", () => {
+ // A chain eight levels deep whose head has a sibling after it, so the
+ // head's branch line passes every row of the chain in the first column.
+ const chain = (depth: number): unknown => ({
+ "Node Type": `Level ${depth}`,
+ "Startup Cost": 0,
+ "Total Cost": 1,
+ "Plan Rows": 1,
+ "Plan Width": 1,
+ ...(depth < 8 ? { Plans: [chain(depth + 1)] } : {}),
+ });
+ renderGrid({
+ tree: treeFrom([
+ {
+ Plan: {
+ "Node Type": "Nested Loop",
+ "Startup Cost": 0,
+ "Total Cost": 2,
+ "Plan Rows": 1,
+ "Plan Width": 1,
+ Plans: [
+ chain(1),
+ {
+ "Node Type": "Seq Scan",
+ "Startup Cost": 0,
+ "Total Cost": 1,
+ "Plan Rows": 1,
+ "Plan Width": 1,
+ },
+ ],
+ },
+ },
+ ]),
+ });
+
+ const nodeCells = screen.getAllByTestId("plan-grid-node");
+ const guides = screen.getAllByTestId("plan-grid-guides");
+ for (let depth = 1; depth <= 8; depth++) {
+ expect(nodeCells[depth].style.paddingLeft).toBe(`${depth * 12}px`);
+ const cells = Array.from(guides[depth - 1].children);
+ expect(cells).toHaveLength(depth);
+ // The head's sibling is still to come, so its line runs down column one.
+ expect(cells[0].querySelector(".w-px")).not.toBeNull();
+ // Nothing between the head and the row continues, so no other column
+ // above the row's own elbow draws a line.
+ for (const cell of cells.slice(1, -1)) {
+ expect(cell.querySelector(".w-px")).toBeNull();
+ }
+ }
+ });
+
+ test("narrows every row's indent alike for a very deep plan", () => {
+ const chain = (depth: number): unknown => ({
+ "Node Type": `Level ${depth}`,
+ "Startup Cost": 0,
+ "Total Cost": 1,
+ "Plan Rows": 1,
+ "Plan Width": 1,
+ ...(depth < 30 ? { Plans: [chain(depth + 1)] } : {}),
+ });
+ renderGrid({ tree: treeFrom([{ Plan: chain(0) }]) });
+
+ // Thirty levels at the full step would take 360px of the node column.
+ const nodeCells = screen.getAllByTestId("plan-grid-node");
+ expect(nodeCells[30].style.paddingLeft).toBe("120px");
+ expect(nodeCells[1].style.paddingLeft).toBe("4px");
+ const deepest = screen.getAllByTestId("plan-grid-guides").at(-1);
+ for (const cell of Array.from(deepest?.children ?? [])) {
+ expect((cell as HTMLElement).style.width).toBe("4px");
+ }
+ });
+
+ test("brings the selected row on screen when the selection changes", () => {
+ // jsdom lays nothing out, so it has no scrollIntoView to observe.
+ const scrollIntoView = vi.fn();
+ Element.prototype.scrollIntoView = scrollIntoView;
+ try {
+ const plan = tree();
+ const { rerender } = renderGrid({ tree: plan });
+ const target = rows()[4];
+ rerender(
+ <QueryPlanGrid
+ tree={plan}
+ selectedId={target.dataset.planNodeId}
+ onSelect={() => undefined}
+ />
+ );
+
+ expect(scrollIntoView).toHaveBeenLastCalledWith({ block: "nearest" });
+ expect(scrollIntoView.mock.contexts.at(-1)).toBe(rows()[4]);
+ } finally {
+ // biome-ignore lint/performance/noDelete: restores jsdom's prototype
+ delete (Element.prototype as Partial<Element>).scrollIntoView;
+ }
+ });
+
test("keeps the guides out of the accessibility tree", () => {
renderGrid();
diff --git a/frontend/src/apps/explain-visualizer/QueryPlanGrid.tsx b/frontend/src/apps/explain-visualizer/QueryPlanGrid.tsx
index a391347f57..9fa11e8b1c 100644
--- a/frontend/src/apps/explain-visualizer/QueryPlanGrid.tsx
+++ b/frontend/src/apps/explain-visualizer/QueryPlanGrid.tsx
@@ -1,4 +1,4 @@
-import { memo, useCallback, useMemo } from "react";
+import { memo, useCallback, useEffect, useMemo, useRef } from "react";
import {
Table,
TableBody,
@@ -9,11 +9,7 @@ import {
} from "@/components/ui/table";
import { cn } from "@/lib/utils";
import { useQueryPlanTranslation } from "./plan-i18n";
-import {
- PLAN_INDENT_STEP,
- planGuideLevels,
- planIndentPixels,
-} from "./plan-layout";
+import { planIndentPixels, planIndentStep } from "./plan-layout";
import {
formatPlanCost,
formatPlanCount,
@@ -48,19 +44,20 @@ const GUIDE_LINE_CLASS = "absolute bg-control-border";
*/
function PlanTreeGuides({
branchContinues,
+ step,
}: {
branchContinues: readonly boolean[];
+ step: number;
}) {
- const levels = planGuideLevels(branchContinues);
- if (levels.length === 0) return null;
+ if (branchContinues.length === 0) return null;
return (
<span
aria-hidden="true"
data-testid="plan-grid-guides"
className="pointer-events-none absolute inset-y-0 left-4 flex"
>
- {levels.map((continues, index) => {
- const last = index === levels.length - 1;
+ {branchContinues.map((continues, index) => {
+ const last = index === branchContinues.length - 1;
// Every level but the last is a pass-through: a line only where an
// ancestor still has rows to come. The last level turns into the row,
// so it always arrives from above and carries on only when a sibling
@@ -72,7 +69,7 @@ function PlanTreeGuides({
// A level has no identity apart from its position in the indent.
key={index}
className="relative shrink-0"
- style={{ width: PLAN_INDENT_STEP }}
+ style={{ width: step }}
>
{vertical ? (
<span
@@ -108,6 +105,7 @@ const PlanGridRow = memo(function PlanGridRow({
row: { node, depth, branchContinues },
index,
tree,
+ step,
selected,
tabStop,
onSelect,
@@ -116,6 +114,8 @@ const PlanGridRow = memo(function PlanGridRow({
row: PlanRow;
index: number;
tree: PlanTree;
+ /** The plan's indent step, shared by every row so the guides line up. */
+ step: number;
selected: boolean;
tabStop: boolean;
onSelect: (id: string) => void;
@@ -143,11 +143,11 @@ const PlanGridRow = memo(function PlanGridRow({
</TableCell>
<TableCell className="relative py-2">
- <PlanTreeGuides branchContinues={branchContinues} />
+ <PlanTreeGuides branchContinues={branchContinues} step={step} />
<div
data-testid="plan-grid-node"
className="relative flex min-w-0 items-baseline gap-2"
- style={{ paddingLeft: planIndentPixels(depth) }}
+ style={{ paddingLeft: planIndentPixels(depth, step) }}
>
<span
data-testid="plan-grid-node-type"
@@ -205,6 +205,19 @@ const PlanGridRow = memo(function PlanGridRow({
export function QueryPlanGrid({ tree, selectedId, onSelect }: Props) {
const translate = useQueryPlanTranslation();
const rows = useMemo(() => planRows(tree.root), [tree]);
+ const step = useMemo(
+ () => planIndentStep(Math.max(0, ...rows.map((row) => row.depth))),
+ [rows]
+ );
+ const scrollRef = useRef<HTMLDivElement>(null);
+
+ // The selection can be chosen beside the table, from the ranking or the
+ // diagram, so the table brings it on screen rather than leaving it below.
+ useEffect(() => {
+ scrollRef.current
+ ?.querySelector('[aria-selected="true"]')
+ ?.scrollIntoView?.({ block: "nearest" });
+ }, [selectedId]);
// Roving tab stop: Tab reaches the grid once and the arrow keys move within
// it, rather than making every row of a 30-node plan its own tab stop.
@@ -252,6 +265,7 @@ export function QueryPlanGrid({ tree, selectedId, onSelect }: Props) {
return (
<div
+ ref={scrollRef}
data-testid="plan-grid-scroll"
className="min-h-0 w-full flex-1 overflow-auto"
>
@@ -318,6 +332,7 @@ export function QueryPlanGrid({ tree, selectedId, onSelect }: Props) {
row={row}
index={index}
tree={tree}
+ step={step}
selected={row.node.id === selectedId}
tabStop={row.node.id === tabStopId}
onSelect={onSelect}
diff --git a/frontend/src/apps/explain-visualizer/QueryPlanNodeDetails.tsx b/frontend/src/apps/explain-visualizer/QueryPlanNodeDetails.tsx
index 3dd2db1fff..211f65e0b7 100644
--- a/frontend/src/apps/explain-visualizer/QueryPlanNodeDetails.tsx
+++ b/frontend/src/apps/explain-visualizer/QueryPlanNodeDetails.tsx
@@ -49,18 +49,16 @@ export function QueryPlanNodeDetails({ node }: Props) {
const translate = useQueryPlanTranslation();
if (!node) {
return (
- <div className="flex h-full items-center justify-center p-4">
- <p className="text-sm leading-5 text-control-light">
- {translate("details.select-node")}
- </p>
- </div>
+ <p className="text-sm leading-5 text-control-light">
+ {translate("details.select-node")}
+ </p>
);
}
const metrics = nodeMetrics(node, translate);
return (
- <div className="flex h-full min-h-0 flex-col overflow-auto p-4 gap-4">
+ <div className="flex flex-col gap-4">
<div className="flex flex-col gap-1">
<h2 className="text-base leading-6 font-semibold text-main">
{node.nodeType}
diff --git a/frontend/src/apps/explain-visualizer/QueryPlanSummary.test.tsx b/frontend/src/apps/explain-visualizer/QueryPlanSummary.test.tsx
index dbc3c5c231..0ebc413796 100644
--- a/frontend/src/apps/explain-visualizer/QueryPlanSummary.test.tsx
+++ b/frontend/src/apps/explain-visualizer/QueryPlanSummary.test.tsx
@@ -1,10 +1,7 @@
-import { fireEvent, render, screen, within } from "@testing-library/react";
+import { fireEvent, render, screen } from "@testing-library/react";
import { describe, expect, test, vi } from "vitest";
import mssqlHashJoinAggregateSort from "./test-data/mssql/hash-join-aggregate-sort.xml?raw";
-import twoStatementBatch from "./test-data/mssql/two-statement-batch.xml?raw";
-import cteNestedLoopInitplan from "./test-data/postgres/cte-nested-loop-initplan.json";
import hashJoinAggregateSort from "./test-data/postgres/hash-join-aggregate-sort.json";
-import seqScanFilter from "./test-data/postgres/seq-scan-filter.json";
import { parseMssqlPlan } from "./mssql-plan";
import type { PlanParseResult, PlanTree } from "./plan-model";
import { parsePostgresPlan } from "./postgres-plan";
@@ -54,242 +51,47 @@ const renderSummary = (
return { onSelect, ...render(<QueryPlanSummary {...props} />) };
};
-const timelineRows = () => screen.getAllByTestId("plan-timeline-row");
-const spans = () => screen.getAllByTestId("plan-timeline-span");
-const percentOf = (value: string) => Number.parseFloat(value);
+const rows = () => screen.getAllByTestId("plan-costliest-row");
describe("QueryPlanSummary", () => {
- test("reports the plan's totals and says they are estimates", () => {
- renderSummary();
-
- expect(screen.getByText("Nodes").nextSibling).toHaveTextContent("6");
- expect(
- screen.getByText("Total estimated cost").nextSibling
- ).toHaveTextContent("1,465.93");
- expect(
- screen.getByText("Estimated rows returned").nextSibling
- ).toHaveTextContent("3");
- expect(screen.getByText(/optimizer estimate rather than a measurement/))
- .toBeVisible();
- expect(
- screen.getByText(/comparable only within this plan/)
- ).toBeInTheDocument();
- });
-
- test("plots one timeline row per node, in plan order", () => {
- renderSummary();
-
- expect(
- screen
- .getAllByTestId("plan-timeline-node-type")
- .map((cell) => cell.textContent)
- ).toEqual([
- "Sort",
- "HashAggregate",
- "Hash Join",
- "Seq Scan",
- "Hash",
- "Seq Scan",
- ]);
- });
-
- test("spans each bar from the startup cost to the total cost", () => {
- renderSummary();
-
- // The hash join starts at 140.5 and finishes at 1,090.86 of the plan's
- // 1,465.93 cost units.
- const join = spans()[2];
- expect(percentOf(join.style.left)).toBeCloseTo((140.5 / 1465.93) * 100, 4);
- expect(percentOf(join.style.width)).toBeCloseTo(
- ((1090.86 - 140.5) / 1465.93) * 100,
- 4
- );
-
- });
-
- test("keeps a span too short to draw visible and inside the axis", () => {
- renderSummary();
-
- // The root sort spans 1,465.92 to 1,465.93 — a thousandth of a percent,
- // so it is widened to the floor and pushed back off the axis end.
- const sort = spans()[0];
- expect(percentOf(sort.style.width)).toBe(0.5);
- expect(percentOf(sort.style.left)).toBe(99.5);
- });
-
- test("shades a span by how much of the plan the node itself costs", () => {
- renderSummary();
- const opacity = (index: number) => Number(spans()[index].style.opacity);
-
- // The scan of `orders` owns the largest self cost, so it saturates, and
- // the Hash that adds nothing stays at the floor that keeps it visible.
- expect(opacity(3)).toBe(1);
- expect(opacity(4)).toBe(0.3);
- expect(opacity(2)).toBeGreaterThan(0.3);
- expect(opacity(2)).toBeLessThan(1);
- });
-
- test("labels the axis from zero to the plan's cost", () => {
- renderSummary();
- expect(screen.getByTestId("plan-timeline-axis")).toHaveTextContent(
- "01,465.93"
- );
- });
-
- test("stretches the axis over the self costs a Limit hides", () => {
- renderSummary({ tree: treeFrom(cteNestedLoopInitplan) });
- // The root Limit reports 979.51, but its children account for 2,578.21.
- expect(screen.getByTestId("plan-timeline-axis")).toHaveTextContent(
- "02,578.21"
- );
- });
-
- test("indents a timeline row by the depth the planner nested it at", () => {
- renderSummary({ tree: treeFrom(cteNestedLoopInitplan) });
-
- expect(
- screen
- .getAllByTestId("plan-timeline-node-type")
- .map((cell) => (cell.parentElement as HTMLElement).style.paddingLeft)
- ).toEqual(["0px", "12px", "24px", "12px", "24px", "24px"]);
- });
-
- test("selects a node from its timeline row", () => {
- const { onSelect } = renderSummary();
-
- expect(timelineRows()[0]).toHaveAttribute("aria-pressed", "true");
- expect(timelineRows()[3]).toHaveAttribute("aria-pressed", "false");
-
- fireEvent.click(timelineRows()[3]);
- expect(onSelect).toHaveBeenCalledWith("0.0.0.0");
- });
-
- test("describes a timeline row without relying on its bar", () => {
+ test("ranks the costliest operators with their share of the plan", () => {
renderSummary();
- expect(timelineRows()[3]).toHaveAccessibleName(
- "Seq Scan, orders, cost 0 to 819, 55.9% of plan cost"
- );
+ expect(screen.getByText("Costliest by estimated cost")).toBeVisible();
+ expect(rows()).toHaveLength(3);
+ expect(rows()[0]).toHaveTextContent("Seq Scan");
+ expect(rows()[0]).toHaveTextContent("orders");
+ expect(rows()[0]).toHaveTextContent("55.9%");
+ expect(rows()[1]).toHaveTextContent("HashAggregate");
});
- test("ranks the costliest operators with their share of the plan", () => {
- renderSummary();
- const rows = screen.getAllByTestId("plan-costliest-row");
+ test("marks the selected operator", () => {
+ renderSummary({ selectedId: "0.0.0.0" });
- expect(rows).toHaveLength(5);
- expect(rows[0]).toHaveTextContent("Seq Scan");
- expect(rows[0]).toHaveTextContent("orders");
- expect(rows[0]).toHaveTextContent("819");
- expect(rows[0]).toHaveTextContent("55.9%");
- expect(rows[1]).toHaveTextContent("HashAggregate");
- // The Hash node adds nothing on top of its child, so it is not ranked.
- expect(
- rows.some((row) => row.textContent?.startsWith("5Hash"))
- ).toBe(false);
+ expect(rows()[0]).toHaveAttribute("aria-pressed", "true");
+ expect(rows()[1]).toHaveAttribute("aria-pressed", "false");
});
- test("selects a node from the costliest list", () => {
+ test("selects a node from the ranking", () => {
const { onSelect } = renderSummary();
- fireEvent.click(screen.getAllByTestId("plan-costliest-row")[0]);
+ fireEvent.click(rows()[0]);
expect(onSelect).toHaveBeenCalledWith("0.0.0.0");
});
- test("totals the cost of every operation kind in the plan", () => {
- renderSummary();
- const cells = screen
- .getAllByTestId("plan-operation-row")
- .map((row) =>
- within(row)
- .getAllByRole("cell")
- .map((cell) => cell.textContent)
- );
-
- expect(cells[0]).toEqual(["Seq Scan", "2", "897", "61.2%"]);
- expect(cells.map((row) => row[0])).toEqual([
- "Seq Scan",
- "HashAggregate",
- "Hash Join",
- "Sort",
- "Hash",
- ]);
- expect(
- Number.parseFloat(
- screen.getAllByTestId("plan-cost-share-bar")[0].style.width
- )
- ).toBeCloseTo((897 / 1465.93) * 100, 4);
- });
-
- test("keeps every share inside the axis when a Limit truncates the root", () => {
- renderSummary({ tree: treeFrom(cteNestedLoopInitplan) });
-
- for (const span of spans()) {
- expect(percentOf(span.style.left)).toBeGreaterThanOrEqual(0);
- expect(
- percentOf(span.style.left) + percentOf(span.style.width)
- ).toBeLessThanOrEqual(100.0001);
- }
- // 1,319 of the 2,578.21 cost units the plan's nodes account for.
- expect(screen.getAllByTestId("plan-costliest-row")[0]).toHaveTextContent(
- "51.2%"
- );
- });
-
- test("gives a single-node plan the whole timeline", () => {
- renderSummary({ tree: treeFrom(seqScanFilter) });
+ test("ranks SQL Server's costs like any other engine's", () => {
+ renderSummary({ tree: treeOf(parseMssqlPlan(mssqlHashJoinAggregateSort)) });
- expect(timelineRows()).toHaveLength(1);
- expect(percentOf(spans()[0].style.left)).toBe(0);
- expect(percentOf(spans()[0].style.width)).toBe(100);
- expect(screen.getAllByTestId("plan-costliest-row")[0]).toHaveTextContent(
- "100%"
- );
- expect(
- within(screen.getAllByTestId("plan-operation-row")[0])
- .getAllByRole("cell")
- .map((cell) => cell.textContent)
- ).toEqual(["Seq Scan", "1", "90.5", "100%"]);
+ expect(rows()[0]).toHaveTextContent("Index Scan");
});
- test("reports a plan the planner costs at nothing without dividing by it", () => {
+ test("says so when no operator adds a cost of its own", () => {
renderSummary({ tree: treeFrom(zeroCostPlan) });
- expect(spans().map((span) => span.style.left)).toEqual(["0%", "0%"]);
- expect(spans().map((span) => span.style.width)).toEqual(["0.5%", "0.5%"]);
- expect(timelineRows()[0]).toHaveTextContent("0%");
expect(screen.queryAllByTestId("plan-costliest-row")).toHaveLength(0);
expect(
screen.getByText("No node in this plan adds an estimated cost of its own.")
).toBeVisible();
- expect(
- screen
- .getAllByTestId("plan-operation-row")
- .map((row) => row.textContent)
- ).toEqual(["Limit100%", "Result100%"]);
- });
-
- test("leaves the cost ranges out of a plan without startup costs", () => {
- renderSummary({ tree: treeOf(parseMssqlPlan(mssqlHashJoinAggregateSort)) });
-
- expect(screen.queryByText("Cost ranges")).toBeNull();
- expect(screen.queryByTestId("plan-timeline")).toBeNull();
- // The rest of the summary reads SQL Server's costs like any other.
- expect(
- screen.getByText("Total estimated cost").nextSibling
- ).toHaveTextContent("0.277");
- expect(screen.getAllByTestId("plan-costliest-row")[0]).toHaveTextContent(
- "Index Scan"
- );
- expect(screen.getAllByTestId("plan-operation-row").length).toBeGreaterThan(
- 0
- );
- });
-
- test("leaves out the rows returned when the root estimates none", () => {
- renderSummary({ tree: treeOf(parseMssqlPlan(twoStatementBatch)) });
-
- expect(screen.getByText("Nodes").nextSibling).toHaveTextContent("9");
- expect(screen.queryByText("Estimated rows returned")).toBeNull();
});
test("renders a subject containing markup as text, not as markup", () => {
@@ -309,7 +111,7 @@ describe("QueryPlanSummary", () => {
]),
});
- expect(timelineRows()[0]).toHaveTextContent(injected);
+ expect(rows()[0]).toHaveTextContent("Seq Scan");
expect(container.querySelector("img")).toBeNull();
});
});
diff --git a/frontend/src/apps/explain-visualizer/QueryPlanSummary.tsx b/frontend/src/apps/explain-visualizer/QueryPlanSummary.tsx
index 9168ee24e6..2dcab5d741 100644
--- a/frontend/src/apps/explain-visualizer/QueryPlanSummary.tsx
+++ b/frontend/src/apps/explain-visualizer/QueryPlanSummary.tsx
@@ -1,35 +1,13 @@
-import { Info } from "lucide-react";
-import type { ReactNode } from "react";
-import { memo, useMemo } from "react";
+import { useMemo } from "react";
import { Button } from "@/components/ui/button";
-import {
- Table,
- TableBody,
- TableCell,
- TableHead,
- TableHeader,
- TableRow,
-} from "@/components/ui/table";
import { cn } from "@/lib/utils";
import { useQueryPlanTranslation } from "./plan-i18n";
-import { planIndentPixels } from "./plan-layout";
import {
- formatPlanCost,
- formatPlanCount,
formatPlanShare,
- type PlanTimelineRow,
type PlanTree,
- planCostByOperation,
planCostliestNodes,
- planHighlightIntensity,
planSelfCostShare,
- planTimeline,
} from "./plan-model";
-import {
- PlanCostShareBar,
- PlanMetric,
- SECONDARY_COLUMN_CLASS,
-} from "./plan-shared";
interface Props {
readonly tree: PlanTree;
@@ -38,388 +16,62 @@ interface Props {
}
/**
- * Faintest a timeline span is drawn. A node that adds no cost of its own still
- * occupies a span of the plan, and hiding it would misreport the shape.
+ * The operators that add the most estimated cost of their own, ranked, so the
+ * expensive step is named outright with no graph to read first.
*/
-const MIN_SPAN_OPACITY = 0.3;
-
-/**
- * Narrowest a timeline span is drawn, as a fraction of the axis. A node whose
- * startup and total costs are the same spans nothing, and a bar of no width
- * would read as an absent row rather than an instant one.
- */
-const MIN_SPAN_FRACTION = 0.005;
-
-/** A span's placement on the axis, kept whole and inside the track. */
-function spanGeometry(start: number, end: number) {
- const width = Math.min(1, Math.max(end - start, MIN_SPAN_FRACTION));
- return {
- left: `${Math.min(start, 1 - width) * 100}%`,
- width: `${width * 100}%`,
- };
-}
-
-/** Width of the label column once the row has room to put it beside the track. */
-const LABEL_COLUMN_CLASS = "sm:w-56 sm:shrink-0";
-/** Width of the trailing share column in the lists that carry one. */
-const SHARE_COLUMN_CLASS = "w-12 shrink-0 text-right";
-
-const ROW_BUTTON_CLASS =
- "h-auto w-full justify-start rounded-xs px-2 py-1.5 text-left font-normal";
-
-function Section({
- title,
- description,
- children,
-}: {
- title: string;
- description?: string;
- children: ReactNode;
-}) {
- return (
- <section className="flex flex-col gap-3">
- <div className="flex flex-col gap-1">
- <h2 className="text-base leading-6 font-semibold text-main">{title}</h2>
- {description ? (
- <p className="text-xs leading-4 text-control-light">{description}</p>
- ) : null}
- </div>
- {children}
- </section>
- );
-}
-
-function PlanTotals({ tree }: { tree: PlanTree }) {
- const translate = useQueryPlanTranslation();
- return (
- <div className="flex flex-col gap-3">
- <dl className="flex flex-wrap gap-4">
- <PlanMetric
- label={translate("summary.nodes")}
- value={formatPlanCount(tree.nodes.length)}
- />
- <PlanMetric
- label={translate("summary.total-estimated-cost")}
- value={formatPlanCost(tree.root.totalCost)}
- />
- {tree.root.rows === undefined ? null : (
- <PlanMetric
- label={translate("summary.estimated-rows-returned")}
- value={formatPlanCount(tree.root.rows)}
- />
- )}
- </dl>
- <p className="flex items-start gap-2 text-xs leading-4 text-control-light">
- <Info aria-hidden="true" className="mt-px size-3.5 shrink-0" />
- <span>{translate("summary.estimate-note")}</span>
- </p>
- </div>
- );
-}
-
-/**
- * One node as a span on the plan's cost axis.
- *
- * Memoized because a selection change re-renders the timeline, and every other
- * row of a large plan is drawing exactly what it drew before.
- */
-const TimelineRow = memo(function TimelineRow({
- row,
- tree,
- selected,
- onSelect,
-}: {
- row: PlanTimelineRow;
- tree: PlanTree;
- selected: boolean;
- onSelect: (id: string) => void;
-}) {
- const translate = useQueryPlanTranslation();
- const { node, depth, start, end, share } = row;
- return (
- <li>
- <Button
- appearance="secondary"
- data-testid="plan-timeline-row"
- aria-pressed={selected}
- aria-label={translate("summary.timeline-node", {
- name: [node.nodeType, node.subject].filter(Boolean).join(", "),
- startup: formatPlanCost(node.startupCost),
- total: formatPlanCost(node.totalCost),
- share: formatPlanShare(share),
- })}
- onClick={() => onSelect(node.id)}
- className={cn(
- ROW_BUTTON_CLASS,
- "flex-col items-stretch gap-1 sm:flex-row sm:items-center sm:gap-3",
- selected && "bg-accent/10 hover:bg-accent/15"
- )}
- >
- <span
- className={cn(
- "flex min-w-0 items-baseline gap-2",
- LABEL_COLUMN_CLASS
- )}
- style={{ paddingLeft: planIndentPixels(depth) }}
- >
- <span
- data-testid="plan-timeline-node-type"
- className={cn(
- "truncate text-xs leading-4",
- selected ? "font-medium text-accent" : "text-main"
- )}
- >
- {node.nodeType}
- </span>
- <span className="min-w-0 flex-1 truncate text-xs leading-4 text-control-light">
- {node.subject ?? ""}
- </span>
- <span className="shrink-0 text-xs leading-4 text-control tabular-nums">
- {formatPlanShare(share)}
- </span>
- </span>
- <span
- aria-hidden="true"
- // `flex-1` only once the row is horizontal: in the stacked layout it
- // is the column's main axis and would flatten the track to nothing.
- className="relative h-2.5 w-full min-w-0 overflow-hidden rounded-xs bg-control-bg sm:flex-1"
- >
- <span
- data-testid="plan-timeline-span"
- className="absolute inset-y-0 rounded-xs bg-warning"
- style={{
- ...spanGeometry(start, end),
- opacity:
- MIN_SPAN_OPACITY +
- (1 - MIN_SPAN_OPACITY) *
- planHighlightIntensity(node, tree, "cost"),
- }}
- />
- </span>
- </Button>
- </li>
- );
-});
-
-function CostTimeline({
- tree,
- selectedId,
- onSelect,
-}: {
- tree: PlanTree;
- selectedId: string | undefined;
- onSelect: (id: string) => void;
-}) {
- const rows = useMemo(() => planTimeline(tree), [tree]);
- return (
- <div className="flex flex-col gap-1">
- <div className="flex items-center gap-3">
- <span
- aria-hidden="true"
- className={cn("hidden sm:block", LABEL_COLUMN_CLASS)}
- />
- <span
- data-testid="plan-timeline-axis"
- className="flex min-w-0 flex-1 items-baseline justify-between px-2 text-xs leading-4 text-control-light tabular-nums sm:px-0"
- >
- <span>0</span>
- <span>{formatPlanCost(tree.costBasis)}</span>
- </span>
- </div>
- <ol data-testid="plan-timeline" className="flex flex-col">
- {rows.map((row) => (
- <TimelineRow
- key={row.node.id}
- row={row}
- tree={tree}
- selected={row.node.id === selectedId}
- onSelect={onSelect}
- />
- ))}
- </ol>
- </div>
- );
-}
-
-function CostliestOperators({
- tree,
- selectedId,
- onSelect,
-}: {
- tree: PlanTree;
- selectedId: string | undefined;
- onSelect: (id: string) => void;
-}) {
+export function QueryPlanSummary({ tree, selectedId, onSelect }: Props) {
const translate = useQueryPlanTranslation();
const nodes = useMemo(() => planCostliestNodes(tree), [tree]);
-
- if (nodes.length === 0) {
- return (
- <p className="text-sm leading-5 text-control-light">
- {translate("summary.no-added-cost")}
- </p>
- );
- }
-
return (
- <ol data-testid="plan-costliest" className="flex flex-col">
- {nodes.map((node, index) => {
- const selected = node.id === selectedId;
- return (
- <li key={node.id}>
- <Button
- appearance="secondary"
- data-testid="plan-costliest-row"
- aria-pressed={selected}
- onClick={() => onSelect(node.id)}
- className={cn(
- ROW_BUTTON_CLASS,
- "items-baseline gap-3",
- selected && "bg-accent/10 hover:bg-accent/15"
- )}
- >
- <span className="w-4 shrink-0 text-xs leading-4 text-control-light tabular-nums">
- {index + 1}
- </span>
- <span className="flex min-w-0 flex-1 items-baseline gap-2">
- <span
+ <section data-testid="plan-summary" className="flex flex-col gap-1">
+ <h2 className="text-xs leading-4 text-control-light">
+ {translate("summary.costliest")}
+ </h2>
+ {nodes.length === 0 ? (
+ <p className="text-sm leading-5 text-control-light">
+ {translate("summary.no-added-cost")}
+ </p>
+ ) : (
+ <ol data-testid="plan-costliest" className="flex flex-col">
+ {nodes.map((node, index) => {
+ const selected = node.id === selectedId;
+ return (
+ <li key={node.id}>
+ <Button
+ appearance="secondary"
+ data-testid="plan-costliest-row"
+ aria-pressed={selected}
+ onClick={() => onSelect(node.id)}
className={cn(
- "truncate text-sm leading-5",
- selected ? "font-medium text-accent" : "text-main"
+ "h-auto w-full items-baseline justify-start gap-2 rounded-xs px-2 py-1 text-left font-normal",
+ selected && "bg-accent/10 hover:bg-accent/15"
)}
>
- {node.nodeType}
- </span>
- <span className="min-w-0 flex-1 truncate text-xs leading-4 text-control-light">
- {node.subject ?? ""}
- </span>
- </span>
- <span className="hidden shrink-0 text-xs leading-4 text-control tabular-nums sm:inline">
- {formatPlanCost(node.selfCost)}
- </span>
- <span
- className={cn(
- SHARE_COLUMN_CLASS,
- "text-xs leading-4 text-main tabular-nums"
- )}
- >
- {formatPlanShare(planSelfCostShare(node, tree))}
- </span>
- </Button>
- </li>
- );
- })}
- </ol>
- );
-}
-
-function CostByOperation({ tree }: { tree: PlanTree }) {
- const translate = useQueryPlanTranslation();
- const operations = useMemo(() => planCostByOperation(tree), [tree]);
- return (
- <Table className="table-fixed">
- <TableHeader>
- <TableRow>
- <TableHead className="text-xs leading-4">
- {translate("summary.operation")}
- </TableHead>
- <TableHead className="w-16 text-right text-xs leading-4">
- {translate("summary.count")}
- </TableHead>
- <TableHead
- className={cn(
- SECONDARY_COLUMN_CLASS,
- "text-right text-xs leading-4 sm:w-28"
- )}
- >
- {translate("summary.added-cost")}
- </TableHead>
- <TableHead className="w-28 text-right text-xs leading-4 sm:w-40">
- {translate("summary.share")}
- </TableHead>
- </TableRow>
- </TableHeader>
- <TableBody striped={false}>
- {operations.map((operation) => (
- <TableRow key={operation.nodeType} data-testid="plan-operation-row">
- <TableCell className="py-2 text-sm leading-5 text-main">
- <span className="block truncate">{operation.nodeType}</span>
- </TableCell>
- <TableCell className="py-2 text-right text-xs leading-4 text-control tabular-nums">
- {formatPlanCount(operation.count)}
- </TableCell>
- <TableCell
- className={cn(
- SECONDARY_COLUMN_CLASS,
- "py-2 text-right text-xs leading-4 text-control tabular-nums"
- )}
- >
- {formatPlanCost(operation.selfCost)}
- </TableCell>
- <TableCell className="py-2 pr-4">
- <span className="flex items-center justify-end gap-2">
- <PlanCostShareBar
- share={operation.share}
- className="w-10 shrink-0 sm:w-20"
- />
- <span className="w-12 shrink-0 text-right text-xs leading-4 text-main tabular-nums">
- {formatPlanShare(operation.share)}
- </span>
- </span>
- </TableCell>
- </TableRow>
- ))}
- </TableBody>
- </Table>
- );
-}
-
-/**
- * Where the plan's estimated cost goes, read three ways: how much of it each
- * node spans, which nodes own the most of it, and which kinds of operation do.
- */
-export function QueryPlanSummary({ tree, selectedId, onSelect }: Props) {
- const translate = useQueryPlanTranslation();
- return (
- <div
- data-testid="plan-summary"
- className="min-h-0 w-full flex-1 overflow-auto"
- >
- <div className="flex flex-col gap-6 p-4">
- <PlanTotals tree={tree} />
-
- {/* A span starts at a startup cost, which not every engine reports. */}
- {tree.estimates.startupCost ? (
- <Section
- title={translate("summary.cost-ranges")}
- description={translate("summary.cost-ranges-description")}
- >
- <CostTimeline
- tree={tree}
- selectedId={selectedId}
- onSelect={onSelect}
- />
- </Section>
- ) : null}
-
- <Section
- title={translate("summary.costliest")}
- description={translate("summary.costliest-description")}
- >
- <CostliestOperators
- tree={tree}
- selectedId={selectedId}
- onSelect={onSelect}
- />
- </Section>
-
- <Section
- title={translate("summary.cost-by-operation")}
- description={translate("summary.cost-by-operation-description")}
- >
- <CostByOperation tree={tree} />
- </Section>
- </div>
- </div>
+ <span className="w-3 shrink-0 text-xs leading-4 text-control-light tabular-nums">
+ {index + 1}
+ </span>
+ <span className="flex min-w-0 flex-1 items-baseline gap-2">
+ <span
+ className={cn(
+ "truncate text-sm leading-5",
+ selected ? "font-medium text-accent" : "text-main"
+ )}
+ >
+ {node.nodeType}
+ </span>
+ <span className="min-w-0 flex-1 truncate text-xs leading-4 text-control-light">
+ {node.subject ?? ""}
+ </span>
+ </span>
+ <span className="shrink-0 text-xs leading-4 text-main tabular-nums">
+ {formatPlanShare(planSelfCostShare(node, tree))}
+ </span>
+ </Button>
+ </li>
+ );
+ })}
+ </ol>
+ )}
+ </section>
);
}
diff --git a/frontend/src/apps/explain-visualizer/QueryPlanView.tsx b/frontend/src/apps/explain-visualizer/QueryPlanView.tsx
index 08863bec84..6d2c55ba51 100644
--- a/frontend/src/apps/explain-visualizer/QueryPlanView.tsx
+++ b/frontend/src/apps/explain-visualizer/QueryPlanView.tsx
@@ -2,7 +2,7 @@ import { type ReactNode, useMemo } from "react";
import { Alert } from "@/components/ui/alert";
import { cn } from "@/lib/utils";
import { Engine } from "@/types/proto-es/v1/common_pb";
-import type { VisualizerEngine } from "@/utils/explainToken";
+import type { VisualizerEngine } from "@/utils/queryPlanEngines";
import {
MSSQL_PLAN_EMPTY_MESSAGE,
MSSQL_PLAN_INVALID_XML_MESSAGE,
@@ -63,21 +63,17 @@ interface Props {
engine: VisualizerEngine;
planSource: string;
textPlanSource?: string;
- planQuery?: string;
note?: ReactNode;
translate?: QueryPlanTranslate;
disallowCopyingData?: boolean;
- syncSelectionWithHash?: boolean;
}
function QueryPlanViewContent({
engine,
planSource,
textPlanSource,
- planQuery,
note,
disallowCopyingData = false,
- syncSelectionWithHash,
}: Props) {
const translate = useQueryPlanTranslation();
const result = useMemo(
@@ -109,10 +105,8 @@ function QueryPlanViewContent({
tree={result.tree}
rawPlan={planSource}
textPlan={textPlanSource}
- query={planQuery}
note={note}
disallowCopyingData={disallowCopyingData}
- syncSelectionWithHash={syncSelectionWithHash}
/>
);
}
diff --git a/frontend/src/apps/explain-visualizer/QueryPlanViewer.test.tsx b/frontend/src/apps/explain-visualizer/QueryPlanViewer.test.tsx
index 0b365d58a5..1270145f9f 100644
--- a/frontend/src/apps/explain-visualizer/QueryPlanViewer.test.tsx
+++ b/frontend/src/apps/explain-visualizer/QueryPlanViewer.test.tsx
@@ -49,10 +49,10 @@ const tree = (): PlanTree => {
return result.tree;
};
-const renderViewer = (query?: string) =>
- render(<QueryPlanViewer tree={tree()} rawPlan={rawPlan} query={query} />);
+const renderViewer = () =>
+ render(<QueryPlanViewer tree={tree()} rawPlan={rawPlan} />);
-/** Renders a plan the way the entry does: parsed, beside its source. */
+/** Renders a plan the way the result pane does: parsed, beside its source. */
const renderParsed = (
parse: (source: string) => ReturnType<typeof parsePostgresPlan>,
source: string
@@ -65,18 +65,17 @@ const renderParsed = (
const openTab = (name: string) =>
fireEvent.click(screen.getByRole("tab", { name }));
-const renderDiagramViewer = (query?: string) => {
- const result = renderViewer(query);
- openTab("Diagram");
- return result;
-};
-
const tabNames = () =>
screen.getAllByRole("tab").map((entry) => entry.textContent);
-/** Loads the page at a fragment, the way following a shared link would. */
-const startAtFragment = (fragment: string) =>
- history.replaceState(null, "", `${location.pathname}${fragment}`);
+/** The panel on screen; the diagram's stays mounted behind the others. */
+const visiblePanel = () => within(screen.getByRole("tabpanel"));
+
+/** A card on the diagram, not the ranking row of the same name. */
+const diagramCard = (name: RegExp) =>
+ within(screen.getByTestId("plan-diagram-viewport")).getByRole("button", {
+ name,
+ });
const collapseToggle = () => screen.getByTestId("plan-node-collapse");
const cards = () => screen.queryAllByTestId("plan-node-card");
@@ -84,33 +83,51 @@ const cards = () => screen.queryAllByTestId("plan-node-card");
describe("QueryPlanViewer", () => {
beforeEach(() => {
mockMatchMedia(false);
- // The viewer keeps the selection in the fragment, so each test has to
- // start from a page that has none.
- startAtFragment("");
});
- test("opens on the text plan", () => {
+ test("opens on the diagram with the costliest operator selected", () => {
+ renderParsed(parseMssqlPlan, procedureTwoStatements);
+
+ expect(screen.getByTestId("plan-diagram-viewport")).toBeVisible();
+ const [first] = visiblePanel().getAllByTestId("plan-costliest-row");
+ expect(first).toHaveAttribute("aria-pressed", "true");
+ const name = first.querySelector(".truncate")?.textContent ?? "";
+ expect(screen.getByRole("heading", { name })).toBeInTheDocument();
+ });
+
+ test("offers the diagram, a table and the text, in that order", () => {
renderViewer();
- expect(screen.getByText(/"Node Type": "Bitmap Heap Scan"/)).toBeVisible();
- expect(screen.getByTestId("plan-diagram-viewport")).not.toBeVisible();
+ expect(tabNames()).toEqual(["Diagram", "Table", "Text"]);
+ expect(screen.getByText("2 nodes · estimated cost 39.18")).toBeVisible();
});
- test("opens the diagram with the root node already selected", () => {
- renderDiagramViewer();
+ test("ranks the costliest operators beside the diagram", () => {
+ renderViewer();
+
+ const rows = visiblePanel().getAllByTestId("plan-costliest-row");
+ // 34.81 of the plan's 39.18 cost units are the heap scan's own.
+ expect(rows[0]).toHaveTextContent("Bitmap Heap Scan");
+ expect(rows[0]).toHaveTextContent("88.8%");
+ });
+
+ test("selects an operator from the ranking", () => {
+ renderViewer();
- expect(screen.getByTestId("plan-diagram-viewport")).toBeInTheDocument();
+ fireEvent.click(visiblePanel().getAllByTestId("plan-costliest-row")[1]);
expect(
- screen.getByRole("heading", { name: "Bitmap Heap Scan" })
+ screen.getByRole("heading", { name: "Bitmap Index Scan" })
).toBeInTheDocument();
- expect(screen.getByText("2 nodes · estimated cost 39.18")).toBeVisible();
+ expect(
+ diagramCard(/Bitmap Index Scan/)
+ ).toHaveAttribute("aria-pressed", "true");
});
test("moves the detail pane to whichever node is clicked", () => {
- renderDiagramViewer();
+ renderViewer();
fireEvent.click(
- screen.getByRole("button", { name: /Bitmap Index Scan/ })
+ diagramCard(/Bitmap Index Scan/)
);
expect(
screen.getByRole("heading", { name: "Bitmap Index Scan" })
@@ -118,29 +135,26 @@ describe("QueryPlanViewer", () => {
expect(screen.getByText("(customer_id = 42)")).toBeInTheDocument();
});
- test("lists the same plan as a table on the grid tab", () => {
+ test("lists the same plan as a table, beside the same ranking", () => {
renderViewer();
- fireEvent.click(screen.getByRole("tab", { name: "Grid" }));
+ openTab("Table");
expect(screen.getByTestId("plan-diagram-viewport")).not.toBeVisible();
expect(
- screen
+ visiblePanel()
.getAllByTestId("plan-grid-node-type")
.map((cell) => cell.textContent)
).toEqual(["Bitmap Heap Scan", "Bitmap Index Scan"]);
- // The diagram stays mounted behind this tab, so the totals it also draws
- // are in the document; this one belongs to the panel on screen.
expect(
- within(screen.getByRole("tabpanel")).getByText(
- "2 nodes · estimated cost 39.18"
- )
+ visiblePanel().getByText("2 nodes · estimated cost 39.18")
).toBeVisible();
+ expect(visiblePanel().getAllByTestId("plan-costliest-row")).toHaveLength(2);
});
- test("keeps the selection when moving between the diagram and grid", () => {
+ test("keeps the selection when moving between the diagram and table", () => {
renderViewer();
- fireEvent.click(screen.getByRole("tab", { name: "Grid" }));
+ openTab("Table");
const rows = screen.getAllByTestId("plan-grid-row");
expect(rows[0]).toHaveAttribute("aria-selected", "true");
@@ -149,73 +163,30 @@ describe("QueryPlanViewer", () => {
screen.getByRole("heading", { name: "Bitmap Index Scan" })
).toBeInTheDocument();
- fireEvent.click(screen.getByRole("tab", { name: "Diagram" }));
+ openTab("Diagram");
expect(
- screen.getByRole("button", { name: /Bitmap Index Scan/ })
+ diagramCard(/Bitmap Index Scan/)
).toHaveAttribute("aria-pressed", "true");
- fireEvent.click(screen.getByRole("button", { name: /^Bitmap Heap Scan/ }));
- fireEvent.click(screen.getByRole("tab", { name: "Grid" }));
+ fireEvent.click(diagramCard(/^Bitmap Heap Scan/));
+ openTab("Table");
expect(screen.getAllByTestId("plan-grid-row")[0]).toHaveAttribute(
"aria-selected",
"true"
);
- expect(
- screen.getByRole("heading", { name: "Bitmap Heap Scan" })
- ).toBeInTheDocument();
- });
-
- test("answers where the cost goes on the summary tab", () => {
- renderViewer();
-
- fireEvent.click(screen.getByRole("tab", { name: "Summary" }));
- expect(screen.getByTestId("plan-diagram-viewport")).not.toBeVisible();
- expect(screen.getByTestId("plan-summary")).toBeInTheDocument();
- expect(
- screen
- .getAllByTestId("plan-timeline-node-type")
- .map((cell) => cell.textContent)
- ).toEqual(["Bitmap Heap Scan", "Bitmap Index Scan"]);
- // 34.81 of the plan's 39.18 cost units are the heap scan's own.
- expect(screen.getAllByTestId("plan-costliest-row")[0]).toHaveTextContent(
- "88.8%"
- );
- });
-
- test("shares the selection between the summary and the other tabs", () => {
- renderViewer();
-
- fireEvent.click(screen.getByRole("tab", { name: "Summary" }));
- const timelineRows = screen.getAllByTestId("plan-timeline-row");
- expect(timelineRows[0]).toHaveAttribute("aria-pressed", "true");
-
- fireEvent.click(timelineRows[1]);
- expect(
- screen.getByRole("heading", { name: "Bitmap Index Scan" })
- ).toBeInTheDocument();
-
- fireEvent.click(screen.getByRole("tab", { name: "Diagram" }));
- expect(
- screen.getByRole("button", { name: /Bitmap Index Scan/ })
- ).toHaveAttribute("aria-pressed", "true");
-
- fireEvent.click(screen.getByRole("tab", { name: "Grid" }));
- fireEvent.click(screen.getAllByTestId("plan-grid-row")[0]);
- fireEvent.click(screen.getByRole("tab", { name: "Summary" }));
- expect(screen.getAllByTestId("plan-timeline-row")[0]).toHaveAttribute(
- "aria-pressed",
- "true"
- );
});
test("switches to the text plan and back to the diagram", () => {
renderViewer();
- fireEvent.click(screen.getByRole("tab", { name: "Text" }));
+ openTab("Text");
expect(screen.getByText(/"Node Type": "Bitmap Heap Scan"/)).toBeVisible();
expect(screen.getByTestId("plan-diagram-viewport")).not.toBeVisible();
+ expect(screen.getByTestId("plan-copy-button")).toHaveTextContent(
+ "Copy plan"
+ );
- fireEvent.click(screen.getByRole("tab", { name: "Diagram" }));
+ openTab("Diagram");
expect(screen.getByTestId("plan-diagram-viewport")).toBeVisible();
});
@@ -233,81 +204,37 @@ describe("QueryPlanViewer", () => {
expect(screen.queryByText(/"Node Type"/)).toBeNull();
});
- test("shows the statement on the query tab", () => {
- renderViewer("SELECT * FROM orders WHERE customer_id = 42;");
-
- fireEvent.click(screen.getByRole("tab", { name: "Query" }));
- expect(
- screen.getByText("SELECT * FROM orders WHERE customer_id = 42;")
- ).toBeVisible();
- });
-
- test("offers a copy of whichever text a tab is showing", () => {
- renderViewer("SELECT * FROM orders WHERE customer_id = 42;");
-
- openTab("Text");
- expect(screen.getByTestId("plan-copy-button")).toHaveTextContent(
- "Copy plan"
- );
-
- openTab("Query");
- expect(screen.getByTestId("plan-copy-button")).toHaveTextContent(
- "Copy query"
- );
- });
-
- test("offers no copy of a statement that was never captured", () => {
- renderViewer();
-
- openTab("Query");
- expect(screen.queryByTestId("plan-copy-button")).toBeNull();
- });
-
- test("explains an absent statement instead of rendering an empty tab", () => {
- renderViewer();
-
- fireEvent.click(screen.getByRole("tab", { name: "Query" }));
- expect(
- screen.getByText("The statement was not captured with this plan.")
- ).toBeVisible();
- });
-
test("shades the diagram once a highlight mode is chosen", () => {
- renderDiagramViewer();
+ renderViewer();
expect(screen.queryAllByTestId("plan-node-tint")).toHaveLength(0);
fireEvent.click(screen.getByRole("button", { name: "Cost" }));
expect(screen.getAllByTestId("plan-node-tint").length).toBeGreaterThan(0);
});
- test("offers every tab and highlight for a plan with cost and row estimates", () => {
+ test("offers every highlight for a plan with cost and row estimates", () => {
renderParsed(parseMssqlPlan, procedureTwoStatements);
- expect(tabNames()).toEqual([
- "Text",
- "Diagram",
- "Grid",
- "Summary",
- "Query",
- ]);
- openTab("Diagram");
expect(
within(screen.getByRole("group", { name: "Highlight" }))
.getAllByRole("button")
.map((option) => option.textContent)
).toEqual(["Off", "Cost", "Rows"]);
expect(screen.getByText("10 nodes · estimated cost 1.64")).toBeVisible();
+ // What the bars and edges mean is a hover or a focus away, not a line of
+ // its own.
+ expect(screen.getByRole("button", { name: /card's bar/ })).toBeVisible();
});
test("keeps to what a plan without estimates can show", () => {
renderParsed(parseSpannerPlan, JSON.stringify(spannerHashJoin));
- // The summary is where the cost goes, and nothing can be shaded.
- expect(tabNames()).toEqual(["Text", "Diagram", "Grid", "Query"]);
- openTab("Diagram");
+ // Nothing can be ranked or shaded.
+ expect(tabNames()).toEqual(["Diagram", "Table", "Text"]);
+ expect(screen.queryByTestId("plan-summary")).toBeNull();
expect(screen.queryByRole("group", { name: "Highlight" })).toBeNull();
expect(screen.getByText("7 nodes")).toBeVisible();
- expect(screen.queryByText(/card's bar/)).toBeNull();
+ expect(screen.queryByLabelText(/card's bar/)).toBeNull();
expect(screen.getAllByTestId("plan-node-card")).toHaveLength(7);
});
@@ -315,9 +242,7 @@ describe("QueryPlanViewer", () => {
renderParsed(parseMssqlPlan, procedureTwoStatements);
openTab("Text");
- const raw = within(screen.getByRole("tabpanel")).getByText(
- /^<ShowPlanXML/
- ).textContent;
+ const raw = visiblePanel().getByText(/^<ShowPlanXML/).textContent;
const lines = raw?.split("\n") ?? [];
expect(lines[0]).toBe(
@@ -343,7 +268,7 @@ describe("QueryPlanViewer", () => {
);
});
- test("stacks the detail pane below the diagram on a narrow screen", () => {
+ test("stacks the side panel below the diagram on a narrow screen", () => {
mockMatchMedia(true);
renderViewer();
expect(screen.getByTestId("plan-split")).toHaveAttribute(
@@ -352,131 +277,49 @@ describe("QueryPlanViewer", () => {
);
});
- test("names the selected node in the URL, which is what shares it", () => {
- renderDiagramViewer();
-
- fireEvent.click(screen.getByRole("button", { name: /Bitmap Index Scan/ }));
- expect(location.hash).toBe("#node-0.0");
- });
-
- test("does not read or write fragments when hash syncing is disabled", () => {
- startAtFragment("#somewhere-else");
- render(
- <QueryPlanViewer
- tree={tree()}
- rawPlan={rawPlan}
- syncSelectionWithHash={false}
- />
- );
- openTab("Diagram");
-
- expect(
- screen.getByRole("heading", { name: "Bitmap Heap Scan" })
- ).toBeInTheDocument();
- fireEvent.click(screen.getByRole("button", { name: /Bitmap Index Scan/ }));
- expect(location.hash).toBe("#somewhere-else");
- });
-
test("hides copy controls when copying is disabled", () => {
render(
- <QueryPlanViewer
- tree={tree()}
- rawPlan={rawPlan}
- query="SELECT 1"
- disallowCopyingData
- />
+ <QueryPlanViewer tree={tree()} rawPlan={rawPlan} disallowCopyingData />
);
- expect(screen.queryByTestId("plan-copy-button")).toBeNull();
- openTab("Query");
+ openTab("Text");
expect(screen.queryByTestId("plan-copy-button")).toBeNull();
expect(screen.getByRole("tablist").parentElement).toHaveClass(
"select-none"
);
});
- test("leaves the URL alone until the reader picks a node", () => {
- renderViewer();
-
- // A fragment written on load would make the next reload look like a
- // followed deep link, which reveals its node over the view the page fits.
- expect(location.hash).toBe("");
- });
-
- test("opens on the node a fragment names", () => {
- startAtFragment("#node-0.0");
- renderDiagramViewer();
-
- expect(
- screen.getByRole("heading", { name: "Bitmap Index Scan" })
- ).toBeInTheDocument();
- expect(
- screen.getByRole("button", { name: /Bitmap Index Scan/ })
- ).toHaveAttribute("aria-pressed", "true");
- });
-
- test("falls back to the root when a fragment names no node in this plan", () => {
- startAtFragment("#node-9.9.9");
- renderDiagramViewer();
-
- expect(
- screen.getByRole("heading", { name: "Bitmap Heap Scan" })
- ).toBeInTheDocument();
- // The fragment is the reader's; a load neither follows nor rewrites it.
- expect(location.hash).toBe("#node-9.9.9");
- });
-
- test("ignores a fragment that is not about a node at all", () => {
- startAtFragment("#somewhere-else");
- renderDiagramViewer();
-
- expect(
- screen.getByRole("heading", { name: "Bitmap Heap Scan" })
- ).toBeInTheDocument();
- });
-
- test("follows a fragment that changes without a reload", () => {
- renderDiagramViewer();
-
- startAtFragment("#node-0.0");
- fireEvent(window, new Event("hashchange"));
-
- expect(
- screen.getByRole("heading", { name: "Bitmap Index Scan" })
- ).toBeInTheDocument();
- });
-
test("keeps the diagram's zoom while the reader moves between tabs", () => {
- renderDiagramViewer();
+ renderViewer();
const canvas = () => screen.getByTestId("plan-diagram-canvas").style.transform;
fireEvent.click(screen.getByRole("button", { name: "Zoom in" }));
const zoomed = canvas();
expect(zoomed).toContain("scale(1.25)");
- openTab("Grid");
+ openTab("Table");
openTab("Diagram");
expect(canvas()).toBe(zoomed);
});
test("keeps a subtree folded while the reader moves between tabs", () => {
- renderDiagramViewer();
+ renderViewer();
expect(cards()).toHaveLength(2);
fireEvent.click(collapseToggle());
expect(cards()).toHaveLength(1);
- openTab("Grid");
+ openTab("Table");
openTab("Diagram");
expect(cards()).toHaveLength(1);
expect(collapseToggle()).toHaveAttribute("aria-expanded", "false");
});
test("moves the selection out of a subtree it folds away", () => {
- renderDiagramViewer();
+ renderViewer();
- fireEvent.click(screen.getByRole("button", { name: /Bitmap Index Scan/ }));
+ fireEvent.click(diagramCard(/Bitmap Index Scan/));
expect(
screen.getByRole("heading", { name: "Bitmap Index Scan" })
).toBeInTheDocument();
@@ -484,25 +327,24 @@ describe("QueryPlanViewer", () => {
fireEvent.click(collapseToggle());
// The selected node has no card any more, so the collapse that swallowed
- // it takes the selection — and the URL follows.
+ // it takes the selection.
expect(
screen.getByRole("heading", { name: "Bitmap Heap Scan" })
).toBeInTheDocument();
- expect(location.hash).toBe("#node-0");
});
test("unfolds a subtree when a node inside it is selected elsewhere", () => {
- renderDiagramViewer();
+ renderViewer();
fireEvent.click(collapseToggle());
- openTab("Grid");
- // The grid still lists every node, folded or not.
+ openTab("Table");
+ // The table still lists every node, folded or not.
fireEvent.click(screen.getAllByTestId("plan-grid-row")[1]);
openTab("Diagram");
expect(cards()).toHaveLength(2);
expect(
- screen.getByRole("button", { name: /Bitmap Index Scan/ })
+ diagramCard(/Bitmap Index Scan/)
).toHaveAttribute("aria-pressed", "true");
});
diff --git a/frontend/src/apps/explain-visualizer/QueryPlanViewer.tsx b/frontend/src/apps/explain-visualizer/QueryPlanViewer.tsx
index 19cbf3b885..d261920a3b 100644
--- a/frontend/src/apps/explain-visualizer/QueryPlanViewer.tsx
+++ b/frontend/src/apps/explain-visualizer/QueryPlanViewer.tsx
@@ -1,5 +1,6 @@
+import { Info } from "lucide-react";
import type { ReactNode } from "react";
-import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { useCallback, useMemo, useState } from "react";
import {
Panel,
Group as PanelGroup,
@@ -25,8 +26,7 @@ import {
type PlanNode,
type PlanTree,
planCollapsedAncestor,
- planNodeFragment,
- planNodeIdFromFragment,
+ planCostliestNodes,
planRevealNode,
} from "./plan-model";
import { QueryPlanDiagram } from "./QueryPlanDiagram";
@@ -40,14 +40,12 @@ interface Props {
readonly rawPlan: string;
/** The plan output shown on the text tab, when it differs from rawPlan. */
readonly textPlan?: string;
- readonly query?: string;
/** Shown at the end of the tab row, such as a reminder that the plan is an estimate. */
readonly note?: ReactNode;
readonly disallowCopyingData?: boolean;
- readonly syncSelectionWithHash?: boolean;
}
-type TabValue = "diagram" | "grid" | "summary" | "text" | "query";
+type TabValue = "diagram" | "grid" | "text";
interface HighlightOption {
readonly value: PlanHighlightMode;
@@ -86,11 +84,7 @@ const RESIZE_HANDLE_BASE_CLASS =
/** Below this width the diagram and its details stack instead of splitting. */
const STACK_QUERY = "(max-width: 767px)";
-/**
- * A toggle group rather than `SegmentedControl`: this entry never loads the
- * main app's stylesheet, which is where the build injects StyleX's rules, so a
- * StyleX-sized control would render unstyled here.
- */
+/** One button per shading mode the plan's estimates support. */
function HighlightControl({
options,
value,
@@ -127,10 +121,11 @@ function HighlightControl({
);
}
-function PlanTotalsLine({ tree }: { tree: PlanTree }) {
+/** The plan's size and cost; `legend`, when given, explains the diagram on hover. */
+function PlanTotalsLine({ tree, legend }: { tree: PlanTree; legend?: string }) {
const translate = useQueryPlanTranslation();
return (
- <p className="text-xs leading-4 text-control-light">
+ <p className="flex items-center gap-1 text-xs leading-4 text-control-light">
{[
translate("totals.nodes", {
count: formatPlanCount(tree.nodes.length),
@@ -143,6 +138,18 @@ function PlanTotalsLine({ tree }: { tree: PlanTree }) {
]
.filter(Boolean)
.join(" · ")}
+ {legend ? (
+ <Tooltip content={legend}>
+ <Button
+ size="xs"
+ appearance="secondary"
+ aria-label={legend}
+ className="w-6 p-0"
+ >
+ <Info aria-hidden="true" />
+ </Button>
+ </Tooltip>
+ ) : null}
</p>
);
}
@@ -162,17 +169,20 @@ function diagramLegend(
}
/**
- * Puts one plan representation beside the detail pane. The diagram and the grid
- * are two readings of the same selection, so they share this frame instead of
- * each carrying its own copy of the details.
+ * Puts one plan representation beside the side panel: the ranked costliest
+ * operators, when the plan has costs, above the selected node's details. The
+ * diagram and the grid are two readings of the same selection, so they share
+ * this frame instead of each carrying its own copy.
*/
function PlanWithDetails({
stacked,
node,
+ summary,
children,
}: {
stacked: boolean;
node: PlanNode | undefined;
+ summary: ReactNode;
children: ReactNode;
}) {
return (
@@ -190,7 +200,10 @@ function PlanWithDetails({
)}
/>
<Panel defaultSize={stacked ? "40%" : "30%"} minSize="20%">
- <QueryPlanNodeDetails node={node} />
+ <div className="flex h-full min-h-0 flex-col gap-4 overflow-auto p-4">
+ {summary}
+ <QueryPlanNodeDetails node={node} />
+ </div>
</Panel>
</PanelGroup>
);
@@ -310,30 +323,19 @@ function TextPlan({
);
}
-/**
- * The node a fragment names, ignoring one that names a node this plan does not
- * have: a stale or hand-edited link should open the plan, not break it.
- */
-function fragmentSelection(tree: PlanTree): string | undefined {
- const id = planNodeIdFromFragment(location.hash);
- return findPlanNode(tree, id)?.id;
-}
-
export function QueryPlanViewer({
tree,
rawPlan,
textPlan = rawPlan,
- query,
note,
disallowCopyingData = false,
- syncSelectionWithHash = true,
}: Props) {
const translate = useQueryPlanTranslation();
- const [tab, setTab] = useState<TabValue>("text");
+ const [tab, setTab] = useState<TabValue>("diagram");
+ // The diagram opens centered on the costliest operator, so the details beside
+ // it start there too.
const [selectedId, setSelectedId] = useState<string>(
- () =>
- (syncSelectionWithHash ? fragmentSelection(tree) : undefined) ??
- tree.root.id
+ () => planCostliestNodes(tree, 1)[0]?.id ?? tree.root.id
);
const [highlight, setHighlight] = useState<PlanHighlightMode>("off");
// Collapsed subtrees live here rather than in the diagram so switching tabs
@@ -342,9 +344,7 @@ export function QueryPlanViewer({
() => new Set()
);
// A node the diagram should scroll to, rather than merely mark as selected.
- const [revealId, setRevealId] = useState<string | undefined>(() =>
- syncSelectionWithHash ? fragmentSelection(tree) : undefined
- );
+ const [revealId, setRevealId] = useState<string | undefined>();
const selectedNode = findPlanNode(tree, selectedId);
const stacked = useMediaQuery(STACK_QUERY);
@@ -377,40 +377,20 @@ export function QueryPlanViewer({
[collapsedIds, selectedId, tree]
);
- // Naming the selection in the fragment is what makes a node shareable. It
- // replaces rather than pushes, so Back leaves the page instead of walking
- // through every node the reader clicked on the way here.
- //
- // Only a selection the reader moved is written: naming the root on load
- // would turn every reload into a followed deep link, which reveals the node
- // and takes the view away from the fit the page opened on.
- const writtenSelection = useRef(selectedId);
- useEffect(() => {
- if (!syncSelectionWithHash) return;
- if (selectedId === writtenSelection.current) return;
- writtenSelection.current = selectedId;
- const fragment = planNodeFragment(selectedId);
- if (location.hash !== fragment) {
- history.replaceState(null, "", fragment);
- }
- }, [selectedId, syncSelectionWithHash]);
-
- // Following a second link to the page it is already on changes the fragment
- // without reloading anything.
- useEffect(() => {
- if (!syncSelectionWithHash) return;
- const onHashChange = () => {
- const id = fragmentSelection(tree);
- if (id === undefined) return;
- selectNode(id);
- setRevealId(id);
- };
- window.addEventListener("hashchange", onHashChange);
- return () => window.removeEventListener("hashchange", onHashChange);
- }, [tree, selectNode, syncSelectionWithHash]);
-
const onRevealed = useCallback(() => setRevealId(undefined), []);
+ // Choosing a ranked operator also brings it into view on the diagram.
+ const summary = tree.estimates.cost ? (
+ <QueryPlanSummary
+ tree={tree}
+ selectedId={selectedId}
+ onSelect={(id) => {
+ selectNode(id);
+ if (tab === "diagram") setRevealId(id);
+ }}
+ />
+ ) : null;
+
return (
<Tabs
value={tab}
@@ -421,15 +401,9 @@ export function QueryPlanViewer({
)}
>
<TabsList className="shrink-0 flex-wrap px-4 pt-3">
- <TabsTrigger value="text">{translate("tab.text")}</TabsTrigger>
<TabsTrigger value="diagram">{translate("tab.diagram")}</TabsTrigger>
<TabsTrigger value="grid">{translate("tab.grid")}</TabsTrigger>
- {/* The summary is where the plan's cost goes, which a plan without
- cost estimates cannot say. */}
- {tree.estimates.cost ? (
- <TabsTrigger value="summary">{translate("tab.summary")}</TabsTrigger>
- ) : null}
- <TabsTrigger value="query">{translate("tab.query")}</TabsTrigger>
+ <TabsTrigger value="text">{translate("tab.text")}</TabsTrigger>
{note ? (
<span className="ml-auto self-center text-sm text-control-light">
{note}
@@ -444,7 +418,11 @@ export function QueryPlanViewer({
keepMounted
className="mt-0 flex min-h-0 flex-1 flex-col overflow-hidden"
>
- <PlanWithDetails stacked={stacked} node={selectedNode}>
+ <PlanWithDetails
+ stacked={stacked}
+ node={selectedNode}
+ summary={summary}
+ >
<div
className={cn(
"flex shrink-0 flex-wrap items-center gap-4 px-4 py-2",
@@ -463,13 +441,8 @@ export function QueryPlanViewer({
/>
</div>
) : null}
- <PlanTotalsLine tree={tree} />
+ <PlanTotalsLine tree={tree} legend={legend} />
</div>
- {legend ? (
- <p className="shrink-0 px-4 pb-2 text-xs leading-4 text-control-light">
- {legend}
- </p>
- ) : null}
<QueryPlanDiagram
tree={tree}
selectedId={selectedId}
@@ -487,7 +460,11 @@ export function QueryPlanViewer({
value="grid"
className="mt-0 flex min-h-0 flex-1 flex-col overflow-hidden"
>
- <PlanWithDetails stacked={stacked} node={selectedNode}>
+ <PlanWithDetails
+ stacked={stacked}
+ node={selectedNode}
+ summary={summary}
+ >
<div className="flex shrink-0 flex-wrap items-center justify-end gap-4 px-4 py-2">
<PlanTotalsLine tree={tree} />
</div>
@@ -499,46 +476,12 @@ export function QueryPlanViewer({
</PlanWithDetails>
</TabsPanel>
- {tree.estimates.cost ? (
- <TabsPanel
- value="summary"
- className="mt-0 flex min-h-0 flex-1 flex-col overflow-hidden"
- >
- <PlanWithDetails stacked={stacked} node={selectedNode}>
- <QueryPlanSummary
- tree={tree}
- selectedId={selectedId}
- onSelect={selectNode}
- />
- </PlanWithDetails>
- </TabsPanel>
- ) : null}
-
<TabsPanel
value="text"
className="mt-0 flex min-h-0 flex-1 flex-col overflow-hidden"
>
<TextPlan source={textPlan} disallowCopyingData={disallowCopyingData} />
</TabsPanel>
-
- <TabsPanel
- value="query"
- className="mt-0 flex min-h-0 flex-1 flex-col overflow-hidden"
- >
- {query ? (
- <CopyablePanel
- content={query}
- label={translate("copy.query")}
- disallowCopyingData={disallowCopyingData}
- >
- <pre className={MONOSPACE_BLOCK_CLASS}>{query}</pre>
- </CopyablePanel>
- ) : (
- <p className="p-4 text-sm leading-5 text-control-light">
- {translate("query.missing")}
- </p>
- )}
- </TabsPanel>
</Tabs>
);
}
diff --git a/frontend/src/apps/explain-visualizer/explain-visualizer.css b/frontend/src/apps/explain-visualizer/explain-visualizer.css
deleted file mode 100644
index 3d44a769a1..0000000000
--- a/frontend/src/apps/explain-visualizer/explain-visualizer.css
+++ /dev/null
@@ -1,14 +0,0 @@
-/* The Explain Visualizer entry loads the product's Tailwind entry and nothing
- else of the app, so the page itself has to fill the tab. */
-
-html,
-body,
-#app {
- height: 100%;
-}
-
-body {
- margin: 0;
- background-color: rgb(var(--color-background));
- color: rgb(var(--color-main));
-}
diff --git a/frontend/src/apps/explain-visualizer/main.tsx b/frontend/src/apps/explain-visualizer/main.tsx
deleted file mode 100644
index d1e70d68f7..0000000000
--- a/frontend/src/apps/explain-visualizer/main.tsx
+++ /dev/null
@@ -1,17 +0,0 @@
-import "@/assets/css/tailwind.css";
-import "./explain-visualizer.css";
-import { Tooltip as BaseTooltip } from "@base-ui/react/tooltip";
-import { createRoot } from "react-dom/client";
-import { ExplainVisualizerApp } from "./ExplainVisualizerApp";
-
-// Some bundled dependencies expect a `global` reference on the window.
-(globalThis as typeof globalThis & Record<string, unknown>).global = globalThis;
-
-const container = document.getElementById("app");
-if (container) {
- createRoot(container).render(
- <BaseTooltip.Provider>
- <ExplainVisualizerApp />
- </BaseTooltip.Provider>
- );
-}
diff --git a/frontend/src/apps/explain-visualizer/plan-i18n.tsx b/frontend/src/apps/explain-visualizer/plan-i18n.tsx
index e1bbbc605f..4ec9363e60 100644
--- a/frontend/src/apps/explain-visualizer/plan-i18n.tsx
+++ b/frontend/src/apps/explain-visualizer/plan-i18n.tsx
@@ -4,7 +4,6 @@ const ENGLISH = {
"copy.copied": "Copied",
"copy.failed": "Copy failed",
"copy.plan": "Copy plan",
- "copy.query": "Copy query",
"details.select-node": "Select a node to see its details.",
"diagram.collapse": "Collapse {{count}} nodes under {{node}}",
"diagram.cost": "cost {{cost}}",
@@ -67,33 +66,11 @@ const ENGLISH = {
"metric.row-width": "Row width",
"metric.startup-cost": "Startup cost",
"metric.total-cost": "Total cost",
- "query.missing": "The statement was not captured with this plan.",
- "summary.added-cost": "Added cost",
- "summary.cost-by-operation": "Cost by operation",
- "summary.cost-by-operation-description":
- "Every node type in the plan and what it costs in total.",
- "summary.cost-ranges": "Cost ranges",
- "summary.cost-ranges-description":
- "Each node spans its startup cost — the cost before its first row — to its total cost, both of which include everything below it. Darker spans carry more of the plan's cost. Costs are not a schedule: two inputs of a join overlap here but run one after the other.",
- "summary.costliest": "Costliest operators",
- "summary.costliest-description":
- "Ranked by the cost a node adds on top of its children. Where an input runs repeatedly, as under a nested loop, some engines count the repeats in the node that reruns it rather than in the input itself.",
- "summary.count": "Count",
- "summary.estimate-note":
- "The statement was planned but not run, so every figure here is an optimizer estimate rather than a measurement. Cost units are arbitrary and comparable only within this plan.",
- "summary.estimated-rows-returned": "Estimated rows returned",
+ "summary.costliest": "Costliest by estimated cost",
"summary.no-added-cost":
"No node in this plan adds an estimated cost of its own.",
- "summary.nodes": "Nodes",
- "summary.operation": "Operation",
- "summary.share": "Share",
- "summary.timeline-node":
- "{{name}}, cost {{startup}} to {{total}}, {{share}} of plan cost",
- "summary.total-estimated-cost": "Total estimated cost",
"tab.diagram": "Diagram",
- "tab.grid": "Grid",
- "tab.query": "Query",
- "tab.summary": "Summary",
+ "tab.grid": "Table",
"tab.text": "Text",
"totals.estimated-cost": "estimated cost {{cost}}",
"totals.nodes": "{{count}} nodes",
diff --git a/frontend/src/apps/explain-visualizer/plan-layout.test.ts b/frontend/src/apps/explain-visualizer/plan-layout.test.ts
index 970a35c468..90b80a95f9 100644
--- a/frontend/src/apps/explain-visualizer/plan-layout.test.ts
+++ b/frontend/src/apps/explain-visualizer/plan-layout.test.ts
@@ -8,8 +8,8 @@ import {
PLAN_READABLE_SCALE,
planFitsViewport,
planFitViewport,
- planGuideLevels,
planIndentPixels,
+ planIndentStep,
planMiniMap,
planNodeCenter,
planNodeOnScreen,
@@ -184,25 +184,25 @@ describe("layoutPlan with collapsed subtrees", () => {
});
describe("planIndentPixels", () => {
- test("steps with depth and then stops, so deep rows stay readable", () => {
- expect([0, 1, 2, 6, 7, 30].map(planIndentPixels)).toEqual([
- 0, 12, 24, 72, 72, 72,
- ]);
+ test("steps with depth at every level", () => {
+ expect([0, 1, 2, 6, 7, 30].map((depth) => planIndentPixels(depth))).toEqual(
+ [0, 12, 24, 72, 84, 360]
+ );
+ expect(planIndentPixels(30, 4)).toBe(120);
});
});
-describe("planGuideLevels", () => {
- test("draws one level per indent step the row actually has", () => {
- expect(planGuideLevels([])).toEqual([]);
- expect(planGuideLevels([true, false])).toEqual([true, false]);
+describe("planIndentStep", () => {
+ test("keeps the full step while the plan's indent fits", () => {
+ expect([0, 1, 7, 12].map(planIndentStep)).toEqual([12, 12, 12, 12]);
});
- test("keeps the levels nearest the row once the indent stops growing", () => {
- const deep = [true, true, false, true, false, true, false, true];
- // Eight levels of nesting, six columns of indent: the six closest to the
- // row survive, so the connector into its own parent is always drawn.
- expect(planGuideLevels(deep)).toEqual(deep.slice(2));
- expect(planGuideLevels(deep)).toHaveLength(planIndentPixels(8) / 12);
+ test("narrows the step so a deep plan's indent stays bounded", () => {
+ expect(planIndentStep(13)).toBe(11);
+ expect(planIndentStep(30)).toBe(4);
+ expect(30 * planIndentStep(30)).toBeLessThanOrEqual(144);
+ // Past the narrowest step the guides still line up; the indent grows.
+ expect(planIndentStep(500)).toBe(2);
});
});
@@ -335,6 +335,29 @@ describe("planOpeningViewport", () => {
expect(planFitsViewport(layout, size, view)).toBe(false);
});
+ test("centers the focus node when it is given", () => {
+ const tree = parseFixture(hashJoinAggregateSort);
+ const layout = layoutPlan(tree.root);
+ const size = { width: 800, height: 300 };
+ // The orders scan sits at the bottom of the plan, below what opens on the
+ // root.
+ const focus = layout.nodes.find((entry) => entry.node.id === "0.0.0.0");
+ if (!focus) throw new Error("the fixture's orders scan is missing");
+ const view = planOpeningViewport(layout, size, focus.node.id);
+ const center = planNodeCenter(focus);
+
+ expect(view.scale).toBe(PLAN_READABLE_SCALE);
+ expect(view.y).toBeLessThan(0);
+ // Centered, unless that would scroll past the plan's bottom edge.
+ expect(view.y + center.y * view.scale).toBeCloseTo(
+ Math.max(
+ size.height / 2,
+ center.y * view.scale + size.height - layout.height * view.scale
+ ),
+ 6
+ );
+ });
+
test("centers the root across a plan wider than the screen", () => {
const layout = layoutPlan(bare("0", leaves("0", 12)));
const size = { width: 600, height: 400 };
diff --git a/frontend/src/apps/explain-visualizer/plan-layout.ts b/frontend/src/apps/explain-visualizer/plan-layout.ts
index ae2a232d77..b7fc15cf02 100644
--- a/frontend/src/apps/explain-visualizer/plan-layout.ts
+++ b/frontend/src/apps/explain-visualizer/plan-layout.ts
@@ -1,6 +1,4 @@
import { hierarchy, tree } from "d3-hierarchy";
-// Deep import: `@/utils` (the barrel) transitively pulls in Monaco, which this
-// standalone entry never loads. `minmax` itself is a leaf math helper.
import { minmax } from "@/utils/math";
import type { PlanNode } from "./plan-model";
@@ -16,30 +14,30 @@ export const PLAN_NODE_WIDTH = 216;
export const PLAN_NODE_HEIGHT = 96;
/**
- * Indent per nesting level for the surfaces that list the plan as rows, capped
- * so a ten-deep plan still leaves the node column readable at phone width.
- * Callers expose the uncapped depth through `aria-level`.
+ * Indent per nesting level for the surfaces that list the plan as rows. Every
+ * level of a plan indents by the same step, so a row's tree guides line up
+ * with its ancestors' at any depth. A plan too deep for the full step within
+ * `PLAN_MAX_INDENT` gets a narrower one, which leaves the node column room
+ * for the names.
*/
export const PLAN_INDENT_STEP = 12;
-const MAX_INDENT_LEVELS = 6;
-
-export function planIndentPixels(depth: number): number {
- return Math.min(Math.max(depth, 0), MAX_INDENT_LEVELS) * PLAN_INDENT_STEP;
+const PLAN_MAX_INDENT = 144;
+const PLAN_MIN_INDENT_STEP = 2;
+
+/** The indent step for a plan whose deepest row is `maxDepth` levels down. */
+export function planIndentStep(maxDepth: number): number {
+ if (maxDepth <= 0) return PLAN_INDENT_STEP;
+ return Math.max(
+ PLAN_MIN_INDENT_STEP,
+ Math.min(PLAN_INDENT_STEP, Math.floor(PLAN_MAX_INDENT / maxDepth))
+ );
}
-/**
- * The connector levels a row has room to draw, one per `PLAN_INDENT_STEP` of
- * its indent.
- *
- * Past the indent cap there is no column left to draw in, so the deepest levels
- * are kept: those are the ones that tie the row to its own parent, which is
- * what a reader traces. Mirrors `planIndentPixels`, and each entry says whether
- * that level's branch carries on below the row.
- */
-export function planGuideLevels(
- branchContinues: readonly boolean[]
-): readonly boolean[] {
- return branchContinues.slice(-MAX_INDENT_LEVELS);
+export function planIndentPixels(
+ depth: number,
+ step: number = PLAN_INDENT_STEP
+): number {
+ return Math.max(depth, 0) * step;
}
const COLUMN_GAP = 32;
@@ -188,13 +186,14 @@ export function planFitViewport(
/**
* The view the diagram opens on: the whole plan when its cards are readable at
- * the scale that shows all of it, and otherwise the readable scale from the
- * root down, centered on the root as far as the plan's edges allow. The
- * mini-map then offers the rest.
+ * the scale that shows all of it, and otherwise the readable scale centered on
+ * the focus node, or the root when there is none, as far as the plan's edges
+ * allow. The mini-map then offers the rest.
*/
export function planOpeningViewport(
layout: PlanLayout,
- size: PlanViewportSize
+ size: PlanViewportSize,
+ focusId?: string
): PlanViewport {
const fit = planFitViewport(layout, size);
if (size.width <= 0 || size.height <= 0) return fit;
@@ -202,15 +201,19 @@ export function planOpeningViewport(
const scale = PLAN_READABLE_SCALE;
const width = layout.width * scale;
const height = layout.height * scale;
- const [root] = layout.nodes;
- const rootX = root ? planNodeCenter(root).x * scale : width / 2;
+ const focus =
+ layout.nodes.find((entry) => entry.node.id === focusId) ?? layout.nodes[0];
+ const center = focus ? planNodeCenter(focus) : { x: layout.width / 2, y: 0 };
return {
scale,
x:
width <= size.width
? (size.width - width) / 2
- : minmax(size.width / 2 - rootX, size.width - width, 0),
- y: height <= size.height ? (size.height - height) / 2 : 0,
+ : minmax(size.width / 2 - center.x * scale, size.width - width, 0),
+ y:
+ height <= size.height
+ ? (size.height - height) / 2
+ : minmax(size.height / 2 - center.y * scale, size.height - height, 0),
};
}
@@ -234,8 +237,8 @@ export function planNodeCenter(placed: PlanLayoutNode): {
/**
* The viewport that puts a content-space point in the middle of the screen,
- * at the zoom already in use. Both the mini-map and a deep link land on a node
- * this way.
+ * at the zoom already in use. Both the mini-map and the ranking beside the
+ * diagram land on a node this way.
*/
export function planViewportCenteredOn(
point: { x: number; y: number },
diff --git a/frontend/src/apps/explain-visualizer/plan-model.test.ts b/frontend/src/apps/explain-visualizer/plan-model.test.ts
index 356f9d36fe..5acfb8b0fe 100644
--- a/frontend/src/apps/explain-visualizer/plan-model.test.ts
+++ b/frontend/src/apps/explain-visualizer/plan-model.test.ts
@@ -18,18 +18,14 @@ import {
type PlanTree,
parseWithDepthLimit,
planCollapsedAncestor,
- planCostByOperation,
planCostliestNodes,
planDescendantCount,
planEdgeWidth,
planHighlightIntensity,
- planNodeFragment,
- planNodeIdFromFragment,
planRevealNode,
planRows,
planSelfCost,
planSelfCostShare,
- planTimeline,
} from "./plan-model";
import { parsePostgresPlan } from "./postgres-plan";
import cteNestedLoopInitplan from "./test-data/postgres/cte-nested-loop-initplan.json";
@@ -423,28 +419,6 @@ describe("planRevealNode", () => {
});
});
-describe("plan node fragments", () => {
- test("round-trips a node id through the fragment that names it", () => {
- expect(planNodeFragment("0.1.1")).toBe("#node-0.1.1");
- expect(planNodeIdFromFragment(planNodeFragment("0.1.1"))).toBe("0.1.1");
- expect(planNodeIdFromFragment("node-0")).toBe("0");
- });
-
- test("ignores a fragment that does not name a node", () => {
- expect(planNodeIdFromFragment(undefined)).toBeUndefined();
- expect(planNodeIdFromFragment("")).toBeUndefined();
- expect(planNodeIdFromFragment("#")).toBeUndefined();
- expect(planNodeIdFromFragment("#node-")).toBeUndefined();
- expect(planNodeIdFromFragment("#section-2")).toBeUndefined();
- expect(planNodeIdFromFragment("#node-%")).toBeUndefined();
- });
-
- test("escapes an id that is not plain fragment text", () => {
- expect(planNodeFragment("a b#c")).toBe("#node-a%20b%23c");
- expect(planNodeIdFromFragment(planNodeFragment("a b#c"))).toBe("a b#c");
- });
-});
-
describe("costBasis", () => {
test("is the root's total cost, which the self costs add back up to", () => {
const tree = parseFixture(hashJoinAggregateSort);
@@ -526,67 +500,6 @@ describe("planEdgeWidth", () => {
});
});
-describe("planTimeline", () => {
- test("spans each node from its startup cost to its total cost", () => {
- const tree = parseFixture(hashJoinAggregateSort);
- const rows = planTimeline(tree);
- const basis = tree.costBasis;
-
- expect(rows.map((row) => row.node.id)).toEqual(
- tree.nodes.map((entry) => entry.id)
- );
-
- const join = rows[2];
- expect(join.node.nodeType).toBe("Hash Join");
- expect(join.start).toBeCloseTo(140.5 / basis, 6);
- expect(join.end).toBeCloseTo(1090.86 / basis, 6);
- expect(join.share).toBeCloseTo(193.86 / basis, 6);
- });
-
- test("keeps every span inside the axis, Limit plans included", () => {
- for (const fixture of [
- hashJoinAggregateSort,
- cteNestedLoopInitplan,
- seqScanFilter,
- ]) {
- for (const row of planTimeline(parseFixture(fixture))) {
- expect(row.start).toBeGreaterThanOrEqual(0);
- expect(row.end).toBeLessThanOrEqual(1);
- expect(row.end).toBeGreaterThanOrEqual(row.start);
- }
- }
- });
-
- test("carries the nesting depth so the rows can be indented", () => {
- const tree = parseFixture(cteNestedLoopInitplan);
- expect(planTimeline(tree).map((row) => row.depth)).toEqual([
- 0, 1, 2, 1, 2, 2,
- ]);
- });
-
- test("collapses to the origin when the planner costs the plan at zero", () => {
- const tree = buildPlanTree(node("0", {}, [node("0.0")]));
- expect(planTimeline(tree)).toEqual([
- {
- node: tree.nodes[0],
- depth: 0,
- branchContinues: [],
- start: 0,
- end: 0,
- share: 0,
- },
- {
- node: tree.nodes[1],
- depth: 1,
- branchContinues: [false],
- start: 0,
- end: 0,
- share: 0,
- },
- ]);
- });
-});
-
describe("planCostliestNodes", () => {
test("ranks by the cost a node adds on top of its children", () => {
const tree = parseFixture(hashJoinAggregateSort);
@@ -596,8 +509,6 @@ describe("planCostliestNodes", () => {
["Seq Scan", "orders"],
["HashAggregate", "c.region"],
["Hash Join", "(o.customer_id = c.id)"],
- ["Seq Scan", "customers"],
- ["Sort", "(count(*)) DESC"],
]);
});
@@ -615,34 +526,3 @@ describe("planCostliestNodes", () => {
expect(planCostliestNodes(buildPlanTree(node("0")))).toEqual([]);
});
});
-
-describe("planCostByOperation", () => {
- test("sums each node type's own cost and ranks the types", () => {
- const tree = parseFixture(hashJoinAggregateSort);
- const operations = planCostByOperation(tree);
-
- expect(operations.map((entry) => entry.nodeType)).toEqual([
- "Seq Scan",
- "HashAggregate",
- "Hash Join",
- "Sort",
- "Hash",
- ]);
- expect(operations[0]).toMatchObject({ nodeType: "Seq Scan", count: 2 });
- expect(operations[0].selfCost).toBeCloseTo(897, 5);
- expect(operations[0].share).toBeCloseTo(897 / 1465.93, 6);
- expect(operations.reduce((sum, entry) => sum + entry.count, 0)).toBe(
- tree.nodes.length
- );
- });
-
- test("lists a zero-cost plan's operations without a share", () => {
- const tree = buildPlanTree(
- node("0", { nodeType: "Limit" }, [node("0.0", { nodeType: "Seq Scan" })])
- );
- expect(planCostByOperation(tree)).toEqual([
- { nodeType: "Limit", count: 1, selfCost: 0, share: 0 },
- { nodeType: "Seq Scan", count: 1, selfCost: 0, share: 0 },
- ]);
- });
-});
diff --git a/frontend/src/apps/explain-visualizer/plan-model.ts b/frontend/src/apps/explain-visualizer/plan-model.ts
index bc06719c3b..8d87712443 100644
--- a/frontend/src/apps/explain-visualizer/plan-model.ts
+++ b/frontend/src/apps/explain-visualizer/plan-model.ts
@@ -62,15 +62,14 @@ export interface PlanTree {
readonly maxSelfCost: number;
readonly maxRows: number;
/**
- * The whole plan's cost: the denominator of every cost share and the maximum
- * of the summary timeline's axis.
+ * The whole plan's cost: the denominator of every cost share.
*
* Normally this is the root's total cost, which by construction equals the
* sum of every node's self cost. A node that stops its children early —
* `Limit` is the common one — reports a total below its children's, and
* `selfCost` clamps that difference at zero, so the self costs can add up to
* more than the root reports. Taking the larger of the two keeps every share
- * at or below 100% and every timeline bar inside the axis.
+ * at or below 100%.
*/
readonly costBasis: number;
}
@@ -328,38 +327,8 @@ export function planRevealNode(
return next;
}
-/**
- * The URL fragment naming a plan node, which is what makes one shareable.
- *
- * Ids come from a parser rather than from the user, but they are not promised
- * to stay bare digits and dots, so they are escaped both ways.
- */
-const NODE_FRAGMENT_PREFIX = "node-";
-
-export function planNodeFragment(id: string): string {
- return `#${NODE_FRAGMENT_PREFIX}${encodeURIComponent(id)}`;
-}
-
-/** The node id a fragment names, or undefined when it names something else. */
-export function planNodeIdFromFragment(
- fragment: string | undefined
-): string | undefined {
- if (!fragment) return undefined;
- const body = fragment.startsWith("#") ? fragment.slice(1) : fragment;
- if (!body.startsWith(NODE_FRAGMENT_PREFIX)) return undefined;
- const id = body.slice(NODE_FRAGMENT_PREFIX.length);
- if (!id) return undefined;
- try {
- return decodeURIComponent(id);
- } catch {
- // A hand-edited fragment can hold a stray percent sign, which is a bad
- // fragment rather than a reason to fail the page.
- return undefined;
- }
-}
-
-// The standalone visualizer entry never initializes i18n, so number formatting
-// is pinned to one locale rather than following the workspace language.
+// Number formatting is pinned to one locale: the viewer's text arrives through
+// a translate function, and its numbers stay comparable across plans.
const costFormat = new Intl.NumberFormat("en-US", {
maximumFractionDigits: 2,
});
@@ -435,40 +404,8 @@ export function planEdgeWidth(
return Math.round(width * 100) / 100;
}
-export interface PlanTimelineRow extends PlanRow {
- /** Where the node's first row is ready, as a fraction of the plan's cost. */
- readonly start: number;
- /** Where the node's last row is ready, as a fraction of the plan's cost. */
- readonly end: number;
- /** The node's self cost as a fraction of the plan's cost. */
- readonly share: number;
-}
-
-/**
- * Every node as a span from its startup cost to its total cost.
- *
- * Both costs include the node's whole subtree, so a span says how much of the
- * plan's cost a node accounts for and how much of that is paid before its first
- * row. It is not a schedule: siblings each start from their own subtree's cost,
- * so two inputs of a join overlap on this axis while actually running one after
- * the other.
- */
-export function planTimeline(tree: PlanTree): PlanTimelineRow[] {
- const fraction = (value = 0) =>
- tree.costBasis <= 0 ? 0 : Math.min(1, Math.max(0, value / tree.costBasis));
- return planRows(tree.root).map((row) => {
- const start = fraction(row.node.startupCost);
- return {
- ...row,
- start,
- end: Math.max(start, fraction(row.node.totalCost)),
- share: planSelfCostShare(row.node, tree),
- };
- });
-}
-
-/** How many operators the summary names before it stops being a summary. */
-export const PLAN_COSTLIEST_LIMIT = 5;
+/** How many operators the side panel ranks before it stops being a summary. */
+export const PLAN_COSTLIEST_LIMIT = 3;
/**
* The nodes that own the most cost, largest first. A node that adds nothing on
@@ -484,35 +421,6 @@ export function planCostliestNodes(
.slice(0, limit);
}
-export interface PlanOperationCost {
- readonly nodeType: string;
- readonly count: number;
- readonly selfCost: number;
- readonly share: number;
-}
-
-/** Each node type in the plan with what it costs in total, largest first. */
-export function planCostByOperation(tree: PlanTree): PlanOperationCost[] {
- const totals = new Map<string, { count: number; selfCost: number }>();
- for (const node of tree.nodes) {
- const entry = totals.get(node.nodeType) ?? { count: 0, selfCost: 0 };
- entry.count += 1;
- entry.selfCost += node.selfCost ?? 0;
- totals.set(node.nodeType, entry);
- }
- return [...totals]
- .map(([nodeType, entry]) => ({
- nodeType,
- count: entry.count,
- selfCost: entry.selfCost,
- share:
- tree.costBasis <= 0 ? 0 : Math.min(1, entry.selfCost / tree.costBasis),
- }))
- .sort(
- (a, b) => b.selfCost - a.selfCost || a.nodeType.localeCompare(b.nodeType)
- );
-}
-
/**
* How strongly a node should be shaded, from 0 (no shading) to 1.
*
diff --git a/frontend/src/hooks/useExecuteSQL.ts b/frontend/src/hooks/useExecuteSQL.ts
index a52657115f..a4fdb3586b 100644
--- a/frontend/src/hooks/useExecuteSQL.ts
+++ b/frontend/src/hooks/useExecuteSQL.ts
@@ -96,7 +96,7 @@ export const useExecuteSQL = () => {
// Propagates the status change to the Zustand store via
// `updateDatabaseQueryContext` (the path that drives React re-renders).
// For ad-hoc contexts that aren't tracked under `(database, ctx.id)` —
- // e.g. the ephemeral context in `getExplainTokenForMSSQL` — the store
+ // e.g. the ephemeral context of a plan request — the store
// action returns `undefined`; we fall back to mutating the passed-in
// `ctx` directly so the caller still sees the new fields after
// `await runQuery(...)`.
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index 806c4dddb0..485f9af8f1 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -3469,8 +3469,7 @@
"copy": {
"copied": "Copied",
"failed": "Copy failed",
- "plan": "Copy plan",
- "query": "Copy query"
+ "plan": "Copy plan"
},
"details": {
"select-node": "Select a node to see its details."
@@ -3534,32 +3533,13 @@
"startup-cost": "Startup cost",
"total-cost": "Total cost"
},
- "query": {
- "missing": "The statement was not captured with this plan."
- },
"summary": {
- "added-cost": "Added cost",
- "cost-by-operation": "Cost by operation",
- "cost-by-operation-description": "Every node type in the plan and what it costs in total.",
- "cost-ranges": "Cost ranges",
- "cost-ranges-description": "Each node spans its startup cost — the cost before its first row — to its total cost, both of which include everything below it. Darker spans carry more of the plan's cost. Costs are not a schedule: two inputs of a join overlap here but run one after the other.",
- "costliest": "Costliest operators",
- "costliest-description": "Ranked by the cost a node adds on top of its children. Where an input runs repeatedly, as under a nested loop, some engines count the repeats in the node that reruns it rather than in the input itself.",
- "count": "Count",
- "estimate-note": "The statement was planned but not run, so every figure here is an optimizer estimate rather than a measurement. Cost units are arbitrary and comparable only within this plan.",
- "estimated-rows-returned": "Estimated rows returned",
- "no-added-cost": "No node in this plan adds an estimated cost of its own.",
- "nodes": "Nodes",
- "operation": "Operation",
- "share": "Share",
- "timeline-node": "{{name}}, cost {{startup}} to {{total}}, {{share}} of plan cost",
- "total-estimated-cost": "Total estimated cost"
+ "costliest": "Costliest by estimated cost",
+ "no-added-cost": "No node in this plan adds an estimated cost of its own."
},
"tab": {
"diagram": "Diagram",
- "grid": "Grid",
- "query": "Query",
- "summary": "Summary",
+ "grid": "Table",
"text": "Text"
},
"totals": {
diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.json
index a56790dcdf..be6cfbcdcd 100644
--- a/frontend/src/locales/es-ES.json
+++ b/frontend/src/locales/es-ES.json
@@ -3469,8 +3469,7 @@
"copy": {
"copied": "Copiado",
"failed": "Error al copiar",
- "plan": "Copiar plan",
- "query": "Copiar consulta"
+ "plan": "Copiar plan"
},
"details": {
"select-node": "Selecciona un nodo para ver sus detalles."
@@ -3534,32 +3533,13 @@
"startup-cost": "Coste inicial",
"total-cost": "Coste total"
},
- "query": {
- "missing": "La sentencia no se guardó con este plan."
- },
"summary": {
- "added-cost": "Coste añadido",
- "cost-by-operation": "Coste por operación",
- "cost-by-operation-description": "Cada tipo de nodo del plan y su coste total.",
- "cost-ranges": "Rangos de coste",
- "cost-ranges-description": "Cada nodo abarca desde su coste inicial —el coste antes de su primera fila— hasta su coste total; ambos incluyen todo lo que hay debajo. Los intervalos más oscuros contienen más coste del plan. Los costes no son un calendario: dos entradas de una unión se solapan aquí, pero se ejecutan una tras otra.",
- "costliest": "Operadores más costosos",
- "costliest-description": "Ordenados por el coste que un nodo añade sobre sus hijos. Cuando una entrada se ejecuta repetidamente, como bajo un bucle anidado, algunos motores cuentan las repeticiones en el nodo que la vuelve a ejecutar y no en la propia entrada.",
- "count": "Cantidad",
- "estimate-note": "La sentencia se planificó, pero no se ejecutó, por lo que todas las cifras son estimaciones del optimizador y no mediciones. Las unidades de coste son arbitrarias y solo comparables dentro de este plan.",
- "estimated-rows-returned": "Filas devueltas estimadas",
- "no-added-cost": "Ningún nodo de este plan añade un coste estimado propio.",
- "nodes": "Nodos",
- "operation": "Operación",
- "share": "Proporción",
- "timeline-node": "{{name}}, coste de {{startup}} a {{total}}, {{share}} del coste del plan",
- "total-estimated-cost": "Coste total estimado"
+ "costliest": "Más costosos según el coste estimado",
+ "no-added-cost": "Ningún nodo de este plan añade un coste estimado propio."
},
"tab": {
"diagram": "Diagrama",
- "grid": "Cuadrícula",
- "query": "Consulta",
- "summary": "Resumen",
+ "grid": "Tabla",
"text": "Texto"
},
"totals": {
diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.json
index 508fd6ab1c..2e2cd69dee 100644
--- a/frontend/src/locales/ja-JP.json
+++ b/frontend/src/locales/ja-JP.json
@@ -3469,8 +3469,7 @@
"copy": {
"copied": "コピーしました",
"failed": "コピーに失敗しました",
- "plan": "プランをコピー",
- "query": "クエリをコピー"
+ "plan": "プランをコピー"
},
"details": {
"select-node": "詳細を表示するノードを選択してください。"
@@ -3534,32 +3533,13 @@
"startup-cost": "開始コスト",
"total-cost": "総コスト"
},
- "query": {
- "missing": "このプランにはステートメントが保存されていません。"
- },
"summary": {
- "added-cost": "追加コスト",
- "cost-by-operation": "操作別コスト",
- "cost-by-operation-description": "プラン内の各ノード種別と、その総コストです。",
- "cost-ranges": "コスト範囲",
- "cost-ranges-description": "各ノードは、最初の行を返す前の開始コストから、その配下のすべてを含む総コストまでを示します。濃い範囲ほどプランコストの割合が高くなります。コストは実行スケジュールではありません。結合の2つの入力はここでは重なりますが、実際には順番に実行されます。",
- "costliest": "高コストなオペレーター",
- "costliest-description": "ノードが子ノードに加えて追加するコスト順です。ネストループ配下などで入力が繰り返し実行される場合、一部のエンジンは反復コストを入力自体ではなく、その入力を再実行するノードに計上します。",
- "count": "件数",
- "estimate-note": "ステートメントはプランニングされましたが実行されていないため、ここにある数値はすべて測定値ではなくオプティマイザーの推定値です。コスト単位は任意で、このプラン内でのみ比較できます。",
- "estimated-rows-returned": "推定返却行数",
- "no-added-cost": "このプランには固有の推定コストを追加するノードがありません。",
- "nodes": "ノード",
- "operation": "操作",
- "share": "割合",
- "timeline-node": "{{name}}、コスト {{startup}} から {{total}}、プランコストの {{share}}",
- "total-estimated-cost": "推定総コスト"
+ "costliest": "推定コストの高い順",
+ "no-added-cost": "このプランには固有の推定コストを追加するノードがありません。"
},
"tab": {
"diagram": "ダイアグラム",
- "grid": "グリッド",
- "query": "クエリ",
- "summary": "概要",
+ "grid": "テーブル",
"text": "テキスト"
},
"totals": {
diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.json
index e2bd7d8ea0..99da11b0a5 100644
--- a/frontend/src/locales/vi-VN.json
+++ b/frontend/src/locales/vi-VN.json
@@ -3469,8 +3469,7 @@
"copy": {
"copied": "Đã sao chép",
"failed": "Sao chép thất bại",
- "plan": "Sao chép kế hoạch",
- "query": "Sao chép truy vấn"
+ "plan": "Sao chép kế hoạch"
},
"details": {
"select-node": "Chọn một nút để xem chi tiết."
@@ -3534,32 +3533,13 @@
"startup-cost": "Chi phí khởi động",
"total-cost": "Tổng chi phí"
},
- "query": {
- "missing": "Câu lệnh không được lưu cùng kế hoạch này."
- },
"summary": {
- "added-cost": "Chi phí thêm",
- "cost-by-operation": "Chi phí theo thao tác",
- "cost-by-operation-description": "Mỗi loại nút trong kế hoạch và tổng chi phí của nó.",
- "cost-ranges": "Khoảng chi phí",
- "cost-ranges-description": "Mỗi nút trải từ chi phí khởi động — chi phí trước hàng đầu tiên — đến tổng chi phí, cả hai đều bao gồm mọi thứ bên dưới. Khoảng tối hơn chiếm nhiều chi phí kế hoạch hơn. Chi phí không phải lịch thực thi: hai đầu vào của phép nối chồng lên nhau ở đây nhưng chạy lần lượt.",
- "costliest": "Toán tử tốn kém nhất",
- "costliest-description": "Xếp hạng theo chi phí mà một nút thêm ngoài các nút con. Khi một đầu vào chạy lặp lại, như trong vòng lặp lồng nhau, một số máy cơ sở dữ liệu tính số lần lặp vào nút chạy lại đầu vào thay vì chính đầu vào.",
- "count": "Số lượng",
- "estimate-note": "Câu lệnh đã được lập kế hoạch nhưng chưa chạy, vì vậy mọi số liệu ở đây là ước tính của bộ tối ưu hóa chứ không phải phép đo. Đơn vị chi phí là tùy ý và chỉ có thể so sánh trong kế hoạch này.",
- "estimated-rows-returned": "Số hàng trả về ước tính",
- "no-added-cost": "Không có nút nào trong kế hoạch này tự thêm chi phí ước tính.",
- "nodes": "Nút",
- "operation": "Thao tác",
- "share": "Tỷ lệ",
- "timeline-node": "{{name}}, chi phí từ {{startup}} đến {{total}}, {{share}} chi phí kế hoạch",
- "total-estimated-cost": "Tổng chi phí ước tính"
+ "costliest": "Tốn kém nhất theo chi phí ước tính",
+ "no-added-cost": "Không có nút nào trong kế hoạch này tự thêm chi phí ước tính."
},
"tab": {
"diagram": "Sơ đồ",
- "grid": "Lưới",
- "query": "Truy vấn",
- "summary": "Tóm tắt",
+ "grid": "Bảng",
"text": "Văn bản"
},
"totals": {
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index ea5a258591..6a97a09403 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -3469,8 +3469,7 @@
"copy": {
"copied": "已复制",
"failed": "复制失败",
- "plan": "复制计划",
- "query": "复制查询"
+ "plan": "复制计划"
},
"details": {
"select-node": "选择节点以查看详情。"
@@ -3534,32 +3533,13 @@
"startup-cost": "启动成本",
"total-cost": "总成本"
},
- "query": {
- "missing": "此计划未记录对应语句。"
- },
"summary": {
- "added-cost": "新增成本",
- "cost-by-operation": "按操作统计成本",
- "cost-by-operation-description": "计划中每种节点类型及其总成本。",
- "cost-ranges": "成本范围",
- "cost-ranges-description": "每个节点从启动成本(返回第一行前的成本)延伸到总成本,两者都包含其下所有节点。颜色越深表示承担的计划成本越高。成本并非执行时间表:连接的两个输入会在此重叠,但实际依次执行。",
- "costliest": "成本最高的操作符",
- "costliest-description": "按节点在其子节点之上增加的成本排序。当输入重复执行时(如嵌套循环),某些引擎会将重复成本计入重新运行该输入的节点,而不是输入本身。",
- "count": "数量",
- "estimate-note": "语句已规划但未执行,因此此处所有数据都是优化器估算值,而非测量值。成本单位是任意的,只能在此计划内比较。",
- "estimated-rows-returned": "预计返回行数",
- "no-added-cost": "此计划中没有节点自身增加预计成本。",
- "nodes": "节点",
- "operation": "操作",
- "share": "占比",
- "timeline-node": "{{name}},成本 {{startup}} 到 {{total}},占计划成本的 {{share}}",
- "total-estimated-cost": "预计总成本"
+ "costliest": "按预估成本最高的操作符",
+ "no-added-cost": "此计划中没有节点自身增加预计成本。"
},
"tab": {
"diagram": "图表",
- "grid": "网格",
- "query": "查询",
- "summary": "摘要",
+ "grid": "表格",
"text": "文本"
},
"totals": {
diff --git a/frontend/src/modules/sql-editor/components/ResultView/QueryPlanResultView.test.tsx b/frontend/src/modules/sql-editor/components/ResultView/QueryPlanResultView.test.tsx
index 36a56fd7e0..002ac452f8 100644
--- a/frontend/src/modules/sql-editor/components/ResultView/QueryPlanResultView.test.tsx
+++ b/frontend/src/modules/sql-editor/components/ResultView/QueryPlanResultView.test.tsx
@@ -11,26 +11,21 @@ vi.mock("@/apps/explain-visualizer/QueryPlanView", () => ({
QueryPlanView: ({
planSource,
textPlanSource,
- planQuery,
note,
translate,
disallowCopyingData,
- syncSelectionWithHash,
}: {
planSource: string;
textPlanSource?: string;
- planQuery?: string;
note?: React.ReactNode;
translate: (key: "tab.text") => string;
disallowCopyingData?: boolean;
- syncSelectionWithHash?: boolean;
}) => (
<div
data-testid="inline-query-plan"
data-copy-disabled={disallowCopyingData}
- data-hash-sync={syncSelectionWithHash}
>
- {planQuery}:{planSource}:{textPlanSource}:{translate("tab.text")}
+ {planSource}:{textPlanSource}:{translate("tab.text")}
{note ? <span>{note}</span> : null}
</div>
),
@@ -56,29 +51,24 @@ describe("QueryPlanResultView", () => {
<QueryPlanResultView
engine={Engine.POSTGRES}
rawPlan="raw plan"
- initialPlan={{ source: "structured plan", statement: "SELECT 1" }}
+ initialPlan={{ source: "structured plan" }}
disallowCopyingData
/>
);
expect(screen.getByTestId("inline-query-plan")).toHaveTextContent(
- "SELECT 1:structured plan:raw plan:sql-editor.query-plan-viewer.tab.text"
+ "structured plan:raw plan:sql-editor.query-plan-viewer.tab.text"
);
expect(screen.queryByRole("tab")).toBeNull();
expect(screen.getByTestId("inline-query-plan")).toHaveAttribute(
"data-copy-disabled",
"true"
);
- expect(screen.getByTestId("inline-query-plan")).toHaveAttribute(
- "data-hash-sync",
- "false"
- );
});
- test("loads a drawable plan immediately and opens on its text tab", async () => {
+ test("loads a drawable plan immediately and hands the viewer its text plan", async () => {
const loadPlan = vi.fn().mockResolvedValue({
source: "structured plan",
- statement: "EXPLAIN SELECT 1",
});
render(
<QueryPlanResultView
@@ -98,7 +88,7 @@ describe("QueryPlanResultView", () => {
});
test("does not reload when only the loader identity changes", async () => {
- const plan = { source: "structured plan", statement: "EXPLAIN SELECT 1" };
+ const plan = { source: "structured plan" };
const first = vi.fn().mockResolvedValue(plan);
const second = vi.fn().mockResolvedValue(plan);
const { rerender } = render(
@@ -165,7 +155,7 @@ describe("QueryPlanResultView", () => {
test("loads a text plan on demand when no picture is available", async () => {
const loadPlan = vi
.fn()
- .mockResolvedValue({ source: "Seq Scan on t", statement: "SELECT 1" });
+ .mockResolvedValue({ source: "Seq Scan on t" });
render(<QueryPlanResultView rawPlan="" loadPlan={loadPlan} estimated />);
expect(screen.getByText("common.loading")).toBeInTheDocument();
@@ -214,7 +204,7 @@ describe("QueryPlanResultView", () => {
test("puts the estimate note in the drawable viewer's tab row", async () => {
const loadPlan = vi
.fn()
- .mockResolvedValue({ source: "structured plan", statement: "SELECT 1" });
+ .mockResolvedValue({ source: "structured plan" });
render(
<QueryPlanResultView
engine={Engine.POSTGRES}
diff --git a/frontend/src/modules/sql-editor/components/ResultView/QueryPlanResultView.tsx b/frontend/src/modules/sql-editor/components/ResultView/QueryPlanResultView.tsx
index bbc3dccbeb..70805de549 100644
--- a/frontend/src/modules/sql-editor/components/ResultView/QueryPlanResultView.tsx
+++ b/frontend/src/modules/sql-editor/components/ResultView/QueryPlanResultView.tsx
@@ -11,11 +11,10 @@ import { CopyButton } from "@/components/ui/copy-button";
import { Tabs, TabsList, TabsPanel, TabsTrigger } from "@/components/ui/tabs";
import { Tooltip } from "@/components/ui/tooltip";
import { cn } from "@/lib/utils";
-import type { VisualizerEngine } from "@/utils/explainToken";
+import type { VisualizerEngine } from "@/utils/queryPlanEngines";
export interface InlineQueryPlan {
source: string;
- statement: string;
}
/** Fetches the plan; the signal fires when the reader cancels the load. */
@@ -146,11 +145,9 @@ export function QueryPlanResultView({
engine={engine}
planSource={plan.source}
textPlanSource={rawPlan || undefined}
- planQuery={plan.statement}
note={estimateNote}
translate={translatePlan}
disallowCopyingData={disallowCopyingData}
- syncSelectionWithHash={false}
/>
);
}
diff --git a/frontend/src/modules/sql-editor/components/ResultView/SingleResultView.test.tsx b/frontend/src/modules/sql-editor/components/ResultView/SingleResultView.test.tsx
index c01e12e38e..d330f6ecf3 100644
--- a/frontend/src/modules/sql-editor/components/ResultView/SingleResultView.test.tsx
+++ b/frontend/src/modules/sql-editor/components/ResultView/SingleResultView.test.tsx
@@ -280,9 +280,9 @@ vi.mock("./QueryPlanResultView", () => ({
disallowCopyingData,
}: {
rawPlan: string;
- initialPlan?: { source: string; statement: string };
+ initialPlan?: { source: string };
loadPlan?: () => Promise<
- { source: string; statement: string } | undefined
+ { source: string } | undefined
>;
disallowCopyingData?: boolean;
}) => {
diff --git a/frontend/src/modules/sql-editor/components/ResultView/SingleResultView.tsx b/frontend/src/modules/sql-editor/components/ResultView/SingleResultView.tsx
index 0160d617e1..6a8b92e82a 100644
--- a/frontend/src/modules/sql-editor/components/ResultView/SingleResultView.tsx
+++ b/frontend/src/modules/sql-editor/components/ResultView/SingleResultView.tsx
@@ -54,11 +54,11 @@ import {
QueryOptionSchema,
type QueryResult,
} from "@/types/proto-es/v1/sql_service_pb";
+import { hasProjectPermissionV2 } from "@/utils/iam/permission";
import {
isVisualizerEngine,
VISUALIZER_EXPLAIN_FORMATS,
-} from "@/utils/explainToken";
-import { hasProjectPermissionV2 } from "@/utils/iam/permission";
+} from "@/utils/queryPlanEngines";
import {
flattenElasticsearchSearchResult,
flattenNoSQLQueryResult,
@@ -988,8 +988,6 @@ function DatabaseInfo({ database }: { database: Database }) {
}
function getInlineQueryPlan(result: QueryResult): InlineQueryPlan | undefined {
- const { statement } = result;
- if (!statement) return undefined;
const lines = result.rows.map((row) =>
row.values.map((value) => String(extractSQLRowValuePlain(value)))
);
@@ -999,13 +997,12 @@ function getInlineQueryPlan(result: QueryResult): InlineQueryPlan | undefined {
? [result.columnNames, ...lines].map((line) => line.join("\t")).join("\n")
: lines.map((line) => line[0]).join("\n");
if (!source) return undefined;
- return { statement, source };
+ return { source };
}
// explainStatement asks the engine for the plan of a statement as it ran, in
// the format the visualizer draws where there is one and the engine's default
-// otherwise. The signal cancels the request. The plan carries the statement
-// itself, limit and all, for the viewer to show.
+// otherwise. The signal cancels the request.
async function explainStatement(
database: Database,
params: SQLEditorQueryParams,
@@ -1038,6 +1035,5 @@ async function explainStatement(
const result = resultSet?.results[0];
if (!result) return undefined;
if (result.error) throw new Error(result.error);
- const plan = getInlineQueryPlan(result);
- return plan && { ...plan, statement };
+ return getInlineQueryPlan(result);
}
diff --git a/frontend/src/utils/explainToken.ts b/frontend/src/utils/explainToken.ts
deleted file mode 100644
index dc524b0b89..0000000000
--- a/frontend/src/utils/explainToken.ts
+++ /dev/null
@@ -1,91 +0,0 @@
-import { Engine } from "@/types/proto-es/v1/common_pb";
-
-/**
- * The engines the query-plan visualizer draws, each with the explain output it
- * reads, named as `QueryOption.ExplainFormat` names it. The SQL editor offers
- * Visualize for exactly these engines and hands over the plan in this format;
- * the visualizer keys its parsers on the same table, so the two cannot drift.
- */
-export const VISUALIZER_EXPLAIN_FORMATS = {
- [Engine.POSTGRES]: "JSON",
- [Engine.MSSQL]: "XML",
- [Engine.SPANNER]: "JSON",
-} as const;
-
-export type VisualizerEngine = keyof typeof VISUALIZER_EXPLAIN_FORMATS;
-
-export const isVisualizerEngine = (
- engine: Engine
-): engine is VisualizerEngine => engine in VISUALIZER_EXPLAIN_FORMATS;
-
-export type StoredExplain = {
- statement: string;
- explain: string;
- engine: Engine;
-};
-
-/**
- * Deliberately not `randomString` from `./util`: the visualizer is a separate
- * entry that imports this module and nothing else of the app, and `./util`
- * drags dayjs, semver, DOMPurify and the i18n bundle in behind it.
- *
- * The token only has to be unique within one tab's sessionStorage — it is a
- * lookup key, not a secret.
- */
-const tokenSuffix = (): string => {
- const bytes = new Uint8Array(16);
- crypto.getRandomValues(bytes);
- return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join(
- ""
- );
-};
-
-const TOKEN_PREFIX = "explain-";
-
-/**
- * Drops the plans this tab stashed earlier.
- *
- * A plan is read once, by the tab this token opens, and `window.open` gives
- * that tab its own copy of sessionStorage — so the opener's copy is dead weight
- * the moment the visualizer has it. Left to accumulate, a few hundred-kilobyte
- * plans fill the origin's quota and every later click fails.
- */
-const dropPreviousExplains = () => {
- const stale: string[] = [];
- for (let i = 0; i < sessionStorage.length; i++) {
- const key = sessionStorage.key(i);
- if (key?.startsWith(TOKEN_PREFIX)) stale.push(key);
- }
- for (const key of stale) sessionStorage.removeItem(key);
-};
-
-// Used only by the legacy standalone entry; the SQL Editor passes plans
-// directly to QueryPlanView.
-export const createExplainToken = ({
- statement,
- explain,
- engine,
-}: StoredExplain): string => {
- const token = `${TOKEN_PREFIX}${tokenSuffix()}`;
-
- const json = JSON.stringify({ statement, explain, engine });
- dropPreviousExplains();
- sessionStorage.setItem(token, json);
-
- return token;
-};
-
-export const readExplainFromToken = (token: string) => {
- if (!token) return undefined;
- try {
- const json = sessionStorage.getItem(token) || "{}";
- const obj = JSON.parse(json) as StoredExplain;
- if (!obj) return undefined;
- if (typeof obj.statement === "string" && typeof obj.explain === "string") {
- return obj;
- }
- return undefined;
- } catch {
- return undefined;
- }
-};
diff --git a/frontend/src/utils/index.ts b/frontend/src/utils/index.ts
index 3030e026f4..c61551c279 100644
--- a/frontend/src/utils/index.ts
+++ b/frontend/src/utils/index.ts
@@ -7,7 +7,7 @@ export * from "./datetime";
export * from "./label";
export * from "./string";
export * from "./sqlEditor";
-export * from "./explainToken";
+export * from "./queryPlanEngines";
export * from "./web-storage";
export * from "./dom";
export * from "./schemaEditor";
diff --git a/frontend/src/utils/queryPlanEngines.ts b/frontend/src/utils/queryPlanEngines.ts
new file mode 100644
index 0000000000..b4bbe6ff4e
--- /dev/null
+++ b/frontend/src/utils/queryPlanEngines.ts
@@ -0,0 +1,19 @@
+import { Engine } from "@/types/proto-es/v1/common_pb";
+
+/**
+ * The engines the query-plan visualizer draws, each with the explain output it
+ * reads, named as `QueryOption.ExplainFormat` names it. The SQL editor offers
+ * Visualize for exactly these engines and hands over the plan in this format;
+ * the visualizer keys its parsers on the same table, so the two cannot drift.
+ */
+export const VISUALIZER_EXPLAIN_FORMATS = {
+ [Engine.POSTGRES]: "JSON",
+ [Engine.MSSQL]: "XML",
+ [Engine.SPANNER]: "JSON",
+} as const;
+
+export type VisualizerEngine = keyof typeof VISUALIZER_EXPLAIN_FORMATS;
+
+export const isVisualizerEngine = (
+ engine: Engine
+): engine is VisualizerEngine => engine in VISUALIZER_EXPLAIN_FORMATS;
diff --git a/frontend/vite.config.ts b/frontend/vite.config.ts
index 1b471ec38a..da506c6b5f 100644
--- a/frontend/vite.config.ts
+++ b/frontend/vite.config.ts
@@ -97,7 +97,6 @@ export default defineConfig({
rollupOptions: {
input: {
main: resolve(__dirname, "index.html"),
- "explain-visualizer": resolve(__dirname, "explain-visualizer.html"),
},
output: {
manualChunks: (id) => {