Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
chore(sql-review): add disallow create event for MySQL (#10861)
boojack17d5f86cd72f
diff --git a/backend/plugin/advisor/advisor.go b/backend/plugin/advisor/advisor.goindex cc259225d3..df0efae530 100644--- a/backend/plugin/advisor/advisor.go+++ b/backend/plugin/advisor/advisor.go@@ -232,6 +232,8 @@ const (// MySQLDisallowProcedure is an advisor type for MySQL disallow procedure.MySQLDisallowProcedure Type = "bb.plugin.advisor.mysql.disallow-procedure"+ // MySQLEventDisallowCreate is an advisor type for MySQL disallow create event.+ MySQLEventDisallowCreate Type = "bb.plugin.advisor.mysql.event.disallow-create"// PostgreSQL Advisor.diff --git a/backend/plugin/advisor/catalog/walk_through_for_mysql.go b/backend/plugin/advisor/catalog/walk_through_for_mysql.goindex 7ec8441d64..0965661e0d 100644--- a/backend/plugin/advisor/catalog/walk_through_for_mysql.go+++ b/backend/plugin/advisor/catalog/walk_through_for_mysql.go@@ -563,6 +563,14 @@ func (*mysqlListener) EnterCreateProcedure(ctx *mysql.CreateProcedureContext) {if ctx.ProcedureName() == nil {return}+ // Skip other checks for now.+}++func (*mysqlListener) EnterCreateEvent(ctx *mysql.CreateEventContext) {+ if ctx.EventName() == nil {+ return+ }+ // Skip other checks for now.}func (d *DatabaseState) mysqlTargetDatabase(renamePair mysql.IRenamePairContext) string {diff --git a/backend/plugin/advisor/code.go b/backend/plugin/advisor/code.goindex 6db8b2448b..74cc477477 100644--- a/backend/plugin/advisor/code.go+++ b/backend/plugin/advisor/code.go@@ -146,6 +146,9 @@ const (// 1401 ~ 1499 procedure error code.DisallowProcedure Code = 1401++ // 1501 ~ 1599 event error code.+ DisallowEvent Code = 1501)// Int returns the int type of code.diff --git a/backend/plugin/advisor/config/sql-review.dev.yaml b/backend/plugin/advisor/config/sql-review.dev.yamlindex 0c8ece305d..0d9effa22c 100644--- a/backend/plugin/advisor/config/sql-review.dev.yaml+++ b/backend/plugin/advisor/config/sql-review.dev.yaml@@ -215,3 +215,5 @@ ruleList:number: 64- type: system.procedure.disallowlevel: ERROR+ - type: system.event.disallow+ level: WARNINGdiff --git a/backend/plugin/advisor/config/sql-review.prod.yaml b/backend/plugin/advisor/config/sql-review.prod.yamlindex ba3cdd2742..9f54542c1d 100644--- a/backend/plugin/advisor/config/sql-review.prod.yaml+++ b/backend/plugin/advisor/config/sql-review.prod.yaml@@ -215,3 +215,5 @@ ruleList:number: 64- type: system.procedure.disallowlevel: ERROR+ - type: system.event.disallow+ level: WARNINGdiff --git a/backend/plugin/advisor/mysql/advisor_event_disallow_create.go b/backend/plugin/advisor/mysql/advisor_event_disallow_create.gonew file mode 100644index 0000000000..47755140c4--- /dev/null+++ b/backend/plugin/advisor/mysql/advisor_event_disallow_create.go@@ -0,0 +1,89 @@+package mysql++import (+ "fmt"++ "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 = (*EventDisallowCreateAdvisor)(nil)+)++func init() {+ advisor.Register(storepb.Engine_MYSQL, advisor.MySQLEventDisallowCreate, &EventDisallowCreateAdvisor{})+}++// EventDisallowCreateAdvisor is the advisor checking for disallow creating event.+type EventDisallowCreateAdvisor struct {+}++// Check checks for disallow creating event.+func (*EventDisallowCreateAdvisor) 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 parser result")+ }++ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)+ if err != nil {+ return nil, err+ }+ checker := &eventDisallowCreateChecker{+ level: level,+ title: string(ctx.Rule.Type),+ }++ for _, stmt := range stmtList {+ checker.baseLine = stmt.BaseLine+ antlr.ParseTreeWalkerDefault.Walk(checker, stmt.Tree)+ }++ 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 eventDisallowCreateChecker struct {+ *mysql.BaseMySQLParserListener++ baseLine int+ adviceList []advisor.Advice+ level advisor.Status+ title string+ text string+}++func (checker *eventDisallowCreateChecker) EnterQuery(ctx *mysql.QueryContext) {+ checker.text = ctx.GetParser().GetTokenStream().GetTextFromRuleContext(ctx)+}++func (checker *eventDisallowCreateChecker) EnterCreateEvent(ctx *mysql.CreateEventContext) {+ code := advisor.Ok+ if ctx.EventName() != nil {+ code = advisor.DisallowEvent+ }++ if code != advisor.Ok {+ checker.adviceList = append(checker.adviceList, advisor.Advice{+ Status: checker.level,+ Code: code,+ Title: checker.title,+ Content: fmt.Sprintf("Event is forbidden, but \"%s\" creates", checker.text),+ Line: checker.baseLine + ctx.GetStart().GetLine(),+ })+ }+}diff --git a/backend/plugin/advisor/mysql/mysql_rules_test.go b/backend/plugin/advisor/mysql/mysql_rules_test.goindex 2824a67fda..85fdcc9ea9 100644--- a/backend/plugin/advisor/mysql/mysql_rules_test.go+++ b/backend/plugin/advisor/mysql/mysql_rules_test.go@@ -12,6 +12,7 @@ func TestMySQLRules(t *testing.T) {// advisor.SchemaRuleMySQLEngine enforce the innodb engine.advisor.SchemaRuleMySQLEngine,+ // Naming related rules.// advisor.SchemaRuleTableNaming enforce the table name format.advisor.SchemaRuleTableNaming,// advisor.SchemaRuleColumnNaming enforce the column name format.@@ -27,6 +28,7 @@ func TestMySQLRules(t *testing.T) {// advisor.SchemaRuleIdentifierNoKeyword enforce the identifier no keyword.advisor.SchemaRuleIdentifierNoKeyword,+ // Statement related rules.// advisor.SchemaRuleStatementNoSelectAll disallow 'SELECT *'.advisor.SchemaRuleStatementNoSelectAll,// advisor.SchemaRuleStatementRequireWhere require 'WHERE' clause.@@ -52,6 +54,11 @@ func TestMySQLRules(t *testing.T) {// advisor.SchemaRuleStatementDMLDryRun dry run the dml.advisor.SchemaRuleStatementDMLDryRun,+ // Database related rules.+ // advisor.SchemaRuleDropEmptyDatabase enforce the MySQL support check if the database is empty before users drop it.+ advisor.SchemaRuleDropEmptyDatabase,++ // Table related rules.// advisor.SchemaRuleTableRequirePK require the table to have a primary key.advisor.SchemaRuleTableRequirePK,// advisor.SchemaRuleTableNoFK require the table disallow the foreign key.@@ -67,6 +74,7 @@ func TestMySQLRules(t *testing.T) {// advisor.SchemaRuleTableNoDuplicateIndex require the table no duplicate index.advisor.SchemaRuleTableNoDuplicateIndex,+ // Column related rules.// advisor.SchemaRuleRequiredColumn enforce the required columns in each table.advisor.SchemaRuleRequiredColumn,// advisor.SchemaRuleColumnNotNull enforce the columns cannot have NULL value.@@ -97,17 +105,8 @@ func TestMySQLRules(t *testing.T) {advisor.SchemaRuleColumnAutoIncrementMustUnsigned,// advisor.SchemaRuleColumnRequireDefault enforce the column default.advisor.SchemaRuleColumnRequireDefault,- // advisor.SchemaRuleDisallowProcedure enforce the disallow procedure.- advisor.SchemaRuleDisallowProcedure,-- // advisor.SchemaRuleSchemaBackwardCompatibility enforce the MySQL and TiDB support check whether the schema change is backward compatible.- advisor.SchemaRuleSchemaBackwardCompatibility,- // advisor.SchemaRuleCurrentTimeColumnCountLimit enforce the current column count limit.- advisor.SchemaRuleCurrentTimeColumnCountLimit,-- // advisor.SchemaRuleDropEmptyDatabase enforce the MySQL support check if the database is empty before users drop it.- advisor.SchemaRuleDropEmptyDatabase,+ // Index related rules.// advisor.SchemaRuleIndexNoDuplicateColumn require the index no duplicate column.advisor.SchemaRuleIndexNoDuplicateColumn,// advisor.SchemaRuleIndexKeyNumberLimit enforce the index key number limit.@@ -120,11 +119,19 @@ func TestMySQLRules(t *testing.T) {advisor.SchemaRuleIndexTotalNumberLimit,advisor.SchemaRuleIndexPrimaryKeyTypeAllowlist,+ // System related rules.+ // advisor.SchemaRuleSchemaBackwardCompatibility enforce the MySQL and TiDB support check whether the schema change is backward compatible.+ advisor.SchemaRuleSchemaBackwardCompatibility,+ // advisor.SchemaRuleCurrentTimeColumnCountLimit enforce the current column count limit.+ advisor.SchemaRuleCurrentTimeColumnCountLimit,// advisor.SchemaRuleCharsetAllowlist enforce the charset allowlist.advisor.SchemaRuleCharsetAllowlist,-// advisor.SchemaRuleCollationAllowlist enforce the collation allowlist.advisor.SchemaRuleCollationAllowlist,+ // advisor.SchemaRuleDisallowProcedure enforce the disallow procedure.+ advisor.SchemaRuleDisallowProcedure,+ // advisor.SchemaRuleDisallowEvent enforce the disallow event.+ advisor.SchemaRuleDisallowEvent,}for _, rule := range mysqlRules {diff --git a/backend/plugin/advisor/mysql/test/system_event_disallow.yaml b/backend/plugin/advisor/mysql/test/system_event_disallow.yamlnew file mode 100644index 0000000000..91a82def05--- /dev/null+++ b/backend/plugin/advisor/mysql/test/system_event_disallow.yaml@@ -0,0 +1,32 @@+- statement: CREATE TABLE t(a int);+ want:+ - status: SUCCESS+ code: 0+ title: OK+ content: ""+ line: 0+ details: ""+- statement: |-+ CREATE EVENT daily_backup+ ON SCHEDULE+ EVERY 1 DAY+ STARTS CURRENT_TIMESTAMP+ DO+ INSERT INTO backup_table (backup_date, data)+ SELECT NOW(), data+ FROM main_table;+ want:+ - status: WARN+ code: 1501+ title: system.event.disallow+ content: |-+ Event is forbidden, but "CREATE EVENT daily_backup+ ON SCHEDULE+ EVERY 1 DAY+ STARTS CURRENT_TIMESTAMP+ DO+ INSERT INTO backup_table (backup_date, data)+ SELECT NOW(), data+ FROM main_table;" creates+ line: 1+ details: ""diff --git a/backend/plugin/advisor/sql_review.go b/backend/plugin/advisor/sql_review.goindex 0adf3a4cc5..c5379df893 100644--- a/backend/plugin/advisor/sql_review.go+++ b/backend/plugin/advisor/sql_review.go@@ -175,15 +175,14 @@ const (// SchemaRuleCharsetAllowlist enforce the charset allowlist.SchemaRuleCharsetAllowlist SQLReviewRuleType = "system.charset.allowlist"-// SchemaRuleCollationAllowlist enforce the collation allowlist.SchemaRuleCollationAllowlist SQLReviewRuleType = "system.collation.allowlist"-// SchemaRuleCommentLength limit comment length.SchemaRuleCommentLength SQLReviewRuleType = "system.comment.length"-// SchemaRuleDisallowProcedure disallow procedure.SchemaRuleDisallowProcedure SQLReviewRuleType = "system.procedure.disallow"+ // SchemaRuleDisallowEvent disallow event.+ SchemaRuleDisallowEvent SQLReviewRuleType = "system.event.disallow"// TableNameTemplateToken is the token for table name.TableNameTemplateToken = "{{table}}"@@ -1469,6 +1468,10 @@ func getAdvisorTypeByRule(ruleType SQLReviewRuleType, engine storepb.Engine) (Tyif engine == storepb.Engine_MYSQL {return MySQLDisallowProcedure, nil}+ case SchemaRuleDisallowEvent:+ if engine == storepb.Engine_MYSQL {+ return MySQLEventDisallowCreate, nil+ }}return Fake, errors.Errorf("unknown SQL review rule type %v for %v", ruleType, engine)}diff --git a/backend/plugin/advisor/utils_for_tests.go b/backend/plugin/advisor/utils_for_tests.goindex 9c7650c1ed..723b75f857 100644--- a/backend/plugin/advisor/utils_for_tests.go+++ b/backend/plugin/advisor/utils_for_tests.go@@ -356,6 +356,7 @@ func SetDefaultSQLReviewRulePayload(ruleTp SQLReviewRuleType, dbType storepb.EngSchemaRuleIdentifierNoKeyword,SchemaRuleTableNameNoKeyword,SchemaRuleDisallowProcedure,+ SchemaRuleDisallowEvent,SchemaRuleStatementCreateSpecifySchema:case SchemaRuleTableDropNamingConvention:payload, err = json.Marshal(NamingRulePayload{