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): support snowflake sql review require column (#6651)
h3n4l64302b3d92ca
diff --git a/backend/plugin/advisor/advisor.go b/backend/plugin/advisor/advisor.goindex 3d99abe9d5..c047b22233 100644--- a/backend/plugin/advisor/advisor.go+++ b/backend/plugin/advisor/advisor.go@@ -411,6 +411,9 @@ const (// SnowflakeWhereRequirement is an advisor type for Snowflake WHERE clause requirement.SnowflakeWhereRequirement Type = "bb.plugin.advisor.snowflake.where.require"++ // SnowflakeColumnRequirement is an advisor type for Snowflake column requirement.+ SnowflakeColumnRequirement Type = "bb.plugin.advisor.snowflake.column.require")// Advice is the result of an advisor.diff --git a/backend/plugin/advisor/snowflake/advisor_column_require.go b/backend/plugin/advisor/snowflake/advisor_column_require.gonew file mode 100644index 0000000000..e380412b13--- /dev/null+++ b/backend/plugin/advisor/snowflake/advisor_column_require.go@@ -0,0 +1,184 @@+// Package snowflake is the advisor for snowflake database.+package snowflake++import (+ "fmt"++ "github.com/antlr4-go/antlr/v4"+ parser "github.com/bytebase/snowsql-parser"+ "golang.org/x/exp/slices"++ "github.com/bytebase/bytebase/backend/plugin/advisor"+ "github.com/bytebase/bytebase/backend/plugin/advisor/db"+)++var (+ _ advisor.Advisor = (*ColumnRequireAdvisor)(nil)+)++func init() {+ advisor.Register(db.Snowflake, advisor.SnowflakeColumnRequirement, &ColumnRequireAdvisor{})+}++// ColumnRequireAdvisor is the advisor checking for column requirement.+type ColumnRequireAdvisor struct {+}++// Check checks for column requirement.+func (*ColumnRequireAdvisor) Check(ctx advisor.Context, statement string) ([]advisor.Advice, error) {+ tree, errAdvice := parseStatement(statement)+ if errAdvice != nil {+ return errAdvice, nil+ }++ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)+ if err != nil {+ return nil, err+ }+ columnList, err := advisor.UnmarshalRequiredColumnList(ctx.Rule.Payload)+ if err != nil {+ return nil, err+ }++ listener := &columnRequireChecker{+ level: level,+ title: string(ctx.Rule.Type),+ requireColumns: make(map[string]any),+ }++ for _, column := range columnList {+ listener.requireColumns[column] = true+ }++ antlr.ParseTreeWalkerDefault.Walk(listener, tree)++ return listener.generateAdvice()+}++// columnRequireChecker is the listener for column requirement.+type columnRequireChecker struct {+ *parser.BaseSnowflakeParserListener++ level advisor.Status+ title string++ adviceList []advisor.Advice++ // requireColumns is the required columns, the key is the normalized column name.+ requireColumns map[string]any++ // The following variables should be clean up when ENTER some statement.+ //+ // currentMissingColumn is the missing column, the key is the normalized column name.+ currentMissingColumn map[string]any+ // currentOriginalTableName is the original table name, should be reset when QUIT some statement.+ currentOriginalTableName string+}++// generateAdvice returns the advices generated by the listener, the advices must not be empty.+func (l *columnRequireChecker) 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 *columnRequireChecker) EnterCreate_table(ctx *parser.Create_tableContext) {+ l.currentOriginalTableName = ctx.Object_name().GetText()+ l.currentMissingColumn = make(map[string]any)+ for column := range l.requireColumns {+ l.currentMissingColumn[column] = true+ }+}++// EnterColumn_decl_item_list is called when production column_decl_item_list is entered.+func (l *columnRequireChecker) EnterColumn_decl_item_list(ctx *parser.Column_decl_item_listContext) {+ if l.currentOriginalTableName == "" {+ return+ }+ allColumnDeclItems := ctx.AllColumn_decl_item()+ for _, columnDeclItem := range allColumnDeclItems {+ if fullColDecl := columnDeclItem.Full_col_decl(); fullColDecl != nil {+ normalizedColumnName := normalizeObjectNamePart(fullColDecl.Col_decl().Column_name().Id_())+ delete(l.currentMissingColumn, normalizedColumnName)+ }+ }+}++// ExitCreate_table is called when production create_table is exited.+func (l *columnRequireChecker) ExitCreate_table(ctx *parser.Create_tableContext) {+ columnNames := make([]string, 0, len(l.currentMissingColumn))+ for column := range l.currentMissingColumn {+ columnNames = append(columnNames, column)+ }+ if len(columnNames) == 0 {+ return+ }++ slices.SortFunc[string](columnNames, func(i, j string) bool {+ return i < j+ })+ for _, column := range columnNames {+ l.adviceList = append(l.adviceList, advisor.Advice{+ Status: l.level,+ Code: advisor.NoRequiredColumn,+ Title: l.title,+ Content: fmt.Sprintf("Table %s missing required column %q", l.currentOriginalTableName, column),+ Line: ctx.Column_decl_item_list().GetStop().GetLine(),+ })+ }+ l.currentOriginalTableName = ""+ l.currentMissingColumn = nil+}++// EnterAlter_table is called when production alter_table is entered.+func (l *columnRequireChecker) EnterAlter_table(ctx *parser.Alter_tableContext) {+ l.currentOriginalTableName = ctx.Object_name(0).GetText()+ l.currentMissingColumn = make(map[string]any)+}++func (l *columnRequireChecker) EnterTable_column_action(ctx *parser.Table_column_actionContext) {+ if l.currentOriginalTableName == "" || len(ctx.AllDROP()) != 1 || ctx.Alter_modify() != nil {+ return+ }++ for _, columnName := range ctx.Column_list().AllColumn_name() {+ originalColumName := columnName.GetText()+ normalizedColumnName := extractOrdinaryIdentifier(originalColumName)+ if _, ok := l.requireColumns[normalizedColumnName]; ok {+ l.currentMissingColumn[normalizedColumnName] = true+ }+ }+}++// ExitAlter_table is called when production alter_table is exited.+func (l *columnRequireChecker) ExitAlter_table(ctx *parser.Alter_tableContext) {+ columnNames := make([]string, 0, len(l.currentMissingColumn))+ for column := range l.currentMissingColumn {+ columnNames = append(columnNames, column)+ }+ if len(columnNames) == 0 {+ return+ }++ slices.SortFunc[string](columnNames, func(i, j string) bool {+ return i < j+ })+ for _, column := range columnNames {+ l.adviceList = append(l.adviceList, advisor.Advice{+ Status: l.level,+ Code: advisor.NoRequiredColumn,+ Title: l.title,+ Content: fmt.Sprintf("Table %s missing required column %q", l.currentOriginalTableName, column),+ Line: ctx.Table_column_action().GetStart().GetLine(),+ })+ }+ l.currentOriginalTableName = ""+ l.currentMissingColumn = nil+}diff --git a/backend/plugin/advisor/snowflake/snowflake_rules_test.go b/backend/plugin/advisor/snowflake/snowflake_rules_test.goindex 7824bdfd2f..90e9fd2ae0 100644--- a/backend/plugin/advisor/snowflake/snowflake_rules_test.go+++ b/backend/plugin/advisor/snowflake/snowflake_rules_test.go@@ -16,6 +16,7 @@ func TestSnowflakeRules(t *testing.T) {advisor.SchemaRuleColumnMaximumVarcharLength,advisor.SchemaRuleTableNameNoKeyword,advisor.SchemaRuleStatementRequireWhere,+ advisor.SchemaRuleRequiredColumn,}for _, rule := range snowflakeRules {diff --git a/backend/plugin/advisor/snowflake/test/column_required.yaml b/backend/plugin/advisor/snowflake/test/column_required.yamlnew file mode 100644index 0000000000..c58fd77f65--- /dev/null+++ b/backend/plugin/advisor/snowflake/test/column_required.yaml@@ -0,0 +1,89 @@+- statement: |-+ CREATE TABLE t (+ "id" INT,+ "creator_id" INT,+ "created_ts" INT,+ "updated_ts" INT,+ "updater_id" INT+ );+ want:+ - status: SUCCESS+ code: 0+ title: OK+ content: ""+ line: 0+ details: ""+- statement: |-+ CREATE TABLE t (+ "name" TEXT,+ "age" INT+ );+ want:+ - status: WARN+ code: 401+ title: column.required+ content: Table t missing required column "created_ts"+ line: 3+ details: ""+ - status: WARN+ code: 401+ title: column.required+ content: Table t missing required column "creator_id"+ line: 3+ details: ""+ - status: WARN+ code: 401+ title: column.required+ content: Table t missing required column "id"+ line: 3+ details: ""+ - status: WARN+ code: 401+ title: column.required+ content: Table t missing required column "updated_ts"+ line: 3+ details: ""+ - status: WARN+ code: 401+ title: column.required+ content: Table t missing required column "updater_id"+ line: 3+ details: ""+- statement: |-+ CREATE TABLE t (+ "id" INT,+ "creator_id" INT,+ "created_ts" INT,+ "updater_id" INT+ );+ want:+ - status: WARN+ code: 401+ title: column.required+ content: Table t missing required column "updated_ts"+ line: 5+ details: ""+- statement: ALTER TABLE t DROP COLUMN "created_ts";+ want:+ - status: WARN+ code: 401+ title: column.required+ content: Table t missing required column "created_ts"+ line: 1+ details: ""+- statement: ALTER TABLE t DROP COLUMN creator_id;+ want:+ - status: SUCCESS+ code: 0+ title: OK+ content: ""+ line: 0+ details: ""+- statement: ALTER TABLE TARGET_TABLE ALTER COLUMN description DROP DEFAULT, COLUMN description DROP NOT NULL;+ 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 261021d6ef..ef1c9c8d68 100644--- a/backend/plugin/advisor/sql_review.go+++ b/backend/plugin/advisor/sql_review.go@@ -898,6 +898,8 @@ func getAdvisorTypeByRule(ruleType SQLReviewRuleType, engine db.Type) (Type, errreturn PostgreSQLColumnRequirement, nilcase db.Oracle:return OracleColumnRequirement, nil+ case db.Snowflake:+ return SnowflakeColumnRequirement, nil}case SchemaRuleColumnNotNull:switch engine {diff --git a/backend/plugin/advisor/utils_for_tests.go b/backend/plugin/advisor/utils_for_tests.goindex 5a31370394..a7dc411cff 100644--- a/backend/plugin/advisor/utils_for_tests.go+++ b/backend/plugin/advisor/utils_for_tests.go@@ -5,7 +5,6 @@ import ("database/sql""encoding/json""io"- "math/rand""os""path/filepath""strings"@@ -211,18 +210,6 @@ func RunSQLReviewRuleTest(t *testing.T, rule SQLReviewRuleType, dbType db.Type,}}-// RandomString returns random string with specific length.-func RandomString(length int) string {- var letters = []rune("abcdefghijklmnopqrstuvwxyz")- var rand = rand.New(rand.NewSource(time.Now().UnixNano()))-- b := make([]rune, length)- for i := range b {- b[i] = letters[rand.Intn(len(letters))]- }- return string(b)-}-// MockDriver is the driver for test only.type MockDriver struct {}