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): show query plans inline (#21493)
Danny Xu36b9f26ec4f6
diff --git a/frontend/scripts/check-i18n.mjs b/frontend/scripts/check-i18n.mjsindex 2e1dd67f85..97bf417884 100644--- a/frontend/scripts/check-i18n.mjs+++ b/frontend/scripts/check-i18n.mjs@@ -32,6 +32,7 @@ const DYNAMIC_PREFIXES = ["sql-review.level.","sql-review.rule.","sql-review.template.",+ "sql-editor.query-plan-viewer.","subscription.plan.","subscription.purchase.cancel-dialog.reason.","settings.sensitive-data.algorithms.",diff --git a/frontend/src/apps/explain-visualizer/ExplainVisualizerApp.tsx b/frontend/src/apps/explain-visualizer/ExplainVisualizerApp.tsxindex b62734d0e2..e0af74636a 100644--- a/frontend/src/apps/explain-visualizer/ExplainVisualizerApp.tsx+++ b/frontend/src/apps/explain-visualizer/ExplainVisualizerApp.tsx@@ -1,64 +1,13 @@import { parse } from "qs";import { useMemo } from "react";import { Alert } from "@/components/ui/alert";-import { Engine } from "@/types/proto-es/v1/common_pb";-import {- isVisualizerEngine,- readExplainFromToken,- type VisualizerEngine,-} from "@/utils/explainToken";-import { parseMssqlPlan } from "./mssql-plan";-import type { PlanParseResult } from "./plan-model";-import { parsePostgresPlan } from "./postgres-plan";-import { QueryPlanViewer } from "./QueryPlanViewer";-import { parseSpannerPlan } from "./spanner-plan";--const PARSERS: Record<VisualizerEngine, (source: string) => PlanParseResult> = {- [Engine.POSTGRES]: parsePostgresPlan,- [Engine.MSSQL]: parseMssqlPlan,- [Engine.SPANNER]: parseSpannerPlan,-};+import { isVisualizerEngine, readExplainFromToken } from "@/utils/explainToken";+import { QueryPlanView } from "./QueryPlanView";const STATUS_CLASS ="flex h-full min-h-0 w-full flex-col gap-4 overflow-auto bg-background p-4";-function PlanView({- parsePlan,- planSource,- planQuery,-}: {- parsePlan: (source: string) => PlanParseResult;- planSource: string;- planQuery?: string;-}) {- const result = useMemo(() => parsePlan(planSource), [parsePlan, planSource]);-- if (!result.ok) {- return (- <div className={STATUS_CLASS}>- <Alert- variant="error"- title="This query plan could not be read"- description={result.message}- />- {planSource.trim() ? (- <pre className="font-mono text-xs leading-4 break-words whitespace-pre-wrap text-control">- {planSource}- </pre>- ) : null}- </div>- );- }-- return (- <QueryPlanViewer- tree={result.tree}- rawPlan={planSource}- query={planQuery}- />- );-}-+// Legacy standalone entry; the SQL Editor renders QueryPlanView inline.export function ExplainVisualizerApp() {const storedQuery = useMemo(() => {const query = location.search.replace(/^\?/, "");@@ -91,8 +40,8 @@ export function ExplainVisualizerApp() {}return (- <PlanView- parsePlan={PARSERS[storedQuery.engine]}+ <QueryPlanView+ engine={storedQuery.engine}planSource={storedQuery.explain}planQuery={storedQuery.statement}/>diff --git a/frontend/src/apps/explain-visualizer/PlanCopyButton.tsx b/frontend/src/apps/explain-visualizer/PlanCopyButton.tsxindex efc8837140..22b883f01a 100644--- a/frontend/src/apps/explain-visualizer/PlanCopyButton.tsx+++ b/frontend/src/apps/explain-visualizer/PlanCopyButton.tsx@@ -3,6 +3,7 @@ import { useCallback, useEffect, useRef, useState } from "react";import { Button } from "@/components/ui/button";import { writeTextToClipboard } from "@/lib/clipboard";import { cn } from "@/lib/utils";+import { useQueryPlanTranslation } from "./plan-i18n";/*** A copy control that reports the result on itself.@@ -24,12 +25,8 @@ const CONFIRMATION_MS = 2000;type CopyState = "idle" | "copied" | "failed";-const MESSAGE: Record<Exclude<CopyState, "idle">, string> = {- copied: "Copied",- failed: "Copy failed",-};-export function PlanCopyButton({ content, label, disabled }: Props) {+ const translate = useQueryPlanTranslation();const [state, setState] = useState<CopyState>("idle");const timerRef = useRef<ReturnType<typeof setTimeout>>(undefined);@@ -42,7 +39,10 @@ export function PlanCopyButton({ content, label, disabled }: Props) {timerRef.current = setTimeout(() => setState("idle"), CONFIRMATION_MS);}, [content]);- const outcome = state === "idle" ? undefined : MESSAGE[state];+ const outcome =+ state === "idle"+ ? undefined+ : translate(state === "copied" ? "copy.copied" : "copy.failed");return (<span className="inline-flex items-center">diff --git a/frontend/src/apps/explain-visualizer/QueryPlanDiagram.tsx b/frontend/src/apps/explain-visualizer/QueryPlanDiagram.tsxindex 3f4dda02a6..bd193aee92 100644--- a/frontend/src/apps/explain-visualizer/QueryPlanDiagram.tsx+++ b/frontend/src/apps/explain-visualizer/QueryPlanDiagram.tsx@@ -21,6 +21,7 @@ import { cn } from "@/lib/utils";// standalone entry never loads. `minmax` itself is a leaf math helper.import { minmax } from "@/utils/math";import { PLAN_MINI_MAP_BOX, PlanMiniMap } from "./PlanMiniMap";+import { type QueryPlanTranslate, useQueryPlanTranslation } from "./plan-i18n";import {layoutPlan,PLAN_IDENTITY_VIEWPORT,@@ -98,10 +99,18 @@ const HIGHLIGHT_CLASS: Record<Exclude<PlanHighlightMode, "off">, string> = {};/** The estimates a card prints, leaving out any the plan does not carry. */-function planCardMetrics(node: PlanNode, tree: PlanTree): string {+function planCardMetrics(+ node: PlanNode,+ tree: PlanTree,+ translate: QueryPlanTranslate+): string {return [- tree.estimates.cost ? `cost ${formatPlanCost(node.totalCost)}` : undefined,- tree.estimates.rows ? `rows ${formatPlanCount(node.rows)}` : undefined,+ 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(" · ");@@ -158,9 +167,16 @@ function PlanCollapseToggle({hiddenCount: number;onToggle: () => void;}) {+ const translate = useQueryPlanTranslation();const label = collapsed- ? `Expand ${formatPlanCount(hiddenCount)} nodes under ${node.nodeType}`- : `Collapse ${formatPlanCount(hiddenCount)} nodes under ${node.nodeType}`;+ ? translate("diagram.expand", {+ count: formatPlanCount(hiddenCount),+ node: node.nodeType,+ })+ : translate("diagram.collapse", {+ count: formatPlanCount(hiddenCount),+ node: node.nodeType,+ });return (<Tooltip content={label}><Button@@ -198,6 +214,7 @@ export function QueryPlanDiagram({revealId,onRevealed,}: Props) {+ const translate = useQueryPlanTranslation();const layout = useMemo(() => layoutPlan(tree.root, collapsedIds),[tree, collapsedIds]@@ -382,11 +399,15 @@ export function QueryPlanDiagram({strokeLinecap="round">{edge.target.rows === undefined ? null : (- <title>{`${formatPlanCount(edge.target.rows)} estimated rows`}</title>+ <title>+ {translate("diagram.estimated-rows", {+ count: formatPlanCount(edge.target.rows),+ })}+ </title>)}</path>)),- [layout, tree]+ [layout, tree, translate]);const cards = useMemo(@@ -394,7 +415,7 @@ export function QueryPlanDiagram({layout.nodes.map((placed) => {const { node, x, y } = placed;const selected = node.id === selectedId;- const metrics = planCardMetrics(node, tree);+ const metrics = planCardMetrics(node, tree, translate);const share = planSelfCostShare(node, tree);const warnings = node.warnings.map((warning) => warning.title);const collapsed = collapsedIds.has(node.id);@@ -424,11 +445,15 @@ export function QueryPlanDiagram({node.subject,metrics,tree.estimates.cost- ? `${formatPlanShare(share)} of plan cost`+ ? translate("diagram.plan-cost-share", {+ share: formatPlanShare(share),+ }): undefined,...warnings,collapsed- ? `${formatPlanCount(subtreeCount)} nodes hidden`+ ? translate("diagram.nodes-hidden", {+ count: formatPlanCount(subtreeCount),+ }): undefined,].filter(Boolean)@@ -525,6 +550,7 @@ export function QueryPlanDiagram({selectNode,panTo,onToggleCollapse,+ translate,]);@@ -568,33 +594,33 @@ export function QueryPlanDiagram({) : null}<div className="absolute right-2 bottom-2 flex items-center gap-1">- <Tooltip content="Zoom out">+ <Tooltip content={translate("diagram.zoom-out")}><Buttonappearance="outline"size="xs"- aria-label="Zoom out"+ aria-label={translate("diagram.zoom-out")}className="bg-background"onClick={() => zoomFromCenter(1 / ZOOM_STEP)}><ZoomOut className="size-3.5" /></Button></Tooltip>- <Tooltip content="Zoom in">+ <Tooltip content={translate("diagram.zoom-in")}><Buttonappearance="outline"size="xs"- aria-label="Zoom in"+ aria-label={translate("diagram.zoom-in")}className="bg-background"onClick={() => zoomFromCenter(ZOOM_STEP)}><ZoomIn className="size-3.5" /></Button></Tooltip>- <Tooltip content="Fit to view">+ <Tooltip content={translate("diagram.fit")}><Buttonappearance="outline"size="xs"- aria-label="Fit to view"+ aria-label={translate("diagram.fit")}className="bg-background"onClick={() => placeView("whole")}>diff --git a/frontend/src/apps/explain-visualizer/QueryPlanGrid.tsx b/frontend/src/apps/explain-visualizer/QueryPlanGrid.tsxindex ab4e3e8736..a391347f57 100644--- a/frontend/src/apps/explain-visualizer/QueryPlanGrid.tsx+++ b/frontend/src/apps/explain-visualizer/QueryPlanGrid.tsx@@ -8,6 +8,7 @@ import {TableRow,} from "@/components/ui/table";import { cn } from "@/lib/utils";+import { useQueryPlanTranslation } from "./plan-i18n";import {PLAN_INDENT_STEP,planGuideLevels,@@ -202,6 +203,7 @@ const PlanGridRow = memo(function PlanGridRow({});export function QueryPlanGrid({ tree, selectedId, onSelect }: Props) {+ const translate = useQueryPlanTranslation();const rows = useMemo(() => planRows(tree.root), [tree]);// Roving tab stop: Tab reaches the grid once and the arrow keys move within@@ -254,23 +256,22 @@ export function QueryPlanGrid({ tree, selectedId, onSelect }: Props) {className="min-h-0 w-full flex-1 overflow-auto"><Table className="table-fixed">- <caption className="sr-only">- Plan nodes in the order the planner nests them, parents before- children.- </caption>+ <caption className="sr-only">{translate("grid.caption")}</caption><TableHeader><TableRow><TableHead className={cn(HEAD_CLASS, "w-12 px-3 text-right")}>#</TableHead>- <TableHead className={HEAD_CLASS}>Node</TableHead>+ <TableHead className={HEAD_CLASS}>+ {translate("grid.node")}+ </TableHead>{tree.estimates.cost ? (<><TableHeadclassName={cn(HEAD_CLASS, "w-32 pl-2 text-right sm:w-48")}- title="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."+ title={translate("grid.added-cost-hint")}>- Added cost+ {translate("grid.added-cost")}</TableHead><TableHeadclassName={cn(@@ -279,7 +280,7 @@ export function QueryPlanGrid({ tree, selectedId, onSelect }: Props) {"text-right sm:w-28")}>- Total cost+ {translate("grid.total-cost")}</TableHead></>) : null}@@ -290,9 +291,9 @@ export function QueryPlanGrid({ tree, selectedId, onSelect }: Props) {SECONDARY_COLUMN_CLASS,"text-right sm:w-24")}- title="Estimated rows"+ title={translate("grid.estimated-rows")}>- Rows+ {translate("grid.rows")}</TableHead>) : null}{tree.estimates.width ? (@@ -302,9 +303,9 @@ export function QueryPlanGrid({ tree, selectedId, onSelect }: Props) {SECONDARY_COLUMN_CLASS,"text-right sm:w-24")}- title="Estimated row width in bytes"+ title={translate("grid.width-hint")}>- Width+ {translate("grid.width")}</TableHead>) : null}</TableRow>diff --git a/frontend/src/apps/explain-visualizer/QueryPlanNodeDetails.tsx b/frontend/src/apps/explain-visualizer/QueryPlanNodeDetails.tsxindex dd1225fcba..3dd2db1fff 100644--- a/frontend/src/apps/explain-visualizer/QueryPlanNodeDetails.tsx+++ b/frontend/src/apps/explain-visualizer/QueryPlanNodeDetails.tsx@@ -1,5 +1,6 @@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 { PlanMetric } from "./plan-shared";@@ -8,16 +9,36 @@ interface Props {}/** The node's estimates as labelled values, leaving out any it does not have. */-function nodeMetrics(node: PlanNode): { label: string; value: string }[] {+function nodeMetrics(+ node: PlanNode,+ translate: QueryPlanTranslate+): { label: string; value: string }[] {return [- { label: "Startup cost", value: node.startupCost, format: formatPlanCost },- { label: "Total cost", value: node.totalCost, format: formatPlanCost },- { label: "Added cost", value: node.selfCost, format: formatPlanCost },- { label: "Estimated rows", value: node.rows, format: formatPlanCount },{- label: "Row width",+ label: translate("metric.startup-cost"),+ value: node.startupCost,+ format: formatPlanCost,+ },+ {+ label: translate("metric.total-cost"),+ value: node.totalCost,+ format: formatPlanCost,+ },+ {+ label: translate("metric.added-cost"),+ value: node.selfCost,+ format: formatPlanCost,+ },+ {+ label: translate("metric.estimated-rows"),+ value: node.rows,+ format: formatPlanCount,+ },+ {+ label: translate("metric.row-width"),value: node.width,- format: (width: number) => `${formatPlanCount(width)} bytes`,+ format: (width: number) =>+ translate("metric.bytes", { count: formatPlanCount(width) }),},].flatMap(({ label, value, format }) =>value === undefined ? [] : [{ label, value: format(value) }]@@ -25,17 +46,18 @@ function nodeMetrics(node: PlanNode): { label: string; value: string }[] {}export function QueryPlanNodeDetails({ node }: Props) {+ const translate = useQueryPlanTranslation();if (!node) {return (<div className="flex h-full items-center justify-center p-4"><p className="text-sm leading-5 text-control-light">- Select a node to see its details.+ {translate("details.select-node")}</p></div>);}- const metrics = nodeMetrics(node);+ const metrics = nodeMetrics(node, translate);return (<div className="flex h-full min-h-0 flex-col overflow-auto p-4 gap-4">diff --git a/frontend/src/apps/explain-visualizer/QueryPlanSummary.tsx b/frontend/src/apps/explain-visualizer/QueryPlanSummary.tsxindex 27d7a5734e..9168ee24e6 100644--- a/frontend/src/apps/explain-visualizer/QueryPlanSummary.tsx+++ b/frontend/src/apps/explain-visualizer/QueryPlanSummary.tsx@@ -11,6 +11,7 @@ import {TableRow,} from "@/components/ui/table";import { cn } from "@/lib/utils";+import { useQueryPlanTranslation } from "./plan-i18n";import { planIndentPixels } from "./plan-layout";import {formatPlanCost,@@ -89,28 +90,28 @@ function Section({}function PlanTotals({ tree }: { tree: PlanTree }) {+ const translate = useQueryPlanTranslation();return (<div className="flex flex-col gap-3"><dl className="flex flex-wrap gap-4">- <PlanMetric label="Nodes" value={formatPlanCount(tree.nodes.length)} /><PlanMetric- label="Total estimated cost"+ label={translate("summary.nodes")}+ value={formatPlanCount(tree.nodes.length)}+ />+ <PlanMetric+ label={translate("summary.total-estimated-cost")}value={formatPlanCost(tree.root.totalCost)}/>{tree.root.rows === undefined ? null : (<PlanMetric- label="Estimated rows returned"+ label={translate("summary.estimated-rows-returned")}value={formatPlanCount(tree.root.rows)}/>)}</dl><p className="flex items-start gap-2 text-xs leading-4 text-control-light"><Info aria-hidden="true" className="mt-px size-3.5 shrink-0" />- <span>- The statement was planned but not run, so every figure here is an- optimizer estimate rather than a measurement. Cost units are arbitrary- and comparable only within this plan.- </span>+ <span>{translate("summary.estimate-note")}</span></p></div>);@@ -133,6 +134,7 @@ const TimelineRow = memo(function TimelineRow({selected: boolean;onSelect: (id: string) => void;}) {+ const translate = useQueryPlanTranslation();const { node, depth, start, end, share } = row;return (<li>@@ -140,7 +142,12 @@ const TimelineRow = memo(function TimelineRow({appearance="secondary"data-testid="plan-timeline-row"aria-pressed={selected}- aria-label={`${[node.nodeType, node.subject].filter(Boolean).join(", ")}, cost ${formatPlanCost(node.startupCost)} to ${formatPlanCost(node.totalCost)}, ${formatPlanShare(share)} of plan cost`}+ aria-label={translate("summary.timeline-node", {+ name: [node.nodeType, node.subject].filter(Boolean).join(", "),+ startup: formatPlanCost(node.startupCost),+ total: formatPlanCost(node.totalCost),+ share: formatPlanShare(share),+ })}onClick={() => onSelect(node.id)}className={cn(ROW_BUTTON_CLASS,@@ -243,12 +250,13 @@ function CostliestOperators({selectedId: string | undefined;onSelect: (id: string) => void;}) {+ const translate = useQueryPlanTranslation();const nodes = useMemo(() => planCostliestNodes(tree), [tree]);if (nodes.length === 0) {return (<p className="text-sm leading-5 text-control-light">- No node in this plan adds an estimated cost of its own.+ {translate("summary.no-added-cost")}</p>);}@@ -306,14 +314,17 @@ function CostliestOperators({}function CostByOperation({ tree }: { tree: PlanTree }) {+ const translate = useQueryPlanTranslation();const operations = useMemo(() => planCostByOperation(tree), [tree]);return (<Table className="table-fixed"><TableHeader><TableRow>- <TableHead className="text-xs leading-4">Operation</TableHead>+ <TableHead className="text-xs leading-4">+ {translate("summary.operation")}+ </TableHead><TableHead className="w-16 text-right text-xs leading-4">- Count+ {translate("summary.count")}</TableHead><TableHeadclassName={cn(@@ -321,10 +332,10 @@ function CostByOperation({ tree }: { tree: PlanTree }) {"text-right text-xs leading-4 sm:w-28")}>- Added cost+ {translate("summary.added-cost")}</TableHead><TableHead className="w-28 text-right text-xs leading-4 sm:w-40">- Share+ {translate("summary.share")}</TableHead></TableRow></TableHeader>@@ -368,6 +379,7 @@ function CostByOperation({ tree }: { tree: PlanTree }) {* node spans, which nodes own the most of it, and which kinds of operation do.*/export function QueryPlanSummary({ tree, selectedId, onSelect }: Props) {+ const translate = useQueryPlanTranslation();return (<divdata-testid="plan-summary"@@ -379,8 +391,8 @@ export function QueryPlanSummary({ tree, selectedId, onSelect }: Props) {{/* A span starts at a startup cost, which not every engine reports. */}{tree.estimates.startupCost ? (<Section- title="Cost ranges"- description="Each node spans its startup cost — the cost before its first row — to its total cost, both of which include everything below it. Darker spans carry more of the plan's cost. Costs are not a schedule: two inputs of a join overlap here but run one after the other."+ title={translate("summary.cost-ranges")}+ description={translate("summary.cost-ranges-description")}><CostTimelinetree={tree}@@ -391,8 +403,8 @@ export function QueryPlanSummary({ tree, selectedId, onSelect }: Props) {) : null}<Section- title="Costliest operators"- description="Ranked by the cost a node adds on top of its children. Where an input runs repeatedly, as under a nested loop, some engines count the repeats in the node that reruns it rather than in the input itself."+ title={translate("summary.costliest")}+ description={translate("summary.costliest-description")}><CostliestOperatorstree={tree}@@ -402,8 +414,8 @@ export function QueryPlanSummary({ tree, selectedId, onSelect }: Props) {</Section><Section- title="Cost by operation"- description="Every node type in the plan and what it costs in total."+ title={translate("summary.cost-by-operation")}+ description={translate("summary.cost-by-operation-description")}><CostByOperation tree={tree} /></Section>diff --git a/frontend/src/apps/explain-visualizer/QueryPlanView.test.tsx b/frontend/src/apps/explain-visualizer/QueryPlanView.test.tsxnew file mode 100644index 0000000000..a853611bb9--- /dev/null+++ b/frontend/src/apps/explain-visualizer/QueryPlanView.test.tsx@@ -0,0 +1,34 @@+import { render, screen } from "@testing-library/react";+import { describe, expect, test, vi } from "vitest";+import { Engine } from "@/types/proto-es/v1/common_pb";+import { QueryPlanView } from "./QueryPlanView";++describe("QueryPlanView", () => {+ test("uses the supplied translations for parse errors", () => {+ const translate = vi.fn((key: string) => `localized:${key}`);++ render(+ <QueryPlanView+ engine={Engine.POSTGRES}+ planSource="not JSON"+ translate={translate}+ />+ );++ expect(screen.getByText("localized:error.unreadable")).toBeVisible();+ expect(screen.getByText("localized:error.postgres-invalid")).toBeVisible();+ });++ test("shows the text plan when the structured plan cannot be parsed", () => {+ render(+ <QueryPlanView+ engine={Engine.POSTGRES}+ planSource="not JSON"+ textPlanSource="Seq Scan on t"+ />+ );++ expect(screen.getByText("Seq Scan on t")).toBeVisible();+ expect(screen.queryByText("not JSON")).toBeNull();+ });+});diff --git a/frontend/src/apps/explain-visualizer/QueryPlanView.tsx b/frontend/src/apps/explain-visualizer/QueryPlanView.tsxnew file mode 100644index 0000000000..39d6ace689--- /dev/null+++ b/frontend/src/apps/explain-visualizer/QueryPlanView.tsx@@ -0,0 +1,118 @@+import { useMemo } from "react";+import { Alert } from "@/components/ui/alert";+import { cn } from "@/lib/utils";+import { Engine } from "@/types/proto-es/v1/common_pb";+import type { VisualizerEngine } from "@/utils/explainToken";+import {+ MSSQL_PLAN_EMPTY_MESSAGE,+ MSSQL_PLAN_INVALID_XML_MESSAGE,+ MSSQL_PLAN_NO_PLAN_MESSAGE,+ parseMssqlPlan,+} from "./mssql-plan";+import {+ QueryPlanI18nProvider,+ type QueryPlanTranslate,+ type QueryPlanTranslationKey,+ useQueryPlanTranslation,+} from "./plan-i18n";+import { PLAN_TOO_DEEP_MESSAGE, type PlanParseResult } from "./plan-model";+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";++const PARSE_ERROR_KEYS = new Map<string, QueryPlanTranslationKey>([+ [PLAN_TOO_DEEP_MESSAGE, "error.too-deep"],+ [POSTGRES_PLAN_EMPTY_MESSAGE, "error.postgres-empty"],+ [POSTGRES_PLAN_INVALID_JSON_MESSAGE, "error.postgres-invalid"],+ [POSTGRES_PLAN_NO_PLAN_MESSAGE, "error.postgres-no-plan"],+ [MSSQL_PLAN_EMPTY_MESSAGE, "error.mssql-empty"],+ [MSSQL_PLAN_INVALID_XML_MESSAGE, "error.mssql-invalid"],+ [MSSQL_PLAN_NO_PLAN_MESSAGE, "error.mssql-no-plan"],+ [SPANNER_PLAN_EMPTY_MESSAGE, "error.spanner-empty"],+ [SPANNER_PLAN_INVALID_JSON_MESSAGE, "error.spanner-invalid"],+ [SPANNER_PLAN_NO_PLAN_MESSAGE, "error.spanner-no-plan"],+ [SPANNER_PLAN_EMULATOR_MESSAGE, "error.spanner-emulator"],+]);++interface Props {+ engine: VisualizerEngine;+ planSource: string;+ textPlanSource?: string;+ planQuery?: string;+ translate?: QueryPlanTranslate;+ disallowCopyingData?: boolean;+ syncSelectionWithHash?: boolean;+}++function QueryPlanViewContent({+ engine,+ planSource,+ textPlanSource,+ planQuery,+ disallowCopyingData = false,+ syncSelectionWithHash,+}: Props) {+ const translate = useQueryPlanTranslation();+ const result = useMemo(+ () => PARSERS[engine](planSource),+ [engine, planSource]+ );++ if (!result.ok) {+ const errorKey = PARSE_ERROR_KEYS.get(result.message);+ const fallbackPlan = textPlanSource?.trim() ? textPlanSource : planSource;+ return (+ <div className={cn(STATUS_CLASS, disallowCopyingData && "select-none")}>+ <Alert+ variant="error"+ title={translate("error.unreadable")}+ description={errorKey ? translate(errorKey) : result.message}+ />+ {fallbackPlan.trim() ? (+ <pre className="font-mono text-xs leading-4 break-words whitespace-pre-wrap text-control">+ {fallbackPlan}+ </pre>+ ) : null}+ </div>+ );+ }++ return (+ <QueryPlanViewer+ tree={result.tree}+ rawPlan={planSource}+ textPlan={textPlanSource}+ query={planQuery}+ disallowCopyingData={disallowCopyingData}+ syncSelectionWithHash={syncSelectionWithHash}+ />+ );+}++export function QueryPlanView({ translate, ...props }: Props) {+ return (+ <QueryPlanI18nProvider translate={translate}>+ <QueryPlanViewContent {...props} />+ </QueryPlanI18nProvider>+ );+}diff --git a/frontend/src/apps/explain-visualizer/QueryPlanViewer.test.tsx b/frontend/src/apps/explain-visualizer/QueryPlanViewer.test.tsxindex bbdfc89ed7..34bb478634 100644--- a/frontend/src/apps/explain-visualizer/QueryPlanViewer.test.tsx+++ b/frontend/src/apps/explain-visualizer/QueryPlanViewer.test.tsx@@ -65,6 +65,12 @@ const renderParsed = (const openTab = (name: string) =>fireEvent.click(screen.getByRole("tab", { name }));+const renderDiagramViewer = (query?: string) => {+ const result = renderViewer(query);+ openTab("Diagram");+ return result;+};+const tabNames = () =>screen.getAllByRole("tab").map((entry) => entry.textContent);@@ -83,9 +89,16 @@ describe("QueryPlanViewer", () => {startAtFragment("");});- test("opens on the diagram with the root node already selected", () => {+ test("opens on the text plan", () => {renderViewer();+ expect(screen.getByText(/"Node Type": "Bitmap Heap Scan"/)).toBeVisible();+ expect(screen.getByTestId("plan-diagram-viewport")).not.toBeVisible();+ });++ test("opens the diagram with the root node already selected", () => {+ renderDiagramViewer();+expect(screen.getByTestId("plan-diagram-viewport")).toBeInTheDocument();expect(screen.getByRole("heading", { name: "Bitmap Heap Scan" })@@ -94,7 +107,7 @@ describe("QueryPlanViewer", () => {});test("moves the detail pane to whichever node is clicked", () => {- renderViewer();+ renderDiagramViewer();fireEvent.click(screen.getByRole("button", { name: /Bitmap Index Scan/ })@@ -195,10 +208,10 @@ describe("QueryPlanViewer", () => {);});- test("switches to the raw plan and back to the diagram", () => {+ test("switches to the text plan and back to the diagram", () => {renderViewer();- fireEvent.click(screen.getByRole("tab", { name: "Raw plan" }));+ fireEvent.click(screen.getByRole("tab", { name: "Text" }));expect(screen.getByText(/"Node Type": "Bitmap Heap Scan"/)).toBeVisible();expect(screen.getByTestId("plan-diagram-viewport")).not.toBeVisible();@@ -206,6 +219,20 @@ describe("QueryPlanViewer", () => {expect(screen.getByTestId("plan-diagram-viewport")).toBeVisible();});+ test("shows a separate text plan in the same tab row", () => {+ render(+ <QueryPlanViewer+ tree={tree()}+ rawPlan={rawPlan}+ textPlan="Seq Scan on orders"+ />+ );++ openTab("Text");+ expect(screen.getByText("Seq Scan on orders")).toBeVisible();+ expect(screen.queryByText(/"Node Type"/)).toBeNull();+ });+test("shows the statement on the query tab", () => {renderViewer("SELECT * FROM orders WHERE customer_id = 42;");@@ -218,7 +245,7 @@ describe("QueryPlanViewer", () => {test("offers a copy of whichever text a tab is showing", () => {renderViewer("SELECT * FROM orders WHERE customer_id = 42;");- openTab("Raw plan");+ openTab("Text");expect(screen.getByTestId("plan-copy-button")).toHaveTextContent("Copy plan");@@ -246,7 +273,7 @@ describe("QueryPlanViewer", () => {});test("shades the diagram once a highlight mode is chosen", () => {- renderViewer();+ renderDiagramViewer();expect(screen.queryAllByTestId("plan-node-tint")).toHaveLength(0);fireEvent.click(screen.getByRole("button", { name: "Cost" }));@@ -257,14 +284,15 @@ describe("QueryPlanViewer", () => {renderParsed(parseMssqlPlan, procedureTwoStatements);expect(tabNames()).toEqual([+ "Text","Diagram","Grid","Summary",- "Raw plan","Query",]);+ openTab("Diagram");expect(- within(screen.getByRole("group", { name: "Highlight nodes by" }))+ within(screen.getByRole("group", { name: "Highlight" })).getAllByRole("button").map((option) => option.textContent)).toEqual(["Off", "Cost", "Rows"]);@@ -275,17 +303,18 @@ describe("QueryPlanViewer", () => {renderParsed(parseSpannerPlan, JSON.stringify(spannerHashJoin));// The summary is where the cost goes, and nothing can be shaded.- expect(tabNames()).toEqual(["Diagram", "Grid", "Raw plan", "Query"]);- expect(screen.queryByRole("group", { name: "Highlight nodes by" })).toBeNull();+ expect(tabNames()).toEqual(["Text", "Diagram", "Grid", "Query"]);+ openTab("Diagram");+ expect(screen.queryByRole("group", { name: "Highlight" })).toBeNull();expect(screen.getByText("7 nodes")).toBeVisible();expect(screen.queryByText(/card's bar/)).toBeNull();expect(screen.getAllByTestId("plan-node-card")).toHaveLength(7);});- test("indents an XML plan one element per line on the raw tab", () => {+ test("indents an XML plan one element per line on the text tab", () => {renderParsed(parseMssqlPlan, procedureTwoStatements);- openTab("Raw plan");+ openTab("Text");const raw = within(screen.getByRole("tabpanel")).getByText(/^<ShowPlanXML/).textContent;@@ -324,12 +353,48 @@ describe("QueryPlanViewer", () => {});test("names the selected node in the URL, which is what shares it", () => {- renderViewer();+ renderDiagramViewer();fireEvent.click(screen.getByRole("button", { name: /Bitmap Index Scan/ }));expect(location.hash).toBe("#node-0.0");});+ test("does not read or write fragments when hash syncing is disabled", () => {+ startAtFragment("#somewhere-else");+ render(+ <QueryPlanViewer+ tree={tree()}+ rawPlan={rawPlan}+ syncSelectionWithHash={false}+ />+ );+ openTab("Diagram");++ expect(+ screen.getByRole("heading", { name: "Bitmap Heap Scan" })+ ).toBeInTheDocument();+ fireEvent.click(screen.getByRole("button", { name: /Bitmap Index Scan/ }));+ expect(location.hash).toBe("#somewhere-else");+ });++ test("hides copy controls when copying is disabled", () => {+ render(+ <QueryPlanViewer+ tree={tree()}+ rawPlan={rawPlan}+ query="SELECT 1"+ disallowCopyingData+ />+ );++ expect(screen.queryByTestId("plan-copy-button")).toBeNull();+ openTab("Query");+ expect(screen.queryByTestId("plan-copy-button")).toBeNull();+ expect(screen.getByRole("tablist").parentElement).toHaveClass(+ "select-none"+ );+ });+test("leaves the URL alone until the reader picks a node", () => {renderViewer();@@ -340,7 +405,7 @@ describe("QueryPlanViewer", () => {test("opens on the node a fragment names", () => {startAtFragment("#node-0.0");- renderViewer();+ renderDiagramViewer();expect(screen.getByRole("heading", { name: "Bitmap Index Scan" })@@ -352,7 +417,7 @@ describe("QueryPlanViewer", () => {test("falls back to the root when a fragment names no node in this plan", () => {startAtFragment("#node-9.9.9");- renderViewer();+ renderDiagramViewer();expect(screen.getByRole("heading", { name: "Bitmap Heap Scan" })@@ -363,7 +428,7 @@ describe("QueryPlanViewer", () => {test("ignores a fragment that is not about a node at all", () => {startAtFragment("#somewhere-else");- renderViewer();+ renderDiagramViewer();expect(screen.getByRole("heading", { name: "Bitmap Heap Scan" })@@ -371,7 +436,7 @@ describe("QueryPlanViewer", () => {});test("follows a fragment that changes without a reload", () => {- renderViewer();+ renderDiagramViewer();startAtFragment("#node-0.0");fireEvent(window, new Event("hashchange"));@@ -382,7 +447,7 @@ describe("QueryPlanViewer", () => {});test("keeps the diagram's zoom while the reader moves between tabs", () => {- renderViewer();+ renderDiagramViewer();const canvas = () => screen.getByTestId("plan-diagram-canvas").style.transform;fireEvent.click(screen.getByRole("button", { name: "Zoom in" }));@@ -396,7 +461,7 @@ describe("QueryPlanViewer", () => {});test("keeps a subtree folded while the reader moves between tabs", () => {- renderViewer();+ renderDiagramViewer();expect(cards()).toHaveLength(2);fireEvent.click(collapseToggle());@@ -409,7 +474,7 @@ describe("QueryPlanViewer", () => {});test("moves the selection out of a subtree it folds away", () => {- renderViewer();+ renderDiagramViewer();fireEvent.click(screen.getByRole("button", { name: /Bitmap Index Scan/ }));expect(@@ -427,7 +492,7 @@ describe("QueryPlanViewer", () => {});test("unfolds a subtree when a node inside it is selected elsewhere", () => {- renderViewer();+ renderDiagramViewer();fireEvent.click(collapseToggle());openTab("Grid");diff --git a/frontend/src/apps/explain-visualizer/QueryPlanViewer.tsx b/frontend/src/apps/explain-visualizer/QueryPlanViewer.tsxindex 824a738961..0708e48e07 100644--- a/frontend/src/apps/explain-visualizer/QueryPlanViewer.tsx+++ b/frontend/src/apps/explain-visualizer/QueryPlanViewer.tsx@@ -11,6 +11,11 @@ import { Tooltip } from "@/components/ui/tooltip";import { useMediaQuery } from "@/hooks/useMediaQuery";import { cn } from "@/lib/utils";import { PlanCopyButton } from "./PlanCopyButton";+import {+ type QueryPlanTranslate,+ type QueryPlanTranslationKey,+ useQueryPlanTranslation,+} from "./plan-i18n";import {findPlanNode,formatPlanCost,@@ -31,17 +36,21 @@ import { QueryPlanSummary } from "./QueryPlanSummary";interface Props {readonly tree: PlanTree;- /** The engine's plan output, shown on the raw tab. */+ /** The machine-readable plan used to build the viewer. */readonly rawPlan: string;+ /** The plan output shown on the text tab, when it differs from rawPlan. */+ readonly textPlan?: string;readonly query?: string;+ readonly disallowCopyingData?: boolean;+ readonly syncSelectionWithHash?: boolean;}-type TabValue = "diagram" | "grid" | "summary" | "raw" | "query";+type TabValue = "diagram" | "grid" | "summary" | "text" | "query";interface HighlightOption {readonly value: PlanHighlightMode;- readonly label: string;- readonly hint: string;+ readonly label: QueryPlanTranslationKey;+ readonly hint: QueryPlanTranslationKey;/** Whether a plan carries the estimate the option shades by. */readonly available: (estimates: PlanEstimates) => boolean;}@@ -49,22 +58,22 @@ interface HighlightOption {const HIGHLIGHT_OPTIONS: readonly HighlightOption[] = [{value: "off",- label: "Off",- hint: "Leave every node card unshaded",+ label: "highlight.off",+ hint: "highlight.off-hint",available: () => true,},{value: "cost",- label: "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: "Shade by the cost a node adds on top of its children",+ hint: "highlight.cost-hint",available: (estimates) => estimates.cost,},{value: "rows",- label: "Rows",- hint: "Shade by the estimated row count",+ label: "highlight.rows",+ hint: "highlight.rows-hint",available: (estimates) => estimates.rows,},];@@ -89,16 +98,17 @@ function HighlightControl({value: PlanHighlightMode;onChange: (next: PlanHighlightMode) => void;}) {+ const translate = useQueryPlanTranslation();return (<divrole="group"- aria-label="Highlight nodes by"+ aria-label={translate("highlight.label")}className="inline-flex items-center gap-px overflow-hidden rounded-xs border border-control-border bg-control-border">{options.map((option) => {const selected = option.value === value;return (- <Tooltip key={option.value} content={option.hint}>+ <Tooltip key={option.value} content={translate(option.hint)}><Buttonsize="sm"appearance={selected ? "solid" : "secondary"}@@ -106,7 +116,7 @@ function HighlightControl({className={cn("rounded-none", !selected && "bg-background")}onClick={() => onChange(option.value)}>- {option.label}+ {translate(option.label)}</Button></Tooltip>);@@ -116,12 +126,17 @@ function HighlightControl({}function PlanTotalsLine({ tree }: { tree: PlanTree }) {+ const translate = useQueryPlanTranslation();return (<p className="text-xs leading-4 text-control-light">{[- `${formatPlanCount(tree.nodes.length)} nodes`,+ translate("totals.nodes", {+ count: formatPlanCount(tree.nodes.length),+ }),tree.estimates.cost- ? `estimated cost ${formatPlanCost(tree.root.totalCost)}`+ ? translate("totals.estimated-cost", {+ cost: formatPlanCost(tree.root.totalCost),+ }): undefined,].filter(Boolean)@@ -131,14 +146,13 @@ function PlanTotalsLine({ tree }: { tree: PlanTree }) {}/** What the diagram's bars and edge widths encode, for the estimates it has. */-function diagramLegend(estimates: PlanEstimates): string | undefined {+function diagramLegend(+ estimates: PlanEstimates,+ translate: QueryPlanTranslate+): string | undefined {const parts = [- estimates.cost- ? "each card's bar is that node's share of the plan's estimated cost"- : undefined,- estimates.rows- ? "an edge thickens with the rows its child is estimated to return"- : undefined,+ estimates.cost ? translate("legend.cost") : undefined,+ estimates.rows ? translate("legend.rows") : undefined,].filter(Boolean);if (parts.length === 0) return undefined;const sentence = `${parts.join("; ")}.`;@@ -232,7 +246,7 @@ function indentXml(source: string): string | undefined {}/** The plan indented for reading when it is JSON or XML, else as it came. */-function formatPlanSource(source: string): string {+export function formatPlanSource(source: string): string {if (source.trimStart().startsWith("<")) {return indentXml(source.trim()) ?? source;}@@ -247,17 +261,21 @@ function formatPlanSource(source: string): string {function CopyablePanel({content,label,+ disallowCopyingData,children,}: {content: string;label: string;+ disallowCopyingData: boolean;children: ReactNode;}) {return (<>- <div className="flex shrink-0 items-center justify-end px-4 py-2">- <PlanCopyButton content={content} label={label} />- </div>+ {disallowCopyingData ? null : (+ <div className="flex shrink-0 items-center justify-end px-4 py-2">+ <PlanCopyButton content={content} label={label} />+ </div>+ )}<div className="min-h-0 flex-1 overflow-auto px-4 pb-4">{children}</div></>);@@ -267,13 +285,24 @@ const MONOSPACE_BLOCK_CLASS ="font-mono text-xs leading-4 break-words whitespace-pre-wrap text-main";/**- * The raw plan tab's content. The tab mounts it only while open, so a large+ * The text plan tab's content. The tab mounts it only while open, so a large* plan is formatted when someone reads it rather than on every page load.*/-function RawPlan({ source }: { source: string }) {+function TextPlan({+ source,+ disallowCopyingData,+}: {+ source: string;+ disallowCopyingData: boolean;+}) {+ const translate = useQueryPlanTranslation();const formatted = useMemo(() => formatPlanSource(source), [source]);return (- <CopyablePanel content={formatted} label="Copy plan">+ <CopyablePanel+ content={formatted}+ label={translate("copy.plan")}+ disallowCopyingData={disallowCopyingData}+ ><pre className={MONOSPACE_BLOCK_CLASS}>{formatted}</pre></CopyablePanel>);@@ -288,10 +317,20 @@ function fragmentSelection(tree: PlanTree): string | undefined {return findPlanNode(tree, id)?.id;}-export function QueryPlanViewer({ tree, rawPlan, query }: Props) {- const [tab, setTab] = useState<TabValue>("diagram");+export function QueryPlanViewer({+ tree,+ rawPlan,+ textPlan = rawPlan,+ query,+ disallowCopyingData = false,+ syncSelectionWithHash = true,+}: Props) {+ const translate = useQueryPlanTranslation();+ const [tab, setTab] = useState<TabValue>("text");const [selectedId, setSelectedId] = useState<string>(- () => fragmentSelection(tree) ?? tree.root.id+ () =>+ (syncSelectionWithHash ? fragmentSelection(tree) : undefined) ??+ tree.root.id);const [highlight, setHighlight] = useState<PlanHighlightMode>("off");// Collapsed subtrees live here rather than in the diagram so switching tabs@@ -301,7 +340,7 @@ export function QueryPlanViewer({ tree, rawPlan, query }: Props) {);// A node the diagram should scroll to, rather than merely mark as selected.const [revealId, setRevealId] = useState<string | undefined>(() =>- fragmentSelection(tree)+ syncSelectionWithHash ? fragmentSelection(tree) : undefined);const selectedNode = findPlanNode(tree, selectedId);@@ -309,7 +348,7 @@ export function QueryPlanViewer({ tree, rawPlan, query }: Props) {const highlightOptions = HIGHLIGHT_OPTIONS.filter((option) =>option.available(tree.estimates));- const legend = diagramLegend(tree.estimates);+ const legend = diagramLegend(tree.estimates, translate);const selectNode = useCallback((id: string) => {@@ -344,17 +383,19 @@ export function QueryPlanViewer({ tree, rawPlan, query }: Props) {// and takes the view away from the fit the page opened on.const writtenSelection = useRef(selectedId);useEffect(() => {+ if (!syncSelectionWithHash) return;if (selectedId === writtenSelection.current) return;writtenSelection.current = selectedId;const fragment = planNodeFragment(selectedId);if (location.hash !== fragment) {history.replaceState(null, "", fragment);}- }, [selectedId]);+ }, [selectedId, syncSelectionWithHash]);// Following a second link to the page it is already on changes the fragment// without reloading anything.useEffect(() => {+ if (!syncSelectionWithHash) return;const onHashChange = () => {const id = fragmentSelection(tree);if (id === undefined) return;@@ -363,7 +404,7 @@ export function QueryPlanViewer({ tree, rawPlan, query }: Props) {};window.addEventListener("hashchange", onHashChange);return () => window.removeEventListener("hashchange", onHashChange);- }, [tree, selectNode]);+ }, [tree, selectNode, syncSelectionWithHash]);const onRevealed = useCallback(() => setRevealId(undefined), []);@@ -371,18 +412,21 @@ export function QueryPlanViewer({ tree, rawPlan, query }: Props) {<Tabsvalue={tab}onValueChange={(value) => setTab(value as TabValue)}- className="flex h-full min-h-0 w-full flex-col bg-background text-main"+ className={cn(+ "flex h-full min-h-0 w-full flex-col bg-background text-main",+ disallowCopyingData && "select-none"+ )}><TabsList className="shrink-0 flex-wrap px-4 pt-3">- <TabsTrigger value="diagram">Diagram</TabsTrigger>- <TabsTrigger value="grid">Grid</TabsTrigger>+ <TabsTrigger value="text">{translate("tab.text")}</TabsTrigger>+ <TabsTrigger value="diagram">{translate("tab.diagram")}</TabsTrigger>+ <TabsTrigger value="grid">{translate("tab.grid")}</TabsTrigger>{/* The summary is where the plan's cost goes, which a plan withoutcost estimates cannot say. */}{tree.estimates.cost ? (- <TabsTrigger value="summary">Summary</TabsTrigger>+ <TabsTrigger value="summary">{translate("tab.summary")}</TabsTrigger>) : null}- <TabsTrigger value="raw">Raw plan</TabsTrigger>- <TabsTrigger value="query">Query</TabsTrigger>+ <TabsTrigger value="query">{translate("tab.query")}</TabsTrigger></TabsList><TabsPanel@@ -402,7 +446,7 @@ export function QueryPlanViewer({ tree, rawPlan, query }: Props) {{highlightOptions.length > 1 ? (<div className="flex items-center gap-2"><span className="text-xs leading-4 text-control-light">- Highlight+ {translate("highlight.label")}</span><HighlightControloptions={highlightOptions}@@ -463,10 +507,10 @@ export function QueryPlanViewer({ tree, rawPlan, query }: Props) {) : null}<TabsPanel- value="raw"+ value="text"className="mt-0 flex min-h-0 flex-1 flex-col overflow-hidden">- <RawPlan source={rawPlan} />+ <TextPlan source={textPlan} disallowCopyingData={disallowCopyingData} /></TabsPanel><TabsPanel@@ -474,12 +518,16 @@ export function QueryPlanViewer({ tree, rawPlan, query }: Props) {className="mt-0 flex min-h-0 flex-1 flex-col overflow-hidden">{query ? (- <CopyablePanel content={query} label="Copy query">+ <CopyablePanel+ content={query}+ label={translate("copy.query")}+ disallowCopyingData={disallowCopyingData}+ ><pre className={MONOSPACE_BLOCK_CLASS}>{query}</pre></CopyablePanel>) : (<p className="p-4 text-sm leading-5 text-control-light">- The statement was not captured with this plan.+ {translate("query.missing")}</p>)}</TabsPanel>diff --git a/frontend/src/apps/explain-visualizer/plan-i18n.tsx b/frontend/src/apps/explain-visualizer/plan-i18n.tsxnew file mode 100644index 0000000000..f88b0cbf4d--- /dev/null+++ b/frontend/src/apps/explain-visualizer/plan-i18n.tsx@@ -0,0 +1,135 @@+import { createContext, type ReactNode, useContext } from "react";++const ENGLISH = {+ "copy.copied": "Copied",+ "copy.failed": "Copy failed",+ "copy.plan": "Copy plan",+ "copy.query": "Copy query",+ "details.select-node": "Select a node to see its details.",+ "diagram.collapse": "Collapse {{count}} nodes under {{node}}",+ "diagram.cost": "cost {{cost}}",+ "diagram.estimated-rows": "{{count}} estimated rows",+ "diagram.expand": "Expand {{count}} nodes under {{node}}",+ "diagram.fit": "Fit to view",+ "diagram.nodes-hidden": "{{count}} nodes hidden",+ "diagram.plan-cost-share": "{{share}} of plan cost",+ "diagram.rows": "rows {{count}}",+ "diagram.zoom-in": "Zoom in",+ "diagram.zoom-out": "Zoom out",+ "error.mssql-empty": "SQL Server returned no query plan for this statement.",+ "error.mssql-invalid":+ "The query plan is not valid XML. SHOWPLAN_XML output is expected.",+ "error.mssql-no-plan":+ "The query plan XML is not a SQL Server showplan with at least one statement.",+ "error.postgres-empty":+ "PostgreSQL returned no query plan for this statement.",+ "error.postgres-invalid":+ "The query plan is not valid JSON. EXPLAIN (FORMAT JSON) output is expected.",+ "error.postgres-no-plan":+ 'The query plan JSON does not contain a "Plan" object.',+ "error.spanner-emulator":+ "Spanner returned no query plan for this statement. The Spanner emulator returns none for any statement, so explain it on a Spanner instance to see one.",+ "error.spanner-empty": "Spanner returned no query plan for this statement.",+ "error.spanner-invalid":+ "The query plan is not valid JSON. A Spanner query plan is expected.",+ "error.spanner-no-plan":+ 'The query plan JSON does not contain a "planNodes" list with an operator at its root.',+ "error.too-deep":+ "The query plan is nested too deeply for this visualizer to draw.",+ "error.unreadable": "This query plan could not be read",+ "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.",+ "grid.caption":+ "Plan nodes in the order the planner nests them, parents before children.",+ "grid.estimated-rows": "Estimated rows",+ "grid.node": "Node",+ "grid.rows": "Rows",+ "grid.total-cost": "Total cost",+ "grid.width": "Width",+ "grid.width-hint": "Estimated row width in bytes",+ "highlight.cost": "Cost",+ "highlight.cost-hint": "Shade by the cost a node adds on top of its children",+ "highlight.label": "Highlight",+ "highlight.off": "Off",+ "highlight.off-hint": "Leave every node card unshaded",+ "highlight.rows": "Rows",+ "highlight.rows-hint": "Shade by the estimated row count",+ "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",+ "metric.added-cost": "Added cost",+ "metric.bytes": "{{count}} bytes",+ "metric.estimated-rows": "Estimated rows",+ "metric.row-width": "Row width",+ "metric.startup-cost": "Startup cost",+ "metric.total-cost": "Total cost",+ "query.missing": "The statement was not captured with this plan.",+ "summary.added-cost": "Added cost",+ "summary.cost-by-operation": "Cost by operation",+ "summary.cost-by-operation-description":+ "Every node type in the plan and what it costs in total.",+ "summary.cost-ranges": "Cost ranges",+ "summary.cost-ranges-description":+ "Each node spans its startup cost — the cost before its first row — to its total cost, both of which include everything below it. Darker spans carry more of the plan's cost. Costs are not a schedule: two inputs of a join overlap here but run one after the other.",+ "summary.costliest": "Costliest operators",+ "summary.costliest-description":+ "Ranked by the cost a node adds on top of its children. Where an input runs repeatedly, as under a nested loop, some engines count the repeats in the node that reruns it rather than in the input itself.",+ "summary.count": "Count",+ "summary.estimate-note":+ "The statement was planned but not run, so every figure here is an optimizer estimate rather than a measurement. Cost units are arbitrary and comparable only within this plan.",+ "summary.estimated-rows-returned": "Estimated rows returned",+ "summary.no-added-cost":+ "No node in this plan adds an estimated cost of its own.",+ "summary.nodes": "Nodes",+ "summary.operation": "Operation",+ "summary.share": "Share",+ "summary.timeline-node":+ "{{name}}, cost {{startup}} to {{total}}, {{share}} of plan cost",+ "summary.total-estimated-cost": "Total estimated cost",+ "tab.diagram": "Diagram",+ "tab.grid": "Grid",+ "tab.query": "Query",+ "tab.summary": "Summary",+ "tab.text": "Text",+ "totals.estimated-cost": "estimated cost {{cost}}",+ "totals.nodes": "{{count}} nodes",+} as const;++export type QueryPlanTranslationKey = keyof typeof ENGLISH;+export type QueryPlanTranslationValues = Record<string, string | number>;+export type QueryPlanTranslate = (+ key: QueryPlanTranslationKey,+ values?: QueryPlanTranslationValues+) => string;++const interpolate = (template: string, values?: QueryPlanTranslationValues) =>+ template.replace(/{{(\w+)}}/g, (_, key: string) =>+ String(values?.[key] ?? "")+ );++const fallbackTranslate: QueryPlanTranslate = (key, values) =>+ interpolate(ENGLISH[key], values);++const QueryPlanI18nContext = createContext<QueryPlanTranslate | undefined>(+ undefined+);++export function QueryPlanI18nProvider({+ translate,+ children,+}: {+ translate?: QueryPlanTranslate;+ children: ReactNode;+}) {+ return (+ <QueryPlanI18nContext.Provider value={translate}>+ {children}+ </QueryPlanI18nContext.Provider>+ );+}++export function useQueryPlanTranslation(): QueryPlanTranslate {+ return useContext(QueryPlanI18nContext) ?? fallbackTranslate;+}diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.jsonindex d08a0ac2d2..28cb59603a 100644--- a/frontend/src/locales/en-US.json+++ b/frontend/src/locales/en-US.json@@ -3316,6 +3316,108 @@"admin-data-source-is-disallowed-to-query": "Admin data source is disallowed to query."},"query-history-not-found": "Query history not found or no longer accessible",+ "query-plan-load-failed": "Failed to load the query plan",+ "query-plan-viewer": {+ "copy": {+ "copied": "Copied",+ "failed": "Copy failed",+ "plan": "Copy plan",+ "query": "Copy query"+ },+ "details": {+ "select-node": "Select a node to see its details."+ },+ "diagram": {+ "collapse": "Collapse {{count}} nodes under {{node}}",+ "cost": "cost {{cost}}",+ "estimated-rows": "{{count}} estimated rows",+ "expand": "Expand {{count}} nodes under {{node}}",+ "fit": "Fit to view",+ "nodes-hidden": "{{count}} nodes hidden",+ "plan-cost-share": "{{share}} of plan cost",+ "rows": "rows {{count}}",+ "zoom-in": "Zoom in",+ "zoom-out": "Zoom out"+ },+ "error": {+ "mssql-empty": "SQL Server returned no query plan for this statement.",+ "mssql-invalid": "The query plan is not valid XML. SHOWPLAN_XML output is expected.",+ "mssql-no-plan": "The query plan XML is not a SQL Server showplan with at least one statement.",+ "postgres-empty": "PostgreSQL returned no query plan for this statement.",+ "postgres-invalid": "The query plan is not valid JSON. EXPLAIN (FORMAT JSON) output is expected.",+ "postgres-no-plan": "The query plan JSON does not contain a \"Plan\" object.",+ "spanner-empty": "Spanner returned no query plan for this statement.",+ "spanner-emulator": "Spanner returned no query plan for this statement. The Spanner emulator returns none for any statement, so explain it on a Spanner instance to see one.",+ "spanner-invalid": "The query plan is not valid JSON. A Spanner query plan is expected.",+ "spanner-no-plan": "The query plan JSON does not contain a \"planNodes\" list with an operator at its root.",+ "too-deep": "The query plan is nested too deeply for this visualizer to draw.",+ "unreadable": "This query plan could not be read"+ },+ "grid": {+ "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",+ "total-cost": "Total cost",+ "width": "Width",+ "width-hint": "Estimated row width in bytes"+ },+ "highlight": {+ "cost": "Cost",+ "cost-hint": "Shade by the cost a node adds on top of its children",+ "label": "Highlight",+ "off": "Off",+ "off-hint": "Leave every node card unshaded",+ "rows": "Rows",+ "rows-hint": "Shade by the estimated row count"+ },+ "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"+ },+ "metric": {+ "added-cost": "Added cost",+ "bytes": "{{count}} bytes",+ "estimated-rows": "Estimated rows",+ "row-width": "Row width",+ "startup-cost": "Startup cost",+ "total-cost": "Total cost"+ },+ "query": {+ "missing": "The statement was not captured with this plan."+ },+ "summary": {+ "added-cost": "Added cost",+ "cost-by-operation": "Cost by operation",+ "cost-by-operation-description": "Every node type in the plan and what it costs in total.",+ "cost-ranges": "Cost ranges",+ "cost-ranges-description": "Each node spans its startup cost — the cost before its first row — to its total cost, both of which include everything below it. Darker spans carry more of the plan's cost. Costs are not a schedule: two inputs of a join overlap here but run one after the other.",+ "costliest": "Costliest operators",+ "costliest-description": "Ranked by the cost a node adds on top of its children. Where an input runs repeatedly, as under a nested loop, some engines count the repeats in the node that reruns it rather than in the input itself.",+ "count": "Count",+ "estimate-note": "The statement was planned but not run, so every figure here is an optimizer estimate rather than a measurement. Cost units are arbitrary and comparable only within this plan.",+ "estimated-rows-returned": "Estimated rows returned",+ "no-added-cost": "No node in this plan adds an estimated cost of its own.",+ "nodes": "Nodes",+ "operation": "Operation",+ "share": "Share",+ "timeline-node": "{{name}}, cost {{startup}} to {{total}}, {{share}} of plan cost",+ "total-estimated-cost": "Total estimated cost"+ },+ "tab": {+ "diagram": "Diagram",+ "grid": "Grid",+ "query": "Query",+ "summary": "Summary",+ "text": "Text"+ },+ "totals": {+ "estimated-cost": "estimated cost {{cost}}",+ "nodes": "{{count}} nodes"+ }+ },"query-time": "Query time","re-request": "Re-request","recent": "Recent",@@ -3402,10 +3504,6 @@"view-detail": "View detail","view-issue": "View issue","view-schema-text": "View schema text",- "visualize-explain": "Visualize Explain",- "visualize-explain-blocked": "The query plan tab was blocked. Allow pop-ups for this site and try again.",- "visualize-explain-executed": "Visualizing this plan would execute the query again.",- "visualize-explain-failed": "Failed to load the query plan","web-socket": {"connection-status": {"connected": "connected",diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.jsonindex 3e7ec17913..ec1c4f6bf5 100644--- a/frontend/src/locales/es-ES.json+++ b/frontend/src/locales/es-ES.json@@ -3316,6 +3316,108 @@"admin-data-source-is-disallowed-to-query": "No se permite realizar consultas a la fuente de datos del administrador."},"query-history-not-found": "Historial de consultas no encontrado o ya no accesible",+ "query-plan-load-failed": "No se pudo cargar el plan de consulta",+ "query-plan-viewer": {+ "copy": {+ "copied": "Copiado",+ "failed": "Error al copiar",+ "plan": "Copiar plan",+ "query": "Copiar consulta"+ },+ "details": {+ "select-node": "Selecciona un nodo para ver sus detalles."+ },+ "diagram": {+ "collapse": "Contraer {{count}} nodos bajo {{node}}",+ "cost": "coste {{cost}}",+ "estimated-rows": "{{count}} filas estimadas",+ "expand": "Expandir {{count}} nodos bajo {{node}}",+ "fit": "Ajustar a la vista",+ "nodes-hidden": "{{count}} nodos ocultos",+ "plan-cost-share": "{{share}} del coste del plan",+ "rows": "filas {{count}}",+ "zoom-in": "Acercar",+ "zoom-out": "Alejar"+ },+ "error": {+ "mssql-empty": "SQL Server no devolvió ningún plan de consulta para esta sentencia.",+ "mssql-invalid": "El plan de consulta no es XML válido. Se espera la salida de SHOWPLAN_XML.",+ "mssql-no-plan": "El XML del plan de consulta no es un showplan de SQL Server con al menos una sentencia.",+ "postgres-empty": "PostgreSQL no devolvió ningún plan de consulta para esta sentencia.",+ "postgres-invalid": "El plan de consulta no es JSON válido. Se espera la salida de EXPLAIN (FORMAT JSON).",+ "postgres-no-plan": "El JSON del plan de consulta no contiene un objeto \"Plan\".",+ "spanner-empty": "Spanner no devolvió ningún plan de consulta para esta sentencia.",+ "spanner-emulator": "Spanner no devolvió ningún plan de consulta para esta sentencia. El emulador de Spanner no devuelve ninguno para ninguna sentencia; explíquela en una instancia de Spanner para ver uno.",+ "spanner-invalid": "El plan de consulta no es JSON válido. Se espera un plan de consulta de Spanner.",+ "spanner-no-plan": "El JSON del plan de consulta no contiene una lista \"planNodes\" con un operador en la raíz.",+ "too-deep": "El plan de consulta está demasiado anidado para que este visualizador pueda dibujarlo.",+ "unreadable": "No se pudo leer este plan de consulta"+ },+ "grid": {+ "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",+ "total-cost": "Coste total",+ "width": "Anchura",+ "width-hint": "Anchura estimada de la fila en bytes"+ },+ "highlight": {+ "cost": "Coste",+ "cost-hint": "Sombrear según el coste que un nodo añade sobre sus hijos",+ "label": "Resaltar",+ "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"+ },+ "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"+ },+ "metric": {+ "added-cost": "Coste añadido",+ "bytes": "{{count}} bytes",+ "estimated-rows": "Filas estimadas",+ "row-width": "Anchura de fila",+ "startup-cost": "Coste inicial",+ "total-cost": "Coste total"+ },+ "query": {+ "missing": "La sentencia no se guardó con este plan."+ },+ "summary": {+ "added-cost": "Coste añadido",+ "cost-by-operation": "Coste por operación",+ "cost-by-operation-description": "Cada tipo de nodo del plan y su coste total.",+ "cost-ranges": "Rangos de coste",+ "cost-ranges-description": "Cada nodo abarca desde su coste inicial —el coste antes de su primera fila— hasta su coste total; ambos incluyen todo lo que hay debajo. Los intervalos más oscuros contienen más coste del plan. Los costes no son un calendario: dos entradas de una unión se solapan aquí, pero se ejecutan una tras otra.",+ "costliest": "Operadores más costosos",+ "costliest-description": "Ordenados por el coste que un nodo añade sobre sus hijos. Cuando una entrada se ejecuta repetidamente, como bajo un bucle anidado, algunos motores cuentan las repeticiones en el nodo que la vuelve a ejecutar y no en la propia entrada.",+ "count": "Cantidad",+ "estimate-note": "La sentencia se planificó, pero no se ejecutó, por lo que todas las cifras son estimaciones del optimizador y no mediciones. Las unidades de coste son arbitrarias y solo comparables dentro de este plan.",+ "estimated-rows-returned": "Filas devueltas estimadas",+ "no-added-cost": "Ningún nodo de este plan añade un coste estimado propio.",+ "nodes": "Nodos",+ "operation": "Operación",+ "share": "Proporción",+ "timeline-node": "{{name}}, coste de {{startup}} a {{total}}, {{share}} del coste del plan",+ "total-estimated-cost": "Coste total estimado"+ },+ "tab": {+ "diagram": "Diagrama",+ "grid": "Cuadrícula",+ "query": "Consulta",+ "summary": "Resumen",+ "text": "Texto"+ },+ "totals": {+ "estimated-cost": "coste estimado {{cost}}",+ "nodes": "{{count}} nodos"+ }+ },"query-time": "Tiempo de consulta","re-request": "Volver a solicitar","recent": "Reciente",@@ -3402,10 +3504,6 @@"view-detail": "Ver detalle","view-issue": "Ver issue","view-schema-text": "Ver texto del esquema",- "visualize-explain": "Visualizar explicación",- "visualize-explain-blocked": "Se bloqueó la pestaña del plan de consulta. Permite las ventanas emergentes de este sitio e inténtalo de nuevo.",- "visualize-explain-executed": "Visualizar este plan volvería a ejecutar la consulta.",- "visualize-explain-failed": "No se pudo cargar el plan de consulta","web-socket": {"connection-status": {"connected": "conectado",diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.jsonindex 70431c3bd4..7f2bf9ed27 100644--- a/frontend/src/locales/ja-JP.json+++ b/frontend/src/locales/ja-JP.json@@ -3316,6 +3316,108 @@"admin-data-source-is-disallowed-to-query": "管理者データ ソースはクエリできません。"},"query-history-not-found": "クエリ履歴が見つからないか、アクセスできなくなりました",+ "query-plan-load-failed": "クエリプランの読み込みに失敗しました",+ "query-plan-viewer": {+ "copy": {+ "copied": "コピーしました",+ "failed": "コピーに失敗しました",+ "plan": "プランをコピー",+ "query": "クエリをコピー"+ },+ "details": {+ "select-node": "詳細を表示するノードを選択してください。"+ },+ "diagram": {+ "collapse": "{{node}} 配下の {{count}} ノードを折りたたむ",+ "cost": "コスト {{cost}}",+ "estimated-rows": "推定 {{count}} 行",+ "expand": "{{node}} 配下の {{count}} ノードを展開",+ "fit": "全体を表示",+ "nodes-hidden": "{{count}} ノードを非表示",+ "plan-cost-share": "プランコストの {{share}}",+ "rows": "行数 {{count}}",+ "zoom-in": "拡大",+ "zoom-out": "縮小"+ },+ "error": {+ "mssql-empty": "SQL Server はこのステートメントのクエリプランを返しませんでした。",+ "mssql-invalid": "クエリプランが有効な XML ではありません。SHOWPLAN_XML の出力が必要です。",+ "mssql-no-plan": "クエリプラン XML は、1つ以上のステートメントを含む SQL Server showplan ではありません。",+ "postgres-empty": "PostgreSQL はこのステートメントのクエリプランを返しませんでした。",+ "postgres-invalid": "クエリプランが有効な JSON ではありません。EXPLAIN (FORMAT JSON) の出力が必要です。",+ "postgres-no-plan": "クエリプラン JSON に \"Plan\" オブジェクトがありません。",+ "spanner-empty": "Spanner はこのステートメントのクエリプランを返しませんでした。",+ "spanner-emulator": "Spanner はこのステートメントのクエリプランを返しませんでした。Spanner エミュレーターはいずれのステートメントにもプランを返さないため、Spanner インスタンスで説明を実行してください。",+ "spanner-invalid": "クエリプランが有効な JSON ではありません。Spanner クエリプランが必要です。",+ "spanner-no-plan": "クエリプラン JSON に、ルートがオペレーターである \"planNodes\" リストがありません。",+ "too-deep": "クエリプランの入れ子が深すぎるため、このビジュアライザーでは描画できません。",+ "unreadable": "このクエリプランを読み取れませんでした"+ },+ "grid": {+ "added-cost": "追加コスト",+ "added-cost-hint": "このノードが子ノードに加えて追加するコストです。一部のエンジンでは、ネストループ配下などで入力の反復実行もここに含めます。バーはプラン全体に占めるこのコストの割合です。",+ "caption": "プランナーが入れ子にする順序で並べたプランノードです。親が子より先に表示されます。",+ "estimated-rows": "推定行数",+ "node": "ノード",+ "rows": "行数",+ "total-cost": "総コスト",+ "width": "幅",+ "width-hint": "推定行幅(バイト)"+ },+ "highlight": {+ "cost": "コスト",+ "cost-hint": "ノードが子ノードに加えて追加するコストで色付け",+ "label": "ハイライト",+ "off": "オフ",+ "off-hint": "すべてのノードカードを色付けしない",+ "rows": "行数",+ "rows-hint": "推定行数で色付け"+ },+ "legend": {+ "cost": "各カードのバーは、そのノードがプランの推定コストに占める割合を示します",+ "rows": "子ノードが返すと推定される行数に応じてエッジが太くなります"+ },+ "metric": {+ "added-cost": "追加コスト",+ "bytes": "{{count}} バイト",+ "estimated-rows": "推定行数",+ "row-width": "行幅",+ "startup-cost": "開始コスト",+ "total-cost": "総コスト"+ },+ "query": {+ "missing": "このプランにはステートメントが保存されていません。"+ },+ "summary": {+ "added-cost": "追加コスト",+ "cost-by-operation": "操作別コスト",+ "cost-by-operation-description": "プラン内の各ノード種別と、その総コストです。",+ "cost-ranges": "コスト範囲",+ "cost-ranges-description": "各ノードは、最初の行を返す前の開始コストから、その配下のすべてを含む総コストまでを示します。濃い範囲ほどプランコストの割合が高くなります。コストは実行スケジュールではありません。結合の2つの入力はここでは重なりますが、実際には順番に実行されます。",+ "costliest": "高コストなオペレーター",+ "costliest-description": "ノードが子ノードに加えて追加するコスト順です。ネストループ配下などで入力が繰り返し実行される場合、一部のエンジンは反復コストを入力自体ではなく、その入力を再実行するノードに計上します。",+ "count": "件数",+ "estimate-note": "ステートメントはプランニングされましたが実行されていないため、ここにある数値はすべて測定値ではなくオプティマイザーの推定値です。コスト単位は任意で、このプラン内でのみ比較できます。",+ "estimated-rows-returned": "推定返却行数",+ "no-added-cost": "このプランには固有の推定コストを追加するノードがありません。",+ "nodes": "ノード",+ "operation": "操作",+ "share": "割合",+ "timeline-node": "{{name}}、コスト {{startup}} から {{total}}、プランコストの {{share}}",+ "total-estimated-cost": "推定総コスト"+ },+ "tab": {+ "diagram": "ダイアグラム",+ "grid": "グリッド",+ "query": "クエリ",+ "summary": "概要",+ "text": "テキスト"+ },+ "totals": {+ "estimated-cost": "推定コスト {{cost}}",+ "nodes": "{{count}} ノード"+ }+ },"query-time": "クエリ時間","re-request": "再申請","recent": "最近",@@ -3402,10 +3504,6 @@"view-detail": "詳細を見る","view-issue": "Issue を表示","view-schema-text": "テキストの表示 スキーマ",- "visualize-explain": "視覚化の説明",- "visualize-explain-blocked": "クエリプランのタブがブロックされました。このサイトのポップアップを許可して再試行してください。",- "visualize-explain-executed": "このプランを視覚化すると、クエリが再度実行されます。",- "visualize-explain-failed": "クエリプランの読み込みに失敗しました","web-socket": {"connection-status": {"connected": "接続済み",diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.jsonindex df6bec1de6..0ae53c69ee 100644--- a/frontend/src/locales/vi-VN.json+++ b/frontend/src/locales/vi-VN.json@@ -3316,6 +3316,108 @@"admin-data-source-is-disallowed-to-query": "Nguồn dữ liệu quản trị không được phép truy vấn."},"query-history-not-found": "Không tìm thấy lịch sử truy vấn hoặc không còn truy cập được",+ "query-plan-load-failed": "Không tải được kế hoạch truy vấn",+ "query-plan-viewer": {+ "copy": {+ "copied": "Đã sao chép",+ "failed": "Sao chép thất bại",+ "plan": "Sao chép kế hoạch",+ "query": "Sao chép truy vấn"+ },+ "details": {+ "select-node": "Chọn một nút để xem chi tiết."+ },+ "diagram": {+ "collapse": "Thu gọn {{count}} nút bên dưới {{node}}",+ "cost": "chi phí {{cost}}",+ "estimated-rows": "{{count}} hàng ước tính",+ "expand": "Mở rộng {{count}} nút bên dưới {{node}}",+ "fit": "Vừa với khung nhìn",+ "nodes-hidden": "Đã ẩn {{count}} nút",+ "plan-cost-share": "{{share}} chi phí kế hoạch",+ "rows": "hàng {{count}}",+ "zoom-in": "Phóng to",+ "zoom-out": "Thu nhỏ"+ },+ "error": {+ "mssql-empty": "SQL Server không trả về kế hoạch truy vấn cho câu lệnh này.",+ "mssql-invalid": "Kế hoạch truy vấn không phải XML hợp lệ. Cần đầu ra SHOWPLAN_XML.",+ "mssql-no-plan": "XML của kế hoạch truy vấn không phải showplan SQL Server có ít nhất một câu lệnh.",+ "postgres-empty": "PostgreSQL không trả về kế hoạch truy vấn cho câu lệnh này.",+ "postgres-invalid": "Kế hoạch truy vấn không phải JSON hợp lệ. Cần đầu ra EXPLAIN (FORMAT JSON).",+ "postgres-no-plan": "JSON của kế hoạch truy vấn không chứa đối tượng \"Plan\".",+ "spanner-empty": "Spanner không trả về kế hoạch truy vấn cho câu lệnh này.",+ "spanner-emulator": "Spanner không trả về kế hoạch truy vấn cho câu lệnh này. Trình giả lập Spanner không trả về kế hoạch cho bất kỳ câu lệnh nào; hãy giải thích câu lệnh trên một phiên bản Spanner để xem kế hoạch.",+ "spanner-invalid": "Kế hoạch truy vấn không phải JSON hợp lệ. Cần một kế hoạch truy vấn Spanner.",+ "spanner-no-plan": "JSON của kế hoạch truy vấn không chứa danh sách \"planNodes\" có toán tử ở gốc.",+ "too-deep": "Kế hoạch truy vấn lồng quá sâu để trình trực quan hóa này có thể vẽ.",+ "unreadable": "Không thể đọc kế hoạch truy vấn này"+ },+ "grid": {+ "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",+ "total-cost": "Tổng chi phí",+ "width": "Độ rộng",+ "width-hint": "Độ rộng hàng ước tính theo byte"+ },+ "highlight": {+ "cost": "Chi phí",+ "cost-hint": "Tô màu theo chi phí mà nút thêm ngoài các nút con",+ "label": "Làm nổi bật",+ "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"+ },+ "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ề"+ },+ "metric": {+ "added-cost": "Chi phí thêm",+ "bytes": "{{count}} byte",+ "estimated-rows": "Số hàng ước tính",+ "row-width": "Độ rộng hàng",+ "startup-cost": "Chi phí khởi động",+ "total-cost": "Tổng chi phí"+ },+ "query": {+ "missing": "Câu lệnh không được lưu cùng kế hoạch này."+ },+ "summary": {+ "added-cost": "Chi phí thêm",+ "cost-by-operation": "Chi phí theo thao tác",+ "cost-by-operation-description": "Mỗi loại nút trong kế hoạch và tổng chi phí của nó.",+ "cost-ranges": "Khoảng chi phí",+ "cost-ranges-description": "Mỗi nút trải từ chi phí khởi động — chi phí trước hàng đầu tiên — đến tổng chi phí, cả hai đều bao gồm mọi thứ bên dưới. Khoảng tối hơn chiếm nhiều chi phí kế hoạch hơn. Chi phí không phải lịch thực thi: hai đầu vào của phép nối chồng lên nhau ở đây nhưng chạy lần lượt.",+ "costliest": "Toán tử tốn kém nhất",+ "costliest-description": "Xếp hạng theo chi phí mà một nút thêm ngoài các nút con. Khi một đầu vào chạy lặp lại, như trong vòng lặp lồng nhau, một số máy cơ sở dữ liệu tính số lần lặp vào nút chạy lại đầu vào thay vì chính đầu vào.",+ "count": "Số lượng",+ "estimate-note": "Câu lệnh đã được lập kế hoạch nhưng chưa chạy, vì vậy mọi số liệu ở đây là ước tính của bộ tối ưu hóa chứ không phải phép đo. Đơn vị chi phí là tùy ý và chỉ có thể so sánh trong kế hoạch này.",+ "estimated-rows-returned": "Số hàng trả về ước tính",+ "no-added-cost": "Không có nút nào trong kế hoạch này tự thêm chi phí ước tính.",+ "nodes": "Nút",+ "operation": "Thao tác",+ "share": "Tỷ lệ",+ "timeline-node": "{{name}}, chi phí từ {{startup}} đến {{total}}, {{share}} chi phí kế hoạch",+ "total-estimated-cost": "Tổng chi phí ước tính"+ },+ "tab": {+ "diagram": "Sơ đồ",+ "grid": "Lưới",+ "query": "Truy vấn",+ "summary": "Tóm tắt",+ "text": "Văn bản"+ },+ "totals": {+ "estimated-cost": "chi phí ước tính {{cost}}",+ "nodes": "{{count}} nút"+ }+ },"query-time": "Thời gian truy vấn","re-request": "Yêu cầu lại","recent": "Gần đây",@@ -3402,10 +3504,6 @@"view-detail": "Xem chi tiết","view-issue": "Xem Issue","view-schema-text": "Xem văn bản lược đồ",- "visualize-explain": "Trực quan hóa Giải thích",- "visualize-explain-blocked": "Tab kế hoạch truy vấn đã bị chặn. Hãy cho phép cửa sổ bật lên cho trang này và thử lại.",- "visualize-explain-executed": "Trực quan hóa kế hoạch này sẽ thực thi lại truy vấn.",- "visualize-explain-failed": "Không tải được kế hoạch truy vấn","web-socket": {"connection-status": {"connected": "đã kết nối",diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.jsonindex 3b1314d3de..3d2750efd0 100644--- a/frontend/src/locales/zh-CN.json+++ b/frontend/src/locales/zh-CN.json@@ -3316,6 +3316,108 @@"admin-data-source-is-disallowed-to-query": "禁止查询主数据源。"},"query-history-not-found": "查询历史记录不存在或已无法访问",+ "query-plan-load-failed": "加载查询计划失败",+ "query-plan-viewer": {+ "copy": {+ "copied": "已复制",+ "failed": "复制失败",+ "plan": "复制计划",+ "query": "复制查询"+ },+ "details": {+ "select-node": "选择节点以查看详情。"+ },+ "diagram": {+ "collapse": "折叠 {{node}} 下的 {{count}} 个节点",+ "cost": "成本 {{cost}}",+ "estimated-rows": "预计 {{count}} 行",+ "expand": "展开 {{node}} 下的 {{count}} 个节点",+ "fit": "适应视图",+ "nodes-hidden": "已隐藏 {{count}} 个节点",+ "plan-cost-share": "占计划成本的 {{share}}",+ "rows": "行数 {{count}}",+ "zoom-in": "放大",+ "zoom-out": "缩小"+ },+ "error": {+ "mssql-empty": "SQL Server 未返回此语句的查询计划。",+ "mssql-invalid": "查询计划不是有效的 XML。需要 SHOWPLAN_XML 输出。",+ "mssql-no-plan": "查询计划 XML 不是至少包含一条语句的 SQL Server showplan。",+ "postgres-empty": "PostgreSQL 未返回此语句的查询计划。",+ "postgres-invalid": "查询计划不是有效的 JSON。需要 EXPLAIN (FORMAT JSON) 输出。",+ "postgres-no-plan": "查询计划 JSON 不包含 \"Plan\" 对象。",+ "spanner-empty": "Spanner 未返回此语句的查询计划。",+ "spanner-emulator": "Spanner 未返回此语句的查询计划。Spanner 模拟器不会为任何语句返回计划,请在 Spanner 实例上执行解释以查看计划。",+ "spanner-invalid": "查询计划不是有效的 JSON。需要 Spanner 查询计划。",+ "spanner-no-plan": "查询计划 JSON 不包含根节点为操作符的 \"planNodes\" 列表。",+ "too-deep": "查询计划嵌套过深,此可视化工具无法绘制。",+ "unreadable": "无法读取此查询计划"+ },+ "grid": {+ "added-cost": "新增成本",+ "added-cost-hint": "此节点在其子节点之上增加的成本;某些引擎还会在此计入输入重复执行的成本,例如嵌套循环下的输入。条形图表示该成本占计划总成本的比例。",+ "caption": "按规划器嵌套顺序排列的计划节点,父节点在子节点之前。",+ "estimated-rows": "预计行数",+ "node": "节点",+ "rows": "行数",+ "total-cost": "总成本",+ "width": "宽度",+ "width-hint": "预计行宽(字节)"+ },+ "highlight": {+ "cost": "成本",+ "cost-hint": "按节点在其子节点之上增加的成本着色",+ "label": "高亮",+ "off": "关闭",+ "off-hint": "不为任何节点卡片着色",+ "rows": "行数",+ "rows-hint": "按预计行数着色"+ },+ "legend": {+ "cost": "每张卡片的条形图表示该节点占计划预计成本的比例",+ "rows": "边的粗细随其子节点预计返回的行数增加"+ },+ "metric": {+ "added-cost": "新增成本",+ "bytes": "{{count}} 字节",+ "estimated-rows": "预计行数",+ "row-width": "行宽",+ "startup-cost": "启动成本",+ "total-cost": "总成本"+ },+ "query": {+ "missing": "此计划未记录对应语句。"+ },+ "summary": {+ "added-cost": "新增成本",+ "cost-by-operation": "按操作统计成本",+ "cost-by-operation-description": "计划中每种节点类型及其总成本。",+ "cost-ranges": "成本范围",+ "cost-ranges-description": "每个节点从启动成本(返回第一行前的成本)延伸到总成本,两者都包含其下所有节点。颜色越深表示承担的计划成本越高。成本并非执行时间表:连接的两个输入会在此重叠,但实际依次执行。",+ "costliest": "成本最高的操作符",+ "costliest-description": "按节点在其子节点之上增加的成本排序。当输入重复执行时(如嵌套循环),某些引擎会将重复成本计入重新运行该输入的节点,而不是输入本身。",+ "count": "数量",+ "estimate-note": "语句已规划但未执行,因此此处所有数据都是优化器估算值,而非测量值。成本单位是任意的,只能在此计划内比较。",+ "estimated-rows-returned": "预计返回行数",+ "no-added-cost": "此计划中没有节点自身增加预计成本。",+ "nodes": "节点",+ "operation": "操作",+ "share": "占比",+ "timeline-node": "{{name}},成本 {{startup}} 到 {{total}},占计划成本的 {{share}}",+ "total-estimated-cost": "预计总成本"+ },+ "tab": {+ "diagram": "图表",+ "grid": "网格",+ "query": "查询",+ "summary": "摘要",+ "text": "文本"+ },+ "totals": {+ "estimated-cost": "预计成本 {{cost}}",+ "nodes": "{{count}} 个节点"+ }+ },"query-time": "查询时间","re-request": "重新申请","recent": "最近",@@ -3402,10 +3504,6 @@"view-detail": "查看详情","view-issue": "查看工单","view-schema-text": "查看文本 Schema",- "visualize-explain": "可视化 Explain",- "visualize-explain-blocked": "查询计划标签页被拦截。请允许本站弹出窗口后重试。",- "visualize-explain-executed": "可视化此计划会再次执行该查询。",- "visualize-explain-failed": "加载查询计划失败","web-socket": {"connection-status": {"connected": "已连接",diff --git a/frontend/src/modules/sql-editor/components/ResultView/QueryPlanResultView.test.tsx b/frontend/src/modules/sql-editor/components/ResultView/QueryPlanResultView.test.tsxnew file mode 100644index 0000000000..9ca41bfe41--- /dev/null+++ b/frontend/src/modules/sql-editor/components/ResultView/QueryPlanResultView.test.tsx@@ -0,0 +1,161 @@+import { render, screen, waitFor } from "@testing-library/react";+import { beforeEach, describe, expect, test, vi } from "vitest";+import { Engine } from "@/types/proto-es/v1/common_pb";+import { QueryPlanResultView } from "./QueryPlanResultView";++vi.mock("react-i18next", () => ({+ useTranslation: () => ({ t: (key: string) => key }),+}));++vi.mock("@/apps/explain-visualizer/QueryPlanView", () => ({+ QueryPlanView: ({+ planSource,+ textPlanSource,+ planQuery,+ translate,+ disallowCopyingData,+ syncSelectionWithHash,+ }: {+ planSource: string;+ textPlanSource?: string;+ planQuery?: string;+ translate: (key: "tab.text") => string;+ disallowCopyingData?: boolean;+ syncSelectionWithHash?: boolean;+ }) => (+ <div+ data-testid="inline-query-plan"+ data-copy-disabled={disallowCopyingData}+ data-hash-sync={syncSelectionWithHash}+ >+ {planQuery}:{planSource}:{textPlanSource}:{translate("tab.text")}+ </div>+ ),+}));++vi.mock("@/apps/explain-visualizer/QueryPlanViewer", () => ({+ formatPlanSource: (source: string) => `formatted:${source}`,+}));++vi.mock("@/components/ui/copy-button", () => ({+ CopyButton: ({ content }: { content: string }) => (+ <button type="button" data-content={content}>+ copy+ </button>+ ),+}));++describe("QueryPlanResultView", () => {+ beforeEach(() => vi.clearAllMocks());++ test("passes the structured and text plans to the inline viewer", () => {+ render(+ <QueryPlanResultView+ engine={Engine.POSTGRES}+ rawPlan="raw plan"+ initialPlan={{ source: "structured plan", statement: "SELECT 1" }}+ disallowCopyingData+ />+ );++ expect(screen.getByTestId("inline-query-plan")).toHaveTextContent(+ "SELECT 1:structured plan:raw plan:sql-editor.query-plan-viewer.tab.text"+ );+ expect(screen.queryByRole("tab")).toBeNull();+ expect(screen.getByTestId("inline-query-plan")).toHaveAttribute(+ "data-copy-disabled",+ "true"+ );+ expect(screen.getByTestId("inline-query-plan")).toHaveAttribute(+ "data-hash-sync",+ "false"+ );+ });++ test("loads a drawable plan immediately and opens on its text tab", async () => {+ const loadPlan = vi.fn().mockResolvedValue({+ source: "structured plan",+ statement: "EXPLAIN SELECT 1",+ });+ render(+ <QueryPlanResultView+ engine={Engine.POSTGRES}+ rawPlan="text plan"+ loadPlan={loadPlan}+ />+ );++ expect(screen.getByText("common.loading")).toBeInTheDocument();+ await waitFor(() =>+ expect(screen.getByTestId("inline-query-plan")).toHaveTextContent(+ "structured plan:text plan:sql-editor.query-plan-viewer.tab.text"+ )+ );+ expect(loadPlan).toHaveBeenCalledTimes(1);+ });++ test("does not reload when only the loader identity changes", async () => {+ const plan = { source: "structured plan", statement: "EXPLAIN SELECT 1" };+ const first = vi.fn().mockResolvedValue(plan);+ const second = vi.fn().mockResolvedValue(plan);+ const { rerender } = render(+ <QueryPlanResultView+ engine={Engine.POSTGRES}+ rawPlan="text plan"+ loadPlan={first}+ />+ );+ await screen.findByTestId("inline-query-plan");++ rerender(+ <QueryPlanResultView+ engine={Engine.POSTGRES}+ rawPlan="text plan"+ loadPlan={second}+ />+ );++ expect(screen.getByTestId("inline-query-plan")).toBeInTheDocument();+ expect(first).toHaveBeenCalledTimes(1);+ expect(second).not.toHaveBeenCalled();+ });++ test("uses a single Plan tab when no picture is available", () => {+ render(<QueryPlanResultView rawPlan="text plan" />);++ expect(screen.getByRole("tab", { name: "common.plan" })).toHaveAttribute(+ "aria-selected",+ "true"+ );+ expect(screen.queryAllByRole("tab")).toHaveLength(1);+ expect(screen.getByText("formatted:text plan")).toBeInTheDocument();+ });++ test("hides copying for a protected text plan", () => {+ render(+ <QueryPlanResultView rawPlan="text plan" disallowCopyingData />+ );++ expect(screen.queryByRole("button", { name: "copy" })).toBeNull();+ expect(screen.getByText("formatted:text plan").parentElement).toHaveClass(+ "select-none"+ );+ });++ test("keeps the text plan visible when the structured plan fails", async () => {+ render(+ <QueryPlanResultView+ engine={Engine.POSTGRES}+ rawPlan="text plan"+ loadPlan={vi.fn().mockResolvedValue(undefined)}+ />+ );++ await waitFor(() =>+ expect(screen.getByRole("alert")).toHaveTextContent(+ "sql-editor.query-plan-load-failed"+ )+ );+ expect(screen.getByText("formatted:text plan")).toBeInTheDocument();+ });+});diff --git a/frontend/src/modules/sql-editor/components/ResultView/QueryPlanResultView.tsx b/frontend/src/modules/sql-editor/components/ResultView/QueryPlanResultView.tsxnew file mode 100644index 0000000000..9357022e85--- /dev/null+++ b/frontend/src/modules/sql-editor/components/ResultView/QueryPlanResultView.tsx@@ -0,0 +1,163 @@+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 { QueryPlanView } from "@/apps/explain-visualizer/QueryPlanView";+import { formatPlanSource } from "@/apps/explain-visualizer/QueryPlanViewer";+import { Alert } from "@/components/ui/alert";+import { CopyButton } from "@/components/ui/copy-button";+import { Tabs, TabsList, TabsPanel, TabsTrigger } from "@/components/ui/tabs";+import { cn } from "@/lib/utils";+import type { VisualizerEngine } from "@/utils/explainToken";++export interface InlineQueryPlan {+ source: string;+ statement: string;+}++type LoadPlan = () => Promise<InlineQueryPlan | undefined>;++interface Props {+ rawPlan: string;+ initialPlan?: InlineQueryPlan;+ engine?: VisualizerEngine;+ loadPlan?: LoadPlan;+ disallowCopyingData?: boolean;+}++interface LoadRequest {+ rawPlan: string;+ promise: ReturnType<LoadPlan>;+}++function TextPlan({+ source,+ disallowCopyingData,+}: {+ source: string;+ disallowCopyingData: boolean;+}) {+ const formatted = useMemo(() => formatPlanSource(source), [source]);+ return (+ <div+ className={cn(+ "flex h-full min-h-0 flex-col",+ disallowCopyingData && "select-none"+ )}+ >+ {disallowCopyingData ? null : (+ <div className="flex shrink-0 justify-end px-4 py-2">+ <CopyButton content={formatted} size="sm" appearance="outline" />+ </div>+ )}+ <pre className="min-h-0 flex-1 overflow-auto px-4 pb-4 font-mono text-xs leading-4 break-words whitespace-pre-wrap text-main">+ {formatted}+ </pre>+ </div>+ );+}++export function QueryPlanResultView({+ rawPlan,+ initialPlan,+ engine,+ loadPlan,+ disallowCopyingData = false,+}: Props) {+ const { t } = useTranslation();+ const [plan, setPlan] = useState(initialPlan);+ const [loading, setLoading] = useState(+ engine !== undefined && !initialPlan && !!loadPlan+ );+ const [failed, setFailed] = useState(false);+ const loadRequest = useRef<LoadRequest | undefined>(undefined);+ // The loader's identity changes with unrelated state (e.g. language); only+ // the plan inputs decide whether to load again.+ const loadPlanRef = useRef(loadPlan);+ loadPlanRef.current = loadPlan;+ const canLoad = !!loadPlan;+ const translatePlan = useCallback<QueryPlanTranslate>(+ (key, values) => t(`sql-editor.query-plan-viewer.${key}`, values),+ [t]+ );++ useEffect(() => {+ let cancelled = false;+ setPlan(initialPlan);+ setFailed(false);+ if (initialPlan || !engine || !canLoad) {+ setLoading(false);+ return;+ }++ setLoading(true);+ if (loadRequest.current?.rawPlan !== rawPlan) {+ loadRequest.current = {+ rawPlan,+ promise: loadPlanRef.current!(),+ };+ }+ void loadRequest.current.promise+ .then((loaded) => {+ if (cancelled) return;+ if (loaded) setPlan(loaded);+ else setFailed(true);+ })+ .catch(() => {+ if (!cancelled) setFailed(true);+ })+ .finally(() => {+ if (!cancelled) setLoading(false);+ });+ return () => {+ cancelled = true;+ };+ }, [engine, initialPlan, canLoad, rawPlan]);++ if (plan && engine) {+ return (+ <QueryPlanView+ engine={engine}+ planSource={plan.source}+ textPlanSource={rawPlan}+ planQuery={plan.statement}+ translate={translatePlan}+ disallowCopyingData={disallowCopyingData}+ syncSelectionWithHash={false}+ />+ );+ }++ if (loading) {+ return (+ <div className="flex min-h-0 flex-1 items-center justify-center gap-2 text-sm text-control-light">+ <LoaderCircle className="size-4 animate-spin" />+ {t("common.loading")}+ </div>+ );+ }++ if (failed) {+ return (+ <div className="flex min-h-0 flex-1 flex-col gap-2 overflow-hidden p-4">+ <Alert variant="error" title={t("sql-editor.query-plan-load-failed")} />+ <TextPlan source={rawPlan} disallowCopyingData={disallowCopyingData} />+ </div>+ );+ }++ return (+ <Tabs value="plan" className="flex min-h-0 flex-1 flex-col">+ <TabsList className="shrink-0 px-2 pt-2">+ <TabsTrigger value="plan">{t("common.plan")}</TabsTrigger>+ </TabsList>++ <TabsPanel+ value="plan"+ className="mt-0 flex min-h-0 flex-1 flex-col overflow-hidden"+ >+ <TextPlan source={rawPlan} disallowCopyingData={disallowCopyingData} />+ </TabsPanel>+ </Tabs>+ );+}diff --git a/frontend/src/modules/sql-editor/components/ResultView/ResultStatusBar.test.tsx b/frontend/src/modules/sql-editor/components/ResultView/ResultStatusBar.test.tsxindex 57f9904e19..d5dfa92a02 100644--- a/frontend/src/modules/sql-editor/components/ResultView/ResultStatusBar.test.tsx+++ b/frontend/src/modules/sql-editor/components/ResultView/ResultStatusBar.test.tsx@@ -1,4 +1,4 @@-import { fireEvent, render, screen } from "@testing-library/react";+import { render, screen } from "@testing-library/react";import { act, cloneElement } from "react";import { beforeEach, describe, expect, test, vi } from "vitest";import type { Database } from "@/types/proto-es/v1/database_service_pb";@@ -120,42 +120,6 @@ describe("ResultStatusBar", () => {);});- test("disables Visualize with the reason", () => {- const onVisualizeExplain = vi.fn();- const { rerender } = render(- <ResultStatusBar- database={database}- statement="EXPLAIN SELECT 1"- queryTime="3 ms"- showVisualizeButton- onVisualizeExplain={onVisualizeExplain}- />- );-- const visualize = screen.getByRole("button", {- name: "sql-editor.visualize-explain",- });- expect(visualize).toBeEnabled();- fireEvent.click(visualize);- expect(onVisualizeExplain).toHaveBeenCalledTimes(1);-- rerender(- <ResultStatusBar- database={database}- statement="EXPLAIN SELECT 1"- queryTime="3 ms"- showVisualizeButton- visualizeDisabledReason="it would run again"- onVisualizeExplain={onVisualizeExplain}- />- );-- expect(visualize).toBeDisabled();- expect(visualize).toHaveAttribute("title", "it would run again");- fireEvent.click(visualize);- expect(onVisualizeExplain).toHaveBeenCalledTimes(1);- });-test("lets the database label shrink while the statement truncates", () => {render(<ResultStatusBar@@ -232,7 +196,6 @@ describe("ResultStatusBar", () => {database={database}statement="EXPLAIN SELECT db.environment as env, db.instance as ins FROM db JOIN project on db.project = project.resource_id WHERE project.resource_id = 'a' AND db.deleted = false"queryTime="6 ms"- showVisualizeButton/>);diff --git a/frontend/src/modules/sql-editor/components/ResultView/ResultStatusBar.tsx b/frontend/src/modules/sql-editor/components/ResultView/ResultStatusBar.tsxindex b99085e012..4f28555c34 100644--- a/frontend/src/modules/sql-editor/components/ResultView/ResultStatusBar.tsx+++ b/frontend/src/modules/sql-editor/components/ResultView/ResultStatusBar.tsx@@ -1,10 +1,8 @@import { useLayoutEffect, useRef, useState } from "react";import { useTranslation } from "react-i18next";import { DatabaseTargetDisplay } from "@/components/DatabaseTargetDisplay";-import { Button } from "@/components/ui/button";import { CopyButton } from "@/components/ui/copy-button";import { EllipsisText } from "@/components/ui/ellipsis-text";-import { Tooltip } from "@/components/ui/tooltip";import { cn } from "@/lib/utils";import type { Database } from "@/types/proto-es/v1/database_service_pb";import type { QueryResult } from "@/types/proto-es/v1/sql_service_pb";@@ -36,18 +34,12 @@ type ResultStatusBarProps = Readonly<{database: Database;statement: string;queryTime: string;- showVisualizeButton?: boolean;- visualizeDisabledReason?: string;- onVisualizeExplain?: () => void;}>;export function ResultStatusBar({database,statement,queryTime,- showVisualizeButton = false,- visualizeDisabledReason,- onVisualizeExplain,}: ResultStatusBarProps) {const { t } = useTranslation();const hasStatement = statement.trim() !== "";@@ -138,19 +130,6 @@ export function ResultStatusBar({</div></div><div className="flex shrink-0 items-center gap-x-2">- {showVisualizeButton && (- <Tooltip content={visualizeDisabledReason}>- <Button- size="sm"- appearance="link"- className="h-auto px-0 text-xs"- disabled={!!visualizeDisabledReason}- onClick={onVisualizeExplain}- >- {t("sql-editor.visualize-explain")}- </Button>- </Tooltip>- )}<span>{t("sql-editor.query-time")}: {queryTime}</span>diff --git a/frontend/src/modules/sql-editor/components/ResultView/SingleResultView.test.tsx b/frontend/src/modules/sql-editor/components/ResultView/SingleResultView.test.tsxindex 79e46cbf3b..fb2b153cea 100644--- a/frontend/src/modules/sql-editor/components/ResultView/SingleResultView.test.tsx+++ b/frontend/src/modules/sql-editor/components/ResultView/SingleResultView.test.tsx@@ -1,6 +1,6 @@import { create } from "@bufbuild/protobuf";import { fireEvent, render, screen, waitFor } from "@testing-library/react";-import { useEffect } from "react";+import { useEffect, useState } from "react";import { beforeEach, describe, expect, test, vi } from "vitest";import type { SQLEditorQueryParams } from "@/types";import { Engine } from "@/types/proto-es/v1/common_pb";@@ -100,11 +100,7 @@ vi.mock("@/components/monaco/MonacoEditor", () => ({},}));-const { createExplainToken, notify, runQuery } = vi.hoisted(() => ({- createExplainToken: vi.fn(() => "explain-token"),- notify: vi.fn(),- runQuery: vi.fn(),-}));+const { runQuery } = vi.hoisted(() => ({ runQuery: vi.fn() }));vi.mock("@/hooks/useExecuteSQL", () => ({useExecuteSQL: () => ({ runQuery }),@@ -205,15 +201,10 @@ vi.mock("@/modules/sql-editor/store/tab", () => ({vi.mock("@/stores/app", () => ({useAppStore: {- getState: () => ({ notify }),+ getState: () => ({}),},}));-vi.mock("@/utils/explainToken", async (importOriginal) => ({- ...(await importOriginal<typeof import("@/utils/explainToken")>()),- createExplainToken,-}));-vi.mock("@/utils/util", () => ({isNullOrUndefined: (value: unknown) => value === null || value === undefined,}));@@ -258,28 +249,42 @@ vi.mock("./ErrorView", () => ({vi.mock("./ResultStatusBar", () => ({formatQueryTime: () => "-",- ResultStatusBar: ({- showVisualizeButton,- visualizeDisabledReason,- onVisualizeExplain,+ ResultStatusBar: () => <div data-testid="result-status" />,+}));++vi.mock("./QueryPlanResultView", () => ({+ QueryPlanResultView: ({+ rawPlan,+ initialPlan,+ loadPlan,+ disallowCopyingData,}: {- showVisualizeButton?: boolean;- visualizeDisabledReason?: string;- onVisualizeExplain?: () => void;- }) => (- <div data-testid="result-status">- {showVisualizeButton ? (- <button- type="button"- disabled={!!visualizeDisabledReason}- title={visualizeDisabledReason}- onClick={onVisualizeExplain}- >- visualize-explain- </button>- ) : null}- </div>- ),+ rawPlan: string;+ initialPlan?: { source: string; statement: string };+ loadPlan?: () => Promise<+ { source: string; statement: string } | undefined+ >;+ disallowCopyingData?: boolean;+ }) => {+ const [plan, setPlan] = useState(initialPlan);+ return (+ <div+ data-testid="query-plan-result"+ data-copy-disabled={disallowCopyingData}+ >+ <span data-testid="raw-plan">{rawPlan}</span>+ {plan ? <span data-testid="inline-plan">{plan.source}</span> : null}+ {loadPlan ? (+ <button+ type="button"+ onClick={() => void loadPlan().then(setPlan)}+ >+ common.plan+ </button>+ ) : null}+ </div>+ );+ },}));vi.mock("./SelectionCopyTooltips", () => ({@@ -627,13 +632,10 @@ const textPlanResult = (statement: string) =>describe("SingleResultView explain visualizer", () => {beforeEach(() => {- createExplainToken.mockClear();- notify.mockClear();runQuery.mockReset();});test("PostgreSQL asks for the JSON plan instead of reusing the text plan", async () => {- const openSpy = vi.spyOn(window, "open").mockReturnValue(null);const planJSON = '[{"Plan": {"Node Type": "Seq Scan"}}]';runQuery.mockImplementation(async (@@ -692,9 +694,12 @@ describe("SingleResultView explain visualizer", () => {/>);- fireEvent.click(screen.getByText("visualize-explain"));+ expect(screen.getByTestId("raw-plan")).toHaveTextContent("Seq Scan on t");+ fireEvent.click(screen.getByText("common.plan"));- await waitFor(() => expect(openSpy).toHaveBeenCalled());+ await waitFor(() =>+ expect(screen.getByTestId("inline-plan")).toHaveTextContent(planJSON)+ );expect(runQuery).toHaveBeenCalledTimes(1);expect(runQuery.mock.calls[0][1].params.queryOption?.explainFormat@@ -703,20 +708,9 @@ describe("SingleResultView explain visualizer", () => {expect(runQuery.mock.calls[0][1].params.statement).toBe("EXPLAIN SELECT 1");- expect(createExplainToken).toHaveBeenCalledWith({- statement: "EXPLAIN (FORMAT JSON) SELECT 1",- explain: planJSON,- engine: Engine.POSTGRES,- });- expect(openSpy).toHaveBeenCalledWith(- "/explain-visualizer.html?token=explain-token",- "_blank"- );- openSpy.mockRestore();});test("re-runs only the statement for the tab the user clicked", async () => {- const openSpy = vi.spyOn(window, "open").mockReturnValue(null);runQuery.mockImplementation(async (_database: unknown, context: { resultSet?: { results: unknown[] } }) => {const plan = (name: string) =>@@ -768,82 +762,18 @@ describe("SingleResultView explain visualizer", () => {/>);- fireEvent.click(screen.getByText("visualize-explain"));+ fireEvent.click(screen.getByText("common.plan"));- await waitFor(() => expect(createExplainToken).toHaveBeenCalled());+ await waitFor(() => expect(runQuery).toHaveBeenCalled());expect(runQuery.mock.calls[0][1].params.statement).toBe("second");- expect(createExplainToken).toHaveBeenCalledWith({- statement: "second",- explain: "plan of second",- engine: Engine.POSTGRES,- });- openSpy.mockRestore();- });-- test("reports a blocked pop-up instead of doing nothing", async () => {- const openSpy = vi.spyOn(window, "open").mockReturnValue(null);- runQuery.mockImplementation(- async (_database: unknown, context: { resultSet?: { results: unknown[] } }) => {- context.resultSet = {- results: [- create(QueryResultSchema, {- statement: "SELECT 1",- rows: [- create(QueryRowSchema, {- values: [- create(RowValueSchema, {- kind: { case: "stringValue", value: "[]" },- }),- ],- }),- ],- }),- ],- };- }- );-- render(- <SingleResultView- disallowCopyingData={false}- params={{ ...params, engine: Engine.POSTGRES, explain: true }}- database={databaseForEngine(Engine.POSTGRES)}- result={create(QueryResultSchema, {- columnNames: ["QUERY PLAN"],- columnTypeNames: ["TEXT"],- statement: "SELECT 1",- queryPlan: create(QueryResult_QueryPlanSchema, {- format: QueryOption_ExplainFormat.TEXT,- }),- rows: [- create(QueryRowSchema, {- values: [- create(RowValueSchema, {- kind: { case: "stringValue", value: "Seq Scan on t" },- }),- ],- }),- ],- })}- showExport={false}- />+ expect(screen.getByTestId("inline-plan")).toHaveTextContent(+ "plan of second");-- fireEvent.click(screen.getByText("visualize-explain"));-- await waitFor(() => expect(notify).toHaveBeenCalled());- expect(notify.mock.calls[0][0].title).toBe(- "sql-editor.visualize-explain-blocked"- );- openSpy.mockRestore();});test.each([[Engine.MSSQL, QueryOption_ExplainFormat.XML, "<ShowPlanXML/>"]])("asks engine %s for the plan in the format its visualizer reads",async (engine, explainFormat, plan) => {- const openSpy = vi- .spyOn(window, "open")- .mockReturnValue({} as Window);runQuery.mockImplementation(async (_database: unknown,@@ -893,24 +823,18 @@ describe("SingleResultView explain visualizer", () => {/>);- fireEvent.click(screen.getByText("visualize-explain"));+ fireEvent.click(screen.getByText("common.plan"));- await waitFor(() => expect(openSpy).toHaveBeenCalled());+ await waitFor(() =>+ expect(screen.getByTestId("inline-plan")).toHaveTextContent(plan)+ );expect(runQuery.mock.calls[0][1].params.queryOption?.explainFormat).toBe(explainFormat);- expect(createExplainToken).toHaveBeenCalledWith({- statement: "SELECT 1",- explain: plan,- engine,- });- expect(notify).not.toHaveBeenCalled();- openSpy.mockRestore();});test("Spanner hands over the plan already in the result", async () => {- const openSpy = vi.spyOn(window, "open").mockReturnValue({} as Window);const plan = '{"planNodes":[]}';render(@@ -939,20 +863,11 @@ describe("SingleResultView explain visualizer", () => {/>);- fireEvent.click(screen.getByText("visualize-explain"));-- await waitFor(() => expect(openSpy).toHaveBeenCalled());expect(runQuery).not.toHaveBeenCalled();- expect(createExplainToken).toHaveBeenCalledWith({- statement: "SELECT 1",- explain: plan,- engine: Engine.SPANNER,- });- openSpy.mockRestore();+ expect(screen.getByTestId("inline-plan")).toHaveTextContent(plan);});test("uses a typed structured plan without running another query", async () => {- const openSpy = vi.spyOn(window, "open").mockReturnValue({} as Window);const plan = '[{"Plan":{"Node Type":"Result"}}]';render(@@ -985,19 +900,11 @@ describe("SingleResultView explain visualizer", () => {/>);- fireEvent.click(screen.getByText("visualize-explain"));-- await waitFor(() => expect(openSpy).toHaveBeenCalled());expect(runQuery).not.toHaveBeenCalled();- expect(createExplainToken).toHaveBeenCalledWith({- statement: "EXPLAIN (FORMAT JSON) SELECT 1",- explain: plan,- engine: Engine.POSTGRES,- });- openSpy.mockRestore();+ expect(screen.getByTestId("inline-plan")).toHaveTextContent(plan);});- test("disables Visualize when reformatting would execute the query again", () => {+ test("does not offer a re-explain after the plan executed the query", () => {render(<SingleResultViewdisallowCopyingData={false}@@ -1021,12 +928,9 @@ describe("SingleResultView explain visualizer", () => {/>);- const button = screen.getByText("visualize-explain");- expect(button).toBeDisabled();- expect(button).toHaveAttribute(- "title",- "sql-editor.visualize-explain-executed"- );+ expect(screen.getByTestId("query-plan-result")).toBeInTheDocument();+ expect(screen.queryByText("common.plan")).toBeNull();+ expect(runQuery).not.toHaveBeenCalled();});test("does not replay after a result that was not a plan", () => {@@ -1045,11 +949,11 @@ describe("SingleResultView explain visualizer", () => {/>);- expect(screen.queryByText("visualize-explain")).toBeNull();+ expect(screen.getByTestId("query-plan-result")).toBeInTheDocument();+ expect(screen.queryByText("common.plan")).toBeNull();});test("ignores later statements when replaying an earlier plan", async () => {- const openSpy = vi.spyOn(window, "open").mockReturnValue({} as Window);const current = textPlanResult("EXPLAIN SELECT 1");const later = create(QueryResultSchema, { statement: "SET x = 1" });runQuery.mockImplementation(@@ -1089,19 +993,18 @@ describe("SingleResultView explain visualizer", () => {/>);- fireEvent.click(screen.getByText("visualize-explain"));+ fireEvent.click(screen.getByText("common.plan"));- await waitFor(() => expect(openSpy).toHaveBeenCalled());+ await waitFor(() => expect(runQuery).toHaveBeenCalled());expect(runQuery.mock.calls[0][1].params.statement).toBe("EXPLAIN SELECT 1");- openSpy.mockRestore();});- test("offers no visualizer for an engine it cannot draw", () => {+ test("shows a text plan inline for an engine it cannot draw", () => {render(<SingleResultView- disallowCopyingData={false}+ disallowCopyingDataparams={{ ...params, engine: Engine.MYSQL, explain: true }}database={databaseForEngine(Engine.MYSQL)}result={create(QueryResultSchema, {@@ -1124,6 +1027,83 @@ describe("SingleResultView explain visualizer", () => {/>);- expect(screen.queryByText("visualize-explain")).toBeNull();+ expect(screen.getByTestId("query-plan-result")).toBeInTheDocument();+ expect(screen.getByTestId("query-plan-result")).toHaveAttribute(+ "data-copy-disabled",+ "true"+ );+ expect(screen.getByTestId("raw-plan")).toHaveTextContent(+ "-> Table scan on t"+ );+ expect(runQuery).not.toHaveBeenCalled();+ });++ test("keeps multi-column explain output in the result table", () => {+ render(+ <SingleResultView+ disallowCopyingData={false}+ params={{ ...params, engine: Engine.MYSQL, explain: true }}+ database={databaseForEngine(Engine.MYSQL)}+ result={create(QueryResultSchema, {+ columnNames: ["table", "type"],+ columnTypeNames: ["TEXT", "TEXT"],+ statement: "EXPLAIN SELECT * FROM t",+ queryPlan: create(QueryResult_QueryPlanSchema, {+ format: QueryOption_ExplainFormat.TEXT,+ }),+ rows: [+ create(QueryRowSchema, {+ values: [+ create(RowValueSchema, {+ kind: { case: "stringValue", value: "t" },+ }),+ create(RowValueSchema, {+ kind: { case: "stringValue", value: "ALL" },+ }),+ ],+ }),+ ],+ })}+ showExport={false}+ />+ );++ expect(screen.queryByTestId("query-plan-result")).toBeNull();+ expect(screen.getByTestId("result-table")).toHaveTextContent(+ "table,typet,ALL"+ );+ });++ test("SQL Server multi-column SHOWPLAN_ALL still opens the visualizer", () => {+ render(+ <SingleResultView+ disallowCopyingData={false}+ params={{ ...params, engine: Engine.MSSQL, explain: true }}+ database={databaseForEngine(Engine.MSSQL)}+ result={create(QueryResultSchema, {+ columnNames: ["StmtText", "EstimateRows"],+ columnTypeNames: ["TEXT", "TEXT"],+ statement: "SELECT 1",+ queryPlan: create(QueryResult_QueryPlanSchema, {+ format: QueryOption_ExplainFormat.TEXT,+ }),+ rows: [+ create(QueryRowSchema, {+ values: [+ create(RowValueSchema, {+ kind: { case: "stringValue", value: "Clustered Index Scan" },+ }),+ create(RowValueSchema, {+ kind: { case: "stringValue", value: "1" },+ }),+ ],+ }),+ ],+ })}+ showExport={false}+ />+ );++ expect(screen.getByTestId("query-plan-result")).toBeInTheDocument();});});diff --git a/frontend/src/modules/sql-editor/components/ResultView/SingleResultView.tsx b/frontend/src/modules/sql-editor/components/ResultView/SingleResultView.tsxindex e47d6c80b3..630529e4a4 100644--- a/frontend/src/modules/sql-editor/components/ResultView/SingleResultView.tsx+++ b/frontend/src/modules/sql-editor/components/ResultView/SingleResultView.tsx@@ -36,7 +36,6 @@ import { cn } from "@/lib/utils";import { useSQLEditorQueryDataPolicy } from "@/modules/sql-editor/hooks/useSQLEditorState";import { useSQLEditorEditorState } from "@/modules/sql-editor/store/editor";import { useSQLEditorTabState } from "@/modules/sql-editor/store/tab";-import { useAppStore } from "@/stores/app";import type {SQLEditorDatabaseQueryContext,SQLEditorQueryParams,@@ -49,7 +48,6 @@ import {type QueryResult,} from "@/types/proto-es/v1/sql_service_pb";import {- createExplainToken,isVisualizerEngine,VISUALIZER_EXPLAIN_FORMATS,type VisualizerEngine,@@ -70,6 +68,10 @@ import { DetailPanel } from "./DetailPanel";import { DocumentJSONView } from "./DocumentJSONView";import { EmptyView } from "./EmptyView";import { ErrorView } from "./ErrorView";+import {+ type InlineQueryPlan,+ QueryPlanResultView,+} from "./QueryPlanResultView";import { formatQueryTime, ResultStatusBar } from "./ResultStatusBar";import { SelectionCopyTooltips } from "./SelectionCopyTooltips";import { TextSearchControl } from "./TextSearchControl";@@ -404,60 +406,33 @@ function SingleResultViewInner({isVisualizerEngine(engine) &&plan?.format ===QueryOption_ExplainFormat[VISUALIZER_EXPLAIN_FORMATS[engine]];+ const resultPlan = useMemo(() => getInlineQueryPlan(result), [result]);// Replaying this statement is safe only when every earlier statement was// itself a non-executing plan and could not change session state.const canReplay =isVisualizerEngine(engine) &&plan?.format === QueryOption_ExplainFormat.TEXT &&+ !plan.executed &&results.slice(0, resultIndex).every((earlier) => earlier.queryPlan && !earlier.queryPlan.executed);- const showVisualizeButton = planInRows || canReplay;- const visualizeDisabledReason =- !planInRows && plan?.executed- ? t("sql-editor.visualize-explain-executed")- : undefined;-- const visualizeExplain = async () => {- if (!isVisualizerEngine(engine)) return;- try {- const token = planInRows- ? getExplainTokenFromResult(result, engine)- : await getExplainToken(+ // Multi-column plans (SQL Server SHOWPLAN_ALL) keep their table unless the+ // XML plan can be loaded for the visualizer.+ const showInlinePlan =+ !!plan && (result.columnNames.length === 1 || canReplay);+ const loadPlan = useCallback(+ () =>+ isVisualizerEngine(engine)+ ? getInlineQueryPlanForStatement(database,params,result.statement,runQuery,engine- );- if (!token) {- // The plan is fetched by a second query, so a failure here is invisible- // unless we say so — the button would otherwise do nothing.- useAppStore.getState().notify({- module: "bytebase",- style: "CRITICAL",- title: t("sql-editor.visualize-explain-failed"),- });- return;- }- // A blocked popup returns null rather than throwing, and the wait for the- // plan can outlast the click's user activation, so say so instead of- // leaving the button looking dead.- if (!window.open(`/explain-visualizer.html?token=${token}`, "_blank")) {- useAppStore.getState().notify({- module: "bytebase",- style: "CRITICAL",- title: t("sql-editor.visualize-explain-blocked"),- });- }- } catch {- useAppStore.getState().notify({- module: "bytebase",- style: "CRITICAL",- title: t("sql-editor.visualize-explain-failed"),- });- }- };+ )+ : Promise.resolve(undefined),+ [database, engine, params, result.statement, runQuery]+ );const queryTime = formatQueryTime(result.latency);@@ -525,7 +500,32 @@ function SingleResultViewInner({</>)}- {viewMode === "RESULT" && (+ {viewMode === "RESULT" && showInlinePlan && (+ <>+ <div+ className={cn(+ "flex flex-col",+ compact ? "h-80 overflow-hidden" : "flex-1 min-h-0"+ )}+ >+ <QueryPlanResultView+ key={`${database.name}\n${engine}\n${result.statement}`}+ rawPlan={resultPlan?.source ?? ""}+ initialPlan={planInRows ? resultPlan : undefined}+ engine={isVisualizerEngine(engine) ? engine : undefined}+ loadPlan={canReplay ? loadPlan : undefined}+ disallowCopyingData={disallowCopyingData}+ />+ </div>+ <ResultStatusBar+ database={database}+ statement={result.statement ?? ""}+ queryTime={queryTime}+ />+ </>+ )}++ {viewMode === "RESULT" && !showInlinePlan && (<>{result.error && (<Alert variant="error" className="w-full mb-2">@@ -770,14 +770,11 @@ function SingleResultViewInner({database={database}statement={result.statement ?? ""}queryTime={queryTime}- showVisualizeButton={showVisualizeButton}- visualizeDisabledReason={visualizeDisabledReason}- onVisualizeExplain={visualizeExplain}/></>)}- {!isJSONView && (+ {!isJSONView && !showInlinePlan && (<DetailPanelrows={rows}columns={columns}@@ -833,27 +830,28 @@ function DatabaseInfo({ database }: { database: Database }) {);}-function getExplainTokenFromResult(- result: QueryResult,- engine: Engine-): string | undefined {+function getInlineQueryPlan(result: QueryResult): InlineQueryPlan | undefined {const { statement } = result;if (!statement) return undefined;const lines = result.rows.map((row) =>row.values.map((value) => String(extractSQLRowValuePlain(value))));- const explain = lines.map((line) => line[0]).join("\n");- if (!explain) return undefined;- return createExplainToken({ statement, explain, engine });+ // 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 { statement, source };}-async function getExplainToken(+async function getInlineQueryPlanForStatement(database: Database,params: SQLEditorQueryParams,statement: string,runQuery: ReturnType<typeof useExecuteSQL>["runQuery"],engine: VisualizerEngine-): Promise<string | undefined> {+): Promise<InlineQueryPlan | undefined> {if (!statement) return undefined;const explainFormat =QueryOption_ExplainFormat[VISUALIZER_EXPLAIN_FORMATS[engine]];@@ -870,5 +868,5 @@ async function getExplainToken(await runQuery(database, context);const result = context.resultSet?.results[0];if (!result) return undefined;- return getExplainTokenFromResult(result, engine);+ return getInlineQueryPlan(result);}diff --git a/frontend/src/utils/explainToken.ts b/frontend/src/utils/explainToken.tsindex dfd753e4d3..dc524b0b89 100644--- a/frontend/src/utils/explainToken.ts+++ b/frontend/src/utils/explainToken.ts@@ -59,6 +59,8 @@ const dropPreviousExplains = () => {for (const key of stale) sessionStorage.removeItem(key);};+// Used only by the legacy standalone entry; the SQL Editor passes plans+// directly to QueryPlanView.export const createExplainToken = ({statement,explain,