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: implement MySQL statement type check (#2386)
rebelice52af026caa08
diff --git a/api/task_check_run.go b/api/task_check_run.goindex 87ae7ddc22..88f5f557ec 100644--- a/api/task_check_run.go+++ b/api/task_check_run.go@@ -99,6 +99,10 @@ type TaskCheckDatabaseStatementAdvisePayload struct {type TaskCheckDatabaseStatementTypePayload struct {Statement string `json:"statement,omitempty"`DbType db.Type `json:"dbType,omitempty"`++ // MySQL special fields.+ Charset string `json:"charset,omitempty"`+ Collation string `json:"collation,omitempty"`}// Namespace is the namespace for task check result.diff --git a/server/task_check_executor_statement_type.go b/server/task_check_executor_statement_type.goindex c6a0ce887f..823328e869 100644--- a/server/task_check_executor_statement_type.go+++ b/server/task_check_executor_statement_type.go@@ -11,6 +11,8 @@ import ("github.com/bytebase/bytebase/plugin/db""github.com/bytebase/bytebase/plugin/parser""github.com/bytebase/bytebase/plugin/parser/ast"+ tidbparser "github.com/pingcap/tidb/parser"+ tidbast "github.com/pingcap/tidb/parser/ast")// NewTaskCheckStatementTypeExecutor creates a task check DML executor.@@ -45,11 +47,42 @@ func (*TaskCheckStatementTypeExecutor) Run(ctx context.Context, server *Server,return nil, common.Wrapf(err, common.Invalid, "invalid check statement type payload")}- if payload.DbType != db.Postgres {+ switch payload.DbType {+ case db.Postgres:+ result, err = postgresqlStatementTypeCheck(payload.Statement, task.Type)+ if err != nil {+ return nil, err+ }+ case db.MySQL, db.TiDB:+ result, err = mysqlStatementTypeCheck(payload.Statement, payload.Charset, payload.Collation, task.Type)+ if err != nil {+ return nil, err+ }+ default:return nil, common.Errorf(common.Invalid, "invalid check statement type database type: %s", payload.DbType)}- stmts, err := parser.Parse(parser.Postgres, parser.Context{}, payload.Statement)+ if len(result) == 0 {+ result = append(result, api.TaskCheckResult{+ Status: api.TaskCheckStatusSuccess,+ Namespace: api.BBNamespace,+ Code: common.Ok.Int(),+ Title: "OK",+ Content: "",+ })+ }++ return result, nil+}++func mysqlStatementTypeCheck(statement string, charset string, collation string, taskType api.TaskType) (result []api.TaskCheckResult, err error) {+ p := tidbparser.New()++ // To support MySQL8 window function syntax.+ // See https://github.com/bytebase/bytebase/issues/175.+ p.EnableWindowFunc(true)++ stmts, _, err := p.Parse(statement, charset, collation)if err != nil {//nolint:nilerrreturn []api.TaskCheckResult{@@ -63,7 +96,58 @@ func (*TaskCheckStatementTypeExecutor) Run(ctx context.Context, server *Server,}, nil}- switch task.Type {+ switch taskType {+ case api.TaskDatabaseDataUpdate:+ for _, node := range stmts {+ _, isDML := node.(tidbast.DMLNode)+ _, isQuery := node.(*tidbast.SelectStmt)+ if !isDML || isQuery {+ result = append(result, api.TaskCheckResult{+ Status: api.TaskCheckStatusError,+ Namespace: api.BBNamespace,+ Code: common.TaskTypeNotDML.Int(),+ Title: "Data change can only run DML",+ Content: fmt.Sprintf("\"%s\" is not DML", node.Text()),+ })+ }+ }+ case api.TaskDatabaseSchemaUpdate, api.TaskDatabaseSchemaUpdateGhostSync:+ for _, node := range stmts {+ _, isDML := node.(tidbast.DMLNode)+ _, isExplain := node.(*tidbast.ExplainStmt)+ if isDML || isExplain {+ result = append(result, api.TaskCheckResult{+ Status: api.TaskCheckStatusError,+ Namespace: api.BBNamespace,+ Code: common.TaskTypeNotDDL.Int(),+ Title: "Alter schema can only run DDL",+ Content: fmt.Sprintf("\"%s\" is not DDL", node.Text()),+ })+ }+ }+ default:+ return nil, common.Errorf(common.Invalid, "invalid check statement type task type: %s", taskType)+ }++ return result, nil+}++func postgresqlStatementTypeCheck(statement string, taskType api.TaskType) (result []api.TaskCheckResult, err error) {+ stmts, err := parser.Parse(parser.Postgres, parser.Context{}, statement)+ if err != nil {+ //nolint:nilerr+ return []api.TaskCheckResult{+ {+ Status: api.TaskCheckStatusError,+ Namespace: api.AdvisorNamespace,+ Code: advisor.StatementSyntaxError.Int(),+ Title: "Syntax error",+ Content: err.Error(),+ },+ }, nil+ }++ switch taskType {case api.TaskDatabaseDataUpdate:for _, node := range stmts {if _, ok := node.(ast.DMLNode); !ok {@@ -92,17 +176,7 @@ func (*TaskCheckStatementTypeExecutor) Run(ctx context.Context, server *Server,}}default:- return nil, common.Errorf(common.Invalid, "invalid check statement type task type: %s", task.Type)- }-- if len(result) == 0 {- result = append(result, api.TaskCheckResult{- Status: api.TaskCheckStatusSuccess,- Namespace: api.BBNamespace,- Code: common.Ok.Int(),- Title: "OK",- Content: "",- })+ return nil, common.Errorf(common.Invalid, "invalid check statement type task type: %s", taskType)}return result, nildiff --git a/server/task_check_scheduler.go b/server/task_check_scheduler.goindex e3b586fa7f..bef97008af 100644--- a/server/task_check_scheduler.go+++ b/server/task_check_scheduler.go@@ -299,12 +299,17 @@ func (*TaskCheckScheduler) getStatement(task *api.Task) (string, error) {}}func (s *TaskCheckScheduler) scheduleStmtTypeTaskCheck(ctx context.Context, task *api.Task, creatorID int, skipIfAlreadyTerminated bool, database *api.Database, statement string) error {- if database.Instance.Engine != db.Postgres {+ switch database.Instance.Engine {+ case db.Postgres:+ case db.MySQL, db.TiDB:+ default:return nil}payload, err := json.Marshal(api.TaskCheckDatabaseStatementTypePayload{Statement: statement,DbType: database.Instance.Engine,+ Charset: database.CharacterSet,+ Collation: database.Collation,})if err != nil {return errors.Wrapf(err, "failed to marshal statement type payload: %v", task.Name)