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 column_no_null (#9082)
zll60005912467c8f5
diff --git a/backend/plugin/advisor/mysqlwip/advisor_column_no_null.go b/backend/plugin/advisor/mysqlwip/advisor_column_no_null.goindex 4bf64be2f9..3eaf65d07a 100644--- a/backend/plugin/advisor/mysqlwip/advisor_column_no_null.go+++ b/backend/plugin/advisor/mysqlwip/advisor_column_no_null.go@@ -4,27 +4,34 @@ import ("fmt""sort"- "github.com/pingcap/tidb/parser/ast"+ "github.com/antlr4-go/antlr/v4"+ mysql "github.com/bytebase/mysql-parser""github.com/pkg/errors""github.com/bytebase/bytebase/backend/plugin/advisor""github.com/bytebase/bytebase/backend/plugin/advisor/catalog"+ mysqlparser "github.com/bytebase/bytebase/backend/plugin/parser/mysql"+ storepb "github.com/bytebase/bytebase/proto/generated-go/store")var (_ advisor.Advisor = (*ColumnNoNullAdvisor)(nil)- _ ast.Visitor = (*columnNoNullChecker)(nil))+func init() {+ // only for mysqlwip test.+ advisor.Register(storepb.Engine_ENGINE_UNSPECIFIED, advisor.MySQLColumnNoNull, &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, _ 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 parser result")}level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)@@ -39,13 +46,27 @@ func (*ColumnNoNullAdvisor) Check(ctx advisor.Context, _ string) ([]advisor.Advi}for _, stmtNode := range root {- (stmtNode).Accept(checker)+ checker.baseLine = stmtNode.BaseLine+ antlr.ParseTreeWalkerDefault.Walk(checker, stmtNode.Tree)}return checker.generateAdvice(), nil}+type columnName struct {+ tableName string+ columnName string+ line int+}++func (c columnName) name() string {+ return fmt.Sprintf("%s.%s", c.tableName, c.columnName)+}+type columnNoNullChecker struct {+ *mysql.BaseMySQLParserListener++ baseLine intadviceList []advisor.Advicelevel advisor.Statustitle string@@ -53,7 +74,7 @@ type columnNoNullChecker struct {catalog *catalog.Finder}-func (checker columnNoNullChecker) generateAdvice() []advisor.Advice {+func (checker *columnNoNullChecker) generateAdvice() []advisor.Advice {var columnList []columnNamefor _, column := range checker.columnSet {columnList = append(columnList, column)@@ -92,74 +113,89 @@ func (checker columnNoNullChecker) generateAdvice() []advisor.Advice {return checker.adviceList}-type columnName struct {- tableName string- columnName string- line int-}+func (checker *columnNoNullChecker) EnterCreateTable(ctx *mysql.CreateTableContext) {+ if ctx.TableName() == nil {+ return+ }+ if ctx.TableElementList() == nil {+ return+ }-func (c columnName) name() string {- return fmt.Sprintf("%s.%s", c.tableName, c.columnName)+ _, tableName := mysqlparser.NormalizeMySQLTableName(ctx.TableName())+ for _, tableElement := range ctx.TableElementList().AllTableElement() {+ if tableElement == nil {+ continue+ }+ if tableElement.ColumnDefinition() == nil {+ continue+ }++ _, _, column := mysqlparser.NormalizeMySQLColumnName(tableElement.ColumnDefinition().ColumnName())+ if tableElement.ColumnDefinition().FieldDefinition() == nil {+ continue+ }+ col := columnName{+ tableName: tableName,+ columnName: column,+ line: checker.baseLine + tableElement.GetStart().GetLine(),+ }+ if _, exists := checker.columnSet[col.name()]; !exists {+ checker.columnSet[col.name()] = col+ }+ }}-// Enter implements the ast.Visitor interface.-func (checker *columnNoNullChecker) Enter(in ast.Node) (ast.Node, bool) {- switch node := in.(type) {- // CREATE TABLE- case *ast.CreateTableStmt:- for _, column := range node.Cols {- col := columnName{- tableName: node.Table.Name.O,- columnName: column.Name.Name.O,- line: column.OriginTextPosition(),- }- if _, exists := checker.columnSet[col.name()]; !exists {- checker.columnSet[col.name()] = col- }+func (checker *columnNoNullChecker) 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())+ // alter table add column, change column, modify column.+ for _, item := range ctx.AlterTableActions().AlterCommandList().AlterList().AllAlterListItem() {+ if item == nil {+ continue}- // ALTER TABLE- case *ast.AlterTableStmt:- for _, spec := range node.Specs {- switch spec.Tp {- // ADD COLUMNS- case ast.AlterTableAddColumns:- for _, column := range spec.NewColumns {- col := columnName{- tableName: node.Table.Name.O,- columnName: column.Name.Name.O,- line: node.OriginTextPosition(),- }- if _, exists := checker.columnSet[col.name()]; !exists {- checker.columnSet[col.name()] = col++ var columns []string+ switch {+ // add column+ case item.ADD_SYMBOL() != nil:+ switch {+ case item.Identifier() != nil && item.FieldDefinition() != nil:+ column := mysqlparser.NormalizeMySQLIdentifier(item.Identifier())+ columns = append(columns, column)+ case item.OPEN_PAR_SYMBOL() != nil && item.TableElementList() != nil:+ for _, tableElement := range item.TableElementList().AllTableElement() {+ if tableElement.ColumnDefinition() == nil {+ continue}- }- // CHANGE COLUMN- case ast.AlterTableChangeColumn:- col := columnName{- tableName: node.Table.Name.O,- columnName: spec.NewColumns[0].Name.Name.O,- line: node.OriginTextPosition(),- }- if _, exists := checker.columnSet[col.name()]; !exists {- checker.columnSet[col.name()] = col+ _, _, column := mysqlparser.NormalizeMySQLColumnName(tableElement.ColumnDefinition().ColumnName())+ columns = append(columns, column)}}+ // change column+ case item.CHANGE_SYMBOL() != nil && item.ColumnInternalRef() != nil && item.Identifier() != nil:+ // only care new column name.+ column := mysqlparser.NormalizeMySQLIdentifier(item.Identifier())+ columns = append(columns, column)}- }- return in, false-}--// Leave implements the ast.Visitor interface.-func (*columnNoNullChecker) Leave(in ast.Node) (ast.Node, bool) {- return in, true-}--func canNull(column *ast.ColumnDef) bool {- for _, option := range column.Options {- if option.Tp == ast.ColumnOptionNotNull || option.Tp == ast.ColumnOptionPrimaryKey {- return false+ for _, column := range columns {+ col := columnName{+ tableName: tableName,+ columnName: column,+ line: checker.baseLine + item.GetStart().GetLine(),+ }+ if _, exists := checker.columnSet[col.name()]; !exists {+ checker.columnSet[col.name()] = col+ }}}- return true}diff --git a/backend/plugin/advisor/mysqlwip/mysqlwip_rules_test.go b/backend/plugin/advisor/mysqlwip/mysqlwip_rules_test.goindex 153dc0b751..57765973b1 100644--- a/backend/plugin/advisor/mysqlwip/mysqlwip_rules_test.go+++ b/backend/plugin/advisor/mysqlwip/mysqlwip_rules_test.go@@ -60,6 +60,8 @@ func TestMySQLWIPRules(t *testing.T) {// advisor.SchemaRuleRequiredColumn enforce the required columns in each table.advisor.SchemaRuleRequiredColumn,+ // advisor.SchemaRuleColumnNotNull enforce the columns cannot have NULL value.+ advisor.SchemaRuleColumnNotNull,// 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/column_no_null.yaml b/backend/plugin/advisor/mysqlwip/test/column_no_null.yamlindex c91a3aa86d..7285b839eb 100644--- a/backend/plugin/advisor/mysqlwip/test/column_no_null.yaml+++ b/backend/plugin/advisor/mysqlwip/test/column_no_null.yaml@@ -1,37 +1,38 @@- statement: |-CREATE TABLE book(id int,- name varchar(255))+ name varchar(255)+ );want:- status: WARNcode: 402title: column.no-null- content: '`book`.`id` cannot have NULL value'+ content: "`book`.`id` cannot have NULL value"line: 2details: ""- status: WARNcode: 402title: column.no-null- content: '`book`.`name` cannot have NULL value'+ content: "`book`.`name` cannot have NULL value"line: 3details: ""-- statement: CREATE TABLE book(id int PRIMARY KEY, name varchar(255))+- statement: CREATE TABLE book(id int PRIMARY KEY, name varchar(255));want:- status: WARNcode: 402title: column.no-null- content: '`book`.`name` cannot have NULL value'+ content: "`book`.`name` cannot have NULL value"line: 1details: ""-- statement: CREATE TABLE book(id int NOT NULL, name varchar(255))+- statement: CREATE TABLE book(id int NOT NULL, name varchar(255));want:- status: WARNcode: 402title: column.no-null- content: '`book`.`name` cannot have NULL value'+ content: "`book`.`name` cannot have NULL value"line: 1details: ""-- statement: CREATE TABLE book(id int PRIMARY KEY, name varchar(255) NOT NULL)+- statement: CREATE TABLE book(id int PRIMARY KEY, name varchar(255) NOT NULL);want:- status: SUCCESScode: 0@@ -46,8 +47,18 @@- status: WARNcode: 402title: column.no-null- content: '`book`.`id` cannot have NULL value'- line: 3+ content: "`book`.`id` cannot have NULL value"+ line: 2+ details: ""+- statement: |-+ CREATE TABLE book(a int NOT NULL);+ ALTER TABLE book ADD COLUMN id int, ADD COLUMN name varchar(255) NOT NULL;+ want:+ - status: WARN+ code: 402+ title: column.no-null+ content: "`book`.`id` cannot have NULL value"+ line: 2details: ""- statement: |-CREATE TABLE book(a int NOT NULL);@@ -59,6 +70,16 @@content: ""line: 0details: ""+- statement: |-+ CREATE TABLE book(a int NOT NULL);+ ALTER TABLE book ADD COLUMN id int PRIMARY KEY, ADD COLUMN name varchar(255) NOT NULL;+ want:+ - status: SUCCESS+ code: 0+ title: OK+ content: ""+ line: 0+ details: ""- statement: |-CREATE TABLE book(id int NOT NULL);ALTER TABLE book CHANGE COLUMN id name varchar(255);@@ -66,8 +87,8 @@- status: WARNcode: 402title: column.no-null- content: '`book`.`name` cannot have NULL value'- line: 3+ content: "`book`.`name` cannot have NULL value"+ line: 2details: ""- statement: |-CREATE TABLE book(id int NOT NULL);diff --git a/backend/plugin/advisor/mysqlwip/utils.go b/backend/plugin/advisor/mysqlwip/utils.goindex 128b886af1..f7987607e4 100644--- a/backend/plugin/advisor/mysqlwip/utils.go+++ b/backend/plugin/advisor/mysqlwip/utils.go@@ -63,3 +63,12 @@ func getTemplateRegexp(template string, templateList []string, tokens map[stringreturn regexp.Compile(template)}++func canNull(column *ast.ColumnDef) bool {+ for _, option := range column.Options {+ if option.Tp == ast.ColumnOptionNotNull || option.Tp == ast.ColumnOptionPrimaryKey {+ return false+ }+ }+ return true+}diff --git a/backend/plugin/advisor/sql_review.go b/backend/plugin/advisor/sql_review.goindex 082bc85f88..e253cf2393 100644--- a/backend/plugin/advisor/sql_review.go+++ b/backend/plugin/advisor/sql_review.go@@ -1187,6 +1187,9 @@ func getAdvisorTypeByRule(ruleType SQLReviewRuleType, engine storepb.Engine) (Ty}case SchemaRuleColumnNotNull:switch engine {+ // only for mysqlwip test.+ case storepb.Engine_ENGINE_UNSPECIFIED:+ return MySQLColumnNoNull, nilcase storepb.Engine_MYSQL, storepb.Engine_TIDB, storepb.Engine_MARIADB, storepb.Engine_OCEANBASE:return MySQLColumnNoNull, nilcase storepb.Engine_POSTGRES: