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 column no null (#6686)
h3n4l3302c1a22670
diff --git a/backend/plugin/advisor/advisor.go b/backend/plugin/advisor/advisor.goindex 395207e9d9..9f371b8c78 100644--- a/backend/plugin/advisor/advisor.go+++ b/backend/plugin/advisor/advisor.go@@ -420,6 +420,9 @@ const (// SnowflakeIdentifierCase is an advisor type for Snowflake identifier case.SnowflakeIdentifierCase Type = "bb.plugin.advisor.snowflake.naming.identifier-case"++ // SnowflakeColumnNoNull is an advisor type for Snowflake column no NULL value.+ SnowflakeColumnNoNull Type = "bb.plugin.advisor.snowflake.column.no-null")// Advice is the result of an advisor.diff --git a/backend/plugin/advisor/snowflake/advisor_column_no_null.go b/backend/plugin/advisor/snowflake/advisor_column_no_null.gonew file mode 100644index 0000000000..97b4e7e1c4--- /dev/null+++ b/backend/plugin/advisor/snowflake/advisor_column_no_null.go@@ -0,0 +1,208 @@+// Package snowflake is the advisor for snowflake database.+package snowflake++import (+ "fmt"++ "github.com/antlr4-go/antlr/v4"+ parser "github.com/bytebase/snowsql-parser"++ "github.com/bytebase/bytebase/backend/plugin/advisor"+ "github.com/bytebase/bytebase/backend/plugin/advisor/db"+)++var (+ _ advisor.Advisor = (*ColumnNoNullAdvisor)(nil)+)++func init() {+ advisor.Register(db.Snowflake, advisor.SnowflakeColumnNoNull, &ColumnNoNullAdvisor{})+}++// ColumnNoNullAdvisor is the advisor checking for column no NULL value.+type ColumnNoNullAdvisor struct {+}++// Check checks for column no NULL value.+func (*ColumnNoNullAdvisor) 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+ }++ listener := &columnNoNullChecker{+ level: level,+ title: string(ctx.Rule.Type),+ currentOriginalTableName: "",+ columnNullable: make(map[string]int),+ }++ antlr.ParseTreeWalkerDefault.Walk(listener, tree)++ return listener.generateAdvice()+}++// columnNoNullChecker is the listener for column no NULL value.+type columnNoNullChecker struct {+ *parser.BaseSnowflakeParserListener++ level advisor.Status+ title string++ adviceList []advisor.Advice++ // currentOriginalTableName is the original table name of the current table.+ currentOriginalTableName string+ // columnNullable is a map from normalized column name to the line number causing the column to be nullable.+ columnNullable map[string]int+}++// generateAdvice returns the advices generated by the listener, the advices must not be empty.+func (l *columnNoNullChecker) 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 *columnNoNullChecker) EnterCreate_table(ctx *parser.Create_tableContext) {+ l.currentOriginalTableName = ctx.Object_name().GetText()+}++// ExitCreate_table is called when production create_table is exited.+func (l *columnNoNullChecker) ExitCreate_table(*parser.Create_tableContext) {+ for normalizedColumnName, columnNullableLine := range l.columnNullable {+ l.adviceList = append(l.adviceList, advisor.Advice{+ Status: l.level,+ Code: advisor.ColumnCannotNull,+ Title: l.title,+ Content: fmt.Sprintf("Column %s is nullable, which is not allowed.", normalizedColumnName),+ Line: columnNullableLine,+ })+ }+ l.currentOriginalTableName = ""+ l.columnNullable = make(map[string]int)+}++// EnterFull_col_decl is called when production full_col_decl is entered.+func (l *columnNoNullChecker) EnterFull_col_decl(ctx *parser.Full_col_declContext) {+ if l.currentOriginalTableName == "" {+ return+ }+ normalizedOriginalColumnID := normalizeObjectNamePart(ctx.Col_decl().Column_name().Id_())+ l.columnNullable[normalizedOriginalColumnID] = ctx.GetStart().GetLine()+ for _, nullNotNull := range ctx.AllNull_not_null() {+ if nullNotNull.NOT() != nil {+ delete(l.columnNullable, normalizedOriginalColumnID)+ break+ }+ }+ for _, constraint := range ctx.AllInline_constraint() {+ if constraint.PRIMARY() != nil {+ delete(l.columnNullable, normalizedOriginalColumnID)+ break+ }+ }+}++// EnterOut_of_line_constraint is called when production out_of_line_constraint is entered.+func (l *columnNoNullChecker) EnterOut_of_line_constraint(ctx *parser.Out_of_line_constraintContext) {+ if l.currentOriginalTableName == "" {+ return+ }+ if ctx.PRIMARY() != nil {+ for _, columnListInParentheses := range ctx.AllColumn_list_in_parentheses() {+ for _, column := range columnListInParentheses.Column_list().AllColumn_name() {+ normalizedOriginalColumnID := normalizeObjectNamePart(column.Id_())+ delete(l.columnNullable, normalizedOriginalColumnID)+ }+ }+ }+}++// EnterAlter_table is called when production alter_table is entered.+func (l *columnNoNullChecker) EnterAlter_table(ctx *parser.Alter_tableContext) {+ l.currentOriginalTableName = ctx.Object_name(0).GetText()+}++// ExitAlter_table is called when production alter_table is exited.+func (l *columnNoNullChecker) ExitAlter_table(*parser.Alter_tableContext) {+ for normalizedColumnName, columnNullableLine := range l.columnNullable {+ l.adviceList = append(l.adviceList, advisor.Advice{+ Status: l.level,+ Code: advisor.ColumnCannotNull,+ Title: l.title,+ Content: fmt.Sprintf("Column %s is nullable, which is not allowed.", normalizedColumnName),+ Line: columnNullableLine,+ })+ }+ l.currentOriginalTableName = ""+ l.columnNullable = make(map[string]int)+}++// EnterTable_column_action is called when production alter_table_add_constraint is entered.+func (l *columnNoNullChecker) EnterTable_column_action(ctx *parser.Table_column_actionContext) {+ if l.currentOriginalTableName == "" {+ return+ }+ if ctx.ADD() != nil {+ normalizedNewColumnName := normalizeObjectNamePart(ctx.Column_name(0).Id_())+ inlineConstraintHasPK := ctx.Inline_constraint() != nil && ctx.Inline_constraint().PRIMARY() != nil+ inlineConstraintHasNotNull := ctx.Inline_constraint() != nil && (ctx.Inline_constraint().Null_not_null() != nil && ctx.Inline_constraint().Null_not_null().NOT() != nil)+ hasNotNull := ctx.Null_not_null() != nil && ctx.Null_not_null().NOT() != nil++ if !(inlineConstraintHasPK || inlineConstraintHasNotNull || hasNotNull) {+ l.columnNullable[normalizedNewColumnName] = ctx.GetStart().GetLine()+ }+ return+ }+ if ctx.Alter_modify() != nil {+ normalizedOriginalColumnName := normalizeObjectNamePart(ctx.Column_name(0).Id_())+ if len(ctx.AllDROP()) == 1 && ctx.NOT() != nil && ctx.NULL_() != nil {+ l.columnNullable[normalizedOriginalColumnName] = ctx.GetStart().GetLine()+ }+ return+ }+}++// EnterAlter_table_alter_column is called when production alter_table_alter_column is entered.+func (l *columnNoNullChecker) EnterAlter_table_alter_column(ctx *parser.Alter_table_alter_columnContext) {+ l.currentOriginalTableName = ctx.Object_name().GetText()+}++// ExitAlter_table_alter_column is called when production alter_table_alter_column is exited.+func (l *columnNoNullChecker) ExitAlter_table_alter_column(*parser.Alter_table_alter_columnContext) {+ for normalizedColumnName, columnNullableLine := range l.columnNullable {+ l.adviceList = append(l.adviceList, advisor.Advice{+ Status: l.level,+ Code: advisor.ColumnCannotNull,+ Title: l.title,+ Content: fmt.Sprintf("After dropping NOT NULL of column %s, it will be nullable, which is not allowed.", normalizedColumnName),+ Line: columnNullableLine,+ })+ }+ l.currentOriginalTableName = ""+ l.columnNullable = make(map[string]int)+}++// EnterAlter_column_decl is called when production alter_column_decl is entered.+func (l *columnNoNullChecker) EnterAlter_column_decl(ctx *parser.Alter_column_declContext) {+ if l.currentOriginalTableName == "" {+ return+ }+ normalizedNewColumnName := normalizeObjectNamePart(ctx.Column_name().Id_())+ if ctx.Alter_column_opts().DROP() != nil && ctx.Alter_column_opts().NOT() != nil && ctx.Alter_column_opts().NULL_() != nil {+ l.columnNullable[normalizedNewColumnName] = ctx.GetStart().GetLine()+ }+}diff --git a/backend/plugin/advisor/snowflake/snowflake_rules_test.go b/backend/plugin/advisor/snowflake/snowflake_rules_test.goindex ea0dc889df..70686a35e4 100644--- a/backend/plugin/advisor/snowflake/snowflake_rules_test.go+++ b/backend/plugin/advisor/snowflake/snowflake_rules_test.go@@ -19,6 +19,7 @@ func TestSnowflakeRules(t *testing.T) {advisor.SchemaRuleIdentifierNoKeyword,advisor.SchemaRuleRequiredColumn,advisor.SchemaRuleIdentifierCase,+ advisor.SchemaRuleColumnNotNull,}for _, rule := range snowflakeRules {diff --git a/backend/plugin/advisor/snowflake/test/column_no_null.yaml b/backend/plugin/advisor/snowflake/test/column_no_null.yamlnew file mode 100644index 0000000000..4bcfba22a0--- /dev/null+++ b/backend/plugin/advisor/snowflake/test/column_no_null.yaml@@ -0,0 +1,73 @@+- statement: |-+ CREATE TABLE t (+ id INT PRIMARY KEY,+ name VARCHAR(100) NOT NULL,+ age INT,+ address VARCHAR+ );+ want:+ - status: WARN+ code: 402+ title: column.no-null+ content: Column AGE is nullable, which is not allowed.+ line: 4+ details: ""+ - status: WARN+ code: 402+ title: column.no-null+ content: Column ADDRESS is nullable, which is not allowed.+ line: 5+ details: ""+- statement: |-+ CREATE TABLE t (+ id INT,+ name VARCHAR(100) NOT NULL,+ age INT,+ address VARCHAR,+ PRIMARY KEY (id, age)+ )+ want:+ - status: WARN+ code: 402+ title: column.no-null+ content: Column ADDRESS is nullable, which is not allowed.+ line: 5+ details: ""+- statement: |-+ CREATE TABLE t (+ id INT NOT NULL,+ name VARCHAR(100) NOT NULL,+ age INT NOT NULL,+ address VARCHAR NOT NULL+ );+ want:+ - status: SUCCESS+ code: 0+ title: OK+ content: ""+ line: 0+ details: ""+- statement: ALTER TABLE a ADD COLUMN age INT;+ want:+ - status: WARN+ code: 402+ title: column.no-null+ content: Column AGE is nullable, which is not allowed.+ line: 1+ details: ""+- statement: ALTER TABLE a ADD COLUMN age INT NOT NULL;+ want:+ - status: SUCCESS+ code: 0+ title: OK+ content: ""+ line: 0+ details: ""+- statement: ALTER TABLE a ALTER COLUMN age DROP NOT NULL;+ want:+ - status: WARN+ code: 402+ title: column.no-null+ content: After dropping NOT NULL of column AGE, it will be nullable, which is not allowed.+ line: 1+ details: ""diff --git a/backend/plugin/advisor/sql_review.go b/backend/plugin/advisor/sql_review.goindex ea921860a3..2cf18f7f29 100644--- a/backend/plugin/advisor/sql_review.go+++ b/backend/plugin/advisor/sql_review.go@@ -915,6 +915,8 @@ func getAdvisorTypeByRule(ruleType SQLReviewRuleType, engine db.Type) (Type, errreturn PostgreSQLColumnNoNull, nilcase db.Oracle:return OracleColumnNoNull, nil+ case db.Snowflake:+ return SnowflakeColumnNoNull, nil}case SchemaRuleColumnDisallowChangeType:switch engine {diff --git a/go.mod b/go.modindex 53f8a12e3b..eb51c67ede 100644--- a/go.mod+++ b/go.mod@@ -14,7 +14,7 @@ require (github.com/blang/semver/v4 v4.0.0github.com/bytebase/mysql-parser v0.0.0-20230612050356-4592d9ba30dagithub.com/bytebase/plsql-parser v0.0.0-20230612081829-80675dfad134- github.com/bytebase/snowsql-parser v0.0.0-20230615025714-80977784d4be+ github.com/bytebase/snowsql-parser v0.0.0-20230618154456-022b48c8d22fgithub.com/casbin/casbin/v2 v2.66.2github.com/cenkalti/backoff/v4 v4.2.0github.com/coreos/go-oidc v2.2.1+incompatiblediff --git a/go.sum b/go.sumindex 002d34c846..19174b76c5 100644--- a/go.sum+++ b/go.sum@@ -143,8 +143,8 @@ github.com/bytebase/pg_query_go/v2 v2.0.0-20221123093650-17425d1d18b7 h1:RDN6Unjgithub.com/bytebase/pg_query_go/v2 v2.0.0-20221123093650-17425d1d18b7/go.mod h1:XAxmVqz1tEGqizcQ3YSdN90vCOHBWjJi8URL1er5+cA=github.com/bytebase/plsql-parser v0.0.0-20230612081829-80675dfad134 h1:4NWP76NVYstvWPtZu4JwRmKDHK+1PudmODEdCQLfU8g=github.com/bytebase/plsql-parser v0.0.0-20230612081829-80675dfad134/go.mod h1:kL1Tk89SNE7wPnUzkVMJ9v012an5z8as7OUmkapJQGs=-github.com/bytebase/snowsql-parser v0.0.0-20230615025714-80977784d4be h1:ztVviS4lCHCisawuJD4jdkGeM3P/kIBj5csWkf9H+bE=-github.com/bytebase/snowsql-parser v0.0.0-20230615025714-80977784d4be/go.mod h1:gJ1aclz1e9xLArQTbCpDjL+A79Jt3Ro9+/QEw8A6vMM=+github.com/bytebase/snowsql-parser v0.0.0-20230618154456-022b48c8d22f h1:9jmKoZQf6wYiyKqNxlFwctXcgDCEWiJlABA2rxDOal0=+github.com/bytebase/snowsql-parser v0.0.0-20230618154456-022b48c8d22f/go.mod h1:gJ1aclz1e9xLArQTbCpDjL+A79Jt3Ro9+/QEw8A6vMM=github.com/bytebase/tidb v0.0.0-20230329095902-fe196d3c77d0 h1:h0LzCFbiCKWy/TbnE5amjDf+/j+06chImQwEhe+TbHc=github.com/bytebase/tidb v0.0.0-20230329095902-fe196d3c77d0/go.mod h1:xrVXE+0V54QRGgrD9o+tuZmBDDx8vJpQgrPtRQvodWo=github.com/bytebase/tidb/parser v0.0.0-20230329095902-fe196d3c77d0 h1:Xdq53fvcG9qeUKkxdNbR9B1JLbfeIjhW2N0xxFbaZNg=