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: 11188 (#11194)
Danny Xu13b84b15727e
diff --git a/backend/plugin/advisor/advisor.go b/backend/plugin/advisor/advisor.goindex 56d592f061..4df96d9b90 100644--- a/backend/plugin/advisor/advisor.go+++ b/backend/plugin/advisor/advisor.go@@ -275,8 +275,8 @@ const (// MySQLStatementJoinStrictColumnAttrs is an advisor type for MySQL statement strict column attrs(type, charset) in join.MySQLStatementJoinStrictColumnAttrs Type = "bb.plugin.advisor.mysql.statement.join-strict-column-attrs"- // MySQLStatementDisallowMixDML is an advisor type for MySQL disallow mix DML on same table.- MySQLStatementDisallowMixDML Type = "bb.plugin.advisor.mysql.statement.disallow-mix-dml"+ // MySQLStatementDisallowMixDDLDML is an advisor type for MySQL disallow mix DDL and DML.+ MySQLStatementDisallowMixDDLDML Type = "bb.plugin.advisor.mysql.statement.disallow-mix-ddl-dml"// MySQLStatementPriorBackupCheck is an advisor type for MySQL prior backup check.MySQLStatementPriorBackupCheck Type = "bb.plugin.advisor.mysql.statement.prior-backup-check"@@ -424,8 +424,8 @@ const (// PostgreSQLStatementCheckSetRoleVariable is an advisor type for PostgreSQL to check set role variable.PostgreSQLStatementCheckSetRoleVariable Type = "bb.plugin.advisor.postgresql.statement.check-set-role-variable"- // PostgreSQLStatementDisallowMixDML is an advisor type for PostgreSQL disallow mix DML on same table.- PostgreSQLStatementDisallowMixDML Type = "bb.plugin.advisor.postgresql.statement.disallow-mix-dml"+ // PostgreSQLStatementDisallowMixDDLDML is an advisor type for PostgreSQL disallow mix DDL and DML.+ PostgreSQLStatementDisallowMixDDLDML Type = "bb.plugin.advisor.postgresql.statement.disallow-mix-ddl-dml"// PostgreSQLStatementPriorBackupCheck is an advisor type for PostgreSQL do prior backup check.PostgreSQLStatementPriorBackupCheck Type = "bb.plugin.advisor.postgresql.statement.prior-backup-check"diff --git a/backend/plugin/advisor/code.go b/backend/plugin/advisor/code.goindex 9caf09c0e6..9673793e8a 100644--- a/backend/plugin/advisor/code.go+++ b/backend/plugin/advisor/code.go@@ -51,8 +51,8 @@ const (StatementUnwantedQueryPlanLevel Code = 224StatementWhereMaximumLogicalOperatorCount Code = 225StatementJoinColumnAttrsNotMatch Code = 226- StatementDisallowMixDML Code = 227- StatementMixDDLDML Code = 228+ StatementDisallowMixDDLDML Code = 227+ StatementPriorBackupCheck Code = 228// 301 ~ 399 naming error code// 301 table naming advisor error code.diff --git a/backend/plugin/advisor/config/sql-review.dev.yaml b/backend/plugin/advisor/config/sql-review.dev.yamlindex 35fca34cbe..20478ec32b 100644--- a/backend/plugin/advisor/config/sql-review.dev.yaml+++ b/backend/plugin/advisor/config/sql-review.dev.yaml@@ -100,7 +100,7 @@ ruleList:number: 10- type: statement.join-strict-column-attrslevel: WARNING- - type: statement.disallow-mix-dml+ - type: statement.disallow-mix-ddl-dmllevel: WARNING- type: statement.prior-backup-checklevel: ERRORdiff --git a/backend/plugin/advisor/config/sql-review.prod.yaml b/backend/plugin/advisor/config/sql-review.prod.yamlindex 48d48d02f7..ca99687045 100644--- a/backend/plugin/advisor/config/sql-review.prod.yaml+++ b/backend/plugin/advisor/config/sql-review.prod.yaml@@ -100,7 +100,7 @@ ruleList:number: 10- type: statement.join-strict-column-attrslevel: WARNING- - type: statement.disallow-mix-dml+ - type: statement.disallow-mix-ddl-dmllevel: WARNING- type: statement.prior-backup-checklevel: ERRORdiff --git a/backend/plugin/advisor/mysql/advisor_statement_disallow_mix_ddl_dml.go b/backend/plugin/advisor/mysql/advisor_statement_disallow_mix_ddl_dml.gonew file mode 100644index 0000000000..d3ed70a0d6--- /dev/null+++ b/backend/plugin/advisor/mysql/advisor_statement_disallow_mix_ddl_dml.go@@ -0,0 +1,93 @@+package mysql++import (+ "fmt"++ "github.com/antlr4-go/antlr/v4"+ "github.com/pkg/errors"++ "github.com/bytebase/bytebase/backend/plugin/advisor"+ mysqlparser "github.com/bytebase/bytebase/backend/plugin/parser/mysql"+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"+)++var (+ _ advisor.Advisor = (*StatementDisallowmixDDLDMLAdvisor)(nil)+)++func init() {+ advisor.Register(storepb.Engine_MYSQL, advisor.MySQLStatementDisallowMixDDLDML, &StatementDisallowmixDDLDMLAdvisor{})+}++type StatementDisallowmixDDLDMLAdvisor struct {+}++func (*StatementDisallowmixDDLDMLAdvisor) Check(ctx advisor.Context, _ string) ([]advisor.Advice, error) {+ stmtList, ok := ctx.AST.([]*mysqlparser.ParseResult)+ if !ok {+ return nil, errors.Errorf("failed to convert to mysql parse result")+ }++ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)+ if err != nil {+ return nil, err+ }+ title := string(ctx.Rule.Type)++ var adviceList []advisor.Advice+ var hasDDL, hasDML bool+ for _, stmt := range stmtList {+ checker := &mysqlparser.StatementTypeChecker{}+ antlr.ParseTreeWalkerDefault.Walk(checker, stmt.Tree)++ switch ctx.ChangeType {+ case storepb.PlanCheckRunConfig_DDL, storepb.PlanCheckRunConfig_SDL, storepb.PlanCheckRunConfig_DDL_GHOST:+ if checker.IsDML {+ adviceList = append(adviceList, advisor.Advice{+ Status: level,+ Title: title,+ Content: fmt.Sprintf("Alter schema can only run DDL, \"%s\" is not DDL", checker.Text),+ Code: advisor.StatementDisallowMixDDLDML,+ Line: stmt.BaseLine,+ })+ }+ case storepb.PlanCheckRunConfig_DML:+ if checker.IsDDL {+ adviceList = append(adviceList, advisor.Advice{+ Status: level,+ Title: title,+ Content: fmt.Sprintf("Data change can only run DML, \"%s\" is not DML", checker.Text),+ Code: advisor.StatementDisallowMixDDLDML,+ Line: stmt.BaseLine,+ })+ }+ }++ if checker.IsDDL {+ hasDDL = true+ }+ if checker.IsDML {+ hasDML = true+ }+ }++ if hasDDL && hasDML {+ adviceList = append(adviceList, advisor.Advice{+ Status: level,+ Title: title,+ Content: "Mixing DDL with DML is not allowed",+ Code: advisor.StatementDisallowMixDDLDML,+ })+ }++ if len(adviceList) == 0 {+ adviceList = append(adviceList, advisor.Advice{+ Status: advisor.Success,+ Code: advisor.Ok,+ Title: "OK",+ Content: "",+ })+ }++ return adviceList, nil+}diff --git a/backend/plugin/advisor/mysql/advisor_statement_disallow_mix_dml.go b/backend/plugin/advisor/mysql/advisor_statement_disallow_mix_dml.godeleted file mode 100644index 3ad5c820a1..0000000000--- a/backend/plugin/advisor/mysql/advisor_statement_disallow_mix_dml.go+++ /dev/null@@ -1,276 +0,0 @@-package mysql--import (- "fmt"- "strings"-- "github.com/antlr4-go/antlr/v4"- "github.com/pkg/errors"-- mysql "github.com/bytebase/mysql-parser"-- "github.com/bytebase/bytebase/backend/plugin/advisor"- mysqlparser "github.com/bytebase/bytebase/backend/plugin/parser/mysql"- storepb "github.com/bytebase/bytebase/proto/generated-go/store"-)--var (- _ advisor.Advisor = (*StatementDisallowMixDMLAdvisor)(nil)-)--func init() {- advisor.Register(storepb.Engine_MYSQL, advisor.MySQLStatementDisallowMixDML, &StatementDisallowMixDMLAdvisor{})-}--type StatementDisallowMixDMLAdvisor struct {-}--func (*StatementDisallowMixDMLAdvisor) Check(ctx advisor.Context, _ string) ([]advisor.Advice, error) {- stmtList, ok := ctx.AST.([]*mysqlparser.ParseResult)- if !ok {- return nil, errors.Errorf("failed to convert to mysql parse result")- }-- level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)- if err != nil {- return nil, err- }-- checker := &statementDisallowMixDMLChecker{- level: level,- title: string(ctx.Rule.Type),- dmlStatementCount: make(map[table]map[string]int),- }-- for _, stmt := range stmtList {- checker.baseLine = stmt.BaseLine- antlr.ParseTreeWalkerDefault.Walk(checker, stmt.Tree)- }-- for table, dmlCount := range checker.dmlStatementCount {- if len(dmlCount) > 1 {- content := "Found"- for _, t := range []string{"DELETE", "INSERT", "UPDATE"} {- count, ok := dmlCount[t]- if ok {- content += fmt.Sprintf(" %d %s,", count, t)- }- }- content = strings.TrimSuffix(content, ",")- content += fmt.Sprintf(" on table `%s`.`%s`, disallow mixing different types of DML statements", table.database, table.table)- checker.adviceList = append(checker.adviceList, advisor.Advice{- Status: checker.level,- Code: advisor.StatementDisallowMixDML,- Title: checker.title,- Content: content,- })- }- }-- if len(checker.adviceList) == 0 {- checker.adviceList = append(checker.adviceList, advisor.Advice{- Status: advisor.Success,- Code: advisor.Ok,- Title: "OK",- Content: "",- })- }- return checker.adviceList, nil-}--type statementDisallowMixDMLChecker struct {- *mysql.BaseMySQLParserListener-- baseLine int- adviceList []advisor.Advice- level advisor.Status- title string-- dmlStatementCount map[table]map[string]int-}--type table struct {- database string- table string-}--func (c *statementDisallowMixDMLChecker) EnterInsertStatement(ctx *mysql.InsertStatementContext) {- if !mysqlparser.IsTopMySQLRule(&ctx.BaseParserRuleContext) {- return- }- if ctx.TableRef() == nil {- return- }- databaseName, tableName := mysqlparser.NormalizeMySQLTableRef(ctx.TableRef())- table := table{- database: databaseName,- table: tableName,- }- if _, ok := c.dmlStatementCount[table]; !ok {- c.dmlStatementCount[table] = make(map[string]int)- }- c.dmlStatementCount[table]["INSERT"]++-}--func (c *statementDisallowMixDMLChecker) EnterUpdateStatement(ctx *mysql.UpdateStatementContext) {- if !mysqlparser.IsTopMySQLRule(&ctx.BaseParserRuleContext) {- return- }- var allTables []table- for _, tableRefCtx := range ctx.TableReferenceList().AllTableReference() {- tables, err := extractTableReference(tableRefCtx)- if err != nil {- c.adviceList = append(c.adviceList, advisor.Advice{- Status: c.level,- Code: advisor.Internal,- Title: c.title,- Content: fmt.Sprintf("Failed to extract table reference: %v", err),- Line: tableRefCtx.GetStart().GetLine() + c.baseLine,- })- continue- }- allTables = append(allTables, tables...)- }- for _, table := range allTables {- if _, ok := c.dmlStatementCount[table]; !ok {- c.dmlStatementCount[table] = make(map[string]int)- }- c.dmlStatementCount[table]["UPDATE"]++- }-}--func (c *statementDisallowMixDMLChecker) EnterDeleteStatement(ctx *mysql.DeleteStatementContext) {- if !mysqlparser.IsTopMySQLRule(&ctx.BaseParserRuleContext) {- return- }- var allTables []table- if ctx.TableRef() != nil {- tables, err := extractTableRef(ctx.TableRef())- if err != nil {- c.adviceList = append(c.adviceList, advisor.Advice{- Status: c.level,- Code: advisor.Internal,- Title: c.title,- Content: fmt.Sprintf("Failed to extract table reference: %v", err),- Line: ctx.GetStart().GetLine() + c.baseLine,- })- } else {- allTables = append(allTables, tables...)- }- }- if ctx.TableReferenceList() != nil {- tables, err := extractTableReferenceList(ctx.TableReferenceList())- if err != nil {- c.adviceList = append(c.adviceList, advisor.Advice{- Status: c.level,- Code: advisor.Internal,- Title: c.title,- Content: fmt.Sprintf("Failed to extract table reference: %v", err),- Line: ctx.GetStart().GetLine() + c.baseLine,- })- } else {- allTables = append(allTables, tables...)- }- }- for _, table := range allTables {- if _, ok := c.dmlStatementCount[table]; !ok {- c.dmlStatementCount[table] = make(map[string]int)- }- c.dmlStatementCount[table]["DELETE"]++- }-}--func extractTableReference(ctx mysql.ITableReferenceContext) ([]table, error) {- if ctx.TableFactor() == nil {- return nil, nil- }- res, err := extractTableFactor(ctx.TableFactor())- if err != nil {- return nil, err- }- for _, joinedTableCtx := range ctx.AllJoinedTable() {- tables, err := extractJoinedTable(joinedTableCtx)- if err != nil {- return nil, err- }- res = append(res, tables...)- }-- return res, nil-}--func extractTableRef(ctx mysql.ITableRefContext) ([]table, error) {- if ctx == nil {- return nil, nil- }- databaseName, tableName := mysqlparser.NormalizeMySQLTableRef(ctx)- return []table{- {- database: databaseName,- table: tableName,- },- }, nil-}--func extractTableReferenceList(ctx mysql.ITableReferenceListContext) ([]table, error) {- var res []table- for _, tableRefCtx := range ctx.AllTableReference() {- tables, err := extractTableReference(tableRefCtx)- if err != nil {- return nil, err- }- res = append(res, tables...)- }- return res, nil-}--func extractTableReferenceListParens(ctx mysql.ITableReferenceListParensContext) ([]table, error) {- if ctx.TableReferenceList() != nil {- return extractTableReferenceList(ctx.TableReferenceList())- }- if ctx.TableReferenceListParens() != nil {- return extractTableReferenceListParens(ctx.TableReferenceListParens())- }- return nil, nil-}--func extractTableFactor(ctx mysql.ITableFactorContext) ([]table, error) {- switch {- case ctx.SingleTable() != nil:- return extractSingleTable(ctx.SingleTable())- case ctx.SingleTableParens() != nil:- return extractSingleTableParens(ctx.SingleTableParens())- case ctx.DerivedTable() != nil:- return nil, nil- case ctx.TableReferenceListParens() != nil:- return extractTableReferenceListParens(ctx.TableReferenceListParens())- case ctx.TableFunction() != nil:- return nil, nil- default:- return nil, nil- }-}--func extractSingleTable(ctx mysql.ISingleTableContext) ([]table, error) {- return extractTableRef(ctx.TableRef())-}--func extractSingleTableParens(ctx mysql.ISingleTableParensContext) ([]table, error) {- if ctx.SingleTable() != nil {- return extractSingleTable(ctx.SingleTable())- }- if ctx.SingleTableParens() != nil {- return extractSingleTableParens(ctx.SingleTableParens())- }- return nil, nil-}--func extractJoinedTable(ctx mysql.IJoinedTableContext) ([]table, error) {- if ctx.TableFactor() != nil {- return extractTableFactor(ctx.TableFactor())- }- if ctx.TableReference() != nil {- return extractTableReference(ctx.TableReference())- }- return nil, nil-}diff --git a/backend/plugin/advisor/mysql/advisor_statement_prior_backup_check.go b/backend/plugin/advisor/mysql/advisor_statement_prior_backup_check.goindex efa51b747a..45c855b4d5 100644--- a/backend/plugin/advisor/mysql/advisor_statement_prior_backup_check.go+++ b/backend/plugin/advisor/mysql/advisor_statement_prior_backup_check.go@@ -57,7 +57,7 @@ func (*StatementPriorBackupCheckAdvisor) Check(ctx advisor.Context, _ string) ([Status: level,Title: title,Content: "Prior backup cannot deal with mixed DDL and DML statements",- Code: advisor.StatementMixDDLDML,+ Code: advisor.StatementPriorBackupCheck,Line: stmt.BaseLine,})}diff --git a/backend/plugin/advisor/mysql/mysql_rules_test.go b/backend/plugin/advisor/mysql/mysql_rules_test.goindex 1b4936dd64..17d90ebaf8 100644--- a/backend/plugin/advisor/mysql/mysql_rules_test.go+++ b/backend/plugin/advisor/mysql/mysql_rules_test.go@@ -120,7 +120,7 @@ func TestMySQLRules(t *testing.T) {// advisor.SchemaRuleColumnRequireDefault enforce the column default.advisor.SchemaRuleColumnRequireDefault,// advisor.SchemaRuleColumnDisallowMixDML disallows mixing different types of DML statements.- advisor.SchemaRuleStatementDisallowMixDML,+ advisor.SchemaRuleStatementDisallowMixDDLDML,// Index related rules.// advisor.SchemaRuleIndexNoDuplicateColumn require the index no duplicate column.diff --git a/backend/plugin/advisor/mysql/test/statement_disallow_mix_ddl_dml.yaml b/backend/plugin/advisor/mysql/test/statement_disallow_mix_ddl_dml.yamlnew file mode 100644index 0000000000..62469211b4--- /dev/null+++ b/backend/plugin/advisor/mysql/test/statement_disallow_mix_ddl_dml.yaml@@ -0,0 +1,27 @@+- statement: DELETE FROM tech_book WHERE a > 1;+ want:+ - status: SUCCESS+ code: 0+ title: OK+ content: ""+ line: 0+ column: 0+ details: ""+- statement: UPDATE tech_book SET id = 1;+ want:+ - status: SUCCESS+ code: 0+ title: OK+ content: ""+ line: 0+ column: 0+ details: ""+- statement: ALTER TABLE tech_book ADD COLUMN author TEXT; UPDATE tech_book SET id = 1;DELETE FROM tech_book WHERE a > 1;+ want:+ - status: WARN+ code: 227+ title: statement.disallow-mix-ddl-dml+ content: Mixing DDL with DML is not allowed+ line: 0+ column: 0+ details: ""\ No newline at end of filediff --git a/backend/plugin/advisor/mysql/test/statement_disallow_mix_dml.yaml b/backend/plugin/advisor/mysql/test/statement_prior_backup_check.yamlsimilarity index 93%rename from backend/plugin/advisor/mysql/test/statement_disallow_mix_dml.yamlrename to backend/plugin/advisor/mysql/test/statement_prior_backup_check.yamlindex a082d839de..328b03fe13 100644--- a/backend/plugin/advisor/mysql/test/statement_disallow_mix_dml.yaml+++ b/backend/plugin/advisor/mysql/test/statement_prior_backup_check.yaml@@ -20,7 +20,7 @@want:- status: WARNcode: 227- title: statement.disallow-mix-dml+ title: statement.prior-backup-checkcontent: Found 1 DELETE, 1 UPDATE on table ``.`tech_book`, disallow mixing different types of DML statementsline: 0column: 0diff --git a/backend/plugin/advisor/pg/advisor_statement_disallow_mix_ddl_dml.go b/backend/plugin/advisor/pg/advisor_statement_disallow_mix_ddl_dml.gonew file mode 100644index 0000000000..b4acd3dfc6--- /dev/null+++ b/backend/plugin/advisor/pg/advisor_statement_disallow_mix_ddl_dml.go@@ -0,0 +1,102 @@+package pg++// Framework code is generated by the generator.++import (+ "fmt"++ "github.com/pkg/errors"++ "github.com/bytebase/bytebase/backend/plugin/advisor"+ "github.com/bytebase/bytebase/backend/plugin/parser/sql/ast"+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"+)++var (+ _ advisor.Advisor = (*StatementDisallowMixDdlDmlAdvisor)(nil)+)++func init() {+ advisor.Register(storepb.Engine_POSTGRES, advisor.PostgreSQLStatementDisallowMixDDLDML, &StatementDisallowMixDdlDmlAdvisor{})+}++// StatementDisallowMixDdlDmlAdvisor is the advisor checking for disallow mix DDL and DML.+type StatementDisallowMixDdlDmlAdvisor struct {+}++// Check checks for disallow mix DDL and DML.+func (*StatementDisallowMixDdlDmlAdvisor) Check(ctx advisor.Context, _ string) ([]advisor.Advice, error) {+ stmtList, ok := ctx.AST.([]ast.Node)+ if !ok {+ return nil, errors.Errorf("failed to convert to Node")+ }++ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)+ if err != nil {+ return nil, err+ }+ title := string(ctx.Rule.Type)++ var adviceList []advisor.Advice+ var hasDDL, hasDML bool+ for _, stmt := range stmtList {+ var isDDL, isDML bool+ if _, ok := stmt.(ast.DDLNode); ok {+ isDDL = true+ }+ if _, ok := stmt.(ast.DMLNode); ok {+ isDML = true+ }+ switch ctx.ChangeType {+ case storepb.PlanCheckRunConfig_DDL, storepb.PlanCheckRunConfig_SDL, storepb.PlanCheckRunConfig_DDL_GHOST:+ if isDML {+ adviceList = append(adviceList, advisor.Advice{+ Status: level,+ Title: title,+ Content: fmt.Sprintf("Alter schema can only run DDL, \"%s\" is not DDL", stmt.Text()),+ Code: advisor.StatementDisallowMixDDLDML,+ Line: stmt.LastLine(),+ })+ }+ case storepb.PlanCheckRunConfig_DML:+ if isDDL {+ adviceList = append(adviceList, advisor.Advice{+ Status: level,+ Title: title,+ Content: fmt.Sprintf("Data change can only run DML, \"%s\" is not DML", stmt.Text()),+ Code: advisor.StatementDisallowMixDDLDML,+ Line: stmt.LastLine(),+ })+ }+ }+ if isDDL {+ hasDDL = true+ }+ if isDML {+ hasDML = true+ }+ if hasDDL && hasDML {+ break+ }+ }++ if hasDDL && hasDML {+ adviceList = append(adviceList, advisor.Advice{+ Status: level,+ Title: title,+ Content: "Mixing DDL with DML is not allowed",+ Code: advisor.StatementDisallowMixDDLDML,+ })+ }++ if len(adviceList) == 0 {+ adviceList = append(adviceList, advisor.Advice{+ Status: advisor.Success,+ Code: advisor.Ok,+ Title: "OK",+ Content: "",+ })+ }++ return adviceList, nil+}diff --git a/backend/plugin/advisor/pg/advisor_statement_disallow_mix_dml.go b/backend/plugin/advisor/pg/advisor_statement_disallow_mix_dml.godeleted file mode 100644index 5c50ee4fe9..0000000000--- a/backend/plugin/advisor/pg/advisor_statement_disallow_mix_dml.go+++ /dev/null@@ -1,71 +0,0 @@-package pg--// Framework code is generated by the generator.--import (- "github.com/pkg/errors"-- "github.com/bytebase/bytebase/backend/plugin/advisor"- "github.com/bytebase/bytebase/backend/plugin/parser/sql/ast"- storepb "github.com/bytebase/bytebase/proto/generated-go/store"-)--var (- _ advisor.Advisor = (*StatementDisallowMixDmlAdvisor)(nil)- _ ast.Visitor = (*statementDisallowMixDmlChecker)(nil)-)--func init() {- advisor.Register(storepb.Engine_POSTGRES, advisor.PostgreSQLStatementDisallowMixDML, &StatementDisallowMixDmlAdvisor{})-}--// StatementDisallowMixDmlAdvisor is the advisor checking for disallow mix DML on same table.-type StatementDisallowMixDmlAdvisor struct {-}--// Check checks for disallow mix DML on same table.-func (*StatementDisallowMixDmlAdvisor) Check(ctx advisor.Context, _ string) ([]advisor.Advice, error) {- // TODO(p0ny): implement it.- stmtList, ok := ctx.AST.([]ast.Node)- if !ok {- return nil, errors.Errorf("failed to convert to Node")- }-- level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)- if err != nil {- return nil, err- }- checker := &statementDisallowMixDmlChecker{- level: level,- title: string(ctx.Rule.Type),- }-- for _, stmt := range stmtList {- ast.Walk(checker, stmt)- }-- if len(checker.adviceList) == 0 {- checker.adviceList = append(checker.adviceList, advisor.Advice{- Status: advisor.Success,- Code: advisor.Ok,- Title: "OK",- Content: "",- })- }- return checker.adviceList, nil-}--type statementDisallowMixDmlChecker struct {- adviceList []advisor.Advice- level advisor.Status- title string-}--// Visit implements ast.Visitor interface.-func (checker *statementDisallowMixDmlChecker) Visit(_ ast.Node) ast.Visitor {- // TODO: implement it- // switch node := in.(type) {- // }-- return checker-}diff --git a/backend/plugin/advisor/pg/advisor_statement_prior_backup_check.go b/backend/plugin/advisor/pg/advisor_statement_prior_backup_check.goindex 961a167fae..b56e578485 100644--- a/backend/plugin/advisor/pg/advisor_statement_prior_backup_check.go+++ b/backend/plugin/advisor/pg/advisor_statement_prior_backup_check.go@@ -60,7 +60,7 @@ func (*StatementPriorBackupCheckAdvisor) Check(ctx advisor.Context, _ string) ([Status: level,Title: title,Content: fmt.Sprintf("Data change can only run DML, \"%s\" is not DML", stmt.Text()),- Code: advisor.StatementMixDDLDML,+ Code: advisor.StatementPriorBackupCheck,Line: stmt.LastLine(),})}diff --git a/backend/plugin/advisor/pg/test/statement_disallow_mix_ddl_dml.yaml b/backend/plugin/advisor/pg/test/statement_disallow_mix_ddl_dml.yamlnew file mode 100644index 0000000000..0ddb8406dc--- /dev/null+++ b/backend/plugin/advisor/pg/test/statement_disallow_mix_ddl_dml.yaml@@ -0,0 +1,27 @@+- statement: DELETE FROM tech_book WHERE a > 1;+ want:+ - status: SUCCESS+ code: 0+ title: OK+ content: ""+ line: 0+ column: 0+ details: ""+- statement: UPDATE tech_book SET id = 1;+ want:+ - status: SUCCESS+ code: 0+ title: OK+ content: ""+ line: 0+ column: 0+ details: ""+- statement: ALTER TABLE tech_book ADD COLUMN author TEXT; UPDATE tech_book SET id = 1;DELETE FROM tech_book WHERE a > 1;+ want:+ - status: WARN+ code: 228+ title: statement.disallow-mix-ddl-dml+ content: Mixing DDL with DML is not allowed+ line: 0+ column: 0+ details: ""\ No newline at end of filediff --git a/backend/plugin/advisor/sql_review.go b/backend/plugin/advisor/sql_review.goindex e75e929978..863daced87 100644--- a/backend/plugin/advisor/sql_review.go+++ b/backend/plugin/advisor/sql_review.go@@ -121,8 +121,8 @@ const (SchemaRuleStatementMaximumStatementsInTransaction = "statement.maximum-statements-in-transaction"// SchemaRuleStatementJoinStrictColumnAttrs enforce the join strict column attributes.SchemaRuleStatementJoinStrictColumnAttrs = "statement.join-strict-column-attrs"- // SchemaRuleStatementDisallowMixDML disallow mix DML on the same table.- SchemaRuleStatementDisallowMixDML = "statement.disallow-mix-dml"+ // SchemaRuleStatementDisallowMixDDLDML disallow mix DDL and DML on the same table.+ SchemaRuleStatementDisallowMixDDLDML = "statement.disallow-mix-ddl-dml"// SchemaRuleStatementPriorBackupCheck checks for prior backup.SchemaRuleStatementPriorBackupCheck = "statement.prior-backup-check"@@ -1429,9 +1429,12 @@ func getAdvisorTypeByRule(ruleType SQLReviewRuleType, engine storepb.Engine) (Tyif engine == storepb.Engine_MYSQL {return MySQLStatementDisallowUsingTemporary, nil}- case SchemaRuleStatementDisallowMixDML:- if engine == storepb.Engine_MYSQL || engine == storepb.Engine_TIDB {- return MySQLStatementDisallowMixDML, nil+ case SchemaRuleStatementDisallowMixDDLDML:+ switch engine {+ case storepb.Engine_MYSQL, storepb.Engine_TIDB:+ return MySQLStatementDisallowMixDDLDML, nil+ case storepb.Engine_POSTGRES:+ return PostgreSQLStatementDisallowMixDDLDML, nil}case SchemaRuleStatementPriorBackupCheck:switch engine {diff --git a/backend/plugin/advisor/tidb/advisor_statement_disallow_mix_ddl_dml.go b/backend/plugin/advisor/tidb/advisor_statement_disallow_mix_ddl_dml.gonew file mode 100644index 0000000000..b43982cd1f--- /dev/null+++ b/backend/plugin/advisor/tidb/advisor_statement_disallow_mix_ddl_dml.go@@ -0,0 +1,101 @@+package tidb++import (+ "fmt"++ "github.com/pingcap/tidb/pkg/parser/ast"+ "github.com/pkg/errors"++ "github.com/bytebase/bytebase/backend/plugin/advisor"+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"+)++var (+ _ advisor.Advisor = (*StatementDisallowMixDDLDMLAdvisor)(nil)+)++func init() {+ advisor.Register(storepb.Engine_TIDB, advisor.MySQLStatementDisallowMixDDLDML, &StatementDisallowMixDDLDMLAdvisor{})+}++// StatementDisallowMixDDLDMLAdvisor is the advisor checking for no mixed DDL and DML.+type StatementDisallowMixDDLDMLAdvisor struct {+}++// Check checks for no mixed DDL and DML.+func (*StatementDisallowMixDDLDMLAdvisor) Check(ctx advisor.Context, _ string) ([]advisor.Advice, error) {+ root, ok := ctx.AST.([]ast.StmtNode)+ if !ok {+ return nil, errors.Errorf("failed to convert to StmtNode")+ }++ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)+ if err != nil {+ return nil, err+ }+ title := string(ctx.Rule.Type)++ var adviceList []advisor.Advice+ var hasDDL, hasDML bool+ for _, stmtNode := range root {+ var isDDL, isDML bool+ if _, ok := stmtNode.(ast.DDLNode); ok {+ isDDL = true+ }+ if _, ok := stmtNode.(ast.DMLNode); ok {+ isDML = true+ }++ switch ctx.ChangeType {+ case storepb.PlanCheckRunConfig_DDL, storepb.PlanCheckRunConfig_SDL, storepb.PlanCheckRunConfig_DDL_GHOST:+ if isDML {+ adviceList = append(adviceList, advisor.Advice{+ Status: level,+ Title: title,+ Content: fmt.Sprintf("Alter schema can only run DDL, \"%s\" is not DDL", stmtNode.Text()),+ Code: advisor.StatementDisallowMixDDLDML,+ Line: stmtNode.OriginTextPosition(),+ })+ }+ case storepb.PlanCheckRunConfig_DML:+ if isDDL {+ adviceList = append(adviceList, advisor.Advice{+ Status: level,+ Title: title,+ Content: fmt.Sprintf("Data change can only run DML, \"%s\" is not DML", stmtNode.Text()),+ Code: advisor.StatementDisallowMixDDLDML,+ Line: stmtNode.OriginTextPosition(),+ })+ }+ }+ if isDDL {+ hasDDL = true+ }+ if isDML {+ hasDML = true+ }+ if hasDDL && hasDML {+ break+ }+ }++ if hasDDL && hasDML {+ adviceList = append(adviceList, advisor.Advice{+ Status: level,+ Title: title,+ Content: "Mixing DDL with DML is not allowed",+ Code: advisor.StatementDisallowMixDDLDML,+ })+ }++ if len(adviceList) == 0 {+ adviceList = append(adviceList, advisor.Advice{+ Status: advisor.Success,+ Code: advisor.Ok,+ Title: "OK",+ Content: "",+ })+ }++ return adviceList, nil+}diff --git a/backend/plugin/advisor/tidb/advisor_statement_disallow_mix_dml.go b/backend/plugin/advisor/tidb/advisor_statement_disallow_mix_dml.godeleted file mode 100644index b189343dc3..0000000000--- a/backend/plugin/advisor/tidb/advisor_statement_disallow_mix_dml.go+++ /dev/null@@ -1,189 +0,0 @@-package tidb--import (- "fmt"- "strings"-- "github.com/pingcap/tidb/pkg/parser/ast"- "github.com/pkg/errors"-- "github.com/bytebase/bytebase/backend/plugin/advisor"- storepb "github.com/bytebase/bytebase/proto/generated-go/store"-)--var (- _ advisor.Advisor = (*StatementDisallowMixDMLAdvisor)(nil)-)--func init() {- advisor.Register(storepb.Engine_TIDB, advisor.MySQLStatementDisallowMixDML, &StatementDisallowMixDMLAdvisor{})-}--// StatementDisallowmixDDLDMLAdvisor is the advisor checking for no multiple DMLs for the same table.-type StatementDisallowMixDMLAdvisor struct {-}--// Check checks for no multiple DMLs for the same table.-func (*StatementDisallowMixDMLAdvisor) Check(ctx advisor.Context, _ string) ([]advisor.Advice, error) {- root, ok := ctx.AST.([]ast.StmtNode)- if !ok {- return nil, errors.Errorf("failed to convert to StmtNode")- }-- level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)- if err != nil {- return nil, err- }- checker := &statementDisallowMixDMLChecker{- level: level,- title: string(ctx.Rule.Type),- dmlStatementCount: make(map[table]map[string]int),- }- for _, stmtNode := range root {- checker.text = stmtNode.Text()- checker.line = stmtNode.OriginTextPosition()- if err := checker.extractNode(stmtNode); err != nil {- checker.adviceList = append(checker.adviceList, advisor.Advice{- Status: checker.level,- Code: advisor.Internal,- Title: checker.title,- Content: fmt.Sprintf("Failed to extract node, error: %s", err),- Line: checker.line,- })- }- }-- for table, dmlCount := range checker.dmlStatementCount {- if len(dmlCount) > 1 {- content := "Found"- for _, t := range []string{"DELETE", "INSERT", "UPDATE"} {- count, ok := dmlCount[t]- if ok {- content += fmt.Sprintf(" %d %s,", count, t)- }- }- content = strings.TrimSuffix(content, ",")- content += fmt.Sprintf(" on table `%s`.`%s`, disallow mixing different types of DML statements", table.database, table.table)- checker.adviceList = append(checker.adviceList, advisor.Advice{- Status: checker.level,- Code: advisor.StatementDisallowMixDML,- Title: checker.title,- Content: content,- })- }- }-- if len(checker.adviceList) == 0 {- checker.adviceList = append(checker.adviceList, advisor.Advice{- Status: advisor.Success,- Code: advisor.Ok,- Title: "OK",- Content: "",- })- }- return checker.adviceList, nil-}--type statementDisallowMixDMLChecker struct {- adviceList []advisor.Advice- level advisor.Status- title string- text string- line int-- dmlStatementCount map[table]map[string]int-}--type table struct {- database string- table string-}--func (c *statementDisallowMixDMLChecker) extractNode(n ast.Node) error {- if n == nil {- return nil- }- var tables []table- var err error- var dmlType string- switch n := n.(type) {- case *ast.InsertStmt:- tables, err = extractJoin(n.Table.TableRefs)- dmlType = "INSERT"- case *ast.DeleteStmt:- tables, err = extractTableRefs(n.TableRefs)- dmlType = "DELETE"- case *ast.UpdateStmt:- tables, err = extractTableRefs(n.TableRefs)- dmlType = "UPDATE"- default:- return nil- }- if err != nil {- return errors.Wrapf(err, "failed to extract table reference")- }- for _, t := range tables {- if _, ok := c.dmlStatementCount[t]; !ok {- c.dmlStatementCount[t] = make(map[string]int)- }- c.dmlStatementCount[t][dmlType]++- }- return nil-}--func extractResultSetNode(n ast.ResultSetNode) ([]table, error) {- if n == nil {- return nil, nil- }- switch n := n.(type) {- case *ast.SelectStmt:- return nil, nil- case *ast.SubqueryExpr:- return nil, nil- case *ast.TableSource:- return extractTableSource(n)- case *ast.TableName:- return extractTableName(n)- case *ast.Join:- return extractJoin(n)- case *ast.SetOprStmt:- return nil, nil- }- return nil, nil-}--func extractTableRefs(n *ast.TableRefsClause) ([]table, error) {- return extractJoin(n.TableRefs)-}--func extractJoin(n *ast.Join) ([]table, error) {- l, err := extractResultSetNode(n.Left)- if err != nil {- return nil, errors.Wrapf(err, "failed to extract left node in join")- }- r, err := extractResultSetNode(n.Right)- if err != nil {- return nil, errors.Wrapf(err, "failed to extract right node in join")- }- l = append(l, r...)- return l, nil-}--func extractTableSource(n *ast.TableSource) ([]table, error) {- if n == nil {- return nil, nil- }- return extractResultSetNode(n.Source)-}--func extractTableName(n *ast.TableName) ([]table, error) {- if n == nil {- return nil, nil- }- return []table{- {- table: n.Name.O,- database: n.Schema.O,- },- }, nil-}diff --git a/backend/plugin/advisor/tidb/advisor_statement_prior_backup_check.go b/backend/plugin/advisor/tidb/advisor_statement_prior_backup_check.goindex 34eab438b6..6b083b57aa 100644--- a/backend/plugin/advisor/tidb/advisor_statement_prior_backup_check.go+++ b/backend/plugin/advisor/tidb/advisor_statement_prior_backup_check.go@@ -60,7 +60,7 @@ func (*StatementPriorBackupCheckAdvisor) Check(ctx advisor.Context, _ string) ([Status: level,Title: title,Content: "Prior backup cannot deal with mixed DDL and DML statements",- Code: advisor.StatementMixDDLDML,+ Code: advisor.StatementPriorBackupCheck,Line: stmtNode.OriginTextPosition(),})}diff --git a/backend/plugin/advisor/tidb/test/statement_disallow_mix_ddl_dml.yaml b/backend/plugin/advisor/tidb/test/statement_disallow_mix_ddl_dml.yamlnew file mode 100644index 0000000000..0ddb8406dc--- /dev/null+++ b/backend/plugin/advisor/tidb/test/statement_disallow_mix_ddl_dml.yaml@@ -0,0 +1,27 @@+- statement: DELETE FROM tech_book WHERE a > 1;+ want:+ - status: SUCCESS+ code: 0+ title: OK+ content: ""+ line: 0+ column: 0+ details: ""+- statement: UPDATE tech_book SET id = 1;+ want:+ - status: SUCCESS+ code: 0+ title: OK+ content: ""+ line: 0+ column: 0+ details: ""+- statement: ALTER TABLE tech_book ADD COLUMN author TEXT; UPDATE tech_book SET id = 1;DELETE FROM tech_book WHERE a > 1;+ want:+ - status: WARN+ code: 228+ title: statement.disallow-mix-ddl-dml+ content: Mixing DDL with DML is not allowed+ line: 0+ column: 0+ details: ""\ No newline at end of filediff --git a/backend/plugin/advisor/utils_for_tests.go b/backend/plugin/advisor/utils_for_tests.goindex 47593ce20a..3eeba65745 100644--- a/backend/plugin/advisor/utils_for_tests.go+++ b/backend/plugin/advisor/utils_for_tests.go@@ -365,7 +365,7 @@ func SetDefaultSQLReviewRulePayload(ruleTp SQLReviewRuleType, dbType storepb.EngSchemaRuleStatementCreateSpecifySchema,SchemaRuleStatementCheckSetRoleVariable,SchemaRuleStatementWhereDisallowUsingFunction,- SchemaRuleStatementDisallowMixDML,+ SchemaRuleStatementDisallowMixDDLDML,SchemaRuleStatementPriorBackupCheck,SchemaRuleStatementJoinStrictColumnAttrs,SchemaRuleTableDisallowSetCharset:diff --git a/frontend/src/locales/sql-review/en-US.json b/frontend/src/locales/sql-review/en-US.jsonindex 59aae3ea72..6ee093c049 100644--- a/frontend/src/locales/sql-review/en-US.json+++ b/frontend/src/locales/sql-review/en-US.json@@ -461,9 +461,9 @@"title": "Fields to be joined must have identical data types, character sets","description": "If the data types, character sets of the join columns are not identical, the database may not be able to correctly identify matching rows, leading to inaccurate or incomplete results."},- "statement-disallow-mix-dml": {- "title": "Disallow DMLs on the same table",- "description": "Performing concurrent data modifications on a table can lead to challenges in accurately identifying the impacted rows. This consequently complicates the process of creating a precise backup of the affected data."+ "statement-disallow-mix-ddl-dml": {+ "title": "Disallow mixing DDL and DML",+ "description": "For optimal performance and data integrity, avoid combining DDL and DML statements within the same script."},"statement-prior-backup-check": {"title": "Check for prior backup before data change",diff --git a/frontend/src/locales/sql-review/es-ES.json b/frontend/src/locales/sql-review/es-ES.jsonindex c8f6d3c021..b86d65b115 100644--- a/frontend/src/locales/sql-review/es-ES.json+++ b/frontend/src/locales/sql-review/es-ES.json@@ -461,9 +461,9 @@"title": "Los campos a unir deben tener tipos de datos y conjuntos de caracteres idénticos","description": "Si los tipos de datos y los juegos de caracteres de las columnas de unión no son idénticos, es posible que la base de datos no pueda identificar correctamente las filas coincidentes, lo que dará lugar a resultados inexactos o incompletos."},- "statement-disallow-mix-dml": {- "title": "Prohibir DML en la misma tabla",- "description": "La realización de modificaciones concurrentes de datos en una tabla puede generar dificultades para identificar con precisión las filas afectadas. En consecuencia, esto complica el proceso de crear una copia de seguridad precisa de los datos modificados."+ "statement-disallow-mix-ddl-dml": {+ "title": "No se permite mezclar DDL y DML",+ "description": "Para un rendimiento óptimo e integridad de los datos, evite combinar sentencias DDL y DML dentro del mismo script."},"statement-prior-backup-check": {"title": "Verificar la existencia de una copia de seguridad previa antes de cambiar los datos",diff --git a/frontend/src/locales/sql-review/ja-JP.json b/frontend/src/locales/sql-review/ja-JP.jsonindex b3b7f1be57..f652eb12bc 100644--- a/frontend/src/locales/sql-review/ja-JP.json+++ b/frontend/src/locales/sql-review/ja-JP.json@@ -461,9 +461,9 @@"title": "ジョインするフィールドは、データ型と文字セットが一致している必要があります","description": "加入カラムのデータ型、文字セットが一致しないと、データベースは一致する行を正しく識別できず、不正確または不完全な結果が生じるおそれがあります。"},- "statement-disallow-mix-dml": {- "title": "同じテーブルに対する DML 操作を禁止する",- "description": "テーブルに対する同時データ更新を行うと、影響を受ける行を正確に特定することが困難になり、結果的に、影響を受けたデータの正確なバックアップを作成するプロセスが複雑になります。"+ "statement-disallow-mix-ddl-dml": {+ "title": "DDL と DML の混在を禁止する",+ "description": "最適なパフォーマンスとデータの整合性を保つために、同じスクリプト内で DDL ステートメントと DML ステートメントを組み合わせることは避けてください。"},"statement-prior-backup-check": {"title": "データ変更前のバックアップの確認",diff --git a/frontend/src/locales/sql-review/vi-VN.json b/frontend/src/locales/sql-review/vi-VN.jsonindex 52251d20d3..3dbfa096d2 100644--- a/frontend/src/locales/sql-review/vi-VN.json+++ b/frontend/src/locales/sql-review/vi-VN.json@@ -461,9 +461,9 @@"title": "Các trường cần ghép phải có cùng kiểu dữ liệu và bộ ký tự","description": "Nếu kiểu dữ liệu, bảng mã của các cột dùng để ghép (join) không giống nhau, cơ sở dữ liệu có thể không xác định chính xác các hàng khớp nhau, dẫn đến kết quả không chính xác hoặc không đầy đủ."},- "statement-disallow-mix-dml": {- "title": "Chặn các truy vấn DML trên cùng một bảng",- "description": "Ch thực hiện các sửa đổi dữ liệu đồng thời trên một bảng có thể dẫn đến những thách thức trong việc xác định chính xác các hàng bị ảnh hưởng. Điều này do đó làm phức tạp quá trình tạo bản sao lưu chính xác của dữ liệu bị ảnh hưởng."+ "statement-disallow-mix-ddl-dml": {+ "title": "Không nên trộn lẫn DDL và DML",+ "description": "Chú ý để đạt hiệu suất tối ưu và tính toàn vẹn dữ liệu, tránh kết hợp các câu lệnh DDL và DML trong cùng một tập lệnh."},"statement-prior-backup-check": {"title": "Kiểm tra sao lưu trước khi thay đổi dữ liệu",diff --git a/frontend/src/locales/sql-review/zh-CN.json b/frontend/src/locales/sql-review/zh-CN.jsonindex 22fbd9120a..2131a5783a 100644--- a/frontend/src/locales/sql-review/zh-CN.json+++ b/frontend/src/locales/sql-review/zh-CN.json@@ -461,9 +461,9 @@"title": "要进行连接的字段必须具有相同的数据类型和字符集。","description": "如果连接列的数据类型、字符集不一致,数据库可能无法正确识别匹配的行,从而导致结果不准确或不完整。"},- "statement-disallow-mix-dml": {- "title": "禁止在同一张表上进行多个 DML 操作",- "description": "对表格进行并发数据修改可能会给准确识别受影响的行带来挑战。 因此,这会使创建受影响数据的精确备份过程变得复杂。"+ "statement-disallow-mix-ddl-dml": {+ "title": "禁止混合 DDL 和 DML 操作",+ "description": "为了获得最佳性能和数据完整性,请避免在同一个脚本中混合使用 DDL 和 DML 语句。"},"statement-prior-backup-check": {"title": "在数据更改前检查先前的备份",diff --git a/frontend/src/types/sql-review-schema.yaml b/frontend/src/types/sql-review-schema.yamlindex 065ee0ef54..1480923449 100644--- a/frontend/src/types/sql-review-schema.yaml+++ b/frontend/src/types/sql-review-schema.yaml@@ -297,10 +297,11 @@ ruleList:category: STATEMENTengineList:- MYSQL- - type: statement.disallow-mix-dml+ - type: statement.disallow-mix-ddl-dmlcategory: STATEMENTengineList:- MYSQL+ - POSTGRES- TIDB- type: statement.prior-backup-checkcategory: STATEMENT