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(sql-review, snowflake): implement the migration compatibility sql review rule for snowflake (#7017)
h3n4l7131215b38c8
diff --git a/backend/api/v1/sql_service.go b/backend/api/v1/sql_service.goindex 59586cc897..492040b755 100644--- a/backend/api/v1/sql_service.go+++ b/backend/api/v1/sql_service.go@@ -1293,6 +1293,7 @@ func (s *SQLService) sqlReviewCheck(ctx context.Context, request *v1pb.QueryRequcatalog,connection,currentSchema,+ database.DatabaseName,)if err != nil {return advisor.Error, nil, status.Errorf(codes.Internal, "Failed to check SQL review policy: %v", err)@@ -1339,6 +1340,7 @@ func (s *SQLService) sqlCheck(catalog catalog.Catalog,driver *sql.DB,currentSchema string,+ currentDatabase string,) (advisor.Status, []advisor.Advice, error) {var adviceList []advisor.Advicepolicy, err := s.store.GetSQLReviewPolicy(ctx, environmentID)@@ -1350,13 +1352,14 @@ func (s *SQLService) sqlCheck(}res, err := advisor.SQLReviewCheck(statement, policy.RuleList, advisor.SQLReviewCheckContext{- Charset: dbCharacterSet,- Collation: dbCollation,- DbType: dbType,- Catalog: catalog,- Driver: driver,- Context: ctx,- CurrentSchema: currentSchema,+ Charset: dbCharacterSet,+ Collation: dbCollation,+ DbType: dbType,+ Catalog: catalog,+ Driver: driver,+ Context: ctx,+ CurrentSchema: currentSchema,+ CurrentDatabase: currentDatabase,})if err != nil {return advisor.Error, nil, errdiff --git a/backend/plugin/advisor/advisor.go b/backend/plugin/advisor/advisor.goindex afcec368c9..0a20074e6f 100644--- a/backend/plugin/advisor/advisor.go+++ b/backend/plugin/advisor/advisor.go@@ -432,6 +432,9 @@ const (// SnowflakeTableDropNamingConvention is an advisor type for Snowflake table drop with naming convention.SnowflakeTableDropNamingConvention Type = "bb.plugin.advisor.snowflake.table.drop-naming-convention"++ // SnowflakeMigrationCompatibility is an advisor type for Snowflake migration compatibility.+ SnowflakeMigrationCompatibility Type = "bb.plugin.advisor.snowflake.migration-compatibility")// Advice is the result of an advisor.@@ -493,6 +496,8 @@ type Context struct {Driver *sql.DBContext context.Context+ // CurrentDatabase is the current database. Special for Snowflake.+ CurrentDatabase string// CurrentSchema is the current schema. Special for Oracle.CurrentSchema string}diff --git a/backend/plugin/advisor/code.go b/backend/plugin/advisor/code.goindex 3ee9b6314b..e07dbffa0a 100644--- a/backend/plugin/advisor/code.go+++ b/backend/plugin/advisor/code.go@@ -22,6 +22,7 @@ const (CompatibilityAddCheck Code = 109CompatibilityAlterCheck Code = 110CompatibilityAlterColumn Code = 111+ CompatibilityDropSchema Code = 112// 201 ~ 299 statement error code.StatementSyntaxError Code = 201diff --git a/backend/plugin/advisor/snowflake/advisor_migration_compatibility.go b/backend/plugin/advisor/snowflake/advisor_migration_compatibility.gonew file mode 100644index 0000000000..f0825f9a7f--- /dev/null+++ b/backend/plugin/advisor/snowflake/advisor_migration_compatibility.go@@ -0,0 +1,194 @@+// Package snowflake is the advisor for snowflake database.+package snowflake++import (+ "fmt"+ "strings"++ "github.com/antlr4-go/antlr/v4"+ parser "github.com/bytebase/snowsql-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.Snowflake, advisor.SnowflakeMigrationCompatibility, &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]bool),+ normalizedNewCreateSchemaNameMap: make(map[string]bool),+ normalizedNewCreateDatabaseNameMap: make(map[string]bool),+ }++ antlr.ParseTreeWalkerDefault.Walk(listener, tree)++ return listener.generateAdvice()+}++// migrationCompatibilityChecker is the listener for migration compatibility.+type migrationCompatibilityChecker struct {+ *parser.BaseSnowflakeParserListener++ level advisor.Status+ title string++ // normalizedLastCreateTableNameMap contain the last created table name in normalized format, e.g. "SNOWFLAKE.PUBLIC.TABLE", If there are IF NOT EXISTS, the value will be false.+ normalizedNewCreateTableNameMap map[string]bool+ // normalizedLastCreateSchemaNameMap contain the last created schema name in normalized format, e.g. "SNOWFLAKE.PUBLIC", If there are IF NOT EXISTS, the value will be false.+ normalizedNewCreateSchemaNameMap map[string]bool+ // normalizedNewCreateDatabaseNameMap contain the new created database name in normalized format, e.g. "SNOWFLAKE", If there are IF NOT EXISTS, the value will be false.+ normalizedNewCreateDatabaseNameMap map[string]bool++ // 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+}++// EnterCreate_Table is called when production create_Table is entered.+func (l *migrationCompatibilityChecker) EnterCreate_table(ctx *parser.Create_tableContext) {+ normalizedFullTableName := bbparser.NormalizeObjectName(ctx.Object_name(), l.currentDatabase, "PUBLIC")+ l.normalizedNewCreateTableNameMap[normalizedFullTableName] = ctx.If_not_exists() == nil+}++// EnterCreate_table_as_select is called when production create_table_as_select is entered.+func (l *migrationCompatibilityChecker) EnterCreate_table_as_select(ctx *parser.Create_table_as_selectContext) {+ normalizedFullTableName := bbparser.NormalizeObjectName(ctx.Object_name(), l.currentDatabase, "PUBLIC")+ l.normalizedNewCreateTableNameMap[normalizedFullTableName] = ctx.If_not_exists() == nil+}++// EnterCreate_schema is called when production create_schema is entered.+func (l *migrationCompatibilityChecker) EnterCreate_schema(ctx *parser.Create_schemaContext) {+ normalizedFullSchemaName := bbparser.NormalizeSchemaName(ctx.Schema_name(), l.currentDatabase)+ l.normalizedNewCreateSchemaNameMap[normalizedFullSchemaName] = ctx.If_not_exists() == nil+}++// EnterCreate_database is called when production create_database is entered.+func (l *migrationCompatibilityChecker) EnterCreate_database(ctx *parser.Create_databaseContext) {+ normalizedFullDatabaseName := bbparser.NormalizeObjectNamePart(ctx.Id_())+ l.normalizedNewCreateDatabaseNameMap[normalizedFullDatabaseName] = ctx.If_not_exists() == nil+}++// EnterDrop_table is called when production drop_table is entered.+func (l *migrationCompatibilityChecker) EnterDrop_table(ctx *parser.Drop_tableContext) {+ normalizedFullDropTableName := bbparser.NormalizeObjectName(ctx.Object_name(), l.currentDatabase, "PUBLIC")+ mustNewCreate, ok := l.normalizedNewCreateTableNameMap[normalizedFullDropTableName]+ if ok && mustNewCreate {+ return+ }+ level := l.level+ if ok && !mustNewCreate {+ level = advisor.Warn+ }+ l.adviceList = append(l.adviceList, advisor.Advice{+ Status: level,+ Code: advisor.CompatibilityDropTable,+ Title: l.title,+ Content: fmt.Sprintf("Drop table %q may cause incompatibility with the existing data and code", normalizedFullDropTableName),+ Line: ctx.GetStart().GetLine(),+ })+}++// EnterDrop_schema is called when production drop_schema is entered.+func (l *migrationCompatibilityChecker) EnterDrop_schema(ctx *parser.Drop_schemaContext) {+ normalizedFullDropSchemaName := bbparser.NormalizeSchemaName(ctx.Schema_name(), l.currentDatabase)+ mustNewCreate, ok := l.normalizedNewCreateSchemaNameMap[normalizedFullDropSchemaName]+ if ok && mustNewCreate {+ return+ }+ level := l.level+ if ok && !mustNewCreate {+ level = advisor.Warn+ }+ l.adviceList = append(l.adviceList, advisor.Advice{+ Status: level,+ Code: advisor.CompatibilityDropSchema,+ Title: l.title,+ Content: fmt.Sprintf("Drop schema %q may cause incompatibility with the existing data and code", normalizedFullDropSchemaName),+ Line: ctx.GetStart().GetLine(),+ })+}++// EnterDrop_database is called when production drop_database is entered.+func (l *migrationCompatibilityChecker) EnterDrop_database(ctx *parser.Drop_databaseContext) {+ normalizedFullDropDatabaseName := bbparser.NormalizeObjectNamePart(ctx.Id_())+ mustNewCreate, ok := l.normalizedNewCreateDatabaseNameMap[normalizedFullDropDatabaseName]+ if ok && mustNewCreate {+ return+ }+ level := l.level+ if ok && !mustNewCreate {+ level = advisor.Warn+ }+ l.adviceList = append(l.adviceList, advisor.Advice{+ Status: level,+ Code: advisor.CompatibilityDropDatabase,+ Title: l.title,+ Content: fmt.Sprintf("Drop database %q may cause incompatibility with the existing data and code", normalizedFullDropDatabaseName),+ Line: ctx.GetStart().GetLine(),+ })+}++// EnterAlter_table is called when production alter_table is entered.+func (l *migrationCompatibilityChecker) EnterAlter_table(ctx *parser.Alter_tableContext) {+ tableColumnAction := ctx.Table_column_action()+ if tableColumnAction == nil {+ return+ }+ dropColumn := tableColumnAction.DROP(0)+ if dropColumn == nil {+ return+ }+ allColumnName := tableColumnAction.Column_list().AllColumn_name()+ normalizedAllColumnNames := make([]string, 0, len(allColumnName))+ for _, columnName := range allColumnName {+ normalizedAllColumnNames = append(normalizedAllColumnNames, fmt.Sprintf("%q", bbparser.NormalizeObjectNamePart(columnName.Id_())))+ }+ l.adviceList = append(l.adviceList, advisor.Advice{+ Status: l.level,+ Code: advisor.CompatibilityDropColumn,+ Title: l.title,+ Content: fmt.Sprintf("Drop column %s may cause incompatibility with the existing data and code", strings.Join(normalizedAllColumnNames, ",")),+ Line: ctx.GetStart().GetLine(),+ })+}diff --git a/backend/plugin/advisor/snowflake/advisor_table_no_foreign_key.go b/backend/plugin/advisor/snowflake/advisor_table_no_foreign_key.goindex aff63ad4f5..66ec642d5e 100644--- a/backend/plugin/advisor/snowflake/advisor_table_no_foreign_key.go+++ b/backend/plugin/advisor/snowflake/advisor_table_no_foreign_key.go@@ -106,7 +106,7 @@ func (l *tableNoForeignKeyChecker) generateAdvice() ([]advisor.Advice, error) {// EnterCreate_table is called when production create_table is entered.func (l *tableNoForeignKeyChecker) EnterCreate_table(ctx *parser.Create_tableContext) {originalTableName := ctx.Object_name()- normalizedTableName := snowsqlparser.NormalizeObjectName(originalTableName)+ normalizedTableName := snowsqlparser.NormalizeObjectName(originalTableName, "", "PUBLIC")l.tableForeignKeyTimes[normalizedTableName] = 0l.tableOriginalName[normalizedTableName] = originalTableName.GetText()@@ -167,7 +167,7 @@ func (l *tableNoForeignKeyChecker) EnterAlter_table(ctx *parser.Alter_tableContereturn}originalTableName := ctx.Object_name(0)- normalizedTableName := snowsqlparser.NormalizeObjectName(originalTableName)+ normalizedTableName := snowsqlparser.NormalizeObjectName(originalTableName, "", "PUBLIC")l.currentNormalizedTableName = normalizedTableNamel.tableOriginalName[normalizedTableName] = originalTableName.GetText()diff --git a/backend/plugin/advisor/snowflake/advisor_table_require_pk.go b/backend/plugin/advisor/snowflake/advisor_table_require_pk.goindex 3c265a405e..63378f49c3 100644--- a/backend/plugin/advisor/snowflake/advisor_table_require_pk.go+++ b/backend/plugin/advisor/snowflake/advisor_table_require_pk.go@@ -106,7 +106,7 @@ func (l *tableRequirePkChecker) generateAdvice() ([]advisor.Advice, error) {// EnterCreate_table is called when production create_table is entered.func (l *tableRequirePkChecker) EnterCreate_table(ctx *parser.Create_tableContext) {originalTableName := ctx.Object_name()- normalizedTableName := snowsqlparser.NormalizeObjectName(originalTableName)+ normalizedTableName := snowsqlparser.NormalizeObjectName(originalTableName, "", "PUBLIC")l.tableHasPrimaryKey[normalizedTableName] = falsel.tableOriginalName[normalizedTableName] = originalTableName.GetText()@@ -118,7 +118,7 @@ func (l *tableRequirePkChecker) EnterCreate_table(ctx *parser.Create_tableContex// EnterDrop_table is called when production drop_table is entered.func (l *tableRequirePkChecker) EnterDrop_table(ctx *parser.Drop_tableContext) {originalTableName := ctx.Object_name()- normalizedTableName := snowsqlparser.NormalizeObjectName(originalTableName)+ normalizedTableName := snowsqlparser.NormalizeObjectName(originalTableName, "", "PUBLIC")delete(l.tableHasPrimaryKey, normalizedTableName)delete(l.tableOriginalName, normalizedTableName)@@ -176,7 +176,7 @@ func (l *tableRequirePkChecker) EnterAlter_table(ctx *parser.Alter_tableContext)return}originalTableName := ctx.Object_name(0)- normalizedTableName := snowsqlparser.NormalizeObjectName(originalTableName)+ normalizedTableName := snowsqlparser.NormalizeObjectName(originalTableName, "", "PUBLIC")l.currentNormalizedTableName = normalizedTableNamel.tableOriginalName[normalizedTableName] = originalTableName.GetText()diff --git a/backend/plugin/advisor/snowflake/snowflake_rules_test.go b/backend/plugin/advisor/snowflake/snowflake_rules_test.goindex 589fbe3e9b..50159edcfa 100644--- a/backend/plugin/advisor/snowflake/snowflake_rules_test.go+++ b/backend/plugin/advisor/snowflake/snowflake_rules_test.go@@ -22,6 +22,7 @@ func TestSnowflakeRules(t *testing.T) {advisor.SchemaRuleColumnNotNull,advisor.SchemaRuleStatementNoSelectAll,advisor.SchemaRuleTableDropNamingConvention,+ advisor.SchemaRuleSchemaBackwardCompatibility,}for _, rule := range snowflakeRules {diff --git a/backend/plugin/advisor/snowflake/test/schema_backward_compatibility.yaml b/backend/plugin/advisor/snowflake/test/schema_backward_compatibility.yamlnew file mode 100644index 0000000000..a8cb61587e--- /dev/null+++ b/backend/plugin/advisor/snowflake/test/schema_backward_compatibility.yaml@@ -0,0 +1,52 @@+- statement: DROP DATABASE DB;+ want:+ - status: WARN+ code: 101+ title: schema.backward-compatibility+ content: Drop database "DB" may cause incompatibility with the existing data and code+ line: 1+ details: ""+- statement: DROP SCHEMA SCHEMA1;+ want:+ - status: WARN+ code: 112+ title: schema.backward-compatibility+ content: Drop schema "TEST_DB.SCHEMA1" may cause incompatibility with the existing data and code+ line: 1+ details: ""+- statement: DROP TABLE T;+ want:+ - status: WARN+ code: 103+ title: schema.backward-compatibility+ content: Drop table "TEST_DB.PUBLIC.T" may cause incompatibility with the existing data and code+ line: 1+ details: ""+- statement: ALTER TABLE T DROP COLUMN COL1;+ want:+ - status: WARN+ code: 105+ title: schema.backward-compatibility+ content: Drop column "COL1" may cause incompatibility with the existing data and code+ line: 1+ details: ""+- statement: |-+ CREATE TABLE IF NOT EXISTS T(ID INT);+ DROP TABLE T;+ want:+ - status: WARN+ code: 103+ title: schema.backward-compatibility+ content: Drop table "TEST_DB.PUBLIC.T" may cause incompatibility with the existing data and code+ line: 2+ details: ""+- statement: |-+ CREATE TABLE T(ID INT);+ DROP TABLE T;+ want:+ - status: SUCCESS+ code: 0+ title: OK+ content: ""+ line: 0+ details: ""diff --git a/backend/plugin/advisor/sql_review.go b/backend/plugin/advisor/sql_review.goindex 45ebe568ea..53f1544797 100644--- a/backend/plugin/advisor/sql_review.go+++ b/backend/plugin/advisor/sql_review.go@@ -476,6 +476,8 @@ type SQLReviewCheckContext struct {Driver *sql.DBContext context.Context+ // Snowflake specific fields+ CurrentDatabase string// Oracle specific fieldsCurrentSchema string}@@ -724,14 +726,15 @@ func SQLReviewCheck(statements string, ruleList []*SQLReviewRule, checkContext ScheckContext.DbType,advisorType,Context{- Charset: checkContext.Charset,- Collation: checkContext.Collation,- AST: ast,- Rule: rule,- Catalog: finder,- Driver: checkContext.Driver,- Context: checkContext.Context,- CurrentSchema: checkContext.CurrentSchema,+ Charset: checkContext.Charset,+ Collation: checkContext.Collation,+ AST: ast,+ Rule: rule,+ Catalog: finder,+ Driver: checkContext.Driver,+ Context: checkContext.Context,+ CurrentSchema: checkContext.CurrentSchema,+ CurrentDatabase: checkContext.CurrentDatabase,},statements,)@@ -1049,6 +1052,8 @@ func getAdvisorTypeByRule(ruleType SQLReviewRuleType, engine db.Type) (Type, errreturn MySQLMigrationCompatibility, nilcase db.Postgres:return PostgreSQLMigrationCompatibility, nil+ case db.Snowflake:+ return SnowflakeMigrationCompatibility, nil}case SchemaRuleTableNaming:switch engine {diff --git a/backend/plugin/advisor/utils_for_tests.go b/backend/plugin/advisor/utils_for_tests.goindex 300c772ac3..a73c90ac32 100644--- a/backend/plugin/advisor/utils_for_tests.go+++ b/backend/plugin/advisor/utils_for_tests.go@@ -175,13 +175,14 @@ func RunSQLReviewRuleTest(t *testing.T, rule SQLReviewRuleType, dbType db.Type,}ctx := SQLReviewCheckContext{- Charset: "",- Collation: "",- DbType: dbType,- Catalog: &testCatalog{finder: finder},- Driver: nil,- Context: context.Background(),- CurrentSchema: "SYS",+ Charset: "",+ Collation: "",+ DbType: dbType,+ Catalog: &testCatalog{finder: finder},+ Driver: nil,+ Context: context.Background(),+ CurrentSchema: "SYS",+ CurrentDatabase: "TEST_DB",}adviceList, err := SQLReviewCheck(tc.Statement, ruleList, ctx)diff --git a/backend/plugin/parser/sql/snowsql.go b/backend/plugin/parser/sql/snowsql.goindex f12453b3a7..f1d58f2e70 100644--- a/backend/plugin/parser/sql/snowsql.go+++ b/backend/plugin/parser/sql/snowsql.go@@ -242,27 +242,25 @@ func extractSnowflakeNormalizeResourceListFromSelectStatement(currentNormalizedD}// NormalizeObjectName normalizes the given object name.-func NormalizeObjectName(objectName parser.IObject_nameContext) string {+func NormalizeObjectName(objectName parser.IObject_nameContext, fallbackDatabaseName, fallbackSchemaName string) string {var parts []string+ database := fallbackDatabaseNameif d := objectName.GetD(); d != nil {normalizedD := NormalizeObjectNamePart(d)if normalizedD != "" {- parts = append(parts, normalizedD)+ database = normalizedD}}+ parts = append(parts, database)- var schema string+ schema := fallbackSchemaNameif s := objectName.GetS(); s != nil {normalizedS := NormalizeObjectNamePart(s)if normalizedS != "" {schema = normalizedS}}- if schema == "" {- // Backfill default schema "PUBLIC" if schema is not specified.- schema = "PUBLIC"- }parts = append(parts, schema)if o := objectName.GetO(); o != nil {@@ -274,6 +272,36 @@ func NormalizeObjectName(objectName parser.IObject_nameContext) string {return strings.Join(parts, ".")}+// NormalizeSchemaName normalizes the given schema name.+func NormalizeSchemaName(schemaName parser.ISchema_nameContext, fallbackDatabaseName string) string {+ ids := schemaName.AllId_()++ var parts []string+ database := fallbackDatabaseName+ if len(ids) == 2 {+ normalizedD := NormalizeObjectNamePart(ids[0])+ if normalizedD != "" {+ database = normalizedD+ }+ }+ parts = append(parts, database)++ var schema string+ if len(ids) == 2 {+ normalizedS := NormalizeObjectNamePart(ids[1])+ if normalizedS != "" {+ schema = normalizedS+ }+ } else {+ normalizedS := NormalizeObjectNamePart(ids[0])+ if normalizedS != "" {+ schema = normalizedS+ }+ }+ parts = append(parts, schema)+ return strings.Join(parts, ".")+}+// NormalizeObjectNamePart normalizes the object name part.func NormalizeObjectNamePart(part parser.IId_Context) string {if part == nil {