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 required (#9077)
zll6004a62c846ccc4
diff --git a/backend/plugin/advisor/mysqlwip/advisor_column_required.go b/backend/plugin/advisor/mysqlwip/advisor_column_required.goindex 4594050b38..a3a97bd55c 100644--- a/backend/plugin/advisor/mysqlwip/advisor_column_required.go+++ b/backend/plugin/advisor/mysqlwip/advisor_column_required.go@@ -5,32 +5,40 @@ import ("sort""strings"- "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"+ mysqlparser "github.com/bytebase/bytebase/backend/plugin/parser/mysql"+ storepb "github.com/bytebase/bytebase/proto/generated-go/store")var (_ advisor.Advisor = (*ColumnRequirementAdvisor)(nil)- _ ast.Visitor = (*columnRequirementChecker)(nil))+func init() {+ // only for mysqlwip test.+ advisor.Register(storepb.Engine_ENGINE_UNSPECIFIED, advisor.MySQLColumnRequirement, &ColumnRequirementAdvisor{})+}+// ColumnRequirementAdvisor is the advisor checking for column requirement.type ColumnRequirementAdvisor struct {}// Check checks for the column requirement.func (*ColumnRequirementAdvisor) Check(ctx advisor.Context, _ string) ([]advisor.Advice, error) {- root, ok := ctx.AST.([]ast.StmtNode)+ list, 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)if err != nil {return nil, err}+columnList, err := advisor.UnmarshalRequiredColumnList(ctx.Rule.Payload)if err != nil {return nil, err@@ -39,6 +47,7 @@ func (*ColumnRequirementAdvisor) Check(ctx advisor.Context, _ string) ([]advisorfor _, column := range columnList {requiredColumns[column] = true}+checker := &columnRequirementChecker{level: level,title: string(ctx.Rule.Type),@@ -47,14 +56,18 @@ func (*ColumnRequirementAdvisor) Check(ctx advisor.Context, _ string) ([]advisorline: make(map[string]int),}- for _, stmtNode := range root {- (stmtNode).Accept(checker)+ for _, stmt := range list {+ checker.baseLine = stmt.BaseLine+ antlr.ParseTreeWalkerDefault.Walk(checker, stmt.Tree)}return checker.generateAdviceList(), nil}type columnRequirementChecker struct {+ *mysql.BaseMySQLParserListener++ baseLine intadviceList []advisor.Advicelevel advisor.Statustitle string@@ -63,154 +76,188 @@ type columnRequirementChecker struct {line map[string]int}-// Enter implements the ast.Visitor interface.-func (v *columnRequirementChecker) Enter(in ast.Node) (ast.Node, bool) {- switch node := in.(type) {- // CREATE TABLE- case *ast.CreateTableStmt:- v.createTable(node)- // DROP TABLE- case *ast.DropTableStmt:- for _, table := range node.Tables {- delete(v.tables, table.Name.String())+// EnterCreateDatabase is called when production createDatabase is entered.+func (checker *columnRequirementChecker) EnterCreateTable(ctx *mysql.CreateTableContext) {+ checker.createTable(ctx)+}++// EnterDropTable is called when production dropTable is entered.+func (checker *columnRequirementChecker) EnterDropTable(ctx *mysql.DropTableContext) {+ if ctx.TableRefList() == nil {+ return+ }++ for _, tableRef := range ctx.TableRefList().AllTableRef() {+ _, tableName := mysqlparser.NormalizeMySQLTableRef(tableRef)+ delete(checker.tables, tableName)+ }+}++// EnterAlterTable is called when production alterTable is entered.+func (checker *columnRequirementChecker) 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:- table := node.Table.Name.O- for _, spec := range node.Specs {- switch spec.Tp {- // RENAME COLUMN- case ast.AlterTableRenameColumn:- v.renameColumn(table, spec.OldColumnName.Name.O, spec.NewColumnName.Name.O)- v.line[table] = node.OriginTextPosition()- // ADD COLUMNS- case ast.AlterTableAddColumns:- for _, column := range spec.NewColumns {- v.addColumn(table, column.Name.Name.O)- }- // DROP COLUMN- case ast.AlterTableDropColumn:- if v.dropColumn(table, spec.OldColumnName.Name.O) {- v.line[table] = node.OriginTextPosition()- }- // CHANGE COLUMN- case ast.AlterTableChangeColumn:- if v.renameColumn(table, spec.OldColumnName.Name.O, spec.NewColumns[0].Name.Name.O) {- v.line[table] = node.OriginTextPosition()- }++ lineNumber := checker.baseLine + item.GetStart().GetLine()+ switch {+ // add column+ case item.ADD_SYMBOL() != nil && item.Identifier() != nil:+ columnName := mysqlparser.NormalizeMySQLIdentifier(item.Identifier())+ checker.addColumn(tableName, columnName)+ // drop column+ case item.DROP_SYMBOL() != nil && item.ColumnInternalRef() != nil:+ columnName := mysqlparser.NormalizeMySQLColumnInternalRef(item.ColumnInternalRef())+ if checker.dropColumn(tableName, columnName) {+ checker.line[tableName] = lineNumber+ }+ // rename column+ case item.RENAME_SYMBOL() != nil && item.COLUMN_SYMBOL() != nil:+ oldColumnName := mysqlparser.NormalizeMySQLColumnInternalRef(item.ColumnInternalRef())+ newColumnName := mysqlparser.NormalizeMySQLIdentifier(item.Identifier())+ checker.renameColumn(tableName, oldColumnName, newColumnName)+ checker.line[tableName] = lineNumber+ // change column+ case item.CHANGE_SYMBOL() != nil && item.ColumnInternalRef() != nil && item.Identifier() != nil:+ oldColumnName := mysqlparser.NormalizeMySQLColumnInternalRef(item.ColumnInternalRef())+ newColumnName := mysqlparser.NormalizeMySQLIdentifier(item.Identifier())+ if checker.renameColumn(tableName, oldColumnName, newColumnName) {+ checker.line[tableName] = lineNumber}}}- return in, false}-// Leave implements the ast.Visitor interface.-func (*columnRequirementChecker) Leave(in ast.Node) (ast.Node, bool) {- return in, true-}--func (v *columnRequirementChecker) generateAdviceList() []advisor.Advice {+func (checker *columnRequirementChecker) generateAdviceList() []advisor.Advice {// Order it cause the random iteration order in Go, see https://go.dev/blog/maps- tableList := v.tables.tableList()+ tableList := checker.tables.tableList()for _, tableName := range tableList {- table := v.tables[tableName]+ table := checker.tables[tableName]var missingColumns []string- for column := range v.requiredColumns {- if exist, ok := table[column]; !ok || !exist {- missingColumns = append(missingColumns, column)+ for columnName := range checker.requiredColumns {+ if exists, ok := table[columnName]; !ok || !exists {+ missingColumns = append(missingColumns, columnName)}}+if len(missingColumns) > 0 {// Order it cause the random iteration order in Go, see https://go.dev/blog/mapssort.Strings(missingColumns)- v.adviceList = append(v.adviceList, advisor.Advice{- Status: v.level,+ checker.adviceList = append(checker.adviceList, advisor.Advice{+ Status: checker.level,Code: advisor.NoRequiredColumn,- Title: v.title,+ Title: checker.title,Content: fmt.Sprintf("Table `%s` requires columns: %s", tableName, strings.Join(missingColumns, ", ")),- Line: v.line[tableName],+ Line: checker.line[tableName],})}}- if len(v.adviceList) == 0 {- v.adviceList = append(v.adviceList, advisor.Advice{+ if len(checker.adviceList) == 0 {+ checker.adviceList = append(checker.adviceList, advisor.Advice{Status: advisor.Success,Code: advisor.Ok,Title: "OK",Content: "",})}- return v.adviceList+ return checker.adviceList}-// initEmptyTable will initialize a table without any required columns.-func (v *columnRequirementChecker) initEmptyTable(name string) columnSet {- v.tables[name] = make(columnSet)- return v.tables[name]-}+func (checker *columnRequirementChecker) createTable(ctx *mysql.CreateTableContext) {+ _, tableName := mysqlparser.NormalizeMySQLTableName(ctx.TableName())+ checker.line[tableName] = checker.baseLine + ctx.GetStart().GetLine()+ checker.initEmptyTable(tableName)-// initFullTable will initialize a table with all required columns.-func (v *columnRequirementChecker) initFullTable(name string) columnSet {- table := v.initEmptyTable(name)- for column := range v.requiredColumns {- table[column] = true+ if ctx.TableElementList() == nil {+ return+ }++ for _, tableElement := range ctx.TableElementList().AllTableElement() {+ if tableElement.ColumnDefinition() == nil {+ continue+ }+ _, _, columnName := mysqlparser.NormalizeMySQLColumnName(tableElement.ColumnDefinition().ColumnName())+ checker.addColumn(tableName, columnName)}- return table}-func (v *columnRequirementChecker) renameColumn(table string, oldColumn string, newColumn string) bool {- _, oldNeed := v.requiredColumns[oldColumn]- _, newNeed := v.requiredColumns[newColumn]- if !oldNeed && !newNeed {- return false+func (checker *columnRequirementChecker) initEmptyTable(tableName string) columnSet {+ checker.tables[tableName] = make(columnSet)+ return checker.tables[tableName]+}++// add a column.+func (checker *columnRequirementChecker) addColumn(tableName string, columnName string) {+ if _, ok := checker.requiredColumns[columnName]; !ok {+ return}- t, ok := v.tables[table]- if !ok {++ if table, ok := checker.tables[tableName]; !ok {// We do not retrospectively check.// So we assume it contains all required columns.- t = v.initFullTable(table)- }- if oldNeed {- t[oldColumn] = false- }- if newNeed {- t[newColumn] = true+ checker.initFullTable(tableName)+ } else {+ table[columnName] = true}- return oldNeed}-func (v *columnRequirementChecker) dropColumn(table string, column string) bool {- if _, ok := v.requiredColumns[column]; !ok {+// drop a column+// return true if the colum was successfully dropped from requirement list.+func (checker *columnRequirementChecker) dropColumn(tableName string, columnName string) bool {+ if _, ok := checker.requiredColumns[columnName]; !ok {return false}- t, ok := v.tables[table]+ table, ok := checker.tables[tableName]if !ok {// We do not retrospectively check.// So we assume it contains all required columns.- t = v.initFullTable(table)+ table = checker.initFullTable(tableName)}- t[column] = false+ table[columnName] = falsereturn true}-func (v *columnRequirementChecker) addColumn(table string, column string) {- if _, ok := v.requiredColumns[column]; !ok {- return+// rename a column+// return if the old column was dropped from requirement list.+func (checker *columnRequirementChecker) renameColumn(tableName string, oldColumn string, newColumn string) bool {+ _, oldNeed := checker.requiredColumns[oldColumn]+ _, newNeed := checker.requiredColumns[newColumn]+ if !oldNeed && !newNeed {+ return false}- if t, ok := v.tables[table]; !ok {+ table, ok := checker.tables[tableName]+ if !ok {// We do not retrospectively check.// So we assume it contains all required columns.- v.initFullTable(table)- } else {- t[column] = true+ table = checker.initFullTable(tableName)}+ if oldNeed {+ table[oldColumn] = false+ }+ if newNeed {+ table[newColumn] = true+ }+ return oldNeed}-func (v *columnRequirementChecker) createTable(node *ast.CreateTableStmt) {- v.line[node.Table.Name.O] = node.OriginTextPosition()- v.initEmptyTable(node.Table.Name.O)- for _, column := range node.Cols {- v.addColumn(node.Table.Name.O, column.Name.Name.O)+func (checker *columnRequirementChecker) initFullTable(tableName string) columnSet {+ table := checker.initEmptyTable(tableName)+ for column := range checker.requiredColumns {+ table[column] = true}+ return table}diff --git a/backend/plugin/advisor/mysqlwip/mysqlwip_rules_test.go b/backend/plugin/advisor/mysqlwip/mysqlwip_rules_test.goindex 42a4e92851..153dc0b751 100644--- a/backend/plugin/advisor/mysqlwip/mysqlwip_rules_test.go+++ b/backend/plugin/advisor/mysqlwip/mysqlwip_rules_test.go@@ -57,6 +57,9 @@ func TestMySQLWIPRules(t *testing.T) {// advisor.SchemaRuleTableDisallowPartition disallow the table partition.advisor.SchemaRuleTableDisallowPartition,+ // advisor.SchemaRuleRequiredColumn enforce the required columns in each table.+ advisor.SchemaRuleRequiredColumn,+// 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_required.yaml b/backend/plugin/advisor/mysqlwip/test/column_required.yamlindex fe2b0c2998..981697ac3f 100644--- a/backend/plugin/advisor/mysqlwip/test/column_required.yaml+++ b/backend/plugin/advisor/mysqlwip/test/column_required.yaml@@ -1,18 +1,49 @@-- statement: CREATE TABLE book(id int)+- statement: |-+ CREATE TABLE t1(a INT);+ CREATE TABLE book(id int);+ CREATE TABLE t2(id INT, creator_id INT);+ CREATE TABLE t3(id INT, creator_id INT, created_ts timestamp);+ CREATE TABLE t4(id INT, creator_id INT, created_ts timestamp, updater_id INT);+ CREATE TABLE t5(id INT, creator_id INT, created_ts timestamp, updater_id INT, updated_ts timestamp);want:- status: WARNcode: 401title: column.required- content: 'Table `book` requires columns: created_ts, creator_id, updated_ts, updater_id'+ content: "Table `t1` requires columns: created_ts, creator_id, id, updated_ts, updater_id"+ line: 1+ details: ""+ - status: WARN+ code: 401+ title: column.required+ content: "Table `book` requires columns: created_ts, creator_id, updated_ts, updater_id"line: 2details: ""+ - status: WARN+ code: 401+ title: column.required+ content: "Table `t2` requires columns: created_ts, updated_ts, updater_id"+ line: 3+ details: ""+ - status: WARN+ code: 401+ title: column.required+ content: "Table `t3` requires columns: updated_ts, updater_id"+ line: 4+ details: ""+ - status: WARN+ code: 401+ title: column.required+ content: "Table `t4` requires columns: updated_ts"+ line: 5+ details: ""- statement: |-CREATE TABLE book(- id int,- creator_id int,- created_ts timestamp,- updater_id int,- updated_ts timestamp)+ id int,+ creator_id int,+ created_ts timestamp,+ updater_id int,+ updated_ts timestamp+ );want:- status: SUCCESScode: 0@@ -22,27 +53,29 @@details: ""- statement: |-CREATE TABLE book(- id int,- creator_id int,- created_ts timestamp,- updater_id int,- updated_ts timestamp);- ALTER TABLE book RENAME COLUMN creator_id TO creator;+ id int,+ creator_id int,+ created_ts timestamp,+ updater_id int,+ updated_ts timestamp+ );+ ALTER TABLE book RENAME COLUMN creator_id TO creator;want:- status: WARNcode: 401title: column.required- content: 'Table `book` requires columns: creator_id'+ content: "Table `book` requires columns: creator_id"line: 8details: ""- statement: |-CREATE TABLE book(- id int,- creator int,- created_ts timestamp,- updater_id int,- updated_ts timestamp);- ALTER TABLE book RENAME COLUMN creator TO creator_id;+ id int,+ creator int,+ created_ts timestamp,+ updater_id int,+ updated_ts timestamp+ );+ ALTER TABLE book RENAME COLUMN creator TO creator_id;want:- status: SUCCESScode: 0@@ -52,27 +85,29 @@details: ""- statement: |-CREATE TABLE book(- id int,- creator_id int,- created_ts timestamp,- updater_id int,- updated_ts timestamp);- ALTER TABLE book CHANGE COLUMN creator_id creator int;+ id int,+ creator_id int,+ created_ts timestamp,+ updater_id int,+ updated_ts timestamp+ );+ ALTER TABLE book CHANGE COLUMN creator_id creator int;want:- status: WARNcode: 401title: column.required- content: 'Table `book` requires columns: creator_id'+ content: "Table `book` requires columns: creator_id"line: 8details: ""- statement: |-CREATE TABLE book(- id int,- creator int,- created_ts timestamp,- updater_id int,- updated_ts timestamp);- ALTER TABLE book CHANGE COLUMN creator creator_id int;+ id int,+ creator int,+ created_ts timestamp,+ updater_id int,+ updated_ts timestamp+ );+ ALTER TABLE book CHANGE COLUMN creator creator_id int;want:- status: SUCCESScode: 0@@ -82,28 +117,30 @@details: ""- statement: |-CREATE TABLE book(- id int,- creator_id int,- created_ts timestamp,- updater_id int,- updated_ts timestamp);- ALTER TABLE book DROP COLUMN creator_id;+ id int,+ creator_id int,+ created_ts timestamp,+ updater_id int,+ updated_ts timestamp+ );+ ALTER TABLE book DROP COLUMN creator_id;want:- status: WARNcode: 401title: column.required- content: 'Table `book` requires columns: creator_id'+ content: "Table `book` requires columns: creator_id"line: 8details: ""- statement: |-CREATE TABLE book(- id int,- creator_id int,- created_ts timestamp,- updater_id int,- updated_ts timestamp,- content varchar(255));- ALTER TABLE book DROP COLUMN content;+ id int,+ creator_id int,+ created_ts timestamp,+ updater_id int,+ updated_ts timestamp,+ content varchar(255)+ );+ ALTER TABLE book DROP COLUMN content;want:- status: SUCCESScode: 0@@ -113,26 +150,28 @@details: ""- statement: |-CREATE TABLE book(- id int,- creator_id int,- created_ts timestamp,- updated_ts timestamp);- ALTER TABLE book ADD COLUMN content varchar(255);+ id int,+ creator_id int,+ created_ts timestamp,+ updated_ts timestamp+ );+ ALTER TABLE book ADD COLUMN content varchar(255);want:- status: WARNcode: 401title: column.required- content: 'Table `book` requires columns: updater_id'- line: 5+ content: "Table `book` requires columns: updater_id"+ line: 1details: ""- statement: |-CREATE TABLE book(- id int,- creator int,- created_ts timestamp,- updater_id int,- updated_ts timestamp);- ALTER TABLE book ADD COLUMN creator_id int;+ id int,+ creator int,+ created_ts timestamp,+ updater_id int,+ updated_ts timestamp+ );+ ALTER TABLE book ADD COLUMN creator_id int;want:- status: SUCCESScode: 0@@ -142,35 +181,38 @@details: ""- statement: |-CREATE TABLE book(- id int,- created_ts timestamp,- updater_id int,- updated_ts timestamp);- CREATE TABLE student(- id int,- created_ts timestamp,- updated_ts timestamp)+ id int,+ created_ts timestamp,+ updater_id int,+ updated_ts timestamp+ );+ CREATE TABLE student(+ id int,+ created_ts timestamp,+ updated_ts timestamp+ );want:- status: WARNcode: 401title: column.required- content: 'Table `book` requires columns: creator_id'- line: 5+ content: "Table `book` requires columns: creator_id"+ line: 1details: ""- status: WARNcode: 401title: column.required- content: 'Table `student` requires columns: creator_id, updater_id'- line: 10+ content: "Table `student` requires columns: creator_id, updater_id"+ line: 7details: ""- statement: |-CREATE TABLE book(- id int,- creator int,- created_ts timestamp,- updater_id int,- updated_ts timestamp);- DROP TABLE book;+ id int,+ creator int,+ created_ts timestamp,+ updater_id int,+ updated_ts timestamp+ );+ DROP TABLE book;want:- status: SUCCESScode: 0diff --git a/backend/plugin/advisor/sql_review.go b/backend/plugin/advisor/sql_review.goindex 1414e79366..3480b198bd 100644--- a/backend/plugin/advisor/sql_review.go+++ b/backend/plugin/advisor/sql_review.go@@ -1166,6 +1166,9 @@ func getAdvisorTypeByRule(ruleType SQLReviewRuleType, engine storepb.Engine) (Ty}case SchemaRuleRequiredColumn:switch engine {+ // only for mysqlwip test.+ case storepb.Engine_ENGINE_UNSPECIFIED:+ return MySQLColumnRequirement, nilcase storepb.Engine_MYSQL, storepb.Engine_TIDB, storepb.Engine_MARIADB, storepb.Engine_OCEANBASE:return MySQLColumnRequirement, nilcase storepb.Engine_POSTGRES: