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): offer Plan in the result pane's view switch (#21646)
Danny Xu4d1401f2879f
diff --git a/docs/design/query-plan-visualizer.md b/docs/design/query-plan-visualizer.mdindex e901feac4f..6d303442af 100644--- a/docs/design/query-plan-visualizer.md+++ b/docs/design/query-plan-visualizer.md@@ -63,7 +63,7 @@ context first.| Trigger | Where the control is | Journey | Executes? ||---|---|---|---|-| Click the **Plan** tab on a result | in the result pane, next to Text | 1, 2 | no |+| Choose **Plan** in the result's view switch | the result pane, beside Table and Vertical | 1, 2 | no || Type `EXPLAIN …`, press **Run** (`Ctrl/Cmd+Enter`) | the editor | 1, 2 | as typed || Choose **Explain**, press `Ctrl/Cmd+E`, or right-click → Explain | Run button's dropdown; keyboard; editor context menu | 3 | **no** || Choose **Explain analyze** | Run button's dropdown | 1, 2 | **yes** |@@ -77,7 +77,7 @@ sets session state, such as `SET search_path = tenant; SELECT * FROM orders`,cannot be explained statement by statement. `EXPLAIN SET …` is not valid, andskipping the `SET` would plan the next statement against the wrong search path.The actions say so rather than explaining part of the script — the same rule-§3.3 applies to the Plan tab, stated once and enforced on both paths.+§3.3 applies to the Plan view, stated once and enforced on both paths.They are two actions, not one, because the difference is whether your query runs.pgAdmin splits them the same way (F7 / Shift+F7). **Explain** never executes:@@ -173,8 +173,9 @@ what the user asked to see, and no SQL editor we surveyed rewrites a typed`EXPLAIN`. Supabase tried the nearest thing — parsing the text plan — and deletedit seven months later for non-use.-**Not every result has a Plan tab.** DDL and anything else the engine cannot-explain gets none — an empty tab is worse than no tab.+**Not every result offers Plan.** DDL and anything else the engine cannot+explain gets no Plan option in its view switch — a Plan that cannot plan is+worse than none.A query killed by the workspace timeout is the case worth having: no measuredplan can exist, but an estimate is usually the answer to why it died. It has a@@ -183,7 +184,7 @@ yields nil (`sql_service.go:999`), `Query` turns that into an RPC error(`:451-456`), and the client records an empty result set — so there is noexecuted statement to explain, and explaining the user's text instead would plana differently-limited query, which is what §3.4 rejects. The timeout response-has to carry the executed statement first. Until it does, no Plan tab here+has to carry the executed statement first. Until it does, no Plan hereeither.**PostgreSQL XML is text until someone writes the parser.** `parsePostgresPlan`@@ -205,19 +206,25 @@ rewriting anyone's statement.### 3.3 Reading the plan-**A tab in the result pane, not a side drawer.** No product surveyed uses a-drawer. BigQuery, Spanner Studio, SSMS, DBeaver, DataGrip, pgAdmin and Navicat-all put the plan in a tab beside the results; BigQuery and Spanner Studio add a-full-screen control on that pane, which is what our Maximize already is.-Snowflake and Databricks escalate to a full page instead, which we rejected in-§4. So: a **Plan** tab beside the results, **Text** one click away — every plan-viewer we checked keeps the raw text next to the picture, so Text is not-optional.+**A view of the result, in the result pane: not a side drawer, not a tab+row.** No product surveyed uses a drawer. BigQuery, Spanner Studio, SSMS,+DBeaver, DataGrip, pgAdmin and Navicat all put the plan beside the results, as+a tab; BigQuery and Spanner Studio add a full-screen control on that pane,+which is what our Maximize already is. Snowflake and Databricks escalate to a+full page instead, which we rejected in §4. Their tabs exist because the plan+came back with the job. On our engines the plan is fetched on demand, so a+permanent tab promises something that is not there until clicked, and the+result toolbar is already full (§4). So: **Plan** is one more option in the+result pane's view switch, beside Table and Vertical — the plan is another way+of looking at this result, which is what it is — and **Text** is one click+away; every plan viewer we checked keeps the raw text next to the picture, so+Text is not optional. The explain action is that one icon: where the engine+cannot explain, the option is absent; where the user lacks the permission, it+is disabled with the reason (§3.5).**Text appears only when Plan has a picture.** On the nine engines we cannot draw-(§3.4), the plan *is* text, so a second text tab would say the same thing twice-and leave the reader asking why the Plan tab has no plan in it. One tab there,-named Plan, containing the plan.+(§3.4), the plan *is* text, so a second text view would say the same thing+twice. There, Plan shows the plan as text, and nothing else.1. **Summary panel** — the most expensive operators, ranked; click one and thegraph jumps to it. Snowflake and Databricks lead with this, because the ranked@@ -270,15 +277,16 @@ tab, and Query duplicates the editor they came from.| Grid | **Table** || Summary (tab, only when the plan has costs) | **always-visible panel** beside the graph || Raw plan | the **Text** tab, beside Plan |-| Query | becomes a **View SQL** disclosure in the Plan tab |+| Query | becomes a **View SQL** disclosure in the Plan view |View SQL is not a tooltip. The editor may have moved on since the result wasproduced, so the statement a plan belongs to has to be readable somewhere — andselectable and copyable, which a hover tooltip is not, least of all for a longstatement.-Plan or Text is remembered per editor tab, like the result pane's height, so-comparing two runs does not mean re-selecting Plan each time (CUJ 2).+The view switch's choice — Table, Vertical, Plan or Text — is remembered per+editor tab, like the result pane's height, so comparing two runs does not mean+re-selecting Plan each time (CUJ 2).CUJ 2 only works on a plan captured **before** the change. A result tab holds theplan it already fetched, so an earlier run keeps its baseline; opening Plan on@@ -297,7 +305,11 @@ SELECT * FROM orders`, the second statement's plan depends on the first, and weexplain statements one at a time on a connection that never saw the `SET`. Thedriver would also prefix a split script blindly, producing an invalid`EXPLAIN SET …`. Temporary tables and SQL Server's `USE` break the same way. So-when a script establishes session state, the statements after it get no Plan tab.+when a script establishes session state, the statements after it get no Plan+option. A result cannot show whether its statement did —+`SELECT set_config('search_path', …)` returns a row like any read — so Plan is+offered only where every earlier statement of the run was a plan that did not+execute.Reproducing session context is a larger feature than this design, and a plan forthe wrong table is worse than no plan.@@ -322,7 +334,7 @@ regression.### 3.4 Engine differences-| Engine | Plan tab on a result | Picture | Explain analyze |+| Engine | Plan on a result | Picture | Explain analyze ||---|---|---|---|| **PostgreSQL** | one `Query()`, on demand, cached | graph | yes — `EXPLAIN (ANALYZE, FORMAT JSON)` || **SQL Server** | one `Query()`, on demand, cached | graph | yes — `SET STATISTICS XML` |@@ -348,9 +360,12 @@ ran. SQL Server and Spanner did not until[#21481](https://github.com/bytebase/bytebase/pull/21481); the timed-out casestill waits on the timeout response carrying its statement.-**Say which one it is, in words.** Measured and estimated carry a badge, and an-estimated plan says *"A new plan, made just now. It may differ from the plan that-ran."* A timestamp alone is not enough: the plan sits in the Plan tab of the+**Say which one it is.** Measured and estimated carry a one-word badge at the+end of the viewer's tab row, and the estimated badge's tooltip says *"A new+plan, made just now. It may differ from the plan that ran."* The words are a+hover away rather than a line of their own because vertical space in the result+pane is scarce, and the pane already says "estimated" in the diagram header and+the summary. A timestamp alone is not enough: the plan sits in the Plan view of theresult of the query that was slow, so everything about its placement says itexplains that run. It may not — PostgreSQL chooses a plan from currentstatistics, and if the slow run was caused by stale statistics that have since@@ -376,14 +391,14 @@ would fail queries the user is authorized to run. Profiling only when askedrequires a control that says so before the run, which is a second explain actionon the Run button for a case **Explain analyze** already covers. Out of scope.-Once the Plan tab matches the pop-up page, delete the page, its token hand-off+Once the Plan view matches the pop-up page, delete the page, its token hand-offand the old link.### 3.5 Permissions, masking and limits**Explain is its own permission** — `bb.sql.explain`, not `bb.sql.select`(`sql_service.go:1480`) — so a user can be allowed to run a query and not to plan-it. For them the Plan tab is **disabled with the reason shown**, not hidden:+it. For them the Plan option is **disabled with the reason shown**, not hidden:hiding it leaves them unable to tell the capability exists or what to ask anadmin for.@@ -405,8 +420,8 @@ histogram-derived boundary values, and any engine's predicates and estimates saysomething about the distribution behind them. So the justification is not "thereis nothing sensitive in here" — it is that reading a plan is a distinct,deliberately granted capability, `bb.sql.explain`, held separately from the-permission to read rows. That boundary applies identically to the Plan tab, the-Text tab, Copy plan, and any plan attached to an ordinary run (§3.4): all of them+permission to read rows. That boundary applies identically to the Plan view, the+Text view, Copy plan, and any plan attached to an ordinary run (§3.4): all of themare the same capability, so none of them may be reachable without it.Two ways that boundary leaked, both in `checkDatabaseAccess`@@ -450,7 +465,7 @@ before. Every query span now carries the tables its statement touches, whateverthe statement type, so this is the only case left to that single check.**Slow and large plans.** The on-demand call can take as long as any query: show-a skeleton, allow cancel, time out rather than hang. Past a node cap the Plan tab+a skeleton, allow cancel, time out rather than hang. Past a node cap the Plan viewfalls back to Text instead of drawing something unreadable — SSMS degrades thesame way, at 2 MB.@@ -465,6 +480,11 @@ rejects shows that error in the tab, like any failed query.- **Keep the pop-up tab.** Only Snowflake opens one, and theirs is a permanentpage with a link, not a throwaway that loses the database, theme and language.+- **A Plan tab beside every result.** The warehouses have one because the plan+ came back with the job. On our engines it is fetched on demand, the journey's+ frequency is unmeasured, and the result toolbar already holds search, the+ view switch, the row count, Copy and Export. One icon in the view switch+ costs one icon if nobody uses it; a tab row costs every result.- **Explain button on the toolbar.** SSMS, pgAdmin and DBeaver do this; none ofthe four does. Permanent space for the rarest journey.- **Parse the text plan.** PostgreSQL's text output has no escaping, so a string@@ -516,19 +536,24 @@ Checked against `main` on 2026-10-22.([#21619](https://github.com/bytebase/bytebase/pull/21619)); explain isrequired on every database the statement references, with a database inanother project failing closed, and a typed `EXPLAIN ANALYZE` needs the inner- statement's permission as well. What remains of §3.5: SQL Server's- `SET STATISTICS XML ON` route still passes on `bb.sql.select` alone, and the- Plan tab items — disabled with the reason shown, skeleton and cancel, the- node cap — ride with item 1.+ statement's permission as well+ ([#21642](https://github.com/bytebase/bytebase/pull/21642)); the Plan option+ is disabled with the reason, a load can be cancelled, and a plan past the+ node cap is shown as text+ ([#21646](https://github.com/bytebase/bytebase/pull/21646)). What remains+ of §3.5: SQL Server's `SET STATISTICS XML ON` route still passes on+ `bb.sql.select` alone.+- §3.2/§3.3 — Plan in the result pane's view switch on an ordinary result,+ planning the executed statement, with the estimate wording from §3.4, the+ choice remembered per editor tab+ ([#21646](https://github.com/bytebase/bytebase/pull/21646)).**Not yet, in the order to do them**-1. §3.2/§3.3 — the Plan tab on an ordinary result, planning the executed- statement, with the estimate wording from §3.4.-2. §3.1 — Explain and Explain analyze in the Run dropdown, planning the limited+1. §3.1 — Explain and Explain analyze in the Run dropdown, planning the limitedstatement; today every driver's explain path skips the limit.-3. §3.3 — the reading changes: summary panel always visible, graph opening on+2. §3.3 — the reading changes: summary panel always visible, graph opening onthe costliest operator, View SQL, warning relevance, measured plans withplanned vs actual rows, cost share on the tab label.-4. §3.4 — delete the pop-up page (`frontend/explain-visualizer.html`), which+3. §3.4 — delete the pop-up page (`frontend/explain-visualizer.html`), whichnothing links to any more.diff --git a/frontend/src/apps/explain-visualizer/QueryPlanView.tsx b/frontend/src/apps/explain-visualizer/QueryPlanView.tsxindex 39d6ace689..08863bec84 100644--- a/frontend/src/apps/explain-visualizer/QueryPlanView.tsx+++ b/frontend/src/apps/explain-visualizer/QueryPlanView.tsx@@ -1,4 +1,4 @@-import { useMemo } from "react";+import { type ReactNode, useMemo } from "react";import { Alert } from "@/components/ui/alert";import { cn } from "@/lib/utils";import { Engine } from "@/types/proto-es/v1/common_pb";@@ -15,7 +15,11 @@ import {type QueryPlanTranslationKey,useQueryPlanTranslation,} from "./plan-i18n";-import { PLAN_TOO_DEEP_MESSAGE, type PlanParseResult } from "./plan-model";+import {+ PLAN_TOO_DEEP_MESSAGE,+ PLAN_TOO_MANY_NODES_MESSAGE,+ type PlanParseResult,+} from "./plan-model";import {POSTGRES_PLAN_EMPTY_MESSAGE,POSTGRES_PLAN_INVALID_JSON_MESSAGE,@@ -42,6 +46,7 @@ const STATUS_CLASS =const PARSE_ERROR_KEYS = new Map<string, QueryPlanTranslationKey>([[PLAN_TOO_DEEP_MESSAGE, "error.too-deep"],+ [PLAN_TOO_MANY_NODES_MESSAGE, "error.too-many-nodes"],[POSTGRES_PLAN_EMPTY_MESSAGE, "error.postgres-empty"],[POSTGRES_PLAN_INVALID_JSON_MESSAGE, "error.postgres-invalid"],[POSTGRES_PLAN_NO_PLAN_MESSAGE, "error.postgres-no-plan"],@@ -59,6 +64,7 @@ interface Props {planSource: string;textPlanSource?: string;planQuery?: string;+ note?: ReactNode;translate?: QueryPlanTranslate;disallowCopyingData?: boolean;syncSelectionWithHash?: boolean;@@ -69,6 +75,7 @@ function QueryPlanViewContent({planSource,textPlanSource,planQuery,+ note,disallowCopyingData = false,syncSelectionWithHash,}: Props) {@@ -103,6 +110,7 @@ function QueryPlanViewContent({rawPlan={planSource}textPlan={textPlanSource}query={planQuery}+ note={note}disallowCopyingData={disallowCopyingData}syncSelectionWithHash={syncSelectionWithHash}/>diff --git a/frontend/src/apps/explain-visualizer/QueryPlanViewer.test.tsx b/frontend/src/apps/explain-visualizer/QueryPlanViewer.test.tsxindex 34bb478634..0b365d58a5 100644--- a/frontend/src/apps/explain-visualizer/QueryPlanViewer.test.tsx+++ b/frontend/src/apps/explain-visualizer/QueryPlanViewer.test.tsx@@ -505,4 +505,14 @@ describe("QueryPlanViewer", () => {screen.getByRole("button", { name: /Bitmap Index Scan/ })).toHaveAttribute("aria-pressed", "true");});++ test("shows a note at the end of the tab row", () => {+ render(+ <QueryPlanViewer tree={tree()} rawPlan={rawPlan} note="Estimated now" />+ );++ const note = screen.getByText("Estimated now");+ expect(note).toHaveClass("ml-auto");+ expect(note.closest('[role="tablist"]')).not.toBeNull();+ });});diff --git a/frontend/src/apps/explain-visualizer/QueryPlanViewer.tsx b/frontend/src/apps/explain-visualizer/QueryPlanViewer.tsxindex 0708e48e07..19cbf3b885 100644--- a/frontend/src/apps/explain-visualizer/QueryPlanViewer.tsx+++ b/frontend/src/apps/explain-visualizer/QueryPlanViewer.tsx@@ -41,6 +41,8 @@ interface Props {/** The plan output shown on the text tab, when it differs from rawPlan. */readonly textPlan?: string;readonly query?: string;+ /** Shown at the end of the tab row, such as a reminder that the plan is an estimate. */+ readonly note?: ReactNode;readonly disallowCopyingData?: boolean;readonly syncSelectionWithHash?: boolean;}@@ -322,6 +324,7 @@ export function QueryPlanViewer({rawPlan,textPlan = rawPlan,query,+ note,disallowCopyingData = false,syncSelectionWithHash = true,}: Props) {@@ -427,6 +430,11 @@ export function QueryPlanViewer({<TabsTrigger value="summary">{translate("tab.summary")}</TabsTrigger>) : null}<TabsTrigger value="query">{translate("tab.query")}</TabsTrigger>+ {note ? (+ <span className="ml-auto self-center text-sm text-control-light">+ {note}+ </span>+ ) : null}</TabsList><TabsPaneldiff --git a/frontend/src/apps/explain-visualizer/plan-i18n.tsx b/frontend/src/apps/explain-visualizer/plan-i18n.tsxindex f88b0cbf4d..e1bbbc605f 100644--- a/frontend/src/apps/explain-visualizer/plan-i18n.tsx+++ b/frontend/src/apps/explain-visualizer/plan-i18n.tsx@@ -36,6 +36,8 @@ const ENGLISH = {'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.too-many-nodes":+ "The query plan has more operators than this visualizer draws, so it is shown as text.","error.unreadable": "This query plan could not be read","grid.added-cost": "Added cost","grid.added-cost-hint":diff --git a/frontend/src/apps/explain-visualizer/plan-model.test.ts b/frontend/src/apps/explain-visualizer/plan-model.test.tsindex 0e9c19a63e..356f9d36fe 100644--- a/frontend/src/apps/explain-visualizer/plan-model.test.ts+++ b/frontend/src/apps/explain-visualizer/plan-model.test.ts@@ -12,6 +12,7 @@ import {PLAN_EDGE_MAX_WIDTH,PLAN_EDGE_MIN_WIDTH,PLAN_TOO_DEEP_MESSAGE,+ PLAN_TOO_MANY_NODES_MESSAGE,type PlanNode,type PlanProperty,type PlanTree,@@ -148,6 +149,12 @@ describe("parseWithDepthLimit", () => {]);});+ test("turns a tree with more operators than the cap into the node-cap message", () => {+ const children = Array.from({ length: 1001 }, (_, i) => bareNode(`0.${i}`));+ const result = parseWithDepthLimit(() => bareNode("0", children));+ expect(result).toEqual({ ok: false, message: PLAN_TOO_MANY_NODES_MESSAGE });+ });+test("turns a build that went too deep into the depth message", () => {const chain = (depth: number): PlanNode => {checkPlanDepth(depth);diff --git a/frontend/src/apps/explain-visualizer/plan-model.ts b/frontend/src/apps/explain-visualizer/plan-model.tsindex 7986b3dcd9..bc06719c3b 100644--- a/frontend/src/apps/explain-visualizer/plan-model.ts+++ b/frontend/src/apps/explain-visualizer/plan-model.ts@@ -101,10 +101,25 @@ export function checkPlanDepth(depth: number) {if (depth > PLAN_MAX_DEPTH) throw PLAN_TOO_DEEP;}-/** A parser's tree from `build`, or the depth message when it went too deep. */+/**+ * Past this many operators the diagram is unreadable and its layout slow, so+ * the plan is shown as text instead. SSMS degrades the same way, at 2 MB.+ */+const PLAN_MAX_NODES = 1000;++export const PLAN_TOO_MANY_NODES_MESSAGE = `The query plan has more than ${PLAN_MAX_NODES} operators, which is more than this visualizer draws.`;++/**+ * A parser's tree from `build`, or the depth message when it went too deep or+ * the node-cap message when it is too large to draw.+ */export function parseWithDepthLimit(build: () => PlanNode): PlanParseResult {try {- return { ok: true, tree: buildPlanTree(build()) };+ const tree = buildPlanTree(build());+ if (tree.nodes.length > PLAN_MAX_NODES) {+ return { ok: false, message: PLAN_TOO_MANY_NODES_MESSAGE };+ }+ return { ok: true, tree };} catch (error) {if (error !== PLAN_TOO_DEEP) throw error;return { ok: false, message: PLAN_TOO_DEEP_MESSAGE };diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.jsonindex a5b0ad2b4c..806c4dddb0 100644--- a/frontend/src/locales/en-US.json+++ b/frontend/src/locales/en-US.json@@ -3455,12 +3455,16 @@"open-in-new-tab": "Open in new tab","opened-from-link": "Opened from link","pending-query": "Pending query",+ "plan-estimated": "Estimated",+ "plan-view": "Plan","previous-row": "Previous Row","query-context": {"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-estimated": "A new plan, made just now. It may differ from the plan that ran.","query-plan-load-failed": "Failed to load the query plan",+ "query-plan-requires-explain": "Needs the bb.sql.explain permission on this project","query-plan-viewer": {"copy": {"copied": "Copied",@@ -3495,6 +3499,7 @@"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.",+ "too-many-nodes": "The query plan has more operators than this visualizer draws, so it is shown as text.","unreadable": "This query plan could not be read"},"grid": {diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.jsonindex 583ee25923..a56790dcdf 100644--- a/frontend/src/locales/es-ES.json+++ b/frontend/src/locales/es-ES.json@@ -3455,12 +3455,16 @@"open-in-new-tab": "Abrir en nueva pestaña","opened-from-link": "Abierto desde enlace","pending-query": "Consulta pendiente",+ "plan-estimated": "Estimado",+ "plan-view": "Plan","previous-row": "Fila anterior","query-context": {"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-estimated": "Un plan nuevo, calculado ahora mismo. Puede diferir del plan que se ejecutó.","query-plan-load-failed": "No se pudo cargar el plan de consulta",+ "query-plan-requires-explain": "Requiere el permiso bb.sql.explain en este proyecto","query-plan-viewer": {"copy": {"copied": "Copiado",@@ -3495,6 +3499,7 @@"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.",+ "too-many-nodes": "El plan de consulta tiene más operadores de los que este visualizador dibuja, así que se muestra como texto.","unreadable": "No se pudo leer este plan de consulta"},"grid": {diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.jsonindex db722c5a7b..508fd6ab1c 100644--- a/frontend/src/locales/ja-JP.json+++ b/frontend/src/locales/ja-JP.json@@ -3455,12 +3455,16 @@"open-in-new-tab": "新しいタブで開く","opened-from-link": "リンクから開く","pending-query": "保留中のクエリ",+ "plan-estimated": "推定",+ "plan-view": "プラン","previous-row": "前の行","query-context": {"admin-data-source-is-disallowed-to-query": "管理者データ ソースはクエリできません。"},"query-history-not-found": "クエリ履歴が見つからないか、アクセスできなくなりました",+ "query-plan-estimated": "たった今作成された新しいプランです。実行時のプランとは異なる場合があります。","query-plan-load-failed": "クエリプランの読み込みに失敗しました",+ "query-plan-requires-explain": "このプロジェクトで bb.sql.explain 権限が必要です","query-plan-viewer": {"copy": {"copied": "コピーしました",@@ -3495,6 +3499,7 @@"spanner-invalid": "クエリプランが有効な JSON ではありません。Spanner クエリプランが必要です。","spanner-no-plan": "クエリプラン JSON に、ルートがオペレーターである \"planNodes\" リストがありません。","too-deep": "クエリプランの入れ子が深すぎるため、このビジュアライザーでは描画できません。",+ "too-many-nodes": "クエリプランの演算子数がこのビジュアライザーで描画できる数を超えているため、テキストで表示します。","unreadable": "このクエリプランを読み取れませんでした"},"grid": {diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.jsonindex 446712c8e9..e2bd7d8ea0 100644--- a/frontend/src/locales/vi-VN.json+++ b/frontend/src/locales/vi-VN.json@@ -3455,12 +3455,16 @@"open-in-new-tab": "Mở trong tab mới","opened-from-link": "Mở từ liên kết","pending-query": "Đang chờ truy vấn",+ "plan-estimated": "Ước tính",+ "plan-view": "Kế hoạch","previous-row": "Dòng trước","query-context": {"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-estimated": "Một kế hoạch mới, vừa được tạo. Có thể khác với kế hoạch đã chạy.","query-plan-load-failed": "Không tải được kế hoạch truy vấn",+ "query-plan-requires-explain": "Cần quyền bb.sql.explain trên dự án này","query-plan-viewer": {"copy": {"copied": "Đã sao chép",@@ -3495,6 +3499,7 @@"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ẽ.",+ "too-many-nodes": "Kế hoạch truy vấn có nhiều toán tử hơn mức trình trực quan hóa này vẽ được, nên được hiển thị dưới dạng văn bản.","unreadable": "Không thể đọc kế hoạch truy vấn này"},"grid": {diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.jsonindex 4e00baef47..ea5a258591 100644--- a/frontend/src/locales/zh-CN.json+++ b/frontend/src/locales/zh-CN.json@@ -3455,12 +3455,16 @@"open-in-new-tab": "在新选项卡中打开","opened-from-link": "从链接打开","pending-query": "待处理查询",+ "plan-estimated": "预估",+ "plan-view": "执行计划","previous-row": "上一行","query-context": {"admin-data-source-is-disallowed-to-query": "禁止查询主数据源。"},"query-history-not-found": "查询历史记录不存在或已无法访问",+ "query-plan-estimated": "这是刚刚生成的新计划,可能与实际运行时的计划不同。","query-plan-load-failed": "加载查询计划失败",+ "query-plan-requires-explain": "需要此项目的 bb.sql.explain 权限","query-plan-viewer": {"copy": {"copied": "已复制",@@ -3495,6 +3499,7 @@"spanner-invalid": "查询计划不是有效的 JSON。需要 Spanner 查询计划。","spanner-no-plan": "查询计划 JSON 不包含根节点为操作符的 \"planNodes\" 列表。","too-deep": "查询计划嵌套过深,此可视化工具无法绘制。",+ "too-many-nodes": "查询计划的算子数量超过此可视化工具可绘制的上限,已改为文本展示。","unreadable": "无法读取此查询计划"},"grid": {diff --git a/frontend/src/modules/sql-editor/components/ResultView/QueryPlanResultView.test.tsx b/frontend/src/modules/sql-editor/components/ResultView/QueryPlanResultView.test.tsxindex 9ca41bfe41..36a56fd7e0 100644--- a/frontend/src/modules/sql-editor/components/ResultView/QueryPlanResultView.test.tsx+++ b/frontend/src/modules/sql-editor/components/ResultView/QueryPlanResultView.test.tsx@@ -1,4 +1,4 @@-import { render, screen, waitFor } from "@testing-library/react";+import { fireEvent, 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";@@ -12,6 +12,7 @@ vi.mock("@/apps/explain-visualizer/QueryPlanView", () => ({planSource,textPlanSource,planQuery,+ note,translate,disallowCopyingData,syncSelectionWithHash,@@ -19,6 +20,7 @@ vi.mock("@/apps/explain-visualizer/QueryPlanView", () => ({planSource: string;textPlanSource?: string;planQuery?: string;+ note?: React.ReactNode;translate: (key: "tab.text") => string;disallowCopyingData?: boolean;syncSelectionWithHash?: boolean;@@ -29,6 +31,7 @@ vi.mock("@/apps/explain-visualizer/QueryPlanView", () => ({data-hash-sync={syncSelectionWithHash}>{planQuery}:{planSource}:{textPlanSource}:{translate("tab.text")}+ {note ? <span>{note}</span> : null}</div>),}));@@ -158,4 +161,73 @@ describe("QueryPlanResultView", () => {);expect(screen.getByText("formatted:text plan")).toBeInTheDocument();});++ test("loads a text plan on demand when no picture is available", async () => {+ const loadPlan = vi+ .fn()+ .mockResolvedValue({ source: "Seq Scan on t", statement: "SELECT 1" });+ render(<QueryPlanResultView rawPlan="" loadPlan={loadPlan} estimated />);++ expect(screen.getByText("common.loading")).toBeInTheDocument();+ await waitFor(() =>+ expect(screen.getByText("formatted:Seq Scan on t")).toBeInTheDocument()+ );+ expect(screen.getByText("sql-editor.plan-estimated")).toBeInTheDocument();+ expect(screen.queryAllByRole("tab")).toHaveLength(1);+ expect(loadPlan).toHaveBeenCalledWith(expect.any(AbortSignal));+ });++ test("cancel aborts the load and hands control back", () => {+ const onCancel = vi.fn();+ let signal: AbortSignal | undefined;+ const loadPlan = vi.fn((requested: AbortSignal) => {+ signal = requested;+ return new Promise<undefined>(() => {});+ });+ render(+ <QueryPlanResultView rawPlan="" loadPlan={loadPlan} onCancel={onCancel} />+ );++ fireEvent.click(screen.getByRole("button", { name: "common.cancel" }));++ expect(onCancel).toHaveBeenCalledTimes(1);+ expect(signal?.aborted).toBe(true);+ });++ test("shows the engine's reason when the load fails", async () => {+ render(+ <QueryPlanResultView+ rawPlan=""+ loadPlan={vi+ .fn()+ .mockRejectedValue(new Error("permission denied to access resources"))}+ />+ );++ await waitFor(() =>+ expect(screen.getByRole("alert")).toHaveTextContent(+ "permission denied to access resources"+ )+ );+ });++ test("puts the estimate note in the drawable viewer's tab row", async () => {+ const loadPlan = vi+ .fn()+ .mockResolvedValue({ source: "structured plan", statement: "SELECT 1" });+ render(+ <QueryPlanResultView+ engine={Engine.POSTGRES}+ rawPlan=""+ loadPlan={loadPlan}+ estimated+ />+ );++ await waitFor(() =>+ expect(screen.getByTestId("inline-query-plan")).toHaveTextContent(+ "sql-editor.plan-estimated"+ )+ );+ });});diff --git a/frontend/src/modules/sql-editor/components/ResultView/QueryPlanResultView.tsx b/frontend/src/modules/sql-editor/components/ResultView/QueryPlanResultView.tsxindex 9357022e85..bbc3dccbeb 100644--- a/frontend/src/modules/sql-editor/components/ResultView/QueryPlanResultView.tsx+++ b/frontend/src/modules/sql-editor/components/ResultView/QueryPlanResultView.tsx@@ -5,8 +5,11 @@ 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 { Badge } from "@/components/ui/badge";+import { Button } from "@/components/ui/button";import { CopyButton } from "@/components/ui/copy-button";import { Tabs, TabsList, TabsPanel, TabsTrigger } from "@/components/ui/tabs";+import { Tooltip } from "@/components/ui/tooltip";import { cn } from "@/lib/utils";import type { VisualizerEngine } from "@/utils/explainToken";@@ -15,19 +18,25 @@ export interface InlineQueryPlan {statement: string;}-type LoadPlan = () => Promise<InlineQueryPlan | undefined>;+/** Fetches the plan; the signal fires when the reader cancels the load. */+type LoadPlan = (signal: AbortSignal) => Promise<InlineQueryPlan | undefined>;interface Props {rawPlan: string;initialPlan?: InlineQueryPlan;engine?: VisualizerEngine;loadPlan?: LoadPlan;+ // The plan was made on demand for a result that already ran, so it is an+ // estimate of now, not a record of that run.+ estimated?: boolean;+ onCancel?: () => void;disallowCopyingData?: boolean;}interface LoadRequest {rawPlan: string;promise: ReturnType<LoadPlan>;+ abort: () => void;}function TextPlan({@@ -62,14 +71,15 @@ export function QueryPlanResultView({initialPlan,engine,loadPlan,+ estimated = false,+ onCancel,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 [loading, setLoading] = useState(!initialPlan && !!loadPlan);+ // null while nothing failed; the engine's message, or "" when there is none.+ const [failure, setFailure] = useState<string | null>(null);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.@@ -84,27 +94,30 @@ export function QueryPlanResultView({useEffect(() => {let cancelled = false;setPlan(initialPlan);- setFailed(false);- if (initialPlan || !engine || !canLoad) {+ setFailure(null);+ if (initialPlan || !canLoad) {setLoading(false);return;}setLoading(true);if (loadRequest.current?.rawPlan !== rawPlan) {+ const controller = new AbortController();loadRequest.current = {rawPlan,- promise: loadPlanRef.current!(),+ promise: loadPlanRef.current!(controller.signal),+ abort: () => controller.abort(),};}void loadRequest.current.promise.then((loaded) => {if (cancelled) return;if (loaded) setPlan(loaded);- else setFailed(true);+ else setFailure("");})- .catch(() => {- if (!cancelled) setFailed(true);+ .catch((error: unknown) => {+ if (cancelled) return;+ setFailure(error instanceof Error ? error.message : String(error));}).finally(() => {if (!cancelled) setLoading(false);@@ -112,15 +125,29 @@ export function QueryPlanResultView({return () => {cancelled = true;};- }, [engine, initialPlan, canLoad, rawPlan]);+ }, [initialPlan, canLoad, rawPlan]);++ const cancel = () => {+ loadRequest.current?.abort();+ loadRequest.current = undefined;+ onCancel?.();+ };++ // One word in the tab row; the reason it matters is a hover away.+ const estimateNote = estimated ? (+ <Tooltip content={t("sql-editor.query-plan-estimated")}>+ <Badge variant="default">{t("sql-editor.plan-estimated")}</Badge>+ </Tooltip>+ ) : undefined;if (plan && engine) {return (<QueryPlanViewengine={engine}planSource={plan.source}- textPlanSource={rawPlan}+ textPlanSource={rawPlan || undefined}planQuery={plan.statement}+ note={estimateNote}translate={translatePlan}disallowCopyingData={disallowCopyingData}syncSelectionWithHash={false}@@ -133,15 +160,29 @@ export function QueryPlanResultView({<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")}+ {onCancel ? (+ <Button size="sm" appearance="secondary" onClick={cancel}>+ {t("common.cancel")}+ </Button>+ ) : null}</div>);}- if (failed) {+ if (failure !== null) {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} />+ <Alert+ variant="error"+ title={t("sql-editor.query-plan-load-failed")}+ description={failure || undefined}+ />+ {rawPlan ? (+ <TextPlan+ source={rawPlan}+ disallowCopyingData={disallowCopyingData}+ />+ ) : null}</div>);}@@ -150,13 +191,21 @@ export function QueryPlanResultView({<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>+ {estimateNote ? (+ <span className="ml-auto self-center text-sm text-control-light">+ {estimateNote}+ </span>+ ) : null}</TabsList><TabsPanelvalue="plan"className="mt-0 flex min-h-0 flex-1 flex-col overflow-hidden">- <TextPlan source={rawPlan} disallowCopyingData={disallowCopyingData} />+ <TextPlan+ source={plan?.source ?? rawPlan}+ disallowCopyingData={disallowCopyingData}+ /></TabsPanel></Tabs>);diff --git a/frontend/src/modules/sql-editor/components/ResultView/SingleResultView.test.tsx b/frontend/src/modules/sql-editor/components/ResultView/SingleResultView.test.tsxindex fb2b153cea..c01e12e38e 100644--- a/frontend/src/modules/sql-editor/components/ResultView/SingleResultView.test.tsx+++ b/frontend/src/modules/sql-editor/components/ResultView/SingleResultView.test.tsx@@ -65,6 +65,12 @@ const {};});+const { explainPermission, tabState, updateCurrentTab } = vi.hoisted(() => ({+ explainPermission: { granted: true },+ tabState: { resultLayout: undefined as string | undefined },+ updateCurrentTab: vi.fn(),+}));+vi.mock("react-i18next", () => ({initReactI18next: {init: vi.fn(),@@ -190,15 +196,28 @@ vi.mock("@/modules/sql-editor/store/tab", () => ({useSQLEditorTabState: (selector: (state: {currentTabId: string;- tabsById: Map<string, { mode: string }>;+ tabsById: Map<string, { mode: string; resultLayout?: string }>;+ updateCurrentTab: typeof updateCurrentTab;}) => unknown) =>selector({currentTabId: "tab-1",- tabsById: new Map([["tab-1", { mode: "READ_ONLY" }]]),+ tabsById: new Map([+ ["tab-1", { mode: "READ_ONLY", resultLayout: tabState.resultLayout }],+ ]),+ updateCurrentTab,}),}));+vi.mock("@/utils/iam/permission", () => ({+ hasProjectPermissionV2: () => explainPermission.granted,+}));++vi.mock("@/utils/v1/instance", () => ({+ instanceV1AllowsExplain: (engine: Engine) =>+ engine === Engine.POSTGRES || engine === Engine.MYSQL,+}));+vi.mock("@/stores/app", () => ({useAppStore: {getState: () => ({}),@@ -210,6 +229,7 @@ vi.mock("@/utils/util", () => ({}));vi.mock("@/utils/v1/database", () => ({+ getDatabaseProject: (database: Database) => ({ name: database.project }),getInstanceResource: (database: Database) => database.instanceResource,}));@@ -1107,3 +1127,104 @@ describe("SingleResultView explain visualizer", () => {expect(screen.getByTestId("query-plan-result")).toBeInTheDocument();});});++const rowsResult = (statement = "SELECT * FROM t") =>+ create(QueryResultSchema, {+ statement,+ columnNames: ["id"],+ columnTypeNames: ["INT"],+ rows: [+ create(QueryRowSchema, {+ values: [+ create(RowValueSchema, { kind: { case: "stringValue", value: "1" } }),+ ],+ }),+ ],+ });++describe("SingleResultView plan view", () => {+ beforeEach(() => {+ explainPermission.granted = true;+ tabState.resultLayout = undefined;+ updateCurrentTab.mockClear();+ });++ const renderRows = (+ engine: Engine,+ overrides: Partial<React.ComponentProps<typeof SingleResultView>> = {}+ ) =>+ render(+ <SingleResultView+ disallowCopyingData={false}+ params={{ ...params, engine, statement: "SELECT * FROM t" }}+ database={databaseForEngine(engine)}+ result={rowsResult()}+ showExport={false}+ {...overrides}+ />+ );++ test("offers Plan beside Table and Vertical and shows the plan in place", () => {+ renderRows(Engine.POSTGRES);++ expect(screen.getByText("sql-editor.table-view")).toHaveClass("sr-only");+ expect(screen.getByText("sql-editor.vertical-display")).toHaveClass(+ "sr-only"+ );+ expect(screen.getByText("sql-editor.plan-view")).toHaveClass("sr-only");+ expect(screen.getByTestId("result-table")).toBeInTheDocument();++ fireEvent.click(screen.getByText("sql-editor.plan-view"));++ expect(screen.getByTestId("query-plan-result")).toBeInTheDocument();+ expect(screen.queryByTestId("result-table")).not.toBeInTheDocument();+ expect(screen.getByRole("button", { name: "common.plan" })).toBeEnabled();+ expect(updateCurrentTab).toHaveBeenCalledWith({ resultLayout: "PLAN" });++ fireEvent.click(screen.getByText("sql-editor.table-view"));+ expect(screen.getByTestId("result-table")).toBeInTheDocument();+ });++ test("disables Plan when the user lacks the explain permission", () => {+ explainPermission.granted = false;+ renderRows(Engine.POSTGRES);++ expect(+ screen.getByRole("radio", { name: "sql-editor.plan-view" })+ ).toHaveAttribute("aria-disabled", "true");+ fireEvent.click(screen.getByText("sql-editor.plan-view"));+ expect(screen.getByTestId("result-table")).toBeInTheDocument();+ });++ test("offers no Plan on an engine that cannot explain", () => {+ renderRows(Engine.REDIS);++ expect(screen.getByText("sql-editor.vertical-display")).toBeInTheDocument();+ expect(screen.queryByText("sql-editor.plan-view")).not.toBeInTheDocument();+ });++ test("offers no Plan after an earlier statement of the run", () => {+ const setSearchPath = create(QueryResultSchema, {+ statement: "SET search_path = tenant",+ });+ renderRows(Engine.POSTGRES, {+ results: [setSearchPath, rowsResult()],+ resultIndex: 1,+ });++ expect(screen.queryByText("sql-editor.plan-view")).not.toBeInTheDocument();+ });++ test("opens on the remembered Plan choice, falling back where nothing can be planned", () => {+ tabState.resultLayout = "PLAN";+ const { unmount } = renderRows(Engine.POSTGRES);+ expect(screen.getByTestId("query-plan-result")).toBeInTheDocument();+ unmount();++ renderRows(Engine.REDIS);+ expect(screen.getByTestId("result-table")).toBeInTheDocument();+ expect(+ screen.getByRole("radio", { name: "sql-editor.table-view" })+ ).toHaveAttribute("aria-checked", "true");+ });+});diff --git a/frontend/src/modules/sql-editor/components/ResultView/SingleResultView.tsx b/frontend/src/modules/sql-editor/components/ResultView/SingleResultView.tsxindex 630529e4a4..0160d617e1 100644--- a/frontend/src/modules/sql-editor/components/ResultView/SingleResultView.tsx+++ b/frontend/src/modules/sql-editor/components/ResultView/SingleResultView.tsx@@ -6,6 +6,9 @@ import {BracesIcon,CopyIcon,InfoIcon,+ type LucideIcon,+ NetworkIcon,+ Rows3Icon,Table2Icon,XIcon,} from "lucide-react";@@ -27,7 +30,10 @@ import {} from "@/components/DataExportButton";import { Alert } from "@/components/ui/alert";import { Button } from "@/components/ui/button";-import { SegmentedControl } from "@/components/ui/segmented-control";+import {+ SegmentedControl,+ type SegmentedControlOption,+} from "@/components/ui/segmented-control";import { Switch } from "@/components/ui/switch";import { Tooltip } from "@/components/ui/tooltip";import { useExecuteSQL } from "@/hooks/useExecuteSQL";@@ -37,6 +43,7 @@ import { useSQLEditorQueryDataPolicy } from "@/modules/sql-editor/hooks/useSQLEdimport { useSQLEditorEditorState } from "@/modules/sql-editor/store/editor";import { useSQLEditorTabState } from "@/modules/sql-editor/store/tab";import type {+ ResultLayout,SQLEditorDatabaseQueryContext,SQLEditorQueryParams,} from "@/types";@@ -50,8 +57,8 @@ import {import {isVisualizerEngine,VISUALIZER_EXPLAIN_FORMATS,- type VisualizerEngine,} from "@/utils/explainToken";+import { hasProjectPermissionV2 } from "@/utils/iam/permission";import {flattenElasticsearchSearchResult,flattenNoSQLQueryResult,@@ -59,7 +66,8 @@ import {isNoSQLQueryResult,} from "@/utils/sqlResult";import { STORAGE_KEY_SQL_EDITOR_NOSQL_TABLE_VIEW } from "@/utils/storage-keys";-import { getInstanceResource } from "@/utils/v1/database";+import { getDatabaseProject, getInstanceResource } from "@/utils/v1/database";+import { instanceV1AllowsExplain } from "@/utils/v1/instance";import { compareQueryRowValues, extractSQLRowValuePlain } from "@/utils/v1/sql";import { CopyAllButton } from "./CopyAllButton";import { SQLResultViewProvider } from "./context";@@ -68,6 +76,7 @@ import { DetailPanel } from "./DetailPanel";import { DocumentJSONView } from "./DocumentJSONView";import { EmptyView } from "./EmptyView";import { ErrorView } from "./ErrorView";+import { canReplayStatement, planAvailability } from "./planAvailability";import {type InlineQueryPlan,QueryPlanResultView,@@ -329,7 +338,100 @@ function SingleResultViewInner({VirtualDataTableHandle | VirtualDataBlockHandle | null>(null);- const [vertical, setVertical] = useState(false);+ // The view switch's choice is remembered per editor tab, so the next run in+ // this tab opens the same way.+ const rememberedLayout = useSQLEditorTabState(+ (s) => s.tabsById.get(s.currentTabId)?.resultLayout+ );+ const updateCurrentTab = useSQLEditorTabState((s) => s.updateCurrentTab);+ const [chosenLayout, setChosenLayout] = useState<ResultLayout>(+ rememberedLayout ?? "TABLE"+ );+ const setLayout = useCallback(+ (next: ResultLayout) => {+ setChosenLayout(next);+ updateCurrentTab({ resultLayout: next });+ },+ [updateCurrentTab]+ );+ const planOption = planAvailability({+ result,+ results,+ resultIndex,+ engineExplains: instanceV1AllowsExplain(engine),+ canExplain: hasProjectPermissionV2(+ getDatabaseProject(database),+ "bb.sql.explain"+ ),+ });+ // A remembered Plan choice falls back to the table where this result offers+ // no plan.+ const layout: ResultLayout =+ chosenLayout === "PLAN" && planOption !== "offered"+ ? "TABLE"+ : chosenLayout;+ const vertical = layout === "VERTICAL";+ // The plan fetched for this result, kept so switching views does not fetch+ // it again.+ const [planCache, setPlanCache] = useState<{+ result: QueryResult;+ plan: InlineQueryPlan;+ }>();+ const resultPlan = planCache?.result === result ? planCache.plan : undefined;+ const loadResultPlan = useCallback(+ async (signal: AbortSignal) => {+ const loaded = await explainStatement(+ database,+ params,+ result.statement,+ runQuery,+ engine,+ signal+ );+ if (loaded) setPlanCache({ result, plan: loaded });+ return loaded;+ },+ [database, engine, params, result, runQuery]+ );+ // Document and search engines keep their own view controls; the SQL+ // engines get the one switch with Table, Vertical and Plan.+ const sqlLayoutSwitch = !supportsDocumentJSONView && !supportsTableViewToggle;+ const layoutOptions = useMemo(() => {+ const options: SegmentedControlOption<ResultLayout>[] = [+ {+ value: "TABLE",+ label: (+ <SegmentIcon icon={Table2Icon} label={t("sql-editor.table-view")} />+ ),+ tooltip: t("sql-editor.table-view"),+ },+ {+ value: "VERTICAL",+ label: (+ <SegmentIcon+ icon={Rows3Icon}+ label={t("sql-editor.vertical-display")}+ />+ ),+ tooltip: t("sql-editor.vertical-display"),+ },+ ];+ if (planOption !== "absent") {+ const needsPermission = planOption === "needs-permission";+ options.push({+ value: "PLAN",+ label: (+ <SegmentIcon icon={NetworkIcon} label={t("sql-editor.plan-view")} />+ ),+ tooltip: needsPermission+ ? t("sql-editor.query-plan-requires-explain")+ : t("sql-editor.plan-view"),+ disabled: needsPermission,+ });+ }+ return options;+ }, [planOption, t]);+const {params: searchParams,setParams: setSearchParams,@@ -406,29 +508,26 @@ 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 planInResult = useMemo(() => getInlineQueryPlan(result), [result]);const canReplay =isVisualizerEngine(engine) &&plan?.format === QueryOption_ExplainFormat.TEXT &&!plan.executed &&- results- .slice(0, resultIndex)- .every((earlier) => earlier.queryPlan && !earlier.queryPlan.executed);+ canReplayStatement(results, resultIndex);// 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(- () =>+ (signal: AbortSignal) =>isVisualizerEngine(engine)- ? getInlineQueryPlanForStatement(+ ? explainStatement(database,params,result.statement,runQuery,- engine+ engine,+ signal): Promise.resolve(undefined),[database, engine, params, result.statement, runQuery]@@ -510,8 +609,8 @@ function SingleResultViewInner({><QueryPlanResultViewkey={`${database.name}\n${engine}\n${result.statement}`}- rawPlan={resultPlan?.source ?? ""}- initialPlan={planInRows ? resultPlan : undefined}+ rawPlan={planInResult?.source ?? ""}+ initialPlan={planInRows ? planInResult : undefined}engine={isVisualizerEngine(engine) ? engine : undefined}loadPlan={canReplay ? loadPlan : undefined}disallowCopyingData={disallowCopyingData}@@ -574,24 +673,20 @@ function SingleResultViewInner({{value: "TABLE",label: (- <span className="flex h-[26px] w-7 items-center justify-center">- <Table2Icon className="size-4" aria-hidden />- <span className="sr-only">- {t("sql-editor.table-view")}- </span>- </span>+ <SegmentIcon+ icon={Table2Icon}+ label={t("sql-editor.table-view")}+ />),tooltip: t("sql-editor.table-view"),},{value: "JSON",label: (- <span className="flex h-[26px] w-7 items-center justify-center">- <BracesIcon className="size-4" aria-hidden />- <span className="sr-only">- {t("sql-editor.json-view")}- </span>- </span>+ <SegmentIcon+ icon={BracesIcon}+ label={t("sql-editor.json-view")}+ />),tooltip: t("sql-editor.json-view"),},@@ -613,13 +708,30 @@ function SingleResultViewInner({</span></div>) : null}- {!isJSONView && (- <div className="flex items-center gap-x-1">- <Switch checked={vertical} onCheckedChange={setVertical} />- <span className="whitespace-nowrap text-sm text-control-light">- {t("sql-editor.vertical-display")}- </span>- </div>+ {sqlLayoutSwitch ? (+ <SegmentedControl<ResultLayout>+ value={layout}+ options={layoutOptions}+ onValueChange={setLayout}+ ariaLabel={t("sql-editor.result-view-mode")}+ appearance="soft"+ className="flex-nowrap"+ size="xs"+ />+ ) : (+ !isJSONView && (+ <div className="flex items-center gap-x-1">+ <Switch+ checked={vertical}+ onCheckedChange={(checked) =>+ setLayout(checked ? "VERTICAL" : "TABLE")+ }+ />+ <span className="whitespace-nowrap text-sm text-control-light">+ {t("sql-editor.vertical-display")}+ </span>+ </div>+ ))}{!disallowCopyingData && rows.length > 0 && isJSONView && (<Button@@ -664,6 +776,24 @@ function SingleResultViewInner({activeMatchIndex={documentSearchActiveIndex}onMatchCountChange={setDocumentSearchMatchCount}/>+ ) : layout === "PLAN" ? (+ <div+ className={cn(+ "w-full flex flex-col",+ compact ? "h-80 overflow-hidden" : "flex-1 min-h-0"+ )}+ >+ <QueryPlanResultView+ key={planViewKey(result)}+ rawPlan=""+ initialPlan={resultPlan}+ engine={isVisualizerEngine(engine) ? engine : undefined}+ loadPlan={loadResultPlan}+ estimated+ onCancel={() => setLayout("TABLE")}+ disallowCopyingData={disallowCopyingData}+ />+ </div>) : (<divclassName={cn(@@ -820,6 +950,33 @@ function useLocalStorageBoolean(return [value, update];}+function SegmentIcon({+ icon: Icon,+ label,+}: {+ icon: LucideIcon;+ label: string;+}) {+ return (+ <span className="flex w-7 items-center justify-center py-1">+ <Icon className="size-4" aria-hidden />+ <span className="sr-only">{label}</span>+ </span>+ );+}++// A plan view is keyed by the result it belongs to, so a re-run of the same+// statement gets a fresh view and a fresh plan.+const planViewKeys = new WeakMap<QueryResult, string>();+function planViewKey(result: QueryResult): string {+ let key = planViewKeys.get(result);+ if (!key) {+ key = uuidv4();+ planViewKeys.set(result, key);+ }+ return key;+}+function DatabaseInfo({ database }: { database: Database }) {const { t } = useTranslation();return (@@ -845,16 +1002,22 @@ function getInlineQueryPlan(result: QueryResult): InlineQueryPlan | undefined {return { statement, source };}-async function getInlineQueryPlanForStatement(+// explainStatement asks the engine for the plan of a statement as it ran, in+// the format the visualizer draws where there is one and the engine's default+// otherwise. The signal cancels the request. The plan carries the statement+// itself, limit and all, for the viewer to show.+async function explainStatement(database: Database,params: SQLEditorQueryParams,statement: string,runQuery: ReturnType<typeof useExecuteSQL>["runQuery"],- engine: VisualizerEngine+ engine: Engine,+ signal?: AbortSignal): Promise<InlineQueryPlan | undefined> {if (!statement) return undefined;- const explainFormat =- QueryOption_ExplainFormat[VISUALIZER_EXPLAIN_FORMATS[engine]];+ const explainFormat = isVisualizerEngine(engine)+ ? QueryOption_ExplainFormat[VISUALIZER_EXPLAIN_FORMATS[engine]]+ : QueryOption_ExplainFormat.EXPLAIN_FORMAT_UNSPECIFIED;const context: SQLEditorDatabaseQueryContext = {id: uuidv4(),params: {@@ -865,8 +1028,16 @@ async function getInlineQueryPlanForStatement(},status: "PENDING",};- await runQuery(database, context);- const result = context.resultSet?.results[0];+ const run = runQuery(database, context);+ signal?.addEventListener("abort", () => context.abortController?.abort(), {+ once: true,+ });+ await run;+ const resultSet = context.resultSet;+ if (resultSet?.error) throw new Error(resultSet.error);+ const result = resultSet?.results[0];if (!result) return undefined;- return getInlineQueryPlan(result);+ if (result.error) throw new Error(result.error);+ const plan = getInlineQueryPlan(result);+ return plan && { ...plan, statement };}diff --git a/frontend/src/modules/sql-editor/components/ResultView/planAvailability.test.ts b/frontend/src/modules/sql-editor/components/ResultView/planAvailability.test.tsnew file mode 100644index 0000000000..125903d95b--- /dev/null+++ b/frontend/src/modules/sql-editor/components/ResultView/planAvailability.test.ts@@ -0,0 +1,80 @@+import { create } from "@bufbuild/protobuf";+import { describe, expect, test } from "vitest";+import {+ QueryResult_QueryPlanSchema,+ QueryResultSchema,+} from "@/types/proto-es/v1/sql_service_pb";+import { planAvailability } from "./planAvailability";++const rows = (statement = "SELECT 1") =>+ create(QueryResultSchema, { statement, columnNames: ["a"] });+const affectedRows = () =>+ create(QueryResultSchema, {+ statement: "INSERT INTO t VALUES (1)",+ columnNames: ["Affected Rows"],+ });+const noRows = () =>+ create(QueryResultSchema, { statement: "SET search_path = tenant" });+const setConfig = () =>+ rows("SELECT set_config('search_path', 'tenant,public', false)");+const plan = (executed: boolean) =>+ create(QueryResultSchema, {+ statement: "EXPLAIN SELECT 1",+ columnNames: ["QUERY PLAN"],+ queryPlan: create(QueryResult_QueryPlanSchema, { executed }),+ });++const offered = (overrides: Partial<Parameters<typeof planAvailability>[0]>) =>+ planAvailability({+ result: rows(),+ results: [rows()],+ resultIndex: 0,+ engineExplains: true,+ canExplain: true,+ ...overrides,+ });++describe("planAvailability", () => {+ test("offers a plan for an ordinary read", () => {+ expect(offered({})).toBe("offered");+ });++ test("is disabled, not absent, without the explain permission", () => {+ expect(offered({ canExplain: false })).toBe("needs-permission");+ });++ test("is absent when the result already is a plan", () => {+ const result = create(QueryResultSchema, {+ statement: "EXPLAIN SELECT 1",+ columnNames: ["QUERY PLAN"],+ queryPlan: create(QueryResult_QueryPlanSchema, {}),+ });+ expect(offered({ result, results: [result] })).toBe("absent");+ });++ test("is absent on an engine that cannot explain", () => {+ expect(offered({ engineExplains: false })).toBe("absent");+ });++ test("is absent when the run recorded no executed statement", () => {+ const result = rows("");+ expect(offered({ result, results: [result] })).toBe("absent");+ });++ test("is absent after any earlier statement that executed", () => {+ for (const earlier of [noRows(), affectedRows(), setConfig(), rows()]) {+ expect(offered({ results: [earlier, rows()], resultIndex: 1 })).toBe(+ "absent"+ );+ }+ expect(offered({ results: [plan(true), rows()], resultIndex: 1 })).toBe(+ "absent"+ );+ });++ test("stays offered after earlier plans that did not execute", () => {+ expect(offered({ results: [plan(false), rows()], resultIndex: 1 })).toBe(+ "offered"+ );+ });+});diff --git a/frontend/src/modules/sql-editor/components/ResultView/planAvailability.ts b/frontend/src/modules/sql-editor/components/ResultView/planAvailability.tsnew file mode 100644index 0000000000..13b1d89b02--- /dev/null+++ b/frontend/src/modules/sql-editor/components/ResultView/planAvailability.ts@@ -0,0 +1,48 @@+import type { QueryResult } from "@/types/proto-es/v1/sql_service_pb";++export type PlanAvailability = "offered" | "needs-permission" | "absent";++/**+ * Whether the statement behind results[index] can be explained again on its+ * own. A plan request runs it alone, so an earlier statement of the run that+ * executed may have set session state the plan would miss, and a result cannot+ * show that: `SELECT set_config('search_path', ...)` returns a row like any+ * read. Only a plan that did not execute is known to leave the session as it+ * was.+ */+export function canReplayStatement(+ results: QueryResult[],+ index: number+): boolean {+ return results+ .slice(0, index)+ .every((earlier) => !!earlier.queryPlan && !earlier.queryPlan.executed);+}++/**+ * Whether a result's view switch offers Plan. It is absent when there is no+ * plan to ask for: the result already is one, the engine cannot explain, the+ * run recorded no executed statement, or the statement cannot be replayed on+ * its own.+ */+export function planAvailability({+ result,+ results,+ resultIndex,+ engineExplains,+ canExplain,+}: {+ result: QueryResult;+ results: QueryResult[];+ resultIndex: number;+ engineExplains: boolean;+ canExplain: boolean;+}): PlanAvailability {+ if (result.queryPlan || !engineExplains || !result.statement) {+ return "absent";+ }+ if (!canReplayStatement(results, resultIndex)) {+ return "absent";+ }+ return canExplain ? "offered" : "needs-permission";+}diff --git a/frontend/src/types/sqlEditor/tab.ts b/frontend/src/types/sqlEditor/tab.tsindex 40878a6441..8ff77a4a37 100644--- a/frontend/src/types/sqlEditor/tab.ts+++ b/frontend/src/types/sqlEditor/tab.ts@@ -68,6 +68,11 @@ export type SQLEditorDatabaseQueryContext = {resultSet?: SQLResultSetV1;};+// How the result pane shows a result set: rows as a table, one row per block,+// or the statement's query plan. Remembered per tab, so the next run opens the+// same way.+export type ResultLayout = "TABLE" | "VERTICAL" | "PLAN";+export type SQLEditorTab = {// basic fieldsid: string; // uuid@@ -78,6 +83,7 @@ export type SQLEditorTab = {statement: string; // local editing statement, might be out-of-sync to ref sheet's statementselectedStatement: string;mode: SQLEditorTabMode;+ resultLayout?: ResultLayout;dataExplorer?: DataExplorerState;// SQL query related fields