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: migrate schema_backward_compatibility (#9255)
zll6001b70a1b5f64b
diff --git a/backend/plugin/advisor/mysqlwip/advisor_migration_compatibility.go b/backend/plugin/advisor/mysqlwip/advisor_migration_compatibility.goindex eeca624119..480fd1d0d0 100644--- a/backend/plugin/advisor/mysqlwip/advisor_migration_compatibility.go+++ b/backend/plugin/advisor/mysqlwip/advisor_migration_compatibility.go@@ -3,27 +3,34 @@ package mysqlwipimport ("fmt"+ "github.com/antlr4-go/antlr/v4""github.com/pkg/errors"- "github.com/bytebase/bytebase/backend/plugin/advisor"+ mysql "github.com/bytebase/mysql-parser"- "github.com/pingcap/tidb/parser/ast"+ "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 = (*CompatibilityAdvisor)(nil)- _ ast.Visitor = (*compatibilityChecker)(nil))+func init() {+ // only for mysqlwip test.+ advisor.Register(storepb.Engine_ENGINE_UNSPECIFIED, advisor.MySQLMigrationCompatibility, &CompatibilityAdvisor{})+}+// CompatibilityAdvisor is the advisor checking for schema backward compatibility.type CompatibilityAdvisor struct {}// Check checks schema backward compatibility.func (*CompatibilityAdvisor) Check(ctx advisor.Context, _ string) ([]advisor.Advice, error) {- root, ok := ctx.AST.([]ast.StmtNode)+ root, ok := ctx.AST.([]*mysqlparser.ParseResult)if !ok {- return nil, errors.Errorf("failed to convert to StmtNode")+ return nil, errors.Errorf("failed to convert to mysql parse result")}level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)@@ -31,139 +38,184 @@ func (*CompatibilityAdvisor) Check(ctx advisor.Context, _ string) ([]advisor.Advreturn nil, err}- c := &compatibilityChecker{+ checker := &compatibilityChecker{level: level,title: string(ctx.Rule.Type),}- for _, stmtNode := range root {- (stmtNode).Accept(c)+ for _, stmt := range root {+ checker.baseLine = stmt.BaseLine+ antlr.ParseTreeWalkerDefault.Walk(checker, stmt.Tree)}- if len(c.adviceList) == 0 {- c.adviceList = append(c.adviceList, advisor.Advice{+ if len(checker.adviceList) == 0 {+ checker.adviceList = append(checker.adviceList, advisor.Advice{Status: advisor.Success,Code: advisor.Ok,Title: "OK",Content: "",})}- return c.adviceList, nil+ return checker.adviceList, nil}type compatibilityChecker struct {+ *mysql.BaseMySQLParserListener++ baseLine intadviceList []advisor.Advicelevel advisor.Statustitle stringlastCreateTable string+ code advisor.Code+}++// EnterQuery is called when production query is entered.+func (checker *compatibilityChecker) EnterQuery(_ *mysql.QueryContext) {+ checker.code = advisor.Ok+}++// ExitQuery is called when production query is exited.+func (checker *compatibilityChecker) ExitQuery(ctx *mysql.QueryContext) {+ if checker.code != advisor.Ok {+ text := ctx.GetParser().GetTokenStream().GetTextFromRuleContext(ctx)+ checker.adviceList = append(checker.adviceList, advisor.Advice{+ Status: checker.level,+ Code: checker.code,+ Title: checker.title,+ Content: fmt.Sprintf("\"%s\" may cause incompatibility with the existing data and code", text),+ Line: checker.baseLine + ctx.GetStart().GetLine(),+ })+ }+}++// EnterCreateTable is called when production createTable is entered.+func (checker *compatibilityChecker) EnterCreateTable(ctx *mysql.CreateTableContext) {+ if ctx.TableName() == nil {+ return+ }+ if ctx.TableElementList() == nil {+ return+ }++ _, tableName := mysqlparser.NormalizeMySQLTableName(ctx.TableName())+ checker.lastCreateTable = tableName+}++// EnterDropDatabase is called when production dropDatabase is entered.+func (checker *compatibilityChecker) EnterDropDatabase(_ *mysql.DropDatabaseContext) {+ checker.code = advisor.CompatibilityDropDatabase}-// Enter implements the ast.Visitor interface.-func (v *compatibilityChecker) Enter(in ast.Node) (ast.Node, bool) {- code := advisor.Ok- switch node := in.(type) {- // CREATE TABLE- case *ast.CreateTableStmt:- v.lastCreateTable = node.Table.Name.O- // DROP DATABASE- case *ast.DropDatabaseStmt:- code = advisor.CompatibilityDropDatabase- // RENAME TABLE- case *ast.RenameTableStmt:- code = advisor.CompatibilityRenameTable- // DROP TABLE/VIEW- case *ast.DropTableStmt:- code = advisor.CompatibilityDropTable- // ALTER TABLE- case *ast.AlterTableStmt:- if node.Table.Name.O == v.lastCreateTable {- break+// EnterRenameTableStatement is called when production renameTableStatement is entered.+func (checker *compatibilityChecker) EnterRenameTableStatement(_ *mysql.RenameTableStatementContext) {+ checker.code = advisor.CompatibilityRenameTable+}++// EnterDropTable is called when production dropTable is entered.+func (checker *compatibilityChecker) EnterDropTable(_ *mysql.DropTableContext) {+ checker.code = advisor.CompatibilityDropTable+}++func (checker *compatibilityChecker) EnterAlterTable(ctx *mysql.AlterTableContext) {+ if ctx.AlterTableActions() == nil {+ return+ }+ if ctx.AlterTableActions().AlterCommandList() == nil {+ return+ }+ if ctx.AlterTableActions().AlterCommandList().AlterList() == nil {+ return+ }++ _, tableName := mysqlparser.NormalizeMySQLTableRef(ctx.TableRef())+ if tableName == checker.lastCreateTable {+ return+ }++ // alter table add column, change column, modify column.+ for _, item := range ctx.AlterTableActions().AlterCommandList().AlterList().AllAlterListItem() {+ if item == nil {+ continue}- for _, spec := range node.Specs {- // RENAME COLUMN- if spec.Tp == ast.AlterTableRenameColumn {- code = advisor.CompatibilityRenameColumn- break- }- // DROP COLUMN- if spec.Tp == ast.AlterTableDropColumn {- code = advisor.CompatibilityDropColumn- break- }- // RENAME TABLE- if spec.Tp == ast.AlterTableRenameTable {- code = advisor.CompatibilityRenameTable- break- }- if spec.Tp == ast.AlterTableAddConstraint {- // ADD PRIMARY KEY- if spec.Constraint.Tp == ast.ConstraintPrimaryKey {- code = advisor.CompatibilityAddPrimaryKey- break- }- // ADD UNIQUE/UNIQUE KEY/UNIQUE INDEX- if spec.Constraint.Tp == ast.ConstraintPrimaryKey ||- spec.Constraint.Tp == ast.ConstraintUniq ||- spec.Constraint.Tp == ast.ConstraintUniqKey {- code = advisor.CompatibilityAddUniqueKey- break- }- // ADD FOREIGN KEY- if spec.Constraint.Tp == ast.ConstraintForeignKey {- code = advisor.CompatibilityAddForeignKey- break- }- // Check is only supported after 8.0.16 https://dev.mysql.com/doc/refman/8.0/en/create-table-check-constraints.html- // ADD CHECK ENFORCED- if spec.Constraint.Tp == ast.ConstraintCheck && spec.Constraint.Enforced {- code = advisor.CompatibilityAddCheck- break+ if item.RENAME_SYMBOL() != nil && item.COLUMN_SYMBOL() != nil {+ checker.code = advisor.CompatibilityRenameColumn+ return+ }++ if item.DROP_SYMBOL() != nil && item.ColumnInternalRef() != nil {+ checker.code = advisor.CompatibilityDropColumn+ return+ }+ if item.DROP_SYMBOL() != nil && item.TableName() != nil {+ checker.code = advisor.CompatibilityRenameTable+ return+ }++ if item.ADD_SYMBOL() != nil {+ if item.TableConstraintDef() != nil {+ switch item.TableConstraintDef().GetType_().GetTokenType() {+ // add primary key.+ case mysql.MySQLParserPRIMARY_SYMBOL:+ checker.code = advisor.CompatibilityAddPrimaryKey+ return+ // add unique key.+ case mysql.MySQLParserUNIQUE_SYMBOL:+ checker.code = advisor.CompatibilityAddUniqueKey+ return+ // add foreign key.+ case mysql.MySQLParserFOREIGN_SYMBOL:+ checker.code = advisor.CompatibilityAddForeignKey+ return}}+ // add check enforced.// Check is only supported after 8.0.16 https://dev.mysql.com/doc/refman/8.0/en/create-table-check-constraints.html- // ALTER CHECK ENFORCED- if spec.Tp == ast.AlterTableAlterCheck {- if spec.Constraint.Enforced {- code = advisor.CompatibilityAlterCheck- break- }+ if item.TableConstraintDef().CheckConstraint() != nil && item.TableConstraintDef().ConstraintEnforcement() != nil {+ checker.code = advisor.CompatibilityAddCheck+ return}+ }- // MODIFY COLUMN / CHANGE COLUMN- // Due to the limitation that we don't know the current data type of the column before the change,- // so we treat all as incompatible. This generates false positive when:- // 1. Change to a compatible data type such as INT to BIGINT- // 2. Change properties such as comment, change it to NULL- if spec.Tp == ast.AlterTableModifyColumn || spec.Tp == ast.AlterTableChangeColumn {- code = advisor.CompatibilityAlterColumn- break+ // add check enforced.+ // Check is only supported after 8.0.16 https://dev.mysql.com/doc/refman/8.0/en/create-table-check-constraints.html+ if item.ALTER_SYMBOL() != nil && item.CHECK_SYMBOL() != nil {+ if item.ConstraintEnforcement() != nil {+ checker.code = advisor.CompatibilityAlterCheck+ return}}- // ALTER VIEW TBD: https://github.com/pingcap/parser/pull/1252- // case *ast.AlterViewStmt:-- // CREATE UNIQUE INDEX- case *ast.CreateIndexStmt:- if v.lastCreateTable != node.Table.Name.O && node.KeyType == ast.IndexKeyTypeUnique {- code = advisor.CompatibilityAddUniqueKey+ // MODIFY COLUMN / CHANGE COLUMN+ // Due to the limitation that we don't know the current data type of the column before the change,+ // so we treat all as incompatible. This generates false positive when:+ // 1. Change to a compatible data type such as INT to BIGINT+ // 2. Change properties such as comment, change it to NULL+ // modify column+ if item.MODIFY_SYMBOL() != nil && item.ColumnInternalRef() != nil {+ checker.code = advisor.CompatibilityAlterColumn+ return+ }+ // change column+ if item.CHANGE_SYMBOL() != nil && item.ColumnInternalRef() != nil && item.Identifier() != nil {+ checker.code = advisor.CompatibilityAlterColumn+ return}}+}- if code != advisor.Ok {- v.adviceList = append(v.adviceList, advisor.Advice{- Status: v.level,- Code: code,- Title: v.title,- Content: fmt.Sprintf("\"%s\" may cause incompatibility with the existing data and code", in.Text()),- Line: in.OriginTextPosition(),- })+// EnterCreateIndex is called when production createIndex is entered.+func (checker *compatibilityChecker) EnterCreateIndex(ctx *mysql.CreateIndexContext) {+ if ctx.GetType_().GetTokenType() != mysql.MySQLParserUNIQUE_SYMBOL {+ return+ }+ if ctx.CreateIndexTarget() == nil || ctx.CreateIndexTarget().TableRef() == nil {+ return}- return in, false-}-// Leave implements the ast.Visitor interface.-func (*compatibilityChecker) Leave(in ast.Node) (ast.Node, bool) {- return in, true+ _, tableName := mysqlparser.NormalizeMySQLTableRef(ctx.CreateIndexTarget().TableRef())+ if checker.lastCreateTable != tableName {+ checker.code = advisor.CompatibilityAddUniqueKey+ }}diff --git a/backend/plugin/advisor/mysqlwip/mysqlwip_rules_test.go b/backend/plugin/advisor/mysqlwip/mysqlwip_rules_test.goindex 1184128d00..e076ea7c11 100644--- a/backend/plugin/advisor/mysqlwip/mysqlwip_rules_test.go+++ b/backend/plugin/advisor/mysqlwip/mysqlwip_rules_test.go@@ -87,6 +87,9 @@ func TestMySQLWIPRules(t *testing.T) {// advisor.SchemaRuleColumnRequireDefault enforce the column default.advisor.SchemaRuleColumnRequireDefault,+ // advisor.SchemaRuleSchemaBackwardCompatibility enforce the MySQL and TiDB support check whether the schema change is backward compatible.+ advisor.SchemaRuleSchemaBackwardCompatibility,+// advisor.SchemaRuleDropEmptyDatabase enforce the MySQL support check if the database is empty before users drop it.advisor.SchemaRuleDropEmptyDatabase,diff --git a/backend/plugin/advisor/mysqlwip/test/schema_backward_compatibility.yaml b/backend/plugin/advisor/mysqlwip/test/schema_backward_compatibility.yamlindex 4513d1535f..804414eacc 100644--- a/backend/plugin/advisor/mysqlwip/test/schema_backward_compatibility.yaml+++ b/backend/plugin/advisor/mysqlwip/test/schema_backward_compatibility.yaml@@ -1,50 +1,45 @@-- statement: ALTER TABLE tech_book CHANGE name f2 TEXT+- statement: ALTER TABLE tech_book CHANGE name f2 TEXT;want:- status: WARNcode: 111title: schema.backward-compatibilitycontent: |-- "ALTER TABLE tech_book CHANGE name f2 TEXT- ;" may cause incompatibility with the existing data and code- line: 2+ "ALTER TABLE tech_book CHANGE name f2 TEXT;" may cause incompatibility with the existing data and code+ line: 1details: ""-- statement: ALTER TABLE tech_book MODIFY name TEXT+- statement: ALTER TABLE tech_book MODIFY name TEXT;want:- status: WARNcode: 111title: schema.backward-compatibilitycontent: |-- "ALTER TABLE tech_book MODIFY name TEXT- ;" may cause incompatibility with the existing data and code- line: 2+ "ALTER TABLE tech_book MODIFY name TEXT;" may cause incompatibility with the existing data and code+ line: 1details: ""-- statement: ALTER TABLE tech_book MODIFY name TEXT NULL+- statement: ALTER TABLE tech_book MODIFY name TEXT NULL;want:- status: WARNcode: 111title: schema.backward-compatibilitycontent: |-- "ALTER TABLE tech_book MODIFY name TEXT NULL- ;" may cause incompatibility with the existing data and code- line: 2+ "ALTER TABLE tech_book MODIFY name TEXT NULL;" may cause incompatibility with the existing data and code+ line: 1details: ""-- statement: ALTER TABLE tech_book MODIFY name TEXT NOT NULL+- statement: ALTER TABLE tech_book MODIFY name TEXT NOT NULL;want:- status: WARNcode: 111title: schema.backward-compatibilitycontent: |-- "ALTER TABLE tech_book MODIFY name TEXT NOT NULL- ;" may cause incompatibility with the existing data and code- line: 2+ "ALTER TABLE tech_book MODIFY name TEXT NOT NULL;" may cause incompatibility with the existing data and code+ line: 1details: ""-- statement: ALTER TABLE tech_book MODIFY name TEXT COMMENT 'bla'+- statement: ALTER TABLE tech_book MODIFY name TEXT COMMENT 'bla';want:- status: WARNcode: 111title: schema.backward-compatibilitycontent: |-- "ALTER TABLE tech_book MODIFY name TEXT COMMENT 'bla'- ;" may cause incompatibility with the existing data and code- line: 2+ "ALTER TABLE tech_book MODIFY name TEXT COMMENT 'bla';" may cause incompatibility with the existing data and code+ line: 1details: ""diff --git a/backend/plugin/advisor/sql_review.go b/backend/plugin/advisor/sql_review.goindex 5bba23e286..44ea6be1ef 100644--- a/backend/plugin/advisor/sql_review.go+++ b/backend/plugin/advisor/sql_review.go@@ -1067,6 +1067,9 @@ func getAdvisorTypeByRule(ruleType SQLReviewRuleType, engine storepb.Engine) (Ty}case SchemaRuleSchemaBackwardCompatibility:switch engine {+ // only for mysqlwip test.+ case storepb.Engine_ENGINE_UNSPECIFIED:+ return MySQLMigrationCompatibility, nilcase storepb.Engine_MYSQL, storepb.Engine_TIDB, storepb.Engine_MARIADB, storepb.Engine_OCEANBASE:return MySQLMigrationCompatibility, nilcase storepb.Engine_POSTGRES: