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): draw the stages of a BigQuery job (#21678)
Danny Xu1f57c0c9ec3d
diff --git a/backend/api/mcp/gen/openapi.yaml b/backend/api/mcp/gen/openapi.yamlindex 6254382c97..c45cc35836 100644--- a/backend/api/mcp/gen/openapi.yaml+++ b/backend/api/mcp/gen/openapi.yaml@@ -19048,9 +19048,19 @@ components:description: |-Whether producing the plan executed the statement, as EXPLAIN ANALYZEdoes.+ content:+ type: string+ title: content+ description: |-+ The plan itself, where the engine states it beside the result rather+ than in the result's rows. BigQuery reports the stages its job ran in+ the job's own statistics, so one result carries the query's data and+ the plan of the run that produced it. Empty when the plan is the rows,+ which is every other engine. Omitted from the audit log, as the rows+ are: the statement is what an audit reads.title: QueryPlanadditionalProperties: false- description: A query plan held in the result's rows.+ description: 'A query plan the result carries: in its rows, or beside them.'bytebase.v1.QueryResult.SyntaxError:type: objectproperties:diff --git a/backend/generated-go/v1/sql_service.pb.go b/backend/generated-go/v1/sql_service.pb.goindex c642012f56..8663f829fc 100644--- a/backend/generated-go/v1/sql_service.pb.go+++ b/backend/generated-go/v1/sql_service.pb.go@@ -1947,13 +1947,20 @@ func (x *QueryResult_Message) GetContent() string {return ""}-// A query plan held in the result's rows.+// A query plan the result carries: in its rows, or beside them.type QueryResult_QueryPlan struct {state protoimpl.MessageState `protogen:"open.v1"`Format QueryOption_ExplainFormat `protobuf:"varint,1,opt,name=format,proto3,enum=bytebase.v1.QueryOption_ExplainFormat" json:"format,omitempty"`// Whether producing the plan executed the statement, as EXPLAIN ANALYZE// does.- Executed bool `protobuf:"varint,2,opt,name=executed,proto3" json:"executed,omitempty"`+ Executed bool `protobuf:"varint,2,opt,name=executed,proto3" json:"executed,omitempty"`+ // The plan itself, where the engine states it beside the result rather+ // than in the result's rows. BigQuery reports the stages its job ran in+ // the job's own statistics, so one result carries the query's data and+ // the plan of the run that produced it. Empty when the plan is the rows,+ // which is every other engine. Omitted from the audit log, as the rows+ // are: the statement is what an audit reads.+ Content string `protobuf:"bytes,3,opt,name=content,proto3" json:"content,omitempty"`unknownFields protoimpl.UnknownFieldssizeCache protoimpl.SizeCache}@@ -2002,6 +2009,13 @@ func (x *QueryResult_QueryPlan) GetExecuted() bool {return false}+func (x *QueryResult_QueryPlan) GetContent() string {+ if x != nil {+ return x.Content+ }+ return ""+}+type RowValue_Timestamp struct {state protoimpl.MessageState `protogen:"open.v1"`GoogleTimestamp *timestamppb.Timestamp `protobuf:"bytes,1,opt,name=google_timestamp,json=googleTimestamp,proto3" json:"google_timestamp,omitempty"`@@ -2175,7 +2189,7 @@ const file_v1_sql_service_proto_rawDesc = "" +"\x04TEXT\x10\x01\x12\b\n" +"\x04JSON\x10\x02\x12\a\n" +"\x03XML\x10\x03\x12\b\n" +- "\x04YAML\x10\x04J\x04\b\x02\x10\x03R\x14mssql_explain_format\"\xc3\x0e\n" ++ "\x04YAML\x10\x04J\x04\b\x02\x10\x03R\x14mssql_explain_format\"\xe4\x0e\n" +"\vQueryResult\x12!\n" +"\fcolumn_names\x18\x01 \x03(\tR\vcolumnNames\x12*\n" +"\x11column_type_names\x18\x02 \x03(\tR\x0fcolumnTypeNames\x12/\n" +@@ -2236,10 +2250,11 @@ const file_v1_sql_service_proto_rawDesc = "" +"\x03LOG\x10\x04\x12\n" +"\n" +"\x06NOTICE\x10\x05\x12\r\n" +- "\tEXCEPTION\x10\x06\x1ag\n" ++ "\tEXCEPTION\x10\x06\x1a\x87\x01\n" +"\tQueryPlan\x12>\n" +"\x06format\x18\x01 \x01(\x0e2&.bytebase.v1.QueryOption.ExplainFormatR\x06format\x12\x1a\n" +- "\bexecuted\x18\x02 \x01(\bR\bexecutedB\x10\n" ++ "\bexecuted\x18\x02 \x01(\bR\bexecuted\x12\x1e\n" ++ "\acontent\x18\x03 \x01(\tB\x04\xd0\xea0\x02R\acontentB\x10\n" +"\x0edetailed_error\"\xb0\x02\n" +"\rMaskingReason\x12(\n" +"\x10semantic_type_id\x18\x01 \x01(\tR\x0esemanticTypeId\x12.\n" +diff --git a/backend/generated-go/v1/sql_service_equal.pb.go b/backend/generated-go/v1/sql_service_equal.pb.goindex 15dcd53033..067f2ea11b 100644--- a/backend/generated-go/v1/sql_service_equal.pb.go+++ b/backend/generated-go/v1/sql_service_equal.pb.go@@ -239,6 +239,9 @@ func (x *QueryResult_QueryPlan) Equal(y *QueryResult_QueryPlan) bool {if x.Executed != y.Executed {return false}+ if x.Content != y.Content {+ return false+ }return true}diff --git a/backend/plugin/db/bigquery/bigquery.go b/backend/plugin/db/bigquery/bigquery.goindex 13d5a9672f..d362e169d2 100644--- a/backend/plugin/db/bigquery/bigquery.go+++ b/backend/plugin/db/bigquery/bigquery.go@@ -217,6 +217,9 @@ func (d *Driver) QueryConn(ctx context.Context, _ *sql.Conn, statement string, q}}+ // The job that returned these rows reports the stages it ran as+ // it goes; BigQuery has no EXPLAIN to ask for them instead.+ result.QueryPlan = queryPlan(ctx, it.SourceJob())return result, nil}diff --git a/backend/plugin/db/bigquery/query_plan.go b/backend/plugin/db/bigquery/query_plan.gonew file mode 100644index 0000000000..189f77878a--- /dev/null+++ b/backend/plugin/db/bigquery/query_plan.go@@ -0,0 +1,140 @@+package bigquery++import (+ "context"+ "encoding/json"+ "log/slog"+ "time"++ "cloud.google.com/go/bigquery"++ "github.com/bytebase/bytebase/backend/common/log"+ v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"+)++// BigQuery has no EXPLAIN. What it has is the plan of a job that ran: the+// stages the query was executed as, each naming the stages that fed it, the+// records it read and wrote, and how long its shards spent waiting, reading,+// computing and writing. That makes it a record of the run rather than an+// estimate of the next one, and it arrives with the job rather than in the+// result's rows — which is why the result carries it in QueryPlan.content.++// queryStage is one stage of a query plan, named as BigQuery's own REST API+// names it (ExplainQueryStage) rather than as the Go client's fields, so the+// viewer reads the shape Google documents. Durations are milliseconds, as that+// API states them; the ids are numbers here, where it quotes them.+//+// Its four ratio fields are left out. Each is relative to the longest-running+// segment of the whole query, which a single node's card cannot explain, and+// the milliseconds beside them say the same thing absolutely.+//+// The record counts carry a zero, where everything else here drops one. A stage+// that wrote no records measured that — a filter left nothing for the aggregate+// above it — and the viewer reads these two as the rows a node really moved, so+// dropping the zero would leave it showing an unknown count instead. A stage+// that spent no time writing has nothing to say about writing, so those fields+// stay out.+type queryStage struct {+ ID int64 `json:"id"`+ Name string `json:"name"`+ Status string `json:"status,omitempty"`+ InputStages []int64 `json:"inputStages,omitempty"`+ Steps []queryStep `json:"steps,omitempty"`+ RecordsRead int64 `json:"recordsRead"`+ RecordsWritten int64 `json:"recordsWritten"`+ ParallelInputs int64 `json:"parallelInputs,omitempty"`+ CompletedParallelInputs int64 `json:"completedParallelInputs,omitempty"`+ ShuffleOutputBytes int64 `json:"shuffleOutputBytes,omitempty"`+ ShuffleOutputBytesSpilled int64 `json:"shuffleOutputBytesSpilled,omitempty"`+ WaitMsAvg int64 `json:"waitMsAvg,omitempty"`+ WaitMsMax int64 `json:"waitMsMax,omitempty"`+ ReadMsAvg int64 `json:"readMsAvg,omitempty"`+ ReadMsMax int64 `json:"readMsMax,omitempty"`+ ComputeMsAvg int64 `json:"computeMsAvg,omitempty"`+ ComputeMsMax int64 `json:"computeMsMax,omitempty"`+ WriteMsAvg int64 `json:"writeMsAvg,omitempty"`+ WriteMsMax int64 `json:"writeMsMax,omitempty"`+}++// queryStep is one operation within a stage, in dependency order.+type queryStep struct {+ Kind string `json:"kind"`+ Substeps []string `json:"substeps,omitempty"`+}++func milliseconds(d time.Duration) int64 {+ return int64(d / time.Millisecond)+}++func toQueryStages(stages []*bigquery.ExplainQueryStage) []queryStage {+ encoded := make([]queryStage, 0, len(stages))+ for _, stage := range stages {+ if stage == nil {+ continue+ }+ steps := make([]queryStep, 0, len(stage.Steps))+ for _, step := range stage.Steps {+ if step == nil {+ continue+ }+ steps = append(steps, queryStep{Kind: step.Kind, Substeps: step.Substeps})+ }+ encoded = append(encoded, queryStage{+ ID: stage.ID,+ Name: stage.Name,+ Status: stage.Status,+ InputStages: stage.InputStages,+ Steps: steps,+ RecordsRead: stage.RecordsRead,+ RecordsWritten: stage.RecordsWritten,+ ParallelInputs: stage.ParallelInputs,+ CompletedParallelInputs: stage.CompletedParallelInputs,+ ShuffleOutputBytes: stage.ShuffleOutputBytes,+ ShuffleOutputBytesSpilled: stage.ShuffleOutputBytesSpilled,+ WaitMsAvg: milliseconds(stage.WaitAvg),+ WaitMsMax: milliseconds(stage.WaitMax),+ ReadMsAvg: milliseconds(stage.ReadAvg),+ ReadMsMax: milliseconds(stage.ReadMax),+ ComputeMsAvg: milliseconds(stage.ComputeAvg),+ ComputeMsMax: milliseconds(stage.ComputeMax),+ WriteMsAvg: milliseconds(stage.WriteAvg),+ WriteMsMax: milliseconds(stage.WriteMax),+ })+ }+ return encoded+}++// queryPlan returns the plan of the job a finished read came from, or nil where+// there is none to report.+//+// Reading it costs one jobs.get after the rows, since the responses the row+// iterator fetches on its way through them do not carry the plan. A read that+// came from no job of its own has none; neither does a job still without+// statistics, nor a failure to fetch them, which leaves the rows the caller+// asked for exactly as they were.+func queryPlan(ctx context.Context, job *bigquery.Job) *v1pb.QueryResult_QueryPlan {+ if job == nil {+ return nil+ }+ status, err := job.Status(ctx)+ if err != nil {+ slog.Debug("failed to read the job status for its query plan", log.BBError(err))+ return nil+ }+ stats, ok := statisticsOf(status)+ if !ok || len(stats.QueryPlan) == 0 {+ return nil+ }+ content, err := json.Marshal(toQueryStages(stats.QueryPlan))+ if err != nil {+ slog.Debug("failed to encode the query plan", log.BBError(err))+ return nil+ }+ return &v1pb.QueryResult_QueryPlan{+ Format: v1pb.QueryOption_JSON,+ // The plan records the run that returned these rows rather than+ // planning another, which is what the viewer's measured badge says.+ Executed: true,+ Content: string(content),+ }+}diff --git a/backend/plugin/db/bigquery/query_plan_test.go b/backend/plugin/db/bigquery/query_plan_test.gonew file mode 100644index 0000000000..3d853482d7--- /dev/null+++ b/backend/plugin/db/bigquery/query_plan_test.go@@ -0,0 +1,133 @@+package bigquery++import (+ "context"+ "encoding/json"+ "testing"+ "time"++ "cloud.google.com/go/bigquery"+ "github.com/stretchr/testify/require"+)++// sampleStages is a two-stage plan of the shape BigQuery reports for a filtered+// aggregate: one stage reads the table and writes partial groups to shuffle, the+// next reads that shuffle and writes the query's rows.+func sampleStages() []*bigquery.ExplainQueryStage {+ return []*bigquery.ExplainQueryStage{+ {+ ID: 0,+ Name: "S00: Input",+ Status: "COMPLETE",+ RecordsRead: 4,+ RecordsWritten: 2,+ ParallelInputs: 1,+ CompletedParallelInputs: 1,+ ShuffleOutputBytes: 72,+ WaitAvg: 2 * time.Millisecond,+ WaitMax: 3 * time.Millisecond,+ ReadAvg: 11 * time.Millisecond,+ ReadMax: 14 * time.Millisecond,+ ComputeAvg: 7 * time.Millisecond,+ ComputeMax: 9 * time.Millisecond,+ WriteAvg: time.Millisecond,+ WriteMax: time.Millisecond,+ Steps: []*bigquery.ExplainQueryStep{+ {Kind: "READ", Substeps: []string{"$1:city", "FROM analytics.customers", "WHERE equal($1, 'berlin')"}},+ {Kind: "AGGREGATE", Substeps: []string{"GROUP BY $10 := $1", "$20 := COUNT(*)"}},+ {Kind: "WRITE", Substeps: []string{"$10, $20", "TO __stage00_output"}},+ },+ },+ {+ ID: 1,+ Name: "S01: Output",+ Status: "COMPLETE",+ InputStages: []int64{0},+ RecordsRead: 2,+ RecordsWritten: 1,+ ParallelInputs: 1,+ WaitAvg: time.Millisecond,+ ComputeAvg: 3 * time.Millisecond,+ ComputeMax: 3 * time.Millisecond,+ Steps: []*bigquery.ExplainQueryStep{+ {Kind: "READ", Substeps: []string{"$10, $20", "FROM __stage00_output"}},+ {Kind: "AGGREGATE", Substeps: []string{"GROUP BY $30 := $10", "$40 := SUM_OF_COUNTS($20)"}},+ {Kind: "WRITE", Substeps: []string{"$30, $40", "TO __stage01_output"}},+ },+ },+ }+}++// TestToQueryStages pins what the result hands the viewer: BigQuery's own REST+// names, its durations as milliseconds, and the stage ids a stage's inputs+// refer to.+func TestToQueryStages(t *testing.T) {+ encoded, err := json.Marshal(toQueryStages(sampleStages()))+ require.NoError(t, err)++ var stages []map[string]any+ require.NoError(t, json.Unmarshal(encoded, &stages))+ require.Len(t, stages, 2)++ require.Equal(t, float64(0), stages[0]["id"])+ require.Equal(t, "S00: Input", stages[0]["name"])+ require.Equal(t, float64(4), stages[0]["recordsRead"])+ require.Equal(t, float64(2), stages[0]["recordsWritten"])+ require.Equal(t, float64(11), stages[0]["readMsAvg"])+ require.Equal(t, float64(9), stages[0]["computeMsMax"])+ require.Equal(t, float64(72), stages[0]["shuffleOutputBytes"])+ // The stage that reads another names it, which is the plan's one edge.+ require.Equal(t, []any{float64(0)}, stages[1]["inputStages"])+ // A step keeps the engine's own words, which is where the table appears.+ steps, ok := stages[0]["steps"].([]any)+ require.True(t, ok)+ require.Len(t, steps, 3)+ first, ok := steps[0].(map[string]any)+ require.True(t, ok)+ require.Equal(t, "READ", first["kind"])+ require.Contains(t, first["substeps"], "FROM analytics.customers")++ // The ratios BigQuery reports beside the durations are left out, since each+ // is relative to the whole query's longest segment.+ for _, key := range []string{"waitRatioAvg", "readRatioAvg", "computeRatioAvg", "writeRatioAvg"} {+ require.NotContains(t, stages[0], key)+ }+ // A stage that spent no time writing says nothing about writing.+ require.NotContains(t, stages[1], "writeMsAvg")+}++// TestToQueryStagesKeepsZeroRecords pins the one measurement that carries a+// zero. A stage that wrote no records measured that, and the viewer reads these+// counts as the rows a node really moved, so dropping the zero would leave it+// showing an unknown count instead of an empty stage.+func TestToQueryStagesKeepsZeroRecords(t *testing.T) {+ encoded, err := json.Marshal(toQueryStages([]*bigquery.ExplainQueryStage{+ {ID: 0, Name: "S00: Input", RecordsRead: 0, RecordsWritten: 0},+ }))+ require.NoError(t, err)++ var stages []map[string]any+ require.NoError(t, json.Unmarshal(encoded, &stages))+ require.Len(t, stages, 1)+ require.Equal(t, float64(0), stages[0]["recordsRead"])+ require.Equal(t, float64(0), stages[0]["recordsWritten"])+}++func TestToQueryStagesSkipsNothing(t *testing.T) {+ // A nil stage or step in the list is skipped rather than encoded as null,+ // which the viewer would have to read as an operator.+ stages := toQueryStages([]*bigquery.ExplainQueryStage{+ nil,+ {ID: 1, Name: "S00: Input", Steps: []*bigquery.ExplainQueryStep{nil}},+ })+ require.Len(t, stages, 1)+ require.Empty(t, stages[0].Steps)++ require.Empty(t, toQueryStages(nil))+}++// TestQueryPlanWithoutJob pins that a read with no job behind it reports no+// plan, rather than failing the rows the caller asked for.+func TestQueryPlanWithoutJob(t *testing.T) {+ require.Nil(t, queryPlan(context.Background(), nil))+}diff --git a/docs/design/query-plan-visualizer.md b/docs/design/query-plan-visualizer.mdindex 1ac21d5315..4799779851 100644--- a/docs/design/query-plan-visualizer.md+++ b/docs/design/query-plan-visualizer.md@@ -28,7 +28,10 @@ This ordering is a judgment call, not a measurement.## 2. Background / problemThe editor explained on 12 engines and drew a picture for 3 (PostgreSQL, SQL-Server, Spanner); it now explains on 18 and draws for 17 (§3.4). Reaching the+Server, Spanner); it now explains on 18 and draws for 18 (§3.4) — not the same+eighteen, since Databricks explains with no parser to draw its plan, and+BigQuery draws from a plan that arrives with an ordinary run rather than with an+explain. Reaching thepicture takes five steps: Ctrl/Cmd+E → plan rows in the grid → click a small"Visualize Explain" link → Bytebase runs `EXPLAIN` a second time for JSON → aseparate browser tab opens.@@ -350,13 +353,13 @@ regression.| **OceanBase** | one `Query()`, on demand, cached | graph, costed in estimated microseconds | none in the editor || **MongoDB** | one `Query()`, on demand, cached | graph, with no estimates at all | `explain("executionStats")`, drawn for its rows || **CockroachDB** | one `Query()`, on demand, cached | graph of the physical flow, with no estimates | none in the editor — `EXPLAIN ANALYZE` executes |+| **BigQuery** | carried by the run that returned the rows, no second call | graph of the stage DAG, measured, with no estimates beside it | the plan is the measured one; BigQuery has no `EXPLAIN`, and its explain action is a dry run || **Redshift** | one `Query()`, on demand, cached | graph, drawn from the text plan | none — `EXPLAIN` never analyzes || **StarRocks** | one `Query()`, on demand, cached | graph, drawn from the text plan | none — `EXPLAIN ANALYZE` executes || **Doris** | one `Query()`, on demand, cached | graph, drawn from the text plan by the StarRocks parser | none — Doris has no `EXPLAIN ANALYZE` || **Snowflake** | one `Query()`, on demand, cached | graph, with pruning in place of estimates | none — `EXPLAIN` compiles without running, whichever format it names || **Hive** | one `Query()`, on demand, cached | graph, with rows and row widths, no costs | none in the editor || **Databricks** | one `Query()`, on demand, cached | text: Spark's `EXPLAIN FORMATTED` has no parser yet | none — `EXPLAIN` never executes what it plans |-| **Hive, Snowflake** | one `Query()`, on demand, cached | text | per engine, text at most |A plan opened from a result is always an estimate, on every engine. Measuredplans come from a typed `EXPLAIN ANALYZE` or its engine's equivalent, which is a@@ -481,18 +484,25 @@ branches the merge reads — and each node says which shard it ran on. A shardedaggregation goes further and states no pipeline of its own: the merger's partis the plan, with each shard's part under the `$mergeCursors` that reads it.-**Attaching a measured plan to an ordinary run is deferred.** Two engines could:-Spanner has a run mode returning rows and plan and real timings in one execution,-and SQL Server's `SET STATISTICS XML` does the same. That is how BigQuery,-Snowflake and Databricks work, and it is tempting.--It does not fit here. To have the plan ready when someone later clicks Plan, we-would have to profile *every* run — and Spanner documents profiling overhead and-discourages it for production traffic, while `SET STATISTICS XML` needs+**Attaching a measured plan to an ordinary run is deferred, except where the+engine states one anyway.** Spanner has a run mode returning rows and plan and+real timings in one execution, and SQL Server's `SET STATISTICS XML` does the+same. Both stay deferred: to have the plan ready when someone later clicks Plan+we would have to profile *every* run — and Spanner documents profiling overhead+and discourages it for production traffic, while `SET STATISTICS XML` needs`SHOWPLAN` on every database the statement touches, so turning it on blindlywould fail queries the user is authorized to run. Profiling only when askedrequires a control that says so before the run — the Explain analyze action §3.1-leaves out. Out of scope.+leaves out.++BigQuery asks for nothing. Every job reports the stages it ran in its own+statistics: no flag to set, no permission to hold, no overhead to weigh, and the+only cost is one `jobs.get` after the rows. So its result carries that plan in+`QueryResult.query_plan.content`, the one place a plan arrives beside the rows+rather than in them, and the Plan view draws it without explaining anything —+badged measured, since it is the record of the run the reader is looking at. A+result carrying a plan keeps its data table however few columns it has: those+rows are the query's answer, not the plan.The pop-up page, its token hand-off and the old link are deleted([#21652](https://github.com/bytebase/bytebase/pull/21652)).diff --git a/frontend/src/apps/explain-visualizer/QueryPlanView.test.tsx b/frontend/src/apps/explain-visualizer/QueryPlanView.test.tsxindex db3da2e7bc..a4f400b3e8 100644--- a/frontend/src/apps/explain-visualizer/QueryPlanView.test.tsx+++ b/frontend/src/apps/explain-visualizer/QueryPlanView.test.tsx@@ -37,6 +37,7 @@ describe("QueryPlanView", () => {[Engine.TIDB]: "tidb",[Engine.ORACLE]: "oracle",[Engine.CLICKHOUSE]: "clickhouse",+ [Engine.BIGQUERY]: "bigquery",[Engine.TRINO]: "trino",[Engine.OCEANBASE]: "oceanbase",[Engine.MONGODB]: "mongodb",diff --git a/frontend/src/apps/explain-visualizer/QueryPlanView.tsx b/frontend/src/apps/explain-visualizer/QueryPlanView.tsxindex c73bfa711e..7d737a430f 100644--- a/frontend/src/apps/explain-visualizer/QueryPlanView.tsx+++ b/frontend/src/apps/explain-visualizer/QueryPlanView.tsx@@ -2,6 +2,11 @@ import { type ReactNode, useMemo } from "react";import { Alert } from "@/components/ui/alert";import { cn } from "@/lib/utils";import type { VisualizerEngine } from "@/utils/queryPlanEngines";+import {+ BIGQUERY_PLAN_EMPTY_MESSAGE,+ BIGQUERY_PLAN_INVALID_JSON_MESSAGE,+ BIGQUERY_PLAN_NO_PLAN_MESSAGE,+} from "./bigquery-plan";import {CLICKHOUSE_PLAN_EMPTY_MESSAGE,CLICKHOUSE_PLAN_INVALID_JSON_MESSAGE,@@ -115,6 +120,9 @@ const PARSE_ERROR_KEYS = new Map<string, QueryPlanTranslationKey>([[ORACLE_PLAN_EMPTY_MESSAGE, "error.oracle-empty"],[ORACLE_PLAN_INVALID_JSON_MESSAGE, "error.oracle-invalid"],[ORACLE_PLAN_NO_PLAN_MESSAGE, "error.oracle-no-plan"],+ [BIGQUERY_PLAN_EMPTY_MESSAGE, "error.bigquery-empty"],+ [BIGQUERY_PLAN_INVALID_JSON_MESSAGE, "error.bigquery-invalid"],+ [BIGQUERY_PLAN_NO_PLAN_MESSAGE, "error.bigquery-no-plan"],[CLICKHOUSE_PLAN_EMPTY_MESSAGE, "error.clickhouse-empty"],[CLICKHOUSE_PLAN_INVALID_JSON_MESSAGE, "error.clickhouse-invalid"],[CLICKHOUSE_PLAN_NO_PLAN_MESSAGE, "error.clickhouse-no-plan"],diff --git a/frontend/src/apps/explain-visualizer/bigquery-plan.test.ts b/frontend/src/apps/explain-visualizer/bigquery-plan.test.tsnew file mode 100644index 0000000000..8faa4e428b--- /dev/null+++ b/frontend/src/apps/explain-visualizer/bigquery-plan.test.ts@@ -0,0 +1,196 @@+import { describe, expect, test } from "vitest";+import {+ BIGQUERY_PLAN_EMPTY_MESSAGE,+ BIGQUERY_PLAN_INVALID_JSON_MESSAGE,+ BIGQUERY_PLAN_NO_PLAN_MESSAGE,+ parseBigqueryPlan,+} from "./bigquery-plan";+import {+ PLAN_TOO_DEEP_MESSAGE,+ type PlanNode,+ type PlanTree,+} from "./plan-model";+import filteredAggregate from "./test-data/bigquery/filtered-aggregate.json";++/** A chain of `depth` stages, which is what drives the depth limit. */+const nestedPlan = (depth: number): string => {+ const stages: Record<string, unknown>[] = [{ id: 0, name: "S00: Input" }];+ for (let level = 1; level < depth; level += 1) {+ stages.push({+ id: level,+ name: `S0${level}: Aggregate+`,+ inputStages: [level - 1],+ });+ }+ return JSON.stringify(stages);+};++const parse = (source: string): PlanTree => {+ const result = parseBigqueryPlan(source);+ if (!result.ok)+ throw new Error(`expected a parsable plan: ${result.message}`);+ return result.tree;+};++const parseFixture = (fixture: unknown): PlanTree =>+ parse(JSON.stringify(fixture));++const outline = (tree: PlanTree): string[] =>+ tree.nodes.map(+ (node) => `${node.id} ${node.nodeType} ${node.subject ?? "-"}`+ );++const propertyValue = (node: PlanNode, label: string): string | undefined =>+ node.properties.find((property) => property.label === label)?.value;++describe("parseBigqueryPlan", () => {+ test("reads the stage that no other stage feeds as the root", () => {+ const tree = parseFixture(filteredAggregate);+ // A stage says what it read: the input stage a table, the output stage the+ // shuffle the one below it wrote, which is the engine's own name for it.+ expect(outline(tree)).toEqual([+ "0 Output __stage00_output",+ "0.0 Input analytics.customers",+ ]);+ });++ test("is measured, since the plan is the run that returned the rows", () => {+ const tree = parseFixture(filteredAggregate);+ // What each stage really wrote, with no estimate beside it.+ expect(tree.nodes[1].actualRows).toBe(2);+ expect(tree.root.actualRows).toBe(1);+ expect(tree.nodes[1].rows).toBeUndefined();+ expect(tree.measured.rows).toBe(true);+ expect(tree.estimates.rows).toBe(false);+ expect(tree.estimates.cost).toBe(false);+ });++ test("reads a measured zero as zero rather than as no measurement", () => {+ // A filter can leave the stage above it nothing to aggregate, and that is a+ // measurement: the driver encodes the zero rather than dropping it, so the+ // node says zero rows instead of saying nothing.+ const tree = parse(+ JSON.stringify([+ { id: 0, name: "S00: Input", recordsRead: 0, recordsWritten: 0 },+ {+ id: 1,+ name: "S01: Output",+ inputStages: [0],+ recordsRead: 0,+ recordsWritten: 0,+ },+ ])+ );+ expect(tree.root.actualRows).toBe(0);+ expect(tree.nodes[1].actualRows).toBe(0);+ // A plan of empty stages is still a measured plan.+ expect(tree.measured.rows).toBe(true);+ });++ test("resolves the table a stage read from its own READ step", () => {+ const tree = parseFixture(filteredAggregate);+ expect(tree.nodes[1].relation).toEqual({+ database: "analytics",+ table: "customers",+ });+ // The output stage reads a shuffle, which is not a table.+ expect(tree.root.relation).toBeUndefined();+ });++ test("leaves a table in another project unresolved", () => {+ const tree = parse(+ JSON.stringify([+ {+ id: 0,+ name: "S00: Input",+ steps: [+ {+ kind: "READ",+ substeps: ["$1:id", "FROM other-project.analytics.customers"],+ },+ ],+ },+ ])+ );+ // Named outside the connection, so the metadata here cannot answer for it.+ expect(tree.root.relation).toBeUndefined();+ expect(tree.root.subject).toBe("other-project.analytics.customers");+ });++ test("keeps the steps and the shard timings on the node", () => {+ const tree = parseFixture(filteredAggregate);+ const input = tree.nodes[1];+ expect(propertyValue(input, "Stage")).toBe("S00: Input");+ expect(propertyValue(input, "Steps")).toContain(+ "READ: $1:city, FROM analytics.customers, WHERE equal($1, 'berlin')"+ );+ expect(propertyValue(input, "Steps")).toContain("AGGREGATE:");+ expect(propertyValue(input, "Read ms avg")).toBe("11");+ expect(propertyValue(input, "Compute ms max")).toBe("9");+ expect(propertyValue(input, "Shuffle output bytes")).toBe("72");+ expect(propertyValue(input, "Records read")).toBe("4");+ });++ test("ranks nothing by time, since a stage states its shards' time", () => {+ const tree = parseFixture(filteredAggregate);+ expect(tree.root.actualTime).toBeUndefined();+ expect(tree.measured.time).toBe(false);+ });++ test("says so when there is no plan to read", () => {+ expect(parseBigqueryPlan("")).toEqual({+ ok: false,+ message: BIGQUERY_PLAN_EMPTY_MESSAGE,+ });+ expect(parseBigqueryPlan("not json")).toEqual({+ ok: false,+ message: BIGQUERY_PLAN_INVALID_JSON_MESSAGE,+ });+ // The stages are a list; an object is some other document.+ expect(parseBigqueryPlan("{}")).toEqual({+ ok: false,+ message: BIGQUERY_PLAN_INVALID_JSON_MESSAGE,+ });+ expect(parseBigqueryPlan("[]")).toEqual({+ ok: false,+ message: BIGQUERY_PLAN_NO_PLAN_MESSAGE,+ });+ });++ test("stops at a stage that reads itself", () => {+ const tree = parse(+ JSON.stringify([+ { id: 0, name: "S00: Input", inputStages: [1] },+ { id: 1, name: "S01: Output", inputStages: [0] },+ ])+ );+ // Every stage feeds another, so the last is taken as the output one and the+ // cycle below it stops.+ expect(outline(tree)).toEqual(["0 Output -", "0.0 Input -"]);+ });++ test("draws a stage two others read, under each of them", () => {+ const tree = parse(+ JSON.stringify([+ { id: 0, name: "S00: Input" },+ { id: 1, name: "S01: Join+", inputStages: [0] },+ { id: 2, name: "S02: Aggregate+", inputStages: [0] },+ { id: 3, name: "S03: Output", inputStages: [1, 2] },+ ])+ );+ expect(outline(tree)).toEqual([+ "0 Output -",+ "0.0 Join+ -",+ "0.0.0 Input -",+ "0.1 Aggregate+ -",+ "0.1.0 Input -",+ ]);+ });++ test("refuses a plan deeper than the viewer draws", () => {+ expect(parseBigqueryPlan(nestedPlan(600))).toEqual({+ ok: false,+ message: PLAN_TOO_DEEP_MESSAGE,+ });+ });+});diff --git a/frontend/src/apps/explain-visualizer/bigquery-plan.ts b/frontend/src/apps/explain-visualizer/bigquery-plan.tsnew file mode 100644index 0000000000..116cbdfde2--- /dev/null+++ b/frontend/src/apps/explain-visualizer/bigquery-plan.ts@@ -0,0 +1,231 @@+import {+ addPlanProperty,+ checkPlanDepth,+ isJsonRecord,+ type JsonRecord,+ type PlanNode,+ type PlanParseResult,+ type PlanProperty,+ type PlanRelation,+ parseWithDepthLimit,+ planLabel,+ planSizeBudget,+} from "./plan-model";++/**+ * Maps the stages of a BigQuery job onto the engine-neutral plan model.+ *+ * BigQuery has no EXPLAIN. What a result carries is the plan of the job that+ * returned it: the stages the query ran as, each naming the stages that fed+ * it. So this plan is measured rather than estimated — the records are what+ * each stage really read and wrote, and there are no estimates beside them.+ *+ * Nothing is ranked by time. A stage states what its average and slowest shard+ * spent waiting, reading, computing and writing, which is a shard's time rather+ * than the stage's, and adding the phases of one shard would not make the+ * stage's own duration. They stay on the node, and the graph shades by rows.+ */++const INPUTS_KEY = "inputStages";++/** Keys the model promotes to typed fields, so the property list drops them. */+const PROMOTED_KEYS = new Set(["id", "name", "steps", INPUTS_KEY]);++/** A stage's name carries its number and what it does: `S00: Input`. */+const STAGE_NAME = /^\s*S\d+\s*:\s*(.+?)\s*$/;++/** The step that reads a table, and the substep that names it. */+const READ_KIND = "READ";+const READ_FROM = /^FROM\s+(\S+)$/;++/**+ * BigQuery writes a table as `dataset.table`. A name carrying a project as well+ * names a table outside the connection, which stays on the card as the subject+ * and resolves to no relation: Bytebase's metadata is this connection's, and+ * answering from it would describe a different table of the same name.+ */+const DATASET_TABLE = /^([^.]+)\.([^.]+)$/;++export const BIGQUERY_PLAN_EMPTY_MESSAGE =+ "BigQuery returned no query plan for this statement.";+export const BIGQUERY_PLAN_INVALID_JSON_MESSAGE =+ "The query plan is not valid JSON. The stages of a BigQuery job are expected.";+export const BIGQUERY_PLAN_NO_PLAN_MESSAGE =+ "The query plan contains no stage to start from.";++function optionalNumber(value: unknown): number | undefined {+ if (typeof value === "number" && Number.isFinite(value)) return value;+ if (typeof value === "string" && value.trim()) {+ const parsed = Number(value);+ if (Number.isFinite(parsed)) return parsed;+ }+ return undefined;+}++function stringValue(value: unknown): string | undefined {+ return typeof value === "string" && value.trim() ? value : undefined;+}++function stageID(raw: JsonRecord): string | undefined {+ const id = optionalNumber(raw.id);+ return id === undefined ? stringValue(raw.id) : String(id);+}++/** The steps of a stage, in the order BigQuery ran them. */+function stepsOf(raw: JsonRecord): JsonRecord[] {+ return Array.isArray(raw.steps) ? raw.steps.filter(isJsonRecord) : [];+}++/** The substeps of a step, which are the engine's own words for what it did. */+function substepsOf(step: JsonRecord): string[] {+ return Array.isArray(step.substeps)+ ? step.substeps+ .map((substep) => stringValue(substep))+ .filter((substep): substep is string => substep !== undefined)+ : [];+}++/**+ * The table the stage reads, which BigQuery names in the `FROM` substep of its+ * read. A stage reading another stage's shuffle names that instead, which is+ * not a table and resolves to none.+ */+function readTable(raw: JsonRecord): string | undefined {+ for (const step of stepsOf(raw)) {+ if (stringValue(step.kind) !== READ_KIND) continue;+ for (const substep of substepsOf(step)) {+ const named = READ_FROM.exec(substep);+ if (named) return named[1];+ }+ }+ return undefined;+}++function toRelation(raw: JsonRecord): PlanRelation | undefined {+ const table = readTable(raw);+ const named = table ? DATASET_TABLE.exec(table) : null;+ // A dataset is the database the editor connects to.+ return named ? { database: named[1], table: named[2] } : undefined;+}++function toProperties(raw: JsonRecord): PlanProperty[] {+ const properties: PlanProperty[] = [];+ // The stage's own name, which is how BigQuery's job statistics refer to it.+ const name = stringValue(raw.name);+ if (name) addPlanProperty(properties, "Stage", name);+ for (const step of stepsOf(raw)) {+ const kind = stringValue(step.kind);+ if (!kind) continue;+ const substeps = substepsOf(step);+ addPlanProperty(+ properties,+ "Steps",+ substeps.length > 0 ? `${kind}: ${substeps.join(", ")}` : kind+ );+ }+ for (const [key, value] of Object.entries(raw)) {+ if (PROMOTED_KEYS.has(key)) continue;+ const scalar =+ typeof value === "string" || typeof value === "number"+ ? String(value)+ : undefined;+ if (scalar !== undefined)+ addPlanProperty(properties, planLabel(key), scalar);+ }+ return properties;+}++/**+ * @param seen - The stages on the path to this node. A stage that reads itself,+ * directly or through another, would never finish; the rest of the plan still+ * draws.+ * @param count - The size budget, since a stage two others read is drawn under+ * each of them.+ */+function toPlanNode(+ raw: JsonRecord,+ stages: Map<string, JsonRecord>,+ id: string,+ seen: Set<string>,+ depth: number,+ count: () => void+): PlanNode {+ checkPlanDepth(depth);+ count();+ const children: PlanNode[] = [];+ const inputs = Array.isArray(raw[INPUTS_KEY]) ? raw[INPUTS_KEY] : [];+ for (const input of inputs) {+ const inputID = String(input);+ const stage = stages.get(inputID);+ if (!stage || seen.has(inputID)) continue;+ seen.add(inputID);+ children.push(+ toPlanNode(+ stage,+ stages,+ `${id}.${children.length}`,+ seen,+ depth + 1,+ count+ )+ );+ seen.delete(inputID);+ }++ const name = stringValue(raw.name);+ return {+ id,+ // What the stage does, which its name states after the stage number.+ nodeType:+ (name ? STAGE_NAME.exec(name)?.[1] : undefined) ?? name ?? "Stage",+ subject: readTable(raw),+ relation: toRelation(raw),+ actualRows: optionalNumber(raw.recordsWritten),+ properties: toProperties(raw),+ warnings: [],+ children,+ };+}++export function parseBigqueryPlan(source: string): PlanParseResult {+ const trimmed = source.trim();+ if (!trimmed) {+ return { ok: false, message: BIGQUERY_PLAN_EMPTY_MESSAGE };+ }++ let parsed: unknown;+ try {+ parsed = JSON.parse(trimmed);+ } catch {+ return { ok: false, message: BIGQUERY_PLAN_INVALID_JSON_MESSAGE };+ }+ if (!Array.isArray(parsed)) {+ return { ok: false, message: BIGQUERY_PLAN_INVALID_JSON_MESSAGE };+ }++ const stages = new Map<string, JsonRecord>();+ for (const stage of parsed.filter(isJsonRecord)) {+ const id = stageID(stage);+ if (id !== undefined && !stages.has(id)) stages.set(id, stage);+ }+ if (stages.size === 0) {+ return { ok: false, message: BIGQUERY_PLAN_NO_PLAN_MESSAGE };+ }++ // The stage no other stage reads is the one that returned the query's rows.+ const read = new Set<string>();+ for (const stage of stages.values()) {+ const inputs = Array.isArray(stage[INPUTS_KEY]) ? stage[INPUTS_KEY] : [];+ for (const input of inputs) read.add(String(input));+ }+ const roots = [...stages.entries()].filter(([id]) => !read.has(id));+ // Where every stage feeds another, which would be a cycle, the last stage is+ // still the output one; BigQuery lists them in the order it ran them.+ const [rootID, root] =+ roots[roots.length - 1] ?? [...stages.entries()][stages.size - 1];++ const count = planSizeBudget();+ return parseWithDepthLimit(() =>+ toPlanNode(root, stages, "0", new Set([rootID]), 0, count)+ );+}diff --git a/frontend/src/apps/explain-visualizer/plan-i18n.tsx b/frontend/src/apps/explain-visualizer/plan-i18n.tsxindex b7e7ffed27..3bcc5ea39f 100644--- a/frontend/src/apps/explain-visualizer/plan-i18n.tsx+++ b/frontend/src/apps/explain-visualizer/plan-i18n.tsx@@ -24,6 +24,10 @@ const ENGLISH = {"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.bigquery-empty": "BigQuery returned no query plan for this statement.",+ "error.bigquery-invalid":+ "The query plan is not valid JSON. The stages of a BigQuery job are expected.",+ "error.bigquery-no-plan": "The query plan contains no stage to start from.","error.clickhouse-empty":"ClickHouse returned no query plan for this statement.","error.clickhouse-invalid":diff --git a/frontend/src/apps/explain-visualizer/plan-parsers.ts b/frontend/src/apps/explain-visualizer/plan-parsers.tsindex f08b593de2..2016065301 100644--- a/frontend/src/apps/explain-visualizer/plan-parsers.ts+++ b/frontend/src/apps/explain-visualizer/plan-parsers.ts@@ -1,5 +1,6 @@import { Engine } from "@/types/proto-es/v1/common_pb";import type { VisualizerEngine } from "@/utils/queryPlanEngines";+import { parseBigqueryPlan } from "./bigquery-plan";import { parseClickhousePlan } from "./clickhouse-plan";import { parseCockroachdbPlan } from "./cockroachdb-plan";import { parseHivePlan } from "./hive-plan";@@ -50,6 +51,9 @@ const PARSERS: Record<VisualizerEngine, (source: string) => PlanParseResult> = {[Engine.SNOWFLAKE]: parseSnowflakePlan,// Hive answers with Calcite's own plan, as a JSON string within the JSON.[Engine.HIVE]: parseHivePlan,+ // BigQuery's plan is the stages of the job that returned the rows, so it is+ // measured rather than estimated.+ [Engine.BIGQUERY]: parseBigqueryPlan,// The text plans drawn here, because none of these engines publishes// anything else. StarRocks forked from Doris and their plans still agree on// the fragments and the tree, so one parser reads both.diff --git a/frontend/src/apps/explain-visualizer/test-data/README.md b/frontend/src/apps/explain-visualizer/test-data/README.mdindex 1429da06b0..1237a566af 100644--- a/frontend/src/apps/explain-visualizer/test-data/README.md+++ b/frontend/src/apps/explain-visualizer/test-data/README.md@@ -363,3 +363,17 @@ where its cost-based optimizer planned the statement.| `no-cbo-plan.json` | `hive.cbo.enable=false`: the Tez stages alone, with no `CBOPlan`, which the viewer shows as text |To add one, `EXPLAIN FORMATTED` through the same client.++## `bigquery/`++The stages of a BigQuery job as the driver encodes them: BigQuery's own REST+names for `ExplainQueryStage`, with its durations as milliseconds. BigQuery is+reachable from neither a dev box nor CI, so this is the driver's own output for+the stage list in `backend/plugin/db/bigquery/query_plan_test.go`, which holds+the shape a job reports — regenerate it from there rather than editing it. Every+plan here is measured, being the record of a run; BigQuery states none for a+statement it has not run.++| File | Shape it covers |+| --- | --- |+| `filtered-aggregate.json` | Two stages: the input reads a table, aggregates and writes a shuffle, and the output reads that shuffle and writes the query's rows |diff --git a/frontend/src/apps/explain-visualizer/test-data/bigquery/filtered-aggregate.json b/frontend/src/apps/explain-visualizer/test-data/bigquery/filtered-aggregate.jsonnew file mode 100644index 0000000000..f71e9e59b6--- /dev/null+++ b/frontend/src/apps/explain-visualizer/test-data/bigquery/filtered-aggregate.json@@ -0,0 +1,55 @@+[+ {+ "id": 0,+ "name": "S00: Input",+ "status": "COMPLETE",+ "steps": [+ {+ "kind": "READ",+ "substeps": [+ "$1:city",+ "FROM analytics.customers",+ "WHERE equal($1, 'berlin')"+ ]+ },+ {+ "kind": "AGGREGATE",+ "substeps": ["GROUP BY $10 := $1", "$20 := COUNT(*)"]+ },+ { "kind": "WRITE", "substeps": ["$10, $20", "TO __stage00_output"] }+ ],+ "recordsRead": 4,+ "recordsWritten": 2,+ "parallelInputs": 1,+ "completedParallelInputs": 1,+ "shuffleOutputBytes": 72,+ "waitMsAvg": 2,+ "waitMsMax": 3,+ "readMsAvg": 11,+ "readMsMax": 14,+ "computeMsAvg": 7,+ "computeMsMax": 9,+ "writeMsAvg": 1,+ "writeMsMax": 1+ },+ {+ "id": 1,+ "name": "S01: Output",+ "status": "COMPLETE",+ "inputStages": [0],+ "steps": [+ { "kind": "READ", "substeps": ["$10, $20", "FROM __stage00_output"] },+ {+ "kind": "AGGREGATE",+ "substeps": ["GROUP BY $30 := $10", "$40 := SUM_OF_COUNTS($20)"]+ },+ { "kind": "WRITE", "substeps": ["$30, $40", "TO __stage01_output"] }+ ],+ "recordsRead": 2,+ "recordsWritten": 1,+ "parallelInputs": 1,+ "waitMsAvg": 1,+ "computeMsAvg": 3,+ "computeMsMax": 3+ }+]diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.jsonindex 3013d02510..00a5f11c20 100644--- a/frontend/src/locales/en-US.json+++ b/frontend/src/locales/en-US.json@@ -3602,6 +3602,9 @@"zoom-out": "Zoom out"},"error": {+ "bigquery-empty": "BigQuery returned no query plan for this statement.",+ "bigquery-invalid": "The query plan is not valid JSON. The stages of a BigQuery job are expected.",+ "bigquery-no-plan": "The query plan contains no stage to start from.","clickhouse-empty": "ClickHouse returned no query plan for this statement.","clickhouse-invalid": "The query plan is not valid JSON. EXPLAIN json = 1 output is expected.","clickhouse-no-plan": "The ClickHouse query plan JSON does not contain a \"Plan\" object.",diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.jsonindex eb813bc87c..48d8ec6193 100644--- a/frontend/src/locales/es-ES.json+++ b/frontend/src/locales/es-ES.json@@ -3602,6 +3602,9 @@"zoom-out": "Alejar"},"error": {+ "bigquery-empty": "BigQuery no devolvió ningún plan de consulta para esta sentencia.",+ "bigquery-invalid": "El plan de consulta no es JSON válido. Se esperan las etapas de un trabajo de BigQuery.",+ "bigquery-no-plan": "El plan de consulta no contiene ninguna etapa por la que empezar.","clickhouse-empty": "ClickHouse no devolvió ningún plan de consulta para esta sentencia.","clickhouse-invalid": "El plan de consulta no es JSON válido. Se espera la salida de EXPLAIN json = 1.","clickhouse-no-plan": "El JSON del plan de consulta de ClickHouse no contiene un objeto \"Plan\".",diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.jsonindex b32f2d3eaf..d4df2f353a 100644--- a/frontend/src/locales/ja-JP.json+++ b/frontend/src/locales/ja-JP.json@@ -3602,6 +3602,9 @@"zoom-out": "縮小"},"error": {+ "bigquery-empty": "BigQuery はこのステートメントのクエリプランを返しませんでした。",+ "bigquery-invalid": "クエリプランが有効な JSON ではありません。BigQuery ジョブのステージが必要です。",+ "bigquery-no-plan": "クエリプランに開始できるステージがありません。","clickhouse-empty": "ClickHouse はこのステートメントのクエリプランを返しませんでした。","clickhouse-invalid": "クエリプランが有効な JSON ではありません。EXPLAIN json = 1 の出力が必要です。","clickhouse-no-plan": "ClickHouse のクエリプラン JSON に \"Plan\" オブジェクトがありません。",diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.jsonindex 07a655419b..853cf2c8f6 100644--- a/frontend/src/locales/vi-VN.json+++ b/frontend/src/locales/vi-VN.json@@ -3602,6 +3602,9 @@"zoom-out": "Thu nhỏ"},"error": {+ "bigquery-empty": "BigQuery không trả về kế hoạch truy vấn cho câu lệnh này.",+ "bigquery-invalid": "Kế hoạch truy vấn không phải JSON hợp lệ. Cần các giai đoạn của một job BigQuery.",+ "bigquery-no-plan": "Kế hoạch truy vấn không có giai đoạn nào để bắt đầu.","clickhouse-empty": "ClickHouse không trả về kế hoạch truy vấn cho câu lệnh này.","clickhouse-invalid": "Kế hoạch truy vấn không phải JSON hợp lệ. Cần đầu ra EXPLAIN json = 1.","clickhouse-no-plan": "JSON của kế hoạch truy vấn ClickHouse không chứa đối tượng \"Plan\".",diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.jsonindex d6b6d020a2..ed163fb445 100644--- a/frontend/src/locales/zh-CN.json+++ b/frontend/src/locales/zh-CN.json@@ -3602,6 +3602,9 @@"zoom-out": "缩小"},"error": {+ "bigquery-empty": "BigQuery 未返回此语句的查询计划。",+ "bigquery-invalid": "查询计划不是有效的 JSON。需要 BigQuery 作业的阶段信息。",+ "bigquery-no-plan": "查询计划中没有可作为起点的阶段。","clickhouse-empty": "ClickHouse 未返回此语句的查询计划。","clickhouse-invalid": "查询计划不是有效的 JSON。需要 EXPLAIN json = 1 输出。","clickhouse-no-plan": "ClickHouse 查询计划 JSON 不包含 \"Plan\" 对象。",diff --git a/frontend/src/modules/sql-editor/components/ResultView/SingleResultView.test.tsx b/frontend/src/modules/sql-editor/components/ResultView/SingleResultView.test.tsxindex a604a02210..a7d3a1a4a6 100644--- a/frontend/src/modules/sql-editor/components/ResultView/SingleResultView.test.tsx+++ b/frontend/src/modules/sql-editor/components/ResultView/SingleResultView.test.tsx@@ -292,6 +292,7 @@ vi.mock("./QueryPlanResultView", () => ({rawPlan,initialPlan,loadPlan,+ estimated,disallowCopyingData,}: {rawPlan: string;@@ -299,6 +300,7 @@ vi.mock("./QueryPlanResultView", () => ({loadPlan?: () => Promise<{ source: string } | undefined>;+ estimated?: boolean;disallowCopyingData?: boolean;}) => {const [plan, setPlan] = useState(initialPlan);@@ -306,6 +308,7 @@ vi.mock("./QueryPlanResultView", () => ({<divdata-testid="query-plan-result"data-copy-disabled={disallowCopyingData}+ data-estimated={estimated ? "true" : "false"}><span data-testid="raw-plan">{rawPlan}</span>{plan ? <span data-testid="inline-plan">{plan.source}</span> : null}@@ -1196,6 +1199,47 @@ describe("SingleResultView plan view", () => {/>);+ test("draws the plan an engine stated beside the rows, without fetching", () => {+ // BigQuery reports the stages its job ran, so the Plan view has the plan+ // already: nothing is explained again, and what it shows is a record of the+ // run that returned these rows rather than an estimate made since.+ const content = JSON.stringify([{ id: 0, name: "S00: Input" }]);+ renderRows(Engine.BIGQUERY, {+ result: create(QueryResultSchema, {+ statement: "SELECT * FROM t",+ columnNames: ["id"],+ columnTypeNames: ["INT"],+ rows: [+ create(QueryRowSchema, {+ values: [+ create(RowValueSchema, {+ kind: { case: "stringValue", value: "1" },+ }),+ ],+ }),+ ],+ queryPlan: create(QueryResult_QueryPlanSchema, {+ format: QueryOption_ExplainFormat.JSON,+ executed: true,+ content,+ }),+ }),+ });++ // The rows are the query's data, so the table is what opens.+ expect(screen.getByTestId("result-table")).toBeInTheDocument();+ fireEvent.click(screen.getByText("sql-editor.plan-view"));++ expect(screen.getByTestId("inline-plan")).toHaveTextContent("S00: Input");+ expect(screen.getByTestId("query-plan-result")).toHaveAttribute(+ "data-estimated",+ "false"+ );+ // No button to load one: there is nothing left to ask the server for.+ expect(screen.queryByRole("button", { name: "common.plan" })).toBeNull();+ expect(runQuery).not.toHaveBeenCalled();+ });+test("offers Plan beside Table and Vertical and shows the plan in place", () => {renderRows(Engine.POSTGRES);diff --git a/frontend/src/modules/sql-editor/components/ResultView/SingleResultView.tsx b/frontend/src/modules/sql-editor/components/ResultView/SingleResultView.tsxindex 02e3d2098d..c204c80aa6 100644--- a/frontend/src/modules/sql-editor/components/ResultView/SingleResultView.tsx+++ b/frontend/src/modules/sql-editor/components/ResultView/SingleResultView.tsx@@ -534,6 +534,9 @@ function SingleResultViewInner({plan?.format ===QueryOption_ExplainFormat[VISUALIZER_EXPLAIN_FORMATS[engine]];const planInResult = useMemo(() => inlineQueryPlan(result), [result]);+ // The plan BigQuery states beside the rows: already in hand, and a record of+ // the run that returned them rather than an estimate made since.+ const carriedPlan = plan?.content ? planInResult : undefined;const canReplay =isVisualizerEngine(engine) &&!!plan &&@@ -544,9 +547,11 @@ function SingleResultViewInner({!plan.executed &&canReplayStatement(results, resultIndex);// Multi-column plans (SQL Server SHOWPLAN_ALL) keep their table unless the- // XML plan can be loaded for the visualizer.+ // XML plan can be loaded for the visualizer. A plan the engine stated beside+ // the rows leaves them as the query's data, however few columns they have,+ // so that result keeps its table and the plan stays in the Plan view.const showInlinePlan =- !!plan && (result.columnNames.length === 1 || canReplay);+ !!plan && !carriedPlan && (result.columnNames.length === 1 || canReplay);const loadPlan = useCallback((signal: AbortSignal) =>isVisualizerEngine(engine)@@ -816,11 +821,11 @@ function SingleResultViewInner({<QueryPlanResultViewkey={planViewKey(result)}rawPlan=""- initialPlan={resultPlan}+ initialPlan={carriedPlan ?? resultPlan}engine={isVisualizerEngine(engine) ? engine : undefined}describeTable={describeTable}- loadPlan={loadResultPlan}- estimated+ loadPlan={carriedPlan ? undefined : loadResultPlan}+ estimated={!carriedPlan}onCancel={() => setLayout("TABLE")}disallowCopyingData={disallowCopyingData}/>diff --git a/frontend/src/modules/sql-editor/components/ResultView/planAvailability.test.ts b/frontend/src/modules/sql-editor/components/ResultView/planAvailability.test.tsindex 4d86b9f158..eae55dc577 100644--- a/frontend/src/modules/sql-editor/components/ResultView/planAvailability.test.ts+++ b/frontend/src/modules/sql-editor/components/ResultView/planAvailability.test.ts@@ -35,7 +35,33 @@ const offered = (overrides: Partial<Parameters<typeof planAvailability>[0]>) =>...overrides,});+/** A result whose rows are data and whose plan came back beside them. */+const carriedPlan = () =>+ create(QueryResultSchema, {+ statement: "SELECT city, count(*) FROM customers GROUP BY city",+ columnNames: ["city", "f0_"],+ queryPlan: create(QueryResult_QueryPlanSchema, {+ format: QueryOption_ExplainFormat.JSON,+ executed: true,+ content: '[{"id":0,"name":"S00: Input"}]',+ }),+ });+describe("planAvailability", () => {+ test("offers the plan an engine stated beside the rows", () => {+ // BigQuery reports the stages its job ran, so the plan is in hand: the view+ // draws it without an explain request, which is why neither the engine's+ // explain support nor the permission for one gates it.+ expect(+ offered({+ result: carriedPlan(),+ results: [carriedPlan()],+ engineExplains: false,+ canExplain: false,+ })+ ).toBe("offered");+ });+test("offers a plan for an ordinary read", () => {expect(offered({})).toBe("offered");});diff --git a/frontend/src/modules/sql-editor/components/ResultView/planAvailability.ts b/frontend/src/modules/sql-editor/components/ResultView/planAvailability.tsindex 2f2d87bdcc..e4b2c2d5b6 100644--- a/frontend/src/modules/sql-editor/components/ResultView/planAvailability.ts+++ b/frontend/src/modules/sql-editor/components/ResultView/planAvailability.ts@@ -41,6 +41,12 @@ export function planAvailability({engineExplains: boolean;canExplain: boolean;}): PlanAvailability {+ // A plan the engine stated beside the result is in hand: the Plan view draws+ // it without asking the server for anything, so neither the engine's explain+ // support nor the permission to explain gates it.+ if (result.queryPlan?.content) {+ return "offered";+ }if (result.queryPlan || !engineExplains || !result.statement) {return "absent";}diff --git a/frontend/src/modules/sql-editor/components/ResultView/resultPlans.test.ts b/frontend/src/modules/sql-editor/components/ResultView/resultPlans.test.tsindex bf182111a7..911ea3b017 100644--- a/frontend/src/modules/sql-editor/components/ResultView/resultPlans.test.ts+++ b/frontend/src/modules/sql-editor/components/ResultView/resultPlans.test.ts@@ -37,6 +37,27 @@ const planResult = (totalCost: number) => {};describe("inlineQueryPlan", () => {+ test("prefers the plan an engine stated beside the rows", () => {+ // BigQuery's result holds the query's data, and its plan arrives with the+ // job rather than in those rows, so the rows are not the plan to read.+ const content = '[{"id":0,"name":"S00: Input"}]';+ const result = create(QueryResultSchema, {+ statement: "SELECT city FROM customers",+ columnNames: ["city"],+ rows: [+ create(QueryRowSchema, {+ values: [+ create(RowValueSchema, {+ kind: { case: "stringValue", value: "berlin" },+ }),+ ],+ }),+ ],+ queryPlan: create(QueryResult_QueryPlanSchema, { content }),+ });+ expect(inlineQueryPlan(result)?.source).toBe(content);+ });+test("joins a single-column plan into its source text", () => {expect(inlineQueryPlan(textResult(["Seq Scan on t", " Filter: (a = 1)"]))diff --git a/frontend/src/modules/sql-editor/components/ResultView/resultPlans.ts b/frontend/src/modules/sql-editor/components/ResultView/resultPlans.tsindex f7d5b0c45a..08910ab5d3 100644--- a/frontend/src/modules/sql-editor/components/ResultView/resultPlans.ts+++ b/frontend/src/modules/sql-editor/components/ResultView/resultPlans.ts@@ -9,6 +9,10 @@ import type { InlineQueryPlan } from "./QueryPlanResultView";export function inlineQueryPlan(result: QueryResult): InlineQueryPlan | undefined {+ // A plan the engine states beside the result rather than in its rows, which+ // is how BigQuery reports the stages its job ran.+ const carried = result.queryPlan?.content;+ if (carried) return { source: carried };const lines = result.rows.map((row) =>row.values.map((value) => String(extractSQLRowValuePlain(value))));diff --git a/frontend/src/types/proto-es/v1/sql_service_pb.d.ts b/frontend/src/types/proto-es/v1/sql_service_pb.d.tsindex 39c239df8a..520ade3e2e 100644--- a/frontend/src/types/proto-es/v1/sql_service_pb.d.ts+++ b/frontend/src/types/proto-es/v1/sql_service_pb.d.ts@@ -652,7 +652,7 @@ export enum QueryResult_Message_Level {export declare const QueryResult_Message_LevelSchema: GenEnum<QueryResult_Message_Level>;/**- * A query plan held in the result's rows.+ * A query plan the result carries: in its rows, or beside them.** @generated from message bytebase.v1.QueryResult.QueryPlan*/@@ -669,6 +669,18 @@ export declare type QueryResult_QueryPlan = Message<"bytebase.v1.QueryResult.Que* @generated from field: bool executed = 2;*/executed: boolean;++ /**+ * The plan itself, where the engine states it beside the result rather+ * than in the result's rows. BigQuery reports the stages its job ran in+ * the job's own statistics, so one result carries the query's data and+ * the plan of the run that produced it. Empty when the plan is the rows,+ * which is every other engine. Omitted from the audit log, as the rows+ * are: the statement is what an audit reads.+ *+ * @generated from field: string content = 3;+ */+ content: string;};/**diff --git a/frontend/src/types/proto-es/v1/sql_service_pb.js b/frontend/src/types/proto-es/v1/sql_service_pb.jsindex c63843231f..059efdc8f4 100644--- a/frontend/src/types/proto-es/v1/sql_service_pb.js+++ b/frontend/src/types/proto-es/v1/sql_service_pb.js@@ -15,7 +15,7 @@ import { file_v1_query_history_service } from "./query_history_service_pb";* Describes the file v1/sql_service.proto.*/export const file_v1_sql_service = /*@__PURE__*/- fileDesc("ChR2MS9zcWxfc2VydmljZS5wcm90bxILYnl0ZWJhc2UudjEiqgEKE0FkbWluRXhlY3V0ZVJlcXVlc3QSKwoEbmFtZRgBIAEoCUId4EEC+kEXChVieXRlYmFzZS5jb20vRGF0YWJhc2USEQoJc3RhdGVtZW50GAIgASgJEg0KBWxpbWl0GAMgASgFEhMKBnNjaGVtYRgEIAEoCUgAiAEBEhYKCWNvbnRhaW5lchgFIAEoCUgBiAEBQgkKB19zY2hlbWFCDAoKX2NvbnRhaW5lciJBChRBZG1pbkV4ZWN1dGVSZXNwb25zZRIpCgdyZXN1bHRzGAEgAygLMhguYnl0ZWJhc2UudjEuUXVlcnlSZXN1bHQi/AEKDFF1ZXJ5UmVxdWVzdBIrCgRuYW1lGAEgASgJQh3gQQL6QRcKFWJ5dGViYXNlLmNvbS9EYXRhYmFzZRIRCglzdGF0ZW1lbnQYAiABKAkSDQoFbGltaXQYAyABKAUSFgoOZGF0YV9zb3VyY2VfaWQYBCABKAkSDwoHZXhwbGFpbhgFIAEoCBITCgZzY2hlbWEYBiABKAlIAIgBARIuCgxxdWVyeV9vcHRpb24YByABKAsyGC5ieXRlYmFzZS52MS5RdWVyeU9wdGlvbhIWCgljb250YWluZXIYCCABKAlIAYgBAUIJCgdfc2NoZW1hQgwKCl9jb250YWluZXIiWAoNUXVlcnlSZXNwb25zZRIpCgdyZXN1bHRzGAEgAygLMhguYnl0ZWJhc2UudjEuUXVlcnlSZXN1bHQSHAoUYXBwbGllZF9hY2Nlc3NfZ3JhbnQYAiABKAki6gIKC1F1ZXJ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J5dGViYXNlLnYxLkxpc3RRdWVyeUhpc3Rvcmllc1Jlc3BvbnNlIimIAgGK6jAWYmIucXVlcnlIaXN0b3JpZXMubGlzdJDqMAGg6jAEqOowChJeCg9HZXRRdWVyeUhpc3RvcnkSIy5ieXRlYmFzZS52MS5HZXRRdWVyeUhpc3RvcnlSZXF1ZXN0GhkuYnl0ZWJhc2UudjEuUXVlcnlIaXN0b3J5IguIAgGQ6jACoOowARLTAQoGRXhwb3J0EhouYnl0ZWJhc2UudjEuRXhwb3J0UmVxdWVzdBobLmJ5dGViYXNlLnYxLkV4cG9ydFJlc3BvbnNlIo8BiuowEGJiLmRhdGFiYXNlcy5nZXSQ6jABmOowAaDqMAKC0+STAmk6ASpaOToBKiI0L3YxL3tuYW1lPXByb2plY3RzLyovaW5zdGFuY2VzLyovZGF0YWJhc2VzLyp9OmV4cG9ydCIpL3YxL3tuYW1lPWluc3RhbmNlcy8qL2RhdGFiYXNlcy8qfTpleHBvcnRCpQEKD2NvbS5ieXRlYmFzZS52MUIPU3FsU2VydmljZVByb3RvUAFaNGdpdGh1Yi5jb20vYnl0ZWJhc2UvYnl0ZWJhc2UvYmFja2VuZC9nZW5lcmF0ZWQtZ28vdjGiAgNCWFiqAgtCeXRlYmFzZS5WMcoCC0J5dGViYXNlXFYx4gIXQnl0ZWJhc2VcVjFcR1BCTWV0YWRhdGHqAgxCeXRlYmFzZTo6VjFiBnByb3RvMw", [file_google_api_annotations, file_google_api_field_behavior, file_google_api_resource, file_google_protobuf_duration, file_google_protobuf_struct, file_google_protobuf_timestamp, file_v1_annotation, file_v1_common, file_v1_query_history_service]);+ fileDesc("ChR2MS9zcWxfc2VydmljZS5wcm90bxILYnl0ZWJhc2UudjEiqgEKE0FkbWluRXhlY3V0ZVJlcXVlc3QSKwoEbmFtZRgBIAEoCUId4EEC+kEXChVieXRlYmFzZS5jb20vRGF0YWJhc2USEQoJc3RhdGVtZW50GAIgASgJEg0KBWxpbWl0GAMgASgFEhMKBnNjaGV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bWU9cHJvamVjdHMvKi9pbnN0YW5jZXMvKi9kYXRhYmFzZXMvKn06ZXhwb3J0IikvdjEve25hbWU9aW5zdGFuY2VzLyovZGF0YWJhc2VzLyp9OmV4cG9ydEKlAQoPY29tLmJ5dGViYXNlLnYxQg9TcWxTZXJ2aWNlUHJvdG9QAVo0Z2l0aHViLmNvbS9ieXRlYmFzZS9ieXRlYmFzZS9iYWNrZW5kL2dlbmVyYXRlZC1nby92MaICA0JYWKoCC0J5dGViYXNlLlYxygILQnl0ZWJhc2VcVjHiAhdCeXRlYmFzZVxWMVxHUEJNZXRhZGF0YeoCDEJ5dGViYXNlOjpWMWIGcHJvdG8z", [file_google_api_annotations, file_google_api_field_behavior, file_google_api_resource, file_google_protobuf_duration, file_google_protobuf_struct, file_google_protobuf_timestamp, file_v1_annotation, file_v1_common, file_v1_query_history_service]);/*** Describes the message bytebase.v1.AdminExecuteRequest.diff --git a/frontend/src/utils/queryPlanEngines.test.ts b/frontend/src/utils/queryPlanEngines.test.tsindex a47c0977f0..8b7d3b2298 100644--- a/frontend/src/utils/queryPlanEngines.test.ts+++ b/frontend/src/utils/queryPlanEngines.test.ts@@ -26,6 +26,7 @@ describe("isVisualizerEngine", () => {Engine.COCKROACHDB,Engine.SNOWFLAKE,Engine.HIVE,+ Engine.BIGQUERY,Engine.REDSHIFT,Engine.STARROCKS,Engine.DORIS,@@ -37,12 +38,15 @@ describe("isVisualizerEngine", () => {expect(isVisualizerEngine(Engine.DATABRICKS)).toBe(false);});- test("names only engines the editor offers Explain on", () => {+ test("names only engines whose plan the editor can reach", () => {// Explain is how a plan is asked for, so a parser for an engine the editor- // does not explain would never be reached.+ // does not explain would never be reached — unless the plan comes back with+ // an ordinary run, which is how BigQuery reports one.for (const engine of Object.keys(VISUALIZER_EXPLAIN_FORMATS).map(Number)) {+ if (engine === Engine.BIGQUERY) continue;expect(instanceV1AllowsExplain(engine), Engine[engine]).toBe(true);}+ expect(instanceV1AllowsExplain(Engine.BIGQUERY)).toBe(false);});});@@ -87,12 +91,20 @@ describe("explainQueryOption", () => {}});+ test("leaves BigQuery's explain request alone, since it is a dry run", () => {+ // Asking for the format the viewer draws would refuse the dry run, and the+ // plan it draws arrives with an ordinary run rather than this request.+ expect(explainQueryOption(Engine.BIGQUERY).explainFormat).toBe(+ QueryOption_ExplainFormat.EXPLAIN_FORMAT_UNSPECIFIED+ );+ });+test("leaves an engine the viewer cannot draw on its own default", () => {// Databricks explains, in Spark's own FORMATTED text, which has no reader.expect(explainQueryOption(Engine.DATABRICKS).explainFormat).toBe(QueryOption_ExplainFormat.EXPLAIN_FORMAT_UNSPECIFIED);- expect(explainQueryOption(Engine.BIGQUERY).explainFormat).toBe(+ expect(explainQueryOption(Engine.HIVE).explainFormat).not.toBe(QueryOption_ExplainFormat.EXPLAIN_FORMAT_UNSPECIFIED);});diff --git a/frontend/src/utils/queryPlanEngines.ts b/frontend/src/utils/queryPlanEngines.tsindex 2347da8fe4..039f6551b2 100644--- a/frontend/src/utils/queryPlanEngines.ts+++ b/frontend/src/utils/queryPlanEngines.ts@@ -26,6 +26,9 @@ export const VISUALIZER_EXPLAIN_FORMATS = {[Engine.COCKROACHDB]: "JSON",[Engine.SNOWFLAKE]: "JSON",[Engine.HIVE]: "JSON",+ // BigQuery states no plan for a statement it has not run. What it reports is+ // the stages of a job that did, which the result carries beside its rows.+ [Engine.BIGQUERY]: "JSON",// These three publish no plan as a document; their text plan is what there// is.[Engine.REDSHIFT]: "TEXT",@@ -42,10 +45,16 @@ export const isVisualizerEngine = (/*** The options of an explain request: the format the visualizer draws where the* engine has one, and the engine's default otherwise.+ *+ * BigQuery is the exception on both counts. Its explain request is a dry run,+ * which validates a statement rather than planning it, and the plan the viewer+ * draws arrives with an ordinary run instead — so asking for a format here+ * would only refuse the dry run.*/export const explainQueryOption = (engine: Engine) =>create(QueryOptionSchema, {- explainFormat: isVisualizerEngine(engine)- ? QueryOption_ExplainFormat[VISUALIZER_EXPLAIN_FORMATS[engine]]- : QueryOption_ExplainFormat.EXPLAIN_FORMAT_UNSPECIFIED,+ explainFormat:+ isVisualizerEngine(engine) && engine !== Engine.BIGQUERY+ ? QueryOption_ExplainFormat[VISUALIZER_EXPLAIN_FORMATS[engine]]+ : QueryOption_ExplainFormat.EXPLAIN_FORMAT_UNSPECIFIED,});diff --git a/proto/gen/grpc-doc/openapi.yaml b/proto/gen/grpc-doc/openapi.yamlindex 65c8d6b324..4cca9bae6c 100644--- a/proto/gen/grpc-doc/openapi.yaml+++ b/proto/gen/grpc-doc/openapi.yaml@@ -26551,9 +26551,19 @@ components:description: |-Whether producing the plan executed the statement, as EXPLAIN ANALYZEdoes.+ content:+ type: string+ title: content+ description: |-+ The plan itself, where the engine states it beside the result rather+ than in the result's rows. BigQuery reports the stages its job ran in+ the job's own statistics, so one result carries the query's data and+ the plan of the run that produced it. Empty when the plan is the rows,+ which is every other engine. Omitted from the audit log, as the rows+ are: the statement is what an audit reads.title: QueryPlanadditionalProperties: false- description: A query plan held in the result's rows.+ description: 'A query plan the result carries: in its rows, or beside them.'bytebase.v1.QueryResult.SyntaxError:type: objectproperties:diff --git a/proto/gen/grpc-doc/v1/README.md b/proto/gen/grpc-doc/v1/README.mdindex 482279a880..c47483988b 100644--- a/proto/gen/grpc-doc/v1/README.md+++ b/proto/gen/grpc-doc/v1/README.md@@ -2717,13 +2717,14 @@ for field description.<a name="bytebase-v1-QueryResult-QueryPlan"></a>### QueryResult.QueryPlan-A query plan held in the result's rows.+A query plan the result carries: in its rows, or beside them.| Field | Type | Label | Description || ----- | ---- | ----- | ----------- || format | [QueryOption.ExplainFormat](#bytebase-v1-QueryOption-ExplainFormat) | | || executed | [bool](#bool) | | Whether producing the plan executed the statement, as EXPLAIN ANALYZE does. |+| content | [string](#string) | | The plan itself, where the engine states it beside the result rather than in the result's rows. BigQuery reports the stages its job ran in the job's own statistics, so one result carries the query's data and the plan of the run that produced it. Empty when the plan is the rows, which is every other engine. Omitted from the audit log, as the rows are: the statement is what an audit reads. |diff --git a/proto/gen/grpc-doc/v1/index.html b/proto/gen/grpc-doc/v1/index.htmlindex 7a6b2dc42f..3a9aab13f7 100644--- a/proto/gen/grpc-doc/v1/index.html+++ b/proto/gen/grpc-doc/v1/index.html@@ -8557,7 +8557,7 @@ Examples include PostgreSQL's RAISE NOTICE, MSSQL's PRINT, or Oracle'<h3 id="bytebase.v1.QueryResult.QueryPlan">QueryResult.QueryPlan</h3>- <p>A query plan held in the result's rows.</p>+ <p>A query plan the result carries: in its rows, or beside them.</p><table class="field-table">@@ -8581,6 +8581,18 @@ Examples include PostgreSQL's RAISE NOTICE, MSSQL's PRINT, or Oracle'does. </p></td></tr>+ <tr>+ <td>content</td>+ <td><a href="#string">string</a></td>+ <td></td>+ <td><p>The plan itself, where the engine states it beside the result rather+than in the result's rows. BigQuery reports the stages its job ran in+the job's own statistics, so one result carries the query's data and+the plan of the run that produced it. Empty when the plan is the rows,+which is every other engine. Omitted from the audit log, as the rows+are: the statement is what an audit reads. </p></td>+ </tr>+</tbody></table>diff --git a/proto/v1/v1/sql_service.proto b/proto/v1/v1/sql_service.protoindex ec733e9ce3..226a3c62e3 100644--- a/proto/v1/v1/sql_service.proto+++ b/proto/v1/v1/sql_service.proto@@ -318,13 +318,21 @@ message QueryResult {// Masking reasons for each column (empty for non-masked columns).repeated MaskingReason masked = 12;- // A query plan held in the result's rows.+ // A query plan the result carries: in its rows, or beside them.message QueryPlan {QueryOption.ExplainFormat format = 1;// Whether producing the plan executed the statement, as EXPLAIN ANALYZE// does.bool executed = 2;++ // The plan itself, where the engine states it beside the result rather+ // than in the result's rows. BigQuery reports the stages its job ran in+ // the job's own statistics, so one result carries the query's data and+ // the plan of the run that produced it. Empty when the plan is the rows,+ // which is every other engine. Omitted from the audit log, as the rows+ // are: the statement is what an audit reads.+ string content = 3 [(bytebase.v1.audit_behavior) = OMIT];}// Set when the result is a query plan. Unset for any other result.