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: implment migration compatibility sql review rule for mssql (#7190)
h3n4lc11c5d0e8148
diff --git a/backend/plugin/advisor/advisor.go b/backend/plugin/advisor/advisor.goindex 24a56b7bd5..494fd0c4b0 100644--- a/backend/plugin/advisor/advisor.go+++ b/backend/plugin/advisor/advisor.go@@ -470,6 +470,9 @@ const (// MSSQLTableNoFK is an advisor type for MSSQL table disallow foreign key.MSSQLTableNoFK Type = "bb.plugin.advisor.mssql.table.no-foreign-key"++ // MSSQLMigrationCompatibility is an advisor type for MSSQL migration compatibility.+ MSSQLMigrationCompatibility Type = "bb.plugin.advisor.mssql.migration-compatibility")// Advice is the result of an advisor.diff --git a/backend/plugin/advisor/mssql/advisor_migration_compatibility.go b/backend/plugin/advisor/mssql/advisor_migration_compatibility.gonew file mode 100644index 0000000000..7d52cb90fb--- /dev/null+++ b/backend/plugin/advisor/mssql/advisor_migration_compatibility.go@@ -0,0 +1,346 @@+// Package mssql is the advisor for MSSQL database.+package mssql++import (+ "fmt"+ "strings"++ "github.com/antlr4-go/antlr/v4"+ parser "github.com/bytebase/tsql-parser"+ "github.com/pkg/errors"++ "github.com/bytebase/bytebase/backend/plugin/advisor"+ "github.com/bytebase/bytebase/backend/plugin/advisor/db"+ bbparser "github.com/bytebase/bytebase/backend/plugin/parser/sql"+)++var (+ _ advisor.Advisor = (*MigrationCompatibilityAdvisor)(nil)+)++func init() {+ advisor.Register(db.MSSQL, advisor.MSSQLMigrationCompatibility, &MigrationCompatibilityAdvisor{})+}++// MigrationCompatibilityAdvisor is the advisor checking for migration compatibility..+type MigrationCompatibilityAdvisor struct {+}++// Check checks for migration compatibility..+func (*MigrationCompatibilityAdvisor) Check(ctx advisor.Context, _ string) ([]advisor.Advice, error) {+ tree, ok := ctx.AST.(antlr.Tree)+ if !ok {+ return nil, errors.Errorf("failed to convert to Tree")+ }++ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)+ if err != nil {+ return nil, err+ }++ listener := &migrationCompatibilityChecker{+ level: level,+ title: string(ctx.Rule.Type),+ currentDatabase: ctx.CurrentDatabase,+ normalizedNewCreateTableNameMap: make(map[string]any),+ normalizedNewCreateSchemaNameMap: make(map[string]any),+ normalizedNewCreateDatabaseNameMap: make(map[string]any),+ }++ antlr.ParseTreeWalkerDefault.Walk(listener, tree)++ return listener.generateAdvice()+}++// migrationCompatibilityChecker is the listener for migration compatibility.+type migrationCompatibilityChecker struct {+ *parser.BaseTSqlParserListener++ level advisor.Status+ title string++ // normalizedLastCreateTableNameMap contain the last created table name in normalized format.+ normalizedNewCreateTableNameMap map[string]any+ // normalizedLastCreateSchemaNameMap contain the last created schema name in normalized format.+ normalizedNewCreateSchemaNameMap map[string]any+ // normalizedNewCreateDatabaseNameMap contain the new created database name in normalized format.+ normalizedNewCreateDatabaseNameMap map[string]any++ // currentDatabase is the current database name.+ currentDatabase string++ adviceList []advisor.Advice+}++// generateAdvice returns the advices generated by the listener, the advices must not be empty.+func (l *migrationCompatibilityChecker) generateAdvice() ([]advisor.Advice, error) {+ if len(l.adviceList) == 0 {+ l.adviceList = append(l.adviceList, advisor.Advice{+ Status: advisor.Success,+ Code: advisor.Ok,+ Title: "OK",+ Content: "",+ })+ }+ return l.adviceList, nil+}++func (l *migrationCompatibilityChecker) EnterCreate_table(ctx *parser.Create_tableContext) {+ tableName := ctx.Table_name()+ if tableName == nil || tableName.GetTable() == nil {+ return+ }+ normalizedTableName := bbparser.NormalizeTSQLTableName(tableName, l.currentDatabase, "dbo", false)+ l.normalizedNewCreateTableNameMap[normalizedTableName] = any(nil)+}++func (l *migrationCompatibilityChecker) EnterCreate_schema(ctx *parser.Create_schemaContext) {+ var schemaName string+ if v := ctx.GetSchema_name(); v != nil {+ schemaName = bbparser.NormalizeTSQLIdentifier(v)+ } else {+ schemaName = bbparser.NormalizeTSQLIdentifier(ctx.GetOwner_name())+ }++ normalizedDatabaseSchemaName := fmt.Sprintf("%s.%s", l.currentDatabase, schemaName)+ l.normalizedNewCreateSchemaNameMap[normalizedDatabaseSchemaName] = any(nil)+}++func (l *migrationCompatibilityChecker) EnterCreate_database(ctx *parser.Create_databaseContext) {+ databaseName := bbparser.NormalizeTSQLIdentifier(ctx.GetDatabase())+ l.normalizedNewCreateDatabaseNameMap[databaseName] = any(nil)+}++func (l *migrationCompatibilityChecker) EnterDrop_table(ctx *parser.Drop_tableContext) {+ allTableNames := ctx.AllTable_name()+ for _, tableName := range allTableNames {+ if tableName == nil || tableName.GetTable() == nil {+ continue+ }+ normalizedTableName := bbparser.NormalizeTSQLTableName(tableName, l.currentDatabase, "dbo", false)+ if _, ok := l.normalizedNewCreateTableNameMap[normalizedTableName]; !ok {+ l.adviceList = append(l.adviceList, advisor.Advice{+ Status: l.level,+ Code: advisor.CompatibilityDropSchema,+ Title: l.title,+ Content: fmt.Sprintf("Drop table %s may cause incompatibility with the existing data and code", normalizedTableName),+ Line: ctx.GetStart().GetLine(),+ })+ }+ delete(l.normalizedNewCreateTableNameMap, normalizedTableName)+ }+}++func (l *migrationCompatibilityChecker) EnterDrop_schema(ctx *parser.Drop_schemaContext) {+ schemaName := ctx.GetSchema_name()+ normalizedSchemaName := fmt.Sprintf("%s.%s", l.currentDatabase, bbparser.NormalizeTSQLIdentifier(schemaName))+ if _, ok := l.normalizedNewCreateSchemaNameMap[normalizedSchemaName]; !ok {+ l.adviceList = append(l.adviceList, advisor.Advice{+ Status: l.level,+ Code: advisor.CompatibilityDropSchema,+ Title: l.title,+ Content: fmt.Sprintf("Drop schema %s may cause incompatibility with the existing data and code", normalizedSchemaName),+ Line: ctx.GetStart().GetLine(),+ })+ }+ delete(l.normalizedNewCreateSchemaNameMap, normalizedSchemaName)+}++func (l *migrationCompatibilityChecker) EnterDrop_database(ctx *parser.Drop_databaseContext) {+ databaseName := ctx.GetDatabase_name_or_database_snapshot_name()+ normalizedDatabaseName := bbparser.NormalizeTSQLIdentifier(databaseName)+ if _, ok := l.normalizedNewCreateDatabaseNameMap[normalizedDatabaseName]; !ok {+ l.adviceList = append(l.adviceList, advisor.Advice{+ Status: l.level,+ Code: advisor.CompatibilityDropSchema,+ Title: l.title,+ Content: fmt.Sprintf("Drop database %s may cause incompatibility with the existing data and code", normalizedDatabaseName),+ Line: ctx.GetStart().GetLine(),+ })+ }+ delete(l.normalizedNewCreateDatabaseNameMap, normalizedDatabaseName)+}++func (l *migrationCompatibilityChecker) EnterAlter_table(ctx *parser.Alter_tableContext) {+ handleTableName := ctx.Table_name(0)+ normalizedHandleTableName := bbparser.NormalizeTSQLTableName(handleTableName, l.currentDatabase, "dbo", false)+ if _, ok := l.normalizedNewCreateTableNameMap[normalizedHandleTableName]; ok {+ return+ }++ if ctx.DROP() != nil && ctx.COLUMN() != nil {+ allDropColumns := ctx.AllId_()+ var allNormalizedDropColumnNames []string+ for _, dropColumn := range allDropColumns {+ normalizedDropColumnName := bbparser.NormalizeTSQLIdentifier(dropColumn)+ allNormalizedDropColumnNames = append(allNormalizedDropColumnNames, normalizedDropColumnName)+ }+ placeholder := strings.Join(allNormalizedDropColumnNames, ", ")+ l.adviceList = append(l.adviceList, advisor.Advice{+ Status: l.level,+ Code: advisor.CompatibilityDropSchema,+ Title: l.title,+ Content: fmt.Sprintf("Drop column %s may cause incompatibility with the existing data and code", placeholder),+ Line: ctx.COLUMN().GetSymbol().GetLine(),+ })+ return+ }+ if len(ctx.AllALTER()) == 2 && ctx.COLUMN() != nil {+ normalizedColumnName := ""+ if ctx.Column_definition() != nil {+ normalizedColumnName = bbparser.NormalizeTSQLIdentifier(ctx.Column_definition().Id_())+ } else if ctx.Column_modifier() != nil {+ normalizedColumnName = bbparser.NormalizeTSQLIdentifier(ctx.Column_modifier().Id_())+ }++ l.adviceList = append(l.adviceList, advisor.Advice{+ Status: l.level,+ Code: advisor.CompatibilityAlterColumn,+ Title: l.title,+ Content: fmt.Sprintf("Alter COLUMN %s may cause incompatibility with the existing data and code", normalizedColumnName),+ Line: ctx.COLUMN().GetSymbol().GetLine(),+ })+ return+ }+ if v := ctx.Column_def_table_constraints(); v != nil {+ allColumnDefTableConstraints := v.AllColumn_def_table_constraint()+ for _, columnDefTableConstraint := range allColumnDefTableConstraints {+ code := advisor.Ok+ operation := ""+ tableConstraint := columnDefTableConstraint.Table_constraint()+ if tableConstraint == nil {+ continue+ }+ if tableConstraint.PRIMARY() != nil {+ code = advisor.CompatibilityAddPrimaryKey+ operation = "Add PRIMARY KEY"+ }+ if tableConstraint.UNIQUE() != nil {+ code = advisor.CompatibilityAddUniqueKey+ operation = "Add UNIQUE KEY"+ }+ if tableConstraint.Check_constraint() != nil {+ code = advisor.CompatibilityAddCheck+ operation = "Add CHECK"+ }+ l.adviceList = append(l.adviceList, advisor.Advice{+ Status: l.level,+ Code: code,+ Title: l.title,+ Content: fmt.Sprintf("%s may cause incompatibility with the existing data and code", operation),+ Line: ctx.GetStart().GetLine(),+ })+ }+ return+ }+ if ctx.WITH() != nil && ctx.NOCHECK() != nil {+ if ctx.FOREIGN() != nil {+ l.adviceList = append(l.adviceList, advisor.Advice{+ Status: l.level,+ Code: advisor.CompatibilityAddForeignKey,+ Title: l.title,+ Content: "Add FOREIGN KEY WITH NO CHECK may cause incompatibility with the existing data and code",+ Line: ctx.FOREIGN().GetSymbol().GetLine(),+ })+ return+ }+ if len(ctx.AllCHECK()) == 1 {+ l.adviceList = append(l.adviceList, advisor.Advice{+ Status: l.level,+ Code: advisor.CompatibilityAddForeignKey,+ Title: l.title,+ Content: "Add CHECK WITH NO CHECK may cause incompatibility with the existing data and code",+ Line: ctx.CHECK(0).GetSymbol().GetLine(),+ })+ return+ }+ }+}++// EnterExecute_body is called when production execute_body is entered.+func (l *migrationCompatibilityChecker) EnterExecute_body(ctx *parser.Execute_bodyContext) {+ if ctx.Func_proc_name_server_database_schema() == nil {+ return+ }+ if ctx.Func_proc_name_server_database_schema().Func_proc_name_database_schema() == nil {+ return+ }+ if ctx.Func_proc_name_server_database_schema().Func_proc_name_database_schema().Func_proc_name_schema() == nil {+ return+ }+ if ctx.Func_proc_name_server_database_schema().Func_proc_name_database_schema().Func_proc_name_schema().GetSchema() != nil {+ return+ }++ v := ctx.Func_proc_name_server_database_schema().Func_proc_name_database_schema().Func_proc_name_schema().GetProcedure()+ normalizedProcedureName := bbparser.NormalizeTSQLIdentifier(v)+ if normalizedProcedureName != "sp_rename" {+ return+ }++ unnamedArguments := bbparser.FlattenExecuteStatementArgExecuteStatementArgUnnamed(ctx.Execute_statement_arg())++ firstArgument := unnamedArguments[0]+ if firstArgument == nil {+ return+ }+ if firstArgument == nil {+ return+ }+ if firstArgument.Execute_parameter() == nil {+ return+ }+ if firstArgument.Execute_parameter().Constant() == nil {+ return+ }+ if firstArgument.Execute_parameter().Constant().STRING() == nil {+ return+ }+ if len(unnamedArguments) == 2 {+ secondArgument := unnamedArguments[1]+ if secondArgument == nil {+ return+ }+ if secondArgument.Execute_parameter() == nil {+ return+ }+ if secondArgument.Execute_parameter().Constant() == nil {+ return+ }+ if secondArgument.Execute_parameter().Constant().STRING() == nil {+ return+ }+ l.adviceList = append(l.adviceList, advisor.Advice{+ Status: l.level,+ Code: advisor.CompatibilityRenameTable,+ Title: l.title,+ Content: fmt.Sprintf("Rename Table %s WITH may cause incompatibility with the existing data and code", firstArgument.GetText()),+ Line: ctx.GetStart().GetLine(),+ })+ } else if len(unnamedArguments) == 3 {+ thirdArgument := unnamedArguments[2]+ if thirdArgument == nil {+ return+ }+ if thirdArgument.Execute_parameter() == nil {+ return+ }+ if thirdArgument.Execute_parameter().Constant() == nil {+ return+ }+ if thirdArgument.Execute_parameter().Constant().STRING() == nil {+ return+ }+ if thirdArgument.GetText() != "'COLUMN'" {+ return+ }++ l.adviceList = append(l.adviceList, advisor.Advice{+ Status: l.level,+ Code: advisor.CompatibilityRenameColumn,+ Title: l.title,+ Content: fmt.Sprintf("Rename COLUMN %s may cause incompatibility with the existing data and code", firstArgument.GetText()),+ Line: ctx.GetStart().GetLine(),+ })+ }+}diff --git a/backend/plugin/advisor/mssql/mssql_rules_test.go b/backend/plugin/advisor/mssql/mssql_rules_test.goindex b39a29d6aa..55638dbaea 100644--- a/backend/plugin/advisor/mssql/mssql_rules_test.go+++ b/backend/plugin/advisor/mssql/mssql_rules_test.go@@ -20,6 +20,7 @@ func TestMSSQLRules(t *testing.T) {advisor.SchemaRuleTableRequirePK,advisor.SchemaRuleColumnNotNull,advisor.SchemaRuleTableNoFK,+ advisor.SchemaRuleSchemaBackwardCompatibility,}for _, rule := range snowflakeRules {diff --git a/backend/plugin/advisor/mssql/test/schema_backward_compatibility.yaml b/backend/plugin/advisor/mssql/test/schema_backward_compatibility.yamlnew file mode 100644index 0000000000..7991f2b26f--- /dev/null+++ b/backend/plugin/advisor/mssql/test/schema_backward_compatibility.yaml@@ -0,0 +1,123 @@+- statement: DROP TABLE MyTable;+ want:+ - status: WARN+ code: 112+ title: schema.backward-compatibility+ content: Drop table TEST_DB.dbo.mytable may cause incompatibility with the existing data and code+ line: 1+ details: ""+- statement: |-+ CREATE TABLE MyTable(Id INT PRIMARY KEY);+ DROP TABLE MyTable;+ want:+ - status: SUCCESS+ code: 0+ title: OK+ content: ""+ line: 0+ details: ""+- statement: DROP SCHEMA MySchema;+ want:+ - status: WARN+ code: 112+ title: schema.backward-compatibility+ content: Drop schema TEST_DB.myschema may cause incompatibility with the existing data and code+ line: 1+ details: ""+- statement: |-+ CREATE SCHEMA AUTHORIZATION dbo;+ DROP SCHEMA dbo;+ want:+ - status: SUCCESS+ code: 0+ title: OK+ content: ""+ line: 0+ details: ""+- statement: DROP DATABASE MyDB;+ want:+ - status: WARN+ code: 112+ title: schema.backward-compatibility+ content: Drop database mydb may cause incompatibility with the existing data and code+ line: 1+ details: ""+- statement: |-+ CREATE DATABASE MyDB;+ DROP DATABASE MyDB;+ want:+ - status: SUCCESS+ code: 0+ title: OK+ content: ""+ line: 0+ details: ""+- statement: |-+ ALTER TABLE MyTable DROP COLUMN MyColumnOne, MyColumnTwo;+ ALTER TABLE MyTable ALTER COLUMN MyColumnOne INT NOT NULL;+ ALTER TABLE MyTable ADD PRIMARY KEY (MyColumnOne, MyColumnTwo);+ ALTER TABLE MyTable ADD UNIQUE (MyColumnOne, MyColumnTwo);+ ALTER TABLE MyTable ADD CHECK NOT FOR REPLICATION (MyColumnOne > 0);+ ALTER TABLE MyTable WITH NOCHECK ADD CONSTRAINT MyConstraint CHECK (MyColumnOne > 0);+ ALTER TABLE MyTable WITH CHECK ADD CONSTRAINT MyConstraint CHECK (MyColumnOne > 0);+ ALTER TABLE MyTable WITH NOCHECK ADD FOREIGN KEY (MyColumnOne) REFERENCES MyTableTwo(MyColumnTwo);+ ALTER TABLE MyTable WITH CHECK ADD FOREIGN KEY (MyColumnOne) REFERENCES MyTableTwo(MyColumnTwo);+ want:+ - status: WARN+ code: 112+ title: schema.backward-compatibility+ content: Drop column mycolumnone, mycolumntwo may cause incompatibility with the existing data and code+ line: 1+ details: ""+ - status: WARN+ code: 111+ title: schema.backward-compatibility+ content: Alter COLUMN mycolumnone may cause incompatibility with the existing data and code+ line: 2+ details: ""+ - status: WARN+ code: 106+ title: schema.backward-compatibility+ content: Add PRIMARY KEY may cause incompatibility with the existing data and code+ line: 3+ details: ""+ - status: WARN+ code: 107+ title: schema.backward-compatibility+ content: Add UNIQUE KEY may cause incompatibility with the existing data and code+ line: 4+ details: ""+ - status: WARN+ code: 109+ title: schema.backward-compatibility+ content: Add CHECK may cause incompatibility with the existing data and code+ line: 5+ details: ""+ - status: WARN+ code: 108+ title: schema.backward-compatibility+ content: Add CHECK WITH NO CHECK may cause incompatibility with the existing data and code+ line: 6+ details: ""+ - status: WARN+ code: 108+ title: schema.backward-compatibility+ content: Add FOREIGN KEY WITH NO CHECK may cause incompatibility with the existing data and code+ line: 8+ details: ""+- statement: EXEC sp_rename 'Sales.SalesTerritory', 'SalesTerr';+ want:+ - status: WARN+ code: 102+ title: schema.backward-compatibility+ content: Rename Table 'Sales.SalesTerritory' WITH may cause incompatibility with the existing data and code+ line: 1+ details: ""+- statement: EXEC sp_rename 'dbo.ErrorLog.ErrorTime', 'ErrorDateTime', 'COLUMN';+ want:+ - status: WARN+ code: 104+ title: schema.backward-compatibility+ content: Rename COLUMN 'dbo.ErrorLog.ErrorTime' may cause incompatibility with the existing data and code+ line: 1+ details: ""diff --git a/backend/plugin/advisor/sql_review.go b/backend/plugin/advisor/sql_review.goindex 7364d8069e..c9ef35bbb3 100644--- a/backend/plugin/advisor/sql_review.go+++ b/backend/plugin/advisor/sql_review.go@@ -1096,6 +1096,8 @@ func getAdvisorTypeByRule(ruleType SQLReviewRuleType, engine db.Type) (Type, errreturn PostgreSQLMigrationCompatibility, nilcase db.Snowflake:return SnowflakeMigrationCompatibility, nil+ case db.MSSQL:+ return MSSQLMigrationCompatibility, nil}case SchemaRuleTableNaming:switch engine {diff --git a/backend/plugin/parser/sql/tsql.go b/backend/plugin/parser/sql/tsql.goindex 8f112e9ef8..e29a64c209 100644--- a/backend/plugin/parser/sql/tsql.go+++ b/backend/plugin/parser/sql/tsql.go@@ -583,3 +583,20 @@ func NormalizeTSQLIdentifier(part tsqlparser.IId_Context) string {}return s}++// FlattenExecuteStatementArgExecuteStatementArgUnnamed returns the flattened unnamed execute statement arg.+func FlattenExecuteStatementArgExecuteStatementArgUnnamed(ctx tsqlparser.IExecute_statement_argContext) []tsqlparser.IExecute_statement_arg_unnamedContext {+ var queue []tsqlparser.IExecute_statement_arg_unnamedContext+ ele := ctx+ for {+ if ele.Execute_statement_arg_unnamed() == nil {+ break+ }+ queue = append(queue, ele.Execute_statement_arg_unnamed())+ if len(ele.AllExecute_statement_arg()) != 1 {+ break+ }+ ele = ele.AllExecute_statement_arg()[0]+ }+ return queue+}diff --git a/frontend/src/types/sql-review-schema.yaml b/frontend/src/types/sql-review-schema.yamlindex 571c198c6a..f0b7cb27cd 100644--- a/frontend/src/types/sql-review-schema.yaml+++ b/frontend/src/types/sql-review-schema.yaml@@ -511,6 +511,7 @@ ruleList:- POSTGRES- OCEANBASE- SNOWFLAKE+ - MSSQLcomponentList: []- type: database.drop-empty-databasecategory: DATABASE