Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat(sql-editor): Explain action, measured plans, and the table a node reads (#21668)
Danny Xu0a987f5cfe5f
diff --git a/docs/design/query-plan-visualizer.md b/docs/design/query-plan-visualizer.mdindex 2bd2ccce9f..a87fa7162f 100644--- a/docs/design/query-plan-visualizer.md+++ b/docs/design/query-plan-visualizer.md@@ -59,55 +59,49 @@ context first.## 3. Design-### 3.1 Four triggers+### 3.1 Three triggers| Trigger | Where the control is | Journey | Executes? ||---|---|---|---|| Choose **Plan** in the result's view switch | the result pane, beside Table and Vertical | 1, 2 | no || Type `EXPLAIN …`, press **Run** (`Ctrl/Cmd+Enter`) | the editor | 1, 2 | as typed || Choose **Explain**, press `Ctrl/Cmd+E`, or right-click → Explain | Run button's dropdown; keyboard; editor context menu | 3 | **no** |-| Choose **Explain analyze** | Run button's dropdown | 1, 2 | **yes** |-Both explain actions go in the dropdown Run already has, not on the toolbar.-Spanner Studio puts "Results only / Explanation only" in exactly that place, and-none of the four reference products ships a toolbar Explain button. They explain+**Explain** goes in the dropdown Run already has, not on the toolbar. Spanner+Studio puts "Results only / Explanation only" in exactly that place, and none of+the four reference products ships a toolbar Explain button. It explains**exactly the statements Run would run** — same selection, same caret rule — sothere is no second scoping rule to learn. With one refusal: a submission thatsets session state, such as `SET search_path = tenant; SELECT * FROM orders`,cannot be explained statement by statement. `EXPLAIN SET …` is not valid, and-skipping the `SET` would plan the next statement against the wrong search path.-The actions say so rather than explaining part of the script — the same rule-§3.3 applies to the Plan view, stated once and enforced on both paths.--They are two actions, not one, because the difference is whether your query runs.-pgAdmin splits them the same way (F7 / Shift+F7). **Explain** never executes:-given a statement that already says `EXPLAIN ANALYZE`, it refuses and says why,-rather than running an expensive query behind a control whose whole purpose is-to avoid running it. **Explain analyze** executes by definition, and asks for a-machine-readable plan on that single run, so nothing needs re-running afterwards.--The mirror case: given a statement that already says plain `EXPLAIN`, **Explain-analyze** adds `ANALYZE` and the format to the options already there, keeping the-rest. Replaying it unchanged would return an estimate and never execute, which is-not what the action promises, and prefixing a second `EXPLAIN` is invalid — so-it is the same option substitution §3.2 uses for Visualize. Each action does what-its name says: one refuses to execute, the other insists on it.--**Both actions plan the statement Run would execute, limit included.** The-drivers apply the result limit only when the request is not an explain-(`pg.go:801-809`, `mysql.go:530-538`), so reusing that path plans the unbounded-query while Run stops at the limit — and `LIMIT` changes plan shape, so the two-are different queries. The limited statement has to be carried or reconstructed-before either action wraps it. It matters twice over for **Explain analyze**,-which executes: unbounded, an `EXPLAIN ANALYZE` against a large table becomes the-workload it was meant to diagnose.--**Explain analyze returns a plan, not rows.** On PostgreSQL that is automatic —-`EXPLAIN ANALYZE` replaces the result set. Spanner's profile mode and SQL-Server's `SET STATISTICS XML` instead hand back the rows *and* the plan, and the-explain path skips masking (§3.5), so passing those rows on would show unmasked-values to a user who is subject to masking. The backend discards them. Same-action, same output, on every engine.+skipping the `SET` would plan the next statement against the wrong search path,+so the request is refused rather than explaining part of the script — the same+rule §3.3 applies to the Plan view.++**Explain never executes.** Given a statement that already says `EXPLAIN+ANALYZE`, it refuses and says why, rather than running an expensive query behind+a control whose whole purpose is to avoid running it. It asks for the engine's+machine-readable plan, so the picture comes back in one call.++**Explain plans the statement as written, with no limit added.** The result+limit caps how many rows the editor reads back. It is not part of the query, and+appending `LIMIT N` would plan a different statement, because `LIMIT` changes+plan shape. The drivers already leave the limit off on the explain path. A plan+opened from a result is different: it explains the statement that produced the+result, including the limit Run added (§3.4).++**There is no Explain analyze action.** A measured plan comes from typing+`EXPLAIN ANALYZE` and pressing Run, which executes exactly once and is drawn+when it names a format we read (§3.2). Desktop clients do pair the two — pgAdmin+(F7 / Shift+F7), SSMS's estimated and actual plans, SQL Developer's Explain Plan+and Autotrace — but how an engine measures a plan does not make one control: a+statement prefix on PostgreSQL, CockroachDB and TiDB; text only on MySQL 8.0.18+and later; a session setting that returns the rows as well on SQL Server; an API+mode on Spanner; a hint and `DBMS_XPLAN` on Oracle; nothing on ClickHouse or+Redshift; and every run already measured on BigQuery, Snowflake and Databricks.+Built cheaply it would exist for PostgreSQL alone, it would be the one explain+control that executes — writes included — and it would save only remembering the+syntax. Revisit if users ask.Run stays literal: a typed `EXPLAIN ANALYZE` executes, because that is what theuser typed. What we never do is wrap a statement that already starts with@@ -139,7 +133,7 @@ rather than to an error.| Statement Bytebase ran | Result tab shows | `Query()` calls ||---|---|---|-| **Explain** / **Explain analyze** — we build it, so we ask for the engine's machine-readable format | picture where the engine has one (§3.4) | 1 |+| **Explain** — we build it, so we ask for the engine's machine-readable format | picture where the engine has one (§3.4) | 1 || Typed `EXPLAIN (FORMAT JSON)` | picture, drawn from what came back | 1 — nothing extra || Typed `EXPLAIN (FORMAT XML)` | text for now — see below | 1 || Typed `EXPLAIN` | text, plus a **Visualize** button | 1, +1 only on Visualize |@@ -159,8 +153,8 @@ The existing link replays the same params with a different formatand flipping `explain` true instead would have the driver prefix a second`EXPLAIN` onto a statement that already starts with one. So Visualize sends thatstatement as an explain request naming the format it wants, and the backend-substitutes the format rather than prefixing, which is the rule §3.1 already-sets for every statement that arrives already explaining itself.+substitutes the format rather than prefixing, as it does for every explain+request whose statement already explains itself.Substitution today keeps the planned statement and nothing else: the caller'sremaining options (`VERBOSE`, `COSTS OFF`) go with the format they came with,@@ -200,9 +194,9 @@ only way to draw it would be to run the query a second time. One that names aformat we can read is drawn like any other structured plan — it has already run,exactly once, and came back machine-readable, so the drawing rule appliesunchanged. The user who wants a picture of-a measured plan uses **Explain analyze** (§3.1), which asks for the structured-plan on its single run. That keeps the cost rule intact without this design-rewriting anyone's statement.+a measured plan types `EXPLAIN (ANALYZE, FORMAT JSON)`, which returns the+structured plan on its single run. That keeps the cost rule intact without this+design rewriting anyone's statement.### 3.3 Reading the plan@@ -328,6 +322,13 @@ never do this. It turns "this scan is expensive" into a next step, with no AIinvolved, and it is the strongest reason for the plan to live inside Bytebaserather than in a tab that could have been any web page.+**It has to be the same table.** The editor knows the connected database, and+only that one. A plan can name another — SQL Server writes the database on every+object it reads, and a query can cross databases — so a node whose table lives+elsewhere says nothing rather than describing the local table that happens to+share its name. The same holds for a name two schemas both use where the plan+names no schema. The wrong table's indexes are worse than none.+**Keep the plan portable.** Experts have tools they trust, so a **Copy plan**action stays, as it is in the viewer today (`PlanCopyButton`) and in every viewerwe surveyed. Dropping it while retiring the pop-up page would be a quiet@@ -335,16 +336,25 @@ regression.### 3.4 Engine differences-| Engine | Plan on a result | Picture | Explain analyze |+| Engine | Plan on a result | Picture | Measured plan, typed ||---|---|---|---|-| **PostgreSQL** | one `Query()`, on demand, cached | graph | yes — `EXPLAIN (ANALYZE, FORMAT JSON)` |-| **SQL Server** | one `Query()`, on demand, cached | graph | yes — `SET STATISTICS XML` |-| **Spanner** | one `Query()`, on demand, cached | graph | yes — profile mode |-| **MySQL** | one `Query()`, on demand, cached | text | 8.0.18+ only, and text — `EXPLAIN ANALYZE` is TREE and rejects JSON. Below that it is not valid syntax, so the action is disabled with the version as the reason |-| **Oracle, 7 others** | one `Query()`, on demand, cached | text | no |+| **PostgreSQL** | one `Query()`, on demand, cached | graph | `EXPLAIN (ANALYZE, FORMAT JSON)`, drawn |+| **SQL Server** | one `Query()`, on demand, cached | graph | `SET STATISTICS XML ON`, with the rows |+| **Spanner** | one `Query()`, on demand, cached | graph | none in the editor — profile mode is an API, not SQL |+| **MySQL** | one `Query()`, on demand, cached | text | `EXPLAIN ANALYZE` from 8.0.18, TREE text only |+| **Oracle, 7 others** | one `Query()`, on demand, cached | text | per engine, text at most |A plan opened from a result is always an estimate, on every engine. Measured-plans come from **Explain analyze** (§3.1), which is a deliberate action.+plans come from a typed `EXPLAIN ANALYZE` or its engine's equivalent, which is a+deliberate act (§3.1).++**What a measured plan is read for.** PostgreSQL reports a node's time and rows+as averages over its executions, so both are multiplied out to totals before+anything is ranked or compared. SQL Server's actual plan is read for rows alone:+`ActualElapsedms` is cumulative on a row-mode operator but per operator on a+batch-mode one, so a single plan can mean both and a ranking built on it would+be wrong for half of it. Those plans rank by the estimated cost they always+carry, with estimated and actual rows side by side on each node.**It explains the statement that ran, limits included.** The driver wraps anordinary query with the result limit but skips that wrapper on the explain path@@ -389,8 +399,8 @@ would have to profile *every* run — and Spanner documents profiling overhead adiscourages it for production traffic, while `SET STATISTICS XML` needs`SHOWPLAN` on every database the statement touches, so turning it on blindlywould 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.+requires a control that says so before the run — the Explain analyze action §3.1+leaves out. Out of scope.The pop-up page, its token hand-off and the old link are deleted([#21652](https://github.com/bytebase/bytebase/pull/21652)).@@ -399,9 +409,9 @@ The pop-up page, its token hand-off and the old link are deleted**Explain is its own permission** — `bb.sql.explain`, not `bb.sql.select`(`sql_service.go:1480`) — so a user can be allowed to run a query and not to plan-it. For them the Plan option is **disabled with the reason shown**, not hidden:-hiding it leaves them unable to tell the capability exists or what to ask an-admin for.+it. For them the Plan option and Explain in Run's dropdown are **disabled with+the reason shown**, not hidden: hiding them leaves them unable to tell the+capability exists or what to ask an admin for.**Anything that both executes and returns a plan needs both permissions.** Atyped `EXPLAIN ANALYZE` was classified as its *inner* statement, so it passed on@@ -411,11 +421,10 @@ them. Both now mark the span as an executed plan, so the statement needs itsnormal ACL, write-target checks included, **and** `bb.sql.explain`([#21642](https://github.com/bytebase/bytebase/pull/21642),[#21648](https://github.com/bytebase/bytebase/pull/21648)). SQL Server's settings are read from the parsed `SET` statement,-not matched as text, so a comment or an option list does not hide them. The-**Explain analyze** action comes the other way: an explain request is checked-on `bb.sql.explain` and is safe today only because `validateExplainStatements`-refuses anything that is not read-only, which is exactly the refusal this-action has to relax; when it lands it must add the statement's own ACL.+not matched as text, so a comment or an option list does not hide them. No+explain request executes — there is no Explain analyze action (§3.1) — so an+explain request needs `bb.sql.explain` alone, and `validateExplainStatements`+refuses any planned form that is not read-only.**Plans are never masked, and that is a privilege, not a safe default.** Explainskips masking (`sql_service.go:726`, `:735`). A plan is not row data, but it is@@ -522,7 +531,7 @@ live servers, September 2026.## 6. Status-Checked against `main` on 2026-10-23, after [#21652](https://github.com/bytebase/bytebase/pull/21652).+Checked against `main` on 2026-10-26, after [#21652](https://github.com/bytebase/bytebase/pull/21652), plus the §3.1 and §3.3 work on the branch below.**Landed**@@ -558,12 +567,33 @@ Checked against `main` on 2026-10-23, after [#21652](https://github.com/bytebaseoperator; three tabs (Diagram, Table, Text) instead of five; the costliestoperators ranked in the side panel; the legend on hover; the pop-up pagedeleted ([#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 rest of the reading changes: warning relevance, measured plans- with planned vs actual rows, cost share on the tab label.+ ranking and the opening view use estimated cost and say so.++- §3.1 — Explain at the top of Run's dropdown, on the statement as written,+ disabled with the reason without `bb.sql.explain`; it, `Ctrl/Cmd+E` and+ right-click → Explain, in the editor and the admin terminal, ask for the+ drawable format, so the picture takes one call. No limit is added to an+ explain, and there is no Explain analyze action; measured plans come from a+ typed `EXPLAIN ANALYZE`. §3.1 is closed.++- §3.3 — the rest of the reading changes. A measured plan is ranked by the time+ each operator spent — its own total less its children's — and says that is+ what it ranked; the shading, the node cards and the table follow the same+ number, and a plan reporting neither cost nor time says why it ranks nothing.+ Planned and actual rows sit together on a node, with the misestimate spelled+ out as a multiple once it is worth a line. One of Bytebase's own scan+ heuristics reaches the summary panel only where the operator is a tenth of+ the plan, while a diagnostic the engine itself reports always does, grouped+ by warning and never removed from node details. A run that planned every+ statement puts each statement's share of the script's estimated cost on its+ result tab. A node that reads a table Bytebase has synced shows that table's+ size and its indexes, which no standalone viewer can do; a table in another+ database, or a bare name two schemas both use, is left unanswered rather than+ answered with the wrong table's indexes. §3.3 is closed.++**Not yet**++Nothing: every section of this design is implemented. The one question §3.3+left open is not code but evidence — whether the diagram should open zoomed on+the costliest operator, as it does, or fit the whole graph and offer *Jump to+operator*. That belongs to the §1 usability test.diff --git a/frontend/src/apps/explain-visualizer/QueryPlanDiagram.tsx b/frontend/src/apps/explain-visualizer/QueryPlanDiagram.tsxindex a664434e51..64aedb728f 100644--- a/frontend/src/apps/explain-visualizer/QueryPlanDiagram.tsx+++ b/frontend/src/apps/explain-visualizer/QueryPlanDiagram.tsx@@ -39,6 +39,7 @@ import {import {formatPlanCost,formatPlanCount,+ formatPlanDuration,formatPlanShare,type PlanHighlightMode,type PlanNode,@@ -47,8 +48,10 @@ import {planCostliestNodes,planDescendantCount,planEdgeWidth,+ planHasSelfMetric,planHighlightIntensity,- planSelfCostShare,+ planRankMetric,+ planSelfShare,} from "./plan-model";import { PlanCostShareBar } from "./plan-shared";@@ -92,28 +95,49 @@ function wheelPixels(event: WheelEvent): number {return event.deltaY;}-/** Semantic surface each shading scale tints a card with. */+/**+ * Semantic surface each shading scale tints a card with. Cost and time share+ * one: both say this operator is where the work went, and only one shades at+ * a time.+ */const HIGHLIGHT_CLASS: Record<Exclude<PlanHighlightMode, "off">, string> = {cost: "bg-warning",+ time: "bg-warning",rows: "bg-info",};-/** The estimates a card prints, leaving out any the plan does not carry. */+/**+ * The numbers a card prints, leaving out any the plan does not carry. A+ * measured plan prints what happened and leaves the estimate to the node's+ * details, where the two sit side by side.+ */function planCardMetrics(node: PlanNode,tree: PlanTree,translate: QueryPlanTranslate): string {- return [- tree.estimates.cost- ? translate("diagram.cost", { cost: formatPlanCost(node.totalCost) })- : undefined,- tree.estimates.rows- ? translate("diagram.rows", { count: formatPlanCount(node.rows) })- : undefined,- ]- .filter(Boolean)- .join(" · ");+ const parts: string[] = [];+ if (planRankMetric(tree) === "time") {+ parts.push(+ translate("diagram.time", { time: formatPlanDuration(node.actualTime) })+ );+ } else if (tree.estimates.cost) {+ parts.push(+ translate("diagram.cost", { cost: formatPlanCost(node.totalCost) })+ );+ }+ if (tree.measured.rows) {+ parts.push(+ translate("diagram.actual-rows", {+ count: formatPlanCount(node.actualRows),+ })+ );+ } else if (tree.estimates.rows) {+ parts.push(+ translate("diagram.rows", { count: formatPlanCount(node.rows) })+ );+ }+ return parts.join(" · ");}/** Opacity of the tint on the plan's worst node; the rest scale below it. */@@ -424,7 +448,7 @@ export function QueryPlanDiagram({const { node, x, y } = placed;const selected = node.id === selectedId;const metrics = planCardMetrics(node, tree, translate);- const share = planSelfCostShare(node, tree);+ const share = planSelfShare(node, tree);const warnings = node.warnings.map((warning) => warning.title);const collapsed = collapsedIds.has(node.id);const subtreeCount = planDescendantCount(node);@@ -452,10 +476,13 @@ export function QueryPlanDiagram({relationship,node.subject,metrics,- tree.estimates.cost- ? translate("diagram.plan-cost-share", {- share: formatPlanShare(share),- })+ planHasSelfMetric(tree)+ ? translate(+ planRankMetric(tree) === "time"+ ? "diagram.plan-time-share"+ : "diagram.plan-cost-share",+ { share: formatPlanShare(share) }+ ): undefined,...warnings,collapsed@@ -524,7 +551,7 @@ export function QueryPlanDiagram({{metrics}</span>) : null}- {tree.estimates.cost ? (+ {planHasSelfMetric(tree) ? (<span className="flex w-full items-center gap-2"><PlanCostShareBarshare={share}diff --git a/frontend/src/apps/explain-visualizer/QueryPlanGrid.test.tsx b/frontend/src/apps/explain-visualizer/QueryPlanGrid.test.tsxindex ba6b2dfaa9..c9997e6d7e 100644--- a/frontend/src/apps/explain-visualizer/QueryPlanGrid.test.tsx+++ b/frontend/src/apps/explain-visualizer/QueryPlanGrid.test.tsx@@ -384,3 +384,57 @@ describe("QueryPlanGrid", () => {expect(container.querySelector("img")).toBeNull();});});++describe("QueryPlanGrid on a measured plan", () => {+ const measuredPlan = [+ {+ Plan: {+ "Node Type": "Nested Loop",+ "Total Cost": 100,+ "Plan Rows": 10,+ "Plan Width": 8,+ "Actual Total Time": 20,+ "Actual Rows": 10,+ "Actual Loops": 1,+ Plans: [+ {+ "Node Type": "Seq Scan",+ "Parent Relationship": "Outer",+ "Relation Name": "orders",+ "Total Cost": 40,+ "Plan Rows": 4,+ "Plan Width": 8,+ "Actual Total Time": 16,+ "Actual Rows": 3,+ "Actual Loops": 1,+ },+ ],+ },+ },+ ];++ test("reports the time each node took where the plan measured it", () => {+ renderGrid({ tree: treeFrom(measuredPlan) });++ expect(headers()).toEqual([+ "#",+ "Node",+ "Self time",+ "Total cost",+ "Rows",+ "Actual rows",+ "Width",+ ]);+ // 16 ms of the plan's 20 went to the scan, which the bar shows as its+ // share; the estimate columns stay beside it.+ expect(cellsOf(rows()[1]).slice(2)).toEqual(["16", "40", "4", "3", "8"]);+ });++ test("keeps the cost column where nothing measured a time", () => {+ renderGrid();++ expect(headers()).toContain("Added cost");+ expect(headers()).not.toContain("Self time");+ expect(headers()).not.toContain("Actual rows");+ });+});diff --git a/frontend/src/apps/explain-visualizer/QueryPlanGrid.tsx b/frontend/src/apps/explain-visualizer/QueryPlanGrid.tsxindex 9fa11e8b1c..8f92eabf9d 100644--- a/frontend/src/apps/explain-visualizer/QueryPlanGrid.tsx+++ b/frontend/src/apps/explain-visualizer/QueryPlanGrid.tsx@@ -13,10 +13,13 @@ import { planIndentPixels, planIndentStep } from "./plan-layout";import {formatPlanCost,formatPlanCount,+ formatPlanDuration,type PlanRow,type PlanTree,+ planHasSelfMetric,+ planRankMetric,planRows,- planSelfCostShare,+ planSelfShare,} from "./plan-model";import { PlanCostShareBar, SECONDARY_COLUMN_CLASS } from "./plan-shared";@@ -170,29 +173,36 @@ const PlanGridRow = memo(function PlanGridRow({</div></TableCell>+ {planHasSelfMetric(tree) ? (+ <TableCell className="py-2 pr-4 pl-2">+ <div className="flex items-center justify-end gap-2">+ <PlanCostShareBar+ share={planSelfShare(node, tree)}+ className="w-10 shrink-0 sm:w-16"+ />+ <span className="text-xs leading-4 text-main tabular-nums">+ {planRankMetric(tree) === "time"+ ? formatPlanDuration(node.selfTime)+ : formatPlanCost(node.selfCost)}+ </span>+ </div>+ </TableCell>+ ) : null}{tree.estimates.cost ? (- <>- <TableCell className="py-2 pr-4 pl-2">- <div className="flex items-center justify-end gap-2">- <PlanCostShareBar- share={planSelfCostShare(node, tree)}- className="w-10 shrink-0 sm:w-16"- />- <span className="text-xs leading-4 text-main tabular-nums">- {formatPlanCost(node.selfCost)}- </span>- </div>- </TableCell>- <TableCell className={cn(NUMERIC_CELL_CLASS, SECONDARY_COLUMN_CLASS)}>- {formatPlanCost(node.totalCost)}- </TableCell>- </>+ <TableCell className={cn(NUMERIC_CELL_CLASS, SECONDARY_COLUMN_CLASS)}>+ {formatPlanCost(node.totalCost)}+ </TableCell>) : null}{tree.estimates.rows ? (<TableCell className={cn(NUMERIC_CELL_CLASS, SECONDARY_COLUMN_CLASS)}>{formatPlanCount(node.rows)}</TableCell>) : null}+ {tree.measured.rows ? (+ <TableCell className={cn(NUMERIC_CELL_CLASS, SECONDARY_COLUMN_CLASS)}>+ {formatPlanCount(node.actualRows)}+ </TableCell>+ ) : null}{tree.estimates.width ? (<TableCell className={cn(NUMERIC_CELL_CLASS, SECONDARY_COLUMN_CLASS)}>{formatPlanCount(node.width)}@@ -204,6 +214,7 @@ const PlanGridRow = memo(function PlanGridRow({export function QueryPlanGrid({ tree, selectedId, onSelect }: Props) {const translate = useQueryPlanTranslation();+ const measured = planRankMetric(tree) === "time";const rows = useMemo(() => planRows(tree.root), [tree]);const step = useMemo(() => planIndentStep(Math.max(0, ...rows.map((row) => row.depth))),@@ -279,24 +290,26 @@ export function QueryPlanGrid({ tree, selectedId, onSelect }: Props) {<TableHead className={HEAD_CLASS}>{translate("grid.node")}</TableHead>+ {planHasSelfMetric(tree) ? (+ <TableHead+ className={cn(HEAD_CLASS, "w-32 pl-2 text-right sm:w-48")}+ title={translate(+ measured ? "grid.self-time-hint" : "grid.added-cost-hint"+ )}+ >+ {translate(measured ? "grid.self-time" : "grid.added-cost")}+ </TableHead>+ ) : null}{tree.estimates.cost ? (- <>- <TableHead- className={cn(HEAD_CLASS, "w-32 pl-2 text-right sm:w-48")}- title={translate("grid.added-cost-hint")}- >- {translate("grid.added-cost")}- </TableHead>- <TableHead- className={cn(- HEAD_CLASS,- SECONDARY_COLUMN_CLASS,- "text-right sm:w-28"- )}- >- {translate("grid.total-cost")}- </TableHead>- </>+ <TableHead+ className={cn(+ HEAD_CLASS,+ SECONDARY_COLUMN_CLASS,+ "text-right sm:w-28"+ )}+ >+ {translate("grid.total-cost")}+ </TableHead>) : null}{tree.estimates.rows ? (<TableHead@@ -310,6 +323,18 @@ export function QueryPlanGrid({ tree, selectedId, onSelect }: Props) {{translate("grid.rows")}</TableHead>) : null}+ {tree.measured.rows ? (+ <TableHead+ className={cn(+ HEAD_CLASS,+ SECONDARY_COLUMN_CLASS,+ "text-right sm:w-24"+ )}+ title={translate("grid.actual-rows-hint")}+ >+ {translate("grid.actual-rows")}+ </TableHead>+ ) : null}{tree.estimates.width ? (<TableHeadclassName={cn(diff --git a/frontend/src/apps/explain-visualizer/QueryPlanNodeDetails.test.tsx b/frontend/src/apps/explain-visualizer/QueryPlanNodeDetails.test.tsxindex 5ef36818b1..659c2ea6bf 100644--- a/frontend/src/apps/explain-visualizer/QueryPlanNodeDetails.test.tsx+++ b/frontend/src/apps/explain-visualizer/QueryPlanNodeDetails.test.tsx@@ -83,7 +83,11 @@ describe("QueryPlanNodeDetails", () => {node={node({warnings: [PLAN_FULL_TABLE_SCAN,- { title: "No join predicate", detail: "Every row pairs up." },+ {+ title: "No join predicate",+ detail: "Every row pairs up.",+ source: "engine",+ },],})}/>@@ -158,3 +162,121 @@ describe("QueryPlanNodeDetails", () => {);});});++describe("QueryPlanNodeDetails on a measured node", () => {+ const measured = (overrides: Partial<PlanNode> = {}): PlanNode =>+ node({+ rows: 100,+ actualRows: 2500,+ actualTime: 12.5,+ selfTime: 4,+ loops: 5,+ ...overrides,+ });++ test("puts what happened beside what the planner expected", () => {+ render(<QueryPlanNodeDetails node={measured()} />);++ expect(screen.getByText("Estimated rows").nextSibling).toHaveTextContent(+ "100"+ );+ expect(screen.getByText("Actual rows").nextSibling).toHaveTextContent(+ "2,500"+ );+ expect(screen.getByText("Loops").nextSibling).toHaveTextContent("5");+ expect(screen.getByText("Actual time").nextSibling).toHaveTextContent(+ "12.5 ms"+ );+ });++ test("does the multiplication a row misestimate needs", () => {+ // 100 rows expected on each of 5 loops is 500, and 2,500 came back.+ render(<QueryPlanNodeDetails node={measured()} />);++ expect(+ screen.getByTestId("plan-details-row-estimate")+ ).toHaveTextContent("Returned 5× more rows than the planner estimated.");+ });++ test("says when far fewer rows came back than were planned", () => {+ render(+ <QueryPlanNodeDetails+ node={measured({ rows: 1000, loops: 1, actualRows: 10 })}+ />+ );++ expect(+ screen.getByTestId("plan-details-row-estimate")+ ).toHaveTextContent("Returned 100× fewer rows than the planner estimated.");+ });++ test("states a node that returned nothing as that, not as a multiple", () => {+ render(+ <QueryPlanNodeDetails+ node={measured({ rows: 500, loops: 1, actualRows: 0 })}+ />+ );++ expect(screen.getByTestId("plan-details-row-estimate")).toHaveTextContent(+ "Returned no rows, where the planner expected some."+ );+ });++ test("stays quiet about an estimate that was close enough", () => {+ render(+ <QueryPlanNodeDetails+ node={measured({ rows: 100, loops: 1, actualRows: 120 })}+ />+ );++ expect(screen.queryByTestId("plan-details-row-estimate")).toBeNull();+ });++ test("leaves the measured rows off a node that was only planned", () => {+ render(<QueryPlanNodeDetails node={node()} />);++ expect(screen.queryByText("Actual rows")).toBeNull();+ expect(screen.queryByText("Loops")).toBeNull();+ expect(screen.queryByTestId("plan-details-row-estimate")).toBeNull();+ });+});++describe("QueryPlanNodeDetails on a table Bytebase knows", () => {+ const facts = {+ rowCount: 9488,+ indexes: [+ {+ name: "salary_pkey",+ columns: "emp_no, from_date",+ primary: true,+ },+ { name: "salary_amount_key", columns: "amount", unique: true },+ ],+ };++ test("turns an expensive scan into a next step", () => {+ render(<QueryPlanNodeDetails node={node()} table={facts} />);++ const section = screen.getByTestId("plan-details-table");+ expect(section).toHaveTextContent("9,488 rows at the last sync");+ expect(section).toHaveTextContent("salary_pkey · primary");+ expect(section).toHaveTextContent("emp_no, from_date");+ expect(section).toHaveTextContent("salary_amount_key · unique");+ });++ test("says a table has no indexes, which is the answer worth having", () => {+ render(+ <QueryPlanNodeDetails node={node()} table={{ rowCount: 9488, indexes: [] }} />+ );++ expect(screen.getByTestId("plan-details-table")).toHaveTextContent(+ "No indexes on this table."+ );+ });++ test("leaves the section out where Bytebase knows nothing", () => {+ render(<QueryPlanNodeDetails node={node()} />);++ expect(screen.queryByTestId("plan-details-table")).toBeNull();+ });+});diff --git a/frontend/src/apps/explain-visualizer/QueryPlanNodeDetails.tsx b/frontend/src/apps/explain-visualizer/QueryPlanNodeDetails.tsxindex 211f65e0b7..3e85519b15 100644--- a/frontend/src/apps/explain-visualizer/QueryPlanNodeDetails.tsx+++ b/frontend/src/apps/explain-visualizer/QueryPlanNodeDetails.tsx@@ -1,11 +1,105 @@import { Alert } from "@/components/ui/alert";import { Separator } from "@/components/ui/separator";import { type QueryPlanTranslate, useQueryPlanTranslation } from "./plan-i18n";-import { formatPlanCost, formatPlanCount, type PlanNode } from "./plan-model";+import {+ formatPlanCost,+ formatPlanCount,+ formatPlanDuration,+ PLAN_ROW_ESTIMATE_NOTABLE_FACTOR,+ type PlanNode,+ type PlanTableFacts,+ type PlanTableIndex,+ planRowEstimateFactor,+} from "./plan-model";import { PlanMetric } from "./plan-shared";+/**+ * How far the row estimate was out, in words, or undefined when it was close+ * enough not to be worth a line.+ */+function rowEstimateNote(+ node: PlanNode,+ translate: QueryPlanTranslate+): string | undefined {+ const factor = planRowEstimateFactor(node);+ if (factor === undefined) return undefined;+ // A node that returned nothing has no multiple to state, and "∞× fewer" is+ // not a number a reader can do anything with.+ if (factor === 0) return translate("metric.rows-none");+ if (factor >= PLAN_ROW_ESTIMATE_NOTABLE_FACTOR) {+ return translate("metric.rows-over", { factor: formatPlanCount(factor) });+ }+ if (factor <= 1 / PLAN_ROW_ESTIMATE_NOTABLE_FACTOR) {+ return translate("metric.rows-under", {+ factor: formatPlanCount(1 / factor),+ });+ }+ return undefined;+}+interface Props {readonly node: PlanNode | undefined;+ /** What Bytebase knows about the table this node reads, where it reads one. */+ readonly table?: PlanTableFacts;+}++/** What marks an index out, where anything does. */+function indexFlag(+ index: PlanTableIndex,+ translate: QueryPlanTranslate+): string | undefined {+ if (index.primary) return translate("table.primary");+ if (index.unique) return translate("table.unique");+ return undefined;+}++/**+ * The table an operator reads, as Bytebase last synced it: how big it is and+ * what indexes it already has, which is the difference between "this scan is+ * expensive" and knowing what to do about it.+ */+function TableFacts({ table }: { table: PlanTableFacts }) {+ const translate = useQueryPlanTranslation();+ return (+ <section data-testid="plan-details-table" className="flex flex-col gap-2">+ <h3 className="text-xs leading-4 text-control-light">+ {translate("table.heading")}+ </h3>+ {table.rowCount === undefined ? null : (+ <p className="text-sm leading-5 text-main tabular-nums">+ {translate("table.rows", {+ count: formatPlanCount(table.rowCount),+ })}+ </p>+ )}+ {table.indexes.length === 0 ? (+ <p className="text-sm leading-5 text-control-light">+ {translate("table.no-indexes")}+ </p>+ ) : (+ <>+ <h4 className="text-xs leading-4 text-control-light">+ {translate("table.indexes")}+ </h4>+ <ul className="flex flex-col gap-2">+ {table.indexes.map((index) => {+ const flag = indexFlag(index, translate);+ return (+ <li key={index.name} className="flex flex-col">+ <span className="truncate text-sm leading-5 text-main">+ {flag ? `${index.name} · ${flag}` : index.name}+ </span>+ <span className="font-mono text-xs leading-4 break-words text-control-light">+ {index.columns}+ </span>+ </li>+ );+ })}+ </ul>+ </>+ )}+ </section>+ );}/** The node's estimates as labelled values, leaving out any it does not have. */@@ -34,6 +128,22 @@ function nodeMetrics(value: node.rows,format: formatPlanCount,},+ {+ label: translate("metric.actual-rows"),+ value: node.actualRows,+ format: formatPlanCount,+ },+ {+ label: translate("metric.loops"),+ value: node.loops,+ format: formatPlanCount,+ },+ {+ label: translate("metric.actual-time"),+ value: node.actualTime,+ format: (time: number) =>+ translate("metric.milliseconds", { count: formatPlanDuration(time) }),+ },{label: translate("metric.row-width"),value: node.width,@@ -45,7 +155,7 @@ function nodeMetrics();}-export function QueryPlanNodeDetails({ node }: Props) {+export function QueryPlanNodeDetails({ node, table }: Props) {const translate = useQueryPlanTranslation();if (!node) {return (@@ -56,6 +166,7 @@ export function QueryPlanNodeDetails({ node }: Props) {}const metrics = nodeMetrics(node, translate);+ const rowEstimate = rowEstimateNote(node, translate);return (<div className="flex flex-col gap-4">@@ -102,6 +213,21 @@ export function QueryPlanNodeDetails({ node }: Props) {/>))}</dl>+ {rowEstimate ? (+ <p+ data-testid="plan-details-row-estimate"+ className="text-xs leading-4 text-control"+ >+ {rowEstimate}+ </p>+ ) : null}+ </>+ ) : null}++ {table ? (+ <>+ <Separator />+ <TableFacts table={table} /></>) : null}diff --git a/frontend/src/apps/explain-visualizer/QueryPlanSummary.test.tsx b/frontend/src/apps/explain-visualizer/QueryPlanSummary.test.tsxindex 0ebc413796..f5dc6b2f84 100644--- a/frontend/src/apps/explain-visualizer/QueryPlanSummary.test.tsx+++ b/frontend/src/apps/explain-visualizer/QueryPlanSummary.test.tsx@@ -3,7 +3,11 @@ import { describe, expect, test, vi } from "vitest";import mssqlHashJoinAggregateSort from "./test-data/mssql/hash-join-aggregate-sort.xml?raw";import hashJoinAggregateSort from "./test-data/postgres/hash-join-aggregate-sort.json";import { parseMssqlPlan } from "./mssql-plan";-import type { PlanParseResult, PlanTree } from "./plan-model";+import {+ buildPlanTree,+ type PlanParseResult,+ type PlanTree,+} from "./plan-model";import { parsePostgresPlan } from "./postgres-plan";import { QueryPlanSummary } from "./QueryPlanSummary";@@ -52,6 +56,46 @@ const renderSummary = (};const rows = () => screen.getAllByTestId("plan-costliest-row");+const warnings = () => screen.getAllByTestId("plan-summary-warning");++/**+ * The same shape as the estimated fixture, measured: the planner expected the+ * index scan to be the cheap side and it took almost all of the time.+ */+const measuredPlan = [+ {+ Plan: {+ "Node Type": "Nested Loop",+ "Total Cost": 100,+ "Plan Rows": 10,+ "Actual Total Time": 50,+ "Actual Rows": 10,+ "Actual Loops": 1,+ Plans: [+ {+ "Node Type": "Seq Scan",+ "Parent Relationship": "Outer",+ "Relation Name": "customers",+ "Total Cost": 90,+ "Plan Rows": 5,+ "Actual Total Time": 2,+ "Actual Rows": 5,+ "Actual Loops": 1,+ },+ {+ "Node Type": "Index Scan",+ "Parent Relationship": "Inner",+ "Relation Name": "orders",+ "Total Cost": 5,+ "Plan Rows": 2,+ "Actual Total Time": 9,+ "Actual Rows": 2,+ "Actual Loops": 5,+ },+ ],+ },+ },+];describe("QueryPlanSummary", () => {test("ranks the costliest operators with their share of the plan", () => {@@ -115,3 +159,136 @@ describe("QueryPlanSummary", () => {expect(container.querySelector("img")).toBeNull();});});++describe("QueryPlanSummary on a measured plan", () => {+ test("ranks by the time each operator took, and says that is what it ranked", () => {+ renderSummary({ tree: treeFrom(measuredPlan) });++ expect(screen.getByText("Slowest by measured time")).toBeVisible();+ // The planner's costliest node is the fast one; 45 ms of the plan's 50 go+ // to the inner scan it costed at 5.+ expect(rows()[0]).toHaveTextContent("Index Scan");+ expect(rows()[0]).toHaveTextContent("90%");+ });++ test("says so when no operator took measurable time of its own", () => {+ renderSummary({+ tree: treeFrom([+ {+ Plan: {+ "Node Type": "Result",+ "Total Cost": 0,+ "Actual Total Time": 0,+ "Actual Rows": 1,+ "Actual Loops": 1,+ },+ },+ ]),+ });++ expect(+ screen.getByText("No node in this plan took measurable time of its own.")+ ).toBeVisible();+ });+});++describe("QueryPlanSummary warnings", () => {+ /** A 5,000-unit plan whose full scan of `orders` costs `scanCost` of it. */+ const scanPlan = (scanCost: number) => [+ {+ Plan: {+ "Node Type": "Nested Loop",+ "Total Cost": 5000,+ "Plan Rows": 1,+ Plans: [+ {+ "Node Type": "Seq Scan",+ "Parent Relationship": "Outer",+ "Relation Name": "orders",+ "Total Cost": scanCost,+ "Plan Rows": 1,+ },+ ],+ },+ },+ ];++ test("names a scan worth a reader's time, and what it reads", () => {+ renderSummary({ tree: treeFrom(scanPlan(4000)) });++ expect(screen.getByText("Warnings")).toBeVisible();+ expect(warnings()).toHaveLength(1);+ expect(warnings()[0]).toHaveTextContent("Full table scan");+ expect(warnings()[0]).toHaveTextContent("orders");+ });++ test("leaves out a scan that is a rounding error in its plan", () => {+ // Over the parser's own threshold, so the node carries the warning, but+ // 100 cost units of a 10,100-unit plan is not where to start reading.+ renderSummary({ tree: treeFrom(scanPlan(100)) });++ expect(screen.queryAllByTestId("plan-summary-warning")).toHaveLength(0);+ expect(screen.queryByText("Warnings")).toBeNull();+ });++ test("selects the node a warning is about", () => {+ const { onSelect } = renderSummary({ tree: treeFrom(scanPlan(4000)) });++ fireEvent.click(warnings()[0]);+ expect(onSelect).toHaveBeenCalledWith("0.0");+ });++ test("counts the operators when one warning covers several", () => {+ renderSummary({+ tree: treeFrom([+ {+ Plan: {+ "Node Type": "Hash Join",+ "Total Cost": 2000,+ "Plan Rows": 1,+ Plans: [+ {+ "Node Type": "Seq Scan",+ "Parent Relationship": "Outer",+ "Relation Name": "orders",+ "Total Cost": 1200,+ "Plan Rows": 1,+ },+ {+ "Node Type": "Seq Scan",+ "Parent Relationship": "Inner",+ "Relation Name": "customers",+ "Total Cost": 800,+ "Plan Rows": 1,+ },+ ],+ },+ },+ ]),+ });++ expect(warnings()).toHaveLength(1);+ expect(warnings()[0]).toHaveTextContent("2 operators");+ });++ test("says why it ranks nothing when the engine reports no cost or time", () => {+ // What an engine that reports no estimates leaves the panel, as Spanner's+ // plans do.+ renderSummary({+ tree: buildPlanTree({+ id: "0",+ nodeType: "Scan",+ properties: [],+ warnings: [],+ children: [],+ }),+ });++ expect(+ screen.getByText(+ "This plan reports no cost or time, so its operators cannot be ranked."+ )+ ).toBeVisible();+ expect(screen.queryAllByTestId("plan-costliest-row")).toHaveLength(0);+ });+});diff --git a/frontend/src/apps/explain-visualizer/QueryPlanSummary.tsx b/frontend/src/apps/explain-visualizer/QueryPlanSummary.tsxindex 2dcab5d741..9e31cbad8e 100644--- a/frontend/src/apps/explain-visualizer/QueryPlanSummary.tsx+++ b/frontend/src/apps/explain-visualizer/QueryPlanSummary.tsx@@ -1,12 +1,17 @@+import { TriangleAlert } from "lucide-react";import { useMemo } from "react";import { Button } from "@/components/ui/button";import { cn } from "@/lib/utils";import { useQueryPlanTranslation } from "./plan-i18n";import {+ formatPlanCount,formatPlanShare,type PlanTree,+ type PlanWarningGroup,planCostliestNodes,- planSelfCostShare,+ planRankMetric,+ planSelfShare,+ planWarningGroups,} from "./plan-model";interface Props {@@ -15,63 +20,142 @@ interface Props {readonly onSelect: (id: string) => void;}+const HEADING_CLASS = "text-xs leading-4 text-control-light";+const ROW_CLASS =+ "h-auto w-full items-baseline justify-start gap-2 rounded-xs px-2 py-1 text-left font-normal";+const SELECTED_ROW_CLASS = "bg-accent/10 hover:bg-accent/15";++function titleClass(selected: boolean): string {+ return cn(+ "truncate text-sm leading-5",+ selected ? "font-medium text-accent" : "text-main"+ );+}++/** Where a warning fired: the operator itself, or how many reported it. */+function warningSubject(+ group: PlanWarningGroup,+ translate: ReturnType<typeof useQueryPlanTranslation>+): string {+ if (group.nodes.length > 1) {+ return translate("summary.warning-operators", {+ count: formatPlanCount(group.nodes.length),+ });+ }+ const [node] = group.nodes;+ return [node.nodeType, node.subject].filter(Boolean).join(" · ");+}+/**- * 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.+ * The operators that own the most of the plan, ranked, and the warnings worth+ * a reader's time, so the step to look at is named outright with no graph to+ * read first. Both pick a node, which the diagram and the table follow.+ *+ * Measured plans rank by measured time and say so: planner costs are arbitrary+ * units and are wrong in exactly the cases worth investigating.*/export function QueryPlanSummary({ tree, selectedId, onSelect }: Props) {const translate = useQueryPlanTranslation();const nodes = useMemo(() => planCostliestNodes(tree), [tree]);+ const warnings = useMemo(() => planWarningGroups(tree), [tree]);+ const measured = planRankMetric(tree) === "time";+ const hasMetric = measured || tree.estimates.cost;+return (- <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 ? (+ <section data-testid="plan-summary" className="flex flex-col gap-4">+ {/* An engine that reports neither a cost nor a time says so, rather than+ leaving the panel to imply there was nothing worth ranking. */}+ {!hasMetric ? (<p className="text-sm leading-5 text-control-light">- {translate("summary.no-added-cost")}+ {translate("summary.no-ranking")}</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(- "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"- )}- >- <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"- )}+ <div className="flex flex-col gap-1">+ <h2 className={HEADING_CLASS}>+ {translate(+ measured ? "summary.slowest-measured" : "summary.costliest"+ )}+ </h2>+ {nodes.length === 0 ? (+ <p className="text-sm leading-5 text-control-light">+ {translate(+ measured ? "summary.no-added-time" : "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(ROW_CLASS, selected && SELECTED_ROW_CLASS)}>- {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>+ <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={titleClass(selected)}>+ {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(planSelfShare(node, tree))}+ </span>+ </Button>+ </li>+ );+ })}+ </ol>+ )}+ </div>)}++ {warnings.length > 0 ? (+ <div className="flex flex-col gap-1">+ <h2 className={HEADING_CLASS}>{translate("summary.warnings")}</h2>+ <ul data-testid="plan-summary-warnings" className="flex flex-col">+ {warnings.map((group) => {+ const selected = group.nodes.some(+ (node) => node.id === selectedId+ );+ return (+ <li key={group.warning.title}>+ <Button+ appearance="secondary"+ data-testid="plan-summary-warning"+ aria-pressed={selected}+ // The worst reporting node, so a grouped warning opens on+ // the one most worth reading.+ onClick={() => onSelect(group.nodes[0].id)}+ className={cn(ROW_CLASS, selected && SELECTED_ROW_CLASS)}+ >+ <TriangleAlert+ aria-hidden="true"+ className="shrink-0 self-center text-warning"+ />+ <span className="flex min-w-0 flex-1 flex-col">+ <span className={titleClass(selected)}>+ {group.warning.title}+ </span>+ <span className="truncate text-xs leading-4 text-control-light">+ {warningSubject(group, translate)}+ </span>+ </span>+ </Button>+ </li>+ );+ })}+ </ul>+ </div>+ ) : null}</section>);}diff --git a/frontend/src/apps/explain-visualizer/QueryPlanView.tsx b/frontend/src/apps/explain-visualizer/QueryPlanView.tsxindex 6d2c55ba51..e1a554765c 100644--- a/frontend/src/apps/explain-visualizer/QueryPlanView.tsx+++ b/frontend/src/apps/explain-visualizer/QueryPlanView.tsx@@ -1,13 +1,11 @@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/queryPlanEngines";import {MSSQL_PLAN_EMPTY_MESSAGE,MSSQL_PLAN_INVALID_XML_MESSAGE,MSSQL_PLAN_NO_PLAN_MESSAGE,- parseMssqlPlan,} from "./mssql-plan";import {QueryPlanI18nProvider,@@ -18,29 +16,22 @@ import {import {PLAN_TOO_DEEP_MESSAGE,PLAN_TOO_MANY_NODES_MESSAGE,- type PlanParseResult,+ type PlanTableLookup,} from "./plan-model";+import { parsePlan } from "./plan-parsers";import {POSTGRES_PLAN_EMPTY_MESSAGE,POSTGRES_PLAN_INVALID_JSON_MESSAGE,POSTGRES_PLAN_NO_PLAN_MESSAGE,- parsePostgresPlan,} from "./postgres-plan";import { QueryPlanViewer } from "./QueryPlanViewer";import {- parseSpannerPlan,SPANNER_PLAN_EMPTY_MESSAGE,SPANNER_PLAN_EMULATOR_MESSAGE,SPANNER_PLAN_INVALID_JSON_MESSAGE,SPANNER_PLAN_NO_PLAN_MESSAGE,} from "./spanner-plan";-const PARSERS: Record<VisualizerEngine, (source: string) => PlanParseResult> = {- [Engine.POSTGRES]: parsePostgresPlan,- [Engine.MSSQL]: parseMssqlPlan,- [Engine.SPANNER]: parseSpannerPlan,-};-const STATUS_CLASS ="flex h-full min-h-0 w-full flex-col gap-4 overflow-auto bg-background p-4";@@ -64,6 +55,7 @@ interface Props {planSource: string;textPlanSource?: string;note?: ReactNode;+ describeTable?: PlanTableLookup;translate?: QueryPlanTranslate;disallowCopyingData?: boolean;}@@ -73,11 +65,12 @@ function QueryPlanViewContent({planSource,textPlanSource,note,+ describeTable,disallowCopyingData = false,}: Props) {const translate = useQueryPlanTranslation();const result = useMemo(- () => PARSERS[engine](planSource),+ () => parsePlan(engine, planSource),[engine, planSource]);@@ -106,6 +99,7 @@ function QueryPlanViewContent({rawPlan={planSource}textPlan={textPlanSource}note={note}+ describeTable={describeTable}disallowCopyingData={disallowCopyingData}/>);diff --git a/frontend/src/apps/explain-visualizer/QueryPlanViewer.test.tsx b/frontend/src/apps/explain-visualizer/QueryPlanViewer.test.tsxindex 1270145f9f..35a34edbfe 100644--- a/frontend/src/apps/explain-visualizer/QueryPlanViewer.test.tsx+++ b/frontend/src/apps/explain-visualizer/QueryPlanViewer.test.tsx@@ -55,11 +55,14 @@ const renderViewer = () =>/** Renders a plan the way the result pane does: parsed, beside its source. */const renderParsed = (parse: (source: string) => ReturnType<typeof parsePostgresPlan>,- source: string+ source: string,+ overrides: Partial<Parameters<typeof QueryPlanViewer>[0]> = {}) => {const result = parse(source);if (!result.ok) throw new Error(result.message);- return render(<QueryPlanViewer tree={result.tree} rawPlan={source} />);+ return render(+ <QueryPlanViewer tree={result.tree} rawPlan={source} {...overrides} />+ );};const openTab = (name: string) =>@@ -231,11 +234,18 @@ describe("QueryPlanViewer", () => {// Nothing can be ranked or shaded.expect(tabNames()).toEqual(["Diagram", "Table", "Text"]);- expect(screen.queryByTestId("plan-summary")).toBeNull();+ expect(screen.queryByTestId("plan-costliest")).toBeNull();expect(screen.queryByRole("group", { name: "Highlight" })).toBeNull();expect(screen.getByText("7 nodes")).toBeVisible();expect(screen.queryByLabelText(/card's bar/)).toBeNull();expect(screen.getAllByTestId("plan-node-card")).toHaveLength(7);+ // With no cost to judge relevance by, the scan warnings still reach the+ // panel rather than being dropped for want of a number to weigh them.+ const warnings = screen.getAllByTestId("plan-summary-warning");+ expect(warnings).toHaveLength(2);+ expect(warnings[0]).toHaveTextContent("Full table scan");+ expect(warnings[0]).toHaveTextContent("Albums");+ expect(warnings[1]).toHaveTextContent("Full index scan");});test("indents an XML plan one element per line on the text tab", () => {@@ -358,3 +368,112 @@ describe("QueryPlanViewer", () => {expect(note.closest('[role="tablist"]')).not.toBeNull();});});++describe("QueryPlanViewer on a measured plan", () => {+ const measuredPlan = JSON.stringify([+ {+ Plan: {+ "Node Type": "Nested Loop",+ "Total Cost": 100,+ "Plan Rows": 10,+ "Actual Total Time": 24.5,+ "Actual Rows": 10,+ "Actual Loops": 1,+ Plans: [+ {+ "Node Type": "Seq Scan",+ "Parent Relationship": "Outer",+ "Relation Name": "orders",+ "Total Cost": 90,+ "Plan Rows": 4,+ "Actual Total Time": 20,+ "Actual Rows": 4,+ "Actual Loops": 1,+ },+ ],+ },+ },+ ]);++ beforeEach(() => mockMatchMedia(false));++ test("offers shading by the time it measured, ahead of the estimate", () => {+ renderParsed(parsePostgresPlan, measuredPlan);++ expect(+ within(screen.getByRole("group", { name: "Highlight" }))+ .getAllByRole("button")+ .map((option) => option.textContent)+ ).toEqual(["Off", "Time", "Cost", "Rows"]);+ });++ test("reports the measured total and says the bars follow it", () => {+ renderParsed(parsePostgresPlan, measuredPlan);++ expect(+ screen.getByText("2 nodes · measured time 24.5 ms · estimated cost 100")+ ).toBeVisible();+ expect(+ screen.getByRole("button", { name: /share of the plan's measured time/ })+ ).toBeVisible();+ });++ test("shades by measured time once asked", () => {+ renderParsed(parsePostgresPlan, measuredPlan);++ fireEvent.click(screen.getByRole("button", { name: "Time" }));+ expect(screen.getAllByTestId("plan-node-tint").length).toBeGreaterThan(0);+ });+});++describe("QueryPlanViewer with Bytebase's own metadata", () => {+ beforeEach(() => mockMatchMedia(false));++ const describeTable = ({ table }: { table: string }) =>+ table === "orders"+ ? { rowCount: 120, indexes: [{ name: "orders_pkey", columns: "id", primary: true }] }+ : undefined;++ test("asks about the table the selected node reads", () => {+ renderParsed(+ parsePostgresPlan,+ JSON.stringify([+ {+ Plan: {+ "Node Type": "Seq Scan",+ "Relation Name": "orders",+ "Total Cost": 500,+ "Plan Rows": 100,+ },+ },+ ]),+ { describeTable }+ );++ expect(screen.getByTestId("plan-details-table")).toHaveTextContent(+ "120 rows at the last sync"+ );+ expect(screen.getByTestId("plan-details-table")).toHaveTextContent(+ "orders_pkey · primary"+ );+ });++ test("says nothing about a node that reads no table it knows", () => {+ renderParsed(+ parsePostgresPlan,+ JSON.stringify([+ {+ Plan: {+ "Node Type": "Seq Scan",+ "Relation Name": "payments",+ "Total Cost": 500,+ "Plan Rows": 100,+ },+ },+ ]),+ { describeTable }+ );++ expect(screen.queryByTestId("plan-details-table")).toBeNull();+ });+});diff --git a/frontend/src/apps/explain-visualizer/QueryPlanViewer.tsx b/frontend/src/apps/explain-visualizer/QueryPlanViewer.tsxindex d261920a3b..7bc455ccd4 100644--- a/frontend/src/apps/explain-visualizer/QueryPlanViewer.tsx+++ b/frontend/src/apps/explain-visualizer/QueryPlanViewer.tsx@@ -21,9 +21,11 @@ import {findPlanNode,formatPlanCost,formatPlanCount,- type PlanEstimates,+ formatPlanDuration,type PlanHighlightMode,type PlanNode,+ type PlanTableFacts,+ type PlanTableLookup,type PlanTree,planCollapsedAncestor,planCostliestNodes,@@ -42,6 +44,8 @@ interface Props {readonly textPlan?: string;/** Shown at the end of the tab row, such as a reminder that the plan is an estimate. */readonly note?: ReactNode;+ /** What Bytebase knows about a table a node reads; nothing is shown without it. */+ readonly describeTable?: PlanTableLookup;readonly disallowCopyingData?: boolean;}@@ -51,8 +55,8 @@ interface HighlightOption {readonly value: PlanHighlightMode;readonly label: QueryPlanTranslationKey;readonly hint: QueryPlanTranslationKey;- /** Whether a plan carries the estimate the option shades by. */- readonly available: (estimates: PlanEstimates) => boolean;+ /** Whether a plan carries the number the option shades by. */+ readonly available: (tree: PlanTree) => boolean;}const HIGHLIGHT_OPTIONS: readonly HighlightOption[] = [@@ -62,19 +66,27 @@ const HIGHLIGHT_OPTIONS: readonly HighlightOption[] = [hint: "highlight.off-hint",available: () => true,},+ {+ // First where a plan has it: a measurement beats an estimate of the same+ // thing, which is why the ranking goes by it too.+ value: "time",+ label: "highlight.time",+ hint: "highlight.time-hint",+ available: (tree) => tree.measured.time,+ },{value: "cost",label: "highlight.cost",// Total cost is cumulative, so shading by it would always make the root// darkest. Self cost is what the node adds on top of its children.hint: "highlight.cost-hint",- available: (estimates) => estimates.cost,+ available: (tree) => tree.estimates.cost,},{value: "rows",label: "highlight.rows",hint: "highlight.rows-hint",- available: (estimates) => estimates.rows,+ available: (tree) => tree.estimates.rows,},];@@ -130,6 +142,11 @@ function PlanTotalsLine({ tree, legend }: { tree: PlanTree; legend?: string }) {translate("totals.nodes", {count: formatPlanCount(tree.nodes.length),}),+ tree.measured.time+ ? translate("totals.measured-time", {+ time: formatPlanDuration(tree.root.actualTime),+ })+ : undefined,tree.estimates.cost? translate("totals.estimated-cost", {cost: formatPlanCost(tree.root.totalCost),@@ -154,14 +171,19 @@ function PlanTotalsLine({ tree, legend }: { tree: PlanTree; legend?: string }) {);}-/** What the diagram's bars and edge widths encode, for the estimates it has. */+/** What the diagram's bars and edge widths encode, for the numbers it has. */function diagramLegend(- estimates: PlanEstimates,+ tree: PlanTree,translate: QueryPlanTranslate): string | undefined {+ const bar = tree.measured.time+ ? translate("legend.time")+ : tree.estimates.cost+ ? translate("legend.cost")+ : undefined;const parts = [- estimates.cost ? translate("legend.cost") : undefined,- estimates.rows ? translate("legend.rows") : undefined,+ bar,+ tree.estimates.rows ? translate("legend.rows") : undefined,].filter(Boolean);if (parts.length === 0) return undefined;const sentence = `${parts.join("; ")}.`;@@ -177,11 +199,13 @@ function diagramLegend(function PlanWithDetails({stacked,node,+ table,summary,children,}: {stacked: boolean;node: PlanNode | undefined;+ table: PlanTableFacts | undefined;summary: ReactNode;children: ReactNode;}) {@@ -202,7 +226,7 @@ function PlanWithDetails({<Panel defaultSize={stacked ? "40%" : "30%"} minSize="20%"><div className="flex h-full min-h-0 flex-col gap-4 overflow-auto p-4">{summary}- <QueryPlanNodeDetails node={node} />+ <QueryPlanNodeDetails node={node} table={table} /></div></Panel></PanelGroup>@@ -328,6 +352,7 @@ export function QueryPlanViewer({rawPlan,textPlan = rawPlan,note,+ describeTable,disallowCopyingData = false,}: Props) {const translate = useQueryPlanTranslation();@@ -347,11 +372,16 @@ export function QueryPlanViewer({const [revealId, setRevealId] = useState<string | undefined>();const selectedNode = findPlanNode(tree, selectedId);+ const relation = selectedNode?.relation;+ const selectedTable = useMemo(+ () => (relation ? describeTable?.(relation) : undefined),+ [describeTable, relation]+ );const stacked = useMediaQuery(STACK_QUERY);const highlightOptions = HIGHLIGHT_OPTIONS.filter((option) =>- option.available(tree.estimates)+ option.available(tree));- const legend = diagramLegend(tree.estimates, translate);+ const legend = diagramLegend(tree, translate);const selectNode = useCallback((id: string) => {@@ -379,8 +409,9 @@ export function QueryPlanViewer({const onRevealed = useCallback(() => setRevealId(undefined), []);- // Choosing a ranked operator also brings it into view on the diagram.- const summary = tree.estimates.cost ? (+ // Choosing a ranked operator or a warning also brings it into view on the+ // diagram. The panel draws nothing when the plan has neither.+ const summary = (<QueryPlanSummarytree={tree}selectedId={selectedId}@@ -389,7 +420,7 @@ export function QueryPlanViewer({if (tab === "diagram") setRevealId(id);}}/>- ) : null;+ );return (<Tabs@@ -421,6 +452,7 @@ export function QueryPlanViewer({<PlanWithDetailsstacked={stacked}node={selectedNode}+ table={selectedTable}summary={summary}><div@@ -463,6 +495,7 @@ export function QueryPlanViewer({<PlanWithDetailsstacked={stacked}node={selectedNode}+ table={selectedTable}summary={summary}><div className="flex shrink-0 flex-wrap items-center justify-end gap-4 px-4 py-2">diff --git a/frontend/src/apps/explain-visualizer/mssql-plan.test.ts b/frontend/src/apps/explain-visualizer/mssql-plan.test.tsindex aac33392b9..b34afe258e 100644--- a/frontend/src/apps/explain-visualizer/mssql-plan.test.ts+++ b/frontend/src/apps/explain-visualizer/mssql-plan.test.ts@@ -282,6 +282,7 @@ describe("parseMssqlPlan", () => {title: "No join predicate",detail:"The join has no condition, so every row of one input is paired with every row of the other.",+ source: "engine",},]);});@@ -303,6 +304,7 @@ describe("parseMssqlPlan", () => {title: "Missing index",detail:"SQL Server estimates this index would lower the statement's cost by 78.4%: CREATE NONCLUSTERED INDEX [idx_orders_total] ON [dbo].[orders] ([total]) INCLUDE ([customer_id]);",+ source: "engine",},]);});@@ -359,10 +361,12 @@ describe("parseMssqlPlan", () => {title: "Unmatched indexes",detail:"A filtered index could not be used because the statement is parameterized.",+ source: "engine",},{title: "Spatial Guess",detail: "SQL Server flagged this while compiling the plan.",+ source: "engine",},]);});@@ -374,6 +378,7 @@ describe("parseMssqlPlan", () => {title: "Unmatched indexes",detail:"The statement is parameterized, so SQL Server could not use the filtered index [plandb].[dbo].[orders].[orders_big_total_idx].",+ source: "engine",});});@@ -385,10 +390,15 @@ describe("parseMssqlPlan", () => {);expect(root.warnings).toEqual([- { title: "Columns With Stale Statistics", detail: "customers.region" },+ {+ title: "Columns With Stale Statistics",+ detail: "customers.region",+ source: "engine",+ },{title: "Spill Occurred",detail: "SQL Server flagged this while compiling the plan.",+ source: "engine",},]);});@@ -479,3 +489,66 @@ describe("parseMssqlPlan", () => {expect(parseMssqlPlan(source)).toEqual({ ok: false, message });});});++describe("parseMssqlPlan on an actual plan", () => {+ // SET STATISTICS XML ON: each thread of a parallel scan counts its own rows.+ const parallelScanActual = showplan(+ `<StmtSimple StatementType="SELECT" StatementSubTreeCost="3.5">+ <QueryPlan>+ <RelOp NodeId="0" PhysicalOp="Table Scan" LogicalOp="Table Scan" EstimateRows="900" EstimatedTotalSubtreeCost="3.5">+ <RunTimeInformation>+ <RunTimeCountersPerThread Thread="1" ActualRows="500" ActualExecutions="1"/>+ <RunTimeCountersPerThread Thread="2" ActualRows="700" ActualExecutions="1"/>+ </RunTimeInformation>+ <TableScan><Object Table="[orders]"/></TableScan>+ </RelOp>+ </QueryPlan>+ </StmtSimple>`+ );++ test("adds up the rows every thread really returned", () => {+ const scan = byType(parseFixture(parallelScanActual), "Table Scan");++ expect(scan.actualRows).toBe(1200);+ expect(scan.loops).toBe(2);+ expect(scan.rows).toBe(900);+ });++ test("says the plan measured rows but not time", () => {+ const { measured } = parseFixture(parallelScanActual);++ // SQL Server's elapsed time means different things in row and batch mode,+ // so the ranking stays on the estimated cost the plan always carries.+ expect(measured).toEqual({ time: false, rows: true });+ });++ test("leaves an estimated plan with no measurements", () => {+ const { measured } = parseFixture(hashJoinAggregateSort);++ expect(measured).toEqual({ time: false, rows: false });+ });+});++describe("parseMssqlPlan relation", () => {+ test("keeps the qualifiers SQL Server writes on the object", () => {+ const scan = byType(parseFixture(indexSeekKeyLookup), "Index Seek");++ // The database matters: a cross-database read must not be answered from+ // the connected database's catalog.+ expect(scan.relation).toEqual({+ table: "orders",+ database: "plandb",+ schema: "dbo",+ });+ });++ test("names no relation for an operator that reads no table", () => {+ const tree = parseFixture(+ showplan(+ '<StmtSimple StatementType="SELECT"><QueryPlan><RelOp NodeId="0" PhysicalOp="Sort" LogicalOp="Sort"><Sort/></RelOp></QueryPlan></StmtSimple>'+ )+ );++ expect(byType(tree, "Sort").relation).toBeUndefined();+ });+});diff --git a/frontend/src/apps/explain-visualizer/mssql-plan.ts b/frontend/src/apps/explain-visualizer/mssql-plan.tsindex cf06845cea..d32e73ca79 100644--- a/frontend/src/apps/explain-visualizer/mssql-plan.ts+++ b/frontend/src/apps/explain-visualizer/mssql-plan.ts@@ -7,6 +7,7 @@ import {type PlanNode,type PlanParseResult,type PlanProperty,+ type PlanRelation,type PlanWarning,parseWithDepthLimit,planSelfCost,@@ -351,8 +352,11 @@ function pairColumns(left: string[], right: string[]): string {.join(", ");}+/** A diagnostic SQL Server itself reports, before its source is stamped on. */+type EngineWarning = Omit<PlanWarning, "source">;+/** Warnings SQL Server raises as a flag on `<Warnings>`, by attribute name. */-const FLAG_WARNINGS: Record<string, PlanWarning> = {+const FLAG_WARNINGS: Record<string, EngineWarning> = {NoJoinPredicate: {title: "No join predicate",detail:@@ -374,7 +378,7 @@ function toServerWarnings(unmatchedIndexes: readonly string[] = []): PlanWarning[] {if (!warnings) return [];- const result: PlanWarning[] = [];+ const result: EngineWarning[] = [];for (const attribute of Array.from(warnings.attributes)) {if (!isTrue(attribute.value)) continue;if (attribute.name === "UnmatchedIndexes" && unmatchedIndexes.length > 0) {@@ -423,7 +427,7 @@ function toServerWarnings(}}}- return result;+ return result.map((warning) => ({ ...warning, source: "engine" }));}/**@@ -464,6 +468,7 @@ function toMissingIndexWarnings(queryPlan: Element): PlanWarning[] {impact === undefined? `SQL Server suggests this index: ${statement}`: `SQL Server estimates this index would lower the statement's cost by ${formatPlanShare(impact / 100)}: ${statement}`,+ source: "engine",};}));@@ -640,6 +645,28 @@ function toOperatorName(relop: Element, operator: Element | undefined): string {return `${physical} (${logical})`;}+/**+ * The table the operator reads, with the qualifiers SQL Server wrote on it.+ * It names the database on every object, including the connected one, so the+ * lookup compares rather than refusing anything qualified.+ */+function toOperatorRelation(+ operator: Element | undefined+): PlanRelation | undefined {+ const object = firstChild(operator, "Object");+ const table = object?.getAttribute("Table");+ if (!object || !table) return undefined;+ const qualifier = (name: string) => {+ const value = object.getAttribute(name);+ return value ? unbracket(value) : undefined;+ };+ return {+ table: unbracket(table),+ database: qualifier("Database"),+ schema: qualifier("Schema"),+ };+}+/** What the operator works on, for the one line a card has room for. */function toOperatorSubject(operator: Element | undefined): string | undefined {const object = firstChild(operator, "Object");@@ -741,6 +768,44 @@ function toOperatorWarnings(return warnings;}+/** A counter summed over the threads reporting it, or undefined when none do. */+function sumThreadAttribute(+ threads: readonly Element[],+ name: string+): number | undefined {+ let total: number | undefined;+ for (const thread of threads) {+ const value = numberAttribute(thread, name);+ if (value === undefined) continue;+ total = (total ?? 0) + value;+ }+ return total;+}++/**+ * What the operator really did, on an actual plan (`SET STATISTICS XML ON`).+ *+ * Every thread reports its own counters, so rows and executions are summed+ * across them. Elapsed time is left out: SQL Server reports it cumulatively on+ * a row-mode operator but per operator on a batch-mode one, and the model+ * holds one meaning, so a plan mixing the two would be ranked by a number that+ * is wrong for half of it. Such a plan ranks by estimated cost, which it always+ * carries, and its estimated and actual rows still sit side by side.+ */+function toOperatorMeasurements(relop: Element): {+ loops?: number;+ actualRows?: number;+} {+ const threads = childElements(+ firstChild(relop, "RunTimeInformation"),+ "RunTimeCountersPerThread"+ );+ return {+ loops: sumThreadAttribute(threads, "ActualExecutions"),+ actualRows: sumThreadAttribute(threads, "ActualRows"),+ };+}+function toOperatorNode({ element: relop, relationship }: PlanChild,id: string,@@ -749,15 +814,19 @@ function toOperatorNode(const operator = operatorElement(relop);const children = operator ? toChildren(operator, id, depth) : [];const totalCost = numberAttribute(relop, "EstimatedTotalSubtreeCost");+ const measured = toOperatorMeasurements(relop);return {id,nodeType: toOperatorName(relop, operator),subject: toOperatorSubject(operator),+ relation: toOperatorRelation(operator),relationship,totalCost,selfCost: planSelfCost(totalCost, children),rows: numberAttribute(relop, "EstimateRows"),width: numberAttribute(relop, "AvgRowSize"),+ loops: measured.loops,+ actualRows: measured.actualRows,properties: toOperatorProperties(relop, operator),warnings: toOperatorWarnings(relop,diff --git a/frontend/src/apps/explain-visualizer/plan-i18n.tsx b/frontend/src/apps/explain-visualizer/plan-i18n.tsxindex 4ec9363e60..95bc2277be 100644--- a/frontend/src/apps/explain-visualizer/plan-i18n.tsx+++ b/frontend/src/apps/explain-visualizer/plan-i18n.tsx@@ -5,6 +5,7 @@ const ENGLISH = {"copy.failed": "Copy failed","copy.plan": "Copy plan","details.select-node": "Select a node to see its details.",+ "diagram.actual-rows": "actual rows {{count}}","diagram.collapse": "Collapse {{count}} nodes under {{node}}","diagram.cost": "cost {{cost}}","diagram.estimated-rows": "{{count}} estimated rows",@@ -12,7 +13,9 @@ const ENGLISH = {"diagram.fit": "Fit to view","diagram.nodes-hidden": "{{count}} nodes hidden","diagram.plan-cost-share": "{{share}} of plan cost",+ "diagram.plan-time-share": "{{share}} of plan time","diagram.rows": "rows {{count}}",+ "diagram.time": "time {{time}} ms","diagram.zoom-in": "Zoom in","diagram.zoom-out": "Zoom out","error.mssql-empty": "SQL Server returned no query plan for this statement.",@@ -38,6 +41,9 @@ const ENGLISH = {"error.too-many-nodes":"The query plan has more operators than this visualizer draws, so it is shown as text.","error.unreadable": "This query plan could not be read",+ "grid.actual-rows": "Actual rows",+ "grid.actual-rows-hint":+ "Rows the operator really returned, over all its runs together","grid.added-cost": "Added cost","grid.added-cost-hint":"Cost this node adds on top of its children; some engines also count an input's repeats here, as under a nested loop. The bar is that cost as a share of the plan.",@@ -46,6 +52,9 @@ const ENGLISH = {"grid.estimated-rows": "Estimated rows","grid.node": "Node","grid.rows": "Rows",+ "grid.self-time": "Self time",+ "grid.self-time-hint":+ "Milliseconds this node took on top of its children, over all its runs. The bar is that time as a share of the plan.","grid.total-cost": "Total cost","grid.width": "Width","grid.width-hint": "Estimated row width in bytes",@@ -56,23 +65,50 @@ const ENGLISH = {"highlight.off-hint": "Leave every node card unshaded","highlight.rows": "Rows","highlight.rows-hint": "Shade by the estimated row count",+ "highlight.time": "Time",+ "highlight.time-hint": "Shade by the time a node took on top of its children","legend.cost":"each card's bar is that node's share of the plan's estimated cost","legend.rows":"an edge thickens with the rows its child is estimated to return",+ "legend.time":+ "each card's bar is that node's share of the plan's measured time",+ "metric.actual-rows": "Actual rows",+ "metric.actual-time": "Actual time","metric.added-cost": "Added cost","metric.bytes": "{{count}} bytes","metric.estimated-rows": "Estimated rows",+ "metric.loops": "Loops",+ "metric.milliseconds": "{{count}} ms","metric.row-width": "Row width",+ "metric.rows-none": "Returned no rows, where the planner expected some.",+ "metric.rows-over":+ "Returned {{factor}}× more rows than the planner estimated.",+ "metric.rows-under":+ "Returned {{factor}}× fewer rows than the planner estimated.","metric.startup-cost": "Startup cost","metric.total-cost": "Total cost","summary.costliest": "Costliest by estimated cost","summary.no-added-cost":"No node in this plan adds an estimated cost of its own.",+ "summary.no-added-time":+ "No node in this plan took measurable time of its own.",+ "summary.no-ranking":+ "This plan reports no cost or time, so its operators cannot be ranked.",+ "summary.slowest-measured": "Slowest by measured time",+ "summary.warning-operators": "{{count}} operators",+ "summary.warnings": "Warnings","tab.diagram": "Diagram","tab.grid": "Table","tab.text": "Text",+ "table.heading": "Table",+ "table.indexes": "Indexes",+ "table.no-indexes": "No indexes on this table.",+ "table.primary": "primary",+ "table.rows": "{{count}} rows at the last sync",+ "table.unique": "unique","totals.estimated-cost": "estimated cost {{cost}}",+ "totals.measured-time": "measured time {{time}} ms","totals.nodes": "{{count}} nodes",} as const;diff --git a/frontend/src/apps/explain-visualizer/plan-model.test.ts b/frontend/src/apps/explain-visualizer/plan-model.test.tsindex 5acfb8b0fe..6f5306c64e 100644--- a/frontend/src/apps/explain-visualizer/plan-model.test.ts+++ b/frontend/src/apps/explain-visualizer/plan-model.test.ts@@ -11,21 +11,30 @@ import {isJsonRecord,PLAN_EDGE_MAX_WIDTH,PLAN_EDGE_MIN_WIDTH,+ PLAN_FULL_TABLE_SCAN,PLAN_TOO_DEEP_MESSAGE,PLAN_TOO_MANY_NODES_MESSAGE,+ PLAN_WARNING_RELEVANT_SHARE,type PlanNode,type PlanProperty,type PlanTree,+ type PlanWarning,parseWithDepthLimit,planCollapsedAncestor,planCostliestNodes,planDescendantCount,planEdgeWidth,+ planHasSelfMetric,planHighlightIntensity,+ planRankMetric,planRevealNode,+ planRowEstimateFactor,planRows,planSelfCost,planSelfCostShare,+ planSelfShare,+ planSelfTime,+ planWarningGroups,} from "./plan-model";import { parsePostgresPlan } from "./postgres-plan";import cteNestedLoopInitplan from "./test-data/postgres/cte-nested-loop-initplan.json";@@ -526,3 +535,192 @@ describe("planCostliestNodes", () => {expect(planCostliestNodes(buildPlanTree(node("0")))).toEqual([]);});});++/** A node the way a plan that ran describes one. */+const timedNode = (+ id: string,+ overrides: Partial<PlanNode> = {},+ children: PlanNode[] = []+): PlanNode =>+ node(+ id,+ { actualRows: 0, actualTime: 0, selfTime: 0, loops: 1, ...overrides },+ children+ );++const engineWarning = (title: string): PlanWarning => ({+ title,+ detail: "SQL Server flagged this while compiling the plan.",+ source: "engine",+});++describe("planSelfTime", () => {+ test("takes the children's measured time off a cumulative one", () => {+ expect(+ planSelfTime(10, [+ timedNode("0.0", { actualTime: 4 }),+ timedNode("0.1", { actualTime: 3 }),+ ])+ ).toBe(3);+ });++ test("clamps a node that stopped its children early at zero", () => {+ expect(planSelfTime(1, [timedNode("0.0", { actualTime: 9 })])).toBe(0);+ });++ test("is undefined for a node the plan did not measure", () => {+ expect(planSelfTime(undefined, [])).toBeUndefined();+ });+});++describe("measured plans", () => {+ const measuredTree = () =>+ buildPlanTree(+ timedNode("0", { actualTime: 100, selfTime: 10, selfCost: 90 }, [+ timedNode("0.0", { actualTime: 70, selfTime: 70, selfCost: 5 }),+ timedNode("0.1", { actualTime: 20, selfTime: 20, selfCost: 5 }),+ ])+ );++ test("records which measurements the plan carries", () => {+ expect(measuredTree().measured).toEqual({ time: true, rows: true });+ expect(buildPlanTree(node("0")).measured).toEqual({+ time: false,+ rows: false,+ });+ });++ test("ranks by measured time, not by the planner's cost", () => {+ const tree = measuredTree();+ expect(planRankMetric(tree)).toBe("time");+ // The root is the costliest by estimate and the least of the work in fact.+ expect(planCostliestNodes(tree).map((entry) => entry.id)).toEqual([+ "0.0",+ "0.1",+ "0",+ ]);+ });++ test("takes every share from the metric the plan is ranked on", () => {+ const tree = measuredTree();+ expect(planSelfShare(tree.nodes[1], tree)).toBeCloseTo(0.7);+ // Cost shares stay available for the surfaces that print a cost.+ expect(planSelfCostShare(tree.nodes[1], tree)).toBeCloseTo(0.05);+ });++ test("keeps the time basis at or above the self times it adds up", () => {+ const limited = buildPlanTree(+ timedNode("0", { actualTime: 1, selfTime: 0 }, [+ timedNode("0.0", { actualTime: 40, selfTime: 40 }),+ ])+ );+ expect(limited.timeBasis).toBe(40);+ expect(planSelfShare(limited.nodes[1], limited)).toBe(1);+ });++ test("shades by measured time where asked", () => {+ const tree = measuredTree();+ expect(planHighlightIntensity(tree.nodes[1], tree, "time")).toBe(1);+ expect(planHighlightIntensity(tree.nodes[0], tree, "time")).toBeCloseTo(+ Math.sqrt(10 / 70)+ );+ });++ test("gives an unmeasured plan no ranking by time", () => {+ const tree = buildPlanTree(node("0", { selfCost: 5 }));+ expect(planRankMetric(tree)).toBe("cost");+ expect(planHasSelfMetric(tree)).toBe(true);+ expect(planHasSelfMetric(buildPlanTree(bareNode("0")))).toBe(false);+ });+});++describe("planRowEstimateFactor", () => {+ test("multiplies the per-execution estimate out by the executions", () => {+ // 5 rows expected each time round a 10-loop nested loop, 500 returned.+ expect(+ planRowEstimateFactor(+ timedNode("0", { rows: 5, loops: 10, actualRows: 500 })+ )+ ).toBe(10);+ });++ test("reads below one when the node returned fewer rows than planned", () => {+ expect(+ planRowEstimateFactor(timedNode("0", { rows: 100, actualRows: 25 }))+ ).toBe(0.25);+ });++ test("is undefined without a measurement, or without an estimate to compare", () => {+ expect(planRowEstimateFactor(node("0", { rows: 10 }))).toBeUndefined();+ expect(+ planRowEstimateFactor(timedNode("0", { rows: 0, actualRows: 10 }))+ ).toBeUndefined();+ });+});++describe("planWarningGroups", () => {+ // One plan: a scan that is most of it, a scan that is a rounding error, and+ // a diagnostic on a node the planner thinks costs nothing.+ const mixedTree = () =>+ buildPlanTree(+ node("0", { selfCost: 10 }, [+ node("0.0", { selfCost: 85, warnings: [PLAN_FULL_TABLE_SCAN] }),+ node("0.1", { selfCost: 5, warnings: [PLAN_FULL_TABLE_SCAN] }),+ node("0.2", {+ selfCost: 0,+ warnings: [engineWarning("Columns with no statistics")],+ }),+ ])+ );++ test("keeps an engine diagnostic whatever the node costs", () => {+ expect(+ planWarningGroups(mixedTree()).map((group) => [+ group.warning.title,+ group.nodes.map((entry) => entry.id),+ ])+ ).toEqual([+ ["Full table scan", ["0.0"]],+ ["Columns with no statistics", ["0.2"]],+ ]);+ });++ test("drops one of our scan heuristics on a node that costs little", () => {+ const share = planSelfShare(mixedTree().nodes[2], mixedTree());+ expect(share).toBeLessThan(PLAN_WARNING_RELEVANT_SHARE);+ expect(+ planWarningGroups(mixedTree()).flatMap((group) =>+ group.nodes.map((entry) => entry.id)+ )+ ).not.toContain("0.1");+ });++ test("groups a warning several nodes report, the worst of them first", () => {+ const tree = buildPlanTree(+ node("0", {}, [+ node("0.0", { selfCost: 20, warnings: [PLAN_FULL_TABLE_SCAN] }),+ node("0.1", { selfCost: 80, warnings: [PLAN_FULL_TABLE_SCAN] }),+ ])+ );+ expect(planWarningGroups(tree)).toHaveLength(1);+ expect(planWarningGroups(tree)[0].nodes.map((entry) => entry.id)).toEqual([+ "0.1",+ "0.0",+ ]);+ });++ test("keeps every warning when the plan has no number to weigh them by", () => {+ const tree = buildPlanTree({+ ...bareNode("0", [+ { ...bareNode("0.0"), warnings: [PLAN_FULL_TABLE_SCAN] },+ ]),+ });+ expect(planWarningGroups(tree).map((group) => group.warning.title)).toEqual(+ ["Full table scan"]+ );+ });++ test("is empty for a plan nothing is wrong with", () => {+ expect(planWarningGroups(buildPlanTree(node("0")))).toEqual([]);+ });+});diff --git a/frontend/src/apps/explain-visualizer/plan-model.ts b/frontend/src/apps/explain-visualizer/plan-model.tsindex 8d87712443..38e215c9b4 100644--- a/frontend/src/apps/explain-visualizer/plan-model.ts+++ b/frontend/src/apps/explain-visualizer/plan-model.ts@@ -4,10 +4,11 @@* Engine adapters map their own EXPLAIN output onto this model and the viewer* components read nothing else, so adding an engine means adding a parser.*- * Bytebase plans without executing, so every number here is an optimizer- * estimate: there is no actual timing, loop, buffer, or worker data to model.- * Engines differ in which estimates they report at all, so each one is- * optional and a surface shows only what the plan carries.+ * Most plans are estimates: Bytebase explains without executing, so there is+ * no timing or loop data to model. A plan the statement produced by running —+ * a typed `EXPLAIN ANALYZE`, SQL Server's actual plan — also carries what each+ * operator really did. Engines differ in which numbers they report at all, so+ * each one is optional and a surface shows only what the plan carries.*//** One free-form attribute the engine reported for a node. */@@ -16,10 +17,14 @@ export interface PlanProperty {readonly value: string;}+/** Where a warning came from, which decides whether relevance can hide it. */+export type PlanWarningSource = "engine" | "heuristic";+/** Something about a node worth a reader's attention, and what it means. */export interface PlanWarning {readonly title: string;readonly detail: string;+ readonly source: PlanWarningSource;}export interface PlanNode {@@ -29,6 +34,13 @@ export interface PlanNode {readonly nodeType: string;/** Table or index the operation reads, when the engine names one. */readonly subject?: string;+ /**+ * The table this operator reads, where it reads one. Narrower than+ * `subject`, which is whatever is worth printing on a card: a join+ * condition, an index, a sort key. This is what a lookup of Bytebase's own+ * metadata can be keyed on.+ */+ readonly relation?: PlanRelation;/** How the parent consumes this node, such as "Inner" or "InitPlan 1". */readonly relationship?: string;/** Cost before the node returns its first row, including its subtree. */@@ -41,6 +53,14 @@ export interface PlanNode {readonly rows?: number;/** Estimated size of one returned row, in bytes. */readonly width?: number;+ /** How many times the node ran, on a measured plan. */+ readonly loops?: number;+ /** Rows the node really returned, over all its runs together. */+ readonly actualRows?: number;+ /** Milliseconds the node and its subtree really took, over all its runs. */+ readonly actualTime?: number;+ /** What the node adds on top of its children's time; see `planSelfTime`. */+ readonly selfTime?: number;readonly properties: readonly PlanProperty[];readonly warnings: readonly PlanWarning[];readonly children: readonly PlanNode[];@@ -54,12 +74,26 @@ export interface PlanEstimates {readonly width: boolean;}+/**+ * What a plan measured, where it ran at all.+ *+ * Separate from `PlanEstimates` because the two answer different questions: an+ * estimate says what the planner expected, a measurement what happened, and a+ * surface that shows both has to say which is which.+ */+export interface PlanMeasurements {+ readonly time: boolean;+ readonly rows: boolean;+}+export interface PlanTree {readonly root: PlanNode;/** Every node in depth-first order, root first. */readonly nodes: readonly PlanNode[];readonly estimates: PlanEstimates;+ readonly measured: PlanMeasurements;readonly maxSelfCost: number;+ readonly maxSelfTime: number;readonly maxRows: number;/*** The whole plan's cost: the denominator of every cost share.@@ -72,6 +106,8 @@ export interface PlanTree {* at or below 100%.*/readonly costBasis: number;+ /** The whole plan's measured time, on the same rule as `costBasis`. */+ readonly timeBasis: number;}export type PlanParseResult =@@ -152,6 +188,17 @@ export function addPlanProperty(}}+/** A cumulative number of a node's own, with its children's share removed. */+function planSelfValue(+ total: number | undefined,+ children: readonly PlanNode[],+ of: (child: PlanNode) => number | undefined+): number | undefined {+ if (total === undefined) return undefined;+ const childTotal = children.reduce((sum, child) => sum + (of(child) ?? 0), 0);+ return Math.max(0, total - childTotal);+}+/*** A node's total cost minus its children's, clamped at zero, or undefined when* the node has no total cost. `PlanTree.costBasis` says when the clamp bites.@@ -160,12 +207,19 @@ export function planSelfCost(totalCost: number | undefined,children: readonly PlanNode[]): number | undefined {- if (totalCost === undefined) return undefined;- const childCost = children.reduce(- (sum, child) => sum + (child.totalCost ?? 0),- 0- );- return Math.max(0, totalCost - childCost);+ return planSelfValue(totalCost, children, (child) => child.totalCost);+}++/**+ * A node's measured time minus its children's, on the same rule as+ * `planSelfCost`: the time the operator itself spent, which is what a reader+ * can act on. Ranking the cumulative number would only ever find the root.+ */+export function planSelfTime(+ actualTime: number | undefined,+ children: readonly PlanNode[]+): number | undefined {+ return planSelfValue(actualTime, children, (child) => child.actualTime);}/** Warning for a read of a whole table, attached by each engine's parser. */@@ -173,6 +227,7 @@ export const PLAN_FULL_TABLE_SCAN: PlanWarning = {title: "Full table scan",detail:"Reads every row of this table. If the query needs only a few of them, an index on the filtered columns could avoid the full read.",+ source: "heuristic",};/** Warning for a read of a whole index, attached by each engine's parser. */@@ -180,10 +235,50 @@ export const PLAN_FULL_INDEX_SCAN: PlanWarning = {title: "Full index scan",detail:"Reads every entry of this index. If the query needs only a few of them, a condition on the index's leading columns could avoid the full read.",+ source: "heuristic",};-/** Which estimate, if any, shades the diagram's node cards. */-export type PlanHighlightMode = "off" | "cost" | "rows";+/**+ * A table an operator reads, as the plan names it.+ *+ * The qualifiers matter as much as the name: SQL Server writes the database on+ * every object it reads, and a plan that reads `archive.dbo.orders` must not be+ * answered with the connected database's own `orders`.+ */+export interface PlanRelation {+ readonly table: string;+ readonly database?: string;+ readonly schema?: string;+}++/** One index on a table an operator reads, as Bytebase last synced it. */+export interface PlanTableIndex {+ readonly name: string;+ /** The indexed columns or expressions, in order, as one line. */+ readonly columns: string;+ readonly unique?: boolean;+ readonly primary?: boolean;+}++/**+ * What Bytebase already knows about a table an operator reads.+ *+ * No standalone plan viewer can show this: pev2 and its kind are handed a+ * pasted file with no catalog behind it. It is what turns "this scan is+ * expensive" into a next step.+ */+export interface PlanTableFacts {+ readonly rowCount?: number;+ readonly indexes: readonly PlanTableIndex[];+}++/** Answers what Bytebase knows about a relation, where it knows anything. */+export type PlanTableLookup = (+ relation: PlanRelation+) => PlanTableFacts | undefined;++/** Which number, if any, shades the diagram's node cards. */+export type PlanHighlightMode = "off" | "cost" | "time" | "rows";export function flattenPlan(root: PlanNode): PlanNode[] {const nodes: PlanNode[] = [];@@ -198,32 +293,43 @@ export function flattenPlan(root: PlanNode): PlanNode[] {export function buildPlanTree(root: PlanNode): PlanTree {const nodes = flattenPlan(root);let maxSelfCost = 0;+ let maxSelfTime = 0;let maxRows = 0;let selfCostTotal = 0;+ let selfTimeTotal = 0;const estimates = {cost: false,startupCost: false,rows: false,width: false,};+ const measured = { time: false, rows: false };for (const node of nodes) {const selfCost = node.selfCost ?? 0;+ const selfTime = node.selfTime ?? 0;const rows = node.rows ?? 0;if (selfCost > maxSelfCost) maxSelfCost = selfCost;+ if (selfTime > maxSelfTime) maxSelfTime = selfTime;if (rows > maxRows) maxRows = rows;selfCostTotal += selfCost;+ selfTimeTotal += selfTime;estimates.cost ||= node.totalCost !== undefined;estimates.startupCost ||= node.startupCost !== undefined;estimates.rows ||= node.rows !== undefined;estimates.width ||= node.width !== undefined;+ measured.time ||= node.actualTime !== undefined;+ measured.rows ||= node.actualRows !== undefined;}return {root,nodes,estimates,+ measured,maxSelfCost,+ maxSelfTime,maxRows,costBasis: Math.max(root.totalCost ?? 0, selfCostTotal),+ timeBasis: Math.max(root.actualTime ?? 0, selfTimeTotal),};}@@ -356,6 +462,17 @@ export function formatPlanCount(value: number | undefined): string {return value === undefined ? PLAN_NO_ESTIMATE : countFormat.format(value);}+// Milliseconds, as PostgreSQL reports them; an operator can run in a few+// microseconds, so sub-millisecond times keep their digits. The unit is in the+// label beside the number, which comes through the viewer's translate.+const durationFormat = new Intl.NumberFormat("en-US", {+ maximumFractionDigits: 3,+});++export function formatPlanDuration(value: number | undefined): string {+ return value === undefined ? PLAN_NO_ESTIMATE : durationFormat.format(value);+}+const shareFormat = new Intl.NumberFormat("en-US", {style: "percent",maximumFractionDigits: 1,@@ -368,6 +485,11 @@ export function formatPlanShare(value: number): string {return shareFormat.format(value);}+function planShare(value: number | undefined, basis: number): number {+ if (basis <= 0) return 0;+ return Math.min(1, Math.max(0, (value ?? 0) / basis));+}+/*** A node's self cost as a fraction of the whole plan's cost, from 0 to 1.*@@ -375,8 +497,68 @@ export function formatPlanShare(value: number): string {* this length is read as a quantity, so it has to be one.*/export function planSelfCostShare(node: PlanNode, tree: PlanTree): number {- if (tree.costBasis <= 0) return 0;- return Math.min(1, Math.max(0, (node.selfCost ?? 0) / tree.costBasis));+ return planShare(node.selfCost, tree.costBasis);+}++/**+ * Which number the ranking and its shares go by.+ *+ * Measured time wins wherever the plan has it: planner costs are arbitrary+ * units, and they are wrong in exactly the cases worth investigating, so+ * ranking a measured plan by estimate would point at the wrong operator+ * precisely when it matters.+ */+export type PlanRankMetric = "time" | "cost";++export function planRankMetric(tree: PlanTree): PlanRankMetric {+ return tree.measured.time ? "time" : "cost";+}++/** A node's share of the plan by whichever number it is ranked on, 0 to 1. */+export function planSelfShare(node: PlanNode, tree: PlanTree): number {+ return planRankMetric(tree) === "time"+ ? planShare(node.selfTime, tree.timeBasis)+ : planShare(node.selfCost, tree.costBasis);+}++/**+ * Below this multiple the planner's row estimate was close enough that saying+ * so would be noise; the two row counts are on the node either way.+ */+export const PLAN_ROW_ESTIMATE_NOTABLE_FACTOR = 2;++/**+ * How far out the planner's row estimate was, as a multiple of it: above 1 the+ * node returned more rows than planned, below 1 fewer.+ *+ * The estimate is per execution and the measurement is a total, so the+ * executions are multiplied back in — the comparison a reader would otherwise+ * have to do by hand, and the one that explains a bad plan that cost alone+ * does not. Undefined when the node was not measured, or when the planner+ * expected no rows at all and there is no multiple to state.+ */+export function planRowEstimateFactor(node: PlanNode): number | undefined {+ if (node.actualRows === undefined || node.rows === undefined)+ return undefined;+ const expected = node.rows * (node.loops ?? 1);+ if (expected <= 0) return undefined;+ return node.actualRows / expected;+}++/**+ * Whether the plan reports what each operator added of its own, so a surface+ * can give it a column and a bar. Says nothing about the numbers being above+ * zero; `planShareIsMeaningful` answers that.+ */+export function planHasSelfMetric(tree: PlanTree): boolean {+ return tree.measured.time || tree.estimates.cost;+}++/** Whether the plan's total is above zero, so a share of it means something. */+function planShareIsMeaningful(tree: PlanTree): boolean {+ return planRankMetric(tree) === "time"+ ? tree.timeBasis > 0+ : tree.costBasis > 0;}/** Narrowest and widest stroke a diagram edge is drawn with, in pixels. */@@ -407,26 +589,96 @@ export function planEdgeWidth(/** How many operators the side panel ranks before it stops being a summary. */export const PLAN_COSTLIEST_LIMIT = 3;+function planOwnValue(tree: PlanTree): (node: PlanNode) => number {+ return planRankMetric(tree) === "time"+ ? (node) => node.selfTime ?? 0+ : (node) => node.selfCost ?? 0;+}+/**- * The nodes that own the most cost, largest first. A node that adds nothing on- * top of its children is not a cost the reader can go after, so it is left out.+ * The nodes that own the most of the plan — measured time where it has it,+ * estimated cost otherwise — largest first. A node that adds nothing on top of+ * its children is not a cost the reader can go after, so it is left out.*/export function planCostliestNodes(tree: PlanTree,limit: number = PLAN_COSTLIEST_LIMIT): PlanNode[] {+ const own = planOwnValue(tree);return tree.nodes- .filter((node) => (node.selfCost ?? 0) > 0)- .sort((a, b) => (b.selfCost ?? 0) - (a.selfCost ?? 0))+ .filter((node) => own(node) > 0)+ .sort((a, b) => own(b) - own(a)).slice(0, limit);}+/**+ * Share of the plan below which one of our own scan heuristics stays off the+ * summary panel.+ *+ * A full scan of a small lookup table is the correct plan, and warning about+ * every scan teaches readers to ignore the warnings that matter. It applies to+ * Bytebase's heuristics alone: a diagnostic the engine itself reports always+ * reaches the panel, because "columns with no statistics" is the explanation+ * for a node that a cost threshold would call cheap.+ */+export const PLAN_WARNING_RELEVANT_SHARE = 0.1;++/** One warning and the nodes reporting it, worst first. */+export interface PlanWarningGroup {+ readonly warning: PlanWarning;+ readonly nodes: readonly PlanNode[];+}++/**+ * The warnings worth the summary panel, grouped by warning so one heuristic+ * firing on eight nodes is one line and not eight. Groups come in plan order;+ * node details still show every warning a node carries, relevant or not.+ */+export function planWarningGroups(tree: PlanTree): PlanWarningGroup[] {+ // With no cost and no measurement there is nothing to judge relevance by, so+ // every warning stands rather than being dropped for want of a number.+ const ranked = planShareIsMeaningful(tree);+ const own = planOwnValue(tree);+ const groups = new Map<string, { warning: PlanWarning; nodes: PlanNode[] }>();+ for (const node of tree.nodes) {+ for (const warning of node.warnings) {+ if (+ warning.source === "heuristic" &&+ ranked &&+ planSelfShare(node, tree) < PLAN_WARNING_RELEVANT_SHARE+ ) {+ continue;+ }+ const group = groups.get(warning.title);+ if (group) group.nodes.push(node);+ else groups.set(warning.title, { warning, nodes: [node] });+ }+ }+ return [...groups.values()].map(({ warning, nodes }) => ({+ warning,+ nodes: nodes.sort((a, b) => own(b) - own(a)),+ }));+}++/** What each shading mode reads off a node, and the plan's largest of it. */+const PLAN_HIGHLIGHT_VALUES: Record<+ Exclude<PlanHighlightMode, "off">,+ {+ readonly of: (node: PlanNode) => number | undefined;+ readonly max: (tree: PlanTree) => number;+ }+> = {+ cost: { of: (node) => node.selfCost, max: (tree) => tree.maxSelfCost },+ time: { of: (node) => node.selfTime, max: (tree) => tree.maxSelfTime },+ rows: { of: (node) => node.rows, max: (tree) => tree.maxRows },+};+/*** How strongly a node should be shaded, from 0 (no shading) to 1.*- * Costs and row counts span orders of magnitude within one plan, so a linear- * ramp leaves everything but the single worst node invisible. The square root- * keeps the extremes ordered while giving mid-range nodes a readable tint.+ * Costs, times and row counts span orders of magnitude within one plan, so a+ * linear ramp leaves everything but the single worst node invisible. The square+ * root keeps the extremes ordered while giving mid-range nodes a readable tint.*/export function planHighlightIntensity(node: PlanNode,@@ -434,8 +686,9 @@ export function planHighlightIntensity(mode: PlanHighlightMode): number {if (mode === "off") return 0;- const value = (mode === "cost" ? node.selfCost : node.rows) ?? 0;- const max = mode === "cost" ? tree.maxSelfCost : tree.maxRows;+ const { of, max: maxOf } = PLAN_HIGHLIGHT_VALUES[mode];+ const value = of(node) ?? 0;+ const max = maxOf(tree);if (max <= 0 || value <= 0) return 0;return Math.sqrt(Math.min(value, max) / max);}diff --git a/frontend/src/apps/explain-visualizer/plan-parsers.ts b/frontend/src/apps/explain-visualizer/plan-parsers.tsnew file mode 100644index 0000000000..b639784d30--- /dev/null+++ b/frontend/src/apps/explain-visualizer/plan-parsers.ts@@ -0,0 +1,24 @@+import { Engine } from "@/types/proto-es/v1/common_pb";+import type { VisualizerEngine } from "@/utils/queryPlanEngines";+import { parseMssqlPlan } from "./mssql-plan";+import type { PlanParseResult } from "./plan-model";+import { parsePostgresPlan } from "./postgres-plan";+import { parseSpannerPlan } from "./spanner-plan";++/**+ * Each engine's explain output on the engine-neutral model, keyed on the same+ * table as the format the SQL editor asks that engine for, so the two cannot+ * drift. Adding an engine means adding a parser and its format.+ */+const PARSERS: Record<VisualizerEngine, (source: string) => PlanParseResult> = {+ [Engine.POSTGRES]: parsePostgresPlan,+ [Engine.MSSQL]: parseMssqlPlan,+ [Engine.SPANNER]: parseSpannerPlan,+};++export function parsePlan(+ engine: VisualizerEngine,+ source: string+): PlanParseResult {+ return PARSERS[engine](source);+}diff --git a/frontend/src/apps/explain-visualizer/postgres-plan.test.ts b/frontend/src/apps/explain-visualizer/postgres-plan.test.tsindex 55a00e264d..a7e9ee409e 100644--- a/frontend/src/apps/explain-visualizer/postgres-plan.test.ts+++ b/frontend/src/apps/explain-visualizer/postgres-plan.test.ts@@ -290,3 +290,141 @@ describe("parsePostgresPlan", () => {expect(warningsOf({ "Node Type": "Bitmap Heap Scan" })).toEqual([]);});});++describe("parsePostgresPlan on a measured plan", () => {+ // EXPLAIN (ANALYZE, FORMAT JSON) over a nested loop: PostgreSQL reports the+ // inner side's time and rows as averages over its four executions.+ const nestedLoopAnalyze = [+ {+ Plan: {+ "Node Type": "Nested Loop",+ "Join Type": "Inner",+ "Startup Cost": 0.29,+ "Total Cost": 48.46,+ "Plan Rows": 10,+ "Plan Width": 36,+ "Actual Startup Time": 0.032,+ "Actual Total Time": 1.234,+ "Actual Rows": 12,+ "Actual Loops": 1,+ Plans: [+ {+ "Node Type": "Seq Scan",+ "Parent Relationship": "Outer",+ "Relation Name": "customers",+ "Startup Cost": 0,+ "Total Cost": 11.4,+ "Plan Rows": 4,+ "Plan Width": 20,+ "Actual Total Time": 0.02,+ "Actual Rows": 4,+ "Actual Loops": 1,+ },+ {+ "Node Type": "Index Scan",+ "Parent Relationship": "Inner",+ "Index Name": "orders_customer_id_idx",+ "Relation Name": "orders",+ "Startup Cost": 0.29,+ "Total Cost": 9.2,+ "Plan Rows": 3,+ "Plan Width": 16,+ "Actual Total Time": 0.25,+ "Actual Rows": 3,+ "Actual Loops": 4,+ },+ ],+ },+ "Execution Time": 1.3,+ },+ ];++ test("multiplies an average over the executions it was averaged over", () => {+ const { nodes } = parseFixture(nestedLoopAnalyze);+ const inner = nodes[2];++ expect(inner.nodeType).toBe("Index Scan");+ expect(inner.loops).toBe(4);+ expect(inner.actualRows).toBe(12);+ expect(inner.actualTime).toBe(1);+ // Nothing below it, so all of that time is its own.+ expect(inner.selfTime).toBe(1);+ });++ test("leaves the parent only the time its children did not account for", () => {+ const { root, measured, timeBasis } = parseFixture(nestedLoopAnalyze);++ expect(root.actualTime).toBe(1.234);+ expect(root.selfTime).toBeCloseTo(0.214);+ expect(measured).toEqual({ time: true, rows: true });+ expect(timeBasis).toBe(1.234);+ });++ test("records a node the planner built and never ran as a measured zero", () => {+ const { nodes } = parseFixture([+ {+ Plan: {+ "Node Type": "Nested Loop",+ "Actual Total Time": 0.5,+ "Actual Rows": 0,+ "Actual Loops": 1,+ Plans: [+ {+ "Node Type": "Seq Scan",+ "Relation Name": "orders",+ "Plan Rows": 100,+ "Actual Total Time": 0,+ "Actual Rows": 0,+ "Actual Loops": 0,+ },+ ],+ },+ },+ ]);++ expect(nodes[1].loops).toBe(0);+ expect(nodes[1].actualRows).toBe(0);+ expect(nodes[1].actualTime).toBe(0);+ });++ test("keeps the measurements out of the property list, bar the ones it does not model", () => {+ const { root } = parseFixture(nestedLoopAnalyze);++ expect(propertyValue(root, "Actual Rows")).toBeUndefined();+ expect(propertyValue(root, "Actual Total Time")).toBeUndefined();+ expect(propertyValue(root, "Actual Loops")).toBeUndefined();+ expect(propertyValue(root, "Actual Startup Time")).toBe("0.032");+ });++ test("leaves an estimate-only plan unmeasured", () => {+ const { root, measured } = parseFixture(seqScanFilter);++ expect(measured).toEqual({ time: false, rows: false });+ expect(root.actualRows).toBeUndefined();+ expect(root.selfTime).toBeUndefined();+ expect(root.loops).toBeUndefined();+ });+});++describe("parsePostgresPlan relation", () => {+ const rootOf = (raw: Record<string, unknown>) =>+ parseFixture([{ Plan: raw }]).root;++ test("names the table a scan reads, not the index it reads it by", () => {+ const root = rootOf({+ "Node Type": "Index Scan",+ "Relation Name": "salary",+ "Index Name": "salary_pkey",+ });++ expect(root.relation).toEqual({ table: "salary" });+ expect(root.subject).toBe("salary");+ });++ test("names no relation for a node that reads no table", () => {+ expect(+ rootOf({ "Node Type": "Hash Join", "Hash Cond": "(a.id = b.id)" })+ .relation+ ).toBeUndefined();+ });+});diff --git a/frontend/src/apps/explain-visualizer/postgres-plan.ts b/frontend/src/apps/explain-visualizer/postgres-plan.tsindex 8a44532e5b..afc81fffc7 100644--- a/frontend/src/apps/explain-visualizer/postgres-plan.ts+++ b/frontend/src/apps/explain-visualizer/postgres-plan.ts@@ -6,9 +6,11 @@ import {type PlanNode,type PlanParseResult,type PlanProperty,+ type PlanRelation,type PlanWarning,parseWithDepthLimit,planSelfCost,+ planSelfTime,} from "./plan-model";/**@@ -36,6 +38,9 @@ const PROMOTED_KEYS = new Set(["Plan Width","Parent Relationship","Subplan Name",+ "Actual Total Time",+ "Actual Rows",+ "Actual Loops",]);export const POSTGRES_PLAN_EMPTY_MESSAGE =@@ -66,13 +71,43 @@ function toWarnings(nodeType: string, totalCost: number): PlanWarning[] {: [];}-function toNumber(value: unknown): number {+function optionalNumber(value: unknown): number | undefined {if (typeof value === "number" && Number.isFinite(value)) return value;- if (typeof value === "string") {+ if (typeof value === "string" && value.trim()) {const parsed = Number(value);if (Number.isFinite(parsed)) return parsed;}- return 0;+ return undefined;+}++function toNumber(value: unknown): number {+ return optionalNumber(value) ?? 0;+}++/**+ * What the node really did, on a plan produced by `EXPLAIN ANALYZE`.+ *+ * PostgreSQL reports a measured node's time and rows as averages per+ * execution, so both are multiplied by the executions to reach the totals the+ * model holds. Before PostgreSQL 18 the row average is a whole number, so that+ * product is approximate to within half the loop count. A node the planner+ * built but never ran reports zero loops, which is a real measurement of zero+ * rows and zero time rather than a missing one.+ */+function toMeasurements(raw: JsonRecord): {+ loops?: number;+ actualRows?: number;+ actualTime?: number;+} {+ const perLoopTime = optionalNumber(raw["Actual Total Time"]);+ const perLoopRows = optionalNumber(raw["Actual Rows"]);+ if (perLoopTime === undefined && perLoopRows === undefined) return {};+ const loops = optionalNumber(raw["Actual Loops"]) ?? 1;+ return {+ loops,+ actualRows: perLoopRows === undefined ? undefined : perLoopRows * loops,+ actualTime: perLoopTime === undefined ? undefined : perLoopTime * loops,+ };}function formatValue(value: unknown): string {@@ -115,6 +150,16 @@ const SUBJECT_CONDITION_KEYS = ["Presorted Key",] as const;+function stringValue(value: unknown): string | undefined {+ return typeof value === "string" && value ? value : undefined;+}++function toRelation(raw: JsonRecord): PlanRelation | undefined {+ const table = stringValue(raw["Relation Name"]);+ if (!table) return undefined;+ return { table, schema: stringValue(raw["Schema"]) };+}+function toSubject(raw: JsonRecord): string | undefined {const relation = raw["Relation Name"];if (typeof relation === "string" && relation) return relation;@@ -204,16 +249,25 @@ function toPlanNode(raw: JsonRecord, id: string, depth: number): PlanNode {const children = toChildren(raw, id, depth);const nodeType = toNodeType(raw);const totalCost = toNumber(raw["Total Cost"]);+ const measured = toMeasurements(raw);return {id,nodeType,subject: toSubject(raw),+ // An index scan names the index as well, but it is the table a reader+ // would want to know about. PostgreSQL cannot read across databases, so a+ // plan never qualifies one.+ relation: toRelation(raw),relationship: toRelationship(raw),startupCost: toNumber(raw["Startup Cost"]),totalCost,selfCost: planSelfCost(totalCost, children),rows: toNumber(raw["Plan Rows"]),width: toNumber(raw["Plan Width"]),+ loops: measured.loops,+ actualRows: measured.actualRows,+ actualTime: measured.actualTime,+ selfTime: planSelfTime(measured.actualTime, children),properties: toProperties(raw),warnings: toWarnings(nodeType, totalCost),children,diff --git a/frontend/src/apps/explain-visualizer/spanner-plan.ts b/frontend/src/apps/explain-visualizer/spanner-plan.tsindex 9cd656b95d..b632ad5a34 100644--- a/frontend/src/apps/explain-visualizer/spanner-plan.ts+++ b/frontend/src/apps/explain-visualizer/spanner-plan.ts@@ -168,6 +168,11 @@ function toPlanNode(id,nodeType: toNodeType(raw),subject: scanTarget || condition?.value || description || undefined,+ // An index scan's target is the index, not a table Bytebase can look up.+ relation:+ stringField(metadata, "scan_type") === "TableScan" && scanTarget+ ? { table: scanTarget }+ : undefined,relationship,properties,warnings: toWarnings(raw),diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.jsonindex 34017bd397..b6339a5c33 100644--- a/frontend/src/locales/en-US.json+++ b/frontend/src/locales/en-US.json@@ -3447,6 +3447,7 @@"expire-in": "Expire in {{time}}","expired": "Expired","explain": "Explain",+ "explain-hint": "Show the plan without running the query","explore-data": "Explore data","export-available-via-issue": "Export available via issue \"{{title}}\"","export-available-via-n-grants": "Export available via {{count}} access grants:",@@ -3484,6 +3485,7 @@"open-in-new-tab": "Open in new tab","opened-from-link": "Opened from link","pending-query": "Pending query",+ "plan-cost-share": "{{share}} of the script's estimated cost","plan-estimated": "Estimated","plan-view": "Plan","previous-row": "Previous Row",@@ -3504,6 +3506,7 @@"select-node": "Select a node to see its details."},"diagram": {+ "actual-rows": "actual rows {{count}}","collapse": "Collapse {{count}} nodes under {{node}}","cost": "cost {{cost}}","estimated-rows": "{{count}} estimated rows",@@ -3511,7 +3514,9 @@"fit": "Fit to view","nodes-hidden": "{{count}} nodes hidden","plan-cost-share": "{{share}} of plan cost",+ "plan-time-share": "{{share}} of plan time","rows": "rows {{count}}",+ "time": "time {{time}} ms","zoom-in": "Zoom in","zoom-out": "Zoom out"},@@ -3531,12 +3536,16 @@"unreadable": "This query plan could not be read"},"grid": {+ "actual-rows": "Actual rows",+ "actual-rows-hint": "Rows the operator really returned, over all its runs together","added-cost": "Added cost","added-cost-hint": "Cost this node adds on top of its children; some engines also count an input's repeats here, as under a nested loop. The bar is that cost as a share of the plan.","caption": "Plan nodes in the order the planner nests them, parents before children.","estimated-rows": "Estimated rows","node": "Node","rows": "Rows",+ "self-time": "Self time",+ "self-time-hint": "Milliseconds this node took on top of its children, over all its runs. The bar is that time as a share of the plan.","total-cost": "Total cost","width": "Width","width-hint": "Estimated row width in bytes"@@ -3548,31 +3557,55 @@"off": "Off","off-hint": "Leave every node card unshaded","rows": "Rows",- "rows-hint": "Shade by the estimated row count"+ "rows-hint": "Shade by the estimated row count",+ "time": "Time",+ "time-hint": "Shade by the time a node took on top of its children"},"legend": {"cost": "each card's bar is that node's share of the plan's estimated cost",- "rows": "an edge thickens with the rows its child is estimated to return"+ "rows": "an edge thickens with the rows its child is estimated to return",+ "time": "each card's bar is that node's share of the plan's measured time"},"metric": {+ "actual-rows": "Actual rows",+ "actual-time": "Actual time","added-cost": "Added cost","bytes": "{{count}} bytes","estimated-rows": "Estimated rows",+ "loops": "Loops",+ "milliseconds": "{{count}} ms","row-width": "Row width",+ "rows-none": "Returned no rows, where the planner expected some.",+ "rows-over": "Returned {{factor}}× more rows than the planner estimated.",+ "rows-under": "Returned {{factor}}× fewer rows than the planner estimated.","startup-cost": "Startup cost","total-cost": "Total cost"},"summary": {"costliest": "Costliest by estimated cost",- "no-added-cost": "No node in this plan adds an estimated cost of its own."+ "no-added-cost": "No node in this plan adds an estimated cost of its own.",+ "no-added-time": "No node in this plan took measurable time of its own.",+ "no-ranking": "This plan reports no cost or time, so its operators cannot be ranked.",+ "slowest-measured": "Slowest by measured time",+ "warning-operators": "{{count}} operators",+ "warnings": "Warnings"},"tab": {"diagram": "Diagram","grid": "Table","text": "Text"},+ "table": {+ "heading": "Table",+ "indexes": "Indexes",+ "no-indexes": "No indexes on this table.",+ "primary": "primary",+ "rows": "{{count}} rows at the last sync",+ "unique": "unique"+ },"totals": {"estimated-cost": "estimated cost {{cost}}",+ "measured-time": "measured time {{time}} ms","nodes": "{{count}} nodes"}},diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.jsonindex f530599edd..bad068405f 100644--- a/frontend/src/locales/es-ES.json+++ b/frontend/src/locales/es-ES.json@@ -3447,6 +3447,7 @@"expire-in": "Expira en {{time}}","expired": "Expirado","explain": "Explicar",+ "explain-hint": "Muestra el plan sin ejecutar la consulta","explore-data": "Explorar datos","export-available-via-issue": "Exportación disponible vía issue \"{{title}}\"","export-available-via-n-grants": "Exportación disponible vía {{count}} concesiones de acceso:",@@ -3484,6 +3485,7 @@"open-in-new-tab": "Abrir en nueva pestaña","opened-from-link": "Abierto desde enlace","pending-query": "Consulta pendiente",+ "plan-cost-share": "{{share}} del coste estimado del script","plan-estimated": "Estimado","plan-view": "Plan","previous-row": "Fila anterior",@@ -3504,6 +3506,7 @@"select-node": "Selecciona un nodo para ver sus detalles."},"diagram": {+ "actual-rows": "filas reales {{count}}","collapse": "Contraer {{count}} nodos bajo {{node}}","cost": "coste {{cost}}","estimated-rows": "{{count}} filas estimadas",@@ -3511,7 +3514,9 @@"fit": "Ajustar a la vista","nodes-hidden": "{{count}} nodos ocultos","plan-cost-share": "{{share}} del coste del plan",+ "plan-time-share": "{{share}} del tiempo del plan","rows": "filas {{count}}",+ "time": "tiempo {{time}} ms","zoom-in": "Acercar","zoom-out": "Alejar"},@@ -3531,12 +3536,16 @@"unreadable": "No se pudo leer este plan de consulta"},"grid": {+ "actual-rows": "Filas reales",+ "actual-rows-hint": "Filas que el operador devolvió realmente, sumando todas sus ejecuciones","added-cost": "Coste añadido","added-cost-hint": "Coste que este nodo añade sobre sus hijos; algunos motores también cuentan aquí las repeticiones de una entrada, como bajo un bucle anidado. La barra muestra este coste como parte del plan.","caption": "Nodos del plan en el orden en que el planificador los anida, con los padres antes que los hijos.","estimated-rows": "Filas estimadas","node": "Nodo","rows": "Filas",+ "self-time": "Tiempo propio",+ "self-time-hint": "Milisegundos que este nodo tardó por encima de sus hijos, sumando todas sus ejecuciones. La barra muestra ese tiempo como parte del plan.","total-cost": "Coste total","width": "Anchura","width-hint": "Anchura estimada de la fila en bytes"@@ -3548,31 +3557,55 @@"off": "Desactivado","off-hint": "Dejar todas las tarjetas de nodo sin sombrear","rows": "Filas",- "rows-hint": "Sombrear según el número estimado de filas"+ "rows-hint": "Sombrear según el número estimado de filas",+ "time": "Tiempo",+ "time-hint": "Sombrear según el tiempo que un nodo tardó por encima de sus hijos"},"legend": {"cost": "la barra de cada tarjeta indica la parte del coste estimado del plan correspondiente a ese nodo",- "rows": "una arista se hace más gruesa según las filas que se estima que devolverá su nodo hijo"+ "rows": "una arista se hace más gruesa según las filas que se estima que devolverá su nodo hijo",+ "time": "la barra de cada tarjeta indica la parte del tiempo medido del plan correspondiente a ese nodo"},"metric": {+ "actual-rows": "Filas reales",+ "actual-time": "Tiempo real","added-cost": "Coste añadido","bytes": "{{count}} bytes","estimated-rows": "Filas estimadas",+ "loops": "Ejecuciones",+ "milliseconds": "{{count}} ms","row-width": "Anchura de fila",+ "rows-none": "No devolvió ninguna fila, aunque el planificador esperaba algunas.",+ "rows-over": "Devolvió {{factor}}× más filas de las que estimó el planificador.",+ "rows-under": "Devolvió {{factor}}× menos filas de las que estimó el planificador.","startup-cost": "Coste inicial","total-cost": "Coste total"},"summary": {"costliest": "Más costosos según el coste estimado",- "no-added-cost": "Ningún nodo de este plan añade un coste estimado propio."+ "no-added-cost": "Ningún nodo de este plan añade un coste estimado propio.",+ "no-added-time": "Ningún nodo de este plan consumió un tiempo propio medible.",+ "no-ranking": "Este plan no indica coste ni tiempo, así que sus operadores no se pueden ordenar.",+ "slowest-measured": "Más lentos según el tiempo medido",+ "warning-operators": "{{count}} operadores",+ "warnings": "Avisos"},"tab": {"diagram": "Diagrama","grid": "Tabla","text": "Texto"},+ "table": {+ "heading": "Tabla",+ "indexes": "Índices",+ "no-indexes": "Esta tabla no tiene índices.",+ "primary": "primaria",+ "rows": "{{count}} filas en la última sincronización",+ "unique": "único"+ },"totals": {"estimated-cost": "coste estimado {{cost}}",+ "measured-time": "tiempo medido {{time}} ms","nodes": "{{count}} nodos"}},diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.jsonindex 2af42c033d..25d39a4aa3 100644--- a/frontend/src/locales/ja-JP.json+++ b/frontend/src/locales/ja-JP.json@@ -3447,6 +3447,7 @@"expire-in": "{{time}} 後に期限切れ","expired": "期限切れ","explain": "実行計画を表示",+ "explain-hint": "クエリを実行せずに実行計画を表示します","explore-data": "データを探索","export-available-via-issue": "Issue「{{title}}」によりエクスポート可能","export-available-via-n-grants": "{{count}} 件のアクセス付与によりエクスポート可能:",@@ -3484,6 +3485,7 @@"open-in-new-tab": "新しいタブで開く","opened-from-link": "リンクから開く","pending-query": "保留中のクエリ",+ "plan-cost-share": "スクリプト全体の推定コストの {{share}}","plan-estimated": "推定","plan-view": "プラン","previous-row": "前の行",@@ -3504,6 +3506,7 @@"select-node": "詳細を表示するノードを選択してください。"},"diagram": {+ "actual-rows": "実測 {{count}} 行","collapse": "{{node}} 配下の {{count}} ノードを折りたたむ","cost": "コスト {{cost}}","estimated-rows": "推定 {{count}} 行",@@ -3511,7 +3514,9 @@"fit": "全体を表示","nodes-hidden": "{{count}} ノードを非表示","plan-cost-share": "プランコストの {{share}}",+ "plan-time-share": "プラン実行時間の {{share}}","rows": "行数 {{count}}",+ "time": "時間 {{time}} ms","zoom-in": "拡大","zoom-out": "縮小"},@@ -3531,12 +3536,16 @@"unreadable": "このクエリプランを読み取れませんでした"},"grid": {+ "actual-rows": "実測行数",+ "actual-rows-hint": "この演算子が実際に返した行数(全実行回数の合計)","added-cost": "追加コスト","added-cost-hint": "このノードが子ノードに加えて追加するコストです。一部のエンジンでは、ネストループ配下などで入力の反復実行もここに含めます。バーはプラン全体に占めるこのコストの割合です。","caption": "プランナーが入れ子にする順序で並べたプランノードです。親が子より先に表示されます。","estimated-rows": "推定行数","node": "ノード","rows": "行数",+ "self-time": "自ノード時間",+ "self-time-hint": "このノードが子ノードに加えて要した時間(ミリ秒、全実行回数の合計)です。バーはプラン全体に占めるこの時間の割合です。","total-cost": "総コスト","width": "幅","width-hint": "推定行幅(バイト)"@@ -3548,31 +3557,55 @@"off": "オフ","off-hint": "すべてのノードカードを色付けしない","rows": "行数",- "rows-hint": "推定行数で色付け"+ "rows-hint": "推定行数で色付け",+ "time": "時間",+ "time-hint": "ノードが子ノードに加えて要した時間で色付け"},"legend": {"cost": "各カードのバーは、そのノードがプランの推定コストに占める割合を示します",- "rows": "子ノードが返すと推定される行数に応じてエッジが太くなります"+ "rows": "子ノードが返すと推定される行数に応じてエッジが太くなります",+ "time": "各カードのバーは、そのノードがプランの実測時間に占める割合を示します"},"metric": {+ "actual-rows": "実測行数",+ "actual-time": "実測時間","added-cost": "追加コスト","bytes": "{{count}} バイト","estimated-rows": "推定行数",+ "loops": "実行回数",+ "milliseconds": "{{count}} ms","row-width": "行幅",+ "rows-none": "プランナーは行を見込んでいましたが、1 行も返しませんでした。",+ "rows-over": "プランナーの推定より {{factor}} 倍多い行を返しました。",+ "rows-under": "プランナーの推定の {{factor}} 分の 1 の行しか返しませんでした。","startup-cost": "開始コスト","total-cost": "総コスト"},"summary": {"costliest": "推定コストの高い順",- "no-added-cost": "このプランには固有の推定コストを追加するノードがありません。"+ "no-added-cost": "このプランには固有の推定コストを追加するノードがありません。",+ "no-added-time": "このプランには固有の実測時間があるノードがありません。",+ "no-ranking": "このプランはコストも時間も報告しないため、演算子を順位付けできません。",+ "slowest-measured": "実測時間の長い順",+ "warning-operators": "{{count}} 個の演算子",+ "warnings": "警告"},"tab": {"diagram": "ダイアグラム","grid": "テーブル","text": "テキスト"},+ "table": {+ "heading": "テーブル",+ "indexes": "インデックス",+ "no-indexes": "このテーブルにはインデックスがありません。",+ "primary": "主キー",+ "rows": "前回の同期時点で {{count}} 行",+ "unique": "一意"+ },"totals": {"estimated-cost": "推定コスト {{cost}}",+ "measured-time": "実測時間 {{time}} ms","nodes": "{{count}} ノード"}},diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.jsonindex ed96c02b30..95b63ba584 100644--- a/frontend/src/locales/vi-VN.json+++ b/frontend/src/locales/vi-VN.json@@ -3447,6 +3447,7 @@"expire-in": "Hết hạn sau {{time}}","expired": "Đã hết hạn","explain": "Giải thích",+ "explain-hint": "Hiển thị kế hoạch mà không chạy truy vấn","explore-data": "Khám phá dữ liệu","export-available-via-issue": "Xuất khả dụng qua issue \"{{title}}\"","export-available-via-n-grants": "Xuất khả dụng qua {{count}} cấp quyền truy cập:",@@ -3484,6 +3485,7 @@"open-in-new-tab": "Mở trong tab mới","opened-from-link": "Mở từ liên kết","pending-query": "Đang chờ truy vấn",+ "plan-cost-share": "{{share}} chi phí ước tính của toàn bộ script","plan-estimated": "Ước tính","plan-view": "Kế hoạch","previous-row": "Dòng trước",@@ -3504,6 +3506,7 @@"select-node": "Chọn một nút để xem chi tiết."},"diagram": {+ "actual-rows": "hàng thực tế {{count}}","collapse": "Thu gọn {{count}} nút bên dưới {{node}}","cost": "chi phí {{cost}}","estimated-rows": "{{count}} hàng ước tính",@@ -3511,7 +3514,9 @@"fit": "Vừa với khung nhìn","nodes-hidden": "Đã ẩn {{count}} nút","plan-cost-share": "{{share}} chi phí kế hoạch",+ "plan-time-share": "{{share}} thời gian kế hoạch","rows": "hàng {{count}}",+ "time": "thời gian {{time}} ms","zoom-in": "Phóng to","zoom-out": "Thu nhỏ"},@@ -3531,12 +3536,16 @@"unreadable": "Không thể đọc kế hoạch truy vấn này"},"grid": {+ "actual-rows": "Số hàng thực tế",+ "actual-rows-hint": "Số hàng toán tử thực sự trả về, tính trên tất cả các lần chạy","added-cost": "Chi phí thêm","added-cost-hint": "Chi phí mà nút này thêm ngoài các nút con; một số máy cơ sở dữ liệu cũng tính số lần lặp của đầu vào tại đây, chẳng hạn trong vòng lặp lồng nhau. Thanh thể hiện tỷ lệ chi phí này trong kế hoạch.","caption": "Các nút kế hoạch theo thứ tự lồng nhau của bộ lập kế hoạch, nút cha đứng trước nút con.","estimated-rows": "Số hàng ước tính","node": "Nút","rows": "Hàng",+ "self-time": "Thời gian riêng",+ "self-time-hint": "Số milisecond nút này tiêu tốn ngoài các nút con, tính trên tất cả các lần chạy. Thanh thể hiện tỷ lệ thời gian này trong kế hoạch.","total-cost": "Tổng chi phí","width": "Độ rộng","width-hint": "Độ rộng hàng ước tính theo byte"@@ -3548,31 +3557,55 @@"off": "Tắt","off-hint": "Không tô màu các thẻ nút","rows": "Hàng",- "rows-hint": "Tô màu theo số hàng ước tính"+ "rows-hint": "Tô màu theo số hàng ước tính",+ "time": "Thời gian",+ "time-hint": "Tô màu theo thời gian nút tiêu tốn ngoài các nút con"},"legend": {"cost": "thanh trên mỗi thẻ thể hiện tỷ lệ chi phí ước tính của nút trong kế hoạch",- "rows": "cạnh dày hơn theo số hàng mà nút con dự kiến trả về"+ "rows": "cạnh dày hơn theo số hàng mà nút con dự kiến trả về",+ "time": "thanh trên mỗi thẻ thể hiện tỷ lệ thời gian đo được của nút trong kế hoạch"},"metric": {+ "actual-rows": "Số hàng thực tế",+ "actual-time": "Thời gian thực tế","added-cost": "Chi phí thêm","bytes": "{{count}} byte","estimated-rows": "Số hàng ước tính",+ "loops": "Số lần chạy",+ "milliseconds": "{{count}} ms","row-width": "Độ rộng hàng",+ "rows-none": "Không trả về hàng nào, trong khi bộ lập kế hoạch dự kiến có hàng.",+ "rows-over": "Trả về nhiều hơn {{factor}}× số hàng mà bộ lập kế hoạch ước tính.",+ "rows-under": "Trả về ít hơn {{factor}}× số hàng mà bộ lập kế hoạch ước tính.","startup-cost": "Chi phí khởi động","total-cost": "Tổng chi phí"},"summary": {"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."+ "no-added-cost": "Không có nút nào trong kế hoạch này tự thêm chi phí ước tính.",+ "no-added-time": "Không có nút nào trong kế hoạch này tiêu tốn thời gian riêng đo được.",+ "no-ranking": "Kế hoạch này không báo cáo chi phí hay thời gian, nên không thể xếp hạng các toán tử.",+ "slowest-measured": "Chậm nhất theo thời gian đo được",+ "warning-operators": "{{count}} toán tử",+ "warnings": "Cảnh báo"},"tab": {"diagram": "Sơ đồ","grid": "Bảng","text": "Văn bản"},+ "table": {+ "heading": "Bảng",+ "indexes": "Chỉ mục",+ "no-indexes": "Bảng này không có chỉ mục nào.",+ "primary": "khóa chính",+ "rows": "{{count}} hàng tại lần đồng bộ gần nhất",+ "unique": "duy nhất"+ },"totals": {"estimated-cost": "chi phí ước tính {{cost}}",+ "measured-time": "thời gian đo được {{time}} ms","nodes": "{{count}} nút"}},diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.jsonindex ec6897c1d0..179cb539f1 100644--- a/frontend/src/locales/zh-CN.json+++ b/frontend/src/locales/zh-CN.json@@ -3447,6 +3447,7 @@"expire-in": "{{time}} 后过期","expired": "已过期","explain": "查看执行计划",+ "explain-hint": "显示执行计划,不运行查询","explore-data": "浏览数据","export-available-via-issue": "通过工单 \"{{title}}\" 可导出","export-available-via-n-grants": "通过 {{count}} 个访问授权可导出:",@@ -3484,6 +3485,7 @@"open-in-new-tab": "在新选项卡中打开","opened-from-link": "从链接打开","pending-query": "待处理查询",+ "plan-cost-share": "占整个脚本预计成本的 {{share}}","plan-estimated": "预估","plan-view": "执行计划","previous-row": "上一行",@@ -3504,6 +3506,7 @@"select-node": "选择节点以查看详情。"},"diagram": {+ "actual-rows": "实际行数 {{count}}","collapse": "折叠 {{node}} 下的 {{count}} 个节点","cost": "成本 {{cost}}","estimated-rows": "预计 {{count}} 行",@@ -3511,7 +3514,9 @@"fit": "适应视图","nodes-hidden": "已隐藏 {{count}} 个节点","plan-cost-share": "占计划成本的 {{share}}",+ "plan-time-share": "占计划耗时的 {{share}}","rows": "行数 {{count}}",+ "time": "耗时 {{time}} ms","zoom-in": "放大","zoom-out": "缩小"},@@ -3531,12 +3536,16 @@"unreadable": "无法读取此查询计划"},"grid": {+ "actual-rows": "实际行数",+ "actual-rows-hint": "该算子实际返回的行数,为所有执行次数的合计","added-cost": "新增成本","added-cost-hint": "此节点在其子节点之上增加的成本;某些引擎还会在此计入输入重复执行的成本,例如嵌套循环下的输入。条形图表示该成本占计划总成本的比例。","caption": "按规划器嵌套顺序排列的计划节点,父节点在子节点之前。","estimated-rows": "预计行数","node": "节点","rows": "行数",+ "self-time": "自身耗时",+ "self-time-hint": "该节点在其子节点之上耗费的毫秒数,为所有执行次数的合计。条形图表示该时间占计划总耗时的比例。","total-cost": "总成本","width": "宽度","width-hint": "预计行宽(字节)"@@ -3548,31 +3557,55 @@"off": "关闭","off-hint": "不为任何节点卡片着色","rows": "行数",- "rows-hint": "按预计行数着色"+ "rows-hint": "按预计行数着色",+ "time": "耗时",+ "time-hint": "按节点在其子节点之上耗费的时间着色"},"legend": {"cost": "每张卡片的条形图表示该节点占计划预计成本的比例",- "rows": "边的粗细随其子节点预计返回的行数增加"+ "rows": "边的粗细随其子节点预计返回的行数增加",+ "time": "每张卡片的条形图表示该节点占计划实测耗时的比例"},"metric": {+ "actual-rows": "实际行数",+ "actual-time": "实际耗时","added-cost": "新增成本","bytes": "{{count}} 字节","estimated-rows": "预计行数",+ "loops": "执行次数",+ "milliseconds": "{{count}} ms","row-width": "行宽",+ "rows-none": "未返回任何行,而规划器预计会有行返回。",+ "rows-over": "返回的行数是规划器预计的 {{factor}} 倍。",+ "rows-under": "返回的行数是规划器预计的 {{factor}} 分之一。","startup-cost": "启动成本","total-cost": "总成本"},"summary": {"costliest": "按预估成本最高的操作符",- "no-added-cost": "此计划中没有节点自身增加预计成本。"+ "no-added-cost": "此计划中没有节点自身增加预计成本。",+ "no-added-time": "此计划中没有节点自身耗费可测量的时间。",+ "no-ranking": "此计划未报告成本或耗时,因此无法为其算子排序。",+ "slowest-measured": "按实测耗时最长的操作符",+ "warning-operators": "{{count}} 个算子",+ "warnings": "警告"},"tab": {"diagram": "图表","grid": "表格","text": "文本"},+ "table": {+ "heading": "表",+ "indexes": "索引",+ "no-indexes": "此表没有索引。",+ "primary": "主键",+ "rows": "上次同步时 {{count}} 行",+ "unique": "唯一"+ },"totals": {"estimated-cost": "预计成本 {{cost}}",+ "measured-time": "实测耗时 {{time}} ms","nodes": "{{count}} 个节点"}},diff --git a/frontend/src/modules/sql-editor/components/EditorAction.test.tsx b/frontend/src/modules/sql-editor/components/EditorAction.test.tsxindex d1ba13375e..3cad37076b 100644--- a/frontend/src/modules/sql-editor/components/EditorAction.test.tsx+++ b/frontend/src/modules/sql-editor/components/EditorAction.test.tsx@@ -3,6 +3,7 @@ import { act } from "react";import { createRoot } from "react-dom/client";import { beforeEach, describe, expect, test, vi } from "vitest";import { Engine } from "@/types/proto-es/v1/common_pb";+import { QueryOption_ExplainFormat } from "@/types/proto-es/v1/sql_service_pb";(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }@@ -30,6 +31,7 @@ const mocks = vi.hoisted(() => ({keyboardShortcutStr: vi.fn((s: string) => s),emit: vi.fn(),useProductIntro: vi.fn(),+ canExplain: true,}));vi.mock("react-i18next", () => ({@@ -77,9 +79,18 @@ vi.mock("@/utils", () => ({isSavedQueryWritableV1: mocks.isSavedQueryWritableV1,canCreateSavedQueryInProject: mocks.canCreateSavedQueryInProject,keyboardShortcutStr: mocks.keyboardShortcutStr,+ instanceV1AllowsExplain: (engine: Engine) => engine !== Engine.REDIS,isDev: () => true,}));+vi.mock("@/utils/iam/permission", () => ({+ hasProjectPermissionV2: () => mocks.canExplain,+}));++vi.mock("@/utils/v1/database", () => ({+ getDatabaseProject: () => ({ name: "projects/p1" }),+}));+vi.mock("@/modules/sql-editor/model/events", () => ({sqlEditorEvents: { emit: mocks.emit },}));@@ -149,11 +160,26 @@ vi.mock("./OpenAIButton", () => ({OpenAIButton: () => <div data-testid="openai-button" />,}));vi.mock("./QueryContextSettingPopover", () => ({- QueryContextSettingPopover: ({ disabled }: { disabled?: boolean }) => (+ QueryContextSettingPopover: ({+ disabled,+ explainDisabledReason,+ onExplain,+ }: {+ disabled?: boolean;+ explainDisabledReason?: string;+ onExplain?: () => void;+ }) => (<divdata-testid="query-context-setting-popover"data-disabled={String(disabled)}- />+ data-explain-disabled-reason={explainDisabledReason}+ >+ {onExplain && (+ <button type="button" onClick={onExplain}>+ explain+ </button>+ )}+ </div>),}));vi.mock("./SharePopoverBody", () => ({@@ -249,6 +275,7 @@ beforeEach(async () => {t: (key: string, fallback?: string) => fallback ?? key,});mocks.isSavedQueryWritableV1.mockReturnValue(true);+ mocks.canExplain = true;({ EditorAction } = await import("./EditorAction"));});@@ -285,6 +312,59 @@ describe("EditorAction", () => {unmount();});+ test("Run's dropdown explains what Run would run, in the drawable format", () => {+ setup();+ const onExecute = vi.fn();+ const { container, render, unmount } = renderIntoContainer(+ <EditorAction onExecute={onExecute} />+ );+ render();+ const button = (label: string) =>+ Array.from(container.querySelectorAll("button")).find(+ (el) => el.textContent === label+ );++ act(() => button("explain")?.click());+ expect(onExecute).toHaveBeenLastCalledWith(+ expect.objectContaining({+ statement: "SELECT 1",+ explain: true,+ queryOption: expect.objectContaining({+ explainFormat: QueryOption_ExplainFormat.JSON,+ }),+ })+ );+ unmount();+ });++ test("Run's dropdown says why Explain is off without bb.sql.explain", () => {+ setup();+ mocks.canExplain = false;+ const { container, render, unmount } = renderIntoContainer(+ <EditorAction onExecute={vi.fn()} />+ );+ render();+ expect(+ container+ .querySelector("[data-testid='query-context-setting-popover']")+ ?.getAttribute("data-explain-disabled-reason")+ ).toBe("sql-editor.query-plan-requires-explain");+ unmount();+ });++ test("Run's dropdown leaves Explain out for an engine without one", () => {+ setup({ engine: Engine.REDIS });+ const { container, render, unmount } = renderIntoContainer(+ <EditorAction onExecute={vi.fn()} />+ );+ render();+ const labels = Array.from(container.querySelectorAll("button")).map(+ (el) => el.textContent+ );+ expect(labels).not.toContain("explain");+ unmount();+ });+test("2. Run button is disabled when disconnected OR statement empty", () => {setup({ statement: "" });diff --git a/frontend/src/modules/sql-editor/components/EditorAction.tsx b/frontend/src/modules/sql-editor/components/EditorAction.tsxindex b771b2102c..0549096404 100644--- a/frontend/src/modules/sql-editor/components/EditorAction.tsx+++ b/frontend/src/modules/sql-editor/components/EditorAction.tsx@@ -24,9 +24,13 @@ import type { SQLEditorQueryParams } from "@/types";import { Engine } from "@/types/proto-es/v1/common_pb";import {canCreateSavedQueryInProject,+ instanceV1AllowsExplain,isSavedQueryWritableV1,keyboardShortcutStr,} from "@/utils";+import { hasProjectPermissionV2 } from "@/utils/iam/permission";+import { explainQueryOption } from "@/utils/queryPlanEngines";+import { getDatabaseProject } from "@/utils/v1/database";import { AdminModeButton } from "./AdminModeButton";import { ChooserGroup } from "./ChooserGroup";import { ContainerChooser } from "./ContainerChooser";@@ -49,7 +53,7 @@ type Props = {export function EditorAction({ onExecute }: Props) {const { t } = useTranslation();const { currentSheet: currentSavedQuery } = useSavedQueryAndTab();- const { instance } = useConnectionOfCurrentSQLEditorTab();+ const { instance, database } = useConnectionOfCurrentSQLEditorTab();const [shareOpen, setShareOpen] = useState(false);@@ -130,14 +134,15 @@ export function EditorAction({ onExecute }: Props) {const showQueryContextSettingPopover =!!currentTab && !!instance && !isAdminMode;- const handleRunQuery = () => {+ const runQuery = (explain: boolean) => {if (!currentTab || !onExecute) return;const statement = currentTab.selectedStatement || currentTab.statement;onExecute({statement,connection: { ...currentTab.connection },engine: instance.engine,- explain: false,+ explain,+ ...(explain ? { queryOption: explainQueryOption(instance.engine) } : {}),selection: currentTab.editorState.selection,});};@@ -184,7 +189,20 @@ export function EditorAction({ onExecute }: Props) {disabled={!allowQuery}productIntroTarget={RUN_QUERY_PRODUCT_INTRO}settingsDisabled={!showQueryContextSettingPopover}- onClick={handleRunQuery}+ onClick={() => runQuery(false)}+ onExplain={+ instanceV1AllowsExplain(instance.engine)+ ? () => runQuery(true)+ : undefined+ }+ explainDisabledReason={+ hasProjectPermissionV2(+ getDatabaseProject(database),+ "bb.sql.explain"+ )+ ? undefined+ : t("sql-editor.query-plan-requires-explain")+ }/>))}diff --git a/frontend/src/modules/sql-editor/components/QueryContextSettingPopover.test.tsx b/frontend/src/modules/sql-editor/components/QueryContextSettingPopover.test.tsxindex f7d9461ec6..d8c2a43e91 100644--- a/frontend/src/modules/sql-editor/components/QueryContextSettingPopover.test.tsx+++ b/frontend/src/modules/sql-editor/components/QueryContextSettingPopover.test.tsx@@ -57,6 +57,7 @@ vi.mock("@/modules/sql-editor/store/editor", () => ({vi.mock("@/utils", () => ({getInstanceResource: mocks.getInstanceResource,+ keyboardShortcutStr: (shortcut: string) => shortcut,readableDataSourceType: mocks.readableDataSourceType,}));@@ -274,6 +275,49 @@ describe("QueryContextSettingPopover", () => {unmount();});+ test("offers Explain with its shortcut when given one, and runs it", () => {+ const onExplain = vi.fn();+ const { container, render, unmount } = renderIntoContainer(+ <QueryContextSettingPopover onExplain={onExplain} />+ );+ render();+ const explain = Array.from(container.querySelectorAll("button")).find(+ (el) => el.textContent?.startsWith("sql-editor.explain")+ );+ expect(explain?.textContent).toContain("cmd_or_ctrl+E");++ act(() => explain?.click());+ expect(onExplain).toHaveBeenCalledTimes(1);+ unmount();+ });++ test("leaves Explain out when not given one, and disables it on request", () => {+ const explainButtons = (element: ReactElement) => {+ const { container, render, unmount } = renderIntoContainer(element);+ render();+ const buttons = Array.from(container.querySelectorAll("button")).filter(+ (el) => el.textContent?.startsWith("sql-editor.explain")+ );+ const disabled = buttons.map((el) => el.disabled);+ unmount();+ return disabled;+ };+ expect(explainButtons(<QueryContextSettingPopover />)).toEqual([]);+ expect(+ explainButtons(+ <QueryContextSettingPopover onExplain={vi.fn()} explainDisabled />+ )+ ).toEqual([true]);+ expect(+ explainButtons(+ <QueryContextSettingPopover+ onExplain={vi.fn()}+ explainDisabledReason="needs bb.sql.explain"+ />+ )+ ).toEqual([true]);+ });+test("MaxRowCountSelect renders inside popover content", () => {const { container, render, unmount } = renderIntoContainer(<QueryContextSettingPopover />diff --git a/frontend/src/modules/sql-editor/components/QueryContextSettingPopover.tsx b/frontend/src/modules/sql-editor/components/QueryContextSettingPopover.tsxindex 8d43164971..56f84b9499 100644--- a/frontend/src/modules/sql-editor/components/QueryContextSettingPopover.tsx+++ b/frontend/src/modules/sql-editor/components/QueryContextSettingPopover.tsx@@ -1,6 +1,6 @@import { orderBy } from "lodash-es";import { ChevronDown } from "lucide-react";-import { useMemo } from "react";+import { useMemo, useState } from "react";import { useTranslation } from "react-i18next";import { MaxRowCountSelect } from "@/components/MaxRowCountSelect";import { Button } from "@/components/ui/button";@@ -31,21 +31,35 @@ import {DataSourceType,} from "@/types/proto-es/v1/instance_service_pb";import { QueryOption_RedisRunCommandsOn } from "@/types/proto-es/v1/sql_service_pb";-import { getInstanceResource, readableDataSourceType } from "@/utils";+import {+ getInstanceResource,+ keyboardShortcutStr,+ readableDataSourceType,+} from "@/utils";type Props = {readonly disabled?: boolean;readonly size?: "sm" | "md";+ readonly explainDisabled?: boolean;+ /** Why the user cannot explain here; disables Explain and says so. */+ readonly explainDisabledReason?: string;+ /** Plans what Run would run, without running it. */+ readonly onExplain?: () => void;};/**- * Popover for selecting query data source, Redis command mode, and max row count.+ * Run's dropdown: Explain, then the query data source, Redis command mode, and+ * max row count.*/export function QueryContextSettingPopover({disabled = false,size = "sm",+ explainDisabled = false,+ explainDisabledReason,+ onExplain,}: Props) {const { t } = useTranslation();+ const [open, setOpen] = useState(false);const { database, connection: connectionRef } =useConnectionOfCurrentSQLEditorTab();const project = useSQLEditorEditorState((s) => s.project);@@ -117,7 +131,7 @@ export function QueryContextSettingPopover({if (!show) return null;return (- <Popover>+ <Popover open={open} onOpenChange={setOpen}><PopoverTriggerrender={<Button@@ -135,8 +149,32 @@ export function QueryContextSettingPopover({</PopoverTrigger><PopoverContent side="bottom" align="end"><div className="flex flex-col gap-1">+ {onExplain && (+ <Tooltip+ content={explainDisabledReason ?? t("sql-editor.explain-hint")}+ side="right"+ render={<div className="-mx-2 flex" />}+ >+ <Button+ appearance="secondary"+ size="md"+ className="flex-1 justify-between gap-4 font-normal"+ disabled={explainDisabled || !!explainDisabledReason}+ onClick={() => {+ setOpen(false);+ onExplain();+ }}+ >+ <span>{t("sql-editor.explain")}</span>+ <span className="text-xs text-control-light">+ {keyboardShortcutStr("cmd_or_ctrl+E")}+ </span>+ </Button>+ </Tooltip>+ )}+{/* Data source radio group */}- <div>+ <div className={cn(onExplain && "border-t pt-1")}><p className="mb-1 textinfolabel">{t("data-source.select-query-data-source")}</p>diff --git a/frontend/src/modules/sql-editor/components/ResultView/QueryPlanResultView.tsx b/frontend/src/modules/sql-editor/components/ResultView/QueryPlanResultView.tsxindex 70805de549..fea0788247 100644--- a/frontend/src/modules/sql-editor/components/ResultView/QueryPlanResultView.tsx+++ b/frontend/src/modules/sql-editor/components/ResultView/QueryPlanResultView.tsx@@ -2,6 +2,7 @@ import { LoaderCircle } from "lucide-react";import { useCallback, useEffect, useMemo, useRef, useState } from "react";import { useTranslation } from "react-i18next";import type { QueryPlanTranslate } from "@/apps/explain-visualizer/plan-i18n";+import type { PlanTableLookup } from "@/apps/explain-visualizer/plan-model";import { QueryPlanView } from "@/apps/explain-visualizer/QueryPlanView";import { formatPlanSource } from "@/apps/explain-visualizer/QueryPlanViewer";import { Alert } from "@/components/ui/alert";@@ -28,6 +29,7 @@ interface Props {// The plan was made on demand for a result that already ran, so it is an// estimate of now, not a record of that run.estimated?: boolean;+ describeTable?: PlanTableLookup;onCancel?: () => void;disallowCopyingData?: boolean;}@@ -71,6 +73,7 @@ export function QueryPlanResultView({engine,loadPlan,estimated = false,+ describeTable,onCancel,disallowCopyingData = false,}: Props) {@@ -146,6 +149,7 @@ export function QueryPlanResultView({planSource={plan.source}textPlanSource={rawPlan || undefined}note={estimateNote}+ describeTable={describeTable}translate={translatePlan}disallowCopyingData={disallowCopyingData}/>diff --git a/frontend/src/modules/sql-editor/components/ResultView/ResultView.test.tsx b/frontend/src/modules/sql-editor/components/ResultView/ResultView.test.tsxindex 7e752f7fa1..46f8f4f229 100644--- a/frontend/src/modules/sql-editor/components/ResultView/ResultView.test.tsx+++ b/frontend/src/modules/sql-editor/components/ResultView/ResultView.test.tsx@@ -4,7 +4,12 @@ import { beforeEach, describe, expect, test, vi } from "vitest";import type { SQLEditorQueryParams } from "@/types";import { Engine, ExportFormat } from "@/types/proto-es/v1/common_pb";import type { Database } from "@/types/proto-es/v1/database_service_pb";-import { QueryResultSchema } from "@/types/proto-es/v1/sql_service_pb";+import {+ QueryResult_QueryPlanSchema,+ QueryResultSchema,+ QueryRowSchema,+ RowValueSchema,+} from "@/types/proto-es/v1/sql_service_pb";import { ResultView } from "./ResultView";const { exportData } = vi.hoisted(() => ({@@ -85,6 +90,7 @@ vi.mock("@/utils/iam/permission", () => ({vi.mock("@/utils/v1/database", () => ({extractDatabaseResourceName: () => ({ databaseName: "main" }),getDatabaseProject: () => "projects/prod",+ getInstanceResource: () => ({ engine: Engine.POSTGRES }),}));vi.mock("./EmptyView", () => ({@@ -175,4 +181,59 @@ describe("ResultView", () => {);});});++ /** A PostgreSQL plan result whose root costs `totalCost`. */+ const planResult = (totalCost: number) =>+ create(QueryResultSchema, {+ statement: "SELECT 1",+ columnNames: ["QUERY PLAN"],+ queryPlan: create(QueryResult_QueryPlanSchema, {}),+ rows: [+ create(QueryRowSchema, {+ values: [+ create(RowValueSchema, {+ kind: {+ case: "stringValue",+ value: JSON.stringify([+ { Plan: { "Node Type": "Seq Scan", "Total Cost": totalCost } },+ ]),+ },+ }),+ ],+ }),+ ],+ });++ const tabs = () => screen.getAllByRole("tab").map((tab) => tab.textContent);++ test("says which of several plans is the one to read", () => {+ render(+ <ResultView+ executeParams={executeParams}+ database={database}+ resultSet={{ error: "", results: [planResult(90), planResult(10)] }}+ />+ );++ expect(tabs()[0]).toContain("90%");+ expect(tabs()[1]).toContain("10%");+ });++ test("leaves the tabs alone when the script's whole cost is unknown", () => {+ render(+ <ResultView+ executeParams={executeParams}+ database={database}+ resultSet={{+ error: "",+ results: [+ planResult(90),+ create(QueryResultSchema, { statement: "SELECT 2" }),+ ],+ }}+ />+ );++ expect(tabs().join()).not.toContain("%");+ });});diff --git a/frontend/src/modules/sql-editor/components/ResultView/ResultView.tsx b/frontend/src/modules/sql-editor/components/ResultView/ResultView.tsxindex df0b8b8697..e0baf92b2e 100644--- a/frontend/src/modules/sql-editor/components/ResultView/ResultView.tsx+++ b/frontend/src/modules/sql-editor/components/ResultView/ResultView.tsx@@ -4,6 +4,7 @@ import dayjs from "dayjs";import { InfoIcon, LoaderCircle } from "lucide-react";import { type ReactNode, useEffect, useMemo, useState } from "react";import { useTranslation } from "react-i18next";+import { formatPlanShare } from "@/apps/explain-visualizer/plan-model";import {DataExportButton,type DataExportRequest,@@ -33,10 +34,12 @@ import { hasProjectPermissionV2 } from "@/utils/iam/permission";import {extractDatabaseResourceName,getDatabaseProject,+ getInstanceResource,} from "@/utils/v1/database";import { ExportGrantLookupStatus } from "../ExportGrantLookupStatus";import { EmptyView } from "./EmptyView";import { ErrorView } from "./ErrorView";+import { planCostShares } from "./resultPlans";import { SingleResultView } from "./SingleResultView";import type { ResultViewPresentation } from "./types";@@ -180,6 +183,13 @@ export function ResultView({const tabName = (index: number) => `${t("common.query")} #${index + 1}`;+ // Which of several plans is the one to read. Only a run that planned every+ // statement knows the whole script's cost, so most runs show no share.+ const costShares = useMemo(+ () => planCostShares(filteredResults, getInstanceResource(database).engine),+ [filteredResults, database]+ );+const supportFormats = useMemo(() => [ExportFormat.CSV,@@ -287,22 +297,43 @@ export function ResultView({><div className="flex items-center justify-between gap-x-2"><TabsList>- {filteredResults.map((result, i) => (- <Tooltip- key={i}- content={result.statement}- popupClassName="ph-no-capture"- >- <TabsTrigger value={tabName(i)}>- <div className="flex items-center gap-x-2 mb-1">- <span>{tabName(i)}</span>- {result.error && (- <InfoIcon className="size-4 text-warning" />- )}- </div>- </TabsTrigger>- </Tooltip>- ))}+ {filteredResults.map((result, i) => {+ const share = costShares?.[i];+ return (+ <Tooltip+ key={i}+ content={+ share === undefined ? (+ result.statement+ ) : (+ <span className="flex flex-col gap-1">+ <span>+ {t("sql-editor.plan-cost-share", {+ share: formatPlanShare(share),+ })}+ </span>+ <span>{result.statement}</span>+ </span>+ )+ }+ popupClassName="ph-no-capture"+ >+ <TabsTrigger value={tabName(i)}>+ <div className="flex items-center gap-x-2 mb-1">+ <span>{tabName(i)}</span>+ {share === undefined ? null : (+ <span className="text-xs text-control-light tabular-nums">+ {formatPlanShare(share)}+ </span>+ )}+ {result.error && (+ <InfoIcon className="size-4 text-warning" />+ )}+ </div>+ </TabsTrigger>+ </Tooltip>+ );+ })}</TabsList>{showExport ? (<div className="mb-1">diff --git a/frontend/src/modules/sql-editor/components/ResultView/SingleResultView.test.tsx b/frontend/src/modules/sql-editor/components/ResultView/SingleResultView.test.tsxindex d330f6ecf3..62db6d300d 100644--- a/frontend/src/modules/sql-editor/components/ResultView/SingleResultView.test.tsx+++ b/frontend/src/modules/sql-editor/components/ResultView/SingleResultView.test.tsx@@ -218,19 +218,34 @@ vi.mock("@/utils/v1/instance", () => ({engine === Engine.POSTGRES || engine === Engine.MYSQL,}));-vi.mock("@/stores/app", () => ({- useAppStore: {- getState: () => ({}),- },-}));+vi.mock("@/stores/app", () => {+ // Zustand's hook is called with a selector and also carries getState. The+ // plan view reads the database's synced metadata through it; an empty+ // catalog is what a test that has not set one up should see.+ const state = {+ getDatabaseMetadata: () => ({ schemas: [] }),+ getOrFetchDatabaseMetadata: async () => undefined,+ metadataByName: {},+ };+ const useAppStore = (selector?: (s: typeof state) => unknown) =>+ selector ? selector(state) : state;+ useAppStore.getState = () => state;+ return { useAppStore };+});vi.mock("@/utils/util", () => ({isNullOrUndefined: (value: unknown) => value === null || value === undefined,+ // Reached through the app store, which the plan view reads the database's+ // synced metadata from.+ isDev: () => false,}));vi.mock("@/utils/v1/database", () => ({getDatabaseProject: (database: Database) => ({ name: database.project }),getInstanceResource: (database: Database) => database.instanceResource,+ extractDatabaseResourceName: (name: string) => ({+ databaseName: name.split("/").pop() ?? "",+ }),}));vi.mock("@/utils/v1/sql", () => ({diff --git a/frontend/src/modules/sql-editor/components/ResultView/SingleResultView.tsx b/frontend/src/modules/sql-editor/components/ResultView/SingleResultView.tsxindex a77e2611e8..5421a2f485 100644--- a/frontend/src/modules/sql-editor/components/ResultView/SingleResultView.tsx+++ b/frontend/src/modules/sql-editor/components/ResultView/SingleResultView.tsx@@ -35,6 +35,7 @@ import {} from "@/components/ui/segmented-control";import { Switch } from "@/components/ui/switch";import { Tooltip } from "@/components/ui/tooltip";+import { useAppDatabaseMetadata } from "@/hooks/useAppDatabaseMetadata";import { useExecuteSQL } from "@/hooks/useExecuteSQL";import { writeTextToClipboard } from "@/lib/clipboard";import { cn } from "@/lib/utils";@@ -65,7 +66,11 @@ import {isNoSQLQueryResult,} from "@/utils/sqlResult";import { STORAGE_KEY_SQL_EDITOR_NOSQL_TABLE_VIEW } from "@/utils/storage-keys";-import { getDatabaseProject, getInstanceResource } from "@/utils/v1/database";+import {+ extractDatabaseResourceName,+ getDatabaseProject,+ getInstanceResource,+} from "@/utils/v1/database";import { instanceV1AllowsExplain } from "@/utils/v1/instance";import { compareQueryRowValues, extractSQLRowValuePlain } from "@/utils/v1/sql";import { CopyAllButton } from "./CopyAllButton";@@ -76,11 +81,13 @@ import { DocumentJSONView } from "./DocumentJSONView";import { EmptyView } from "./EmptyView";import { ErrorView } from "./ErrorView";import { canReplayStatement, planAvailability } from "./planAvailability";+import { tableFactsLookup } from "./planTableFacts";import {type InlineQueryPlan,QueryPlanResultView,} from "./QueryPlanResultView";import { formatQueryTime, ResultStatusBar } from "./ResultStatusBar";+import { inlineQueryPlan } from "./resultPlans";import { SelectionCopyTooltips } from "./SelectionCopyTooltips";import { TextSearchControl } from "./TextSearchControl";import type {@@ -502,12 +509,27 @@ function SingleResultViewInner({[flattenedTableView, result.masked]);+ // The editor's panels already fetch this database's metadata, so the plan+ // reads that cache rather than asking for it again; without it a node simply+ // says nothing about its table.+ const databaseMetadata = useAppDatabaseMetadata(database.name, {+ autoFetch: false,+ });+ const describeTable = useMemo(+ () =>+ tableFactsLookup(+ databaseMetadata,+ extractDatabaseResourceName(database.name).databaseName+ ),+ [databaseMetadata, database.name]+ );+const plan = result.queryPlan;const planInRows =isVisualizerEngine(engine) &&plan?.format ===QueryOption_ExplainFormat[VISUALIZER_EXPLAIN_FORMATS[engine]];- const planInResult = useMemo(() => getInlineQueryPlan(result), [result]);+ const planInResult = useMemo(() => inlineQueryPlan(result), [result]);const canReplay =isVisualizerEngine(engine) &&plan?.format === QueryOption_ExplainFormat.TEXT &&@@ -611,6 +633,7 @@ function SingleResultViewInner({rawPlan={planInResult?.source ?? ""}initialPlan={planInRows ? planInResult : undefined}engine={isVisualizerEngine(engine) ? engine : undefined}+ describeTable={describeTable}loadPlan={canReplay ? loadPlan : undefined}disallowCopyingData={disallowCopyingData}/>@@ -787,6 +810,7 @@ function SingleResultViewInner({rawPlan=""initialPlan={resultPlan}engine={isVisualizerEngine(engine) ? engine : undefined}+ describeTable={describeTable}loadPlan={loadResultPlan}estimatedonCancel={() => setLayout("TABLE")}@@ -986,19 +1010,6 @@ function DatabaseInfo({ database }: { database: Database }) {);}-function getInlineQueryPlan(result: QueryResult): InlineQueryPlan | undefined {- const lines = result.rows.map((row) =>- row.values.map((value) => String(extractSQLRowValuePlain(value)))- );- // Multi-column plans keep every column, tab-separated under a header.- const source =- result.columnNames.length > 1- ? [result.columnNames, ...lines].map((line) => line.join("\t")).join("\n")- : lines.map((line) => line[0]).join("\n");- if (!source) return undefined;- 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.@@ -1031,5 +1042,5 @@ async function explainStatement(const result = resultSet?.results[0];if (!result) return undefined;if (result.error) throw new Error(result.error);- return getInlineQueryPlan(result);+ return inlineQueryPlan(result);}diff --git a/frontend/src/modules/sql-editor/components/ResultView/planTableFacts.test.ts b/frontend/src/modules/sql-editor/components/ResultView/planTableFacts.test.tsnew file mode 100644index 0000000000..993869d434--- /dev/null+++ b/frontend/src/modules/sql-editor/components/ResultView/planTableFacts.test.ts@@ -0,0 +1,137 @@+import { create } from "@bufbuild/protobuf";+import { describe, expect, test } from "vitest";+import {+ DatabaseMetadataSchema,+ IndexMetadataSchema,+ SchemaMetadataSchema,+ TableMetadataSchema,+} from "@/types/proto-es/v1/database_service_pb";+import { tableFactsLookup } from "./planTableFacts";++const index = (name: string, expressions: string[], flags = {}) =>+ create(IndexMetadataSchema, { name, expressions, ...flags });++const table = (+ name: string,+ rowCount: bigint,+ indexes = [index("salary_pkey", ["emp_no", "from_date"], { primary: true })]+) => create(TableMetadataSchema, { name, rowCount, indexes });++const metadata = (+ schemas: { name: string; tables: ReturnType<typeof table>[] }[]+) =>+ create(DatabaseMetadataSchema, {+ schemas: schemas.map((schema) =>+ create(SchemaMetadataSchema, { name: schema.name, tables: schema.tables })+ ),+ });++const oneSchema = () =>+ metadata([{ name: "public", tables: [table("salary", 9488n)] }]);++/** The lookup as the result pane builds it, for the connected database. */+const lookup = (data = oneSchema(), connected = "hr_test") =>+ tableFactsLookup(data, connected);++describe("tableFactsLookup", () => {+ test("answers with the table's size and its indexes", () => {+ expect(lookup()({ table: "salary" })).toEqual({+ rowCount: 9488,+ indexes: [+ {+ name: "salary_pkey",+ columns: "emp_no, from_date",+ primary: true,+ unique: false,+ },+ ],+ });+ });++ test("answers for a table with no indexes, which is the point", () => {+ const facts = lookup(+ metadata([{ name: "public", tables: [table("salary", 100n, [])] }])+ )({ table: "salary" });++ expect(facts).toEqual({ rowCount: 100, indexes: [] });+ });++ test("leaves out a row count nothing has counted", () => {+ expect(+ lookup(metadata([{ name: "public", tables: [table("salary", 0n, [])] }]))(+ {+ table: "salary",+ }+ )?.rowCount+ ).toBeUndefined();+ });++ test("says nothing about a relation it does not have", () => {+ expect(lookup()({ table: "orders" })).toBeUndefined();+ expect(lookup()({ table: "" })).toBeUndefined();+ });++ test("says nothing when two schemas both have that name", () => {+ // A plan that names no schema and a name both schemas use: the wrong+ // table's indexes would be worse than none.+ const ambiguous = metadata([+ { name: "public", tables: [table("salary", 9488n)] },+ { name: "archive", tables: [table("salary", 12n)] },+ ]);++ expect(lookup(ambiguous)({ table: "salary" })).toBeUndefined();+ });++ test("picks the schema the plan named, where it named one", () => {+ const ambiguous = metadata([+ { name: "public", tables: [table("salary", 9488n)] },+ { name: "archive", tables: [table("salary", 12n)] },+ ]);++ expect(+ lookup(ambiguous)({ table: "salary", schema: "archive" })?.rowCount+ ).toBe(12);+ expect(+ lookup(ambiguous)({ table: "salary", schema: "DBO" })+ ).toBeUndefined();+ });++ test("says nothing about a table in another database", () => {+ // SQL Server writes the database on every object it reads, so a plan for+ // `archive.dbo.salary` must not be answered from hr_test's catalog, where+ // an unrelated `salary` happens to live.+ expect(+ lookup()({ table: "salary", database: "archive", schema: "public" })+ ).toBeUndefined();+ });++ test("still answers for the connected database, whatever its case", () => {+ expect(lookup()({ table: "salary", database: "HR_TEST" })?.rowCount).toBe(+ 9488+ );+ });++ test("carries a unique index as unique, not as primary", () => {+ const facts = lookup(+ metadata([+ {+ name: "public",+ tables: [+ table("salary", 5n, [+ index("salary_amount_key", ["amount"], { unique: true }),+ ]),+ ],+ },+ ])+ )({ table: "salary" });++ expect(facts?.indexes).toEqual([+ {+ name: "salary_amount_key",+ columns: "amount",+ unique: true,+ primary: false,+ },+ ]);+ });+});diff --git a/frontend/src/modules/sql-editor/components/ResultView/planTableFacts.ts b/frontend/src/modules/sql-editor/components/ResultView/planTableFacts.tsnew file mode 100644index 0000000000..af5465ecee--- /dev/null+++ b/frontend/src/modules/sql-editor/components/ResultView/planTableFacts.ts@@ -0,0 +1,60 @@+import type {+ PlanTableFacts,+ PlanTableIndex,+ PlanTableLookup,+} from "@/apps/explain-visualizer/plan-model";+import type {+ DatabaseMetadata,+ IndexMetadata,+ SchemaMetadata,+ TableMetadata,+} from "@/types/proto-es/v1/database_service_pb";++const toIndex = (index: IndexMetadata): PlanTableIndex => ({+ name: index.name,+ columns: index.expressions.join(", "),+ unique: index.unique,+ primary: index.primary,+});++const toFacts = (table: TableMetadata): PlanTableFacts => ({+ // A table nothing has counted reports zero, which is not a count of zero.+ rowCount: table.rowCount > 0n ? Number(table.rowCount) : undefined,+ indexes: table.indexes.map(toIndex),+});++/** Engines differ on identifier case, and a qualifier is not worth a mismatch. */+const sameIdentifier = (a: string, b: string) =>+ a.localeCompare(b, undefined, { sensitivity: "accent" }) === 0;++/**+ * What Bytebase's own metadata says about a table a plan node reads.+ *+ * The metadata is the connected database's alone, so a plan that names another+ * database — SQL Server writes the database on every object it reads, and a+ * query can cross databases — is left unanswered. Answering it from here would+ * describe a different table that happens to share a name, and the wrong+ * table's indexes are worse than none.+ *+ * The same holds within a database: a plan that names no schema and a name two+ * schemas both use is left unanswered. The metadata is the last sync's, which+ * is what the rest of the editor shows too.+ */+export function tableFactsLookup(+ metadata: DatabaseMetadata,+ connectedDatabase: string+): PlanTableLookup {+ return ({ table, schema, database }) => {+ if (!table) return undefined;+ if (database && !sameIdentifier(database, connectedDatabase)) {+ return undefined;+ }+ const schemas: SchemaMetadata[] = schema+ ? metadata.schemas.filter((entry) => sameIdentifier(entry.name, schema))+ : metadata.schemas;+ const matches = schemas.flatMap((entry) =>+ entry.tables.filter((entry) => entry.name === table)+ );+ return matches.length === 1 ? toFacts(matches[0]) : undefined;+ };+}diff --git a/frontend/src/modules/sql-editor/components/ResultView/resultPlans.test.ts b/frontend/src/modules/sql-editor/components/ResultView/resultPlans.test.tsnew file mode 100644index 0000000000..bf182111a7--- /dev/null+++ b/frontend/src/modules/sql-editor/components/ResultView/resultPlans.test.ts@@ -0,0 +1,89 @@+import { create } from "@bufbuild/protobuf";+import { describe, expect, test } from "vitest";+import { Engine } from "@/types/proto-es/v1/common_pb";+import {+ QueryResult_QueryPlanSchema,+ QueryResultSchema,+ QueryRowSchema,+ RowValueSchema,+} from "@/types/proto-es/v1/sql_service_pb";+import { inlineQueryPlan, planCostShares } from "./resultPlans";++/** A result holding one column of text, the way an explain comes back. */+const textResult = (lines: string[], columnNames = ["QUERY PLAN"]) =>+ create(QueryResultSchema, {+ statement: "SELECT 1",+ columnNames,+ rows: lines.map((line) =>+ create(QueryRowSchema, {+ values: [+ create(RowValueSchema, {+ kind: { case: "stringValue", value: line },+ }),+ ],+ })+ ),+ });++/** A PostgreSQL plan result whose root costs `totalCost`. */+const planResult = (totalCost: number) => {+ const result = textResult([+ JSON.stringify([+ { Plan: { "Node Type": "Seq Scan", "Total Cost": totalCost } },+ ]),+ ]);+ result.queryPlan = create(QueryResult_QueryPlanSchema, {});+ return result;+};++describe("inlineQueryPlan", () => {+ test("joins a single-column plan into its source text", () => {+ expect(+ inlineQueryPlan(textResult(["Seq Scan on t", " Filter: (a = 1)"]))+ ?.source+ ).toBe("Seq Scan on t\n Filter: (a = 1)");+ });++ test("is undefined for a result with no rows to read", () => {+ expect(inlineQueryPlan(textResult([]))).toBeUndefined();+ });+});++describe("planCostShares", () => {+ test("gives each statement its share of the script's cost", () => {+ expect(+ planCostShares([planResult(75), planResult(25)], Engine.POSTGRES)+ ).toEqual([0.75, 0.25]);+ });++ test("withholds every share when one statement is not a plan", () => {+ expect(+ planCostShares(+ [planResult(75), textResult(["a"], ["a"])],+ Engine.POSTGRES+ )+ ).toBeUndefined();+ });++ test("withholds every share when a plan cannot be read", () => {+ const unreadable = textResult(["Seq Scan on t"]);+ unreadable.queryPlan = create(QueryResult_QueryPlanSchema, {});++ expect(+ planCostShares([planResult(75), unreadable], Engine.POSTGRES)+ ).toBeUndefined();+ });++ test("invents no order for a script the planner costs at nothing", () => {+ expect(+ planCostShares([planResult(0), planResult(0)], Engine.POSTGRES)+ ).toBeUndefined();+ });++ test("has nothing to say about an engine whose plans it cannot read", () => {+ expect(+ planCostShares([planResult(75), planResult(25)], Engine.MYSQL)+ ).toBeUndefined();+ expect(planCostShares([], Engine.POSTGRES)).toBeUndefined();+ });+});diff --git a/frontend/src/modules/sql-editor/components/ResultView/resultPlans.ts b/frontend/src/modules/sql-editor/components/ResultView/resultPlans.tsnew file mode 100644index 0000000000..f7d5b0c45a--- /dev/null+++ b/frontend/src/modules/sql-editor/components/ResultView/resultPlans.ts@@ -0,0 +1,53 @@+import { parsePlan } from "@/apps/explain-visualizer/plan-parsers";+import type { Engine } from "@/types/proto-es/v1/common_pb";+import type { QueryResult } from "@/types/proto-es/v1/sql_service_pb";+import { isVisualizerEngine } from "@/utils/queryPlanEngines";+import { extractSQLRowValuePlain } from "@/utils/v1/sql";+import type { InlineQueryPlan } from "./QueryPlanResultView";++/** The plan a result carries in its rows, or undefined when it has none. */+export function inlineQueryPlan(+ result: QueryResult+): InlineQueryPlan | undefined {+ const lines = result.rows.map((row) =>+ row.values.map((value) => String(extractSQLRowValuePlain(value)))+ );+ // Multi-column plans keep every column, tab-separated under a header.+ const source =+ result.columnNames.length > 1+ ? [result.columnNames, ...lines].map((line) => line.join("\t")).join("\n")+ : lines.map((line) => line[0]).join("\n");+ if (!source) return undefined;+ return { source };+}++/**+ * Each result's statement as a share of the whole script's estimated cost,+ * which says which of several plans is the one to read — the signal SSMS puts+ * on a plan tab.+ *+ * Undefined unless every result is a plan this engine's parser reads and every+ * one of them states a cost: a share of an incomplete total is worse than no+ * share. In practice that means a run of the Explain action, which plans every+ * statement at once; plans fetched one tab at a time never complete the total.+ */+export function planCostShares(+ results: readonly QueryResult[],+ engine: Engine+): number[] | undefined {+ if (!isVisualizerEngine(engine) || results.length === 0) return undefined;+ const costs: number[] = [];+ for (const result of results) {+ if (!result.queryPlan) return undefined;+ const source = inlineQueryPlan(result)?.source;+ if (!source) return undefined;+ const parsed = parsePlan(engine, source);+ if (!parsed.ok) return undefined;+ const cost = parsed.tree.root.totalCost;+ if (cost === undefined) return undefined;+ costs.push(cost);+ }+ const total = costs.reduce((sum, cost) => sum + cost, 0);+ if (total <= 0) return undefined;+ return costs.map((cost) => cost / total);+}diff --git a/frontend/src/modules/sql-editor/components/RunQueryButton.tsx b/frontend/src/modules/sql-editor/components/RunQueryButton.tsxindex ee9a327757..d9903a6730 100644--- a/frontend/src/modules/sql-editor/components/RunQueryButton.tsx+++ b/frontend/src/modules/sql-editor/components/RunQueryButton.tsx@@ -13,6 +13,8 @@ type Props = {readonly size?: "sm" | "md";readonly type?: ComponentProps<typeof Button>["type"];readonly onClick?: ComponentProps<typeof Button>["onClick"];+ readonly onExplain?: () => void;+ readonly explainDisabledReason?: string;};export function RunQueryButton({@@ -22,6 +24,8 @@ export function RunQueryButton({size = "sm",type = "button",onClick,+ onExplain,+ explainDisabledReason,}: Props) {const resultRowsLimit = useSQLEditorEditorState((s) => s.resultRowsLimit);@@ -46,7 +50,13 @@ export function RunQueryButton({</span></Button></Tooltip>- <QueryContextSettingPopover disabled={settingsDisabled} size={size} />+ <QueryContextSettingPopover+ disabled={settingsDisabled}+ size={size}+ explainDisabled={disabled}+ onExplain={onExplain}+ explainDisabledReason={explainDisabledReason}+ /></div>);}