Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
fix(sql)!: require bb.sql.explain for SQL Server's STATISTICS XML and PROFILE (#21648)
Danny Xu7d0ca27aa05a
diff --git a/backend/plugin/parser/base/interface.go b/backend/plugin/parser/base/interface.goindex 41c06e574d..e9b0fca63d 100644--- a/backend/plugin/parser/base/interface.go+++ b/backend/plugin/parser/base/interface.go@@ -3,7 +3,6 @@ package baseimport ("context""fmt"- "regexp""strings""sync"@@ -237,13 +236,12 @@ func GetQuerySpan(ctx context.Context, gCtx GetQuerySpanContext, engine storepb.}gCtx.Engine = enginegCtx.TempTables = make(map[string]*PhysicalTable)+ gCtx.PlanOutput = make(PlanOutput)var results []*QuerySpan- var nonEmptyStatements []Statementfor _, stmt := range statements {if stmt.Empty {continue}- nonEmptyStatements = append(nonEmptyStatements, stmt)result, err := f(ctx, gCtx, stmt, database, schema, ignoreCaseSensitive)if err != nil {// Try to unwrap the error to see if it's a ResourceNotFoundError to decrease the error noise.@@ -260,9 +258,6 @@ func GetQuerySpan(ctx context.Context, gCtx GetQuerySpanContext, engine storepb.}results = append(results, result)}- if engine == storepb.Engine_MSSQL {- tsqlRecognizeExplainType(results, nonEmptyStatements)- }return results, nil}@@ -431,48 +426,6 @@ func SplitSearchPath(statement string) (string, string) {return setup, rest}-// REFACTOR(zp): Put it here to avoid circular import for now.-var (- showplanReg = regexp.MustCompile(`(?mi)^\s*SET\s+SHOWPLAN_(ALL|XML|TEXT)\s+(?P<status>(ON|OFF))\s*;?$`)-)--// tsqlRecognizeExplainType walks the spans, and rewrite the select type to explain type if previous statement is SET SHOWPLAN_ALL.-func tsqlRecognizeExplainType(spans []*QuerySpan, stmts []Statement) {- if len(spans) != len(stmts) {- return- }- on := false- for i := range spans {- matches := showplanReg.FindStringSubmatch(stmts[i].Text)- if matches != nil {- for k, name := range showplanReg.SubexpNames() {- if k != 0 && name == "status" {- switch strings.ToLower(matches[k]) {- case "on":- on = true- case "off":- on = false- default:- // Unknown status, keep default value- }- }- }- }- if on {- if matches != nil {- spans[i].Type = Explain- } else if spans[i].Type == Select {- spans[i].Type = Explain- }- } else {- // SET SHOW_PLANALL OFF, this statement is explain either.- if matches != nil {- spans[i].Type = Explain- }- }- }-}-type StatementRangeContext struct{}type Range = lsp.Rangediff --git a/backend/plugin/parser/base/interface_test.go b/backend/plugin/parser/base/interface_test.goindex 660dd03382..dcb9b248c6 100644--- a/backend/plugin/parser/base/interface_test.go+++ b/backend/plugin/parser/base/interface_test.go@@ -18,64 +18,3 @@ func TestWithSearchPath(t *testing.T) {require.Empty(t, setup)require.Equal(t, "DELETE FROM t;", rest)}--func TestTSQLRecognizeExplainType(t *testing.T) {- testCases := []struct {- spans []*QuerySpan- stmts []Statement- wantSpans []*QuerySpan- }{- {- spans: []*QuerySpan{- {- Type: Select,- },- {- Type: Select,- },- {- Type: Select,- },- {- Type: Select,- },- {- Type: Select,- },- },- stmts: []Statement{- {Text: "SELECT 1"},- {Text: "SET SHOWPLAN_TEXT ON"},- {Text: "SELECT 2"},- {Text: "SET SHOWPLAN_TEXT OFF"},- {Text: "SELECT 3"},- },- wantSpans: []*QuerySpan{- {- Type: Select,- },- {- Type: Explain,- },- {- Type: Explain,- },- {- Type: Explain,- },- {- Type: Select,- },- },- },- }-- for _, tc := range testCases {- tsqlRecognizeExplainType(tc.spans, tc.stmts)- for i := range tc.spans {- if tc.spans[i].Type != tc.wantSpans[i].Type {- t.Errorf("tsqlRecognizeExplainType() = %v, want %v", tc.spans[i].Type, tc.wantSpans[i].Type)- }- }- }-}diff --git a/backend/plugin/parser/base/span.go b/backend/plugin/parser/base/span.goindex 995cc1dccd..9860631826 100644--- a/backend/plugin/parser/base/span.go+++ b/backend/plugin/parser/base/span.go@@ -376,6 +376,9 @@ type GetQuerySpanContext struct {// TempTables is the temporary tables created in the query span.// It's used to store the temporary tables declared in one batch for SQL Server.TempTables map[string]*PhysicalTable+ // PlanOutput is the plan output a SQL Server batch has turned on, carried to+ // its later statements like TempTables.+ PlanOutput PlanOutput// Adding the engine information here is a trade-off between the copy-pasted and shared code.// For engines with more different, we implement the getQuerySpan separately.@@ -386,6 +389,11 @@ type GetQuerySpanContext struct {Engine storepb.Engine}+// PlanOutput is the SQL Server plan options a batch has turned on, keyed by+// option name as the parser writes it, such as "SHOWPLAN_XML" or "STATISTICS+// XML". Each stays on until its own SET ... OFF.+type PlanOutput map[string]bool+// GetDatabaseMetadataFunc is the function to get database metadata.// It may return nil metadata and a nil error when Bytebase has not synced the// database's schema, as in the window after an instance is added; callers mustdiff --git a/backend/plugin/parser/tsql/query_span.go b/backend/plugin/parser/tsql/query_span.goindex 5854307f7d..f49e9de2cf 100644--- a/backend/plugin/parser/tsql/query_span.go+++ b/backend/plugin/parser/tsql/query_span.go@@ -2,6 +2,10 @@ package tsqlimport ("context"+ "slices"+ "strings"++ "github.com/bytebase/omni/mssql/ast"storepb "github.com/bytebase/bytebase/backend/generated-go/store""github.com/bytebase/bytebase/backend/plugin/parser/base"@@ -21,5 +25,55 @@ func GetQuerySpan(ignoreCaseSensitive bool,) (*base.QuerySpan, error) {q := newOmniQuerySpanExtractor(database, schema, gCtx, ignoreCaseSensitive)- return q.getOmniQuerySpan(ctx, stmt.Text)+ span, err := q.getOmniQuerySpan(ctx, stmt.Text)+ if err != nil {+ return nil, err+ }+ if gCtx.PlanOutput != nil {+ markPlanOutput(span, q.setOption, gCtx.PlanOutput)+ }+ return span, nil+}++var (+ // showplanOptions plan a statement instead of running it.+ showplanOptions = []string{"SHOWPLAN_ALL", "SHOWPLAN_TEXT", "SHOWPLAN_XML"}+ // statisticsOptions run a statement and return its plan as well.+ statisticsOptions = []string{"STATISTICS XML", "STATISTICS PROFILE"}+)++// markPlanOutput records what a SET statement turns on or off in output and+// marks the statements a plan comes back for, since reading a plan needs+// bb.sql.explain. While a SHOWPLAN option is on a read is an Explain; while a+// STATISTICS option is on a statement is marked like EXPLAIN ANALYZE. A SET+// that names one of these options is marked the same way, and any other SET+// follows the batch's options like every other statement.+func markPlanOutput(span *base.QuerySpan, set *ast.SetOptionStmt, output base.PlanOutput) {+ if set != nil {+ // Anything but OFF counts as on, so an unexpected form costs a check+ // rather than skipping one.+ on := true+ if value, ok := set.Value.(*ast.ColumnRef); ok && strings.EqualFold(value.Column, "OFF") {+ on = false+ }+ for _, option := range set.Options {+ name := strings.ToUpper(option)+ switch {+ case slices.Contains(showplanOptions, name):+ output[name] = on+ span.Type = base.Explain+ case slices.Contains(statisticsOptions, name):+ output[name] = on+ span.ExplainAnalyze = true+ default:+ }+ }+ }+ isOn := func(name string) bool { return output[name] }+ if slices.ContainsFunc(showplanOptions, isOn) && span.Type == base.Select {+ span.Type = base.Explain+ }+ if slices.ContainsFunc(statisticsOptions, isOn) {+ span.ExplainAnalyze = true+ }}diff --git a/backend/plugin/parser/tsql/query_span_extractor.go b/backend/plugin/parser/tsql/query_span_extractor.goindex b9758923d3..4a378588d5 100644--- a/backend/plugin/parser/tsql/query_span_extractor.go+++ b/backend/plugin/parser/tsql/query_span_extractor.go@@ -432,6 +432,8 @@ type omniQuerySpanExtractor struct {*querySpanExtractor// source is the original SQL text, used to slice expression names via Loc.source string+ // setOption is the statement when it is a SET of session options.+ setOption *ast.SetOptionStmt}func newOmniQuerySpanExtractor(defaultDatabase, defaultSchema string, gCtx base.GetQuerySpanContext, ignoreCaseSensitive bool) *omniQuerySpanExtractor {@@ -486,6 +488,9 @@ func (q *omniQuerySpanExtractor) getOmniQuerySpan(ctx context.Context, statementif d, ok := root.(*ast.DeclareStmt); ok {populateOmniTempTables(d, q.gCtx.TempTables)}+ if set, ok := root.(*ast.SetOptionStmt); ok {+ q.setOption = set+ }if c, ok := root.(*ast.CreateTableStmt); ok {populateOmniCreateTempTable(c, q.gCtx.TempTables)}diff --git a/backend/plugin/parser/tsql/query_span_test.go b/backend/plugin/parser/tsql/query_span_test.goindex 0836cd128d..3364d6a9bb 100644--- a/backend/plugin/parser/tsql/query_span_test.go+++ b/backend/plugin/parser/tsql/query_span_test.go@@ -173,3 +173,53 @@ func TestGetQuerySpanCyclicViewReference(t *testing.T) {require.Error(t, err)require.ErrorContains(t, err, "cyclic view reference")}++// TestGetQuerySpanMarksPlanOutput pins which statements of a batch return a+// plan: a SET that names SHOWPLAN_* or STATISTICS XML or PROFILE, and every+// statement while one is on, comments and option lists included. Each option+// stays on until its own OFF.+func TestGetQuerySpanMarksPlanOutput(t *testing.T) {+ getter, lister := buildMockDatabaseMetadataGetter([]*metadatapb.DatabaseSchemaMetadata{{Name: "db"}})+ type want struct {+ statement string+ queryType base.QueryType+ explainAnalyze bool+ }+ cases := []want{+ {"SELECT 1", base.Select, false},+ {"SET /* x */ STATISTICS XML ON -- y", base.Select, true},+ {"SELECT 2", base.Select, true},+ {"SET NOCOUNT ON", base.Select, true},+ {"DELETE FROM t", base.DML, true},+ {"SET STATISTICS PROFILE OFF", base.Select, true},+ {"SELECT 8", base.Select, true},+ {"SET STATISTICS XML OFF", base.Select, true},+ {"SELECT 3", base.Select, false},+ {"SET STATISTICS IO ON", base.Select, false},+ {"SELECT 4", base.Select, false},+ {"set statistics io, profile on", base.Select, true},+ {"SELECT 5", base.Select, true},+ {"SET STATISTICS PROFILE OFF", base.Select, true},+ {"SET SHOWPLAN_TEXT ON -- z", base.Explain, false},+ {"SET NOCOUNT OFF", base.Explain, false},+ {"SET SHOWPLAN_ALL OFF", base.Explain, false},+ {"SELECT 6", base.Explain, false},+ {"SET SHOWPLAN_TEXT OFF", base.Explain, false},+ {"SELECT 7", base.Select, false},+ }+ var statements []base.Statement+ for _, c := range cases {+ statements = append(statements, base.Statement{Text: c.statement})+ }++ spans, err := base.GetQuerySpan(context.Background(), base.GetQuerySpanContext{+ GetDatabaseMetadataFunc: getter,+ ListDatabaseNamesFunc: lister,+ }, storepb.Engine_MSSQL, statements, "db", "dbo", true)+ require.NoError(t, err)+ require.Len(t, spans, len(cases))+ for i, c := range cases {+ require.Equal(t, c.queryType, spans[i].Type, c.statement)+ require.Equal(t, c.explainAnalyze, spans[i].ExplainAnalyze, c.statement)+ }+}diff --git a/docs/design/query-plan-visualizer.md b/docs/design/query-plan-visualizer.mdindex 6d303442af..8be5087cce 100644--- a/docs/design/query-plan-visualizer.md+++ b/docs/design/query-plan-visualizer.md@@ -402,16 +402,19 @@ it. For them the Plan option is **disabled with the reason shown**, not hidden:hiding it leaves them unable to tell the capability exists or what to ask anadmin for.-**Anything that both executes and returns a plan needs both permissions**, and-today neither route does. A typed `EXPLAIN ANALYZE` is classified as its *inner*-statement (`pg/query_type.go:47`), so it passes on `bb.sql.select` alone and-still returns a plan. The **Explain analyze** action comes the other way: an-explain request has no query spans, so the check falls to-`bb.sql.explain` alone (`sql_service.go:1450-1458`) — safe today only because-`validateExplainStatements` refuses anything that is not read-only, which is-exactly the refusal this action has to relax. Both routes must require the-underlying statement's normal ACL, write-target checks included, **and**-`bb.sql.explain`.+**Anything that both executes and returns a plan needs both permissions.** A+typed `EXPLAIN ANALYZE` was classified as its *inner* statement, so it passed on+`bb.sql.select` alone and still returned a plan; SQL Server's `SET STATISTICS+XML ON` and `SET STATISTICS PROFILE ON` did the same for every statement after+them. Both now mark the span as an executed plan, so the statement needs its+normal ACL, write-target checks included, **and** `bb.sql.explain`+([#21642](https://github.com/bytebase/bytebase/pull/21642),+[#21648](https://github.com/bytebase/bytebase/pull/21648)). SQL Server's settings are read from the parsed `SET` statement,+not matched as text, so a comment or an option list does not hide them. The+**Explain analyze** action comes the other way: an explain request is checked+on `bb.sql.explain` and is safe today only because `validateExplainStatements`+refuses anything that is not read-only, which is exactly the refusal this+action has to relax; when it lands it must add the statement's own ACL.**Plans are never masked, and that is a privilege, not a safe default.** Explainskips masking (`sql_service.go:726`, `:735`). A plan is not row data, but it is@@ -518,7 +521,7 @@ live servers, September 2026.## 6. Status-Checked against `main` on 2026-10-22.+Checked against `main` on 2026-10-23.**Landed**@@ -540,9 +543,11 @@ Checked against `main` on 2026-10-22.([#21642](https://github.com/bytebase/bytebase/pull/21642)); the Plan optionis disabled with the reason, a load can be cancelled, and a plan past thenode cap is shown as text- ([#21646](https://github.com/bytebase/bytebase/pull/21646)). What remains- of §3.5: SQL Server's `SET STATISTICS XML ON` route still passes on- `bb.sql.select` alone.+ ([#21646](https://github.com/bytebase/bytebase/pull/21646)); SQL Server's+ `SET STATISTICS XML` and `PROFILE` need `bb.sql.explain` as well as the+ statement's own permission, and its SHOWPLAN settings are read from the+ parsed statement ([#21648](https://github.com/bytebase/bytebase/pull/21648)).+ §3.5 is closed.- §3.2/§3.3 — Plan in the result pane's view switch on an ordinary result,planning the executed statement, with the estimate wording from §3.4, thechoice remembered per editor tab