Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
refactor: refactor MySQL differ (#4818)
rebelice1beb2431493f
diff --git a/backend/plugin/parser/differ/mysql/column_test.go b/backend/plugin/parser/differ/mysql/column_test.goindex eb9299d493..53c4d708ea 100644--- a/backend/plugin/parser/differ/mysql/column_test.go+++ b/backend/plugin/parser/differ/mysql/column_test.go@@ -262,10 +262,10 @@ func TestColumnOrder(t *testing.T) {{old: `CREATE TABLE book(c1 INT, c2 INT, c3 INT, c4 INT, c5 INT);`,new: `CREATE TABLE book(c6 INT, c2 INT, c3 INT, c7 INT, c8 INT, c4 INT, c5 INT);`,- want: "ALTER TABLE `book` ADD COLUMN `c6` INT FIRST, " + // c6, c1, c2, c3, c4, c5- "ADD COLUMN `c7` INT AFTER `c3`, " + // c6, c1, c2, c3, c7, c4, c5- "ADD COLUMN `c8` INT AFTER `c7`;\n\n" + // c6, c1, c2, c3, c7, c8, c4, c5- "ALTER TABLE `book` DROP COLUMN `c1`;\n\n", // c6, c2, c3, c7, c8, c4, c5+ want: "ALTER TABLE `book` DROP COLUMN `c1`;\n\n" + // c2, c3, c4, c5+ "ALTER TABLE `book` ADD COLUMN `c6` INT FIRST, " + // c6, c2, c3, c4, c5+ "ADD COLUMN `c7` INT AFTER `c3`, " + // c6, c2, c3, c7, c4, c5+ "ADD COLUMN `c8` INT AFTER `c7`;\n\n", // c6, c2, c3, c7, c8, c4, c5},}testDiffWithoutDisableForeignKeyCheck(t, tests)diff --git a/backend/plugin/parser/differ/mysql/constraint_test.go b/backend/plugin/parser/differ/mysql/constraint_test.goindex 20613eb1bd..712554cc57 100644--- a/backend/plugin/parser/differ/mysql/constraint_test.go+++ b/backend/plugin/parser/differ/mysql/constraint_test.go@@ -238,8 +238,8 @@ func TestIndexType(t *testing.T) {{old: `CREATE TABLE book(name VARCHAR(50) NOT NULL, INDEX book_idx USING BTREE(name));`,new: `CREATE TABLE book(name VARCHAR(50) NOT NULL, INDEX book_idx USING HASH(name));`,- want: "ALTER TABLE `book` DROP INDEX `book_idx`;\n\n" +- "ALTER TABLE `book` ADD INDEX `book_idx` (`name`) USING HASH;\n\n",+ want: "DROP INDEX `book_idx` ON `book`;\n\n" ++ "CREATE INDEX `book_idx` ON `book` (`name`) USING HASH;\n\n",},{old: `CREATE TABLE book(name VARCHAR(50) NOT NULL, INDEX book_idx USING BTREE(name));`,@@ -262,8 +262,8 @@ func TestIndexOption(t *testing.T) {{old: `CREATE TABLE book(name VARCHAR(50) NOT NULL, INDEX book_idx(name) KEY_BLOCK_SIZE=30);`,new: `CREATE TABLE book(name VARCHAR(50) NOT NULL, INDEX book_idx(name) KEY_BLOCK_SIZE=50);`,- want: "ALTER TABLE `book` DROP INDEX `book_idx`;\n\n" +- "ALTER TABLE `book` ADD INDEX `book_idx` (`name`) KEY_BLOCK_SIZE=50;\n\n",+ want: "DROP INDEX `book_idx` ON `book`;\n\n" ++ "CREATE INDEX `book_idx` ON `book` (`name`) KEY_BLOCK_SIZE=50;\n\n",},{old: `CREATE TABLE book(name VARCHAR(50) NOT NULL, CONSTRAINT PRIMARY KEY (name) KEY_BLOCK_SIZE=30);`,@@ -275,8 +275,8 @@ func TestIndexOption(t *testing.T) {{old: `CREATE TABLE book(name VARCHAR(50) NOT NULL, FULLTEXT INDEX book_idx(name) WITH PARSER parser_a);`,new: `CREATE TABLE book(name VARCHAR(50) NOT NULL, FULLTEXT INDEX book_idx(name) WITH PARSER parser_b);`,- want: "ALTER TABLE `book` DROP INDEX `book_idx`;\n\n" +- "ALTER TABLE `book` ADD FULLTEXT `book_idx` (`name`) WITH PARSER `parser_b`;\n\n",+ want: "DROP INDEX `book_idx` ON `book`;\n\n" ++ "CREATE FULLTEXT INDEX `book_idx` ON `book` (`name`) WITH PARSER `parser_b`;\n\n",},{old: `CREATE TABLE book(name VARCHAR(50) NOT NULL, CONSTRAINT PRIMARY KEY (name) WITH PARSER parser_a);`,@@ -288,8 +288,8 @@ func TestIndexOption(t *testing.T) {{old: `CREATE TABLE book(name VARCHAR(50) NOT NULL, INDEX book_idx(name) COMMENT 'comment_a');`,new: `CREATE TABLE book(name VARCHAR(50) NOT NULL, INDEX book_idx(name) COMMENT 'comment_b');`,- want: "ALTER TABLE `book` DROP INDEX `book_idx`;\n\n" +- "ALTER TABLE `book` ADD INDEX `book_idx` (`name`) COMMENT 'comment_b';\n\n",+ want: "DROP INDEX `book_idx` ON `book`;\n\n" ++ "CREATE INDEX `book_idx` ON `book` (`name`) COMMENT 'comment_b';\n\n",},{old: `CREATE TABLE book(name VARCHAR(50) NOT NULL, CONSTRAINT PRIMARY KEY(name) COMMENT 'comment_a');`,@@ -302,8 +302,8 @@ func TestIndexOption(t *testing.T) {old: `CREATE TABLE book(name VARCHAR(50) NOT NULL, INDEX book_idx(name) VISIBLE);`,new: `CREATE TABLE book(name VARCHAR(50) NOT NULL, INDEX book_idx(name) INVISIBLE);`,- want: "ALTER TABLE `book` DROP INDEX `book_idx`;\n\n" +- "ALTER TABLE `book` ADD INDEX `book_idx` (`name`) INVISIBLE;\n\n",+ want: "DROP INDEX `book_idx` ON `book`;\n\n" ++ "CREATE INDEX `book_idx` ON `book` (`name`) INVISIBLE;\n\n",},{@@ -332,8 +332,8 @@ func TestKeyPart(t *testing.T) {{old: `CREATE TABLE book(id INT, name VARCHAR(50) NOT NULL, INDEX book_idx USING BTREE (id, name) COMMENT 'comment_a');`,new: `CREATE TABLE book(id INT, name VARCHAR(50) NOT NULL, INDEX book_idx USING BTREE (id) COMMENT 'comment_a');`,- want: "ALTER TABLE `book` DROP INDEX `book_idx`;\n\n" +- "ALTER TABLE `book` ADD INDEX `book_idx` (`id`) USING BTREE COMMENT 'comment_a';\n\n",+ want: "DROP INDEX `book_idx` ON `book`;\n\n" ++ "CREATE INDEX `book_idx` ON `book` (`id`) USING BTREE COMMENT 'comment_a';\n\n",},{old: `CREATE TABLE book(id INT, name VARCHAR(50) NOT NULL, CONSTRAINT PRIMARY KEY(id, name) COMMENT 'comment_a');`,@@ -344,8 +344,8 @@ func TestKeyPart(t *testing.T) {{old: `CREATE TABLE book(id INT, name VARCHAR(50) NOT NULL, INDEX book_idx USING BTREE (id, name) COMMENT 'comment_a');`,new: `CREATE TABLE book(id INT, name VARCHAR(50) NOT NULL, INDEX book_idx USING BTREE ((id + 1)) COMMENT 'comment_a');`,- want: "ALTER TABLE `book` DROP INDEX `book_idx`;\n\n" +- "ALTER TABLE `book` ADD INDEX `book_idx` ((`id`+1)) USING BTREE COMMENT 'comment_a';\n\n",+ want: "DROP INDEX `book_idx` ON `book`;\n\n" ++ "CREATE INDEX `book_idx` ON `book` ((`id`+1)) USING BTREE COMMENT 'comment_a';\n\n",},{old: `CREATE TABLE book(id INT, name VARCHAR(50) NOT NULL, CONSTRAINT PRIMARY KEY (id, name) COMMENT 'comment_a');`,@@ -356,8 +356,8 @@ func TestKeyPart(t *testing.T) {{old: `CREATE TABLE book(id INT, name VARCHAR(50) NOT NULL, INDEX book_idx USING BTREE ((id + 1)) COMMENT 'comment_a');`,new: `CREATE TABLE book(id INT, name VARCHAR(50) NOT NULL, INDEX book_idx USING BTREE ((id + 2)) COMMENT 'comment_a');`,- want: "ALTER TABLE `book` DROP INDEX `book_idx`;\n\n" +- "ALTER TABLE `book` ADD INDEX `book_idx` ((`id`+2)) USING BTREE COMMENT 'comment_a';\n\n",+ want: "DROP INDEX `book_idx` ON `book`;\n\n" ++ "CREATE INDEX `book_idx` ON `book` ((`id`+2)) USING BTREE COMMENT 'comment_a';\n\n",},{old: `CREATE TABLE book(id INT, name VARCHAR(50) NOT NULL, CONSTRAINT PRIMARY KEY ((id + 1)) COMMENT 'comment_a');`,@@ -397,7 +397,7 @@ func TestForeignKeyDefination(t *testing.T) {CREATE TABLE employee(id INT, name VARCHAR(50) NOT NULL, department_id INT, PRIMARY KEY(id), FOREIGN KEY employee_ibfk_1(department_id) REFERENCES department(id));`,new: `CREATE TABLE department(id INT, name VARCHAR(50) NOT NULL, PRIMARY KEY(department));CREATE TABLE employee(id INT, name VARCHAR(50) NOT NULL, department_id INT, PRIMARY KEY(id), FOREIGN KEY fk_2(department_id) REFERENCES department(id));`,- want: "ALTER TABLE `employee` ADD CONSTRAINT `fk_2` FOREIGN KEY (`department_id`) REFERENCES `department` (`id`);\n\nALTER TABLE `employee` DROP FOREIGN KEY `employee_ibfk_1`;\n\n",+ want: "ALTER TABLE `employee` DROP FOREIGN KEY `employee_ibfk_1`;\n\nALTER TABLE `employee` ADD CONSTRAINT `fk_2` FOREIGN KEY (`department_id`) REFERENCES `department` (`id`);\n\n",},{old: "CREATE TABLE `department` (" +@@ -434,12 +434,12 @@ func TestForeignKeyDefination(t *testing.T) {" CONSTRAINT `employee_ibfk_1` FOREIGN KEY (`department_id`) REFERENCES `department` (`id`)" +") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;",- want: "ALTER TABLE `department` ADD INDEX `id_idx` (`id`);\n\n" +- "ALTER TABLE `employee` ADD INDEX `department_id_idx` (`department_id`);\n\n" +- "ALTER TABLE `employee` DROP FOREIGN KEY `employee_ibfk_1`;\n\n" +- "ALTER TABLE `employee` ADD CONSTRAINT `employee_ibfk_1` FOREIGN KEY (`department_id`) REFERENCES `department` (`id`);\n\n" +- "ALTER TABLE `employee` DROP INDEX `department_id_name_idx`;\n\n" +- "ALTER TABLE `department` DROP INDEX `id_name_idx`;\n\n",+ want: "ALTER TABLE `employee` DROP FOREIGN KEY `employee_ibfk_1`;\n\n" ++ "DROP INDEX `id_name_idx` ON `department`;\n\n" ++ "DROP INDEX `department_id_name_idx` ON `employee`;\n\n" ++ "CREATE INDEX `id_idx` ON `department` (`id`);\n\n" ++ "CREATE INDEX `department_id_idx` ON `employee` (`department_id`);\n\n" ++ "ALTER TABLE `employee` ADD CONSTRAINT `employee_ibfk_1` FOREIGN KEY (`department_id`) REFERENCES `department` (`id`);\n\n",},// Reference itself.{@@ -460,8 +460,8 @@ func TestForeignKeyDefination(t *testing.T) {" CONSTRAINT `employee_ibfk_1` FOREIGN KEY (`manager_id`) REFERENCES `employeee` (`id`)" +") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;",- want: "ALTER TABLE `employeee` ADD COLUMN `manager_id` INT DEFAULT NULL AFTER `leader_id`;\n\n" +- "ALTER TABLE `employeee` DROP FOREIGN KEY `employee_ibfk_1`;\n\n" ++ want: "ALTER TABLE `employeee` DROP FOREIGN KEY `employee_ibfk_1`;\n\n" ++ "ALTER TABLE `employeee` ADD COLUMN `manager_id` INT DEFAULT NULL AFTER `leader_id`;\n\n" +"ALTER TABLE `employeee` ADD CONSTRAINT `employee_ibfk_1` FOREIGN KEY (`manager_id`) REFERENCES `employeee` (`id`);\n\n",},}@@ -492,8 +492,8 @@ func TestCheckConstraint(t *testing.T) {old: "CREATE TABLE book(id INT, price INT, PRIMARY KEY(id), CONSTRAINT `check_price` CHECK (price > 0), CONSTRAINT `check_price2` CHECK(price > 1));",new: "CREATE TABLE book(id INT, price INT, PRIMARY KEY(id), CONSTRAINT `check_price` CHECK (price > 0) NOT ENFORCED);",want: "ALTER TABLE `book` DROP CHECK `check_price`;\n\n" +- "ALTER TABLE `book` ADD CONSTRAINT `check_price` CHECK(`price`>0) NOT ENFORCED;\n\n" +- "ALTER TABLE `book` DROP CHECK `check_price2`;\n\n",+ "ALTER TABLE `book` DROP CHECK `check_price2`;\n\n" ++ "ALTER TABLE `book` ADD CONSTRAINT `check_price` CHECK(`price`>0) NOT ENFORCED;\n\n",},}testDiffWithoutDisableForeignKeyCheck(t, tests)@@ -505,25 +505,25 @@ func TestConstraint(t *testing.T) {{old: `CREATE TABLE book(id INT, name VARCHAR(50), CONSTRAINT PRIMARY KEY(id, name));`,new: `CREATE TABLE book(id INT, name VARCHAR(50), address VARCHAR(50) NOT NULL, CONSTRAINT PRIMARY KEY(id, address));`,- want: "ALTER TABLE `book` ADD COLUMN `address` VARCHAR(50) NOT NULL AFTER `name`;\n\n" +- "ALTER TABLE `book` DROP PRIMARY KEY;\n\n" ++ want: "ALTER TABLE `book` DROP PRIMARY KEY;\n\n" ++ "ALTER TABLE `book` ADD COLUMN `address` VARCHAR(50) NOT NULL AFTER `name`;\n\n" +"ALTER TABLE `book` ADD PRIMARY KEY (`id`, `address`);\n\n",},// ADD COLUMN -> ADD INDEX WITH ANOTHER NAME-> DROP INDEX{old: `CREATE TABLE book(id INT, name VARCHAR(50), INDEX id_name_idx (id, name));`,new: `CREATE TABLE book(id INT, name VARCHAR(50), address VARCHAR(50) NOT NULL, INDEX id_address_idx (id, address));`,- want: "ALTER TABLE `book` ADD COLUMN `address` VARCHAR(50) NOT NULL AFTER `name`;\n\n" +- "ALTER TABLE `book` ADD INDEX `id_address_idx` (`id`, `address`);\n\n" +- "ALTER TABLE `book` DROP INDEX `id_name_idx`;\n\n",+ want: "DROP INDEX `id_name_idx` ON `book`;\n\n" ++ "ALTER TABLE `book` ADD COLUMN `address` VARCHAR(50) NOT NULL AFTER `name`;\n\n" ++ "CREATE INDEX `id_address_idx` ON `book` (`id`, `address`);\n\n",},// ADD COLUMN -> ADD INDEX WITH SAME NAME -> DROP INDEX{old: `CREATE TABLE book(id INT, name VARCHAR(50), INDEX idx (id, name));`,new: `CREATE TABLE book(id INT, name VARCHAR(50), address VARCHAR(50) NOT NULL, INDEX idx (id, address));`,- want: "ALTER TABLE `book` ADD COLUMN `address` VARCHAR(50) NOT NULL AFTER `name`;\n\n" +- "ALTER TABLE `book` DROP INDEX `idx`;\n\n" +- "ALTER TABLE `book` ADD INDEX `idx` (`id`, `address`);\n\n",+ want: "DROP INDEX `idx` ON `book`;\n\n" ++ "ALTER TABLE `book` ADD COLUMN `address` VARCHAR(50) NOT NULL AFTER `name`;\n\n" ++ "CREATE INDEX `idx` ON `book` (`id`, `address`);\n\n",},}testDiffWithoutDisableForeignKeyCheck(t, tests)diff --git a/backend/plugin/parser/differ/mysql/differ.go b/backend/plugin/parser/differ/mysql/differ.goindex 3aaa2b4552..1524969bc5 100644--- a/backend/plugin/parser/differ/mysql/differ.go+++ b/backend/plugin/parser/differ/mysql/differ.go@@ -46,325 +46,40 @@ const (type SchemaDiffer struct {}-// constraintMap returns a map of constraint name to constraint.-type constraintMap map[string]*ast.Constraint--// SchemaDiff returns the schema diff.-// It only supports schema information from mysqldump.-func (*SchemaDiffer) SchemaDiff(oldStmt, newStmt string) (string, error) {- // TiDB parser doesn't support some statements like `CREATE EVENT`, so we need to extract them out and diff them based on string compare.- oldUnsupportStmts, oldSupportStmts, err := bbparser.ExtractTiDBUnsupportStmts(oldStmt)- if err != nil {- return "", errors.Wrapf(err, "failed to extract TiDB unsupport statements from old statements %q", oldStmt)- }- var oldUnsupportFilterStmts []string- for _, stmt := range oldUnsupportStmts {- if !bbparser.IsDelimiter(stmt) {- oldUnsupportFilterStmts = append(oldUnsupportFilterStmts, stmt)- }- }-- newUnsupportStmts, newSupportStmts, err := bbparser.ExtractTiDBUnsupportStmts(newStmt)- if err != nil {- return "", errors.Wrapf(err, "failed to extract TiDB unsupport statements from old statements %q", oldStmt)- }- var newUnsupportFilterStmts []string- for _, stmt := range newUnsupportStmts {- if !bbparser.IsDelimiter(stmt) {- newUnsupportFilterStmts = append(newUnsupportFilterStmts, stmt)- }- }-- oldNodes, _, err := parser.New().Parse(oldSupportStmts, "", "")- if err != nil {- return "", errors.Wrapf(err, "failed to parse old statement %q", oldStmt)- }- newNodes, _, err := parser.New().Parse(newSupportStmts, "", "")- if err != nil {- return "", errors.Wrapf(err, "failed to parse new statement %q", newStmt)- }-- var newNodeList []ast.Node- var inplaceUpdate []ast.Node- // inplaceDropNodeList and inplaceAddNodeList are used to handle destructive node updates.- // For example, we should drop the old index named 'id_idx' and then add a new index named 'id_idx' in the same table.- var inplaceDropNodeList []ast.Node- var inplaceAddNodeList []ast.Node- var dropNodeList []ast.Node- var viewStmts []*ast.CreateViewStmt-- oldTableMap := buildTableMap(oldNodes)- oldViewMap := buildViewMap(oldNodes)- newViewMap := buildViewMap(newNodes)- var newViewList []*ast.CreateViewStmt-- for _, node := range newNodes {- switch newStmt := node.(type) {- case *ast.CreateTableStmt:- tableName := newStmt.Table.Name.O- oldStmt, ok := oldTableMap[tableName]- if !ok {- stmt := *newStmt- stmt.IfNotExists = true- newNodeList = append(newNodeList, &stmt)- continue- }- if alterTableOptionStmt := diffTableOptions(newStmt.Table, oldStmt.Options, newStmt.Options); alterTableOptionStmt != nil {- inplaceUpdate = append(inplaceUpdate, alterTableOptionStmt)- }- indexMap := buildIndexMap(oldStmt)- constraintMap := buildConstraintMap(oldStmt)- var alterTableAddColumnSpecs []*ast.AlterTableSpec- var alterTableDropColumnSpecs []*ast.AlterTableSpec- var alterTableModifyColumnSpecs []*ast.AlterTableSpec- var alterTableAddNewConstraintSpecs []*ast.AlterTableSpec- var alterTableDropExcessConstraintSpecs []*ast.AlterTableSpec- var alterTableInplaceAddConstraintSpecs []*ast.AlterTableSpec- var alterTableInplaceDropConstraintSpecs []*ast.AlterTableSpec-- oldColumnMap := buildColumnMap(oldNodes, newStmt.Table.Name)- oldColumnPositionMap := buildColumnPositionMap(oldStmt)- for idx, columnDef := range newStmt.Cols {- newColumnName := columnDef.Name.Name.O- oldColumnDef, ok := oldColumnMap[newColumnName]- if !ok {- columnPosition := &ast.ColumnPosition{Tp: ast.ColumnPositionFirst}- if idx >= 1 {- columnPosition.Tp = ast.ColumnPositionAfter- columnPosition.RelativeColumn = &ast.ColumnName{Name: model.NewCIStr(newStmt.Cols[idx-1].Name.Name.O)}- }- alterTableAddColumnSpecs = append(alterTableAddColumnSpecs, &ast.AlterTableSpec{- Tp: ast.AlterTableAddColumns,- NewColumns: []*ast.ColumnDef{columnDef},- Position: columnPosition,- })- continue- }-- // Compare the column positions.- columnPosition := &ast.ColumnPosition{Tp: ast.ColumnPositionNone}- columnPosInOld := oldColumnPositionMap[newColumnName]- if hasColumnsIntersection(oldStmt.Cols[:columnPosInOld], newStmt.Cols[idx+1:]) {- if idx == 0 {- columnPosition.Tp = ast.ColumnPositionFirst- } else {- columnPosition.Tp = ast.ColumnPositionAfter- columnPosition.RelativeColumn = &ast.ColumnName{Name: model.NewCIStr(newStmt.Cols[idx-1].Name.Name.O)}- }- }- // Compare the column definitions.- if !isColumnEqual(oldColumnDef, columnDef) || columnPosition.Tp != ast.ColumnPositionNone {- alterTableModifyColumnSpecs = append(alterTableModifyColumnSpecs, &ast.AlterTableSpec{- Tp: ast.AlterTableModifyColumn,- NewColumns: []*ast.ColumnDef{columnDef},- Position: columnPosition,- })- }- delete(oldColumnMap, newColumnName)- }- // TODO(zp): add an option to control whether to drop the excess columns.- for _, columnDef := range oldColumnMap {- alterTableDropColumnSpecs = append(alterTableDropColumnSpecs, &ast.AlterTableSpec{- Tp: ast.AlterTableDropColumn,- OldColumnName: &ast.ColumnName{- Name: model.NewCIStr(columnDef.Name.Name.O),- },- })- }- // Compare the create definitions- for _, constraint := range newStmt.Constraints {- switch constraint.Tp {- case ast.ConstraintIndex, ast.ConstraintKey, ast.ConstraintUniq, ast.ConstraintUniqKey, ast.ConstraintUniqIndex, ast.ConstraintFulltext:- indexName := constraint.Name- if oldConstraint, ok := indexMap[indexName]; ok {- if !isIndexEqual(constraint, oldConstraint) {- alterTableInplaceDropConstraintSpecs = append(alterTableInplaceDropConstraintSpecs, &ast.AlterTableSpec{- Tp: ast.AlterTableDropIndex,- Name: indexName,- })- alterTableInplaceAddConstraintSpecs = append(alterTableInplaceAddConstraintSpecs, &ast.AlterTableSpec{- Tp: ast.AlterTableAddConstraint,- Constraint: constraint,- })- }- delete(indexMap, indexName)- continue- }- alterTableAddNewConstraintSpecs = append(alterTableAddNewConstraintSpecs, &ast.AlterTableSpec{- Tp: ast.AlterTableAddConstraint,- Constraint: constraint,- })- case ast.ConstraintPrimaryKey:- primaryKeyName := "PRIMARY"- if oldConstraint, ok := indexMap[primaryKeyName]; ok {- if !isIndexEqual(constraint, oldConstraint) {- alterTableInplaceDropConstraintSpecs = append(alterTableInplaceDropConstraintSpecs, &ast.AlterTableSpec{- Tp: ast.AlterTableDropPrimaryKey,- })- alterTableInplaceAddConstraintSpecs = append(alterTableInplaceAddConstraintSpecs, &ast.AlterTableSpec{- Tp: ast.AlterTableAddConstraint,- Constraint: constraint,- })- }- delete(indexMap, primaryKeyName)- continue- }- alterTableAddNewConstraintSpecs = append(alterTableAddNewConstraintSpecs, &ast.AlterTableSpec{- Tp: ast.AlterTableAddConstraint,- Constraint: constraint,- })- // The parent column in the foreign key always needs an index, so in the case of referencing itself,- // we need to drop the foreign key before dropping the primary key.- // Since the mysqldump statement always puts the primary key in front of the foreign key, and we will reverse the drop statements order.- // TODO(zp): So we don't have to worry about this now until one of the statements doesn't come from mysqldump.- case ast.ConstraintForeignKey:- if oldConstraint, ok := constraintMap[constraint.Name]; ok {- if !isForeignKeyConstraintEqual(constraint, oldConstraint) {- alterTableInplaceDropConstraintSpecs = append(alterTableInplaceDropConstraintSpecs, &ast.AlterTableSpec{- Tp: ast.AlterTableDropForeignKey,- Name: constraint.Name,- })- alterTableInplaceAddConstraintSpecs = append(alterTableInplaceAddConstraintSpecs, &ast.AlterTableSpec{- Tp: ast.AlterTableAddConstraint,- Constraint: constraint,- })- }- delete(constraintMap, constraint.Name)- continue- }- alterTableAddNewConstraintSpecs = append(alterTableAddNewConstraintSpecs, &ast.AlterTableSpec{- Tp: ast.AlterTableAddConstraint,- Constraint: constraint,- })- case ast.ConstraintCheck:- if oldConstraint, ok := constraintMap[constraint.Name]; ok {- if !isCheckConstraintEqual(constraint, oldConstraint) {- alterTableInplaceDropConstraintSpecs = append(alterTableInplaceDropConstraintSpecs, &ast.AlterTableSpec{- Tp: ast.AlterTableDropCheck,- Constraint: constraint,- })- alterTableInplaceAddConstraintSpecs = append(alterTableInplaceAddConstraintSpecs, &ast.AlterTableSpec{- Tp: ast.AlterTableAddConstraint,- Constraint: constraint,- })- }- delete(constraintMap, constraint.Name)- continue- }- alterTableAddNewConstraintSpecs = append(alterTableAddNewConstraintSpecs, &ast.AlterTableSpec{- Tp: ast.AlterTableAddConstraint,- Constraint: constraint,- })- }- }- if len(alterTableAddColumnSpecs) > 0 {- newNodeList = append(newNodeList, &ast.AlterTableStmt{- Table: &ast.TableName{- Name: model.NewCIStr(tableName),- },- Specs: alterTableAddColumnSpecs,- })- }- if len(alterTableDropColumnSpecs) > 0 {- dropNodeList = append(dropNodeList, &ast.AlterTableStmt{- Table: &ast.TableName{- Name: model.NewCIStr(tableName),- },- Specs: alterTableDropColumnSpecs,- })- }- if len(alterTableModifyColumnSpecs) > 0 {- inplaceUpdate = append(inplaceUpdate, &ast.AlterTableStmt{- Table: &ast.TableName{- Name: model.NewCIStr(tableName),- },- Specs: alterTableModifyColumnSpecs,- })- }- // Drop the remaining indices.- for indexName, constraint := range indexMap {- switch constraint.Tp {- case ast.ConstraintIndex, ast.ConstraintKey, ast.ConstraintUniq, ast.ConstraintUniqKey, ast.ConstraintUniqIndex, ast.ConstraintFulltext:- alterTableDropExcessConstraintSpecs = append(alterTableDropExcessConstraintSpecs, &ast.AlterTableSpec{- Tp: ast.AlterTableDropIndex,- Name: indexName,- })- case ast.ConstraintPrimaryKey:- alterTableDropExcessConstraintSpecs = append(alterTableDropExcessConstraintSpecs, &ast.AlterTableSpec{- Tp: ast.AlterTableDropPrimaryKey,- })- }- }- // Drop the remaining constraints.- for constraintName, constraint := range constraintMap {- switch constraint.Tp {- case ast.ConstraintForeignKey:- alterTableDropExcessConstraintSpecs = append(alterTableDropExcessConstraintSpecs, &ast.AlterTableSpec{- Tp: ast.AlterTableDropForeignKey,- Name: constraintName,- })- case ast.ConstraintCheck:- alterTableDropExcessConstraintSpecs = append(alterTableDropExcessConstraintSpecs, &ast.AlterTableSpec{- Tp: ast.AlterTableDropCheck,- Constraint: constraint,- })- }- }-- if len(alterTableAddNewConstraintSpecs) > 0 {- newNodeList = append(newNodeList, &ast.AlterTableStmt{- Table: &ast.TableName{- Name: model.NewCIStr(tableName),- },- Specs: alterTableAddNewConstraintSpecs,- })- }-- if len(alterTableDropExcessConstraintSpecs) > 0 {- dropNodeList = append(dropNodeList, &ast.AlterTableStmt{- Table: &ast.TableName{- Name: model.NewCIStr(tableName),- },- Specs: alterTableDropExcessConstraintSpecs,- })- }-- if len(alterTableInplaceDropConstraintSpecs) > 0 {- inplaceDropNodeList = append(inplaceDropNodeList, &ast.AlterTableStmt{- Table: &ast.TableName{- Name: model.NewCIStr(tableName),- },- Specs: alterTableInplaceDropConstraintSpecs,- })- }-- if len(alterTableInplaceAddConstraintSpecs) > 0 {- inplaceAddNodeList = append(inplaceAddNodeList, &ast.AlterTableStmt{- Table: &ast.TableName{- Name: model.NewCIStr(tableName),- },- Specs: alterTableInplaceAddConstraintSpecs,- })- }- delete(oldTableMap, tableName)- case *ast.CreateViewStmt:- newViewList = append(newViewList, newStmt)- }- }+// diffNode defines different modification types as the safe change order.+// The safe change order means we can change them with no dependency conflicts as this order.+type diffNode struct {+ dropUnsupportedStatement []string+ dropForeignKeyList []ast.Node+ dropConstraintExceptFkList []ast.Node+ dropIndexList []ast.Node+ dropViewList []ast.Node+ dropColumnList []ast.Node+ dropTableList []ast.Node++ createTableList []ast.Node+ alterTableOptionList []ast.Node+ addColumnList []ast.Node+ modifyColumnList []ast.Node+ createTempViewList []ast.Node+ createIndexList []ast.Node+ addConstraintExceptFkList []ast.Node+ addForeignKeyList []ast.Node+ createViewList []ast.Node+ createUnsupportedStatement []string+ inPlaceDropUnsupportedStatement []string+ inPlaceAddUnsupportedStatement []string+}+func (diff *diffNode) diffUnsupportedStatement(oldUnsupportedStmtList, newUnsupportedStmtList []string) error {// We compare the CREATE TRIGGER/EVENT/FUNCTION/PROCEDURE statements based on strcmp.- var newNodeStmt []string- var inplaceDropStmt []string- var inplaceAddStmt []string- var dropStmt []string-- oldUnsupportMap, err := buildUnsupportObjectMap(oldUnsupportFilterStmts)+ oldUnsupportMap, err := buildUnsupportObjectMap(oldUnsupportedStmtList)if err != nil {- return "", err+ return err}- newUnsupportMap, err := buildUnsupportObjectMap(newUnsupportFilterStmts)+ newUnsupportMap, err := buildUnsupportObjectMap(newUnsupportedStmtList)if err != nil {- return "", err+ return err}for tp, objs := range newUnsupportMap {for newName, newStmt := range objs {@@ -373,8 +88,8 @@ func (*SchemaDiffer) SchemaDiff(oldStmt, newStmt string) (string, error) {// We should drop the old function and create the new function.// https://dev.mysql.com/doc/refman/8.0/en/drop-procedure.html// https://dev.mysql.com/doc/refman/5.7/en/drop-procedure.html- inplaceDropStmt = append(inplaceDropStmt, fmt.Sprintf("DROP %s IF EXISTS `%s`;", tp, newName))- inplaceAddStmt = append(inplaceAddStmt, newStmt)+ diff.inPlaceDropUnsupportedStatement = append(diff.inPlaceDropUnsupportedStatement, fmt.Sprintf("DROP %s IF EXISTS `%s`;", tp, newName))+ diff.inPlaceAddUnsupportedStatement = append(diff.inPlaceAddUnsupportedStatement, newStmt)}delete(oldUnsupportMap[tp], newName)continue@@ -382,18 +97,75 @@ func (*SchemaDiffer) SchemaDiff(oldStmt, newStmt string) (string, error) {// Now, the input of differ comes from the our mysqldump, mysqldump use ;; to separate the CREATE TRIGGER/FUNCTION/PROCEDURE/EVENT statements;// So we should append DELIMITER statement to the newStmt.delimiterNewStmt := fmt.Sprintf("DELIMITER ;;\n%s\nDELIMITER ;\n", newStmt)- newNodeStmt = append(newNodeStmt, delimiterNewStmt)+ diff.createUnsupportedStatement = append(diff.createUnsupportedStatement, delimiterNewStmt)}}// drop remaining TiDB unsupported objectsfor tp, objs := range oldUnsupportMap {for name := range objs {- dropStmt = append(dropStmt, fmt.Sprintf("DROP %s IF EXISTS `%s`;", tp, name))+ diff.dropUnsupportedStatement = append(diff.dropUnsupportedStatement, fmt.Sprintf("DROP %s IF EXISTS `%s`;", tp, name))+ }+ }++ return nil+}++func (diff *diffNode) diffSupportedStatement(oldStatement, newStatement string) error {+ oldNodeList, _, err := parser.New().Parse(oldStatement, "", "")+ if err != nil {+ return errors.Wrapf(err, "failed to parse old statement %q", oldStatement)+ }+ newNodeList, _, err := parser.New().Parse(newStatement, "", "")+ if err != nil {+ return errors.Wrapf(err, "failed to parse new statement %q", newStatement)+ }++ oldSchemaInfo, err := buildSchemaInfo(oldNodeList)+ if err != nil {+ return err+ }+ newSchemaInfo, err := buildSchemaInfo(newNodeList)+ if err != nil {+ return err+ }++ for tableName, newTable := range newSchemaInfo.tableMap {+ oldTable, exists := oldSchemaInfo.tableMap[tableName]+ if !exists {+ newTable.createTable.IfNotExists = true+ diff.createTableList = append(diff.createTableList, newTable.createTable)+ // Create indexes.+ for _, index := range newTable.indexMap {+ diff.createIndexList = append(diff.createIndexList, index.createIndex)+ }+ continue+ }+ diff.diffTable(oldTable, newTable)+ delete(oldSchemaInfo.tableMap, tableName)+ }++ for _, oldTable := range oldSchemaInfo.tableMap {+ diff.dropTableList = append(diff.dropTableList, &ast.DropTableStmt{+ IfExists: true,+ Tables: []*ast.TableName{oldTable.createTable.Table},+ })+ }++ var newViewList []*ast.CreateViewStmt+ for _, newNode := range newNodeList {+ if newView, ok := newNode.(*ast.CreateViewStmt); ok {+ newViewList = append(newViewList, newView)}}- var tempViewList []*ast.CreateViewStmt- var viewList []*ast.CreateViewStmt+ diff.diffView(oldSchemaInfo.viewMap, newSchemaInfo.viewMap, newViewList)++ return nil+}++func (diff *diffNode) diffView(oldViewMap viewMap, newViewMap viewMap, newViewList []*ast.CreateViewStmt) {+ var tempViewList []ast.Node+ var viewList []ast.Nodefor _, view := range newViewList {viewName := view.ViewName.Name.Oif newNode, ok := newViewMap[viewName]; ok {@@ -413,7 +185,7 @@ func (*SchemaDiffer) SchemaDiff(oldStmt, newStmt string) (string, error) {delete(oldViewMap, viewName)} else {// We should create the view.- // We create the temporary view first and replace it to avoid break the rependency like mysqldump does.+ // We create the temporary view first and replace it to avoid break the dependency like mysqldump does.tempViewStmt := getTempView(view)tempViewList = append(tempViewList, tempViewStmt)createViewStmt := *view@@ -421,8 +193,8 @@ func (*SchemaDiffer) SchemaDiff(oldStmt, newStmt string) (string, error) {viewList = append(viewList, &createViewStmt)}}- viewStmts = append(viewStmts, tempViewList...)- viewStmts = append(viewStmts, viewList...)+ diff.createTempViewList = append(diff.createTempViewList, tempViewList...)+ diff.createViewList = append(diff.createViewList, viewList...)// Remove the remaining views in the oldViewMap.dropViewStmt := &ast.DropTableStmt{@@ -432,104 +204,396 @@ func (*SchemaDiffer) SchemaDiff(oldStmt, newStmt string) (string, error) {dropViewStmt.Tables = append(dropViewStmt.Tables, oldView.ViewName)}if len(dropViewStmt.Tables) > 0 {- dropNodeList = append(dropNodeList, dropViewStmt)+ diff.dropViewList = append(diff.dropViewList, dropViewStmt)}+}++func (diff *diffNode) diffTable(oldTable, newTable *tableInfo) {+ diff.diffTableOption(oldTable, newTable)+ diff.diffColumn(oldTable, newTable)+ diff.diffIndex(oldTable, newTable)+ diff.diffConstraint(oldTable, newTable)+}- // TODO(zp): Add an option to control whether to drop the excess table.- for _, oldTable := range oldTableMap {- dropTableStmt := &ast.DropTableStmt{- Tables: []*ast.TableName{oldTable.Table},+func (diff *diffNode) diffConstraint(oldTable, newTable *tableInfo) {+ oldPrimaryKey, oldConstraintMap := buildConstraintMap(oldTable.createTable)+ // Compare the create definitions.+ for _, constraint := range newTable.createTable.Constraints {+ switch constraint.Tp {+ case ast.ConstraintPrimaryKey:+ if oldPrimaryKey != nil {+ if !isPrimaryKeyEqual(constraint, oldPrimaryKey) {+ diff.dropConstraintExceptFkList = append(diff.dropConstraintExceptFkList, &ast.AlterTableStmt{+ Table: newTable.createTable.Table,+ Specs: []*ast.AlterTableSpec{+ {+ Tp: ast.AlterTableDropPrimaryKey,+ },+ },+ })+ diff.addConstraintExceptFkList = append(diff.addConstraintExceptFkList, &ast.AlterTableStmt{+ Table: newTable.createTable.Table,+ Specs: []*ast.AlterTableSpec{+ {+ Tp: ast.AlterTableAddConstraint,+ Constraint: constraint,+ },+ },+ })+ }+ oldPrimaryKey = nil+ continue+ }+ diff.addConstraintExceptFkList = append(diff.addConstraintExceptFkList, &ast.AlterTableStmt{+ Table: newTable.createTable.Table,+ Specs: []*ast.AlterTableSpec{+ {+ Tp: ast.AlterTableAddConstraint,+ Constraint: constraint,+ },+ },+ })+ case ast.ConstraintForeignKey:+ if oldConstraint, ok := oldConstraintMap[constraint.Name]; ok {+ if !isForeignKeyConstraintEqual(constraint, oldConstraint) {+ diff.dropForeignKeyList = append(diff.dropForeignKeyList, &ast.AlterTableStmt{+ Table: newTable.createTable.Table,+ Specs: []*ast.AlterTableSpec{+ {+ Tp: ast.AlterTableDropForeignKey,+ Name: constraint.Name,+ },+ },+ })+ diff.addForeignKeyList = append(diff.addForeignKeyList, &ast.AlterTableStmt{+ Table: newTable.createTable.Table,+ Specs: []*ast.AlterTableSpec{+ {+ Tp: ast.AlterTableAddConstraint,+ Constraint: constraint,+ },+ },+ })+ }+ delete(oldConstraintMap, constraint.Name)+ continue+ }+ diff.addForeignKeyList = append(diff.addForeignKeyList, &ast.AlterTableStmt{+ Table: newTable.createTable.Table,+ Specs: []*ast.AlterTableSpec{+ {+ Tp: ast.AlterTableAddConstraint,+ Constraint: constraint,+ },+ },+ })+ case ast.ConstraintCheck:+ if oldConstraint, ok := oldConstraintMap[constraint.Name]; ok {+ if !isCheckConstraintEqual(constraint, oldConstraint) {+ diff.dropConstraintExceptFkList = append(diff.dropConstraintExceptFkList, &ast.AlterTableStmt{+ Table: newTable.createTable.Table,+ Specs: []*ast.AlterTableSpec{+ {+ Tp: ast.AlterTableDropCheck,+ Constraint: constraint,+ },+ },+ })+ diff.addConstraintExceptFkList = append(diff.addConstraintExceptFkList, &ast.AlterTableStmt{+ Table: newTable.createTable.Table,+ Specs: []*ast.AlterTableSpec{+ {+ Tp: ast.AlterTableAddConstraint,+ Constraint: constraint,+ },+ },+ })+ }+ delete(oldConstraintMap, constraint.Name)+ continue+ }+ diff.addConstraintExceptFkList = append(diff.addConstraintExceptFkList, &ast.AlterTableStmt{+ Table: newTable.createTable.Table,+ Specs: []*ast.AlterTableSpec{+ {+ Tp: ast.AlterTableAddConstraint,+ Constraint: constraint,+ },+ },+ })}- dropNodeList = append(dropNodeList, dropTableStmt)}- var buf bytes.Buffer- if err := deparse(&buf, newNodeList, newNodeStmt, inplaceUpdate,- inplaceAddNodeList, inplaceAddStmt, inplaceDropNodeList,- inplaceDropStmt, dropNodeList, dropStmt, viewStmts,- format.DefaultRestoreFlags|format.RestoreStringWithoutCharset|format.RestorePrettyFormat); err != nil {- return "", errors.Wrapf(err, "deparse failed")+ if oldPrimaryKey != nil {+ diff.dropConstraintExceptFkList = append(diff.dropConstraintExceptFkList, &ast.AlterTableStmt{+ Table: newTable.createTable.Table,+ Specs: []*ast.AlterTableSpec{+ {+ Tp: ast.AlterTableDropPrimaryKey,+ },+ },+ })}- if buf.Len() > 0 {- return fmt.Sprintf("%s%s%s", disableFKCheckStmt, buf.String(), enableFKCheckStmt), nil++ for _, oldConstraint := range oldConstraintMap {+ switch oldConstraint.Tp {+ case ast.ConstraintCheck:+ diff.dropConstraintExceptFkList = append(diff.dropConstraintExceptFkList, &ast.AlterTableStmt{+ Table: newTable.createTable.Table,+ Specs: []*ast.AlterTableSpec{+ {+ Tp: ast.AlterTableDropCheck,+ Constraint: oldConstraint,+ },+ },+ })+ case ast.ConstraintForeignKey:+ diff.dropForeignKeyList = append(diff.dropForeignKeyList, &ast.AlterTableStmt{+ Table: newTable.createTable.Table,+ Specs: []*ast.AlterTableSpec{+ {+ Tp: ast.AlterTableDropForeignKey,+ Name: oldConstraint.Name,+ },+ },+ })+ }}- return "", nil}-// deparse deparses the ast node list and stmt list to sql string and write it to the out.-func deparse(out io.Writer, newNodeList []ast.Node, newNodeStmt []string, inplaceUpdate []ast.Node,- inplaceAdd []ast.Node, inplaceAddStmt []string, inplaceDrop []ast.Node,- inplaceDropStmt []string, dropNodeList []ast.Node, dropStmt []string,- viewStmts []*ast.CreateViewStmt, flag format.RestoreFlags) error {- // We should following the right order to avoid break the dependency:- // Additions for new nodes.- // Updates for in-place node updates.- // Deletions for destructive (none in-place) node updates (in reverse order).- // Additions for destructive node updates.- // Deletions for deleted nodes (in reverse order).- if err := writeNodeStatementList(out, newNodeList, flag, false /*reverse*/); err != nil {- return errors.Wrap(err, "failed to write new node list" /*reverse*/)+func (diff *diffNode) diffIndex(oldTable, newTable *tableInfo) {+ for indexName, newIndex := range newTable.indexMap {+ if oldIndex, ok := oldTable.indexMap[indexName]; ok {+ if !isIndexEqual(newIndex.createIndex, oldIndex.createIndex) {+ diff.dropIndexList = append(diff.dropIndexList, &ast.DropIndexStmt{+ IndexName: indexName,+ Table: oldIndex.createIndex.Table,+ })+ diff.createIndexList = append(diff.createIndexList, newIndex.createIndex)+ }+ delete(oldTable.indexMap, indexName)+ continue+ }+ diff.createIndexList = append(diff.createIndexList, newIndex.createIndex)+ }++ for indexName, oldIndex := range oldTable.indexMap {+ diff.dropIndexList = append(diff.dropIndexList, &ast.DropIndexStmt{+ IndexName: indexName,+ Table: oldIndex.createIndex.Table,+ })}- if err := writeStringStatementList(out, newNodeStmt, false /*reverse*/); err != nil {- return errors.Wrap(err, "failed to write new node statement list")+}++func (diff *diffNode) diffColumn(oldTable, newTable *tableInfo) {+ addColumnStatement := &ast.AlterTableStmt{Table: newTable.createTable.Table}+ modifyColumnStatement := &ast.AlterTableStmt{Table: newTable.createTable.Table}+ dropColumnStatement := &ast.AlterTableStmt{Table: newTable.createTable.Table}++ oldColumnMap := buildColumnMap(oldTable.createTable.Cols)+ oldColumnPositionMap := buildColumnPositionMap(oldTable.createTable)+ for idx, columnDef := range newTable.createTable.Cols {+ newColumnName := columnDef.Name.Name.O+ oldColumnDef, ok := oldColumnMap[newColumnName]+ if !ok {+ columnPosition := &ast.ColumnPosition{Tp: ast.ColumnPositionFirst}+ if idx >= 1 {+ columnPosition.Tp = ast.ColumnPositionAfter+ columnPosition.RelativeColumn = &ast.ColumnName{Name: model.NewCIStr(newTable.createTable.Cols[idx-1].Name.Name.O)}+ }+ addColumnStatement.Specs = append(addColumnStatement.Specs, &ast.AlterTableSpec{+ Tp: ast.AlterTableAddColumns,+ NewColumns: []*ast.ColumnDef{columnDef},+ Position: columnPosition,+ })+ continue+ }++ // Compare the column positions.+ // TODO(rebelice): fix the position comparing.+ columnPosition := &ast.ColumnPosition{Tp: ast.ColumnPositionNone}+ columnPosInOld := oldColumnPositionMap[newColumnName]+ if hasColumnsIntersection(oldTable.createTable.Cols[:columnPosInOld], newTable.createTable.Cols[idx+1:]) {+ if idx == 0 {+ columnPosition.Tp = ast.ColumnPositionFirst+ } else {+ columnPosition.Tp = ast.ColumnPositionAfter+ columnPosition.RelativeColumn = &ast.ColumnName{Name: model.NewCIStr(newTable.createTable.Cols[idx-1].Name.Name.O)}+ }+ }+ // Compare the column definitions.+ if !isColumnEqual(oldColumnDef, columnDef) || columnPosition.Tp != ast.ColumnPositionNone {+ modifyColumnStatement.Specs = append(modifyColumnStatement.Specs, &ast.AlterTableSpec{+ Tp: ast.AlterTableModifyColumn,+ NewColumns: []*ast.ColumnDef{columnDef},+ Position: columnPosition,+ })+ }+ delete(oldColumnMap, newColumnName)+ }+ // TODO(zp): add an option to control whether to drop the excess columns.+ for _, columnDef := range oldColumnMap {+ dropColumnStatement.Specs = append(dropColumnStatement.Specs, &ast.AlterTableSpec{+ Tp: ast.AlterTableDropColumn,+ OldColumnName: &ast.ColumnName{+ Name: model.NewCIStr(columnDef.Name.Name.O),+ },+ })}- if err := writeNodeStatementList(out, inplaceUpdate, flag, false /*reverse*/); err != nil {- return errors.Wrap(err, "failed to write inplace update node list")++ if len(addColumnStatement.Specs) > 0 {+ diff.addColumnList = append(diff.addColumnList, addColumnStatement)}- if err := writeNodeStatementList(out, inplaceDrop, flag, true /*reverse*/); err != nil {- return errors.Wrap(err, "failed to write inplace drop node list")+ if len(modifyColumnStatement.Specs) > 0 {+ diff.modifyColumnList = append(diff.modifyColumnList, modifyColumnStatement)}- if err := writeStringStatementList(out, inplaceDropStmt, true /*reverse*/); err != nil {- return errors.Wrap(err, "failed to write inplace drop statement list")+ if len(dropColumnStatement.Specs) > 0 {+ diff.dropColumnList = append(diff.dropColumnList, dropColumnStatement)}- if err := writeNodeStatementList(out, inplaceAdd, flag, false /*reverse*/); err != nil {- return errors.Wrap(err, "failed to write inplace add node list")+}++func (diff *diffNode) diffTableOption(oldTable, newTable *tableInfo) {+ if alterTableOptionStmt := diffTableOptions(newTable.createTable.Table, oldTable.createTable.Options, newTable.createTable.Options); alterTableOptionStmt != nil {+ diff.alterTableOptionList = append(diff.alterTableOptionList, alterTableOptionStmt)}- if err := writeStringStatementList(out, inplaceAddStmt, false /*reverse*/); err != nil {- return errors.Wrap(err, "failed to write inplace add statement list")+}++func (diff *diffNode) deparse() (string, error) {+ var buf bytes.Buffer+ flag := format.DefaultRestoreFlags | format.RestoreStringWithoutCharset | format.RestorePrettyFormat++ sort.Strings(diff.dropUnsupportedStatement)+ for _, statement := range diff.dropUnsupportedStatement {+ if _, err := buf.WriteString(statement); err != nil {+ return "", err+ }+ if _, err := buf.WriteString("\n\n"); err != nil {+ return "", err+ }}- if err := writeNodeStatementList(out, dropNodeList, flag, true /*reverse*/); err != nil {- return errors.Wrap(err, "failed to write drop node list")+ if err := sortAndWriteNodeList(&buf, diff.dropForeignKeyList, flag); err != nil {+ return "", err}- if err := writeStringStatementList(out, dropStmt, true /*reverse*/); err != nil {- return errors.Wrap(err, "failed to write drop statement list")+ if err := sortAndWriteNodeList(&buf, diff.dropConstraintExceptFkList, flag); err != nil {+ return "", err}- for _, node := range viewStmts {- if err := node.Restore(format.NewRestoreCtx(flag, out)); err != nil {- return err+ if err := sortAndWriteNodeList(&buf, diff.dropIndexList, flag); err != nil {+ return "", err+ }+ if err := sortAndWriteNodeList(&buf, diff.dropViewList, flag); err != nil {+ return "", err+ }+ if err := sortAndWriteNodeList(&buf, diff.dropColumnList, flag); err != nil {+ return "", err+ }+ if err := sortAndWriteNodeList(&buf, diff.dropTableList, flag); err != nil {+ return "", err+ }+ if err := sortAndWriteNodeList(&buf, diff.createTableList, flag); err != nil {+ return "", err+ }+ if err := sortAndWriteNodeList(&buf, diff.alterTableOptionList, flag); err != nil {+ return "", err+ }+ if err := sortAndWriteNodeList(&buf, diff.addColumnList, flag); err != nil {+ return "", err+ }+ if err := sortAndWriteNodeList(&buf, diff.modifyColumnList, flag); err != nil {+ return "", err+ }+ if err := sortAndWriteNodeList(&buf, diff.createTempViewList, flag); err != nil {+ return "", err+ }+ if err := sortAndWriteNodeList(&buf, diff.createIndexList, flag); err != nil {+ return "", err+ }+ if err := sortAndWriteNodeList(&buf, diff.addConstraintExceptFkList, flag); err != nil {+ return "", err+ }+ if err := sortAndWriteNodeList(&buf, diff.addForeignKeyList, flag); err != nil {+ return "", err+ }+ if err := sortAndWriteNodeList(&buf, diff.createViewList, flag); err != nil {+ return "", err+ }++ sort.Strings(diff.createUnsupportedStatement)+ for _, statement := range diff.createUnsupportedStatement {+ if _, err := buf.WriteString(statement); err != nil {+ return "", err}- if _, err := out.Write([]byte(";\n\n")); err != nil {- return err+ if _, err := buf.WriteString("\n\n"); err != nil {+ return "", err}}- return nil++ sort.Strings(diff.inPlaceDropUnsupportedStatement)+ for _, statement := range diff.inPlaceDropUnsupportedStatement {+ if _, err := buf.WriteString(statement); err != nil {+ return "", err+ }+ if _, err := buf.WriteString("\n\n"); err != nil {+ return "", err+ }+ }++ sort.Strings(diff.inPlaceAddUnsupportedStatement)+ for _, statement := range diff.inPlaceAddUnsupportedStatement {+ if _, err := buf.WriteString(statement); err != nil {+ return "", err+ }+ if _, err := buf.WriteString("\n\n"); err != nil {+ return "", err+ }+ }++ text := buf.String()+ if len(text) > 0 {+ return fmt.Sprintf("%s%s%s", disableFKCheckStmt, buf.String(), enableFKCheckStmt), nil+ }+ return "", nil}-func writeStringStatement(w io.Writer, s string) error {- if _, err := w.Write([]byte(s)); err != nil {- return err+// constraintMap returns a map of constraint name to constraint.+type constraintMap map[string]*ast.Constraint++// SchemaDiff returns the schema diff.+// It only supports schema information from mysqldump.+func (*SchemaDiffer) SchemaDiff(oldStmt, newStmt string) (string, error) {+ // 1. Preprocessing Stage.+ // TiDB parser doesn't support some statements like `CREATE EVENT`, so we need to extract them out and diff them based on string compare.+ oldUnsupportedStmtList, oldSupportedStmt, err := classifyStatement(oldStmt)+ if err != nil {+ return "", err}- if _, err := w.Write([]byte("\n\n")); err != nil {- return err+ newUnsupportedStmtList, newSupportedStmt, err := classifyStatement(newStmt)+ if err != nil {+ return "", err}- return nil++ diff := &diffNode{}+ if err := diff.diffSupportedStatement(oldSupportedStmt, newSupportedStmt); err != nil {+ return "", err+ }+ if err := diff.diffUnsupportedStatement(oldUnsupportedStmtList, newUnsupportedStmtList); err != nil {+ return "", err+ }++ return diff.deparse()}-func writeStringStatementList(w io.Writer, ss []string, reverse bool) error {- if reverse {- for i := len(ss) - 1; i >= 0; i-- {- if err := writeStringStatement(w, ss[i]); err != nil {- return err- }- }- } else {- for _, s := range ss {- if err := writeStringStatement(w, s); err != nil {- return err- }+func classifyStatement(statement string) ([]string, string, error) {+ unsupported, supported, err := bbparser.ExtractTiDBUnsupportStmts(statement)+ if err != nil {+ return nil, "", errors.Wrapf(err, "failed to extract TiDB unsupported statements from statements %q", statement)+ }+ var afterFilter []string+ for _, stmt := range unsupported {+ if !bbparser.IsDelimiter(stmt) {+ afterFilter = append(afterFilter, stmt)}}- return nil+ return afterFilter, supported, nil}func writeNodeStatement(w io.Writer, n ast.Node, flags format.RestoreFlags) error {@@ -543,47 +607,155 @@ func writeNodeStatement(w io.Writer, n ast.Node, flags format.RestoreFlags) erroreturn nil}-func writeNodeStatementList(w io.Writer, ns []ast.Node, flags format.RestoreFlags, reverse bool) error {- if reverse {- for i := len(ns) - 1; i >= 0; i-- {- if err := writeNodeStatement(w, ns[i], flags); err != nil {- return err+func getID(node ast.Node) string {+ switch in := node.(type) {+ case *ast.CreateTableStmt:+ return in.Table.Name.String()+ case *ast.DropTableStmt:+ return in.Tables[0].Name.String()+ case *ast.AlterTableStmt:+ for _, spec := range in.Specs {+ switch spec.Tp {+ case ast.AlterTableOption:+ return in.Table.Name.String()+ case ast.AlterTableAddColumns:+ return fmt.Sprintf("%s.%s", in.Table.Name.String(), spec.NewColumns[0].Name)+ case ast.AlterTableDropColumn:+ return fmt.Sprintf("%s.%s", in.Table.Name.String(), spec.OldColumnName.Name.String())+ case ast.AlterTableModifyColumn:+ return fmt.Sprintf("%s.%s", in.Table.Name.String(), spec.NewColumns[0].Name)+ case ast.AlterTableAddConstraint:+ return fmt.Sprintf("%s.%s", in.Table.Name.String(), spec.Constraint.Name)+ case ast.AlterTableDropForeignKey:+ return fmt.Sprintf("%s.%s", in.Table.Name.String(), spec.Name)+ case ast.AlterTableDropPrimaryKey:+ return in.Table.Name.String()+ case ast.AlterTableDropCheck:+ return fmt.Sprintf("%s.%s", in.Table.Name.String(), spec.Constraint.Name)}}- } else {- for _, n := range ns {- if err := writeNodeStatement(w, n, flags); err != nil {- return err- }+ case *ast.CreateIndexStmt:+ return fmt.Sprintf("%s.%s", in.Table.Name.String(), in.IndexName)+ case *ast.DropIndexStmt:+ return fmt.Sprintf("%s.%s", in.Table.Name.String(), in.IndexName)+ case *ast.CreateViewStmt:+ return in.ViewName.Name.String()+ }+ return ""+}++func sortAndWriteNodeList(w io.Writer, ns []ast.Node, flags format.RestoreFlags) error {+ sort.Slice(ns, func(i, j int) bool {+ return getID(ns[i]) < getID(ns[j])+ })++ for _, n := range ns {+ if err := writeNodeStatement(w, n, flags); err != nil {+ return err}}return nil}-// buildTableMap returns a map of table name to create table statements.-func buildTableMap(nodes []ast.StmtNode) map[string]*ast.CreateTableStmt {- tableMap := make(map[string]*ast.CreateTableStmt)- for _, node := range nodes {- switch stmt := node.(type) {- case *ast.CreateTableStmt:- tableName := stmt.Table.Name.String()- tableMap[tableName] = stmt- default:+type schemaInfo struct {+ tableMap tableMap+ viewMap viewMap+}++type viewMap map[string]*ast.CreateViewStmt++type indexInfo struct {+ createIndex *ast.CreateIndexStmt+}+type indexMap map[string]*indexInfo++func newIndexInfo(createIndex *ast.CreateIndexStmt) *indexInfo {+ return &indexInfo{+ createIndex: createIndex,+ }+}++type tableInfo struct {+ createTable *ast.CreateTableStmt+ indexMap indexMap+}+type tableMap map[string]*tableInfo++func newTableInfo(createTable *ast.CreateTableStmt) (*tableInfo, error) {+ result := &tableInfo{+ createTable: createTable,+ indexMap: make(indexMap),+ }++ var newConstraintList []*ast.Constraint+ for _, constraint := range createTable.Constraints {+ if createIndex := transformConstraintToIndex(createTable.Table, constraint); createIndex != nil {+ if _, exists := result.indexMap[createIndex.IndexName]; exists {+ return nil, errors.Errorf("Try to create index `%s` on table `%s`, but index already exists", createIndex.IndexName, createIndex.Table.Name.String())+ }+ result.indexMap[constraint.Name] = newIndexInfo(createIndex)+ } else {+ newConstraintList = append(newConstraintList, constraint)}}- return tableMap+ createTable.Constraints = newConstraintList++ return result, nil}-// buildViewMap returns a map of view name to create view statements.-func buildViewMap(nodes []ast.StmtNode) map[string]*ast.CreateViewStmt {- viewMap := make(map[string]*ast.CreateViewStmt)+func transformConstraintToIndex(tableName *ast.TableName, constraint *ast.Constraint) *ast.CreateIndexStmt {+ indexType := ast.IndexKeyTypeNone+ switch constraint.Tp {+ case ast.ConstraintKey, ast.ConstraintIndex:+ case ast.ConstraintUniq, ast.ConstraintUniqKey, ast.ConstraintUniqIndex:+ indexType = ast.IndexKeyTypeUnique+ case ast.ConstraintFulltext:+ indexType = ast.IndexKeyTypeFullText+ default:+ return nil+ }+ result := &ast.CreateIndexStmt{+ IndexName: constraint.Name,+ Table: tableName,+ IndexPartSpecifications: constraint.Keys,+ IndexOption: constraint.Option,+ KeyType: indexType,+ }+ if result.IndexOption == nil {+ result.IndexOption = &ast.IndexOption{Tp: model.IndexTypeInvalid}+ }+ return result+}++// buildSchemaInfo returns schema information built by statements.+func buildSchemaInfo(nodes []ast.StmtNode) (*schemaInfo, error) {+ result := &schemaInfo{+ tableMap: make(tableMap),+ viewMap: make(viewMap),+ }for _, node := range nodes {- if stmt, ok := node.(*ast.CreateViewStmt); ok {- viewName := stmt.ViewName.Name.O- viewMap[viewName] = stmt+ switch stmt := node.(type) {+ case *ast.CreateTableStmt:+ var err error+ tableName := stmt.Table.Name.String()+ if result.tableMap[tableName], err = newTableInfo(stmt); err != nil {+ return nil, err+ }+ case *ast.CreateIndexStmt:+ table, exists := result.tableMap[stmt.Table.Name.String()]+ if !exists {+ return nil, errors.Errorf("Try to create index `%s` on table `%s`, but table not found", stmt.IndexName, stmt.Table.Name.String())+ }+ if _, exists := table.indexMap[stmt.IndexName]; exists {+ return nil, errors.Errorf("Try to create index `%s` on table `%s`, but index already exists", stmt.IndexName, stmt.Table.Name.String())+ }+ table.indexMap[stmt.IndexName] = newIndexInfo(stmt)+ case *ast.CreateViewStmt:+ result.viewMap[stmt.ViewName.Name.String()] = stmt+ default:}}- return viewMap+ return result, nil}// buildUnsupportObjectMap builds map for trigger, function, procedure, event to correspond create object string statements.@@ -663,19 +835,10 @@ func getTempView(stmt *ast.CreateViewStmt) *ast.CreateViewStmt {}// buildColumnMap returns a map of column name to column definition on a given table.-func buildColumnMap(nodes []ast.StmtNode, tableName model.CIStr) map[string]*ast.ColumnDef {+func buildColumnMap(columnList []*ast.ColumnDef) map[string]*ast.ColumnDef {oldColumnMap := make(map[string]*ast.ColumnDef)- for _, node := range nodes {- switch stmt := node.(type) {- case *ast.CreateTableStmt:- if stmt.Table.Name.O != tableName.O {- continue- }- for _, columnDef := range stmt.Cols {- oldColumnMap[columnDef.Name.Name.O] = columnDef- }- default:- }+ for _, columnDef := range columnList {+ oldColumnMap[columnDef.Name.Name.O] = columnDef}return oldColumnMap}@@ -689,34 +852,19 @@ func buildColumnPositionMap(stmt *ast.CreateTableStmt) map[string]int {return m}-// buildIndexMap build a map of index name to constraint on given table name.-func buildIndexMap(stmt *ast.CreateTableStmt) constraintMap {- indexMap := make(constraintMap)- for _, constraint := range stmt.Constraints {- switch constraint.Tp {- case ast.ConstraintIndex, ast.ConstraintKey, ast.ConstraintUniq, ast.ConstraintUniqKey, ast.ConstraintUniqIndex, ast.ConstraintFulltext:- indexMap[constraint.Name] = constraint- case ast.ConstraintPrimaryKey:- // A table can have only one PRIMARY KEY.- // The name of a PRIMARY KEY is always PRIMARY, which thus cannot be used as the name for any other kind of index.- // https://dev.mysql.com/doc/refman/8.0/en/create-table.html- // https://dev.mysql.com/doc/refman/5.7/en/create-table.html- indexMap["PRIMARY"] = constraint- }- }- return indexMap-}--func buildConstraintMap(stmt *ast.CreateTableStmt) constraintMap {+func buildConstraintMap(stmt *ast.CreateTableStmt) (*ast.Constraint, constraintMap) {+ var primaryKey *ast.ConstraintconstraintMap := make(constraintMap)for _, constraint := range stmt.Constraints {switch constraint.Tp {case ast.ConstraintForeignKey, ast.ConstraintCheck:constraintMap[constraint.Name] = constraint+ case ast.ConstraintPrimaryKey:+ primaryKey = constraintdefault:}}- return constraintMap+ return primaryKey, constraintMap}// isColumnEqual returns true if definitions of two columns with the same name are the same.@@ -783,7 +931,36 @@ func normalizeColumnOptions(options []*ast.ColumnOption) []*ast.ColumnOption {}// isIndexEqual returns true if definitions of two indexes are the same.-func isIndexEqual(old, new *ast.Constraint) bool {+func isIndexEqual(old, new *ast.CreateIndexStmt) bool {+ // CREATE [UNIQUE | FULLTEXT | SPATIAL] INDEX index_name+ // [index_type]+ // ON tbl_name (key_part,...)+ // [index_option]+ // [algorithm_option | lock_option] ...++ if old.IndexName != new.IndexName {+ return false+ }+ if (old.IndexOption == nil) != (new.IndexOption == nil) {+ return false+ }+ if old.IndexOption != nil && new.IndexOption != nil {+ if old.IndexOption.Tp != new.IndexOption.Tp {+ return false+ }+ }++ if !isKeyPartEqual(old.IndexPartSpecifications, new.IndexPartSpecifications) {+ return false+ }+ if !isIndexOptionEqual(old.IndexOption, new.IndexOption) {+ return false+ }+ return true+}++// isPrimaryKeyEqual returns true if definitions of two indexes are the same.+func isPrimaryKeyEqual(old, new *ast.Constraint) bool {// {INDEX | KEY} [index_name] [index_type] (key_part,...) [index_option] ...if old.Name != new.Name {return falsediff --git a/backend/plugin/parser/differ/mysql/table_test.go b/backend/plugin/parser/differ/mysql/table_test.goindex 8d900e07d6..a5a85fb036 100644--- a/backend/plugin/parser/differ/mysql/table_test.go+++ b/backend/plugin/parser/differ/mysql/table_test.go@@ -14,14 +14,14 @@ func TestTable(t *testing.T) {CREATE TABLE author(id INT, name VARCHAR(255), PRIMARY KEY(id));`,want: "" +- "CREATE TABLE IF NOT EXISTS `book` (\n" ++ "CREATE TABLE IF NOT EXISTS `author` (\n" +" `id` INT,\n" +- " `price` INT,\n" ++ " `name` VARCHAR(255),\n" +" PRIMARY KEY (`id`)\n" +");\n\n" +- "CREATE TABLE IF NOT EXISTS `author` (\n" ++ "CREATE TABLE IF NOT EXISTS `book` (\n" +" `id` INT,\n" +- " `name` VARCHAR(255),\n" ++ " `price` INT,\n" +" PRIMARY KEY (`id`)\n" +");\n\n",},@@ -50,9 +50,9 @@ func TestTable(t *testing.T) {old: `CREATE TABLE book(id INT, price_id INT, PRIMARY KEY(id), CONSTRAINT fk_price_id FOREIGN KEY (price_id) REFERENCES price(id));CREATE TABLE price(id INT, PRIMARY KEY(id));`,new: `CREATE TABLE book(id INT, PRIMARY KEY(id));`,- want: "DROP TABLE `price`;\n\n" +- "ALTER TABLE `book` DROP FOREIGN KEY `fk_price_id`;\n\n" +- "ALTER TABLE `book` DROP COLUMN `price_id`;\n\n",+ want: "ALTER TABLE `book` DROP FOREIGN KEY `fk_price_id`;\n\n" ++ "ALTER TABLE `book` DROP COLUMN `price_id`;\n\n" ++ "DROP TABLE IF EXISTS `price`;\n\n",},}testDiffWithoutDisableForeignKeyCheck(t, tests)