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): visualize typed EXPLAIN results (#21492)
Danny Xu44de64cd4939
diff --git a/backend/api/mcp/gen/openapi.yaml b/backend/api/mcp/gen/openapi.yamlindex 67641af183..f383bee259 100644--- a/backend/api/mcp/gen/openapi.yaml+++ b/backend/api/mcp/gen/openapi.yaml@@ -18375,6 +18375,13 @@ components:allOf:- $ref: '#/components/schemas/bytebase.v1.QueryOption.ExplainFormat'title: explain_format+ description: |-+ Which explain output the caller wants, for an explain request.++ Leave it unspecified for the engine's own default, which is the only+ output most engines have. Naming a format an engine cannot produce is+ INVALID_ARGUMENT rather than a silent fallback, as is any explain request+ against an engine that has no explain at all.title: QueryOptionadditionalProperties: falsebytebase.v1.QueryOption.ExplainFormat:@@ -18385,13 +18392,8 @@ components:- TEXT- JSON- XML- description: |-- Which explain output the caller wants, for an explain request.-- Leave it unspecified for the engine's own default, which is the only- output most engines have. Naming a format an engine cannot produce is- INVALID_ARGUMENT rather than a silent fallback, as is any explain request- against an engine that has no explain at all.+ - YAML+ description: The output format of a query plan.bytebase.v1.QueryOption.RedisRunCommandsOn:type: stringtitle: RedisRunCommandsOn@@ -18576,6 +18578,11 @@ components:$ref: '#/components/schemas/bytebase.v1.MaskingReason'title: maskeddescription: Masking reasons for each column (empty for non-masked columns).+ queryPlan:+ allOf:+ - $ref: '#/components/schemas/bytebase.v1.QueryResult.QueryPlan'+ title: query_plan+ description: Set when the result is a query plan. Unset for any other result.title: QueryResultbytebase.v1.QueryResult.CommandError:type: object@@ -18683,6 +18690,22 @@ components:description: |-refer https://www.postgresql.org/docs/11/protocol-error-fields.htmlfor field description.+ bytebase.v1.QueryResult.QueryPlan:+ type: object+ properties:+ format:+ allOf:+ - $ref: '#/components/schemas/bytebase.v1.QueryOption.ExplainFormat'+ title: format+ executed:+ type: boolean+ title: executed+ description: |-+ Whether producing the plan executed the statement, as EXPLAIN ANALYZE+ does.+ title: QueryPlan+ additionalProperties: false+ description: A query plan held in the result's rows.bytebase.v1.QueryResult.SyntaxError:type: objectproperties:diff --git a/backend/api/v1/sql_service.go b/backend/api/v1/sql_service.goindex cf15533e3a..6d436fbf2c 100644--- a/backend/api/v1/sql_service.go+++ b/backend/api/v1/sql_service.go@@ -753,6 +753,13 @@ func queryRetry(}slog.Debug("execute success", slog.String("instance", instance.ResourceID), slog.String("statement", originalStatement), slog.Duration("duration", duration))if queryContext.Explain {+ if format, ok := db.ExplainResultFormat(instance.Metadata.GetEngine(), queryContext.Option.GetExplainFormat()); ok {+ for _, result := range results {+ if result.Error == "" {+ result.QueryPlan = &v1pb.QueryResult_QueryPlan{Format: format}+ }+ }+ }return results, nil, duration, nil}@@ -1983,37 +1990,11 @@ func (s *SQLService) prepareRelatedMessage(ctx context.Context, requestName strireturn user, instance, database, nil}-// supportedExplainFormats lists the explain formats an engine's driver actually-// produces. TEXT is the human-readable plan every engine returns by default,-// which is why only the engines with a machine-readable plan, or without a-// readable one, need a case here.-func supportedExplainFormats(engine storepb.Engine) []v1pb.QueryOption_ExplainFormat {- switch engine {- case storepb.Engine_POSTGRES:- return []v1pb.QueryOption_ExplainFormat{v1pb.QueryOption_TEXT, v1pb.QueryOption_JSON, v1pb.QueryOption_XML}- case storepb.Engine_MSSQL:- return []v1pb.QueryOption_ExplainFormat{v1pb.QueryOption_TEXT, v1pb.QueryOption_XML}- case storepb.Engine_SPANNER:- // Spanner returns its plan as JSON and has no text form.- return []v1pb.QueryOption_ExplainFormat{v1pb.QueryOption_JSON}- case storepb.Engine_MONGODB, storepb.Engine_REDIS, storepb.Engine_DYNAMODB,- storepb.Engine_CASSANDRA, storepb.Engine_COSMOSDB, storepb.Engine_DATABRICKS,- storepb.Engine_ELASTICSEARCH:- // No driver here implements explain: the first three refuse it, the rest- // ignore the flag and would run the statement itself. Saying TEXT would- // send a caller down a path that never produces a plan.- return nil- default:- return []v1pb.QueryOption_ExplainFormat{v1pb.QueryOption_TEXT}- }-}--// validateExplainFormat refuses a format the engine cannot produce. This is the-// one place the engine-to-format support is decided: drivers below map whatever-// reaches them onto their own syntax, so a request that slipped through would-// silently come back in a format the caller cannot parse.+// validateExplainFormat refuses a format the driver cannot produce. Drivers+// map whatever reaches them onto their own syntax, so a request that slipped+// through would silently come back in a format the caller cannot parse.func validateExplainFormat(engine storepb.Engine, format v1pb.QueryOption_ExplainFormat) error {- supported := supportedExplainFormats(engine)+ supported := db.SupportedExplainFormats(engine)// An engine with no explain at all is refused whatever the caller asked for,// including nothing. Its driver would otherwise run the statement as an// ordinary query — and an explain request skips the read-only validationdiff --git a/backend/api/v1/sql_service_test.go b/backend/api/v1/sql_service_test.goindex a6cf627f57..2d8ca9a129 100644--- a/backend/api/v1/sql_service_test.go+++ b/backend/api/v1/sql_service_test.go@@ -348,6 +348,8 @@ func TestValidateExplainFormat(t *testing.T) {{name: "postgres json", engine: storepb.Engine_POSTGRES, format: v1pb.QueryOption_JSON},{name: "postgres xml", engine: storepb.Engine_POSTGRES, format: v1pb.QueryOption_XML},{name: "postgres text", engine: storepb.Engine_POSTGRES, format: v1pb.QueryOption_TEXT},+ {name: "postgres yaml", engine: storepb.Engine_POSTGRES, format: v1pb.QueryOption_YAML},+ {name: "mssql yaml", engine: storepb.Engine_MSSQL, format: v1pb.QueryOption_YAML, wantErr: true},{name: "mssql xml", engine: storepb.Engine_MSSQL, format: v1pb.QueryOption_XML},{name: "mssql json", engine: storepb.Engine_MSSQL, format: v1pb.QueryOption_JSON, wantErr: true},{name: "spanner json", engine: storepb.Engine_SPANNER, format: v1pb.QueryOption_JSON},diff --git a/backend/generated-go/v1/sql_service.pb.go b/backend/generated-go/v1/sql_service.pb.goindex 07196dc29b..c642012f56 100644--- a/backend/generated-go/v1/sql_service.pb.go+++ b/backend/generated-go/v1/sql_service.pb.go@@ -77,16 +77,13 @@ func (QueryOption_RedisRunCommandsOn) EnumDescriptor() ([]byte, []int) {return file_v1_sql_service_proto_rawDescGZIP(), []int{4, 0}}-// Which explain output the caller wants, for an explain request.-//-// Leave it unspecified for the engine's own default, which is the only-// output most engines have. Naming a format an engine cannot produce is-// INVALID_ARGUMENT rather than a silent fallback, as is any explain request-// against an engine that has no explain at all.+// The output format of a query plan.type QueryOption_ExplainFormat int32const (- // The engine's default: PostgreSQL EXPLAIN, SQL Server SHOWPLAN_ALL.+ // The engine's default: PostgreSQL EXPLAIN, SQL Server SHOWPLAN_ALL. On a+ // result, a default the server could not resolve, as when MySQL follows the+ // session's explain_format; read such a plan as text.QueryOption_EXPLAIN_FORMAT_UNSPECIFIED QueryOption_ExplainFormat = 0// The human-readable plan. PostgreSQL: EXPLAIN (FORMAT TEXT). SQL Server:// SHOWPLAN_ALL.@@ -96,6 +93,8 @@ const (// The plan tree as XML. PostgreSQL: EXPLAIN (FORMAT XML). SQL Server:// SHOWPLAN_XML.QueryOption_XML QueryOption_ExplainFormat = 3+ // The plan tree as YAML. PostgreSQL: EXPLAIN (FORMAT YAML).+ QueryOption_YAML QueryOption_ExplainFormat = 4)// Enum value maps for QueryOption_ExplainFormat.@@ -105,12 +104,14 @@ var (1: "TEXT",2: "JSON",3: "XML",+ 4: "YAML",}QueryOption_ExplainFormat_value = map[string]int32{"EXPLAIN_FORMAT_UNSPECIFIED": 0,"TEXT": 1,"JSON": 2,"XML": 3,+ "YAML": 4,})@@ -677,9 +678,15 @@ func (x *QueryResponse) GetAppliedAccessGrant() string {type QueryOption struct {state protoimpl.MessageState `protogen:"open.v1"`RedisRunCommandsOn QueryOption_RedisRunCommandsOn `protobuf:"varint,1,opt,name=redis_run_commands_on,json=redisRunCommandsOn,proto3,enum=bytebase.v1.QueryOption_RedisRunCommandsOn" json:"redis_run_commands_on,omitempty"`- ExplainFormat QueryOption_ExplainFormat `protobuf:"varint,3,opt,name=explain_format,json=explainFormat,proto3,enum=bytebase.v1.QueryOption_ExplainFormat" json:"explain_format,omitempty"`- unknownFields protoimpl.UnknownFields- sizeCache protoimpl.SizeCache+ // Which explain output the caller wants, for an explain request.+ //+ // Leave it unspecified for the engine's own default, which is the only+ // output most engines have. Naming a format an engine cannot produce is+ // INVALID_ARGUMENT rather than a silent fallback, as is any explain request+ // against an engine that has no explain at all.+ ExplainFormat QueryOption_ExplainFormat `protobuf:"varint,3,opt,name=explain_format,json=explainFormat,proto3,enum=bytebase.v1.QueryOption_ExplainFormat" json:"explain_format,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache}func (x *QueryOption) Reset() {@@ -753,7 +760,9 @@ type QueryResult struct {// Examples include PostgreSQL's RAISE NOTICE, MSSQL's PRINT, or Oracle's DBMS_OUTPUT.PUT_LINE.Messages []*QueryResult_Message `protobuf:"bytes,11,rep,name=messages,proto3" json:"messages,omitempty"`// Masking reasons for each column (empty for non-masked columns).- Masked []*MaskingReason `protobuf:"bytes,12,rep,name=masked,proto3" json:"masked,omitempty"`+ Masked []*MaskingReason `protobuf:"bytes,12,rep,name=masked,proto3" json:"masked,omitempty"`+ // Set when the result is a query plan. Unset for any other result.+ QueryPlan *QueryResult_QueryPlan `protobuf:"bytes,14,opt,name=query_plan,json=queryPlan,proto3" json:"query_plan,omitempty"`unknownFields protoimpl.UnknownFieldssizeCache protoimpl.SizeCache}@@ -894,6 +903,13 @@ func (x *QueryResult) GetMasked() []*MaskingReason {return nil}+func (x *QueryResult) GetQueryPlan() *QueryResult_QueryPlan {+ if x != nil {+ return x.QueryPlan+ }+ return nil+}+type isQueryResult_DetailedError interface {isQueryResult_DetailedError()}@@ -1931,6 +1947,61 @@ func (x *QueryResult_Message) GetContent() string {return ""}+// A query plan held in the result's rows.+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"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *QueryResult_QueryPlan) Reset() {+ *x = QueryResult_QueryPlan{}+ mi := &file_v1_sql_service_proto_msgTypes[16]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *QueryResult_QueryPlan) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*QueryResult_QueryPlan) ProtoMessage() {}++func (x *QueryResult_QueryPlan) ProtoReflect() protoreflect.Message {+ mi := &file_v1_sql_service_proto_msgTypes[16]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use QueryResult_QueryPlan.ProtoReflect.Descriptor instead.+func (*QueryResult_QueryPlan) Descriptor() ([]byte, []int) {+ return file_v1_sql_service_proto_rawDescGZIP(), []int{5, 4}+}++func (x *QueryResult_QueryPlan) GetFormat() QueryOption_ExplainFormat {+ if x != nil {+ return x.Format+ }+ return QueryOption_EXPLAIN_FORMAT_UNSPECIFIED+}++func (x *QueryResult_QueryPlan) GetExecuted() bool {+ if x != nil {+ return x.Executed+ }+ return false+}+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"`@@ -1942,7 +2013,7 @@ type RowValue_Timestamp struct {func (x *RowValue_Timestamp) Reset() {*x = RowValue_Timestamp{}- mi := &file_v1_sql_service_proto_msgTypes[16]+ mi := &file_v1_sql_service_proto_msgTypes[17]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -1954,7 +2025,7 @@ func (x *RowValue_Timestamp) String() string {func (*RowValue_Timestamp) ProtoMessage() {}func (x *RowValue_Timestamp) ProtoReflect() protoreflect.Message {- mi := &file_v1_sql_service_proto_msgTypes[16]+ mi := &file_v1_sql_service_proto_msgTypes[17]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -2003,7 +2074,7 @@ type RowValue_TimestampTZ struct {func (x *RowValue_TimestampTZ) Reset() {*x = RowValue_TimestampTZ{}- mi := &file_v1_sql_service_proto_msgTypes[17]+ mi := &file_v1_sql_service_proto_msgTypes[18]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -2015,7 +2086,7 @@ func (x *RowValue_TimestampTZ) String() string {func (*RowValue_TimestampTZ) ProtoMessage() {}func (x *RowValue_TimestampTZ) ProtoReflect() protoreflect.Message {- mi := &file_v1_sql_service_proto_msgTypes[17]+ mi := &file_v1_sql_service_proto_msgTypes[18]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -2091,19 +2162,20 @@ const file_v1_sql_service_proto_rawDesc = "" +"_container\"u\n" +"\rQueryResponse\x122\n" +"\aresults\x18\x01 \x03(\v2\x18.bytebase.v1.QueryResultR\aresults\x120\n" +- "\x14applied_access_grant\x18\x02 \x01(\tR\x12appliedAccessGrant\"\x83\x03\n" ++ "\x14applied_access_grant\x18\x02 \x01(\tR\x12appliedAccessGrant\"\x8d\x03\n" +"\vQueryOption\x12^\n" +"\x15redis_run_commands_on\x18\x01 \x01(\x0e2+.bytebase.v1.QueryOption.RedisRunCommandsOnR\x12redisRunCommandsOn\x12M\n" +"\x0eexplain_format\x18\x03 \x01(\x0e2&.bytebase.v1.QueryOption.ExplainFormatR\rexplainFormat\"[\n" +"\x12RedisRunCommandsOn\x12%\n" +"!REDIS_RUN_COMMANDS_ON_UNSPECIFIED\x10\x00\x12\x0f\n" +"\vSINGLE_NODE\x10\x01\x12\r\n" +- "\tALL_NODES\x10\x02\"L\n" ++ "\tALL_NODES\x10\x02\"V\n" +"\rExplainFormat\x12\x1e\n" +"\x1aEXPLAIN_FORMAT_UNSPECIFIED\x10\x00\x12\b\n" +"\x04TEXT\x10\x01\x12\b\n" +"\x04JSON\x10\x02\x12\a\n" +- "\x03XML\x10\x03J\x04\b\x02\x10\x03R\x14mssql_explain_format\"\x97\r\n" ++ "\x03XML\x10\x03\x12\b\n" ++ "\x04YAML\x10\x04J\x04\b\x02\x10\x03R\x14mssql_explain_format\"\xc3\x0e\n" +"\vQueryResult\x12!\n" +"\fcolumn_names\x18\x01 \x03(\tR\vcolumnNames\x12*\n" +"\x11column_type_names\x18\x02 \x03(\tR\x0fcolumnTypeNames\x12/\n" +@@ -2119,7 +2191,9 @@ const file_v1_sql_service_proto_rawDesc = "" +" \x01(\v2#.bytebase.v1.PermissionDeniedDetailH\x00R\x10permissionDenied\x12L\n" +"\rcommand_error\x18\r \x01(\v2%.bytebase.v1.QueryResult.CommandErrorH\x00R\fcommandError\x12B\n" +"\bmessages\x18\v \x03(\v2 .bytebase.v1.QueryResult.MessageB\x04\xd0\xea0\x02R\bmessages\x122\n" +- "\x06masked\x18\f \x03(\v2\x1a.bytebase.v1.MaskingReasonR\x06masked\x1a\xfd\x03\n" ++ "\x06masked\x18\f \x03(\v2\x1a.bytebase.v1.MaskingReasonR\x06masked\x12A\n" ++ "\n" ++ "query_plan\x18\x0e \x01(\v2\".bytebase.v1.QueryResult.QueryPlanR\tqueryPlan\x1a\xfd\x03\n" +"\rPostgresError\x12\x1a\n" +"\bseverity\x18\x01 \x01(\tR\bseverity\x12\x12\n" +"\x04code\x18\x02 \x01(\tR\x04code\x12\x18\n" +@@ -2162,7 +2236,10 @@ const file_v1_sql_service_proto_rawDesc = "" +"\x03LOG\x10\x04\x12\n" +"\n" +"\x06NOTICE\x10\x05\x12\r\n" +- "\tEXCEPTION\x10\x06B\x10\n" ++ "\tEXCEPTION\x10\x06\x1ag\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" +"\x0edetailed_error\"\xb0\x02\n" +"\rMaskingReason\x12(\n" +"\x10semantic_type_id\x18\x01 \x01(\tR\x0esemanticTypeId\x12.\n" +@@ -2264,7 +2341,7 @@ func file_v1_sql_service_proto_rawDescGZIP() []byte {}var file_v1_sql_service_proto_enumTypes = make([]protoimpl.EnumInfo, 6)-var file_v1_sql_service_proto_msgTypes = make([]protoimpl.MessageInfo, 18)+var file_v1_sql_service_proto_msgTypes = make([]protoimpl.MessageInfo, 19)var file_v1_sql_service_proto_goTypes = []any{(QueryOption_RedisRunCommandsOn)(0), // 0: bytebase.v1.QueryOption.RedisRunCommandsOn(QueryOption_ExplainFormat)(0), // 1: bytebase.v1.QueryOption.ExplainFormat@@ -2288,21 +2365,22 @@ var file_v1_sql_service_proto_goTypes = []any{(*QueryResult_SyntaxError)(nil), // 19: bytebase.v1.QueryResult.SyntaxError(*QueryResult_CommandError)(nil), // 20: bytebase.v1.QueryResult.CommandError(*QueryResult_Message)(nil), // 21: bytebase.v1.QueryResult.Message- (*RowValue_Timestamp)(nil), // 22: bytebase.v1.RowValue.Timestamp- (*RowValue_TimestampTZ)(nil), // 23: bytebase.v1.RowValue.TimestampTZ- (*durationpb.Duration)(nil), // 24: google.protobuf.Duration- (*PermissionDeniedDetail)(nil), // 25: bytebase.v1.PermissionDeniedDetail- (structpb.NullValue)(0), // 26: google.protobuf.NullValue- (*structpb.Value)(nil), // 27: google.protobuf.Value- (*Position)(nil), // 28: bytebase.v1.Position- (ExportFormat)(0), // 29: bytebase.v1.ExportFormat- (*timestamppb.Timestamp)(nil), // 30: google.protobuf.Timestamp- (*SearchQueryHistoriesRequest)(nil), // 31: bytebase.v1.SearchQueryHistoriesRequest- (*ListQueryHistoriesRequest)(nil), // 32: bytebase.v1.ListQueryHistoriesRequest- (*GetQueryHistoryRequest)(nil), // 33: bytebase.v1.GetQueryHistoryRequest- (*SearchQueryHistoriesResponse)(nil), // 34: bytebase.v1.SearchQueryHistoriesResponse- (*ListQueryHistoriesResponse)(nil), // 35: bytebase.v1.ListQueryHistoriesResponse- (*QueryHistory)(nil), // 36: bytebase.v1.QueryHistory+ (*QueryResult_QueryPlan)(nil), // 22: bytebase.v1.QueryResult.QueryPlan+ (*RowValue_Timestamp)(nil), // 23: bytebase.v1.RowValue.Timestamp+ (*RowValue_TimestampTZ)(nil), // 24: bytebase.v1.RowValue.TimestampTZ+ (*durationpb.Duration)(nil), // 25: google.protobuf.Duration+ (*PermissionDeniedDetail)(nil), // 26: bytebase.v1.PermissionDeniedDetail+ (structpb.NullValue)(0), // 27: google.protobuf.NullValue+ (*structpb.Value)(nil), // 28: google.protobuf.Value+ (*Position)(nil), // 29: bytebase.v1.Position+ (ExportFormat)(0), // 30: bytebase.v1.ExportFormat+ (*timestamppb.Timestamp)(nil), // 31: google.protobuf.Timestamp+ (*SearchQueryHistoriesRequest)(nil), // 32: bytebase.v1.SearchQueryHistoriesRequest+ (*ListQueryHistoriesRequest)(nil), // 33: bytebase.v1.ListQueryHistoriesRequest+ (*GetQueryHistoryRequest)(nil), // 34: bytebase.v1.GetQueryHistoryRequest+ (*SearchQueryHistoriesResponse)(nil), // 35: bytebase.v1.SearchQueryHistoriesResponse+ (*ListQueryHistoriesResponse)(nil), // 36: bytebase.v1.ListQueryHistoriesResponse+ (*QueryHistory)(nil), // 37: bytebase.v1.QueryHistory}var file_v1_sql_service_proto_depIdxs = []int32{11, // 0: bytebase.v1.AdminExecuteResponse.results:type_name -> bytebase.v1.QueryResult@@ -2311,45 +2389,47 @@ var file_v1_sql_service_proto_depIdxs = []int32{0, // 3: bytebase.v1.QueryOption.redis_run_commands_on:type_name -> bytebase.v1.QueryOption.RedisRunCommandsOn1, // 4: bytebase.v1.QueryOption.explain_format:type_name -> bytebase.v1.QueryOption.ExplainFormat13, // 5: bytebase.v1.QueryResult.rows:type_name -> bytebase.v1.QueryRow- 24, // 6: bytebase.v1.QueryResult.latency:type_name -> google.protobuf.Duration+ 25, // 6: bytebase.v1.QueryResult.latency:type_name -> google.protobuf.Duration18, // 7: bytebase.v1.QueryResult.postgres_error:type_name -> bytebase.v1.QueryResult.PostgresError19, // 8: bytebase.v1.QueryResult.syntax_error:type_name -> bytebase.v1.QueryResult.SyntaxError- 25, // 9: bytebase.v1.QueryResult.permission_denied:type_name -> bytebase.v1.PermissionDeniedDetail+ 26, // 9: bytebase.v1.QueryResult.permission_denied:type_name -> bytebase.v1.PermissionDeniedDetail20, // 10: bytebase.v1.QueryResult.command_error:type_name -> bytebase.v1.QueryResult.CommandError21, // 11: bytebase.v1.QueryResult.messages:type_name -> bytebase.v1.QueryResult.Message12, // 12: bytebase.v1.QueryResult.masked:type_name -> bytebase.v1.MaskingReason- 14, // 13: bytebase.v1.QueryRow.values:type_name -> bytebase.v1.RowValue- 26, // 14: bytebase.v1.RowValue.null_value:type_name -> google.protobuf.NullValue- 27, // 15: bytebase.v1.RowValue.value_value:type_name -> google.protobuf.Value- 22, // 16: bytebase.v1.RowValue.timestamp_value:type_name -> bytebase.v1.RowValue.Timestamp- 23, // 17: bytebase.v1.RowValue.timestamp_tz_value:type_name -> bytebase.v1.RowValue.TimestampTZ- 4, // 18: bytebase.v1.Advice.status:type_name -> bytebase.v1.Advice.Level- 28, // 19: bytebase.v1.Advice.start_position:type_name -> bytebase.v1.Position- 28, // 20: bytebase.v1.Advice.end_position:type_name -> bytebase.v1.Position- 5, // 21: bytebase.v1.Advice.rule_type:type_name -> bytebase.v1.Advice.RuleType- 29, // 22: bytebase.v1.ExportRequest.format:type_name -> bytebase.v1.ExportFormat- 28, // 23: bytebase.v1.QueryResult.SyntaxError.start_position:type_name -> bytebase.v1.Position- 2, // 24: bytebase.v1.QueryResult.CommandError.command_type:type_name -> bytebase.v1.QueryResult.CommandError.Type- 3, // 25: bytebase.v1.QueryResult.Message.level:type_name -> bytebase.v1.QueryResult.Message.Level- 30, // 26: bytebase.v1.RowValue.Timestamp.google_timestamp:type_name -> google.protobuf.Timestamp- 30, // 27: bytebase.v1.RowValue.TimestampTZ.google_timestamp:type_name -> google.protobuf.Timestamp- 8, // 28: bytebase.v1.SQLService.Query:input_type -> bytebase.v1.QueryRequest- 6, // 29: bytebase.v1.SQLService.AdminExecute:input_type -> bytebase.v1.AdminExecuteRequest- 31, // 30: bytebase.v1.SQLService.SearchQueryHistories:input_type -> bytebase.v1.SearchQueryHistoriesRequest- 32, // 31: bytebase.v1.SQLService.ListQueryHistories:input_type -> bytebase.v1.ListQueryHistoriesRequest- 33, // 32: bytebase.v1.SQLService.GetQueryHistory:input_type -> bytebase.v1.GetQueryHistoryRequest- 16, // 33: bytebase.v1.SQLService.Export:input_type -> bytebase.v1.ExportRequest- 9, // 34: bytebase.v1.SQLService.Query:output_type -> bytebase.v1.QueryResponse- 7, // 35: bytebase.v1.SQLService.AdminExecute:output_type -> bytebase.v1.AdminExecuteResponse- 34, // 36: bytebase.v1.SQLService.SearchQueryHistories:output_type -> bytebase.v1.SearchQueryHistoriesResponse- 35, // 37: bytebase.v1.SQLService.ListQueryHistories:output_type -> bytebase.v1.ListQueryHistoriesResponse- 36, // 38: bytebase.v1.SQLService.GetQueryHistory:output_type -> bytebase.v1.QueryHistory- 17, // 39: bytebase.v1.SQLService.Export:output_type -> bytebase.v1.ExportResponse- 34, // [34:40] is the sub-list for method output_type- 28, // [28:34] is the sub-list for method input_type- 28, // [28:28] is the sub-list for extension type_name- 28, // [28:28] is the sub-list for extension extendee- 0, // [0:28] is the sub-list for field type_name+ 22, // 13: bytebase.v1.QueryResult.query_plan:type_name -> bytebase.v1.QueryResult.QueryPlan+ 14, // 14: bytebase.v1.QueryRow.values:type_name -> bytebase.v1.RowValue+ 27, // 15: bytebase.v1.RowValue.null_value:type_name -> google.protobuf.NullValue+ 28, // 16: bytebase.v1.RowValue.value_value:type_name -> google.protobuf.Value+ 23, // 17: bytebase.v1.RowValue.timestamp_value:type_name -> bytebase.v1.RowValue.Timestamp+ 24, // 18: bytebase.v1.RowValue.timestamp_tz_value:type_name -> bytebase.v1.RowValue.TimestampTZ+ 4, // 19: bytebase.v1.Advice.status:type_name -> bytebase.v1.Advice.Level+ 29, // 20: bytebase.v1.Advice.start_position:type_name -> bytebase.v1.Position+ 29, // 21: bytebase.v1.Advice.end_position:type_name -> bytebase.v1.Position+ 5, // 22: bytebase.v1.Advice.rule_type:type_name -> bytebase.v1.Advice.RuleType+ 30, // 23: bytebase.v1.ExportRequest.format:type_name -> bytebase.v1.ExportFormat+ 29, // 24: bytebase.v1.QueryResult.SyntaxError.start_position:type_name -> bytebase.v1.Position+ 2, // 25: bytebase.v1.QueryResult.CommandError.command_type:type_name -> bytebase.v1.QueryResult.CommandError.Type+ 3, // 26: bytebase.v1.QueryResult.Message.level:type_name -> bytebase.v1.QueryResult.Message.Level+ 1, // 27: bytebase.v1.QueryResult.QueryPlan.format:type_name -> bytebase.v1.QueryOption.ExplainFormat+ 31, // 28: bytebase.v1.RowValue.Timestamp.google_timestamp:type_name -> google.protobuf.Timestamp+ 31, // 29: bytebase.v1.RowValue.TimestampTZ.google_timestamp:type_name -> google.protobuf.Timestamp+ 8, // 30: bytebase.v1.SQLService.Query:input_type -> bytebase.v1.QueryRequest+ 6, // 31: bytebase.v1.SQLService.AdminExecute:input_type -> bytebase.v1.AdminExecuteRequest+ 32, // 32: bytebase.v1.SQLService.SearchQueryHistories:input_type -> bytebase.v1.SearchQueryHistoriesRequest+ 33, // 33: bytebase.v1.SQLService.ListQueryHistories:input_type -> bytebase.v1.ListQueryHistoriesRequest+ 34, // 34: bytebase.v1.SQLService.GetQueryHistory:input_type -> bytebase.v1.GetQueryHistoryRequest+ 16, // 35: bytebase.v1.SQLService.Export:input_type -> bytebase.v1.ExportRequest+ 9, // 36: bytebase.v1.SQLService.Query:output_type -> bytebase.v1.QueryResponse+ 7, // 37: bytebase.v1.SQLService.AdminExecute:output_type -> bytebase.v1.AdminExecuteResponse+ 35, // 38: bytebase.v1.SQLService.SearchQueryHistories:output_type -> bytebase.v1.SearchQueryHistoriesResponse+ 36, // 39: bytebase.v1.SQLService.ListQueryHistories:output_type -> bytebase.v1.ListQueryHistoriesResponse+ 37, // 40: bytebase.v1.SQLService.GetQueryHistory:output_type -> bytebase.v1.QueryHistory+ 17, // 41: bytebase.v1.SQLService.Export:output_type -> bytebase.v1.ExportResponse+ 36, // [36:42] is the sub-list for method output_type+ 30, // [30:36] is the sub-list for method input_type+ 30, // [30:30] is the sub-list for extension type_name+ 30, // [30:30] is the sub-list for extension extendee+ 0, // [0:30] is the sub-list for field type_name}func init() { file_v1_sql_service_proto_init() }@@ -2390,7 +2470,7 @@ func file_v1_sql_service_proto_init() {GoPackagePath: reflect.TypeOf(x{}).PkgPath(),RawDescriptor: unsafe.Slice(unsafe.StringData(file_v1_sql_service_proto_rawDesc), len(file_v1_sql_service_proto_rawDesc)),NumEnums: 6,- NumMessages: 18,+ NumMessages: 19,NumExtensions: 0,NumServices: 1,},diff --git a/backend/generated-go/v1/sql_service_equal.pb.go b/backend/generated-go/v1/sql_service_equal.pb.goindex 46623cac87..15dcd53033 100644--- a/backend/generated-go/v1/sql_service_equal.pb.go+++ b/backend/generated-go/v1/sql_service_equal.pb.go@@ -226,6 +226,22 @@ func (x *QueryResult_Message) Equal(y *QueryResult_Message) bool {return true}+func (x *QueryResult_QueryPlan) Equal(y *QueryResult_QueryPlan) bool {+ if x == y {+ return true+ }+ if x == nil || y == nil {+ return x == nil && y == nil+ }+ if x.Format != y.Format {+ return false+ }+ if x.Executed != y.Executed {+ return false+ }+ return true+}+func (x *QueryResult) Equal(y *QueryResult) bool {if x == y {return true@@ -297,6 +313,9 @@ func (x *QueryResult) Equal(y *QueryResult) bool {return false}}+ if !x.QueryPlan.Equal(y.QueryPlan) {+ return false+ }return true}diff --git a/backend/plugin/db/explain_format.go b/backend/plugin/db/explain_format.goindex bd3982d534..77cc4b3127 100644--- a/backend/plugin/db/explain_format.go+++ b/backend/plugin/db/explain_format.go@@ -1,6 +1,7 @@package dbimport (+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"v1pb "github.com/bytebase/bytebase/backend/generated-go/v1""github.com/bytebase/bytebase/backend/plugin/parser/base")@@ -17,7 +18,45 @@ func ExplainFormat(format v1pb.QueryOption_ExplainFormat) base.ExplainFormat {return base.ExplainFormatJSONcase v1pb.QueryOption_XML:return base.ExplainFormatXML+ case v1pb.QueryOption_YAML:+ return base.ExplainFormatYAMLdefault:return base.ExplainFormatDefault}}++// SupportedExplainFormats lists the formats an engine's explain path accepts.+func SupportedExplainFormats(engine storepb.Engine) []v1pb.QueryOption_ExplainFormat {+ switch engine {+ case storepb.Engine_POSTGRES:+ return []v1pb.QueryOption_ExplainFormat{v1pb.QueryOption_TEXT, v1pb.QueryOption_JSON, v1pb.QueryOption_XML, v1pb.QueryOption_YAML}+ case storepb.Engine_MSSQL:+ return []v1pb.QueryOption_ExplainFormat{v1pb.QueryOption_TEXT, v1pb.QueryOption_XML}+ case storepb.Engine_SPANNER:+ return []v1pb.QueryOption_ExplainFormat{v1pb.QueryOption_JSON}+ case storepb.Engine_MONGODB, storepb.Engine_REDIS, storepb.Engine_DYNAMODB,+ storepb.Engine_CASSANDRA, storepb.Engine_COSMOSDB, storepb.Engine_DATABRICKS,+ storepb.Engine_ELASTICSEARCH:+ return nil+ default:+ return []v1pb.QueryOption_ExplainFormat{v1pb.QueryOption_TEXT}+ }+}++// ExplainResultFormat returns the format of a query plan result. The boolean is+// false when the engine uses the explain path for something other than a plan.+func ExplainResultFormat(engine storepb.Engine, format v1pb.QueryOption_ExplainFormat) (v1pb.QueryOption_ExplainFormat, bool) {+ if engine == storepb.Engine_BIGQUERY {+ return v1pb.QueryOption_EXPLAIN_FORMAT_UNSPECIFIED, false+ }+ if engine == storepb.Engine_MYSQL {+ return v1pb.QueryOption_EXPLAIN_FORMAT_UNSPECIFIED, true+ }+ if format != v1pb.QueryOption_EXPLAIN_FORMAT_UNSPECIFIED {+ return format, true+ }+ if engine == storepb.Engine_SPANNER {+ return v1pb.QueryOption_JSON, true+ }+ return v1pb.QueryOption_TEXT, true+}diff --git a/backend/plugin/db/explain_format_test.go b/backend/plugin/db/explain_format_test.goindex fb885738a8..94a653a50c 100644--- a/backend/plugin/db/explain_format_test.go+++ b/backend/plugin/db/explain_format_test.go@@ -5,6 +5,7 @@ import ("github.com/stretchr/testify/require"+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"v1pb "github.com/bytebase/bytebase/backend/generated-go/v1""github.com/bytebase/bytebase/backend/plugin/parser/base")@@ -18,6 +19,7 @@ func TestExplainFormat(t *testing.T) {{v1pb.QueryOption_TEXT, base.ExplainFormatText},{v1pb.QueryOption_JSON, base.ExplainFormatJSON},{v1pb.QueryOption_XML, base.ExplainFormatXML},+ {v1pb.QueryOption_YAML, base.ExplainFormatYAML},}for _, tc := range tests {require.Equalf(t, tc.want, ExplainFormat(tc.format), "%v", tc.format)@@ -25,3 +27,26 @@ func TestExplainFormat(t *testing.T) {// A request with no option at all asks for no particular format.require.Equal(t, base.ExplainFormatDefault, ExplainFormat((*v1pb.QueryOption)(nil).GetExplainFormat()))}++func TestExplainResultFormat(t *testing.T) {+ for _, tc := range []struct {+ name string+ engine storepb.Engine+ format v1pb.QueryOption_ExplainFormat+ want v1pb.QueryOption_ExplainFormat+ isPlan bool+ }{+ {name: "postgres default", engine: storepb.Engine_POSTGRES, want: v1pb.QueryOption_TEXT, isPlan: true},+ {name: "postgres json", engine: storepb.Engine_POSTGRES, format: v1pb.QueryOption_JSON, want: v1pb.QueryOption_JSON, isPlan: true},+ {name: "mssql xml", engine: storepb.Engine_MSSQL, format: v1pb.QueryOption_XML, want: v1pb.QueryOption_XML, isPlan: true},+ {name: "spanner default", engine: storepb.Engine_SPANNER, want: v1pb.QueryOption_JSON, isPlan: true},+ {name: "mysql unknown", engine: storepb.Engine_MYSQL, format: v1pb.QueryOption_TEXT, want: v1pb.QueryOption_EXPLAIN_FORMAT_UNSPECIFIED, isPlan: true},+ {name: "bigquery dry run", engine: storepb.Engine_BIGQUERY},+ } {+ t.Run(tc.name, func(t *testing.T) {+ got, isPlan := ExplainResultFormat(tc.engine, tc.format)+ require.Equal(t, tc.want, got)+ require.Equal(t, tc.isPlan, isPlan)+ })+ }+}diff --git a/backend/plugin/db/pg/pg.go b/backend/plugin/db/pg/pg.goindex 2e4c5b8627..af39d1aafc 100644--- a/backend/plugin/db/pg/pg.go+++ b/backend/plugin/db/pg/pg.go@@ -841,6 +841,9 @@ func (d *Driver) QueryConn(ctx context.Context, conn *sql.Conn, statement stringif err := rows.Err(); err != nil {return nil, err}+ if !queryContext.Explain {+ r.QueryPlan = typedExplainPlan(statement)+ }return r, nil}@@ -874,6 +877,17 @@ func (d *Driver) QueryConn(ctx context.Context, conn *sql.Conn, statement stringreturn results, nil}+func typedExplainPlan(statement string) *v1pb.QueryResult_QueryPlan {+ format, executed, ok := pgparser.DescribeExplain(statement)+ if !ok {+ return nil+ }+ return &v1pb.QueryResult_QueryPlan{+ Format: v1pb.QueryOption_ExplainFormat(v1pb.QueryOption_ExplainFormat_value[strings.ToUpper(format)]),+ Executed: executed,+ }+}+func getPgError(e error) *v1pb.QueryResult_PostgresError_ {if e == nil {return nildiff --git a/backend/plugin/db/pg/pg_test.go b/backend/plugin/db/pg/pg_test.goindex 72fe729ae1..2ee168c29f 100644--- a/backend/plugin/db/pg/pg_test.go+++ b/backend/plugin/db/pg/pg_test.go@@ -428,6 +428,22 @@ func TestQueryConnExplainFormat(t *testing.T) {require.Equal(t, "plan_target", plan[0].Plan.RelationName)}+func TestTypedExplainPlan(t *testing.T) {+ t.Parallel()+ for _, tc := range []struct {+ statement string+ want *v1pb.QueryResult_QueryPlan+ }{+ {statement: "SELECT 1"},+ {statement: "EXPLAIN SELECT 1", want: &v1pb.QueryResult_QueryPlan{Format: v1pb.QueryOption_TEXT}},+ {statement: "EXPLAIN (FORMAT JSON) SELECT 1", want: &v1pb.QueryResult_QueryPlan{Format: v1pb.QueryOption_JSON}},+ {statement: "EXPLAIN (ANALYZE, FORMAT XML) SELECT 1", want: &v1pb.QueryResult_QueryPlan{Format: v1pb.QueryOption_XML, Executed: true}},+ {statement: "EXPLAIN (FORMAT YAML) SELECT 1", want: &v1pb.QueryResult_QueryPlan{Format: v1pb.QueryOption_YAML}},+ } {+ require.Equal(t, tc.want, typedExplainPlan(tc.statement), tc.statement)+ }+}+func firstStringValue(t *testing.T, results []*v1pb.QueryResult) string {t.Helper()require.NotEmpty(t, results)diff --git a/backend/plugin/parser/base/explain.go b/backend/plugin/parser/base/explain.goindex 154fc51422..a35c5857d3 100644--- a/backend/plugin/parser/base/explain.go+++ b/backend/plugin/parser/base/explain.go@@ -22,6 +22,7 @@ const (ExplainFormatTextExplainFormatJSONExplainFormatXML+ ExplainFormatYAML)// ExplainStatementFunc returns the statement that plans the single statementdiff --git a/backend/plugin/parser/doris/explain.go b/backend/plugin/parser/doris/explain.goindex 74a311c258..4f8b66bd6c 100644--- a/backend/plugin/parser/doris/explain.go+++ b/backend/plugin/parser/doris/explain.go@@ -14,8 +14,8 @@ func init() {// explainStatement implements base.ExplainStatement. Doris returns one plan// format here whatever the caller asked for: its other EXPLAIN forms are plans of-// their own shape that nothing downstream reads (supportedExplainFormats in the-// API offers this engine the default plan only).+// their own shape that nothing downstream reads (the driver capability table+// offers this engine the default plan only).func explainStatement(statement string, _ base.ExplainFormat) (string, error) {node, err := singleStatement(statement)if err != nil {diff --git a/backend/plugin/parser/mysql/explain.go b/backend/plugin/parser/mysql/explain.goindex 4cd67ad0ee..d8ff52ee9c 100644--- a/backend/plugin/parser/mysql/explain.go+++ b/backend/plugin/parser/mysql/explain.go@@ -18,8 +18,8 @@ func init() {// explainStatement implements base.ExplainStatement. MySQL returns one plan// format here whatever the caller asked for: FORMAT=JSON and FORMAT=TREE are-// plans of their own shape that nothing downstream reads (supportedExplainFormats-// in the API offers this engine the default plan only).+// plans of their own shape that nothing downstream reads (the driver capability+// table offers this engine the default plan only).func explainStatement(statement string, _ base.ExplainFormat) (string, error) {node, err := singleStatement(statement)if err != nil {diff --git a/backend/plugin/parser/pg/explain.go b/backend/plugin/parser/pg/explain.goindex 6145e53b84..a9b9374f02 100644--- a/backend/plugin/parser/pg/explain.go+++ b/backend/plugin/parser/pg/explain.go@@ -1,6 +1,8 @@package pgimport (+ "strings"+"github.com/bytebase/omni/pg/ast""github.com/pkg/errors"@@ -39,15 +41,49 @@ func explainStatement(statement string, format base.ExplainFormat) (string, erroreturn "EXPLAIN (FORMAT JSON) " + planned, nilcase base.ExplainFormatXML:return "EXPLAIN (FORMAT XML) " + planned, nil+ case base.ExplainFormatYAML:+ return "EXPLAIN (FORMAT YAML) " + planned, nildefault:return "EXPLAIN " + planned, nil}}+// DescribeExplain returns the output format of an EXPLAIN statement and+// whether it executes the statement it plans.+func DescribeExplain(statement string) (format string, executed bool, ok bool) {+ node, err := singleStatement(statement)+ if err != nil {+ return "", false, false+ }+ explain, ok := node.(*ast.ExplainStmt)+ if !ok {+ return "", false, false+ }+ return explainFormat(explain), isExplainAnalyzeOmni(explain), true+}++func explainFormat(explain *ast.ExplainStmt) string {+ format := "text"+ if explain.Options == nil {+ return format+ }+ for _, item := range explain.Options.Items {+ option, ok := item.(*ast.DefElem)+ if !ok || !strings.EqualFold(option.Defname, "format") {+ continue+ }+ format = ""+ if arg, ok := option.Arg.(*ast.String); ok {+ format = strings.ToLower(arg.Str)+ }+ }+ return format+}+// explainStatementDefaultFormat plans in the engine's default format whatever the// request asked for. CockroachDB's EXPLAIN takes its own option list rather than-// PostgreSQL's FORMAT, so it offers only the default plan (supportedExplainFormats-// in the API refuses any other format for it before a request gets here).+// PostgreSQL's FORMAT, so it offers only the default plan (the driver capability+// table refuses any other format before a request gets here).func explainStatementDefaultFormat(statement string, _ base.ExplainFormat) (string, error) {return explainStatement(statement, base.ExplainFormatDefault)}diff --git a/backend/plugin/parser/pg/explain_test.go b/backend/plugin/parser/pg/explain_test.goindex 4edb402522..b992852a3e 100644--- a/backend/plugin/parser/pg/explain_test.go+++ b/backend/plugin/parser/pg/explain_test.go@@ -19,6 +19,7 @@ func TestExplainStatement(t *testing.T) {{"SELECT 1", base.ExplainFormatText, "EXPLAIN SELECT 1"},{"SELECT 1", base.ExplainFormatJSON, "EXPLAIN (FORMAT JSON) SELECT 1"},{"SELECT 1", base.ExplainFormatXML, "EXPLAIN (FORMAT XML) SELECT 1"},+ {"SELECT 1", base.ExplainFormatYAML, "EXPLAIN (FORMAT YAML) SELECT 1"},{"SELECT 1;", base.ExplainFormatDefault, "EXPLAIN SELECT 1;"},{"DELETE FROM t", base.ExplainFormatDefault, "EXPLAIN DELETE FROM t"},{"WITH x AS (SELECT 1) SELECT * FROM x", base.ExplainFormatDefault, "EXPLAIN WITH x AS (SELECT 1) SELECT * FROM x"},@@ -40,6 +41,26 @@ func TestExplainStatement(t *testing.T) {}}+func TestDescribeExplain(t *testing.T) {+ for _, tc := range []struct {+ statement string+ format string+ executed bool+ ok bool+ }{+ {statement: "SELECT 1"},+ {statement: "EXPLAIN SELECT 1", format: "text", ok: true},+ {statement: "EXPLAIN (FORMAT JSON) SELECT 1", format: "json", ok: true},+ {statement: "EXPLAIN (FORMAT XML, ANALYZE) SELECT 1", format: "xml", executed: true, ok: true},+ {statement: "EXPLAIN (ANALYZE false, FORMAT YAML) SELECT 1", format: "yaml", ok: true},+ } {+ format, executed, ok := DescribeExplain(tc.statement)+ require.Equal(t, tc.format, format, tc.statement)+ require.Equal(t, tc.executed, executed, tc.statement)+ require.Equal(t, tc.ok, ok, tc.statement)+ }+}+// TestExplainStatementRejects locks what never becomes an EXPLAIN: a write with// EXPLAIN options smuggled in front of it, which anything that simply prefixed// EXPLAIN would turn into an EXPLAIN ANALYZE DELETE that runs the DELETE, and andiff --git a/backend/plugin/parser/redshift/explain.go b/backend/plugin/parser/redshift/explain.goindex 1529868671..52dab37f17 100644--- a/backend/plugin/parser/redshift/explain.go+++ b/backend/plugin/parser/redshift/explain.go@@ -14,8 +14,7 @@ func init() {// explainStatement implements base.ExplainStatement. Redshift returns one plan// format here whatever the caller asked for: its EXPLAIN has no machine-readable-// form (supportedExplainFormats in the API offers this engine the default plan-// only).+// form (the driver capability table offers this engine the default plan only).func explainStatement(statement string, _ base.ExplainFormat) (string, error) {node, err := singleStatement(statement)if err != nil {diff --git a/backend/plugin/parser/snowflake/explain.go b/backend/plugin/parser/snowflake/explain.goindex c9516dfb58..e290cfb01b 100644--- a/backend/plugin/parser/snowflake/explain.go+++ b/backend/plugin/parser/snowflake/explain.go@@ -15,8 +15,8 @@ func init() {// explainStatement implements base.ExplainStatement. Snowflake returns one plan// format here whatever the caller asked for: its EXPLAIN USING JSON is a plan of-// its own shape that nothing downstream reads (supportedExplainFormats in the API-// offers this engine the default plan only).+// its own shape that nothing downstream reads (the driver capability table offers+// this engine the default plan only).func explainStatement(statement string, _ base.ExplainFormat) (string, error) {node, err := singleStatement(statement)if err != nil {diff --git a/backend/plugin/parser/standard/explain.go b/backend/plugin/parser/standard/explain.goindex a08887a100..633bc6f215 100644--- a/backend/plugin/parser/standard/explain.go+++ b/backend/plugin/parser/standard/explain.go@@ -14,8 +14,8 @@ func init() {// as text here. With no AST to ask which statement an EXPLAIN plans, a statement// that already asks for a plan runs as the user wrote it; that keeps a request// from planning a plan, which is what the rest of this package can promise.-// Both engines return one plan format whatever the caller asked for-// (supportedExplainFormats in the API offers them the default plan only).+// Both engines return one plan format whatever the caller asked for; the driver+// capability table offers them the default plan only.func explainStatement(statement string, _ base.ExplainFormat) (string, error) {if base.StartsWithExplain(statement) {return statement, nildiff --git a/backend/plugin/parser/starrocks/explain.go b/backend/plugin/parser/starrocks/explain.goindex a089be8dfa..d3cf59036d 100644--- a/backend/plugin/parser/starrocks/explain.go+++ b/backend/plugin/parser/starrocks/explain.go@@ -14,8 +14,8 @@ func init() {// explainStatement implements base.ExplainStatement. StarRocks returns one plan// format here whatever the caller asked for: its other EXPLAIN forms are plans of-// their own shape that nothing downstream reads (supportedExplainFormats in the-// API offers this engine the default plan only).+// their own shape that nothing downstream reads (the driver capability table+// offers this engine the default plan only).func explainStatement(statement string, _ base.ExplainFormat) (string, error) {node, err := singleStatement(statement)if err != nil {diff --git a/backend/plugin/parser/tidb/explain.go b/backend/plugin/parser/tidb/explain.goindex 88febfa3ca..998bbbe547 100644--- a/backend/plugin/parser/tidb/explain.go+++ b/backend/plugin/parser/tidb/explain.go@@ -16,8 +16,8 @@ func init() {// explainStatement implements base.ExplainStatement. TiDB returns one plan format// here whatever the caller asked for: its other FORMAT values are plans of their-// own shape that nothing downstream reads (supportedExplainFormats in the API-// offers this engine the default plan only).+// own shape that nothing downstream reads (the driver capability table offers+// this engine the default plan only).func explainStatement(statement string, _ base.ExplainFormat) (string, error) {node, err := singleStatement(statement)if err != nil {diff --git a/backend/plugin/parser/trino/explain.go b/backend/plugin/parser/trino/explain.goindex 2a3c03e139..922dd0e50d 100644--- a/backend/plugin/parser/trino/explain.go+++ b/backend/plugin/parser/trino/explain.go@@ -15,8 +15,8 @@ func init() {// explainStatement implements base.ExplainStatement. Trino returns one plan// format here whatever the caller asked for: its EXPLAIN (FORMAT JSON) is a plan-// of its own shape that nothing downstream reads (supportedExplainFormats in the-// API offers this engine the default plan only).+// of its own shape that nothing downstream reads (the driver capability table+// offers this engine the default plan only).func explainStatement(statement string, _ base.ExplainFormat) (string, error) {node, err := singleStatement(statement)if err != nil {diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.jsonindex d546f3285c..d08a0ac2d2 100644--- a/frontend/src/locales/en-US.json+++ b/frontend/src/locales/en-US.json@@ -3404,6 +3404,7 @@"view-schema-text": "View schema text","visualize-explain": "Visualize Explain","visualize-explain-blocked": "The query plan tab was blocked. Allow pop-ups for this site and try again.",+ "visualize-explain-executed": "Visualizing this plan would execute the query again.","visualize-explain-failed": "Failed to load the query plan","web-socket": {"connection-status": {diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.jsonindex 2e5907a5da..3e7ec17913 100644--- a/frontend/src/locales/es-ES.json+++ b/frontend/src/locales/es-ES.json@@ -3404,6 +3404,7 @@"view-schema-text": "Ver texto del esquema","visualize-explain": "Visualizar explicación","visualize-explain-blocked": "Se bloqueó la pestaña del plan de consulta. Permite las ventanas emergentes de este sitio e inténtalo de nuevo.",+ "visualize-explain-executed": "Visualizar este plan volvería a ejecutar la consulta.","visualize-explain-failed": "No se pudo cargar el plan de consulta","web-socket": {"connection-status": {diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.jsonindex 745d506b0a..70431c3bd4 100644--- a/frontend/src/locales/ja-JP.json+++ b/frontend/src/locales/ja-JP.json@@ -3404,6 +3404,7 @@"view-schema-text": "テキストの表示 スキーマ","visualize-explain": "視覚化の説明","visualize-explain-blocked": "クエリプランのタブがブロックされました。このサイトのポップアップを許可して再試行してください。",+ "visualize-explain-executed": "このプランを視覚化すると、クエリが再度実行されます。","visualize-explain-failed": "クエリプランの読み込みに失敗しました","web-socket": {"connection-status": {diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.jsonindex e14ed70950..df6bec1de6 100644--- a/frontend/src/locales/vi-VN.json+++ b/frontend/src/locales/vi-VN.json@@ -3404,6 +3404,7 @@"view-schema-text": "Xem văn bản lược đồ","visualize-explain": "Trực quan hóa Giải thích","visualize-explain-blocked": "Tab kế hoạch truy vấn đã bị chặn. Hãy cho phép cửa sổ bật lên cho trang này và thử lại.",+ "visualize-explain-executed": "Trực quan hóa kế hoạch này sẽ thực thi lại truy vấn.","visualize-explain-failed": "Không tải được kế hoạch truy vấn","web-socket": {"connection-status": {diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.jsonindex 0e2cf75871..3b1314d3de 100644--- a/frontend/src/locales/zh-CN.json+++ b/frontend/src/locales/zh-CN.json@@ -3404,6 +3404,7 @@"view-schema-text": "查看文本 Schema","visualize-explain": "可视化 Explain","visualize-explain-blocked": "查询计划标签页被拦截。请允许本站弹出窗口后重试。",+ "visualize-explain-executed": "可视化此计划会再次执行该查询。","visualize-explain-failed": "加载查询计划失败","web-socket": {"connection-status": {diff --git a/frontend/src/modules/sql-editor/components/ResultView/ResultStatusBar.test.tsx b/frontend/src/modules/sql-editor/components/ResultView/ResultStatusBar.test.tsxindex 2351ba5173..57f9904e19 100644--- a/frontend/src/modules/sql-editor/components/ResultView/ResultStatusBar.test.tsx+++ b/frontend/src/modules/sql-editor/components/ResultView/ResultStatusBar.test.tsx@@ -1,5 +1,5 @@-import { render, screen } from "@testing-library/react";-import { act } from "react";+import { fireEvent, render, screen } from "@testing-library/react";+import { act, cloneElement } from "react";import { beforeEach, describe, expect, test, vi } from "vitest";import type { Database } from "@/types/proto-es/v1/database_service_pb";import { formatQueryTime, ResultStatusBar } from "./ResultStatusBar";@@ -29,7 +29,13 @@ vi.mock("@/components/DatabaseTargetDisplay", () => ({}));vi.mock("@/components/ui/tooltip", () => ({- Tooltip: ({ children }: { children: React.ReactNode }) => <>{children}</>,+ Tooltip: ({+ children,+ content,+ }: {+ children: React.ReactElement<{ title?: string }>;+ content?: string;+ }) => (content ? cloneElement(children, { title: content }) : children),}));vi.mock("@/stores/app", () => ({@@ -114,6 +120,42 @@ describe("ResultStatusBar", () => {);});+ test("disables Visualize with the reason", () => {+ const onVisualizeExplain = vi.fn();+ const { rerender } = render(+ <ResultStatusBar+ database={database}+ statement="EXPLAIN SELECT 1"+ queryTime="3 ms"+ showVisualizeButton+ onVisualizeExplain={onVisualizeExplain}+ />+ );++ const visualize = screen.getByRole("button", {+ name: "sql-editor.visualize-explain",+ });+ expect(visualize).toBeEnabled();+ fireEvent.click(visualize);+ expect(onVisualizeExplain).toHaveBeenCalledTimes(1);++ rerender(+ <ResultStatusBar+ database={database}+ statement="EXPLAIN SELECT 1"+ queryTime="3 ms"+ showVisualizeButton+ visualizeDisabledReason="it would run again"+ onVisualizeExplain={onVisualizeExplain}+ />+ );++ expect(visualize).toBeDisabled();+ expect(visualize).toHaveAttribute("title", "it would run again");+ fireEvent.click(visualize);+ expect(onVisualizeExplain).toHaveBeenCalledTimes(1);+ });+test("lets the database label shrink while the statement truncates", () => {render(<ResultStatusBardiff --git a/frontend/src/modules/sql-editor/components/ResultView/ResultStatusBar.tsx b/frontend/src/modules/sql-editor/components/ResultView/ResultStatusBar.tsxindex 09ec7914d8..b99085e012 100644--- a/frontend/src/modules/sql-editor/components/ResultView/ResultStatusBar.tsx+++ b/frontend/src/modules/sql-editor/components/ResultView/ResultStatusBar.tsx@@ -4,6 +4,7 @@ import { DatabaseTargetDisplay } from "@/components/DatabaseTargetDisplay";import { Button } from "@/components/ui/button";import { CopyButton } from "@/components/ui/copy-button";import { EllipsisText } from "@/components/ui/ellipsis-text";+import { Tooltip } from "@/components/ui/tooltip";import { cn } from "@/lib/utils";import type { Database } from "@/types/proto-es/v1/database_service_pb";import type { QueryResult } from "@/types/proto-es/v1/sql_service_pb";@@ -36,6 +37,7 @@ type ResultStatusBarProps = Readonly<{statement: string;queryTime: string;showVisualizeButton?: boolean;+ visualizeDisabledReason?: string;onVisualizeExplain?: () => void;}>;@@ -44,6 +46,7 @@ export function ResultStatusBar({statement,queryTime,showVisualizeButton = false,+ visualizeDisabledReason,onVisualizeExplain,}: ResultStatusBarProps) {const { t } = useTranslation();@@ -136,14 +139,17 @@ export function ResultStatusBar({</div><div className="flex shrink-0 items-center gap-x-2">{showVisualizeButton && (- <Button- size="sm"- appearance="link"- className="h-auto px-0 text-xs"- onClick={onVisualizeExplain}- >- {t("sql-editor.visualize-explain")}- </Button>+ <Tooltip content={visualizeDisabledReason}>+ <Button+ size="sm"+ appearance="link"+ className="h-auto px-0 text-xs"+ disabled={!!visualizeDisabledReason}+ onClick={onVisualizeExplain}+ >+ {t("sql-editor.visualize-explain")}+ </Button>+ </Tooltip>)}<span>{t("sql-editor.query-time")}: {queryTime}diff --git a/frontend/src/modules/sql-editor/components/ResultView/ResultView.tsx b/frontend/src/modules/sql-editor/components/ResultView/ResultView.tsxindex 66edd7ff0a..75ca794458 100644--- a/frontend/src/modules/sql-editor/components/ResultView/ResultView.tsx+++ b/frontend/src/modules/sql-editor/components/ResultView/ResultView.tsx@@ -333,6 +333,7 @@ export function ResultView({params={executeParams}database={database}result={result}+ results={resultSet.results}resultIndex={resultSet.results.indexOf(result)}showExport={false}maximumExportCount={queryDataPolicy?.maximumResultRows}diff --git a/frontend/src/modules/sql-editor/components/ResultView/SingleResultView.test.tsx b/frontend/src/modules/sql-editor/components/ResultView/SingleResultView.test.tsxindex 1640986bb0..79e46cbf3b 100644--- a/frontend/src/modules/sql-editor/components/ResultView/SingleResultView.test.tsx+++ b/frontend/src/modules/sql-editor/components/ResultView/SingleResultView.test.tsx@@ -7,6 +7,7 @@ import { Engine } from "@/types/proto-es/v1/common_pb";import type { Database } from "@/types/proto-es/v1/database_service_pb";import {QueryOption_ExplainFormat,+ QueryResult_QueryPlanSchema,QueryResultSchema,QueryRowSchema,RowValueSchema,@@ -259,14 +260,21 @@ vi.mock("./ResultStatusBar", () => ({formatQueryTime: () => "-",ResultStatusBar: ({showVisualizeButton,+ visualizeDisabledReason,onVisualizeExplain,}: {showVisualizeButton?: boolean;+ visualizeDisabledReason?: string;onVisualizeExplain?: () => void;}) => (<div data-testid="result-status">{showVisualizeButton ? (- <button type="button" onClick={onVisualizeExplain}>+ <button+ type="button"+ disabled={!!visualizeDisabledReason}+ title={visualizeDisabledReason}+ onClick={onVisualizeExplain}+ >visualize-explain</button>) : null}@@ -599,6 +607,24 @@ describe("SingleResultView document view", () => {});});+const textPlanResult = (statement: string) =>+ create(QueryResultSchema, {+ columnNames: ["QUERY PLAN"],+ statement,+ queryPlan: create(QueryResult_QueryPlanSchema, {+ format: QueryOption_ExplainFormat.TEXT,+ }),+ rows: [+ create(QueryRowSchema, {+ values: [+ create(RowValueSchema, {+ kind: { case: "stringValue", value: "Result" },+ }),+ ],+ }),+ ],+ });+describe("SingleResultView explain visualizer", () => {beforeEach(() => {createExplainToken.mockClear();@@ -619,7 +645,7 @@ describe("SingleResultView explain visualizer", () => {context.resultSet = {results: [create(QueryResultSchema, {- statement: "SELECT 1",+ statement: "EXPLAIN (FORMAT JSON) SELECT 1",rows: [create(QueryRowSchema, {values: [@@ -638,12 +664,20 @@ describe("SingleResultView explain visualizer", () => {render(<SingleResultViewdisallowCopyingData={false}- params={{ ...params, engine: Engine.POSTGRES, explain: true }}+ params={{+ ...params,+ engine: Engine.POSTGRES,+ explain: false,+ statement: "EXPLAIN SELECT 1",+ }}database={databaseForEngine(Engine.POSTGRES)}result={create(QueryResultSchema, {columnNames: ["QUERY PLAN"],columnTypeNames: ["TEXT"],- statement: "SELECT 1",+ statement: "EXPLAIN SELECT 1",+ queryPlan: create(QueryResult_QueryPlanSchema, {+ format: QueryOption_ExplainFormat.TEXT,+ }),rows: [create(QueryRowSchema, {values: [@@ -665,8 +699,12 @@ describe("SingleResultView explain visualizer", () => {expect(runQuery.mock.calls[0][1].params.queryOption?.explainFormat).toBe(QueryOption_ExplainFormat.JSON);+ expect(runQuery.mock.calls[0][1].params.explain).toBe(true);+ expect(runQuery.mock.calls[0][1].params.statement).toBe(+ "EXPLAIN SELECT 1"+ );expect(createExplainToken).toHaveBeenCalledWith({- statement: "SELECT 1",+ statement: "EXPLAIN (FORMAT JSON) SELECT 1",explain: planJSON,engine: Engine.POSTGRES,});@@ -677,7 +715,7 @@ describe("SingleResultView explain visualizer", () => {openSpy.mockRestore();});- test("re-runs for the tab the user clicked, not the first result", async () => {+ test("re-runs only the statement for the tab the user clicked", async () => {const openSpy = vi.spyOn(window, "open").mockReturnValue(null);runQuery.mockImplementation(async (_database: unknown, context: { resultSet?: { results: unknown[] } }) => {@@ -694,19 +732,27 @@ describe("SingleResultView explain visualizer", () => {}),],});- context.resultSet = { results: [plan("first"), plan("second")] };+ context.resultSet = { results: [plan("second")] };});render(<SingleResultViewdisallowCopyingData={false}- params={{ ...params, engine: Engine.POSTGRES, explain: true }}+ params={{+ ...params,+ engine: Engine.POSTGRES,+ explain: true,+ statement: "first; second",+ }}database={databaseForEngine(Engine.POSTGRES)}result={create(QueryResultSchema, {columnNames: ["QUERY PLAN"],columnTypeNames: ["TEXT"],statement: "second",+ queryPlan: create(QueryResult_QueryPlanSchema, {+ format: QueryOption_ExplainFormat.TEXT,+ }),rows: [create(QueryRowSchema, {values: [@@ -725,6 +771,7 @@ describe("SingleResultView explain visualizer", () => {fireEvent.click(screen.getByText("visualize-explain"));await waitFor(() => expect(createExplainToken).toHaveBeenCalled());+ expect(runQuery.mock.calls[0][1].params.statement).toBe("second");expect(createExplainToken).toHaveBeenCalledWith({statement: "second",explain: "plan of second",@@ -765,6 +812,9 @@ describe("SingleResultView explain visualizer", () => {columnNames: ["QUERY PLAN"],columnTypeNames: ["TEXT"],statement: "SELECT 1",+ queryPlan: create(QueryResult_QueryPlanSchema, {+ format: QueryOption_ExplainFormat.TEXT,+ }),rows: [create(QueryRowSchema, {values: [@@ -826,6 +876,9 @@ describe("SingleResultView explain visualizer", () => {result={create(QueryResultSchema, {columnNames: ["QUERY PLAN"],statement: "SELECT 1",+ queryPlan: create(QueryResult_QueryPlanSchema, {+ format: QueryOption_ExplainFormat.TEXT,+ }),rows: [create(QueryRowSchema, {values: [@@ -869,6 +922,9 @@ describe("SingleResultView explain visualizer", () => {columnNames: ["QUERY PLAN"],columnTypeNames: ["JSON"],statement: "SELECT 1",+ queryPlan: create(QueryResult_QueryPlanSchema, {+ format: QueryOption_ExplainFormat.JSON,+ }),rows: [create(QueryRowSchema, {values: [@@ -895,6 +951,153 @@ describe("SingleResultView explain visualizer", () => {openSpy.mockRestore();});+ test("uses a typed structured plan without running another query", async () => {+ const openSpy = vi.spyOn(window, "open").mockReturnValue({} as Window);+ const plan = '[{"Plan":{"Node Type":"Result"}}]';++ render(+ <SingleResultView+ disallowCopyingData={false}+ params={{+ ...params,+ engine: Engine.POSTGRES,+ explain: false,+ statement: "EXPLAIN (FORMAT JSON) SELECT 1",+ }}+ database={databaseForEngine(Engine.POSTGRES)}+ result={create(QueryResultSchema, {+ columnNames: ["QUERY PLAN"],+ statement: "EXPLAIN (FORMAT JSON) SELECT 1",+ queryPlan: create(QueryResult_QueryPlanSchema, {+ format: QueryOption_ExplainFormat.JSON,+ }),+ rows: [+ create(QueryRowSchema, {+ values: [+ create(RowValueSchema, {+ kind: { case: "stringValue", value: plan },+ }),+ ],+ }),+ ],+ })}+ showExport={false}+ />+ );++ fireEvent.click(screen.getByText("visualize-explain"));++ await waitFor(() => expect(openSpy).toHaveBeenCalled());+ expect(runQuery).not.toHaveBeenCalled();+ expect(createExplainToken).toHaveBeenCalledWith({+ statement: "EXPLAIN (FORMAT JSON) SELECT 1",+ explain: plan,+ engine: Engine.POSTGRES,+ });+ openSpy.mockRestore();+ });++ test("disables Visualize when reformatting would execute the query again", () => {+ render(+ <SingleResultView+ disallowCopyingData={false}+ params={{+ ...params,+ engine: Engine.POSTGRES,+ explain: false,+ statement: "EXPLAIN ANALYZE SELECT 1",+ }}+ database={databaseForEngine(Engine.POSTGRES)}+ result={create(QueryResultSchema, {+ columnNames: ["QUERY PLAN"],+ statement: "EXPLAIN ANALYZE SELECT 1",+ queryPlan: create(QueryResult_QueryPlanSchema, {+ format: QueryOption_ExplainFormat.TEXT,+ executed: true,+ }),+ rows: [],+ })}+ showExport={false}+ />+ );++ const button = screen.getByText("visualize-explain");+ expect(button).toBeDisabled();+ expect(button).toHaveAttribute(+ "title",+ "sql-editor.visualize-explain-executed"+ );+ });++ test("does not replay after a result that was not a plan", () => {+ const earlier = create(QueryResultSchema, { statement: "SET x = 1" });+ const current = textPlanResult("EXPLAIN SELECT 1");++ render(+ <SingleResultView+ disallowCopyingData={false}+ params={{ ...params, engine: Engine.POSTGRES }}+ database={databaseForEngine(Engine.POSTGRES)}+ result={current}+ results={[earlier, current]}+ resultIndex={1}+ showExport={false}+ />+ );++ expect(screen.queryByText("visualize-explain")).toBeNull();+ });++ test("ignores later statements when replaying an earlier plan", async () => {+ const openSpy = vi.spyOn(window, "open").mockReturnValue({} as Window);+ const current = textPlanResult("EXPLAIN SELECT 1");+ const later = create(QueryResultSchema, { statement: "SET x = 1" });+ runQuery.mockImplementation(+ async (_database: unknown, context: { resultSet?: { results: unknown[] } }) => {+ context.resultSet = {+ results: [+ create(QueryResultSchema, {+ statement: "EXPLAIN (FORMAT JSON) SELECT 1",+ rows: [+ create(QueryRowSchema, {+ values: [+ create(RowValueSchema, {+ kind: { case: "stringValue", value: "[]" },+ }),+ ],+ }),+ ],+ }),+ ],+ };+ }+ );++ render(+ <SingleResultView+ disallowCopyingData={false}+ params={{+ ...params,+ engine: Engine.POSTGRES,+ statement: "EXPLAIN SELECT 1; SET x = 1",+ }}+ database={databaseForEngine(Engine.POSTGRES)}+ result={current}+ results={[current, later]}+ resultIndex={0}+ showExport={false}+ />+ );++ fireEvent.click(screen.getByText("visualize-explain"));++ await waitFor(() => expect(openSpy).toHaveBeenCalled());+ expect(runQuery.mock.calls[0][1].params.statement).toBe(+ "EXPLAIN SELECT 1"+ );+ openSpy.mockRestore();+ });+test("offers no visualizer for an engine it cannot draw", () => {render(<SingleResultView@@ -904,6 +1107,9 @@ describe("SingleResultView explain visualizer", () => {result={create(QueryResultSchema, {columnNames: ["EXPLAIN"],statement: "SELECT 1",+ queryPlan: create(QueryResult_QueryPlanSchema, {+ format: QueryOption_ExplainFormat.TEXT,+ }),rows: [create(QueryRowSchema, {values: [diff --git a/frontend/src/modules/sql-editor/components/ResultView/SingleResultView.tsx b/frontend/src/modules/sql-editor/components/ResultView/SingleResultView.tsxindex c2a9a8dcc5..e47d6c80b3 100644--- a/frontend/src/modules/sql-editor/components/ResultView/SingleResultView.tsx+++ b/frontend/src/modules/sql-editor/components/ResultView/SingleResultView.tsx@@ -94,8 +94,9 @@ export interface SingleResultViewProps {params: SQLEditorQueryParams;database: Database;result: QueryResult;- // Which statement of a multi-statement run this view shows. Visualize re-runs- // the whole statement and has to pick the same one back out.+ // Every result of the run, and which one this view shows. Visualize uses+ // earlier results to decide whether replaying this statement is safe.+ results?: QueryResult[];resultIndex?: number;showExport: boolean;// Optional tooltip shown on the export button — used to explain when the@@ -281,6 +282,7 @@ function SingleResultViewInner({params,database,result,+ results = [],resultIndex = 0,showExport,exportTooltip,@@ -397,23 +399,37 @@ function SingleResultViewInner({[flattenedTableView, result.masked]);- const showVisualizeButton = isVisualizerEngine(engine) && !!params.explain;+ const plan = result.queryPlan;+ const planInRows =+ isVisualizerEngine(engine) &&+ plan?.format ===+ QueryOption_ExplainFormat[VISUALIZER_EXPLAIN_FORMATS[engine]];+ // Replaying this statement is safe only when every earlier statement was+ // itself a non-executing plan and could not change session state.+ const canReplay =+ isVisualizerEngine(engine) &&+ plan?.format === QueryOption_ExplainFormat.TEXT &&+ results+ .slice(0, resultIndex)+ .every((earlier) => earlier.queryPlan && !earlier.queryPlan.executed);+ const showVisualizeButton = planInRows || canReplay;+ const visualizeDisabledReason =+ !planInRows && plan?.executed+ ? t("sql-editor.visualize-explain-executed")+ : undefined;const visualizeExplain = async () => {if (!isVisualizerEngine(engine)) return;try {- // Spanner explains only as JSON, so the result on screen already is the- // plan the visualizer reads; the other engines show a readable plan.- const token =- engine === Engine.SPANNER- ? getExplainTokenFromResult(result, engine)- : await getExplainToken(- database,- params,- runQuery,- engine,- resultIndex- );+ const token = planInRows+ ? getExplainTokenFromResult(result, engine)+ : await getExplainToken(+ database,+ params,+ result.statement,+ runQuery,+ engine+ );if (!token) {// The plan is fetched by a second query, so a failure here is invisible// unless we say so — the button would otherwise do nothing.@@ -755,6 +771,7 @@ function SingleResultViewInner({statement={result.statement ?? ""}queryTime={queryTime}showVisualizeButton={showVisualizeButton}+ visualizeDisabledReason={visualizeDisabledReason}onVisualizeExplain={visualizeExplain}/></>@@ -830,30 +847,28 @@ function getExplainTokenFromResult(return createExplainToken({ statement, explain, engine });}-// getExplainToken re-runs the explain in the format the visualizer reads for-// the engine, whatever format the grid is showing, so the plan is only fetched-// when the user asks for it.async function getExplainToken(database: Database,params: SQLEditorQueryParams,+ statement: string,runQuery: ReturnType<typeof useExecuteSQL>["runQuery"],- engine: VisualizerEngine,- resultIndex: number+ engine: VisualizerEngine): Promise<string | undefined> {+ if (!statement) return undefined;const explainFormat =QueryOption_ExplainFormat[VISUALIZER_EXPLAIN_FORMATS[engine]];const context: SQLEditorDatabaseQueryContext = {id: uuidv4(),params: {...params,+ statement,+ explain: true,queryOption: create(QueryOptionSchema, { explainFormat }),},status: "PENDING",};await runQuery(database, context);- // The re-run replays every statement the user submitted, so take the one this- // view is showing rather than the first.- const result = context.resultSet?.results[resultIndex];+ const result = context.resultSet?.results[0];if (!result) return undefined;return getExplainTokenFromResult(result, engine);}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 e670d7ebbb..2951d2f56c 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@@ -191,6 +191,13 @@ export declare type QueryOption = Message<"bytebase.v1.QueryOption"> & {redisRunCommandsOn: QueryOption_RedisRunCommandsOn;/**+ * Which explain output the caller wants, for an explain request.+ *+ * Leave it unspecified for the engine's own default, which is the only+ * output most engines have. Naming a format an engine cannot produce is+ * INVALID_ARGUMENT rather than a silent fallback, as is any explain request+ * against an engine that has no explain at all.+ ** @generated from field: bytebase.v1.QueryOption.ExplainFormat explain_format = 3;*/explainFormat: QueryOption_ExplainFormat;@@ -234,18 +241,15 @@ export enum QueryOption_RedisRunCommandsOn {export declare const QueryOption_RedisRunCommandsOnSchema: GenEnum<QueryOption_RedisRunCommandsOn>;/**- * Which explain output the caller wants, for an explain request.- *- * Leave it unspecified for the engine's own default, which is the only- * output most engines have. Naming a format an engine cannot produce is- * INVALID_ARGUMENT rather than a silent fallback, as is any explain request- * against an engine that has no explain at all.+ * The output format of a query plan.** @generated from enum bytebase.v1.QueryOption.ExplainFormat*/export enum QueryOption_ExplainFormat {/**- * The engine's default: PostgreSQL EXPLAIN, SQL Server SHOWPLAN_ALL.+ * The engine's default: PostgreSQL EXPLAIN, SQL Server SHOWPLAN_ALL. On a+ * result, a default the server could not resolve, as when MySQL follows the+ * session's explain_format; read such a plan as text.** @generated from enum value: EXPLAIN_FORMAT_UNSPECIFIED = 0;*/@@ -273,6 +277,13 @@ export enum QueryOption_ExplainFormat {* @generated from enum value: XML = 3;*/XML = 3,++ /**+ * The plan tree as YAML. PostgreSQL: EXPLAIN (FORMAT YAML).+ *+ * @generated from enum value: YAML = 4;+ */+ YAML = 4,}/**@@ -375,6 +386,13 @@ export declare type QueryResult = Message<"bytebase.v1.QueryResult"> & {* @generated from field: repeated bytebase.v1.MaskingReason masked = 12;*/masked: MaskingReason[];++ /**+ * Set when the result is a query plan. Unset for any other result.+ *+ * @generated from field: bytebase.v1.QueryResult.QueryPlan query_plan = 14;+ */+ queryPlan?: QueryResult_QueryPlan | undefined;};/**@@ -633,6 +651,32 @@ export enum QueryResult_Message_Level {*/export declare const QueryResult_Message_LevelSchema: GenEnum<QueryResult_Message_Level>;+/**+ * A query plan held in the result's rows.+ *+ * @generated from message bytebase.v1.QueryResult.QueryPlan+ */+export declare type QueryResult_QueryPlan = Message<"bytebase.v1.QueryResult.QueryPlan"> & {+ /**+ * @generated from field: bytebase.v1.QueryOption.ExplainFormat format = 1;+ */+ format: QueryOption_ExplainFormat;++ /**+ * Whether producing the plan executed the statement, as EXPLAIN ANALYZE+ * does.+ *+ * @generated from field: bool executed = 2;+ */+ executed: boolean;+};++/**+ * Describes the message bytebase.v1.QueryResult.QueryPlan.+ * Use `create(QueryResult_QueryPlanSchema)` to create a new message.+ */+export declare const QueryResult_QueryPlanSchema: GenMessage<QueryResult_QueryPlan>;+/*** @generated from message bytebase.v1.MaskingReason*/diff --git a/frontend/src/types/proto-es/v1/sql_service_pb.js b/frontend/src/types/proto-es/v1/sql_service_pb.jsindex f4d13fc517..332cd0a1ef 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/AEKDFF1ZXJ5UmVxdWVzdBIrCgRuYW1lGAEgASgJQh3gQQL6QRcKFWJ5dGViYXNlLmNvbS9EYXRhYmFzZRIRCglzdGF0ZW1lbnQYAiABKAkSDQoFbGltaXQYAyABKAUSFgoOZGF0YV9zb3VyY2VfaWQYBCABKAkSDwoHZXhwbGFpbhgFIAEoCBITCgZzY2hlbWEYBiABKAlIAIgBARIuCgxxdWVyeV9vcHRpb24YByABKAsyGC5ieXRlYmFzZS52MS5RdWVyeU9wdGlvbhIWCgljb250YWluZXIYCCABKAlIAYgBAUIJCgdfc2NoZW1hQgwKCl9jb250YWluZXIiWAoNUXVlcnlSZXNwb25zZRIpCgdyZXN1bHRzGAEgAygLMhguYnl0ZWJhc2UudjEuUXVlcnlSZXN1bHQSHAoUYXBwbGllZF9hY2Nlc3NfZ3JhbnQYAiABKAki4AIKC1F1ZXJ5T3B0aW9uEkoKFXJlZGlzX3J1bl9jb21tYW5kc19vbhgBIAEoDjIrLmJ5dGViYXNlLnYxLlF1ZXJ5T3B0aW9uLlJlZGlzUnVu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GViYXNlLnYxLkV4cG9ydFJlc3BvbnNlIo8BiuowEGJiLmRhdGFiYXNlcy5nZXSQ6jABmOowAaDqMAKC0+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+kEXChVieXRlYmFzZS5jb20vRGF0YWJhc2USEQoJc3RhdGVtZW50GAIgASgJEg0KBWxpbWl0GAMgASgFEhMKBnNjaGVtYRgEIAEoCUgAiAEBEhYKCWNvbnRhaW5lchgFIAEoCUgBiAEBQgkKB19zY2hlbWFCDAoKX2NvbnRhaW5lciJBChRBZG1pbkV4ZWN1dGVSZXNwb25zZRIpCgdyZXN1bHRzGAEgAygLMhguYnl0ZWJhc2UudjEuUXVlcnlSZXN1bHQi/AEKDFF1ZXJ5UmVxdWVzdBIrCgRuYW1lGAEgASgJQh3gQQL6QRcKFWJ5dGViYXNlLmNvbS9EYXRhYmFzZRIRCglzdGF0ZW1lbnQYAiABKAkSDQoFbGltaXQYA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TWV0YWRhdGHqAgxCeXRlYmFzZTo6VjFiBnByb3RvMw", [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.@@ -71,12 +71,7 @@ export const QueryOption_ExplainFormatSchema = /*@__PURE__*/enumDesc(file_v1_sql_service, 4, 1);/**- * Which explain output the caller wants, for an explain request.- *- * Leave it unspecified for the engine's own default, which is the only- * output most engines have. Naming a format an engine cannot produce is- * INVALID_ARGUMENT rather than a silent fallback, as is any explain request- * against an engine that has no explain at all.+ * The output format of a query plan.** @generated from enum bytebase.v1.QueryOption.ExplainFormat*/@@ -142,6 +137,13 @@ export const QueryResult_Message_LevelSchema = /*@__PURE__*/export const QueryResult_Message_Level = /*@__PURE__*/tsEnum(QueryResult_Message_LevelSchema);+/**+ * Describes the message bytebase.v1.QueryResult.QueryPlan.+ * Use `create(QueryResult_QueryPlanSchema)` to create a new message.+ */+export const QueryResult_QueryPlanSchema = /*@__PURE__*/+ messageDesc(file_v1_sql_service, 5, 4);+/*** Describes the message bytebase.v1.MaskingReason.* Use `create(MaskingReasonSchema)` to create a new message.diff --git a/proto/gen/grpc-doc/openapi.yaml b/proto/gen/grpc-doc/openapi.yamlindex d623f72688..6ed5787044 100644--- a/proto/gen/grpc-doc/openapi.yaml+++ b/proto/gen/grpc-doc/openapi.yaml@@ -26050,6 +26050,13 @@ components:allOf:- $ref: '#/components/schemas/bytebase.v1.QueryOption.ExplainFormat'title: explain_format+ description: |-+ Which explain output the caller wants, for an explain request.++ Leave it unspecified for the engine's own default, which is the only+ output most engines have. Naming a format an engine cannot produce is+ INVALID_ARGUMENT rather than a silent fallback, as is any explain request+ against an engine that has no explain at all.title: QueryOptionadditionalProperties: falsebytebase.v1.QueryOption.ExplainFormat:@@ -26060,13 +26067,8 @@ components:- TEXT- JSON- XML- description: |-- Which explain output the caller wants, for an explain request.-- Leave it unspecified for the engine's own default, which is the only- output most engines have. Naming a format an engine cannot produce is- INVALID_ARGUMENT rather than a silent fallback, as is any explain request- against an engine that has no explain at all.+ - YAML+ description: The output format of a query plan.bytebase.v1.QueryOption.RedisRunCommandsOn:type: stringtitle: RedisRunCommandsOn@@ -26253,6 +26255,11 @@ components:$ref: '#/components/schemas/bytebase.v1.MaskingReason'title: maskeddescription: Masking reasons for each column (empty for non-masked columns).+ queryPlan:+ allOf:+ - $ref: '#/components/schemas/bytebase.v1.QueryResult.QueryPlan'+ title: query_plan+ description: Set when the result is a query plan. Unset for any other result.title: QueryResultbytebase.v1.QueryResult.CommandError:type: object@@ -26360,6 +26367,22 @@ components:description: |-refer https://www.postgresql.org/docs/11/protocol-error-fields.htmlfor field description.+ bytebase.v1.QueryResult.QueryPlan:+ type: object+ properties:+ format:+ allOf:+ - $ref: '#/components/schemas/bytebase.v1.QueryOption.ExplainFormat'+ title: format+ executed:+ type: boolean+ title: executed+ description: |-+ Whether producing the plan executed the statement, as EXPLAIN ANALYZE+ does.+ title: QueryPlan+ additionalProperties: false+ description: A query plan held in the result's rows.bytebase.v1.QueryResult.SyntaxError:type: objectproperties:diff --git a/proto/gen/grpc-doc/v1/README.md b/proto/gen/grpc-doc/v1/README.mdindex a6d4dd43de..1be73b23c6 100644--- a/proto/gen/grpc-doc/v1/README.md+++ b/proto/gen/grpc-doc/v1/README.md@@ -126,6 +126,7 @@- [QueryResult.CommandError](#bytebase-v1-QueryResult-CommandError)- [QueryResult.Message](#bytebase-v1-QueryResult-Message)- [QueryResult.PostgresError](#bytebase-v1-QueryResult-PostgresError)+ - [QueryResult.QueryPlan](#bytebase-v1-QueryResult-QueryPlan)- [QueryResult.SyntaxError](#bytebase-v1-QueryResult-SyntaxError)- [QueryRow](#bytebase-v1-QueryRow)- [RowValue](#bytebase-v1-RowValue)@@ -2564,7 +2565,9 @@ QueryHistoryService manages query history records of SQL Editor queries and expo| Field | Type | Label | Description || ----- | ---- | ----- | ----------- || redis_run_commands_on | [QueryOption.RedisRunCommandsOn](#bytebase-v1-QueryOption-RedisRunCommandsOn) | | |-| explain_format | [QueryOption.ExplainFormat](#bytebase-v1-QueryOption-ExplainFormat) | | |+| explain_format | [QueryOption.ExplainFormat](#bytebase-v1-QueryOption-ExplainFormat) | | Which explain output the caller wants, for an explain request.++Leave it unspecified for the engine's own default, which is the only output most engines have. Naming a format an engine cannot produce is INVALID_ARGUMENT rather than a silent fallback, as is any explain request against an engine that has no explain at all. |@@ -2630,6 +2633,7 @@ QueryHistoryService manages query history records of SQL Editor queries and expo| command_error | [QueryResult.CommandError](#bytebase-v1-QueryResult-CommandError) | | || messages | [QueryResult.Message](#bytebase-v1-QueryResult-Message) | repeated | Informational or debug messages returned by the database engine during query execution. Examples include PostgreSQL's RAISE NOTICE, MSSQL's PRINT, or Oracle's DBMS_OUTPUT.PUT_LINE. || masked | [MaskingReason](#bytebase-v1-MaskingReason) | repeated | Masking reasons for each column (empty for non-masked columns). |+| query_plan | [QueryResult.QueryPlan](#bytebase-v1-QueryResult-QueryPlan) | | Set when the result is a query plan. Unset for any other result. |@@ -2700,6 +2704,22 @@ for field description.+<a name="bytebase-v1-QueryResult-QueryPlan"></a>++### QueryResult.QueryPlan+A query plan held in the result's rows.+++| 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. |++++++<a name="bytebase-v1-QueryResult-SyntaxError"></a>### QueryResult.SyntaxError@@ -2823,19 +2843,15 @@ RuleType indicates the source of the linting rule.<a name="bytebase-v1-QueryOption-ExplainFormat"></a>### QueryOption.ExplainFormat-Which explain output the caller wants, for an explain request.--Leave it unspecified for the engine's own default, which is the only-output most engines have. Naming a format an engine cannot produce is-INVALID_ARGUMENT rather than a silent fallback, as is any explain request-against an engine that has no explain at all.+The output format of a query plan.| Name | Number | Description || ---- | ------ | ----------- |-| EXPLAIN_FORMAT_UNSPECIFIED | 0 | The engine's default: PostgreSQL EXPLAIN, SQL Server SHOWPLAN_ALL. |+| EXPLAIN_FORMAT_UNSPECIFIED | 0 | The engine's default: PostgreSQL EXPLAIN, SQL Server SHOWPLAN_ALL. On a result, a default the server could not resolve, as when MySQL follows the session's explain_format; read such a plan as text. || TEXT | 1 | The human-readable plan. PostgreSQL: EXPLAIN (FORMAT TEXT). SQL Server: SHOWPLAN_ALL. || JSON | 2 | The plan tree as JSON. PostgreSQL: EXPLAIN (FORMAT JSON). || XML | 3 | The plan tree as XML. PostgreSQL: EXPLAIN (FORMAT XML). SQL Server: SHOWPLAN_XML. |+| YAML | 4 | The plan tree as YAML. PostgreSQL: EXPLAIN (FORMAT YAML). |diff --git a/proto/gen/grpc-doc/v1/index.html b/proto/gen/grpc-doc/v1/index.htmlindex 2889d81231..0b05c98641 100644--- a/proto/gen/grpc-doc/v1/index.html+++ b/proto/gen/grpc-doc/v1/index.html@@ -649,6 +649,10 @@<a href="#bytebase.v1.QueryResult.PostgresError"><span class="badge">M</span>QueryResult.PostgresError</a></li>+ <li>+ <a href="#bytebase.v1.QueryResult.QueryPlan"><span class="badge">M</span>QueryResult.QueryPlan</a>+ </li>+<li><a href="#bytebase.v1.QueryResult.SyntaxError"><span class="badge">M</span>QueryResult.SyntaxError</a></li>@@ -8059,7 +8063,12 @@ Empty when the user was authorized through normal ACL rather than a grant. </p><<td>explain_format</td><td><a href="#bytebase.v1.QueryOption.ExplainFormat">QueryOption.ExplainFormat</a></td><td></td>- <td><p> </p></td>+ <td><p>Which explain output the caller wants, for an explain request.++Leave it unspecified for the engine's own default, which is the only+output most engines have. Naming a format an engine cannot produce is+INVALID_ARGUMENT rather than a silent fallback, as is any explain request+against an engine that has no explain at all. </p></td></tr></tbody>@@ -8286,6 +8295,13 @@ Examples include PostgreSQL's RAISE NOTICE, MSSQL's PRINT, or Oracle'<td><p>Masking reasons for each column (empty for non-masked columns). </p></td></tr>+ <tr>+ <td>query_plan</td>+ <td><a href="#bytebase.v1.QueryResult.QueryPlan">QueryResult.QueryPlan</a></td>+ <td></td>+ <td><p>Set when the result is a query plan. Unset for any other result. </p></td>+ </tr>+</tbody></table>@@ -8484,6 +8500,38 @@ 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>+++ <table class="field-table">+ <thead>+ <tr><td>Field</td><td>Type</td><td>Label</td><td>Description</td></tr>+ </thead>+ <tbody>++ <tr>+ <td>format</td>+ <td><a href="#bytebase.v1.QueryOption.ExplainFormat">QueryOption.ExplainFormat</a></td>+ <td></td>+ <td><p> </p></td>+ </tr>++ <tr>+ <td>executed</td>+ <td><a href="#bool">bool</a></td>+ <td></td>+ <td><p>Whether producing the plan executed the statement, as EXPLAIN ANALYZE+does. </p></td>+ </tr>++ </tbody>+ </table>+++++<h3 id="bytebase.v1.QueryResult.SyntaxError">QueryResult.SyntaxError</h3><p>Syntax error with position information for editor highlighting</p>@@ -8794,7 +8842,7 @@ These are custom, flexible checks powered by AI models.</p></td></table><h3 id="bytebase.v1.QueryOption.ExplainFormat">QueryOption.ExplainFormat</h3>- <p>Which explain output the caller wants, for an explain request.</p><p>Leave it unspecified for the engine's own default, which is the only</p><p>output most engines have. Naming a format an engine cannot produce is</p><p>INVALID_ARGUMENT rather than a silent fallback, as is any explain request</p><p>against an engine that has no explain at all.</p>+ <p>The output format of a query plan.</p><table class="enum-table"><thead><tr><td>Name</td><td>Number</td><td>Description</td></tr>@@ -8804,7 +8852,9 @@ These are custom, flexible checks powered by AI models.</p></td><tr><td>EXPLAIN_FORMAT_UNSPECIFIED</td><td>0</td>- <td><p>The engine's default: PostgreSQL EXPLAIN, SQL Server SHOWPLAN_ALL.</p></td>+ <td><p>The engine's default: PostgreSQL EXPLAIN, SQL Server SHOWPLAN_ALL. On a+result, a default the server could not resolve, as when MySQL follows the+session's explain_format; read such a plan as text.</p></td></tr><tr>@@ -8827,6 +8877,12 @@ SHOWPLAN_ALL.</p></td>SHOWPLAN_XML.</p></td></tr>+ <tr>+ <td>YAML</td>+ <td>4</td>+ <td><p>The plan tree as YAML. PostgreSQL: EXPLAIN (FORMAT YAML).</p></td>+ </tr>+</tbody></table>diff --git a/proto/v1/v1/sql_service.proto b/proto/v1/v1/sql_service.protoindex 516433ef16..ec733e9ce3 100644--- a/proto/v1/v1/sql_service.proto+++ b/proto/v1/v1/sql_service.proto@@ -192,14 +192,11 @@ message QueryOption {reserved 2;reserved "mssql_explain_format";- // Which explain output the caller wants, for an explain request.- //- // Leave it unspecified for the engine's own default, which is the only- // output most engines have. Naming a format an engine cannot produce is- // INVALID_ARGUMENT rather than a silent fallback, as is any explain request- // against an engine that has no explain at all.+ // The output format of a query plan.enum ExplainFormat {- // The engine's default: PostgreSQL EXPLAIN, SQL Server SHOWPLAN_ALL.+ // The engine's default: PostgreSQL EXPLAIN, SQL Server SHOWPLAN_ALL. On a+ // result, a default the server could not resolve, as when MySQL follows the+ // session's explain_format; read such a plan as text.EXPLAIN_FORMAT_UNSPECIFIED = 0;// The human-readable plan. PostgreSQL: EXPLAIN (FORMAT TEXT). SQL Server:// SHOWPLAN_ALL.@@ -209,7 +206,15 @@ message QueryOption {// The plan tree as XML. PostgreSQL: EXPLAIN (FORMAT XML). SQL Server:// SHOWPLAN_XML.XML = 3;+ // The plan tree as YAML. PostgreSQL: EXPLAIN (FORMAT YAML).+ YAML = 4;}+ // Which explain output the caller wants, for an explain request.+ //+ // Leave it unspecified for the engine's own default, which is the only+ // output most engines have. Naming a format an engine cannot produce is+ // INVALID_ARGUMENT rather than a silent fallback, as is any explain request+ // against an engine that has no explain at all.ExplainFormat explain_format = 3;}@@ -312,6 +317,18 @@ 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.+ message QueryPlan {+ QueryOption.ExplainFormat format = 1;++ // Whether producing the plan executed the statement, as EXPLAIN ANALYZE+ // does.+ bool executed = 2;+ }++ // Set when the result is a query plan. Unset for any other result.+ QueryPlan query_plan = 14;}message MaskingReason {