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: generate alter table stmt add column spec if origin table missing some columns (#2615)
h3n4l209f12180d05
diff --git a/plugin/parser/differ/mysql/column_test.go b/plugin/parser/differ/mysql/column_test.gonew file mode 100644index 0000000000..72a19d1988--- /dev/null+++ b/plugin/parser/differ/mysql/column_test.go@@ -0,0 +1,47 @@+package mysql++import (+ "testing"++ "github.com/pingcap/tidb/parser"+ "github.com/stretchr/testify/require"+)++func TestColumn(t *testing.T) {+ tests := []struct {+ old string+ new string+ want string+ }{+ {+ old: `CREATE TABLE book(id INT, PRIMARY KEY(id))`,+ new: `CREATE TABLE book(id INT, price INT, PRIMARY KEY(id));`,+ want: "ALTER TABLE `book` ADD COLUMN (`price` INT);\n",+ },+ {+ old: `CREATE TABLE book(id INT, PRIMARY KEY(id))`,+ new: `CREATE TABLE book(id INT, price INT, code VARCHAR(50), PRIMARY KEY(id));`,+ want: "ALTER TABLE `book` ADD COLUMN (`price` INT), ADD COLUMN (`code` VARCHAR(50));\n",+ },+ {+ old: ``,+ new: `CREATE TABLE book(id INT, price INT, code VARCHAR(50), PRIMARY KEY(id));`,+ want: "CREATE TABLE IF NOT EXISTS `book` (`id` INT,`price` INT,`code` VARCHAR(50),PRIMARY KEY(`id`));\n",+ },+ {+ old: `CREATE TABLE book(id INT, price INT, code VARCHAR(50), PRIMARY KEY(id));`,+ new: `CREATE TABLE book(id INT, price INT, code VARCHAR(50), PRIMARY KEY(id));`,+ want: "",+ },+ }+ a := require.New(t)+ for _, test := range tests {+ oldNodes, _, err := parser.New().Parse(test.old, "", "")+ a.NoError(err)+ newNodes, _, err := parser.New().Parse(test.new, "", "")+ a.NoError(err)+ out, err := SchemaDiff(oldNodes, newNodes)+ a.NoError(err)+ a.Equal(test.want, out)+ }+}diff --git a/plugin/parser/differ/mysql/differ.go b/plugin/parser/differ/mysql/differ.goindex d82c798c5e..effade6a67 100644--- a/plugin/parser/differ/mysql/differ.go+++ b/plugin/parser/differ/mysql/differ.go@@ -6,24 +6,52 @@ import ("github.com/pingcap/tidb/parser/ast""github.com/pingcap/tidb/parser/format"+ "github.com/pingcap/tidb/parser/model")// SchemaDiff returns the schema diff.func SchemaDiff(old, new []ast.StmtNode) (string, error) {- oldTableMap := make(map[string]ast.Node)- tableDiff := make([]ast.Node, 0)- for _, node := range old {- if stmt, ok := node.(*ast.CreateTableStmt); ok {- tableName := stmt.Table.Name.String()- oldTableMap[tableName] = node- }- }+ var diff []ast.Node+ oldTableMap := buildTableMap(old)+for _, node := range new {- if stmt, ok := node.(*ast.CreateTableStmt); ok {- if _, ok := oldTableMap[stmt.Table.Name.String()]; !ok {+ switch newStmt := node.(type) {+ case *ast.CreateTableStmt:+ tableName := newStmt.Table.Name.String()+ oldStmt, ok := oldTableMap[tableName]+ if !ok {+ stmt := *newStmtstmt.IfNotExists = true- tableDiff = append(tableDiff, node)+ diff = append(diff, &stmt)+ continue+ }++ var alterTableAddColumnSpecs []*ast.AlterTableSpec+ var oldColumnMap = make(map[string]*ast.ColumnDef)+ for _, oldColumnDef := range oldStmt.Cols {+ oldColumnName := oldColumnDef.Name.Name.String()+ oldColumnMap[oldColumnName] = oldColumnDef+ }++ for _, columnDef := range newStmt.Cols {+ newColumnName := columnDef.Name.Name.String()+ if _, ok := oldColumnMap[newColumnName]; !ok {+ alterTableAddColumnSpecs = append(alterTableAddColumnSpecs, &ast.AlterTableSpec{+ Tp: ast.AlterTableAddColumns,+ NewColumns: []*ast.ColumnDef{columnDef},+ })+ }}++ if len(alterTableAddColumnSpecs) > 0 {+ diff = append(diff, &ast.AlterTableStmt{+ Table: &ast.TableName{+ Name: model.NewCIStr(tableName),+ },+ Specs: alterTableAddColumnSpecs,+ })+ }+ default:}}@@ -33,11 +61,25 @@ func SchemaDiff(old, new []ast.StmtNode) (string, error) {if err := node.Restore(format.NewRestoreCtx(format.DefaultRestoreFlags, &buf)); err != nil {return "", err}- if _, err := buf.Write([]byte("\n")); err != nil {+ if _, err := buf.Write([]byte(";\n")); err != nil {return "", err}}return buf.String(), nil}- return deparse(tableDiff)+ return deparse(diff)+}++// buildTableMap returns a map of table name to create table statements.+func buildTableMap(nodes []ast.StmtNode) map[string]*ast.CreateTableStmt {+ oldTableMap := make(map[string]*ast.CreateTableStmt)+ for _, node := range nodes {+ switch stmt := node.(type) {+ case *ast.CreateTableStmt:+ tableName := stmt.Table.Name.String()+ oldTableMap[tableName] = stmt+ default:+ }+ }+ return oldTableMap}diff --git a/plugin/parser/differ/mysql/table_test.go b/plugin/parser/differ/mysql/table_test.goindex 05711534ff..a3afb44a00 100644--- a/plugin/parser/differ/mysql/table_test.go+++ b/plugin/parser/differ/mysql/table_test.go@@ -19,14 +19,14 @@ func TestTable(t *testing.T) {new: `CREATE TABLE book(id INT, price INT, PRIMARY KEY(id));CREATE TABLE author(id INT, name VARCHAR(255), PRIMARY KEY(id));`,- want: "CREATE TABLE IF NOT EXISTS `book` (`id` INT,`price` INT,PRIMARY KEY(`id`))\nCREATE TABLE IF NOT EXISTS `author` (`id` INT,`name` VARCHAR(255),PRIMARY KEY(`id`))\n",+ want: "CREATE TABLE IF NOT EXISTS `book` (`id` INT,`price` INT,PRIMARY KEY(`id`));\nCREATE TABLE IF NOT EXISTS `author` (`id` INT,`name` VARCHAR(255),PRIMARY KEY(`id`));\n",},{old: `CREATE TABLE author(id INT, name VARCHAR(255), PRIMARY KEY(id))`,new: `CREATE TABLE book(id INT, price INT, PRIMARY KEY(id));CREATE TABLE author(id INT, name VARCHAR(255), PRIMARY KEY(id));`,- want: "CREATE TABLE IF NOT EXISTS `book` (`id` INT,`price` INT,PRIMARY KEY(`id`))\n",+ want: "CREATE TABLE IF NOT EXISTS `book` (`id` INT,`price` INT,PRIMARY KEY(`id`));\n",},{old: `CREATE TABLE book(id INT, price INT, PRIMARY KEY(id));diff --git a/scripts/.air.toml b/scripts/.air.tomlindex 00e82ecde4..013856aa7c 100644--- a/scripts/.air.toml+++ b/scripts/.air.toml@@ -2,7 +2,7 @@ root = "."tmp_dir = ".air"[build]- full_bin = 'BB_REDIRECT_URL=http:\/\/localhost:3000 ./.air/bytebase --port 8080 --external-url http:\/\/localhost:3000 --data . --debug'+ full_bin = 'BB_REDIRECT_URL=http:\/\/localhost:3000 ./.air/bytebase --port 8080 --external-url https:\/\/b940-20-247-89-73.eu.ngrok.io --data . --debug'## Use --tags "store.db" to enable SQL query logging against our metadata db.cmd = """go build \