Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

fix(sql)!: require bb.sql.explain on every database a plan describes (#21642)

Danny Xu4d22c80f8765
diff --git a/backend/api/v1/sql_service.go b/backend/api/v1/sql_service.go
index 5acbcf4179..34e69fdace 100644
--- a/backend/api/v1/sql_service.go
+++ b/backend/api/v1/sql_service.go
@@ -833,38 +833,34 @@ func queryRetry(
schemaSyncer *schemasync.Syncer,
multiStatement bool,
) ([]*v1pb.QueryResult, []*parserbase.QuerySpan, time.Duration, error) {
- var spans []*parserbase.QuerySpan
var sensitivePredicateColumns [][]parserbase.ColumnResource
- var err error
- if !queryContext.Explain {
- spans, err = parserbase.GetQuerySpan(
- ctx,
- parserbase.GetQuerySpanContext{
- InstanceID: instance.ResourceID,
- GetDatabaseMetadataFunc: parsercontext.BuildGetDatabaseMetadataFunc(stores),
- ListDatabaseNamesFunc: parsercontext.BuildListDatabaseNamesFunc(stores),
- GetLinkedDatabaseMetadataFunc: parsercontext.BuildGetLinkedDatabaseMetadataFunc(stores, instance.Metadata.GetEngine()),
- },
- instance.Metadata.GetEngine(),
- statements,
- database.DatabaseName,
- queryContext.Schema,
- !store.IsObjectCaseSensitive(instance),
- )
- if err != nil {
- return nil, nil, time.Duration(0), err
- }
- // After replacing backup table with source, we can apply the original access check and mask sensitive data for backup table.
- // If err != nil, this function will return the original spans.
- if err := replaceBackupTableWithSource(ctx, stores, instance, database, spans); err != nil {
- slog.Debug("failed to replace backup table with source", log.BBError(err))
- }
+ // An explain request carries the bare statements the driver will wrap, so
+ // their spans name the databases the plan describes.
+ spans, err := parserbase.GetQuerySpan(
+ ctx,
+ parserbase.GetQuerySpanContext{
+ InstanceID: instance.ResourceID,
+ GetDatabaseMetadataFunc: parsercontext.BuildGetDatabaseMetadataFunc(stores),
+ ListDatabaseNamesFunc: parsercontext.BuildListDatabaseNamesFunc(stores),
+ GetLinkedDatabaseMetadataFunc: parsercontext.BuildGetLinkedDatabaseMetadataFunc(stores, instance.Metadata.GetEngine()),
+ },
+ instance.Metadata.GetEngine(),
+ statements,
+ database.DatabaseName,
+ queryContext.Schema,
+ !store.IsObjectCaseSensitive(instance),
+ )
+ if err != nil {
+ return nil, nil, time.Duration(0), err
+ }
+ // After replacing backup table with source, we can apply the original access check and mask sensitive data for backup table.
+ // If err != nil, this function will return the original spans.
+ if err := replaceBackupTableWithSource(ctx, stores, instance, database, spans); err != nil {
+ slog.Debug("failed to replace backup table with source", log.BBError(err))
}
if optionalAccessCheck != nil {
- // An EXPLAIN request leaves spans nil (GetQuerySpan runs only above), so
- // accessCheckWithGrantedTargets takes its database-level branch and requires
- // bb.sql.explain. A smuggled write (EXPLAIN ANALYZE of a write) is refused
- // earlier, in the Query handler, before it reaches execution.
+ // A smuggled write (EXPLAIN ANALYZE of a write) is refused earlier, in
+ // the Query handler, before it reaches execution.
if err := optionalAccessCheck(ctx, instance, database, user, spans, queryContext.Explain, statements, queryContext.Schema, multiStatement); err != nil {
return nil, nil, time.Duration(0), err
}
@@ -1615,9 +1611,8 @@ func (s *SQLService) accessCheckWithGrantedTargets(
return nil
}
- // No spans: either a read with no source columns (e.g. SELECT 1) or an EXPLAIN
- // request (GetQuerySpan runs only for non-EXPLAIN). Check at the database
- // level, with EXPLAIN permission for the latter.
+ // No spans: an engine without a span extractor. Check at the database level,
+ // with the explain permission for an explain request.
if len(spans) == 0 {
perm := permission.SQLSelect
if isExplain {
@@ -1662,6 +1657,19 @@ func (s *SQLService) accessCheckWithGrantedTargets(
perm = permission.SQLSelect
}
+ // A plan names the tables it reads, so reading one needs bb.sql.explain on
+ // every database the statement references, not only the connected one.
+ // A plain EXPLAIN, typed or requested, executes nothing and is done here;
+ // EXPLAIN ANALYZE executes its statement and is checked for that below.
+ if isExplain || perm == permission.SQLExplain || (span.ExplainAnalyze && common.EngineSupportQueryNewACL(instance.Metadata.GetEngine())) {
+ if err := s.checkExplainAccess(ctx, user, instance, database, span, workspacePolicy.Policy, projectPolicy.Policy); err != nil {
+ return err
+ }
+ if !span.ExplainAnalyze {
+ continue
+ }
+ }
+
// DML/DDL: authorize per write-target so table/schema-scoped grants work. Resolve the
// write targets of the statement aligned with this span (spans skip Empty statements, so
// nonEmptyStatements is indexed in lockstep).
@@ -1795,9 +1803,86 @@ func (s *SQLService) accessCheckWithGrantedTargets(
return nil
}
+// checkExplainAccess requires bb.sql.explain on every database a plan of the
+// span's statement would describe: the connected database and each tracked
+// database the statement's tables live in, authorized like a write's targets.
+// Access grants do not apply; they convey data access, not plan access. What
+// the span cannot place in a tracked database — a procedure call that names no
+// table, a system schema such as Oracle's SYS — is left to the connected
+// database's check.
+func (s *SQLService) checkExplainAccess(
+ ctx context.Context,
+ user *store.UserMessage,
+ instance *store.InstanceMessage,
+ database *store.DatabaseMessage,
+ span *parserbase.QuerySpan,
+ workspacePolicy *storepb.IamPolicy,
+ projectPolicy *storepb.IamPolicy,
+) error {
+ targets := []writeTargetResource{{database: database.DatabaseName}}
+ var referenced []string
+ for column := range span.SourceColumns {
+ if column.Database != "" && column.Database != database.DatabaseName {
+ referenced = append(referenced, column.Database)
+ }
+ }
+ slices.Sort(referenced)
+ for _, name := range slices.Compact(referenced) {
+ tracked, err := s.findDatabaseAsTyped(ctx, instance, name)
+ if err != nil {
+ return err
+ }
+ if tracked != nil {
+ targets = append(targets, writeTargetResource{database: tracked.DatabaseName})
+ }
+ }
+ deniedResources, err := s.authorizeWriteTargets(ctx, user, instance, database, permission.SQLExplain, targets, nil, true, workspacePolicy, projectPolicy)
+ if err != nil {
+ return err
+ }
+ if len(deniedResources) > 0 {
+ setPermissionDenied(ctx)
+ return &queryError{
+ err: connect.NewError(
+ connect.CodePermissionDenied,
+ errors.Errorf("permission denied to access resources: %v", deniedResources),
+ ),
+ resources: deniedResources,
+ permission: permission.SQLExplain,
+ }
+ }
+ return nil
+}
+
+// findDatabaseAsTyped resolves a database name as a statement spells it. An
+// engine that folds case accepts DB_B for db_b, so there the name is matched
+// case-insensitively against the instance's databases. nil means Bytebase does
+// not track the name.
+func (s *SQLService) findDatabaseAsTyped(ctx context.Context, instance *store.InstanceMessage, name string) (*store.DatabaseMessage, error) {
+ workspace := common.GetWorkspaceIDFromContext(ctx)
+ database, err := s.store.GetDatabase(ctx, &store.FindDatabaseMessage{Workspace: workspace, InstanceID: &instance.ResourceID, DatabaseName: &name})
+ if err != nil {
+ return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to resolve database %q: %v", name, err))
+ }
+ if database != nil || store.IsObjectCaseSensitive(instance) {
+ return database, nil
+ }
+ databases, err := s.store.ListDatabases(ctx, &store.FindDatabaseMessage{Workspace: workspace, InstanceID: &instance.ResourceID})
+ if err != nil {
+ return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to list databases of %q: %v", instance.ResourceID, err))
+ }
+ for _, candidate := range databases {
+ if strings.EqualFold(candidate.DatabaseName, name) {
+ return candidate, nil
+ }
+ }
+ return nil, nil
+}
+
// authorizeWriteTargets evaluates perm for each resolved DML/DDL write target and returns the
// resources that were denied (empty = all authorized). A target whose database is already
-// JIT-granted is skipped.
+// JIT-granted is skipped. checkExplainAccess reuses it, at the database level, for the
+// databases a plan describes.
//
// databaseLevelOnly selects the precision of the check. For a single statement it is false and
// each target is authorized at full per-(schema,table) precision. For a multi-statement batch it
diff --git a/backend/api/v1/sql_service_test.go b/backend/api/v1/sql_service_test.go
index 2d8ca9a129..66fa49c32d 100644
--- a/backend/api/v1/sql_service_test.go
+++ b/backend/api/v1/sql_service_test.go
@@ -9,6 +9,9 @@ import (
"github.com/stretchr/testify/require"
"github.com/bytebase/bytebase/backend/common"
+ "github.com/bytebase/bytebase/backend/common/permission"
+ "github.com/bytebase/bytebase/backend/common/testcontainer"
+ "github.com/bytebase/bytebase/backend/component/iam"
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"
parserbase "github.com/bytebase/bytebase/backend/plugin/parser/base"
@@ -487,3 +490,155 @@ func TestExplainGateAllowsPlans(t *testing.T) {
require.Errorf(t, validateExplainStatements(instance, "ANALYZE DELETE FROM t; SELECT 1", v1pb.QueryOption_EXPLAIN_FORMAT_UNSPECIFIED), "%s: smuggle before a read", engine)
}
}
+
+// explainAccessFixture is one instance holding a database of project A and a
+// database of project B, with users whose explain and select rights differ
+// between the two projects.
+type explainAccessFixture struct {
+ service *SQLService
+ instance *store.InstanceMessage
+ database *store.DatabaseMessage
+}
+
+func newExplainAccessFixture(ctx context.Context, t *testing.T, engine storepb.Engine) *explainAccessFixture {
+ t.Helper()
+ db, stores, _ := testcontainer.NewMetadataDB(t)
+ _, err := db.ExecContext(ctx, `
+ INSERT INTO workspace (resource_id) VALUES ('default');
+ INSERT INTO principal (name, email, password_hash) VALUES
+ ('explain-a', '[email protected]', 'unused'),
+ ('explain-ab', '[email protected]', 'unused'),
+ ('select-a', '[email protected]', 'unused'),
+ ('both-a', '[email protected]', 'unused');
+ INSERT INTO project (resource_id, workspace, name) VALUES ('project-a', 'default', 'A'), ('project-b', 'default', 'B');`)
+ require.NoError(t, err)
+ for _, role := range []struct {
+ id string
+ perm permission.Permission
+ }{
+ {id: "explainer", perm: permission.SQLExplain},
+ {id: "selector", perm: permission.SQLSelect},
+ } {
+ _, err = stores.CreateRole(ctx, &store.RoleMessage{
+ ResourceID: role.id, Workspace: "default", Name: role.id,
+ Permissions: map[permission.Permission]bool{role.perm: true},
+ })
+ require.NoError(t, err)
+ }
+ for _, binding := range []struct {
+ project string
+ role string
+ members []string
+ }{
+ {project: "project-a", role: "explainer", members: []string{"[email protected]", "[email protected]", "[email protected]"}},
+ {project: "project-a", role: "selector", members: []string{"[email protected]", "[email protected]"}},
+ {project: "project-b", role: "explainer", members: []string{"[email protected]"}},
+ } {
+ members := make([]string, 0, len(binding.members))
+ for _, member := range binding.members {
+ members = append(members, common.FormatUserEmail(member))
+ }
+ _, err = stores.PatchIamPolicy(ctx, "default", storepb.Policy_PROJECT, common.FormatProject(binding.project), func(policy *storepb.IamPolicy) error {
+ policy.Bindings = append(policy.Bindings, &storepb.Binding{Role: "roles/" + binding.role, Members: members})
+ return nil
+ })
+ require.NoError(t, err)
+ }
+ instance, err := stores.CreateInstance(ctx, &store.InstanceMessage{
+ ResourceID: "test", Workspace: "default",
+ // lower_case_table_names=1 makes the instance fold case, so DB_B names db_b.
+ Metadata: &storepb.Instance{Engine: engine, Activation: true, MysqlLowerCaseTableNames: 1, DataSources: []*storepb.DataSource{{Id: "admin", Type: storepb.DataSourceType_ADMIN}}},
+ })
+ require.NoError(t, err)
+ var connected *store.DatabaseMessage
+ for name, project := range map[string]string{"db_a": "project-a", "db_b": "project-b"} {
+ database, err := stores.UpsertDatabase(ctx, &store.DatabaseMessage{
+ InstanceID: "test", DatabaseName: name, ProjectID: project, Metadata: &storepb.DatabaseMetadata{},
+ })
+ require.NoError(t, err)
+ if name == "db_a" {
+ connected = database
+ }
+ }
+ iamManager, err := iam.NewManager(stores, nil, false)
+ require.NoError(t, err)
+ return &explainAccessFixture{
+ service: &SQLService{store: stores, iamManager: iamManager},
+ instance: instance,
+ database: connected,
+ }
+}
+
+func (f *explainAccessFixture) check(ctx context.Context, email string, isExplain bool, statement string, span *parserbase.QuerySpan) error {
+ user := &store.UserMessage{Email: email}
+ return f.service.accessCheckWithGrantedTargets(ctx, f.instance, f.database, user, []*parserbase.QuerySpan{span}, isExplain, []parserbase.Statement{{Text: statement}}, nil, "", false)
+}
+
+func reads(databases ...string) parserbase.SourceColumnSet {
+ columns := parserbase.SourceColumnSet{}
+ for _, database := range databases {
+ columns[parserbase.ColumnResource{Database: database, Table: "t"}] = true
+ }
+ return columns
+}
+
+func requireExplainDenied(t *testing.T, err error, perm permission.Permission, resources ...string) {
+ t.Helper()
+ var denied *queryError
+ require.ErrorAs(t, err, &denied)
+ require.Equal(t, connect.CodePermissionDenied, connect.CodeOf(denied.err))
+ require.Equal(t, perm, denied.permission)
+ require.Equal(t, resources, denied.resources)
+}
+
+// TestExplainRequiresEachReferencedDatabase pins the plan boundary: a plan
+// describes every database its statement references, a database in another
+// project fails closed as it does for a write, and a typed EXPLAIN ANALYZE
+// needs the statement's permission as well as explain.
+func TestExplainRequiresEachReferencedDatabase(t *testing.T) {
+ t.Parallel()
+ ctx := context.WithValue(context.Background(), common.WorkspaceIDContextKey, "default")
+ f := newExplainAccessFixture(ctx, t, storepb.Engine_MYSQL)
+ const dbB = "instances/test/databases/db_b"
+
+ t.Run("explain request", func(t *testing.T) {
+ t.Parallel()
+ crossRead := &parserbase.QuerySpan{Type: parserbase.Select, SourceColumns: reads("db_a", "db_b")}
+ require.NoError(t, f.check(ctx, "[email protected]", true, "SELECT 1", &parserbase.QuerySpan{Type: parserbase.Select, SourceColumns: reads("db_a")}))
+ requireExplainDenied(t, f.check(ctx, "[email protected]", true, "SELECT 1", crossRead), permission.SQLExplain, dbB)
+ requireExplainDenied(t, f.check(ctx, "[email protected]", true, "SELECT 1", crossRead), permission.SQLExplain, dbB)
+ requireExplainDenied(t, f.check(ctx, "[email protected]", true, "SELECT 1", crossRead), permission.SQLExplain, "instances/test/databases/db_a", dbB)
+ require.NoError(t, f.check(ctx, "[email protected]", true, "SELECT 1", &parserbase.QuerySpan{Type: parserbase.Select, SourceColumns: reads("db_a", "SYS")}), "an untracked database is left to the connected database's check")
+ })
+
+ t.Run("typed EXPLAIN", func(t *testing.T) {
+ t.Parallel()
+ crossRead := &parserbase.QuerySpan{Type: parserbase.Explain, SourceColumns: reads("db_a", "db_b")}
+ requireExplainDenied(t, f.check(ctx, "[email protected]", false, "EXPLAIN SELECT 1", crossRead), permission.SQLExplain, dbB)
+ requireExplainDenied(t, f.check(ctx, "[email protected]", false, "EXPLAIN SELECT 1", &parserbase.QuerySpan{Type: parserbase.Explain, SourceColumns: reads("DB_B")}), permission.SQLExplain, dbB)
+ require.NoError(t, f.check(ctx, "[email protected]", false, "EXPLAIN SELECT 1", &parserbase.QuerySpan{Type: parserbase.Explain, SourceColumns: reads("db_a")}))
+ })
+
+ t.Run("typed EXPLAIN ANALYZE", func(t *testing.T) {
+ t.Parallel()
+ analyze := &parserbase.QuerySpan{Type: parserbase.Select, ExplainAnalyze: true, SourceColumns: reads("db_a")}
+ requireExplainDenied(t, f.check(ctx, "[email protected]", false, "EXPLAIN ANALYZE SELECT 1", analyze), permission.SQLSelect, "instances/test/databases/db_a/tables/t")
+ requireExplainDenied(t, f.check(ctx, "[email protected]", false, "EXPLAIN ANALYZE SELECT 1", analyze), permission.SQLExplain, "instances/test/databases/db_a")
+ require.NoError(t, f.check(ctx, "[email protected]", false, "EXPLAIN ANALYZE SELECT 1", analyze))
+ })
+}
+
+// TestExplainOfAWriteNamesItsTables pins explain over DML: the databases its
+// tables live in are checked like a read's, and a write that names no table,
+// such as a procedure call, is checked on the connected database alone.
+func TestExplainOfAWriteNamesItsTables(t *testing.T) {
+ t.Parallel()
+ ctx := context.WithValue(context.Background(), common.WorkspaceIDContextKey, "default")
+ f := newExplainAccessFixture(ctx, t, storepb.Engine_MYSQL)
+ require.NoError(t, f.check(ctx, "[email protected]", true, "DELETE FROM t", &parserbase.QuerySpan{Type: parserbase.DML, SourceColumns: reads("db_a")}))
+ crossRead := &parserbase.QuerySpan{Type: parserbase.DML, SourceColumns: reads("db_a", "db_b")}
+ requireExplainDenied(t, f.check(ctx, "[email protected]", true, "INSERT INTO t SELECT * FROM db_b.t", crossRead), permission.SQLExplain, "instances/test/databases/db_b")
+ call := &parserbase.QuerySpan{Type: parserbase.DML, SourceColumns: parserbase.SourceColumnSet{}}
+ require.NoError(t, f.check(ctx, "[email protected]", true, "CALL p()", call))
+ requireExplainDenied(t, f.check(ctx, "[email protected]", true, "CALL p()", call), permission.SQLExplain, "instances/test/databases/db_a")
+}
diff --git a/backend/plugin/parser/base/span.go b/backend/plugin/parser/base/span.go
index 2d4e052dea..995cc1dccd 100644
--- a/backend/plugin/parser/base/span.go
+++ b/backend/plugin/parser/base/span.go
@@ -55,11 +55,16 @@ func MergeSourceColumnSet(m, n SourceColumnSet) (SourceColumnSet, bool) {
// QuerySpan is the span for a query.
type QuerySpan struct {
Type QueryType
+ // ExplainAnalyze marks a typed EXPLAIN ANALYZE: Type is the executed
+ // statement's, and the result is its plan, so the caller must hold the
+ // explain permission as well as Type's.
+ ExplainAnalyze bool
// Results are the result columns of a query span.
// Currently, SourceColumns in the QuerySpanResult are only for the fields in the Query.
Results []QuerySpanResult
// SourceColumns are the source columns contributing to the span.
// SourceColumns here are the source columns for the whole query span, containing fields, where conditions, join conditions, etc.
+ // A statement that is not a SELECT carries the tables it touches here, at the table level.
SourceColumns SourceColumnSet
// PredicateColumns are the source columns contributing to the span.
// PredicateColumns here are the source columns for the where conditions.
diff --git a/backend/plugin/parser/googlesql/query_span_extractor.go b/backend/plugin/parser/googlesql/query_span_extractor.go
index 10d1146ccd..0576647103 100644
--- a/backend/plugin/parser/googlesql/query_span_extractor.go
+++ b/backend/plugin/parser/googlesql/query_span_extractor.go
@@ -121,13 +121,12 @@ func (q *QuerySpanExtractor) GetQuerySpan(ctx context.Context, statement string)
accessTables := q.toTableResources(omniSpan)
// Only a read-only query produces per-column results; DML/DDL/Explain/
- // Unknown return no per-column lineage — exactly the legacy behaviour
- // (it returned an empty span for any non-Select). SelectInfoSchema is a
- // read so it is treated like Select here.
+ // Unknown keep the accessed tables and no per-column lineage.
+ // SelectInfoSchema is a read so it is treated like Select here.
if queryType != base.Select && queryType != base.SelectInfoSchema {
return &base.QuerySpan{
Type: queryType,
- SourceColumns: base.SourceColumnSet{},
+ SourceColumns: accessTables,
Results: []base.QuerySpanResult{},
}, nil
}
diff --git a/backend/plugin/parser/mysql/query_span_extractor.go b/backend/plugin/parser/mysql/query_span_extractor.go
index 12ed9c4bfe..ea7902703b 100644
--- a/backend/plugin/parser/mysql/query_span_extractor.go
+++ b/backend/plugin/parser/mysql/query_span_extractor.go
@@ -430,10 +430,8 @@ func (q *omniQuerySpanExtractor) getOmniQuerySpan(ctx context.Context, statement
if allSystems {
accessTables = base.SourceColumnSet{}
}
- resultSourceColumns := accessTables
- if queryType != base.Select {
- resultSourceColumns = base.SourceColumnSet{}
- }
+ explain, isExplain := root.(*ast.ExplainStmt)
+ explainAnalyze := isExplain && explain.Analyze
var results []base.QuerySpanResult
if queryType == base.Select {
@@ -455,7 +453,8 @@ func (q *omniQuerySpanExtractor) getOmniQuerySpan(ctx context.Context, statement
}
return &base.QuerySpan{
Type: queryType,
- SourceColumns: resultSourceColumns,
+ ExplainAnalyze: explainAnalyze,
+ SourceColumns: accessTables,
Results: results,
PredicateColumns: base.SourceColumnSet{},
}, nil
diff --git a/backend/plugin/parser/mysql/query_span_extractor_test.go b/backend/plugin/parser/mysql/query_span_extractor_test.go
index 3f8c35dc16..42267a4209 100644
--- a/backend/plugin/parser/mysql/query_span_extractor_test.go
+++ b/backend/plugin/parser/mysql/query_span_extractor_test.go
@@ -37,9 +37,12 @@ func TestOmniQuerySpanScaffold_QueryTypesAndAccessTables(t *testing.T) {
wantType: base.SelectInfoSchema,
},
{
- name: "plain_explain_is_explain",
+ name: "plain_explain_keeps_the_tables_it_plans",
statement: "EXPLAIN SELECT * FROM t",
wantType: base.Explain,
+ wantResources: []base.ColumnResource{
+ {Database: "db", Table: "t"},
+ },
},
{
name: "describe_is_info_schema",
@@ -57,14 +60,16 @@ func TestOmniQuerySpanScaffold_QueryTypesAndAccessTables(t *testing.T) {
wantType: base.SelectInfoSchema,
},
{
- name: "ddl",
- statement: "CREATE TABLE t(a INT)",
- wantType: base.DDL,
+ name: "ddl",
+ statement: "CREATE TABLE t(a INT)",
+ wantType: base.DDL,
+ wantResources: []base.ColumnResource{{Database: "db", Table: "t"}},
},
{
- name: "dml",
- statement: "INSERT INTO t VALUES(1)",
- wantType: base.DML,
+ name: "dml",
+ statement: "INSERT INTO t VALUES(1)",
+ wantType: base.DML,
+ wantResources: []base.ColumnResource{{Database: "db", Table: "t"}},
},
{
name: "system_select",
@@ -565,9 +570,10 @@ func TestOmniQuerySpanScenarioBatch1_RootAndQueryTypeCoverage(t *testing.T) {
wantType: base.Select,
},
{
- name: "explain_analyze_insert",
- statement: "EXPLAIN ANALYZE INSERT INTO t VALUES(1, 2, 3)",
- wantType: base.DML,
+ name: "explain_analyze_insert",
+ statement: "EXPLAIN ANALYZE INSERT INTO t VALUES(1, 2, 3)",
+ wantType: base.DML,
+ wantResources: []base.ColumnResource{{Database: "db", Table: "t"}},
},
}
for _, tc := range tests {
diff --git a/backend/plugin/parser/mysql/test-data/query-span/query_type.yaml b/backend/plugin/parser/mysql/test-data/query-span/query_type.yaml
index cd677a5a00..654350d666 100644
--- a/backend/plugin/parser/mysql/test-data/query-span/query_type.yaml
+++ b/backend/plugin/parser/mysql/test-data/query-span/query_type.yaml
@@ -61,7 +61,12 @@
querySpan:
type: 2
results: []
- sourcecolumns: []
+ sourcecolumns:
+ - server: ""
+ database: db
+ schema: ""
+ table: t
+ column: ""
predicatecolumns: []
- description: standard query
statement: select * from t where a > 0
@@ -90,7 +95,12 @@
querySpan:
type: 4
results: []
- sourcecolumns: []
+ sourcecolumns:
+ - server: ""
+ database: db
+ schema: ""
+ table: t
+ column: ""
predicatecolumns: []
- description: dml
statement: insert into t values(1);
@@ -102,5 +112,10 @@
querySpan:
type: 5
results: []
- sourcecolumns: []
+ sourcecolumns:
+ - server: ""
+ database: db
+ schema: ""
+ table: t
+ column: ""
predicatecolumns: []
diff --git a/backend/plugin/parser/pg/query_span.go b/backend/plugin/parser/pg/query_span.go
index 0bf1f2e12b..fae50bcbed 100644
--- a/backend/plugin/parser/pg/query_span.go
+++ b/backend/plugin/parser/pg/query_span.go
@@ -284,21 +284,14 @@ func (e *omniQuerySpanExtractor) getQuerySpan(ctx context.Context, stmt string)
// Step 4: Classify query type.
queryType, isExplainAnalyze := classifyQueryType(omniStmts[0].AST, allSystems)
- // Step 5: Return early for non-SELECT queries.
- if queryType != base.Select {
+ // Step 5: Return early for non-SELECT queries, keeping the tables the
+ // statement touches and no result columns.
+ if queryType != base.Select || isExplainAnalyze {
return &base.QuerySpan{
- Type: queryType,
- SourceColumns: base.SourceColumnSet{},
- Results: []base.QuerySpanResult{},
- }, nil
- }
-
- // For EXPLAIN ANALYZE SELECT, return with source columns but no results.
- if isExplainAnalyze {
- return &base.QuerySpan{
- Type: queryType,
- SourceColumns: accessesMap,
- Results: []base.QuerySpanResult{},
+ Type: queryType,
+ ExplainAnalyze: isExplainAnalyze,
+ SourceColumns: accessesMap,
+ Results: []base.QuerySpanResult{},
}, nil
}
diff --git a/backend/plugin/parser/pg/test-data/query_span.yaml b/backend/plugin/parser/pg/test-data/query_span.yaml
index ef3466e3c3..dcec60021e 100644
--- a/backend/plugin/parser/pg/test-data/query_span.yaml
+++ b/backend/plugin/parser/pg/test-data/query_span.yaml
@@ -2915,7 +2915,12 @@
querySpan:
type: 3
results: []
- sourcecolumns: []
+ sourcecolumns:
+ - server: ""
+ database: db
+ schema: information_schema
+ table: tables
+ column: ""
predicatecolumns: []
- description: Test table.* with JOIN on different tables for masking
statement: SELECT users.*, payments.* FROM users JOIN payments ON users.id = payments.user_id;
diff --git a/backend/plugin/parser/pg/test-data/query_type.yaml b/backend/plugin/parser/pg/test-data/query_type.yaml
index 4b3639a899..44ec2f7d8a 100644
--- a/backend/plugin/parser/pg/test-data/query_type.yaml
+++ b/backend/plugin/parser/pg/test-data/query_type.yaml
@@ -129,7 +129,7 @@
sourcecolumns: []
predicatecolumns: []
- description: Explain
- statement: EXPLAIN SELECT * FROM t;
+ statement: EXPLAIN SELECT * FROM t1;
defaultDatabase: db
metadata: |-
{
@@ -185,7 +185,12 @@
querySpan:
type: 2
results: []
- sourcecolumns: []
+ sourcecolumns:
+ - server: ""
+ database: db
+ schema: public
+ table: t1
+ column: ""
predicatecolumns: []
- description: Explain Analyze
statement: EXPLAIN ANALYZE SELECT * FROM t1;
@@ -275,7 +280,12 @@
querySpan:
type: 5
results: []
- sourcecolumns: []
+ sourcecolumns:
+ - server: ""
+ database: db
+ schema: public
+ table: t
+ column: ""
predicatecolumns: []
- description: DELETE statement
statement: DELETE FROM t WHERE id > 100;
@@ -300,7 +310,12 @@
querySpan:
type: 5
results: []
- sourcecolumns: []
+ sourcecolumns:
+ - server: ""
+ database: db
+ schema: public
+ table: t
+ column: ""
predicatecolumns: []
- description: MERGE statement
statement: MERGE INTO target USING source ON target.id = source.id WHEN MATCHED THEN UPDATE SET target.value = source.value;
@@ -625,7 +640,12 @@
querySpan:
type: 5
results: []
- sourcecolumns: []
+ sourcecolumns:
+ - server: ""
+ database: db
+ schema: public
+ table: t1
+ column: ""
predicatecolumns: []
- description: EXPLAIN ANALYZE executes MERGE
statement: EXPLAIN ANALYZE MERGE INTO t1 USING t2 ON t1.a = t2.a WHEN NOT MATCHED THEN INSERT (a) VALUES (t2.a);
@@ -662,7 +682,17 @@
querySpan:
type: 5
results: []
- sourcecolumns: []
+ sourcecolumns:
+ - server: ""
+ database: db
+ schema: public
+ table: t1
+ column: ""
+ - server: ""
+ database: db
+ schema: public
+ table: t2
+ column: ""
predicatecolumns: []
- description: EXPLAIN ANALYZE executes a data-modifying CTE
statement: EXPLAIN ANALYZE WITH i AS (INSERT INTO t1 (a) VALUES ('1') RETURNING a) SELECT count(*) FROM i;
@@ -699,5 +729,10 @@
querySpan:
type: 5
results: []
- sourcecolumns: []
+ sourcecolumns:
+ - server: ""
+ database: db
+ schema: public
+ table: t1
+ column: ""
predicatecolumns: []
diff --git a/backend/plugin/parser/plsql/query_span_extractor.go b/backend/plugin/parser/plsql/query_span_extractor.go
index 682d063ecb..ec703334d6 100644
--- a/backend/plugin/parser/plsql/query_span_extractor.go
+++ b/backend/plugin/parser/plsql/query_span_extractor.go
@@ -342,9 +342,13 @@ func (q *omniQuerySpanExtractor) getOmniQuerySpan(ctx context.Context, statement
queryType := omniQueryType(raw.Stmt, allSystem)
if queryType != base.Select {
+ sourceColumns := make(base.SourceColumnSet)
+ for _, resource := range accessTables {
+ sourceColumns[base.ColumnResource{Database: resource.Database, Table: resource.Table}] = true
+ }
return &base.QuerySpan{
Type: queryType,
- SourceColumns: base.SourceColumnSet{},
+ SourceColumns: sourceColumns,
Results: []base.QuerySpanResult{},
}, nil
}
@@ -366,7 +370,6 @@ func (q *omniQuerySpanExtractor) getOmniQuerySpan(ctx context.Context, statement
}
columnSet[column] = true
}
-
selectStmt, ok := raw.Stmt.(*oracleast.SelectStmt)
if !ok {
return nil, errors.Errorf("expected SELECT statement, got %T", raw.Stmt)
@@ -582,14 +585,28 @@ func collectOmniAccessTables(defaultDatabase string, stmt oracleast.StmtNode) (l
}
local = append(local, resource)
}
+ addTarget := func(name *oracleast.ObjectName) {
+ if name != nil {
+ addResource(name, name.DBLink)
+ }
+ }
oracleast.Inspect(stmt, func(node oracleast.Node) bool {
switch node := node.(type) {
case *oracleast.TableRef:
addResource(node.Name, omniTableLink(node))
case *oracleast.ContainersExpr:
- if node.Name != nil {
- addResource(node.Name, node.Name.DBLink)
- }
+ addTarget(node.Name)
+ // A DML target is an ObjectName, not a TableRef, so it is named here.
+ case *oracleast.InsertStmt:
+ addTarget(node.Table)
+ case *oracleast.InsertIntoClause:
+ addTarget(node.Table)
+ case *oracleast.UpdateStmt:
+ addTarget(node.Table)
+ case *oracleast.DeleteStmt:
+ addTarget(node.Table)
+ case *oracleast.MergeStmt:
+ addTarget(node.Target)
default:
}
return true
diff --git a/backend/plugin/parser/plsql/test-data/query_span.yaml b/backend/plugin/parser/plsql/test-data/query_span.yaml
index 47f921aa18..77043cb476 100644
--- a/backend/plugin/parser/plsql/test-data/query_span.yaml
+++ b/backend/plugin/parser/plsql/test-data/query_span.yaml
@@ -26,7 +26,12 @@
querySpan:
type: 3
results: []
- sourcecolumns: []
+ sourcecolumns:
+ - server: ""
+ database: SYS
+ schema: ""
+ table: SOMETABLE
+ column: ""
predicatecolumns: []
- description: Test for Explain
statement: EXPLAIN PLAN FOR SELECT * FROM SCHEMA1.V1;
@@ -56,7 +61,12 @@
querySpan:
type: 2
results: []
- sourcecolumns: []
+ sourcecolumns:
+ - server: ""
+ database: SCHEMA1
+ schema: ""
+ table: V1
+ column: ""
predicatecolumns: []
- description: Test for DDL
statement: create table t(a int);
@@ -116,7 +126,12 @@
querySpan:
type: 5
results: []
- sourcecolumns: []
+ sourcecolumns:
+ - server: ""
+ database: PUBLIC
+ schema: ""
+ table: T
+ column: ""
predicatecolumns: []
- description: Test for cross-schema view
statement: SELECT * FROM SCHEMA1.V1;
diff --git a/backend/plugin/parser/snowflake/query_span_extractor.go b/backend/plugin/parser/snowflake/query_span_extractor.go
index 94a1697c46..f8183ba880 100644
--- a/backend/plugin/parser/snowflake/query_span_extractor.go
+++ b/backend/plugin/parser/snowflake/query_span_extractor.go
@@ -102,7 +102,7 @@ func (q *querySpanExtractor) getQuerySpan(ctx context.Context, statement string)
if queryType != base.Select {
return &base.QuerySpan{
Type: queryType,
- SourceColumns: base.SourceColumnSet{},
+ SourceColumns: accessTables,
Results: []base.QuerySpanResult{},
}, nil
}
diff --git a/backend/plugin/parser/tidb/query_span_explain_test.go b/backend/plugin/parser/tidb/query_span_explain_test.go
index ef528a6512..6fd0b0c637 100644
--- a/backend/plugin/parser/tidb/query_span_explain_test.go
+++ b/backend/plugin/parser/tidb/query_span_explain_test.go
@@ -2,6 +2,7 @@ package tidb
import (
"context"
+ "strings"
"testing"
metadatapb "github.com/bytebase/omni/metadata"
@@ -13,7 +14,7 @@ import (
func TestExplainAnalyzeDigestRejected(t *testing.T) {
span, err := GetQuerySpan(context.Background(), base.GetQuerySpanContext{},
base.Statement{Text: "EXPLAIN ANALYZE 'sqldigest'"}, "db", "", false)
- require.ErrorContains(t, err, "EXPLAIN ANALYZE by digest is not supported")
+ require.ErrorContains(t, err, "EXPLAIN by digest or connection is not supported")
require.Nil(t, span)
}
@@ -130,7 +131,7 @@ func TestExplainAnalyzeAccessTables(t *testing.T) {
name: "plain explain permits mixed tables",
statement: "EXPLAIN SELECT * FROM t JOIN information_schema.tables ON TRUE",
queryType: base.Explain,
- sources: base.SourceColumnSet{},
+ sources: base.SourceColumnSet{{Database: "db", Table: "t"}: true},
},
{
name: "analyze still rejects mixed tables",
@@ -147,13 +148,13 @@ func TestExplainAnalyzeAccessTables(t *testing.T) {
name: "plain explain",
statement: "EXPLAIN SELECT * FROM t",
queryType: base.Explain,
- sources: base.SourceColumnSet{},
+ sources: base.SourceColumnSet{{Database: "db", Table: "t"}: true},
},
{
name: "analyzed write remains dml",
statement: "EXPLAIN ANALYZE DELETE FROM t WHERE id = 1",
queryType: base.DML,
- sources: base.SourceColumnSet{},
+ sources: base.SourceColumnSet{{Database: "db", Table: "t"}: true},
},
} {
t.Run(tc.name, func(t *testing.T) {
@@ -167,6 +168,7 @@ func TestExplainAnalyzeAccessTables(t *testing.T) {
}
require.NoError(t, err)
require.Equal(t, tc.queryType, span.Type)
+ require.Equal(t, strings.HasPrefix(tc.statement, "EXPLAIN ANALYZE"), span.ExplainAnalyze)
require.Equal(t, tc.sources, span.SourceColumns)
require.Empty(t, span.Results)
})
diff --git a/backend/plugin/parser/tidb/query_span_extractor.go b/backend/plugin/parser/tidb/query_span_extractor.go
index d501888b75..77a2d8304a 100644
--- a/backend/plugin/parser/tidb/query_span_extractor.go
+++ b/backend/plugin/parser/tidb/query_span_extractor.go
@@ -66,11 +66,19 @@ func (q *querySpanExtractor) getQuerySpan(ctx context.Context, statement string)
accessNode := node
includeUncached := false
if explain, ok := node.(*tidbast.ExplainStmt); ok {
- if !explain.Analyze {
- return &base.QuerySpan{Type: base.Explain, Results: []base.QuerySpanResult{}, SourceColumns: base.SourceColumnSet{}}, nil
- }
if explain.Stmt == nil {
- return nil, errors.New("EXPLAIN ANALYZE by digest is not supported: referenced tables cannot be determined")
+ return nil, errors.New("EXPLAIN by digest or connection is not supported: referenced tables cannot be determined")
+ }
+ // A plan carries the tables it reads. System tables are left out: they are
+ // not tracked databases, and a plain EXPLAIN may mix them with user tables.
+ if !explain.Analyze {
+ sourceColumns := q.getAccessTables(explain.Stmt, true)
+ for resource := range sourceColumns {
+ if isSystemResource(resource) {
+ delete(sourceColumns, resource)
+ }
+ }
+ return &base.QuerySpan{Type: base.Explain, Results: []base.QuerySpanResult{}, SourceColumns: sourceColumns}, nil
}
accessNode = explain.Stmt
includeUncached = true
@@ -84,18 +92,20 @@ func (q *querySpanExtractor) getQuerySpan(ctx context.Context, statement string)
queryType, isExplainAnalyze := getQueryType(node, allSystems)
if skipQuerySpan(node, queryType) {
return &base.QuerySpan{
- Type: queryType,
- Results: []base.QuerySpanResult{},
- SourceColumns: base.SourceColumnSet{},
+ Type: queryType,
+ ExplainAnalyze: isExplainAnalyze,
+ Results: []base.QuerySpanResult{},
+ SourceColumns: accessTables,
}, nil
}
// For EXPLAIN ANALYZE SELECT, we determine the query type and access tables from the inner SELECT statement.
if isExplainAnalyze {
return &base.QuerySpan{
- Type: queryType,
- Results: []base.QuerySpanResult{},
- SourceColumns: accessTables,
+ Type: queryType,
+ ExplainAnalyze: true,
+ Results: []base.QuerySpanResult{},
+ SourceColumns: accessTables,
}, nil
}
diff --git a/backend/plugin/parser/tidb/test-data/query_type.yaml b/backend/plugin/parser/tidb/test-data/query_type.yaml
index 973b550490..903af5307f 100644
--- a/backend/plugin/parser/tidb/test-data/query_type.yaml
+++ b/backend/plugin/parser/tidb/test-data/query_type.yaml
@@ -35,7 +35,12 @@
querySpan:
type: 5
results: []
- sourcecolumns: []
+ sourcecolumns:
+ - server: ""
+ database: db
+ schema: ""
+ table: t
+ column: ""
predicatecolumns: []
- description: Test DDL
statement: create table t(a int);
@@ -62,7 +67,12 @@
querySpan:
type: 4
results: []
- sourcecolumns: []
+ sourcecolumns:
+ - server: ""
+ database: db
+ schema: ""
+ table: t
+ column: ""
predicatecolumns: []
- description: Test Explain ANALYZE
statement: EXPLAIN ANALYZE SELECT t1.*, t2.* FROM t t1 JOIN (select * from t) t2 ON t1.a = t2.a;
@@ -121,5 +131,10 @@
querySpan:
type: 2
results: []
- sourcecolumns: []
+ sourcecolumns:
+ - server: ""
+ database: db
+ schema: ""
+ table: t
+ column: ""
predicatecolumns: []
diff --git a/backend/plugin/parser/tsql/query_span_extractor.go b/backend/plugin/parser/tsql/query_span_extractor.go
index 4ae721e119..b9758923d3 100644
--- a/backend/plugin/parser/tsql/query_span_extractor.go
+++ b/backend/plugin/parser/tsql/query_span_extractor.go
@@ -504,7 +504,7 @@ func (q *omniQuerySpanExtractor) getOmniQuerySpan(ctx context.Context, statement
if queryType != base.Select || !isSelect {
return &base.QuerySpan{
Type: queryType,
- SourceColumns: base.SourceColumnSet{},
+ SourceColumns: accessTables,
Results: []base.QuerySpanResult{},
}, nil
}
@@ -1878,6 +1878,15 @@ func collectOmniAccessTables(root ast.Node, currentDatabase, currentSchema strin
return out
}
+func walkTableList(list *ast.List, db, schema string, out base.SourceColumnSet) {
+ if list == nil {
+ return
+ }
+ for _, it := range list.Items {
+ walkAccessTables(it, db, schema, out)
+ }
+}
+
func walkAccessTables(n ast.Node, db, schema string, out base.SourceColumnSet) {
if n == nil {
return
@@ -1909,6 +1918,27 @@ func walkAccessTables(n ast.Node, db, schema string, out base.SourceColumnSet) {
if v.Rarg != nil {
walkAccessTables(v.Rarg, db, schema, out)
}
+ if v.OrderByClause != nil {
+ for _, it := range v.OrderByClause.Items {
+ walkAccessTables(it, db, schema, out)
+ }
+ }
+ case *ast.OrderByItem:
+ walkAccessTables(v.Expr, db, schema, out)
+ case *ast.InsertStmt:
+ walkAccessTables(v.Relation, db, schema, out)
+ walkAccessTables(v.Source, db, schema, out)
+ case *ast.UpdateStmt:
+ walkAccessTables(v.Relation, db, schema, out)
+ walkTableList(v.FromClause, db, schema, out)
+ walkAccessTables(v.WhereClause, db, schema, out)
+ case *ast.DeleteStmt:
+ walkAccessTables(v.Relation, db, schema, out)
+ walkTableList(v.FromClause, db, schema, out)
+ walkAccessTables(v.WhereClause, db, schema, out)
+ case *ast.MergeStmt:
+ walkAccessTables(v.Target, db, schema, out)
+ walkAccessTables(v.Source, db, schema, out)
case *ast.WithClause:
if v.CTEs != nil {
for _, it := range v.CTEs.Items {
diff --git a/backend/plugin/parser/tsql/test-data/query-span/query_type.yaml b/backend/plugin/parser/tsql/test-data/query-span/query_type.yaml
index 6d287bd88d..16f05d5b5e 100644
--- a/backend/plugin/parser/tsql/test-data/query-span/query_type.yaml
+++ b/backend/plugin/parser/tsql/test-data/query-span/query_type.yaml
@@ -48,7 +48,12 @@
querySpan:
type: 5
results: []
- sourcecolumns: []
+ sourcecolumns:
+ - server: ""
+ database: db
+ schema: dbo
+ table: t
+ column: ""
predicatecolumns: []
- description: DDL
statement: ALTER TABLE dbo.doc_exa ADD column_b VARCHAR(20) NULL, column_c INT NULL;
@@ -74,5 +79,10 @@
querySpan:
type: 3
results: []
- sourcecolumns: []
+ sourcecolumns:
+ - server: ""
+ database: db
+ schema: INFORMATION_SCHEMA
+ table: TABLES
+ column: ""
predicatecolumns: []
diff --git a/docs/design/query-plan-visualizer.md b/docs/design/query-plan-visualizer.md
index 131d5f356e..e901feac4f 100644
--- a/docs/design/query-plan-visualizer.md
+++ b/docs/design/query-plan-visualizer.md
@@ -1,6 +1,6 @@
# Query plan visualizer
-**Status:** draft for review · **Scope:** SQL Editor · Code references are to `main` at `7664688752`.
+**Status:** partly implemented, see §6 · **Scope:** SQL Editor · Code references are to `main` at `7664688752` unless a PR is named.
Bytebase draws query plans, but few users reach the drawing. This covers the
whole journey: how you ask for a plan, when you get a picture, how you read it,
@@ -21,10 +21,7 @@ Journey 3 is the rarest — most people press Run without checking — so the de
spends its effort on what happens *after* a run. Supabase removed its editor
Explain tab, which only served journey 3, for non-use.
-This ordering is a guess, so instrument it before building. Four events settle
-it: which of the four triggers fired (§3.1), whether the result drew a graph or
-fell back to text, whether Visualize was pressed, and time-to-plan. Unnamed
-telemetry never gets built, so these are the names.
+This ordering is a judgment call, not a measurement.
---
@@ -346,11 +343,10 @@ limit and all. The estimate badge is about statistics moving; it must not quietl
cover a different query.
That requires every driver that rewrites a statement to record what it actually
-ran, and two do not: SQL Server executes `refinedBatch` but records
-`singleSQLs[i].Text` (`mssql.go:607`), and Spanner executes `limitedStatement`
-but records `statement` (`spanner.go:400`). Their Plan tabs wait on that being
-fixed, exactly as the timed-out case waits on the timeout response carrying its
-statement.
+ran. SQL Server and Spanner did not until
+[#21476](https://github.com/bytebase/bytebase/pull/21476) and
+[#21481](https://github.com/bytebase/bytebase/pull/21481); the timed-out case
+still waits on the timeout response carrying its statement.
**Say which one it is, in words.** Measured and estimated carry a badge, and an
estimated plan says *"A new plan, made just now. It may differ from the plan that
@@ -363,9 +359,7 @@ was never the problem. That is the inverted failure this wording exists to stop.
**Nine of twelve engines have no parser**, so for those the plan is text. Showing
it as formatted text instead of grid rows is a small change with wide reach.
-Whether it reaches most *users* is a separate question that engine counts cannot
-answer — the §1 instrumentation is what settles which engines people actually
-explain, and it should settle the sequencing too. MySQL and Oracle are the
+MySQL and Oracle are the
cheapest graphs to add later: MySQL already emits structured JSON, and Oracle's
plan table already holds the parent-child links the driver discards.
@@ -415,36 +409,45 @@ permission to read rows. That boundary applies identically to the Plan tab, the
Text tab, Copy plan, and any plan attached to an ordinary run (§3.4): all of them
are the same capability, so none of them may be reachable without it.
-Two ways that boundary leaks today, both in `checkDatabaseAccess`
-(`sql_service.go:1411-1447`), and both have to close before any of this ships:
-
-- **It is checked per connection, not per referenced database**, on both routes.
- An explain request has no query spans at all; a typed `EXPLAIN` does have one,
- but MySQL extracts it as a pseudo-table with no source columns
- (`query_span_extractor.go:468`), so nothing per-resource fires there either.
- Both end at the same single check against the database the editor is connected
- to, so `EXPLAIN SELECT * FROM db_b.secret` on `db_a` yields `db_b`'s plan to
- someone with explain on `db_a` only. Explain has to be required on every
- database the statement references — typed and generated alike — which means
- extracting them from the inner statement, and evaluating each against **its
- own** project's policy. One instance can hold databases owned by different
- projects, while the policy is loaded once from the connected database
- (`sql_service.go:1393-1407`), so reusing it would judge `db_b` by `db_a`'s
- bindings: exposure for a project-A member, and a wrong denial for a legitimate
- project-B one.
-- **A data access grant exempts it.** The check returns early for a granted
- target before the permission is ever evaluated, so a temporary select or
- unmask grant carries explain along with it. Access grants convey data access;
- they do not convey the right to read plans.
+Two ways that boundary leaked, both in `checkDatabaseAccess`
+(`sql_service.go:1411-1447`), both closed:
+
+- **It was checked per connection, not per referenced database**, on both
+ routes. An explain request had no query spans at all; a typed `EXPLAIN` had
+ one, but MySQL extracted it as a pseudo-table with no source columns, so
+ nothing per-resource fired there either. Both ended at the same single check
+ against the database the editor is connected to, so `EXPLAIN SELECT * FROM
+ db_b.secret` on `db_a` yielded `db_b`'s plan to someone with explain on `db_a`
+ only. Now the inner statement's span names every database it references —
+ typed and generated alike — and `bb.sql.explain` is required on each tracked
+ one, through the same per-target check a write uses (`checkExplainAccess`
+ over `authorizeWriteTargets`). One instance can hold databases owned by
+ different projects, and the connected database's policy says nothing about
+ another project's, so a database in another project fails closed, as it does
+ for a write. A name is resolved as typed, and case-insensitively where the
+ engine folds case; one Bytebase does not track as a database — Oracle's
+ `SYS`, Snowflake's `SNOWFLAKE` — is left to the connected database's check. A
+ typed `EXPLAIN ANALYZE` carries an `ExplainAnalyze` mark on its span and needs
+ the inner statement's permission as well. SQL Server's `SET STATISTICS XML
+ ON` also executes and returns a plan, and still passes on `bb.sql.select`
+ alone: the explain recognizer knows only SHOWPLAN. That is the one permission
+ item still open here.
+- **A data access grant exempted it**
+ ([#21619](https://github.com/bytebase/bytebase/pull/21619)). The check
+ returned early for a granted target before the permission was evaluated, so a
+ temporary select or unmask grant carried explain along with it. Access grants
+ convey data access; they do not convey the right to read plans, and
+ `bb.sql.explain` now comes from IAM on every route.
Reading the statement does not always reveal what it touches. `EXEC dbo.p` is
classified as DML with no source columns (`tsql/query_type.go:42`,
`query_span_extractor.go:501-505`), while SHOWPLAN and `STATISTICS XML` expose
plans for the statements *inside* the procedure — so a procedure reading `db_b`
-would be authorized against `db_a` alone. Resolving routine dependencies is a
-larger feature than this design. **When the resource set is opaque, refuse the
-plan**: no plan is the safe answer, and it is the same choice §3.3 makes for
-session-dependent scripts.
+is authorized against `db_a` alone. Resolving routine dependencies is a larger
+feature than this design, and a plan is still worth having: a statement whose
+span names no table is checked on the connected database, as every explain was
+before. Every query span now carries the tables its statement touches, whatever
+the statement type, so this is the only case left to that single check.
**Slow and large plans.** The on-demand call can take as long as any query: show
a skeleton, allow cancel, time out rather than hang. Past a node cap the Plan tab
@@ -490,3 +493,42 @@ they are no guide — two cannot express one — so §3.2 follows SSMS and pgAdm
**Method.** Code read at `main`; walkthrough of a local build (86 screenshots, 24
problems); 20+ SQL editors and 6 plan viewers checked against docs, source and
live servers, September 2026.
+
+---
+
+## 6. Status
+
+Checked against `main` on 2026-10-22.
+
+**Landed**
+
+- §3.2 — the result states its plan format (`QueryResult.query_plan`), a typed
+ `EXPLAIN (FORMAT JSON)` draws inline, and Visualize substitutes the format on
+ the server: [#21485](https://github.com/bytebase/bytebase/pull/21485),
+ [#21492](https://github.com/bytebase/bytebase/pull/21492),
+ [#21493](https://github.com/bytebase/bytebase/pull/21493).
+- §3.4 — SQL Server and Spanner record the statement they ran:
+ [#21476](https://github.com/bytebase/bytebase/pull/21476),
+ [#21481](https://github.com/bytebase/bytebase/pull/21481).
+- §3.5 — the explain gate refuses a smuggled write
+ ([#21447](https://github.com/bytebase/bytebase/pull/21447)); an access
+ grant no longer carries `bb.sql.explain`
+ ([#21619](https://github.com/bytebase/bytebase/pull/21619)); explain is
+ required on every database the statement references, with a database in
+ another project failing closed, and a typed `EXPLAIN ANALYZE` needs the inner
+ statement's permission as well. What remains of §3.5: SQL Server's
+ `SET STATISTICS XML ON` route still passes on `bb.sql.select` alone, and the
+ Plan tab items — disabled with the reason shown, skeleton and cancel, the
+ node cap — ride with item 1.
+
+**Not yet, in the order to do them**
+
+1. §3.2/§3.3 — the Plan tab on an ordinary result, planning the executed
+ statement, with the estimate wording from §3.4.
+2. §3.1 — Explain and Explain analyze in the Run dropdown, planning the limited
+ statement; today every driver's explain path skips the limit.
+3. §3.3 — the reading changes: summary panel always visible, graph opening on
+ the costliest operator, View SQL, warning relevance, measured plans with
+ planned vs actual rows, cost share on the tab label.
+4. §3.4 — delete the pop-up page (`frontend/explain-visualizer.html`), which
+ nothing links to any more.