Skip to content

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

fix(sql): reject a smuggled write in an EXPLAIN request (#21447)

Danny Xuda941c388c72
diff --git a/backend/api/v1/sql_service.go b/backend/api/v1/sql_service.go
index 5d0e313dfd..f7dc80ff3d 100644
--- a/backend/api/v1/sql_service.go
+++ b/backend/api/v1/sql_service.go
@@ -315,12 +315,21 @@ func (s *SQLService) Query(ctx context.Context, req *connect.Request[v1pb.QueryR
}
// Validate the request.
- // New query ACL experience.
+ // Engines without the per-statement ACL rely on this read-only gate to refuse
+ // writes (they do not classify DML/DDL in the access check). New-ACL engines
+ // classify per statement instead.
if !request.Explain && !common.EngineSupportQueryNewACL(instance.Metadata.GetEngine()) {
if err := validateQueryRequest(instance, statement); err != nil {
return nil, err
}
}
+ // EXPLAIN ANALYZE of a write executes it, so refuse an explain whose wrapped
+ // form is not read-only. See validateExplainStatements.
+ if request.Explain {
+ if err := validateExplainStatements(instance, statement, request.GetQueryOption().GetExplainFormat()); err != nil {
+ return nil, err
+ }
+ }
if request.Explain {
if err := validateExplainFormat(instance.Metadata.GetEngine(), request.GetQueryOption().GetExplainFormat()); err != nil {
return nil, err
@@ -703,21 +712,24 @@ func queryRetry(
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 {
- // Check query access
- if err := optionalAccessCheck(ctx, instance, database, user, spans, queryContext.Explain, statements, queryContext.Schema, multiStatement); err != nil {
- return nil, nil, time.Duration(0), err
- }
- slog.Debug("optional access check", slog.String("instance", instance.ResourceID), slog.String("database", database.DatabaseName))
+ }
+ 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.
+ if err := optionalAccessCheck(ctx, instance, database, user, spans, queryContext.Explain, statements, queryContext.Schema, multiStatement); err != nil {
+ return nil, nil, time.Duration(0), err
}
- if !queryContext.SkipMasking && licenseService.IsFeatureEnabledForInstance(ctx, common.GetWorkspaceIDFromContext(ctx), v1pb.PlanFeature_FEATURE_DATA_MASKING, instance) == nil {
- masker := NewQueryResultMasker(stores)
- sensitivePredicateColumns, err = masker.ExtractSensitivePredicateColumns(ctx, spans, instance, user)
- if err != nil {
- return nil, nil, time.Duration(0), connect.NewError(connect.CodeInternal, errors.New(err.Error()))
- }
- slog.Debug("extract sensitive predicate columns", slog.String("instance", instance.ResourceID), slog.String("database", database.DatabaseName))
+ slog.Debug("optional access check", slog.String("instance", instance.ResourceID), slog.String("database", database.DatabaseName))
+ }
+ if !queryContext.Explain && !queryContext.SkipMasking && licenseService.IsFeatureEnabledForInstance(ctx, common.GetWorkspaceIDFromContext(ctx), v1pb.PlanFeature_FEATURE_DATA_MASKING, instance) == nil {
+ masker := NewQueryResultMasker(stores)
+ sensitivePredicateColumns, err = masker.ExtractSensitivePredicateColumns(ctx, spans, instance, user)
+ if err != nil {
+ return nil, nil, time.Duration(0), connect.NewError(connect.CodeInternal, errors.New(err.Error()))
}
+ slog.Debug("extract sensitive predicate columns", slog.String("instance", instance.ResourceID), slog.String("database", database.DatabaseName))
}
maskingEnabled := !queryContext.Explain && !queryContext.SkipMasking &&
@@ -1435,8 +1447,9 @@ func (s *SQLService) accessCheckWithGrantedTargets(
return nil
}
- // When spans is empty, it's an EXPLAIN query where GetQuerySpan is skipped (queryContext.Explain is true).
- // Check at database level with EXPLAIN permission.
+ // 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.
if len(spans) == 0 {
perm := permission.SQLSelect
if isExplain {
@@ -2016,6 +2029,38 @@ func validateExplainFormat(engine storepb.Engine, format v1pb.QueryOption_Explai
return connect.NewError(connect.CodeInvalidArgument, errors.Errorf("%s does not support explain format %s, supported formats: %s", engine, format, strings.Join(names, ", ")))
}
+// validateExplainStatements refuses an explain request whose EXPLAIN-wrapped form
+// would execute a write. The driver splits a multi-statement request and prefixes
+// EXPLAIN to each statement (see pg.go and its siblings), so this validates the
+// same per-statement wrapped form: a smuggled "ANALYZE DELETE FROM t" becomes
+// EXPLAIN ANALYZE DELETE and is rejected before it runs. Engines whose EXPLAIN is
+// not a statement prefix (Oracle EXPLAIN PLAN, SQL Server SHOWPLAN, Spanner/BigQuery
+// plan APIs) report ok=false from db.ExplainStatement and run their own plan API,
+// which does not execute the statement.
+func validateExplainStatements(instance *store.InstanceMessage, statement string, format v1pb.QueryOption_ExplainFormat) error {
+ engine := instance.Metadata.GetEngine()
+ statements, err := parserbase.SplitMultiSQL(engine, statement)
+ if err != nil {
+ // No splitter for this engine: validate the whole statement wrapped once.
+ // Execution goes through the same splitter, so a request that fails to split
+ // here fails there too rather than executing.
+ statements = []parserbase.Statement{{Text: statement}}
+ }
+ for _, stmt := range statements {
+ if stmt.Empty {
+ continue
+ }
+ wrapped, ok := db.ExplainStatement(engine, stmt.Text, format)
+ if !ok {
+ return nil
+ }
+ if err := validateQueryRequest(instance, wrapped); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
func validateQueryRequest(instance *store.InstanceMessage, statement string) error {
ok, _, err := parserbase.ValidateSQLForEditor(instance.Metadata.GetEngine(), statement)
if err != nil {
diff --git a/backend/api/v1/sql_service_test.go b/backend/api/v1/sql_service_test.go
index 41fa1f0b80..d0be83cc2a 100644
--- a/backend/api/v1/sql_service_test.go
+++ b/backend/api/v1/sql_service_test.go
@@ -375,3 +375,64 @@ func TestValidateExplainFormat(t *testing.T) {
})
}
}
+
+// TestExplainGateRejectsSmuggledWrite locks the smuggle defense. An explain
+// request carries the bare statement and the driver prefixes EXPLAIN, so
+// "ANALYZE DELETE FROM t" — not valid SQL on its own — would become
+// EXPLAIN ANALYZE DELETE and execute the DELETE. validateExplainStatements wraps
+// each statement the way the driver does and refuses it unless read-only. Every
+// prefix engine must classify the wrapped smuggle as non-read-only (by verdict or
+// syntax error) so it never reaches the driver.
+//
+// The engine parsers are registered for the whole v1 test binary by blank imports
+// elsewhere in the package, so each ValidateSQLForEditor call returns that engine's
+// real verdict rather than the no-validator default.
+func TestExplainGateRejectsSmuggledWrite(t *testing.T) {
+ t.Parallel()
+ engines := []storepb.Engine{
+ storepb.Engine_POSTGRES, storepb.Engine_MYSQL, storepb.Engine_MARIADB,
+ storepb.Engine_OCEANBASE, storepb.Engine_TIDB, storepb.Engine_REDSHIFT,
+ storepb.Engine_COCKROACHDB, storepb.Engine_SNOWFLAKE, storepb.Engine_CLICKHOUSE,
+ storepb.Engine_STARROCKS, storepb.Engine_DORIS, storepb.Engine_HIVE,
+ storepb.Engine_TRINO,
+ }
+ for _, engine := range engines {
+ t.Run(engine.String(), func(t *testing.T) {
+ t.Parallel()
+ instance := &store.InstanceMessage{Metadata: &storepb.Instance{Engine: engine}}
+ require.Error(t, validateExplainStatements(instance, "ANALYZE DELETE FROM t", v1pb.QueryOption_EXPLAIN_FORMAT_UNSPECIFIED),
+ "EXPLAIN ANALYZE DELETE must not pass the read-only gate")
+ })
+ }
+}
+
+// TestExplainGateAllowsPlans confirms the gate does not over-reject legitimate
+// plans. A plain EXPLAIN plans without executing, so a read or a write is allowed;
+// and because the driver splits a multi-statement request and prefixes EXPLAIN to
+// each statement (pg.go and siblings), the gate does the same with the same
+// per-engine splitter — a batch of plain writes is planned one at a time. A write
+// smuggled into a batch as EXPLAIN ANALYZE is still refused wherever it sits;
+// TestExplainGateRejectsSmuggledWrite is the single-statement sweep over every
+// engine.
+func TestExplainGateAllowsPlans(t *testing.T) {
+ t.Parallel()
+ pg := &store.InstanceMessage{Metadata: &storepb.Instance{Engine: storepb.Engine_POSTGRES}}
+ // Plain single-statement plans, read or write, are allowed.
+ for _, stmt := range []string{"SELECT 1", "DELETE FROM t"} {
+ require.NoError(t, validateExplainStatements(pg, stmt, v1pb.QueryOption_EXPLAIN_FORMAT_UNSPECIFIED), stmt)
+ }
+ // Engines that split on ';' plan each statement in its own non-executing EXPLAIN,
+ // so a batch of plain writes is allowed rather than over-rejected.
+ for _, engine := range []storepb.Engine{storepb.Engine_POSTGRES, storepb.Engine_MYSQL} {
+ instance := &store.InstanceMessage{Metadata: &storepb.Instance{Engine: engine}}
+ require.NoErrorf(t, validateExplainStatements(instance, "DELETE FROM hello; DELETE FROM hello", v1pb.QueryOption_EXPLAIN_FORMAT_UNSPECIFIED), "%s: batch of plain writes", engine)
+ }
+ // A write smuggled into a batch is refused wherever it sits — on engines that
+ // split it (pg, mysql) and on one whose splitter keeps it whole and validates
+ // the unwrapped tail (clickhouse).
+ for _, engine := range []storepb.Engine{storepb.Engine_POSTGRES, storepb.Engine_MYSQL, storepb.Engine_CLICKHOUSE} {
+ instance := &store.InstanceMessage{Metadata: &storepb.Instance{Engine: engine}}
+ require.Errorf(t, validateExplainStatements(instance, "SELECT 1; ANALYZE DELETE FROM t", v1pb.QueryOption_EXPLAIN_FORMAT_UNSPECIFIED), "%s: smuggle after a read", engine)
+ require.Errorf(t, validateExplainStatements(instance, "ANALYZE DELETE FROM t; SELECT 1", v1pb.QueryOption_EXPLAIN_FORMAT_UNSPECIFIED), "%s: smuggle before a read", engine)
+ }
+}
diff --git a/backend/plugin/db/clickhouse/query.go b/backend/plugin/db/clickhouse/query.go
index 5ec38f1eb5..82ca66b50c 100644
--- a/backend/plugin/db/clickhouse/query.go
+++ b/backend/plugin/db/clickhouse/query.go
@@ -45,7 +45,7 @@ func (*Driver) QueryConn(ctx context.Context, conn *sql.Conn, statement string,
for _, singleSQL := range singleSQLs {
statement := singleSQL.Text
if queryContext.Explain {
- statement = fmt.Sprintf("EXPLAIN %s", statement)
+ statement, _ = db.ExplainStatement(storepb.Engine_CLICKHOUSE, statement, queryContext.Option.GetExplainFormat())
} else if queryContext.Limit > 0 {
statement = getStatementWithResultLimit(statement, queryContext.Limit)
}
diff --git a/backend/plugin/db/cockroachdb/cockroachdb.go b/backend/plugin/db/cockroachdb/cockroachdb.go
index bdb36625a3..8302b80f37 100644
--- a/backend/plugin/db/cockroachdb/cockroachdb.go
+++ b/backend/plugin/db/cockroachdb/cockroachdb.go
@@ -622,7 +622,7 @@ func (*Driver) QueryConn(ctx context.Context, conn *sql.Conn, statement string,
for _, singleSQL := range singleSQLs {
statement := singleSQL
if queryContext.Explain {
- statement = fmt.Sprintf("EXPLAIN %s", statement)
+ statement, _ = db.ExplainStatement(storepb.Engine_COCKROACHDB, statement, queryContext.Option.GetExplainFormat())
} else if queryContext.Limit > 0 {
statement = getStatementWithResultLimit(statement, queryContext.Limit)
}
diff --git a/backend/plugin/db/explain.go b/backend/plugin/db/explain.go
new file mode 100644
index 0000000000..3b96a0dc24
--- /dev/null
+++ b/backend/plugin/db/explain.go
@@ -0,0 +1,48 @@
+package db
+
+import (
+ "fmt"
+
+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"
+ v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"
+)
+
+// ExplainStatement returns the statement that produces a query plan for
+// statement on engine, and whether engine explains by prefixing the statement
+// with EXPLAIN. It is the single source of that wrapping: a driver calls it to
+// build the statement it runs, and the Query handler calls it to validate the
+// exact statement that will run (an EXPLAIN ANALYZE of a write is not read-only
+// and is refused before execution).
+//
+// The second return is false for engines whose EXPLAIN is not a bare prefix and
+// so does not execute the wrapped statement — Oracle (EXPLAIN PLAN FOR), SQL
+// Server (SET SHOWPLAN), Spanner/BigQuery (plan APIs) — and for engines with no
+// EXPLAIN at all. Those drivers produce a plan on their own and pass "" here.
+func ExplainStatement(engine storepb.Engine, statement string, format v1pb.QueryOption_ExplainFormat) (string, bool) {
+ switch engine {
+ case storepb.Engine_POSTGRES:
+ switch format {
+ case v1pb.QueryOption_JSON:
+ return fmt.Sprintf("EXPLAIN (FORMAT JSON) %s", statement), true
+ case v1pb.QueryOption_XML:
+ return fmt.Sprintf("EXPLAIN (FORMAT XML) %s", statement), true
+ default:
+ return fmt.Sprintf("EXPLAIN %s", statement), true
+ }
+ case storepb.Engine_MYSQL,
+ storepb.Engine_MARIADB,
+ storepb.Engine_OCEANBASE,
+ storepb.Engine_TIDB,
+ storepb.Engine_REDSHIFT,
+ storepb.Engine_COCKROACHDB,
+ storepb.Engine_SNOWFLAKE,
+ storepb.Engine_CLICKHOUSE,
+ storepb.Engine_STARROCKS,
+ storepb.Engine_DORIS,
+ storepb.Engine_HIVE,
+ storepb.Engine_TRINO:
+ return fmt.Sprintf("EXPLAIN %s", statement), true
+ default:
+ return "", false
+ }
+}
diff --git a/backend/plugin/db/explain_test.go b/backend/plugin/db/explain_test.go
new file mode 100644
index 0000000000..652c353f30
--- /dev/null
+++ b/backend/plugin/db/explain_test.go
@@ -0,0 +1,36 @@
+package db
+
+import (
+ "testing"
+
+ "github.com/stretchr/testify/require"
+
+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"
+ v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"
+)
+
+func TestExplainStatement(t *testing.T) {
+ tests := []struct {
+ engine storepb.Engine
+ format v1pb.QueryOption_ExplainFormat
+ want string
+ wantOK bool
+ }{
+ {storepb.Engine_POSTGRES, v1pb.QueryOption_EXPLAIN_FORMAT_UNSPECIFIED, "EXPLAIN SELECT 1", true},
+ {storepb.Engine_POSTGRES, v1pb.QueryOption_JSON, "EXPLAIN (FORMAT JSON) SELECT 1", true},
+ {storepb.Engine_POSTGRES, v1pb.QueryOption_XML, "EXPLAIN (FORMAT XML) SELECT 1", true},
+ {storepb.Engine_MYSQL, v1pb.QueryOption_JSON, "EXPLAIN SELECT 1", true},
+ {storepb.Engine_TRINO, v1pb.QueryOption_EXPLAIN_FORMAT_UNSPECIFIED, "EXPLAIN SELECT 1", true},
+ {storepb.Engine_HIVE, v1pb.QueryOption_EXPLAIN_FORMAT_UNSPECIFIED, "EXPLAIN SELECT 1", true},
+ // Non-prefix engines (their driver builds the plan another way) report ok=false.
+ {storepb.Engine_ORACLE, v1pb.QueryOption_EXPLAIN_FORMAT_UNSPECIFIED, "", false},
+ {storepb.Engine_MSSQL, v1pb.QueryOption_EXPLAIN_FORMAT_UNSPECIFIED, "", false},
+ {storepb.Engine_SPANNER, v1pb.QueryOption_EXPLAIN_FORMAT_UNSPECIFIED, "", false},
+ {storepb.Engine_MONGODB, v1pb.QueryOption_EXPLAIN_FORMAT_UNSPECIFIED, "", false},
+ }
+ for _, tc := range tests {
+ got, ok := ExplainStatement(tc.engine, "SELECT 1", tc.format)
+ require.Equalf(t, tc.wantOK, ok, "%s ok", tc.engine)
+ require.Equalf(t, tc.want, got, "%s statement", tc.engine)
+ }
+}
diff --git a/backend/plugin/db/hive/hive.go b/backend/plugin/db/hive/hive.go
index b36ec1d06c..ac6157ea61 100644
--- a/backend/plugin/db/hive/hive.go
+++ b/backend/plugin/db/hive/hive.go
@@ -192,7 +192,7 @@ func (d *Driver) QueryConn(ctx context.Context, _ *sql.Conn, statement string, q
for _, singleSQL := range singleSQLs {
statement := util.TrimStatement(singleSQL.Text)
if queryCtx.Explain {
- statement = fmt.Sprintf("EXPLAIN %s", statement)
+ statement, _ = db.ExplainStatement(storepb.Engine_HIVE, statement, queryCtx.Option.GetExplainFormat())
}
result, err := d.queryStatementWithLimit(ctx, statement, queryCtx.MaximumSQLResultSize)
diff --git a/backend/plugin/db/mysql/mysql.go b/backend/plugin/db/mysql/mysql.go
index f34cc07bed..2c4b69f363 100644
--- a/backend/plugin/db/mysql/mysql.go
+++ b/backend/plugin/db/mysql/mysql.go
@@ -528,7 +528,7 @@ func (d *Driver) QueryConn(ctx context.Context, conn *sql.Conn, statement string
for _, singleSQL := range singleSQLs {
statement := singleSQL.Text
if queryContext.Explain {
- statement = fmt.Sprintf("EXPLAIN %s", statement)
+ statement, _ = db.ExplainStatement(storepb.Engine_MYSQL, statement, queryContext.Option.GetExplainFormat())
} else if queryContext.Limit > 0 {
statement = getStatementWithResultLimit(statement, queryContext.Limit)
}
diff --git a/backend/plugin/db/pg/pg.go b/backend/plugin/db/pg/pg.go
index bb9442f952..6565770986 100644
--- a/backend/plugin/db/pg/pg.go
+++ b/backend/plugin/db/pg/pg.go
@@ -799,7 +799,7 @@ func (d *Driver) QueryConn(ctx context.Context, conn *sql.Conn, statement string
for _, singleSQL := range singleSQLs {
statement := singleSQL.Text
if queryContext.Explain {
- statement = explainStatement(statement, queryContext.Option.GetExplainFormat())
+ statement, _ = db.ExplainStatement(storepb.Engine_POSTGRES, statement, queryContext.Option.GetExplainFormat())
} else if queryContext.Limit > 0 {
statement = getStatementWithResultLimit(statement, queryContext.Limit)
}
diff --git a/backend/plugin/db/pg/query.go b/backend/plugin/db/pg/query.go
index e28eb4b49d..c12bf5dd1e 100644
--- a/backend/plugin/db/pg/query.go
+++ b/backend/plugin/db/pg/query.go
@@ -212,21 +212,6 @@ func padZeroes(rawStr string, acc int) string {
return rawStr
}
-// explainStatement wraps statement in EXPLAIN. JSON and XML return the plan tree
-// in a single row, so a caller that renders the plan never has to parse the text
-// output. PostgreSQL produces every format this API offers, so there is nothing
-// to reject.
-func explainStatement(statement string, format v1pb.QueryOption_ExplainFormat) string {
- switch format {
- case v1pb.QueryOption_JSON:
- return fmt.Sprintf("EXPLAIN (FORMAT JSON) %s", statement)
- case v1pb.QueryOption_XML:
- return fmt.Sprintf("EXPLAIN (FORMAT XML) %s", statement)
- default:
- return fmt.Sprintf("EXPLAIN %s", statement)
- }
-}
-
// getStatementWithResultLimit returns the statement with LIMIT clause if not exists.
func getStatementWithResultLimit(statement string, limit int) string {
stmt, err := getStatementWithResultLimitInline(statement, limit)
diff --git a/backend/plugin/db/pg/query_test.go b/backend/plugin/db/pg/query_test.go
index 16ebd95e73..282f9c0067 100644
--- a/backend/plugin/db/pg/query_test.go
+++ b/backend/plugin/db/pg/query_test.go
@@ -10,26 +10,9 @@ import (
"github.com/stretchr/testify/require"
"google.golang.org/protobuf/encoding/protojson"
- v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"
pgparser "github.com/bytebase/bytebase/backend/plugin/parser/pg"
)
-func TestExplainStatement(t *testing.T) {
- for _, tc := range []struct {
- format v1pb.QueryOption_ExplainFormat
- want string
- }{
- {v1pb.QueryOption_EXPLAIN_FORMAT_UNSPECIFIED, "EXPLAIN SELECT 1;"},
- {v1pb.QueryOption_TEXT, "EXPLAIN SELECT 1;"},
- {v1pb.QueryOption_JSON, "EXPLAIN (FORMAT JSON) SELECT 1;"},
- {v1pb.QueryOption_XML, "EXPLAIN (FORMAT XML) SELECT 1;"},
- } {
- t.Run(tc.format.String(), func(t *testing.T) {
- require.Equal(t, tc.want, explainStatement("SELECT 1;", tc.format))
- })
- }
-}
-
func TestBuildTimestamptzRowValue(t *testing.T) {
tests := []struct {
name string
diff --git a/backend/plugin/db/redshift/redshift.go b/backend/plugin/db/redshift/redshift.go
index dee43e4146..085f951c45 100644
--- a/backend/plugin/db/redshift/redshift.go
+++ b/backend/plugin/db/redshift/redshift.go
@@ -388,7 +388,7 @@ func (d *Driver) QueryConn(ctx context.Context, conn *sql.Conn, statement string
statement = strings.ReplaceAll(statement, fmt.Sprintf("%s.", d.databaseName), "")
}
if queryContext.Explain {
- statement = fmt.Sprintf("EXPLAIN %s", statement)
+ statement, _ = db.ExplainStatement(storepb.Engine_REDSHIFT, statement, queryContext.Option.GetExplainFormat())
} else if queryContext.Limit > 0 {
statement = getStatementWithResultLimit(statement, queryContext.Limit)
}
diff --git a/backend/plugin/db/snowflake/snowflake.go b/backend/plugin/db/snowflake/snowflake.go
index 920c732b21..e492b330d6 100644
--- a/backend/plugin/db/snowflake/snowflake.go
+++ b/backend/plugin/db/snowflake/snowflake.go
@@ -337,7 +337,7 @@ func (*Driver) QueryConn(ctx context.Context, conn *sql.Conn, statement string,
for _, singleSQL := range singleSQLs {
statement := singleSQL.Text
if queryContext.Explain {
- statement = fmt.Sprintf("EXPLAIN %s", statement)
+ statement, _ = db.ExplainStatement(storepb.Engine_SNOWFLAKE, statement, queryContext.Option.GetExplainFormat())
} else if queryContext.Limit > 0 {
statement = getStatementWithResultLimit(statement, queryContext.Limit)
}
diff --git a/backend/plugin/db/starrocks/starrocks.go b/backend/plugin/db/starrocks/starrocks.go
index 2950466fd9..03e2d86572 100644
--- a/backend/plugin/db/starrocks/starrocks.go
+++ b/backend/plugin/db/starrocks/starrocks.go
@@ -304,7 +304,7 @@ func (d *Driver) QueryConn(ctx context.Context, conn *sql.Conn, statement string
for _, singleSQL := range singleSQLs {
statement := singleSQL.Text
if queryContext.Explain {
- statement = fmt.Sprintf("EXPLAIN %s", statement)
+ statement, _ = db.ExplainStatement(d.dbType, statement, queryContext.Option.GetExplainFormat())
} else if queryContext.Limit > 0 {
statement = getStatementWithResultLimit(statement, queryContext.Limit)
}
diff --git a/backend/plugin/db/tidb/tidb.go b/backend/plugin/db/tidb/tidb.go
index abe08c6d3e..e1e2628075 100644
--- a/backend/plugin/db/tidb/tidb.go
+++ b/backend/plugin/db/tidb/tidb.go
@@ -373,7 +373,7 @@ func (d *Driver) QueryConn(ctx context.Context, conn *sql.Conn, statement string
for _, singleSQL := range singleSQLs {
statement := singleSQL.Text
if queryContext.Explain {
- statement = fmt.Sprintf("EXPLAIN %s", statement)
+ statement, _ = db.ExplainStatement(storepb.Engine_TIDB, statement, queryContext.Option.GetExplainFormat())
} else if queryContext.Limit > 0 {
statement = getStatementWithResultLimit(statement, queryContext.Limit)
}
diff --git a/backend/plugin/db/trino/trino.go b/backend/plugin/db/trino/trino.go
index 9050c8c973..8246a29ad1 100644
--- a/backend/plugin/db/trino/trino.go
+++ b/backend/plugin/db/trino/trino.go
@@ -233,7 +233,7 @@ func (*Driver) QueryConn(ctx context.Context, conn *sql.Conn, statement string,
strings.HasPrefix(upperStmt, "EXPLAIN")
if queryContext.Explain {
- stmt = fmt.Sprintf("EXPLAIN %s", stmt)
+ stmt, _ = db.ExplainStatement(storepb.Engine_TRINO, stmt, queryContext.Option.GetExplainFormat())
isQuery = true
}
diff --git a/backend/plugin/parser/pg/query_type.go b/backend/plugin/parser/pg/query_type.go
index ea3821b32f..92b1f6dfca 100644
--- a/backend/plugin/parser/pg/query_type.go
+++ b/backend/plugin/parser/pg/query_type.go
@@ -167,7 +167,13 @@ func UnwrapExplainAnalyze(node ast.Node, text string) (ast.Node, string) {
return explain.Query, text[start:explain.Loc.End]
}
-// classifyExplainedQuery returns the QueryType for the query inside EXPLAIN ANALYZE.
+// classifyExplainedQuery returns the QueryType for the query inside EXPLAIN
+// ANALYZE, which actually runs it — so unlike classifyQueryType's own default,
+// an unrecognized node type here must fail closed rather than pass as Select.
+// The cases below are exhaustive over what PostgreSQL actually accepts as an
+// EXPLAIN target (CALL, TRUNCATE, COPY, DDL like DROP/ALTER do not parse
+// there), matching classifyQueryType's DML/DDL classification for the same
+// node types; the default exists only for a future grammar addition.
func classifyExplainedQuery(query ast.Node) base.QueryType {
if query == nil {
return base.Select
@@ -192,6 +198,6 @@ func classifyExplainedQuery(query ast.Node) base.QueryType {
case *ast.ExecuteStmt:
return base.Select
default:
- return base.Select
+ return base.QueryTypeUnknown
}
}
diff --git a/backend/plugin/parser/pg/query_type_test.go b/backend/plugin/parser/pg/query_type_test.go
new file mode 100644
index 0000000000..5dd0cf788e
--- /dev/null
+++ b/backend/plugin/parser/pg/query_type_test.go
@@ -0,0 +1,49 @@
+package pg
+
+import (
+ "testing"
+
+ "github.com/stretchr/testify/require"
+
+ "github.com/bytebase/bytebase/backend/plugin/parser/base"
+)
+
+// TestClassifyQueryTypeExplain pins how EXPLAIN is classified, which decides the
+// permission an explain request needs and whether the driver will run it. The
+// security-critical case is EXPLAIN ANALYZE of a write: PostgreSQL executes the
+// wrapped statement, so it must classify as the write it performs, not as a
+// plain EXPLAIN.
+func TestClassifyQueryTypeExplain(t *testing.T) {
+ testCases := []struct {
+ statement string
+ wantType base.QueryType
+ wantAlyze bool
+ }{
+ // Plain EXPLAIN only plans; it never executes, whatever it wraps.
+ {"EXPLAIN SELECT * FROM t", base.Explain, false},
+ {"EXPLAIN DELETE FROM t", base.Explain, false},
+ {"EXPLAIN INSERT INTO t VALUES (1)", base.Explain, false},
+
+ // EXPLAIN ANALYZE executes the wrapped statement, so it inherits its type.
+ {"EXPLAIN ANALYZE SELECT * FROM t", base.Select, true},
+ {"EXPLAIN ANALYZE DELETE FROM t", base.DML, true},
+ {"EXPLAIN ANALYZE INSERT INTO t VALUES (1)", base.DML, true},
+ {"EXPLAIN ANALYZE UPDATE t SET a = 1", base.DML, true},
+
+ // Bare statements keep classifying as before.
+ {"SELECT * FROM t", base.Select, false},
+ {"DELETE FROM t", base.DML, false},
+ }
+
+ for _, tc := range testCases {
+ t.Run(tc.statement, func(t *testing.T) {
+ stmts, err := ParsePg(tc.statement)
+ require.NoError(t, err)
+ require.Len(t, stmts, 1)
+
+ gotType, gotAnalyze := classifyQueryType(stmts[0].AST, false /* allSystems */)
+ require.Equal(t, tc.wantType, gotType)
+ require.Equal(t, tc.wantAlyze, gotAnalyze)
+ })
+ }
+}