Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

chore: duplicate tidb parser (#8618)

Danny Xuc10e42c7416f
diff --git a/backend/plugin/db/mysql/rollback.go b/backend/plugin/db/mysql/rollback.go
index 25b7aa36d8..18cfa174a4 100644
--- a/backend/plugin/db/mysql/rollback.go
+++ b/backend/plugin/db/mysql/rollback.go
@@ -14,7 +14,7 @@ import (
"github.com/pingcap/tidb/parser/ast"
"github.com/pkg/errors"
- mysqlparser "github.com/bytebase/bytebase/backend/plugin/parser/mysql"
+ tidbparser "github.com/bytebase/bytebase/backend/plugin/parser/tidb"
"github.com/bytebase/bytebase/backend/resources/mysqlutil"
)
@@ -147,7 +147,7 @@ func (driver *Driver) GenerateRollbackSQL(ctx context.Context, binlogSizeLimit i
// GetTableColumns parses the schema to get the table columns map.
// This is used to generate rollback SQL from the binlog events.
func GetTableColumns(schema string) (map[string][]string, error) {
- _, supportStmts, err := mysqlparser.ExtractTiDBUnsupportedStmts(schema)
+ _, supportStmts, err := tidbparser.ExtractTiDBUnsupportedStmts(schema)
if err != nil {
return nil, errors.Wrapf(err, "failed to extract TiDB unsupported statements from old statements %q", schema)
}
diff --git a/backend/plugin/parser/mysql/compatible.go b/backend/plugin/parser/mysql/compatible.go
index d03745f5f6..cad48571f3 100644
--- a/backend/plugin/parser/mysql/compatible.go
+++ b/backend/plugin/parser/mysql/compatible.go
@@ -4,15 +4,18 @@ import (
"bytes"
"fmt"
"regexp"
+ "strconv"
+ tidbparser "github.com/pingcap/tidb/parser"
+ "github.com/pingcap/tidb/parser/ast"
"github.com/pkg/errors"
- tidbparser "github.com/bytebase/bytebase/backend/plugin/parser/tidb"
+ "github.com/bytebase/bytebase/backend/plugin/parser/base"
)
-// ExtractTiDBUnsupportedStmts returns a list of unsupported statements in TiDB extracted from the `stmts`,
+// extractTiDBUnsupportedStmts returns a list of unsupported statements in TiDB extracted from the `stmts`,
// and returns the remaining statements supported by TiDB from `stmts`.
-func ExtractTiDBUnsupportedStmts(stmts string) ([]string, string, error) {
+func extractTiDBUnsupportedStmts(stmts string) ([]string, string, error) {
var unsupportStmts []string
var supportedStmts bytes.Buffer
// We use our bb tokenizer to help us split the multi-statements into statement list.
@@ -34,12 +37,55 @@ func ExtractTiDBUnsupportedStmts(stmts string) ([]string, string, error) {
// isTiDBUnsupportStmt returns true if this statement is unsupported in TiDB.
func isTiDBUnsupportStmt(stmt string) bool {
- if _, err := tidbparser.ParseTiDB(stmt, "", ""); err != nil {
+ if _, err := ParseTiDB(stmt, "", ""); err != nil {
return true
}
return false
}
+// ParseTiDB parses the given SQL statement and returns the AST.
+func ParseTiDB(sql string, charset string, collation string) ([]ast.StmtNode, error) {
+ p := tidbparser.New()
+
+ // To support MySQL8 window function syntax.
+ // See https://github.com/bytebase/bytebase/issues/175.
+ p.EnableWindowFunc(true)
+
+ nodes, _, err := p.Parse(sql, charset, collation)
+ if err != nil {
+ return nil, convertParserError(err)
+ }
+ return nodes, nil
+}
+
+var (
+ lineColumnRegex = regexp.MustCompile(`line (\d+) column (\d+)`)
+)
+
+func convertParserError(parserErr error) error {
+ // line 1 column 15 near "TO world;"
+ res := lineColumnRegex.FindAllStringSubmatch(parserErr.Error(), -1)
+ if len(res) != 1 {
+ return parserErr
+ }
+ if len(res[0]) != 3 {
+ return parserErr
+ }
+ line, err := strconv.Atoi(res[0][1])
+ if err != nil {
+ return parserErr
+ }
+ column, err := strconv.Atoi(res[0][2])
+ if err != nil {
+ return parserErr
+ }
+ return &base.SyntaxError{
+ Line: line,
+ Column: column,
+ Message: parserErr.Error(),
+ }
+}
+
// IsTiDBUnsupportDDLStmt checks whether the `stmt` is unsupported DDL statement in TiDB, the following statements are unsupported:
// 1. `CREATE TRIGGER`
// 2. `CREATE EVENT`
diff --git a/backend/plugin/parser/mysql/compatible_test.go b/backend/plugin/parser/mysql/compatible_test.go
index 2c997a3af2..c06ffc1171 100644
--- a/backend/plugin/parser/mysql/compatible_test.go
+++ b/backend/plugin/parser/mysql/compatible_test.go
@@ -44,7 +44,7 @@ CREATE TRIGGER order_insert_audit
}
a := require.New(t)
for _, test := range tests {
- gotUnsupport, gotSupport, err := ExtractTiDBUnsupportedStmts(test.stmts)
+ gotUnsupport, gotSupport, err := extractTiDBUnsupportedStmts(test.stmts)
if test.wantErr {
a.Error(err)
} else {
diff --git a/backend/plugin/parser/mysql/differ.go b/backend/plugin/parser/mysql/differ.go
index e64b875b15..6ff1cf7b37 100644
--- a/backend/plugin/parser/mysql/differ.go
+++ b/backend/plugin/parser/mysql/differ.go
@@ -28,7 +28,6 @@ import (
func init() {
base.RegisterSchemaDiffFunc(storepb.Engine_MYSQL, SchemaDiff)
- base.RegisterSchemaDiffFunc(storepb.Engine_TIDB, SchemaDiff)
base.RegisterSchemaDiffFunc(storepb.Engine_OCEANBASE, SchemaDiff)
}
@@ -584,7 +583,7 @@ func SchemaDiff(oldStmt, newStmt string, ignoreCaseSensitive bool) (string, erro
}
func classifyStatement(statement string) ([]string, string, error) {
- unsupported, supported, err := ExtractTiDBUnsupportedStmts(statement)
+ unsupported, supported, err := extractTiDBUnsupportedStmts(statement)
if err != nil {
return nil, "", errors.Wrapf(err, "failed to extract TiDB unsupported statements from statements %q", statement)
}
diff --git a/backend/plugin/parser/tidb/compatible.go b/backend/plugin/parser/tidb/compatible.go
new file mode 100644
index 0000000000..cb59a7b4af
--- /dev/null
+++ b/backend/plugin/parser/tidb/compatible.go
@@ -0,0 +1,70 @@
+package tidb
+
+import (
+ "bytes"
+ "fmt"
+ "regexp"
+
+ "github.com/pkg/errors"
+
+ mysqlparser "github.com/bytebase/bytebase/backend/plugin/parser/mysql"
+)
+
+// ExtractTiDBUnsupportedStmts returns a list of unsupported statements in TiDB extracted from the `stmts`,
+// and returns the remaining statements supported by TiDB from `stmts`.
+func ExtractTiDBUnsupportedStmts(stmts string) ([]string, string, error) {
+ var unsupportStmts []string
+ var supportedStmts bytes.Buffer
+ // We use our bb tokenizer to help us split the multi-statements into statement list.
+ singleSQLs, err := mysqlparser.SplitSQL(stmts)
+ if err != nil {
+ return nil, "", errors.Wrapf(err, "cannot split multi sql %q via bytebase parser", stmts)
+ }
+ for _, sql := range singleSQLs {
+ content := sql.Text
+ if isTiDBUnsupportStmt(content) {
+ unsupportStmts = append(unsupportStmts, content)
+ continue
+ }
+ _, _ = supportedStmts.WriteString(content)
+ _, _ = supportedStmts.WriteString("\n")
+ }
+ return unsupportStmts, supportedStmts.String(), nil
+}
+
+// isTiDBUnsupportStmt returns true if this statement is unsupported in TiDB.
+func isTiDBUnsupportStmt(stmt string) bool {
+ if _, err := ParseTiDB(stmt, "", ""); err != nil {
+ return true
+ }
+ return false
+}
+
+// IsTiDBUnsupportDDLStmt checks whether the `stmt` is unsupported DDL statement in TiDB, the following statements are unsupported:
+// 1. `CREATE TRIGGER`
+// 2. `CREATE EVENT`
+// 3. `CREATE FUNCTION`
+// 4. `CREATE PROCEDURE`.
+func IsTiDBUnsupportDDLStmt(stmt string) bool {
+ objects := []string{
+ "TRIGGER",
+ "EVENT",
+ "FUNCTION",
+ "PROCEDURE",
+ }
+ createRegexFmt := "(?i)^\\s*CREATE\\s+(DEFINER=(`(.)+`|(.)+)@(`(.)+`|(.)+)(\\s)+)?%s\\s+"
+ dropRegexFmt := "(?i)^\\s*DROP\\s+%s\\s+"
+ for _, obj := range objects {
+ createRegexp := fmt.Sprintf(createRegexFmt, obj)
+ re := regexp.MustCompile(createRegexp)
+ if re.MatchString(stmt) {
+ return true
+ }
+ dropRegexp := fmt.Sprintf(dropRegexFmt, obj)
+ re = regexp.MustCompile(dropRegexp)
+ if re.MatchString(stmt) {
+ return true
+ }
+ }
+ return false
+}
diff --git a/backend/plugin/parser/tidb/compatible_test.go b/backend/plugin/parser/tidb/compatible_test.go
new file mode 100644
index 0000000000..937129b18d
--- /dev/null
+++ b/backend/plugin/parser/tidb/compatible_test.go
@@ -0,0 +1,142 @@
+package tidb
+
+import (
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+func TestExtractTiDBUnsupportStmts(t *testing.T) {
+ tests := []struct {
+ stmts string
+ wantUnsupport []string
+ wantSupport string
+ wantErr bool
+ }{
+ {
+ stmts: "CREATE TABLE `actor` (\n `actor_id` smallint unsigned NOT NULL AUTO_INCREMENT,\n `first_name` varchar(45) NOT NULL,\n `last_name` varchar(45) NOT NULL,\n `last_update` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,\n PRIMARY KEY (`actor_id`),\n KEY `idx_actor_last_name` (`last_name`)\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3;",
+ wantSupport: "CREATE TABLE `actor` (\n `actor_id` smallint unsigned NOT NULL AUTO_INCREMENT,\n `first_name` varchar(45) NOT NULL,\n `last_name` varchar(45) NOT NULL,\n `last_update` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,\n PRIMARY KEY (`actor_id`),\n KEY `idx_actor_last_name` (`last_name`)\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3\n;\n",
+ wantErr: false,
+ },
+ {
+ stmts: "CREATE TABLE t1(id INT);\n" +
+ `CREATE TRIGGER order_insert_audit
+ AFTER INSERT ON orders
+ FOR EACH ROW
+ BEGIN
+ INSERT INTO orders_audit(order_id, order_date, customer_id, order_amount)
+ VALUES (NEW.order_id, NEW.order_date, NEW.customer_id, NEW.order_amount);
+ END;`,
+ wantUnsupport: []string{
+ `
+CREATE TRIGGER order_insert_audit
+ AFTER INSERT ON orders
+ FOR EACH ROW
+ BEGIN
+ INSERT INTO orders_audit(order_id, order_date, customer_id, order_amount)
+ VALUES (NEW.order_id, NEW.order_date, NEW.customer_id, NEW.order_amount);
+ END
+;`,
+ },
+ wantSupport: "CREATE TABLE t1(id INT);\n",
+ wantErr: false,
+ },
+ }
+ a := require.New(t)
+ for _, test := range tests {
+ gotUnsupport, gotSupport, err := ExtractTiDBUnsupportedStmts(test.stmts)
+ if test.wantErr {
+ a.Error(err)
+ } else {
+ a.NoError(err)
+ a.Equal(test.wantUnsupport, gotUnsupport)
+ a.Equal(test.wantSupport, gotSupport)
+ }
+ }
+}
+
+func TestIsTiDBUnsupportStmt(t *testing.T) {
+ tests := []struct {
+ stmt string
+ want bool
+ }{
+ {
+ stmt: "DELIMITER ;;",
+ want: true,
+ },
+ {
+ stmt: "delimiter ;;",
+ want: true,
+ },
+ {
+ stmt: "CREATE DEFINER=`root`@`%` TRIGGER `ins_sum` BEFORE INSERT ON `account` FOR EACH SET @sum=@sum + NEW.price;;",
+ want: true,
+ },
+ {
+ stmt: "create trigger `ins_sum` BEFORE INSERT ON `account` FOR EACH SET @sum=@sum + NEW.price;;",
+ want: true,
+ },
+ {
+ stmt: "DROP TRIGGER `ins_sum`;",
+ want: true,
+ },
+ {
+ stmt: "DROP TRIGGER IF EXISTS `ins_sum`;",
+ want: true,
+ },
+ {
+ stmt: "CREATE TABLE t1(id INT, name VARCHAR(50));",
+ want: false,
+ },
+ {
+ stmt: "CREATE DEFINER=`root`@`%` PROCEDURE `citycount` (IN `country` CHAR(3), OUT `cities` INT)\n" +
+ "BEGIN\n" +
+ " SELECT COUNT(*) INTO cities FROM world.city\n" +
+ "WHERE CountryCode = country;\n" +
+ "END//",
+ want: true,
+ },
+ {
+ stmt: "create procedure `citycount` (IN `country` CHAR(3), OUT `cities` INT)\n" +
+ "BEGIN\n" +
+ " SELECT COUNT(*) INTO cities FROM world.city\n" +
+ "WHERE CountryCode = country;\n" +
+ "END//",
+ want: true,
+ },
+ {
+ stmt: "CREATE DEFINER=`root`@`%` FUNCTION `hello`(s CHAR(20)) RETURNS CHAR(50) DETERMINISTIC\n" +
+ "RETURN CONCAT('Hello, ',s,'!');",
+ want: true,
+ },
+ {
+ stmt: "CREATE DEFINER=root@%% FUNCTION `hello`(s CHAR(20)) RETURNS CHAR(50) DETERMINISTIC\n" +
+ "RETURN CONCAT('Hello, ',s,'!');",
+ want: true,
+ },
+ {
+ stmt: "create function `hello` (s CHAR(20)) RETURNS CHAR(50) DETERMINISTIC\n" +
+ "RETURN CONCAT('Hello, ',s,'!');",
+ want: true,
+ },
+ {
+ stmt: "CREATE DEFINER=`root`@`%` EVENT `test_event_01` ON SCHEDULE AT CURRENT_TIMESTAMP \n" +
+ "DO\n" +
+ " INSERT INTO message(message, created_at)\n" +
+ " VALUES('test event', NOW());",
+ want: true,
+ },
+ {
+ stmt: "create event `test_event_01` ON SCHEDULE AT CURRENT_TIMESTAMP \n" +
+ "DO\n" +
+ " INSERT INTO message(message, created_at)\n" +
+ " VALUES('test event', NOW());",
+ want: true,
+ },
+ }
+ a := require.New(t)
+ for _, test := range tests {
+ got := isTiDBUnsupportStmt(test.stmt)
+ a.Equalf(test.want, got, "statement: %s\n", test.stmt)
+ }
+}
diff --git a/backend/plugin/parser/tidb/differ.go b/backend/plugin/parser/tidb/differ.go
new file mode 100644
index 0000000000..068eb6633d
--- /dev/null
+++ b/backend/plugin/parser/tidb/differ.go
@@ -0,0 +1,1594 @@
+package tidb
+
+import (
+ "bytes"
+ "fmt"
+ "io"
+ "log/slog"
+ "regexp"
+ "sort"
+ "strings"
+
+ "github.com/bytebase/bytebase/backend/common/log"
+
+ "github.com/pingcap/tidb/parser"
+ "github.com/pingcap/tidb/parser/ast"
+ "github.com/pingcap/tidb/parser/format"
+ "github.com/pingcap/tidb/parser/model"
+ "github.com/pingcap/tidb/parser/mysql"
+ "github.com/pingcap/tidb/types"
+ "github.com/pkg/errors"
+
+ "github.com/bytebase/bytebase/backend/plugin/parser/base"
+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"
+
+ // Register pingcap parser driver.
+ driver "github.com/pingcap/tidb/types/parser_driver"
+)
+
+func init() {
+ base.RegisterSchemaDiffFunc(storepb.Engine_TIDB, SchemaDiff)
+}
+
+const (
+ disableFKCheckStmt string = "SET FOREIGN_KEY_CHECKS=0;\n\n"
+ enableFKCheckStmt string = "SET FOREIGN_KEY_CHECKS=1;\n"
+)
+
+// 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 {
+ // Ignore the case sensitive when comparing the table and view names.
+ ignoreCaseSensitive bool
+
+ dropUnsupportedStatement []string
+ dropForeignKeyList []ast.Node
+ dropConstraintExceptFkList []ast.Node
+ dropIndexList []ast.Node
+ dropViewList []ast.Node
+ dropTableList []ast.Node
+
+ createTableList []ast.Node
+ alterTableOptionList []ast.Node
+ addAndModifyColumnList []ast.Node
+ dropColumnList []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.
+ oldUnsupportedMap, err := buildUnsupportedObjectMap(oldUnsupportedStmtList)
+ if err != nil {
+ return err
+ }
+ newUnsupportedMap, err := buildUnsupportedObjectMap(newUnsupportedStmtList)
+ if err != nil {
+ return err
+ }
+ for tp, objects := range newUnsupportedMap {
+ for newName, newStmt := range objects {
+ if oldStmt, ok := oldUnsupportedMap[tp][newName]; ok {
+ if strings.Compare(oldStmt, newStmt) != 0 {
+ // 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
+ diff.inPlaceDropUnsupportedStatement = append(diff.inPlaceDropUnsupportedStatement, fmt.Sprintf("DROP %s IF EXISTS `%s`;", tp, newName))
+ diff.inPlaceAddUnsupportedStatement = append(diff.inPlaceAddUnsupportedStatement, newStmt)
+ }
+ delete(oldUnsupportedMap[tp], newName)
+ continue
+ }
+ // 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)
+ diff.createUnsupportedStatement = append(diff.createUnsupportedStatement, delimiterNewStmt)
+ }
+ }
+ // drop remaining TiDB unsupported objects
+ for tp, objects := range oldUnsupportedMap {
+ for name := range objects {
+ 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 := diff.buildSchemaInfo(oldNodeList)
+ if err != nil {
+ return err
+ }
+ newSchemaInfo, err := diff.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)
+ }
+ }
+
+ if err := diff.diffView(oldSchemaInfo.viewMap, newSchemaInfo.viewMap, newViewList); err != nil {
+ return errors.Wrapf(err, "failed to diff view")
+ }
+
+ return nil
+}
+
+func (diff *diffNode) diffView(oldViewMap viewMap, newViewMap viewMap, newViewList []*ast.CreateViewStmt) error {
+ var tempViewList []ast.Node
+ var viewList []ast.Node
+ for _, view := range newViewList {
+ viewName := view.ViewName.Name.O
+ if diff.ignoreCaseSensitive {
+ viewName = view.ViewName.Name.L
+ }
+ if newNode, ok := newViewMap[viewName]; ok {
+ if !diff.isViewEqual(view, newNode) {
+ // Skip predefined view such as the temporary view from mysqldump.
+ continue
+ }
+ }
+ oldNode, ok := oldViewMap[viewName]
+ if ok {
+ if !diff.isViewEqual(view, oldNode) {
+ createViewStmt := *view
+ createViewStmt.OrReplace = true
+ viewList = append(viewList, &createViewStmt)
+ }
+ // We should delete the view in the oldViewMap, because we will drop the all views in the oldViewMap explicitly at last.
+ delete(oldViewMap, viewName)
+ } else {
+ // We should create the view.
+ // We create the temporary view first and replace it to avoid break the dependency like mysqldump does.
+ tempViewStmt, err := getTempView(view)
+ if err != nil {
+ return errors.Wrapf(err, "failed to get temporary view for view %s", view.ViewName.Name.O)
+ }
+ tempViewList = append(tempViewList, tempViewStmt)
+ createViewStmt := *view
+ createViewStmt.OrReplace = true
+ viewList = append(viewList, &createViewStmt)
+ }
+ }
+ diff.createTempViewList = append(diff.createTempViewList, tempViewList...)
+ diff.createViewList = append(diff.createViewList, viewList...)
+
+ // Remove the remaining views in the oldViewMap.
+ dropViewStmt := &ast.DropTableStmt{
+ IsView: true,
+ }
+ for _, oldView := range oldViewMap {
+ dropViewStmt.Tables = append(dropViewStmt.Tables, oldView.ViewName)
+ }
+ if len(dropViewStmt.Tables) > 0 {
+ diff.dropViewList = append(diff.dropViewList, dropViewStmt)
+ }
+ return nil
+}
+
+func (diff *diffNode) diffTable(oldTable, newTable *tableInfo) {
+ diff.diffTableOption(oldTable, newTable)
+ diff.diffColumn(oldTable, newTable)
+ diff.diffIndex(oldTable, newTable)
+ diff.diffConstraint(oldTable, newTable)
+}
+
+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[strings.ToLower(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, strings.ToLower(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[strings.ToLower(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, strings.ToLower(constraint.Name))
+ continue
+ }
+ diff.addConstraintExceptFkList = append(diff.addConstraintExceptFkList, &ast.AlterTableStmt{
+ Table: newTable.createTable.Table,
+ Specs: []*ast.AlterTableSpec{
+ {
+ Tp: ast.AlterTableAddConstraint,
+ Constraint: constraint,
+ },
+ },
+ })
+ }
+ }
+
+ if oldPrimaryKey != nil {
+ diff.dropConstraintExceptFkList = append(diff.dropConstraintExceptFkList, &ast.AlterTableStmt{
+ Table: newTable.createTable.Table,
+ Specs: []*ast.AlterTableSpec{
+ {
+ Tp: ast.AlterTableDropPrimaryKey,
+ },
+ },
+ })
+ }
+
+ 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,
+ },
+ },
+ })
+ }
+ }
+}
+
+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: oldIndex.createIndex.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 _, oldIndex := range oldTable.indexMap {
+ diff.dropIndexList = append(diff.dropIndexList, &ast.DropIndexStmt{
+ IndexName: oldIndex.createIndex.IndexName,
+ Table: oldIndex.createIndex.Table,
+ })
+ }
+}
+
+func (diff *diffNode) diffColumn(oldTable, newTable *tableInfo) {
+ // We use a single ALTER TABLE statement to add and modify columns,
+ // because we need to maintain a fixed order of these two operations.
+ // This approach ensures that we can manipulate the column position as needed.
+ addAndModifyColumnStatement := &ast.AlterTableStmt{Table: newTable.createTable.Table}
+
+ oldColumnMap := buildColumnMap(oldTable.createTable.Cols)
+ oldColumnPositionMap := buildColumnPositionMap(oldTable.createTable)
+ for idx, columnDef := range newTable.createTable.Cols {
+ // Column names are always case insensitive.
+ newColumnName := columnDef.Name.Name.L
+ 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)}
+ }
+ addAndModifyColumnStatement.Specs = append(addAndModifyColumnStatement.Specs, &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(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 {
+ addAndModifyColumnStatement.Specs = append(addAndModifyColumnStatement.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 {
+ diff.dropColumnList = append(diff.dropColumnList, &ast.AlterTableStmt{
+ Table: newTable.createTable.Table,
+ Specs: []*ast.AlterTableSpec{
+ {
+ Tp: ast.AlterTableDropColumn,
+ OldColumnName: &ast.ColumnName{
+ Name: model.NewCIStr(columnDef.Name.Name.O),
+ },
+ },
+ },
+ })
+ }
+
+ if len(addAndModifyColumnStatement.Specs) > 0 {
+ diff.addAndModifyColumnList = append(diff.addAndModifyColumnList, addAndModifyColumnStatement)
+ }
+}
+
+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)
+ }
+}
+
+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 := sortAndWriteNodeList(&buf, diff.dropForeignKeyList, flag); err != nil {
+ return "", err
+ }
+ if err := sortAndWriteNodeList(&buf, diff.dropConstraintExceptFkList, flag); 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.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.addAndModifyColumnList, flag); err != nil {
+ return "", err
+ }
+ if err := sortAndWriteNodeList(&buf, diff.dropColumnList, 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 := buf.WriteString("\n\n"); err != nil {
+ return "", err
+ }
+ }
+
+ 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
+}
+
+// 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 SchemaDiff(oldStmt, newStmt string, ignoreCaseSensitive bool) (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
+ }
+ newUnsupportedStmtList, newSupportedStmt, err := classifyStatement(newStmt)
+ if err != nil {
+ return "", err
+ }
+
+ diff := &diffNode{
+ ignoreCaseSensitive: ignoreCaseSensitive,
+ }
+ if err := diff.diffSupportedStatement(oldSupportedStmt, newSupportedStmt); err != nil {
+ return "", err
+ }
+ if err := diff.diffUnsupportedStatement(oldUnsupportedStmtList, newUnsupportedStmtList); err != nil {
+ return "", err
+ }
+
+ return diff.deparse()
+}
+
+func classifyStatement(statement string) ([]string, string, error) {
+ unsupported, supported, err := ExtractTiDBUnsupportedStmts(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 !IsDelimiter(stmt) {
+ afterFilter = append(afterFilter, stmt)
+ }
+ }
+ return afterFilter, supported, nil
+}
+
+// IsDelimiter returns true if the statement is a delimiter statement.
+func IsDelimiter(stmt string) bool {
+ delimiterRegex := `(?i)^\s*DELIMITER\s+`
+ re := regexp.MustCompile(delimiterRegex)
+ return re.MatchString(stmt)
+}
+
+func writeNodeStatement(w io.Writer, n ast.Node, flags format.RestoreFlags) error {
+ restoreCtx := format.NewRestoreCtx(flags, w)
+ if err := n.Restore(restoreCtx); err != nil {
+ return err
+ }
+ if _, err := w.Write([]byte(";\n\n")); err != nil {
+ return err
+ }
+ return nil
+}
+
+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)
+ }
+ }
+ 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
+}
+
+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[strings.ToLower(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[strings.ToLower(constraint.Name)] = newIndexInfo(createIndex)
+ } else {
+ newConstraintList = append(newConstraintList, constraint)
+ }
+ }
+ createTable.Constraints = newConstraintList
+
+ return result, nil
+}
+
+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 (diff *diffNode) buildSchemaInfo(nodes []ast.StmtNode) (*schemaInfo, error) {
+ result := &schemaInfo{
+ tableMap: make(tableMap),
+ viewMap: make(viewMap),
+ }
+ for _, node := range nodes {
+ switch stmt := node.(type) {
+ case *ast.CreateTableStmt:
+ var err error
+ tableName := stmt.Table.Name.O
+ if diff.ignoreCaseSensitive {
+ tableName = stmt.Table.Name.L
+ }
+ if result.tableMap[tableName], err = newTableInfo(stmt); err != nil {
+ return nil, err
+ }
+ case *ast.CreateIndexStmt:
+ tableName := stmt.Table.Name.O
+ if diff.ignoreCaseSensitive {
+ tableName = stmt.Table.Name.L
+ }
+ table, exists := result.tableMap[tableName]
+ if !exists {
+ return nil, errors.Errorf("Try to create index `%s` on table `%s`, but table not found", stmt.IndexName, stmt.Table.Name.String())
+ }
+ // Index names are always case insensitive
+ if _, exists := table.indexMap[strings.ToLower(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[strings.ToLower(stmt.IndexName)] = newIndexInfo(stmt)
+ case *ast.CreateViewStmt:
+ viewName := stmt.ViewName.Name.O
+ if diff.ignoreCaseSensitive {
+ viewName = stmt.ViewName.Name.L
+ }
+ result.viewMap[viewName] = stmt
+ default:
+ }
+ }
+ return result, nil
+}
+
+// buildUnsupportedObjectMap builds map for trigger, function, procedure, event to correspond create object string statements.
+func buildUnsupportedObjectMap(stmts []string) (map[objectType]map[string]string, error) {
+ m := make(map[objectType]map[string]string)
+ m[trigger] = make(map[string]string)
+ m[function] = make(map[string]string)
+ m[procedure] = make(map[string]string)
+ m[event] = make(map[string]string)
+ for _, stmt := range stmts {
+ objName, objType, err := extractUnsupportedObjectNameAndType(stmt)
+ if err != nil {
+ return nil, err
+ }
+ m[objType][objName] = stmt
+ }
+ return m, nil
+}
+
+// getTempView returns the temporary view name and the create statement.
+func getTempView(stmt *ast.CreateViewStmt) (*ast.CreateViewStmt, error) {
+ // We create the temp view similar to what mysqldump does.
+ // Create a temporary view with the same name as the view. Its columns should
+ // have the same name in order to satisfy views that depend on this view.
+ // This temporary view will be removed when the actual view is created.
+ // The column properties are unnecessary and not preserved in this temporary view.
+ // because other views only need to reference the column name.
+ // Example: SELECT 1 AS colName1, 1 AS colName2.
+ // TODO(zp): support SDL for GitOps.
+ var selectFields []*ast.SelectField
+ // mysqldump always show field list
+ if len(stmt.Cols) > 0 {
+ for _, col := range stmt.Cols {
+ selectFields = append(selectFields, &ast.SelectField{
+ Expr: &driver.ValueExpr{
+ Datum: types.NewDatum(1),
+ },
+ AsName: col,
+ })
+ }
+ } else {
+ colName, err := extractColNameFromSelectListClauseOfCreateViewStmt(stmt.Select)
+ if err != nil {
+ return nil, errors.Wrapf(err, "failed to extract column name from select list clause of create view statement")
+ }
+ for _, name := range colName {
+ selectFields = append(selectFields, &ast.SelectField{
+ Expr: &driver.ValueExpr{
+ Datum: types.NewDatum(1),
+ },
+ AsName: model.NewCIStr(name),
+ })
+ }
+ }
+
+ return &ast.CreateViewStmt{
+ ViewName: stmt.ViewName,
+ Select: &ast.SelectStmt{
+ SelectStmtOpts: &ast.SelectStmtOpts{
+ // Avoid generating SQL_NO_CACHE
+ // https://sourcegraph.com/github.com/pingcap/tidb/-/blob/parser/ast/dml.go?L1234
+ SQLCache: true,
+ },
+ Fields: &ast.FieldList{
+ Fields: selectFields,
+ },
+ },
+ OrReplace: true,
+ // Avoid nil pointer dereference panic.
+ // https://sourcegraph.com/github.com/pingcap/tidb/-/blob/parser/ast/ddl.go?L1398
+ Definer: stmt.Definer,
+ Security: stmt.Security,
+ CheckOption: model.CheckOptionCascaded,
+ }, nil
+}
+
+// extractColNameFromCreateViewStmt extracts column names from create view statement.
+// For example, CREATE OR REPLACE VIEW `v` AS select `d` as `c` WILL return `c`.
+func extractColNameFromSelectListClauseOfCreateViewStmt(stmt ast.Node) ([]string, error) {
+ var result []string
+ switch stmt := (stmt).(type) {
+ case *ast.SelectStmt:
+ for _, field := range stmt.Fields.Fields {
+ if field.WildCard != nil {
+ return nil, errors.New("wildcard(*) is not supported now in select statement")
+ }
+ var fieldName string
+ if field.AsName.O != "" {
+ fieldName = field.AsName.O
+ } else {
+ fieldName = field.Expr.(*ast.ColumnNameExpr).Name.Name.O
+ }
+ result = append(result, fieldName)
+ }
+ return result, nil
+ case *ast.SetOprStmt:
+ // For SetOprStmt, we focus on the first select statement, for example:
+ // with `tt` as (select `t1`.`id` AS `id` from `t1` union select `t2`.`id2` AS `id2` from `t2`) select `tt`.`id` AS `id` from `tt` union select `t1`.`id` AS `id` from `t1`
+ // we just focus on select `tt`.`id` as `id` from `tt`.
+ if len(stmt.SelectList.Selects) == 0 {
+ return nil, errors.New("select list in SetOprStmt is empty")
+ }
+ return extractColNameFromSelectListClauseOfCreateViewStmt(stmt.SelectList.Selects[0])
+ case *ast.SetOprSelectList:
+ if len(stmt.Selects) == 0 {
+ return nil, errors.New("select list in SetOprSelectList is empty")
+ }
+ return extractColNameFromSelectListClauseOfCreateViewStmt(stmt.Selects[0])
+ default:
+ stmtStr, err := toString(stmt)
+ if err != nil {
+ return nil, errors.Wrapf(err, "failed to convert create view statement to string")
+ }
+ return nil, errors.Errorf("unsupported create view statement %q which select is not supported node", stmtStr)
+ }
+}
+
+// buildColumnMap returns a map of column name to column definition on a given table.
+func buildColumnMap(columnList []*ast.ColumnDef) map[string]*ast.ColumnDef {
+ oldColumnMap := make(map[string]*ast.ColumnDef)
+ for _, columnDef := range columnList {
+ // Column names are always case insensitive.
+ oldColumnMap[columnDef.Name.Name.L] = columnDef
+ }
+ return oldColumnMap
+}
+
+// buildColumnPositionMap returns a map of column name to column position.
+func buildColumnPositionMap(stmt *ast.CreateTableStmt) map[string]int {
+ m := make(map[string]int)
+ for i, col := range stmt.Cols {
+ // Column names are always case insensitive.
+ m[col.Name.Name.L] = i
+ }
+ return m
+}
+
+func buildConstraintMap(stmt *ast.CreateTableStmt) (*ast.Constraint, constraintMap) {
+ var primaryKey *ast.Constraint
+ constraintMap := make(constraintMap)
+ for _, constraint := range stmt.Constraints {
+ switch constraint.Tp {
+ case ast.ConstraintForeignKey, ast.ConstraintCheck:
+ constraintMap[strings.ToLower(constraint.Name)] = constraint
+ case ast.ConstraintPrimaryKey:
+ primaryKey = constraint
+ default:
+ }
+ }
+ return primaryKey, constraintMap
+}
+
+// isColumnEqual returns true if definitions of two columns with the same name are the same.
+func isColumnEqual(old, new *ast.ColumnDef) bool {
+ if !isColumnTypesEqual(old, new) {
+ return false
+ }
+ if !isColumnOptionsEqual(old.Options, new.Options) {
+ return false
+ }
+ return true
+}
+
+func isColumnTypesEqual(old, new *ast.ColumnDef) bool {
+ return old.Tp.String() == new.Tp.String()
+}
+
+func isColumnOptionsEqual(old, new []*ast.ColumnOption) bool {
+ oldCollate, oldNormalizeOptions := normalizeColumnOptions(old)
+ newCollate, newNormalizeOptions := normalizeColumnOptions(new)
+ if len(oldNormalizeOptions) != len(newNormalizeOptions) {
+ return false
+ }
+ if newCollate != nil {
+ if oldCollate == nil {
+ return false
+ }
+ if oldCollate.StrValue != newCollate.StrValue {
+ return false
+ }
+ }
+ for idx, oldOption := range oldNormalizeOptions {
+ oldOptionStr, err := toString(oldOption)
+ if err != nil {
+ slog.Error("failed to convert old column option to string", log.BBError(err))
+ return false
+ }
+ newOption := newNormalizeOptions[idx]
+ newOptionStr, err := toString(newOption)
+ if err != nil {
+ slog.Error("failed to convert new column option to string", log.BBError(err))
+ return false
+ }
+ if oldOptionStr != newOptionStr {
+ return false
+ }
+ }
+ return true
+}
+
+// normalizeColumnOptions normalizes the column options.
+// It skips the NULL option, NO option and then order the options by OptionType.
+func normalizeColumnOptions(options []*ast.ColumnOption) (*ast.ColumnOption, []*ast.ColumnOption) {
+ var retOptions []*ast.ColumnOption
+ var collateOption *ast.ColumnOption
+ for _, option := range options {
+ switch option.Tp {
+ case ast.ColumnOptionCollate:
+ collateOption = option
+ continue
+ case ast.ColumnOptionNull:
+ continue
+ case ast.ColumnOptionNoOption:
+ continue
+ case ast.ColumnOptionDefaultValue:
+ if option.Expr.GetType().GetType() == mysql.TypeNull {
+ continue
+ }
+ }
+ retOptions = append(retOptions, option)
+ }
+ sort.Slice(retOptions, func(i, j int) bool {
+ return retOptions[i].Tp < retOptions[j].Tp
+ })
+ return collateOption, retOptions
+}
+
+// isIndexEqual returns true if definitions of two indexes are the same.
+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] ...
+
+ // MySQL index names are case insensitive.
+ if !strings.EqualFold(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 false
+ }
+ if (old.Option == nil) != (new.Option == nil) {
+ return false
+ }
+ if old.Option != nil && new.Option != nil {
+ if old.Option.Tp != new.Option.Tp {
+ return false
+ }
+ }
+
+ if !isKeyPartEqual(old.Keys, new.Keys) {
+ return false
+ }
+ if !isIndexOptionEqual(old.Option, new.Option) {
+ return false
+ }
+ return true
+}
+
+// isKeyPartEqual returns true if two key parts are the same.
+func isKeyPartEqual(old, new []*ast.IndexPartSpecification) bool {
+ if len(old) != len(new) {
+ return false
+ }
+ // key_part: {col_name [(length)] | (expr)} [ASC | DESC]
+ for idx, oldKeyPart := range old {
+ newKeyPart := new[idx]
+ if (oldKeyPart.Column == nil) != (newKeyPart.Column == nil) {
+ return false
+ }
+ if oldKeyPart.Column != nil && newKeyPart.Column != nil {
+ if oldKeyPart.Column.Name.String() != newKeyPart.Column.Name.String() {
+ return false
+ }
+ if oldKeyPart.Length != newKeyPart.Length {
+ return false
+ }
+ }
+ if (oldKeyPart.Expr == nil) != (newKeyPart.Expr == nil) {
+ // if the key part uses expression instead of column name, the expression node is nil.
+ return false
+ }
+ if oldKeyPart.Expr != nil && newKeyPart.Expr != nil {
+ oldKeyPartStr, err := toString(oldKeyPart.Expr)
+ if err != nil {
+ slog.Error("failed to convert old key part to string", log.BBError(err))
+ return false
+ }
+ newKeyPartStr, err := toString(newKeyPart.Expr)
+ if err != nil {
+ slog.Error("failed to convert new key part to string", log.BBError(err))
+ return false
+ }
+ return oldKeyPartStr == newKeyPartStr
+ }
+ if oldKeyPart.Desc != newKeyPart.Desc {
+ return false
+ }
+ // TODO(zp): TiDB MySQL parser doesn't record the index order field in go struct, but it can parse correctly.
+ // https://sourcegraph.com/github.com/pingcap/tidb/-/blob/parser/parser.y?L3688
+ // We can support the index order until we implement the parser by ourself or https://github.com/pingcap/tidb/pull/38137 is merged.
+ }
+ return true
+}
+
+// isIndexOptionEqual returns true if two index options are the same.
+func isIndexOptionEqual(old, new *ast.IndexOption) bool {
+ // index_option: {
+ // KEY_BLOCK_SIZE [=] value
+ // | index_type
+ // | WITH PARSER parser_name
+ // | COMMENT 'string'
+ // | {VISIBLE | INVISIBLE}
+ // |ENGINE_ATTRIBUTE [=] 'string'
+ // |SECONDARY_ENGINE_ATTRIBUTE [=] 'string'
+ // }
+ if (old == nil) != (new == nil) {
+ return false
+ }
+ if old == nil && new == nil {
+ return true
+ }
+ if old.KeyBlockSize != new.KeyBlockSize {
+ return false
+ }
+ if old.Tp != new.Tp {
+ return false
+ }
+ if old.ParserName.O != new.ParserName.O {
+ return false
+ }
+ if old.Comment != new.Comment {
+ return false
+ }
+ if old.Visibility != new.Visibility {
+ return false
+ }
+ // TODO(zp): support ENGINE_ATTRIBUTE and SECONDARY_ENGINE_ATTRIBUTE.
+ return true
+}
+
+// isForeignKeyEqual returns true if two foreign keys are the same.
+func isForeignKeyConstraintEqual(old, new *ast.Constraint) bool {
+ // FOREIGN KEY [index_name] (index_col_name,...) reference_definition
+ if !strings.EqualFold(old.Name, new.Name) {
+ return false
+ }
+ if !isKeyPartEqual(old.Keys, new.Keys) {
+ return false
+ }
+ if !isReferenceDefinitionEqual(old.Refer, new.Refer) {
+ return false
+ }
+ return true
+}
+
+// isReferenceDefinitionEqual returns true if two reference definitions are the same.
+func isReferenceDefinitionEqual(old, new *ast.ReferenceDef) bool {
+ // reference_definition:
+ // REFERENCES tbl_name (index_col_name,...)
+ // [MATCH FULL | MATCH PARTIAL | MATCH SIMPLE]
+ // [ON DELETE reference_option]
+ // [ON UPDATE reference_option]
+ if old.Table.Name.String() != new.Table.Name.String() {
+ return false
+ }
+
+ if len(old.IndexPartSpecifications) != len(new.IndexPartSpecifications) {
+ return false
+ }
+ for idx, oldIndexColName := range old.IndexPartSpecifications {
+ newIndexColName := new.IndexPartSpecifications[idx]
+ if oldIndexColName.Column.Name.String() != newIndexColName.Column.Name.String() {
+ return false
+ }
+ }
+
+ if old.Match != new.Match {
+ return false
+ }
+
+ if (old.OnDelete == nil) != (new.OnDelete == nil) {
+ return false
+ }
+ if old.OnDelete != nil && new.OnDelete != nil && old.OnDelete.ReferOpt != new.OnDelete.ReferOpt {
+ return false
+ }
+
+ if (old.OnUpdate == nil) != (new.OnUpdate == nil) {
+ return false
+ }
+ if old.OnUpdate != nil && new.OnUpdate != nil && old.OnUpdate.ReferOpt != new.OnUpdate.ReferOpt {
+ return false
+ }
+ return true
+}
+
+// trimParentheses trims outer parentheses.
+func trimParentheses(expr ast.ExprNode) ast.ExprNode {
+ result := expr
+ for {
+ if node, yes := result.(*ast.ParenthesesExpr); yes {
+ result = node.Expr
+ } else {
+ break
+ }
+ }
+ return result
+}
+
+// isCheckConstraintEqual returns true if two check constraints are the same.
+func isCheckConstraintEqual(old, new *ast.Constraint) bool {
+ // check_constraint_definition:
+ // [CONSTRAINT [symbol]] CHECK (expr) [[NOT] ENFORCED]
+ if !strings.EqualFold(old.Name, new.Name) {
+ return false
+ }
+
+ if old.Enforced != new.Enforced {
+ return false
+ }
+
+ oldExpr, err := toString(trimParentheses(old.Expr))
+ if err != nil {
+ slog.Error("failed to convert old check constraint expression to string", log.BBError(err))
+ return false
+ }
+ newExpr, err := toString(trimParentheses(new.Expr))
+ if err != nil {
+ slog.Error("failed to convert new check constraint expression to string", log.BBError(err))
+ return false
+ }
+ return oldExpr == newExpr
+}
+
+// diffTableOptions returns the diff of two table options, returns nil if they are the same.
+func diffTableOptions(tableName *ast.TableName, old, new []*ast.TableOption) *ast.AlterTableStmt {
+ // https://dev.mysql.com/doc/refman/8.0/en/create-table.html
+ // table_option: {
+ // AUTOEXTEND_SIZE [=] value
+ // | AUTO_INCREMENT [=] value
+ // | AVG_ROW_LENGTH [=] value
+ // | [DEFAULT] CHARACTER SET [=] charset_name
+ // | CHECKSUM [=] {0 | 1}
+ // | [DEFAULT] COLLATE [=] collation_name
+ // | COMMENT [=] 'string'
+ // | COMPRESSION [=] {'ZLIB' | 'LZ4' | 'NONE'}
+ // | CONNECTION [=] 'connect_string'
+ // | {DATA | INDEX} DIRECTORY [=] 'absolute path to directory'
+ // | DELAY_KEY_WRITE [=] {0 | 1}
+ // | ENCRYPTION [=] {'Y' | 'N'}
+ // | ENGINE [=] engine_name
+ // | ENGINE_ATTRIBUTE [=] 'string'
+ // | INSERT_METHOD [=] { NO | FIRST | LAST }
+ // | KEY_BLOCK_SIZE [=] value
+ // | MAX_ROWS [=] value
+ // | MIN_ROWS [=] value
+ // | PACK_KEYS [=] {0 | 1 | DEFAULT}
+ // | PASSWORD [=] 'string'
+ // | ROW_FORMAT [=] {DEFAULT | DYNAMIC | FIXED | COMPRESSED | REDUNDANT | COMPACT}
+ // | START TRANSACTION // This is an internal-use table option.
+ // // It was introduced in MySQL 8.0.21 to permit CREATE TABLE ... SELECT to be logged as a single,
+ // // atomic transaction in the binary log when using row-based replication with a storage engine that supports atomic DDL.
+ // | SECONDARY_ENGINE_ATTRIBUTE [=] 'string'
+ // | STATS_AUTO_RECALC [=] {DEFAULT | 0 | 1}
+ // | STATS_PERSISTENT [=] {DEFAULT | 0 | 1}
+ // | STATS_SAMPLE_PAGES [=] value
+ // | TABLESPACE tablespace_name [STORAGE {DISK | MEMORY}]
+ // | UNION [=] (tbl_name[,tbl_name]...)
+ // }
+
+ // We use map to record the table options, so we can easily find the difference.
+ oldOptionsMap := buildTableOptionMap(old)
+ newOptionsMap := buildTableOptionMap(new)
+
+ var options []*ast.TableOption
+ for oldTp, oldOption := range oldOptionsMap {
+ newOption, ok := newOptionsMap[oldTp]
+ if !ok {
+ switch oldOption.Tp {
+ // For table engine, table charset and table collation, if oldTable has but newTable doesn't,
+ // we skip drop them.
+ case ast.TableOptionEngine, ast.TableOptionCharset, ast.TableOptionCollate:
+ continue
+ }
+ // We should drop the table option if it doesn't exist in the new table options.
+ if astOption := dropTableOption(oldOption); astOption != nil {
+ options = append(options, astOption)
+ }
+ continue
+ }
+ if !isTableOptionValEqual(oldOption, newOption) {
+ options = append(options, newOption)
+ }
+ }
+ // We should add the table option if it doesn't exist in the old table options.
+ for newTp, newOption := range newOptionsMap {
+ if _, ok := oldOptionsMap[newTp]; !ok {
+ // We should add the table option if it doesn't exist in the old table options.
+ options = append(options, newOption)
+ }
+ }
+ if len(options) == 0 {
+ return nil
+ }
+ return &ast.AlterTableStmt{
+ Table: tableName,
+ Specs: []*ast.AlterTableSpec{
+ {
+ Tp: ast.AlterTableOption,
+ Options: options,
+ },
+ },
+ }
+}
+
+// dropTableOption generate the table options node need to oppended to the ALTER TABLE OPTION spec.
+func dropTableOption(option *ast.TableOption) *ast.TableOption {
+ switch option.Tp {
+ case ast.TableOptionAutoIncrement:
+ // You cannot reset the counter to a value less than or equal to the value that is currently in use.
+ // For both InnoDB and MyISAM, if the value is less than or equal to the maximum value currently in the AUTO_INCREMENT column,
+ // the value is reset to the current maximum AUTO_INCREMENT column value plus one.
+ // https://dev.mysql.com/doc/refman/8.0/en/alter-table.html
+ // So we always set the auto_increment value to 0, it will be reset to the current maximum AUTO_INCREMENT column value plus one.
+ return &ast.TableOption{
+ Tp: ast.TableOptionAutoIncrement,
+ UintValue: 0,
+ }
+ case ast.TableOptionAvgRowLength:
+ // AVG_ROW_LENGTH only works in MyISAM tables.
+ return &ast.TableOption{
+ Tp: ast.TableOptionAvgRowLength,
+ UintValue: 0,
+ }
+ case ast.TableOptionCharset:
+ // TODO(zp): we use utf8mb4 as the default charset, but it's not always true. We should consider the database default charset.
+ defaultCharset := "utf8mb4"
+ if option.StrValue == defaultCharset {
+ return nil
+ }
+ return &ast.TableOption{
+ Tp: ast.TableOptionCharset,
+ StrValue: defaultCharset,
+ }
+ case ast.TableOptionCollate:
+ // TODO(zp): default collate is related with the charset.
+ defaultCollate := "utf8mb4_general_ci"
+ if option.StrValue == defaultCollate {
+ return nil
+ }
+ return &ast.TableOption{
+ Tp: ast.TableOptionCollate,
+ StrValue: defaultCollate,
+ }
+ case ast.TableOptionCheckSum:
+ return &ast.TableOption{
+ Tp: ast.TableOptionCheckSum,
+ UintValue: 0,
+ }
+ case ast.TableOptionComment:
+ // Set to "" to remove the comment.
+ return &ast.TableOption{
+ Tp: ast.TableOptionComment,
+ }
+ case ast.TableOptionCompression:
+ // TODO(zp): handle the compression
+ case ast.TableOptionConnection:
+ // Set to "" to remove the connection.
+ return &ast.TableOption{
+ Tp: ast.TableOptionConnection,
+ }
+ case ast.TableOptionDataDirectory:
+ case ast.TableOptionIndexDirectory:
+ // TODO(zp): handle the default data directory and index directory, there are a lot of situations we need to consider.
+ // 1. Data Directory and Index Directory will be ignored on Windows.
+ // 2. For a normal table, data directory and index directory cannot changed after the table is created, but for a partition table, it can be changed by USING `alter add PARTITIONS data DIRECTORY ...`
+ // 3. We should know the default data directory like /var/mysql/data, and the default index directory like /var/mysql/index.
+ case ast.TableOptionDelayKeyWrite:
+ return &ast.TableOption{
+ Tp: ast.TableOptionDelayKeyWrite,
+ UintValue: 0,
+ }
+ case ast.TableOptionEncryption:
+ return &ast.TableOption{
+ Tp: ast.TableOptionEncryption,
+ StrValue: "N",
+ }
+ case ast.TableOptionEngine:
+ // TODO(zp): handle the default engine
+ case ast.TableOptionInsertMethod:
+ // INSERT METHOD only support in MERGE storage engine.
+ // https://dev.mysql.com/doc/refman/8.0/en/create-table.html
+ return &ast.TableOption{
+ Tp: ast.TableOptionInsertMethod,
+ StrValue: "NO",
+ }
+ case ast.TableOptionKeyBlockSize:
+ // TODO(zp): InnoDB doesn't support this. And the default value will be ensured when compiling.
+ case ast.TableOptionMaxRows:
+ return &ast.TableOption{
+ Tp: ast.TableOptionMaxRows,
+ UintValue: 0,
+ }
+ case ast.TableOptionMinRows:
+ return &ast.TableOption{
+ Tp: ast.TableOptionMinRows,
+ UintValue: 0,
+ }
+ case ast.TableOptionPackKeys:
+ // TiDB doesn't support this, and the restore will always write "DEFAULT".
+ return &ast.TableOption{
+ Tp: ast.TableOptionPackKeys,
+ }
+ case ast.TableOptionPassword:
+ // mysqldump will not dump the password, but we handle it to pass the test.
+ return &ast.TableOption{
+ Tp: ast.TableOptionPassword,
+ }
+ case ast.TableOptionRowFormat:
+ return &ast.TableOption{
+ Tp: ast.TableOptionRowFormat,
+ UintValue: ast.RowFormatDefault,
+ }
+ case ast.TableOptionStatsAutoRecalc:
+ return &ast.TableOption{
+ Tp: ast.TableOptionStatsAutoRecalc,
+ Default: true,
+ }
+ case ast.TableOptionStatsPersistent:
+ // TiDB doesn't support this, and the restore will always write "DEFAULT".
+ return &ast.TableOption{
+ Tp: ast.TableOptionStatsPersistent,
+ }
+ case ast.TableOptionStatsSamplePages:
+ return &ast.TableOption{
+ Tp: ast.TableOptionStatsSamplePages,
+ Default: true,
+ }
+ case ast.TableOptionTablespace:
+ // TODO(zp): handle the table space
+ case ast.TableOptionUnion:
+ // TODO(zp): handle the union
+ }
+ return nil
+}
+
+// isTableOptionValEqual compare the two table options value, if they are equal, returns true.
+// Caller need to ensure the two table options are not nil and the type is the same.
+func isTableOptionValEqual(old, new *ast.TableOption) bool {
+ switch old.Tp {
+ case ast.TableOptionAutoIncrement:
+ // You cannot reset the counter to a value less than or equal to the value that is currently in use.
+ // For both InnoDB and MyISAM, if the value is less than or equal to the maximum value currently in the AUTO_INCREMENT column,
+ // the value is reset to the current maximum AUTO_INCREMENT column value plus one.
+ // https://dev.mysql.com/doc/refman/8.0/en/alter-table.html
+ return old.UintValue == new.UintValue
+ case ast.TableOptionAvgRowLength:
+ return old.UintValue == new.UintValue
+ case ast.TableOptionCharset:
+ if old.Default != new.Default {
+ return false
+ }
+ if old.Default && new.Default {
+ return true
+ }
+ return old.StrValue == new.StrValue
+ case ast.TableOptionCollate:
+ return old.StrValue == new.StrValue
+ case ast.TableOptionCheckSum:
+ return old.UintValue == new.UintValue
+ case ast.TableOptionComment:
+ return old.StrValue == new.StrValue
+ case ast.TableOptionCompression:
+ return old.StrValue == new.StrValue
+ case ast.TableOptionConnection:
+ return old.StrValue == new.StrValue
+ case ast.TableOptionDataDirectory:
+ return old.StrValue == new.StrValue
+ case ast.TableOptionIndexDirectory:
+ return old.StrValue == new.StrValue
+ case ast.TableOptionDelayKeyWrite:
+ return old.UintValue == new.UintValue
+ case ast.TableOptionEncryption:
+ return old.StrValue == new.StrValue
+ case ast.TableOptionEngine:
+ return old.StrValue == new.StrValue
+ case ast.TableOptionInsertMethod:
+ return old.StrValue == new.StrValue
+ case ast.TableOptionKeyBlockSize:
+ return old.UintValue == new.UintValue
+ case ast.TableOptionMaxRows:
+ return old.UintValue == new.UintValue
+ case ast.TableOptionMinRows:
+ return old.UintValue == new.UintValue
+ case ast.TableOptionPackKeys:
+ // TiDB doesn't support this, and the restore will always write "DEFAULT".
+ // The parser will ignore it. So we can only ignore it here.
+ // https://github.com/pingcap/tidb/blob/master/parser/parser.y#L11661
+ return old.Default == new.Default
+ case ast.TableOptionPassword:
+ // mysqldump will not dump the password, so we just return false here.
+ return false
+ case ast.TableOptionRowFormat:
+ return old.UintValue == new.UintValue
+ case ast.TableOptionStatsAutoRecalc:
+ // TiDB parser will ignore the DEFAULT value. So we just can compare the UINT value here.
+ // https://github.com/pingcap/tidb/blob/master/parser/parser.y#L11599
+ return old.UintValue == new.UintValue
+ case ast.TableOptionStatsPersistent:
+ // TiDB parser doesn't support this, it only assign the type without any value.
+ // https://github.com/pingcap/tidb/blob/master/parser/parser.y#L11595
+ return true
+ case ast.TableOptionStatsSamplePages:
+ return old.UintValue == new.UintValue
+ case ast.TableOptionTablespace:
+ return old.StrValue == new.StrValue
+ case ast.TableOptionUnion:
+ oldTableNames := old.TableNames
+ newTableNames := new.TableNames
+ if len(oldTableNames) != len(newTableNames) {
+ return false
+ }
+ for i, oldTableName := range oldTableNames {
+ newTableName := newTableNames[i]
+ if oldTableName.Name.O != newTableName.Name.O {
+ return false
+ }
+ }
+ return true
+ }
+ return true
+}
+
+// isViewEqual checks whether two views with same name are equal.
+func (diff *diffNode) isViewEqual(old, new *ast.CreateViewStmt) bool {
+ // CREATE
+ // [OR REPLACE]
+ // [ALGORITHM = {UNDEFINED | MERGE | TEMPTABLE}]
+ // [DEFINER = user]
+ // [SQL SECURITY { DEFINER | INVOKER }]
+ // VIEW view_name [(column_list)]
+ // AS select_statement
+ // [WITH [CASCADED | LOCAL] CHECK OPTION]
+ // We can easily replace view statement by using `CREATE OR REPLACE VIEW` statement to replace the old one.
+ // So we don't need to compare each part, just compare the restore string.
+ if diff.ignoreCaseSensitive {
+ oldViewStr, err := toLowerNameString(old)
+ if err != nil {
+ slog.Error("fail to convert old view to string", log.BBError(err))
+ return false
+ }
+ newViewStr, err := toLowerNameString(new)
+ if err != nil {
+ slog.Error("fail to convert new view to string", log.BBError(err))
+ return false
+ }
+ return oldViewStr == newViewStr
+ }
+ oldViewStr, err := toString(old)
+ if err != nil {
+ slog.Error("fail to convert old view to string", log.BBError(err))
+ return false
+ }
+ newViewStr, err := toString(new)
+ if err != nil {
+ slog.Error("fail to convert new view to string", log.BBError(err))
+ return false
+ }
+ return oldViewStr == newViewStr
+}
+
+// buildTableOptionMap builds a map of table options.
+func buildTableOptionMap(options []*ast.TableOption) map[ast.TableOptionType]*ast.TableOption {
+ m := make(map[ast.TableOptionType]*ast.TableOption)
+ for _, option := range options {
+ m[option.Tp] = option
+ }
+ return m
+}
+
+// hasColumnsIntersection returns true if two column slices have column name intersection.
+func hasColumnsIntersection(a, b []*ast.ColumnDef) bool {
+ bMap := make(map[string]bool)
+ for _, col := range b {
+ // MySQL column name is case insensitive.
+ bMap[col.Name.Name.L] = true
+ }
+ for _, col := range a {
+ // MySQL column name is case insensitive.
+ if _, ok := bMap[col.Name.Name.L]; ok {
+ return true
+ }
+ }
+ return false
+}
diff --git a/backend/plugin/parser/tidb/differ_column_test.go b/backend/plugin/parser/tidb/differ_column_test.go
new file mode 100644
index 0000000000..fb9740eaee
--- /dev/null
+++ b/backend/plugin/parser/tidb/differ_column_test.go
@@ -0,0 +1,298 @@
+package tidb
+
+import (
+ "testing"
+)
+
+func TestColumnExist(t *testing.T) {
+ tests := []testCase{
+ // Missing columns
+ {
+ 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 AFTER `id`;\n\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 AFTER `id`, ADD COLUMN `code` VARCHAR(50) AFTER `price`;\n\n",
+ },
+ {
+ old: ``,
+ new: `CREATE TABLE book(id INT, price INT, code VARCHAR(50), PRIMARY KEY(id));`,
+ want: "" +
+ "CREATE TABLE IF NOT EXISTS `book` (\n" +
+ " `id` INT,\n" +
+ " `price` INT,\n" +
+ " `code` VARCHAR(50),\n" +
+ " PRIMARY KEY (`id`)\n" +
+ ");\n\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: "",
+ },
+ // excess columns
+ {
+ old: `CREATE TABLE book(id INT, price INT, code VARCHAR(50), PRIMARY KEY(id));`,
+ new: `CREATE TABLE book(price INT, code VARCHAR(50));`,
+ want: "ALTER TABLE `book` DROP PRIMARY KEY;\n\n" +
+ "ALTER TABLE `book` DROP COLUMN `id`;\n\n",
+ },
+ }
+ testDiffWithoutDisableForeignKeyCheck(t, tests)
+}
+
+func TestColumnType(t *testing.T) {
+ tests := []testCase{
+ // Different types.
+ {
+ old: `CREATE TABLE book(id INT);`,
+ new: `CREATE TABLE book(id VARCHAR(50));`,
+ want: "ALTER TABLE `book` MODIFY COLUMN `id` VARCHAR(50);\n\n",
+ },
+
+ {
+ old: `CREATE TABLE book(id INT, isbn VARCHAR(50));`,
+ new: `CREATE TABLE book(id VARCHAR(50), isbn VARCHAR(100));`,
+ want: "ALTER TABLE `book` MODIFY COLUMN `id` VARCHAR(50), MODIFY COLUMN `isbn` VARCHAR(100);\n\n",
+ },
+ {
+ old: `CREATE TABLE book(id INT, isbn VARCHAR(50));`,
+ new: `CREATE TABLE book(id INT, isbn VARCHAR(50));`,
+ want: "",
+ },
+ }
+ testDiffWithoutDisableForeignKeyCheck(t, tests)
+}
+
+func TestColumnOption(t *testing.T) {
+ tests := []testCase{
+ {
+ old: `CREATE TABLE book(id INT COLUMN_FORMAT FIXED, PRIMARY KEY(id));`,
+ new: `CREATE TABLE book(id INT COLUMN_FORMAT DYNAMIC, PRIMARY KEY(id));`,
+ want: "ALTER TABLE `book` MODIFY COLUMN `id` INT COLUMN_FORMAT DYNAMIC;\n\n",
+ },
+ // NULL option not match.
+ {
+ old: `CREATE TABLE book(name VARCHAR(50) NOT NULL);`,
+ new: `CREATE TABLE book(name VARCHAR(50) NULL);`,
+ want: "ALTER TABLE `book` MODIFY COLUMN `name` VARCHAR(50) NULL;\n\n",
+ },
+ {
+ old: `CREATE TABLE book(name VARCHAR(50) NOT NULL);`,
+ new: `CREATE TABLE book(name VARCHAR(50));`,
+ want: "ALTER TABLE `book` MODIFY COLUMN `name` VARCHAR(50);\n\n",
+ },
+ {
+ old: `CREATE TABLE book(name VARCHAR(50) NOT NULL DEFAULT 'Harry Potter');`,
+ new: `CREATE TABLE book(name VARCHAR(50) NULL DEFAULT 'Harry Potter');`,
+ want: "ALTER TABLE `book` MODIFY COLUMN `name` VARCHAR(50) NULL DEFAULT 'Harry Potter';\n\n",
+ },
+ {
+ old: `CREATE TABLE book(name VARCHAR(50) NOT NULL DEFAULT 'Harry Potter');`,
+ new: `CREATE TABLE book(name VARCHAR(50) DEFAULT 'Harry Potter');`,
+ want: "ALTER TABLE `book` MODIFY COLUMN `name` VARCHAR(50) DEFAULT 'Harry Potter';\n\n",
+ },
+ {
+ old: `CREATE TABLE book(name VARCHAR(50) NULL);`,
+ new: `CREATE TABLE book(name VARCHAR(50));`,
+ want: "",
+ },
+ {
+ old: `CREATE TABLE book(name VARCHAR(50));`,
+ new: `CREATE TABLE book(name VARCHAR(50) NULL);`,
+ want: "",
+ },
+ {
+ old: `CREATE TABLE book(name VARCHAR(50) NULL);`,
+ new: `CREATE TABLE book(name VARCHAR(50) NULL);`,
+ want: "",
+ },
+ {
+ old: `CREATE TABLE book(name VARCHAR(50) NOT NULL);`,
+ new: `CREATE TABLE book(name VARCHAR(50) NOT NULL);`,
+ want: "",
+ },
+ }
+ testDiffWithoutDisableForeignKeyCheck(t, tests)
+}
+
+func TestColumnComment(t *testing.T) {
+ tests := []testCase{
+ {
+ old: `CREATE TABLE book(name VARCHAR(50) COMMENT 'Author Name' NOT NULL);`,
+ new: `CREATE TABLE book(name VARCHAR(50) COMMENT 'Book Name' NOT NULL);`,
+ want: "ALTER TABLE `book` MODIFY COLUMN `name` VARCHAR(50) COMMENT 'Book Name' NOT NULL;\n\n",
+ },
+ {
+ old: `CREATE TABLE book(name VARCHAR(50) COMMENT 'Author Name' NOT NULL);`,
+ new: `CREATE TABLE book(name VARCHAR(50) COMMENT 'AUTHOR NAME' NOT NULL);`,
+ want: "ALTER TABLE `book` MODIFY COLUMN `name` VARCHAR(50) COMMENT 'AUTHOR NAME' NOT NULL;\n\n",
+ },
+ {
+ old: `CREATE TABLE book(name VARCHAR(50) NOT NULL);`,
+ new: `CREATE TABLE book(name VARCHAR(50) COMMENT 'Book Name' NOT NULL);`,
+ want: "ALTER TABLE `book` MODIFY COLUMN `name` VARCHAR(50) COMMENT 'Book Name' NOT NULL;\n\n",
+ },
+ {
+ old: `CREATE TABLE book(name VARCHAR(50) COMMENT 'Book Name' NOT NULL);`,
+ new: `CREATE TABLE book(name VARCHAR(50) NOT NULL);`,
+ want: "ALTER TABLE `book` MODIFY COLUMN `name` VARCHAR(50) NOT NULL;\n\n",
+ },
+ {
+ old: `CREATE TABLE book(name VARCHAR(50) NOT NULL);`,
+ new: `CREATE TABLE book(name VARCHAR(50) NOT NULL);`,
+ want: "",
+ },
+ {
+ old: `CREATE TABLE book(name VARCHAR(50) COMMENT 'Book Name' NOT NULL);`,
+ new: `CREATE TABLE book(name VARCHAR(50) COMMENT 'Book Name' NOT NULL);`,
+ want: "",
+ },
+ }
+ testDiffWithoutDisableForeignKeyCheck(t, tests)
+}
+
+func TestColumnDefaultValue(t *testing.T) {
+ tests := []testCase{
+ {
+ old: `CREATE TABLE book(name VARCHAR(50) DEFAULT 'Harry Potter' NOT NULL);`,
+ new: `CREATE TABLE book(name VARCHAR(50) NOT NULL);`,
+ want: "ALTER TABLE `book` MODIFY COLUMN `name` VARCHAR(50) NOT NULL;\n\n",
+ },
+ {
+ old: `CREATE TABLE book(name VARCHAR(50) NOT NULL);`,
+ new: `CREATE TABLE book(name VARCHAR(50) DEFAULT 'Harry Potter' NOT NULL);`,
+ want: "ALTER TABLE `book` MODIFY COLUMN `name` VARCHAR(50) DEFAULT 'Harry Potter' NOT NULL;\n\n",
+ },
+ {
+ old: `CREATE TABLE book(name VARCHAR(50) DEFAULT 'Holmes' NOT NULL);`,
+ new: `CREATE TABLE book(name VARCHAR(50) DEFAULT 'Harry Potter' NOT NULL);`,
+ want: "ALTER TABLE `book` MODIFY COLUMN `name` VARCHAR(50) DEFAULT 'Harry Potter' NOT NULL;\n\n",
+ },
+ {
+ old: `CREATE TABLE book(name VARCHAR(50) DEFAULT 'Holmes' NOT NULL);`,
+ new: `CREATE TABLE book(name VARCHAR(50) DEFAULT 'Holmes' NOT NULL);`,
+ want: "",
+ },
+ {
+ old: `CREATE TABLE book(id INT DEFAULT 0 NOT NULL);`,
+ new: `CREATE TABLE book(id INT NOT NULL);`,
+ want: "ALTER TABLE `book` MODIFY COLUMN `id` INT NOT NULL;\n\n",
+ },
+ {
+ old: `CREATE TABLE book(id INT NOT NULL);`,
+ new: `CREATE TABLE book(id INT DEFAULT 0 NOT NULL);`,
+ want: "ALTER TABLE `book` MODIFY COLUMN `id` INT DEFAULT 0 NOT NULL;\n\n",
+ },
+ {
+ old: `CREATE TABLE book(id INT DEFAULT 0 NOT NULL);`,
+ new: `CREATE TABLE book(id INT DEFAULT 1 NOT NULL);`,
+ want: "ALTER TABLE `book` MODIFY COLUMN `id` INT DEFAULT 1 NOT NULL;\n\n",
+ },
+ {
+ old: `CREATE TABLE book(id INT DEFAULT 0 NOT NULL);`,
+ new: `CREATE TABLE book(id INT DEFAULT 0 NOT NULL);`,
+ want: "",
+ },
+ // Function Call
+ {
+ old: "CREATE TABLE action(action_id smallint(5) unsigned NOT NULL AUTO_INCREMENT," +
+ "`last_update` timestamp not null default current_timestamp);",
+ new: "CREATE TABLE action(action_id smallint(5) unsigned NOT NULL AUTO_INCREMENT," +
+ "`last_update` timestamp not null default current_timestamp(1));",
+ want: "ALTER TABLE `action` MODIFY COLUMN `last_update` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP(1);\n\n",
+ },
+ }
+ testDiffWithoutDisableForeignKeyCheck(t, tests)
+}
+
+func TestColumnCollate(t *testing.T) {
+ tests := []testCase{
+ {
+ old: `CREATE TABLE book(name VARCHAR(50) COLLATE utf8mb4_bin DEFAULT 'Harry Potter' NOT NULL);`,
+ new: `CREATE TABLE book(name VARCHAR(50) COLLATE utf8mb4_polish_ci DEFAULT 'Harry Potter' NOT NULL);`,
+ want: "ALTER TABLE `book` MODIFY COLUMN `name` VARCHAR(50) COLLATE utf8mb4_polish_ci DEFAULT 'Harry Potter' NOT NULL;\n\n",
+ },
+ {
+ old: `CREATE TABLE book(name VARCHAR(50) DEFAULT 'Harry Potter' NOT NULL);`,
+ new: `CREATE TABLE book(name VARCHAR(50) COLLATE utf8mb4_polish_ci DEFAULT 'Harry Potter' NOT NULL);`,
+ want: "ALTER TABLE `book` MODIFY COLUMN `name` VARCHAR(50) COLLATE utf8mb4_polish_ci DEFAULT 'Harry Potter' NOT NULL;\n\n",
+ },
+ {
+ old: `CREATE TABLE book(name VARCHAR(50) DEFAULT 'Holmes' NOT NULL);`,
+ new: `CREATE TABLE book(name VARCHAR(50) DEFAULT 'Holmes' NOT NULL);`,
+ want: "",
+ },
+ {
+ old: `CREATE TABLE book(name VARCHAR(50) COLLATE utf8mb4_bin DEFAULT 'Holmes' NOT NULL);`,
+ new: `CREATE TABLE book(name VARCHAR(50) COLLATE utf8mb4_bin DEFAULT 'Holmes' NOT NULL);`,
+ want: "",
+ },
+ {
+ old: `CREATE TABLE book(name VARCHAR(50) COLLATE utf8mb4_bin DEFAULT 'Holmes' NOT NULL);`,
+ new: `CREATE TABLE book(name VARCHAR(50) DEFAULT 'Holmes' NOT NULL);`,
+ want: "",
+ },
+ }
+ testDiffWithoutDisableForeignKeyCheck(t, tests)
+}
+
+func TestColumnOrder(t *testing.T) {
+ tests := []testCase{
+ // Append the column to the end of the table.
+ {
+ old: `CREATE TABLE book(id INT PRIMARY KEY);`,
+ new: `CREATE TABLE book(id INT PRIMARY KEY, name VARCHAR(50) NOT NULL, author VARCHAR(50) NOT NULL);`,
+ want: "ALTER TABLE `book` ADD COLUMN `name` VARCHAR(50) NOT NULL AFTER `id`, ADD COLUMN `author` VARCHAR(50) NOT NULL AFTER `name`;\n\n",
+ },
+ // Add the column at the beginning of the table.
+ {
+ old: `CREATE TABLE book(author VARCHAR(50) NOT NULL);`,
+ new: `CREATE TABLE book(id INT PRIMARY KEY, name VARCHAR(50) NOT NULL, author VARCHAR(50) NOT NULL);`,
+ want: "ALTER TABLE `book` ADD COLUMN `id` INT PRIMARY KEY FIRST, ADD COLUMN `name` VARCHAR(50) NOT NULL AFTER `id`;\n\n",
+ },
+ // Add the column in the middle of the table.
+ {
+ old: `CREATE TABLE book(id INT PRIMARY KEY, author VARCHAR(50) NOT NULL);`,
+ new: `CREATE TABLE book(id INT PRIMARY KEY, name VARCHAR(50) NOT NULL, author VARCHAR(50) NOT NULL);`,
+ want: "ALTER TABLE `book` ADD COLUMN `name` VARCHAR(50) NOT NULL AFTER `id`;\n\n",
+ },
+ // Modify the existing column order.
+ {
+ old: `CREATE TABLE book(author VARCHAR(50) NOT NULL, id INT PRIMARY KEY, name VARCHAR(50) NOT NULL);`,
+ new: `CREATE TABLE book(id INT PRIMARY KEY, name VARCHAR(50) NOT NULL, author VARCHAR(50) NOT NULL);`,
+ want: "ALTER TABLE `book` MODIFY COLUMN `id` INT PRIMARY KEY FIRST, MODIFY COLUMN `name` VARCHAR(50) NOT NULL AFTER `id`;\n\n",
+ },
+ // Complicated case.
+ {
+ 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
+
+ },
+ {
+ old: `CREATE TABLE book(c1 INT, c2 INT, c3 INT, c4 INT, c8 INT);`,
+ new: `CREATE TABLE book(c9 INT, c8 VARCHAR(10), c4 INT, c2 VARCHAR(10), c9 INT);`,
+ want: "ALTER TABLE `book` ADD COLUMN `c9` INT FIRST, " +
+ "MODIFY COLUMN `c8` VARCHAR(10) AFTER `c9`, " +
+ "MODIFY COLUMN `c4` INT AFTER `c8`, " +
+ "MODIFY COLUMN `c2` VARCHAR(10), " +
+ "ADD COLUMN `c9` INT AFTER `c2`;\n\n" +
+ "ALTER TABLE `book` DROP COLUMN `c1`;\n\n" +
+ "ALTER TABLE `book` DROP COLUMN `c3`;\n\n",
+ },
+ {
+ old: `CREATE TABLE t(a int);`,
+ new: `CREATE TABLE t(b int);`,
+ want: "ALTER TABLE `t` ADD COLUMN `b` INT FIRST;\n\n" +
+ "ALTER TABLE `t` DROP COLUMN `a`;\n\n",
+ },
+ }
+ testDiffWithoutDisableForeignKeyCheck(t, tests)
+}
diff --git a/backend/plugin/parser/tidb/differ_constraint_test.go b/backend/plugin/parser/tidb/differ_constraint_test.go
new file mode 100644
index 0000000000..c8107bd2de
--- /dev/null
+++ b/backend/plugin/parser/tidb/differ_constraint_test.go
@@ -0,0 +1,530 @@
+package tidb
+
+import (
+ "testing"
+
+ "github.com/pingcap/tidb/parser/ast"
+ "github.com/pingcap/tidb/parser/model"
+ "github.com/pingcap/tidb/parser/opcode"
+ "github.com/pingcap/tidb/types"
+ driver "github.com/pingcap/tidb/types/parser_driver"
+ "github.com/stretchr/testify/require"
+)
+
+func TestIsKeyPartEqual(t *testing.T) {
+ tests := []struct {
+ old []*ast.IndexPartSpecification
+ new []*ast.IndexPartSpecification
+ eq bool
+ }{
+ {
+ old: []*ast.IndexPartSpecification{
+ // `id` + 1
+ {
+ Expr: &ast.BinaryOperationExpr{
+ Op: opcode.Plus,
+ L: &ast.ColumnNameExpr{
+ Name: &ast.ColumnName{
+ Name: model.NewCIStr("id"),
+ },
+ },
+ R: &driver.ValueExpr{
+ Datum: types.NewDatum(1),
+ },
+ },
+ Column: &ast.ColumnName{
+ Name: model.NewCIStr("id"),
+ },
+ },
+ },
+ new: []*ast.IndexPartSpecification{
+ // `id` * 2
+ {
+ Expr: &ast.BinaryOperationExpr{
+ Op: opcode.Mul,
+ L: &ast.ColumnNameExpr{
+ Name: &ast.ColumnName{
+ Name: model.NewCIStr("id"),
+ },
+ },
+ R: &driver.ValueExpr{
+ Datum: types.NewDatum(2),
+ },
+ },
+ Column: &ast.ColumnName{
+ Name: model.NewCIStr("id"),
+ },
+ },
+ },
+ eq: false,
+ },
+ {
+ old: []*ast.IndexPartSpecification{
+ // `id` + 1
+ {
+ Expr: &ast.BinaryOperationExpr{
+ Op: opcode.Plus,
+ L: &ast.ColumnNameExpr{
+ Name: &ast.ColumnName{
+ Name: model.NewCIStr("id"),
+ },
+ },
+ R: &driver.ValueExpr{
+ Datum: types.NewDatum(1),
+ },
+ },
+ Column: &ast.ColumnName{
+ Name: model.NewCIStr("id"),
+ },
+ },
+ },
+ new: []*ast.IndexPartSpecification{
+ // `id` + 1
+ {
+ Expr: &ast.BinaryOperationExpr{
+ Op: opcode.Plus,
+ L: &ast.ColumnNameExpr{
+ Name: &ast.ColumnName{
+ Name: model.NewCIStr("id"),
+ },
+ },
+ R: &driver.ValueExpr{
+ Datum: types.NewDatum(1),
+ },
+ },
+ Column: &ast.ColumnName{
+ Name: model.NewCIStr("id"),
+ },
+ },
+ // `id` * 2
+ {
+ Expr: &ast.BinaryOperationExpr{
+ Op: opcode.Mul,
+ L: &ast.ColumnNameExpr{
+ Name: &ast.ColumnName{
+ Name: model.NewCIStr("id"),
+ },
+ },
+ R: &driver.ValueExpr{
+ Datum: types.NewDatum(2),
+ },
+ },
+ Column: &ast.ColumnName{
+ Name: model.NewCIStr("id"),
+ },
+ },
+ },
+ eq: false,
+ },
+ {
+ old: []*ast.IndexPartSpecification{
+ // `id` + 1
+ {
+ Expr: &ast.BinaryOperationExpr{
+ Op: opcode.Plus,
+ L: &ast.ColumnNameExpr{
+ Name: &ast.ColumnName{
+ Name: model.NewCIStr("id"),
+ },
+ },
+ R: &driver.ValueExpr{
+ Datum: types.NewDatum(1),
+ },
+ },
+ Column: &ast.ColumnName{
+ Name: model.NewCIStr("id"),
+ },
+ },
+ },
+ new: []*ast.IndexPartSpecification{
+ // `id` + 1
+ {
+ Expr: &ast.BinaryOperationExpr{
+ Op: opcode.Plus,
+ L: &ast.ColumnNameExpr{
+ Name: &ast.ColumnName{
+ Name: model.NewCIStr("id"),
+ },
+ },
+ R: &driver.ValueExpr{
+ Datum: types.NewDatum(1),
+ },
+ },
+ Column: &ast.ColumnName{
+ Name: model.NewCIStr("id"),
+ },
+ },
+ },
+ eq: true,
+ },
+ }
+ a := require.New(t)
+ for _, test := range tests {
+ got := isKeyPartEqual(test.old, test.new)
+ a.Equalf(test.eq, got, "old: %v, new: %v", test.old, test.new)
+ }
+}
+
+func TestIsIndexOptionEqual(t *testing.T) {
+ tests := []struct {
+ old *ast.IndexOption
+ new *ast.IndexOption
+ eq bool
+ }{
+ {
+ old: nil,
+ new: nil,
+ eq: true,
+ },
+ {
+ old: &ast.IndexOption{
+ KeyBlockSize: 1024,
+ },
+ new: nil,
+ eq: false,
+ },
+ {
+ old: &ast.IndexOption{
+ KeyBlockSize: 1024,
+ },
+ new: nil,
+ eq: false,
+ },
+ {
+ old: &ast.IndexOption{
+ KeyBlockSize: 1024,
+ Tp: model.IndexTypeBtree,
+ ParserName: model.NewCIStr("parser"),
+ Comment: "comment",
+ Visibility: ast.IndexVisibilityVisible,
+ },
+ new: &ast.IndexOption{
+ KeyBlockSize: 1024,
+ Tp: model.IndexTypeHash,
+ ParserName: model.NewCIStr("parser"),
+ Comment: "commen_idx",
+ Visibility: ast.IndexVisibilityInvisible,
+ },
+ eq: false,
+ },
+ {
+ old: &ast.IndexOption{
+ KeyBlockSize: 1024,
+ Tp: model.IndexTypeBtree,
+ ParserName: model.NewCIStr("parser"),
+ Comment: "comment",
+ Visibility: ast.IndexVisibilityVisible,
+ },
+ new: &ast.IndexOption{
+ KeyBlockSize: 1024,
+ Tp: model.IndexTypeBtree,
+ ParserName: model.NewCIStr("parser"),
+ Comment: "comment",
+ Visibility: ast.IndexVisibilityVisible,
+ },
+ eq: true,
+ },
+ }
+
+ a := require.New(t)
+ for _, test := range tests {
+ got := isIndexOptionEqual(test.old, test.new)
+ a.Equalf(test.eq, got, "old: %v, new: %v", test.old, test.new)
+ }
+}
+
+func TestIndexType(t *testing.T) {
+ tests := []testCase{
+ {
+ 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: "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));`,
+ new: `CREATE TABLE book(name VARCHAR(50) NOT NULL, INDEX book_idx USING BTREE(name));`,
+ want: "",
+ },
+ {
+ old: `CREATE TABLE book(name VARCHAR(50) NOT NULL, INDEX book_idx(name));`,
+ new: `CREATE TABLE book(name VARCHAR(50) NOT NULL, INDEX book_idx(name));`,
+ want: "",
+ },
+ }
+
+ testDiffWithoutDisableForeignKeyCheck(t, tests)
+}
+
+func TestIndexOption(t *testing.T) {
+ tests := []testCase{
+ // KEY_BLOCK_SIZE not match.
+ {
+ 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: "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);`,
+ new: `CREATE TABLE book(name VARCHAR(50) NOT NULL, CONSTRAINT PRIMARY KEY (name) KEY_BLOCK_SIZE=50);`,
+ want: "ALTER TABLE `book` DROP PRIMARY KEY;\n\n" +
+ "ALTER TABLE `book` ADD PRIMARY KEY (`name`) KEY_BLOCK_SIZE=50;\n\n",
+ },
+ // WITH PARSER not match.
+ // {
+ // 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: "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);`,
+ // new: `CREATE TABLE book(name VARCHAR(50) NOT NULL,CONSTRAINT PRIMARY KEY (name) WITH PARSER parser_b);`,
+ // want: "ALTER TABLE `book` DROP PRIMARY KEY;\n\n" +
+ // "ALTER TABLE `book` ADD PRIMARY KEY (`name`) WITH PARSER `parser_b`;\n\n",
+ // },
+ // COMMENT not match.
+ {
+ 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: "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');`,
+ new: `CREATE TABLE book(name VARCHAR(50) NOT NULL, CONSTRAINT PRIMARY KEY(name) COMMENT 'comment_b');`,
+ want: "ALTER TABLE `book` DROP PRIMARY KEY;\n\n" +
+ "ALTER TABLE `book` ADD PRIMARY KEY (`name`) COMMENT 'comment_b';\n\n",
+ },
+ // VISIBILITY not match.
+ {
+
+ 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: "DROP INDEX `book_idx` ON `book`;\n\n" +
+ "CREATE INDEX `book_idx` ON `book` (`name`) INVISIBLE;\n\n",
+ },
+ {
+
+ old: `CREATE TABLE book(name VARCHAR(50) NOT NULL, CONSTRAINT PRIMARY KEY(name) VISIBLE);`,
+ new: `CREATE TABLE book(name VARCHAR(50) NOT NULL, CONSTRAINT PRIMARY KEY(name) INVISIBLE);`,
+ want: "ALTER TABLE `book` DROP PRIMARY KEY;\n\n" +
+ "ALTER TABLE `book` ADD PRIMARY KEY (`name`) INVISIBLE;\n\n",
+ },
+ {
+ old: `CREATE TABLE book(name VARCHAR(50) NOT NULL, FULLTEXT INDEX book_idx(name) KEY_BLOCK_SIZE=30 COMMENT 'no difference!');`,
+ new: `CREATE TABLE book(name VARCHAR(50) NOT NULL, FULLTEXT INDEX book_idx(name) KEY_BLOCK_SIZE=30 COMMENT 'no difference!');`,
+ want: "",
+ },
+ {
+ old: `CREATE TABLE book(name VARCHAR(50) NOT NULL, CONSTRAINT PRIMARY KEY(name) KEY_BLOCK_SIZE=30 COMMENT 'no difference!');`,
+ new: `CREATE TABLE book(name VARCHAR(50) NOT NULL, CONSTRAINT PRIMARY KEY(name) KEY_BLOCK_SIZE=30 COMMENT 'no difference!');`,
+ want: "",
+ },
+ }
+
+ testDiffWithoutDisableForeignKeyCheck(t, tests)
+}
+
+func TestKeyPart(t *testing.T) {
+ tests := []testCase{
+ {
+ 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: "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');`,
+ new: `CREATE TABLE book(id INT, name VARCHAR(50) NOT NULL, CONSTRAINT PRIMARY KEY(id) COMMENT 'comment_a');`,
+ want: "ALTER TABLE `book` DROP PRIMARY KEY;\n\n" +
+ "ALTER TABLE `book` ADD PRIMARY KEY (`id`) COMMENT 'comment_a';\n\n",
+ },
+ {
+ 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: "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');`,
+ new: `CREATE TABLE book(id INT, name VARCHAR(50) NOT NULL, CONSTRAINT PRIMARY KEY ((id + 1)) COMMENT 'comment_a');`,
+ want: "ALTER TABLE `book` DROP PRIMARY KEY;\n\n" +
+ "ALTER TABLE `book` ADD PRIMARY KEY ((`id`+1)) COMMENT 'comment_a';\n\n",
+ },
+ {
+ 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: "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');`,
+ new: `CREATE TABLE book(id INT, name VARCHAR(50) NOT NULL, CONSTRAINT PRIMARY KEY ((id + 2)) COMMENT 'comment_a');`,
+ want: "ALTER TABLE `book` DROP PRIMARY KEY;\n\n" +
+ "ALTER TABLE `book` ADD PRIMARY KEY ((`id`+2)) COMMENT 'comment_a';\n\n",
+ },
+ {
+ 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, name) COMMENT 'comment_a');`,
+ want: "",
+ },
+ {
+ old: `CREATE TABLE book(id INT, name VARCHAR(50) NOT NULL, CONSTRAINT PRIMARY KEY (id, name) COMMENT 'comment_a');`,
+ new: `CREATE TABLE book(id INT, name VARCHAR(50) NOT NULL, CONSTRAINT PRIMARY KEY (id, name) COMMENT 'comment_a');`,
+ want: "",
+ },
+ {
+ 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 + 1)) COMMENT 'comment_a');`,
+ want: "",
+ },
+ {
+ old: `CREATE TABLE book(id INT, name VARCHAR(50) NOT NULL, CONSTRAINT PRIMARY KEY ((id + 1)) COMMENT 'comment_a');`,
+ new: `CREATE TABLE book(id INT, name VARCHAR(50) NOT NULL, CONSTRAINT PRIMARY KEY ((id + 1)) COMMENT 'comment_a');`,
+ want: "",
+ },
+ }
+
+ testDiffWithoutDisableForeignKeyCheck(t, tests)
+}
+
+func TestForeignKeyDefination(t *testing.T) {
+ tests := []testCase{
+ {
+ old: `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 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` 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` (" +
+ " `id` int NOT NULL," +
+ " `name` varchar(50) NOT NULL," +
+ " PRIMARY KEY (`id`)," +
+ " KEY `id_name_idx` (`id`,`name`)" +
+ ") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;" +
+
+ "CREATE TABLE `employee` (" +
+ " `id` int NOT NULL," +
+ " `name` varchar(50) NOT NULL," +
+ " `department_id` int DEFAULT NULL," +
+ " `department_name` varchar(50) DEFAULT NULL," +
+ " PRIMARY KEY (`id`)," +
+ " KEY `department_id_name_idx` (`department_id`,`department_name`)," +
+ " CONSTRAINT `employee_ibfk_1` FOREIGN KEY (`department_id`, `department_name`) REFERENCES `department` (`id`, `name`)" +
+ ") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;",
+
+ new: "CREATE TABLE `department` (" +
+ " `id` int NOT NULL," +
+ " `name` varchar(50) NOT NULL," +
+ " PRIMARY KEY (`id`)," +
+ " KEY `id_idx` (`id`)" +
+ ") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;" +
+
+ "CREATE TABLE `employee` (" +
+ " `id` int NOT NULL," +
+ " `name` varchar(50) NOT NULL," +
+ " `department_id` int DEFAULT NULL," +
+ " `department_name` varchar(50) DEFAULT NULL," +
+ " PRIMARY KEY (`id`)," +
+ " KEY `department_id_idx` (`department_id`)," +
+ " CONSTRAINT `employee_ibfk_1` FOREIGN KEY (`department_id`) REFERENCES `department` (`id`)" +
+ ") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;",
+
+ 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.
+ {
+ old: "CREATE TABLE `employeee` (" +
+ " `id` int NOT NULL," +
+ " `name` varchar(50) NOT NULL," +
+ " `leader_id` int DEFAULT NULL," +
+ " PRIMARY KEY (`id`)," +
+ " CONSTRAINT `employee_ibfk_1` FOREIGN KEY (`leader_id`) REFERENCES `employeee` (`id`)" +
+ ") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;",
+
+ new: "CREATE TABLE `employeee` (" +
+ " `id` int NOT NULL," +
+ " `name` varchar(50) NOT NULL," +
+ " `leader_id` int DEFAULT NULL," +
+ " `manager_id` int DEFAULT NULL," +
+ " PRIMARY KEY (`id`)," +
+ " 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` 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",
+ },
+ }
+
+ testDiffWithoutDisableForeignKeyCheck(t, tests)
+}
+
+func TestCheckConstraint(t *testing.T) {
+ tests := []testCase{
+ {
+ old: `CREATE TABLE book(a INT, CONSTRAINT t1_chk_1 CHECK (a>0))`,
+ new: `CREATE TABLE book(a INT, CONSTRAINT t1_chk_1 CHECK ((a > 0)))`,
+ want: "",
+ },
+ {
+ old: "CREATE TABLE book(id INT, price INT, PRIMARY KEY(id), CONSTRAINT `check_price` CHECK (price > 0));",
+ new: "CREATE TABLE book(id INT, price INT, PRIMARY KEY(id), CONSTRAINT `check_price` CHECK (price > 1));",
+ want: "ALTER TABLE `book` DROP CHECK `check_price`;\n\n" +
+ "ALTER TABLE `book` ADD CONSTRAINT `check_price` CHECK(`price`>1) ENFORCED;\n\n",
+ },
+ {
+ old: "CREATE TABLE book(id INT, price INT, PRIMARY KEY(id), CONSTRAINT `check_price` CHECK (price > 0));",
+ 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",
+ },
+ {
+ 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` DROP CHECK `check_price2`;\n\n" +
+ "ALTER TABLE `book` ADD CONSTRAINT `check_price` CHECK(`price`>0) NOT ENFORCED;\n\n",
+ },
+ }
+ testDiffWithoutDisableForeignKeyCheck(t, tests)
+}
+
+func TestConstraint(t *testing.T) {
+ tests := []testCase{
+ // ADD COLUMN -> DROP PRIMARY KEY -> ADD PRIMARY KEY
+ {
+ 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` 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: "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: "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/tidb/differ_table_test.go b/backend/plugin/parser/tidb/differ_table_test.go
new file mode 100644
index 0000000000..6de8b4981d
--- /dev/null
+++ b/backend/plugin/parser/tidb/differ_table_test.go
@@ -0,0 +1,347 @@
+package tidb
+
+import (
+ "testing"
+)
+
+func TestTable(t *testing.T) {
+ tests := []testCase{
+ {
+ old: ``,
+ 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 `author` (\n" +
+ " `id` INT,\n" +
+ " `name` VARCHAR(255),\n" +
+ " PRIMARY KEY (`id`)\n" +
+ ");\n\n" +
+ "CREATE TABLE IF NOT EXISTS `book` (\n" +
+ " `id` INT,\n" +
+ " `price` INT,\n" +
+ " PRIMARY KEY (`id`)\n" +
+ ");\n\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` (\n" +
+ " `id` INT,\n" +
+ " `price` INT,\n" +
+ " PRIMARY KEY (`id`)\n" +
+ ");\n\n",
+ },
+ {
+ old: `CREATE TABLE book(id INT, price INT, PRIMARY KEY(id));
+ 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: "",
+ },
+ // Drop excess table
+ {
+ 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: "ALTER TABLE `book` DROP FOREIGN KEY `fk_price_id`;\n\n" +
+ "DROP TABLE IF EXISTS `price`;\n\n" +
+ "ALTER TABLE `book` DROP COLUMN `price_id`;\n\n",
+ },
+ }
+ testDiffWithoutDisableForeignKeyCheck(t, tests)
+}
+
+func TestTableOption(t *testing.T) {
+ tests := []testCase{
+ // AUTO_INCREMENT
+ {
+ old: `CREATE TABLE book(id INT AUTO_INCREMENT, CONSTRAINT PRIMARY KEY(id)) AUTO_INCREMENT = 4;`,
+ new: `CREATE TABLE book(id INT AUTO_INCREMENT, CONSTRAINT PRIMARY KEY(id)) AUTO_INCREMENT = 10;`,
+ want: "ALTER TABLE `book` AUTO_INCREMENT=10;\n\n",
+ },
+ {
+ old: `CREATE TABLE book(id INT AUTO_INCREMENT, CONSTRAINT PRIMARY KEY(id)) AUTO_INCREMENT = 4;`,
+ new: `CREATE TABLE book(id INT AUTO_INCREMENT, CONSTRAINT PRIMARY KEY(id));`,
+ want: "ALTER TABLE `book` AUTO_INCREMENT=0;\n\n",
+ },
+ // AVG_ROW_LENGTH
+ {
+ old: `CREATE TABLE book(id INT) AVG_ROW_LENGTH = 1;`,
+ new: `CREATE TABLE book(id INT) AVG_ROW_LENGTH = 2;`,
+ want: "ALTER TABLE `book` AVG_ROW_LENGTH=2;\n\n",
+ },
+ {
+ old: `CREATE TABLE book(id INT) AVG_ROW_LENGTH = 1;`,
+ new: `CREATE TABLE book(id INT);`,
+ want: "ALTER TABLE `book` AVG_ROW_LENGTH=0;\n\n",
+ },
+ // DEFAULT CHARSET
+ {
+ old: `CREATE TABLE book(id INT) DEFAULT CHARACTER SET = utf8;`,
+ new: `CREATE TABLE book(id INT) DEFAULT CHARACTER SET = utf8mb4;`,
+ want: "ALTER TABLE `book` DEFAULT CHARACTER SET=UTF8MB4;\n\n",
+ },
+ {
+ old: `CREATE TABLE book(id INT) DEFAULT CHARACTER SET = utf8;`,
+ new: `CREATE TABLE book(id INT);`,
+ want: "",
+ },
+ // DEFAULT COLLATE
+ {
+ old: `CREATE TABLE book(id INT) DEFAULT COLLATE = latin1_swedish_ci;`,
+ new: `CREATE TABLE book(id INT) DEFAULT COLLATE = utf8mb4_general_ci;`,
+ want: "ALTER TABLE `book` DEFAULT COLLATE=UTF8MB4_GENERAL_CI;\n\n",
+ },
+ {
+ old: `CREATE TABLE book(id INT) DEFAULT COLLATE = latin1_swedish_ci;`,
+ new: `CREATE TABLE book(id INT);`,
+ want: "",
+ },
+ // CHECKSUM
+ {
+ old: `CREATE TABLE book(id INT) CHECKSUM = 1;`,
+ new: `CREATE TABLE book(id INT) CHECKSUM = 0;`,
+ want: "ALTER TABLE `book` CHECKSUM=0;\n\n",
+ },
+ {
+ old: `CREATE TABLE book(id INT) CHECKSUM = 1;`,
+ new: `CREATE TABLE book(id INT);`,
+ want: "ALTER TABLE `book` CHECKSUM=0;\n\n",
+ },
+ // COMMENT
+ {
+ old: `CREATE TABLE book(id INT) COMMENT = 'old';`,
+ new: `CREATE TABLE book(id INT) COMMENT = 'new';`,
+ want: "ALTER TABLE `book` COMMENT='new';\n\n",
+ },
+ {
+ old: `CREATE TABLE book(id INT) COMMENT = 'old';`,
+ new: `CREATE TABLE book(id INT);`,
+ want: "ALTER TABLE `book` COMMENT='';\n\n",
+ },
+ // TODO(zp): handle drop COMPRESSION
+ {
+ old: `CREATE TABLE book(id INT) COMPRESSION = 'ZLIB';`,
+ new: `CREATE TABLE book(id INT) COMPRESSION = 'LZ4';`,
+ want: "ALTER TABLE `book` COMPRESSION='LZ4';\n\n",
+ },
+ // CONNECTION
+ {
+ old: `CREATE TABLE book(id INT) CONNECTION = 'old';`,
+ new: `CREATE TABLE book(id INT) CONNECTION = 'new';`,
+ want: "ALTER TABLE `book` CONNECTION='new';\n\n",
+ },
+ {
+ old: `CREATE TABLE book(id INT) CONNECTION = 'old';`,
+ new: `CREATE TABLE book(id INT);`,
+ want: "ALTER TABLE `book` CONNECTION='';\n\n",
+ },
+ // TODO(zp): handle drop DATA DIRECTORY
+ {
+ old: `CREATE TABLE book(id INT) DATA DIRECTORY = 'old';`,
+ new: `CREATE TABLE book(id INT) DATA DIRECTORY = 'new';`,
+ want: "ALTER TABLE `book` DATA DIRECTORY='new';\n\n",
+ },
+ // TODO(zp): handle drop INDEX DIRECTORY
+ {
+ old: `CREATE TABLE book(id INT) INDEX DIRECTORY = 'old';`,
+ new: `CREATE TABLE book(id INT) INDEX DIRECTORY = 'new';`,
+ want: "ALTER TABLE `book` INDEX DIRECTORY='new';\n\n",
+ },
+ // DELAY_KEY_WRITE
+ {
+ old: `CREATE TABLE book(id INT) DELAY_KEY_WRITE = 1;`,
+ new: `CREATE TABLE book(id INT) DELAY_KEY_WRITE = 0;`,
+ want: "ALTER TABLE `book` DELAY_KEY_WRITE=0;\n\n",
+ },
+ {
+ old: `CREATE TABLE book(id INT) DELAY_KEY_WRITE = 1;`,
+ new: `CREATE TABLE book(id INT)`,
+ want: "ALTER TABLE `book` DELAY_KEY_WRITE=0;\n\n",
+ },
+ // ENCRYPTION
+ {
+ old: `CREATE TABLE book(id INT) ENCRYPTION = 'Y';`,
+ new: `CREATE TABLE book(id INT) ENCRYPTION = 'N';`,
+ want: "ALTER TABLE `book` ENCRYPTION='N';\n\n",
+ },
+ {
+ old: `CREATE TABLE book(id INT) ENCRYPTION = 'Y';`,
+ new: `CREATE TABLE book(id INT);`,
+ want: "ALTER TABLE `book` ENCRYPTION='N';\n\n",
+ },
+ // INSERT_METHOD
+ // TODO(zp): enable this test if the upstream repo fix it.
+ // https://github.com/pingcap/tidb/pull/38355
+ // {
+ // old: `CREATE TABLE book(id INT) INSERT_METHOD = LAST;`,
+ // new: `CREATE TABLE book(id INT) INSERT_METHOD = FIRST;`,
+ // want: "ALTER TABLE `book` INSERT_METHOD = FIRST;\n",
+ // },
+ // {
+ // old: `CREATE TABLE book(id INT) INSERT_METHOD = LAST;`,
+ // new: `CREATE TABLE book(id INT);`,
+ // want: "ALTER TABLE `book` INSERT_METHOD = NO;\n",
+ // },
+ // TODO(zp): KEY_BLOCK_SIZE
+
+ // MAX_ROWS
+ {
+ old: `CREATE TABLE book(id INT) MAX_ROWS = 100;`,
+ new: `CREATE TABLE book(id INT) MAX_ROWS = 200;`,
+ want: "ALTER TABLE `book` MAX_ROWS=200;\n\n",
+ },
+ {
+ old: `CREATE TABLE book(id INT) MAX_ROWS = 100;`,
+ new: `CREATE TABLE book(id INT);`,
+ want: "ALTER TABLE `book` MAX_ROWS=0;\n\n",
+ },
+ // MIN_ROWS
+ {
+ old: `CREATE TABLE book(id INT) MIN_ROWS = 100;`,
+ new: `CREATE TABLE book(id INT) MIN_ROWS = 200;`,
+ want: "ALTER TABLE `book` MIN_ROWS=200;\n\n",
+ },
+ {
+ old: `CREATE TABLE book(id INT) MIN_ROWS = 100;`,
+ new: `CREATE TABLE book(id INT);`,
+ want: "ALTER TABLE `book` MIN_ROWS=0;\n\n",
+ },
+ // PACK_KEYS
+ // TODO(zp): alter table pack_keys
+ {
+ old: `CREATE TABLE book(id INT) PACK_KEYS = 1;`,
+ new: `CREATE TABLE book(id INT);`,
+ want: "ALTER TABLE `book` PACK_KEYS=DEFAULT /* TableOptionPackKeys is not supported */ ;\n\n",
+ },
+ // PACK_KEYS
+ // TODO(zp): alter table pack_keys
+ {
+ old: `CREATE TABLE book(id INT) PACK_KEYS = 1;`,
+ new: `CREATE TABLE book(id INT);`,
+ want: "ALTER TABLE `book` PACK_KEYS=DEFAULT /* TableOptionPackKeys is not supported */ ;\n\n",
+ },
+ // PASSWORD
+ {
+ old: `CREATE TABLE book(id INT) PASSWORD = 'old';`,
+ new: `CREATE TABLE book(id INT) PASSWORD = 'new';`,
+ want: "ALTER TABLE `book` PASSWORD='new';\n\n",
+ },
+ {
+ old: `CREATE TABLE book(id INT) PASSWORD = 'old';`,
+ new: `CREATE TABLE book(id INT);`,
+ want: "ALTER TABLE `book` PASSWORD='';\n\n",
+ },
+ // ROW_FORMAT
+ {
+ old: `CREATE TABLE book(id INT) ROW_FORMAT = DYNAMIC;`,
+ new: `CREATE TABLE book(id INT) ROW_FORMAT = COMPRESSED;`,
+ want: "ALTER TABLE `book` ROW_FORMAT=COMPRESSED;\n\n",
+ },
+ {
+ old: `CREATE TABLE book(id INT) ROW_FORMAT = DYNAMIC;`,
+ new: `CREATE TABLE book(id INT);`,
+ want: "ALTER TABLE `book` ROW_FORMAT=DEFAULT;\n\n",
+ },
+ // STATS_AUTO_RECALC
+ {
+ old: `CREATE TABLE book(id INT) STATS_AUTO_RECALC = 1;`,
+ new: `CREATE TABLE book(id INT) STATS_AUTO_RECALC = 0;`,
+ want: "ALTER TABLE `book` STATS_AUTO_RECALC=0;\n\n",
+ },
+ {
+ old: `CREATE TABLE book(id INT) STATS_AUTO_RECALC = 1;`,
+ new: `CREATE TABLE book(id INT);`,
+ want: "ALTER TABLE `book` STATS_AUTO_RECALC=DEFAULT;\n\n",
+ },
+ // TODO(zp): STATS_PERSISTENT
+
+ // UNION
+ {
+ old: `CREATE TABLE book(id INT) UNION = (book2);`,
+ new: `CREATE TABLE book(id INT) UNION = (book2, book3);`,
+ want: "ALTER TABLE `book` UNION=(`book2`,`book3`);\n\n",
+ },
+ }
+ testDiffWithoutDisableForeignKeyCheck(t, tests)
+}
+
+func TestView(t *testing.T) {
+ tests := []testCase{
+ {
+ old: `CREATE VIEW book AS SELECT * FROM book;`,
+ new: `CREATE VIEW book AS SELECT * FROM book2;`,
+ want: "CREATE OR REPLACE ALGORITHM = UNDEFINED DEFINER = CURRENT_USER SQL SECURITY DEFINER VIEW `book` AS SELECT * FROM `book2`;\n\n",
+ },
+ {
+ old: `CREATE VIEW order_incomes AS
+ SELECT
+ order_id,
+ customer_name,
+ SUM(ordered_quantity * product_price) total
+ FROM
+ order_details
+ INNER JOIN orders USING (order_id)
+ INNER JOIN customers USING (customer_name)
+ GROUP BY order_id;`,
+
+ new: `CREATE VIEW order_incomes AS
+ SELECT
+ order_id,
+ customer_name,
+ SUM(ordered_quantity * product_price) + 1 total
+ FROM
+ order_details
+ INNER JOIN orders USING (order_id)
+ INNER JOIN customers USING (customer_name)
+ GROUP BY order_id;`,
+
+ want: "CREATE OR REPLACE ALGORITHM = UNDEFINED DEFINER = CURRENT_USER SQL SECURITY DEFINER VIEW `order_incomes` AS " +
+ "SELECT `order_id`,`customer_name`,SUM(`ordered_quantity`*`product_price`)+1 AS `total` " +
+ "FROM (`order_details` JOIN `orders` USING (`order_id`)) JOIN `customers` USING (`customer_name`) GROUP BY `order_id`;\n\n",
+ },
+ // mysqldump temporary view
+ {
+ old: `CREATE VIEW a AS SELECT 1 AS id, 1 AS name;
+ CREATE VIEW a AS SELECT id, name FROM book;
+ `,
+
+ new: `CREATE VIEW a AS SELECT 1 AS id;
+ CREATE VIEW a AS SELECT id FROM book;
+ `,
+
+ want: "CREATE OR REPLACE ALGORITHM = UNDEFINED DEFINER = CURRENT_USER SQL SECURITY DEFINER VIEW `a` AS SELECT `id` FROM `book`;\n\n",
+ },
+ // SDL for gitops dependency view
+ {
+ old: `CREATE VIEW a AS SELECT id, name FROM book`,
+ new: `CREATE VIEW a AS SELECT id FROM book;
+ CREATE VIEW b AS SELECT id FROM a;
+ `,
+ want: "CREATE OR REPLACE ALGORITHM = UNDEFINED DEFINER = CURRENT_USER SQL SECURITY DEFINER VIEW `b` AS SELECT 1 AS `id`;\n\n" +
+ "CREATE OR REPLACE ALGORITHM = UNDEFINED DEFINER = CURRENT_USER SQL SECURITY DEFINER VIEW `a` AS SELECT `id` FROM `book`;\n\n" +
+ "CREATE OR REPLACE ALGORITHM = UNDEFINED DEFINER = CURRENT_USER SQL SECURITY DEFINER VIEW `b` AS SELECT `id` FROM `a`;\n\n",
+ },
+ {
+ old: `CREATE VIEW a AS SELECT id, name FROM book`,
+ new: `CREATE VIEW a AS SELECT id AS a_id FROM book;
+ CREATE VIEW b AS SELECT a_id AS b_id FROM a;
+ `,
+ want: "CREATE OR REPLACE ALGORITHM = UNDEFINED DEFINER = CURRENT_USER SQL SECURITY DEFINER VIEW `b` AS SELECT 1 AS `b_id`;\n\n" +
+ "CREATE OR REPLACE ALGORITHM = UNDEFINED DEFINER = CURRENT_USER SQL SECURITY DEFINER VIEW `a` AS SELECT `id` AS `a_id` FROM `book`;\n\n" +
+ "CREATE OR REPLACE ALGORITHM = UNDEFINED DEFINER = CURRENT_USER SQL SECURITY DEFINER VIEW `b` AS SELECT `a_id` AS `b_id` FROM `a`;\n\n",
+ },
+ {
+ old: ``,
+ new: `CREATE VIEW a AS WITH cte AS (SELECT id, name FROM book) SELECT id, name FROM cte UNION SELECT c, d FROM e;`,
+ want: "CREATE OR REPLACE ALGORITHM = UNDEFINED DEFINER = CURRENT_USER SQL SECURITY DEFINER VIEW `a` AS SELECT 1 AS `id`,1 AS `name`;\n\n" +
+ "CREATE OR REPLACE ALGORITHM = UNDEFINED DEFINER = CURRENT_USER SQL SECURITY DEFINER VIEW `a` AS WITH `cte` AS (SELECT `id`,`name` FROM `book`) SELECT `id`,`name` FROM `cte` UNION SELECT `c`,`d` FROM `e`;\n\n",
+ },
+ }
+ testDiffWithoutDisableForeignKeyCheck(t, tests)
+}
diff --git a/backend/plugin/parser/tidb/differ_test.go b/backend/plugin/parser/tidb/differ_test.go
new file mode 100644
index 0000000000..d21c6120e9
--- /dev/null
+++ b/backend/plugin/parser/tidb/differ_test.go
@@ -0,0 +1,106 @@
+package tidb
+
+import (
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+func TestExtractUnsupportObjNameAndType(t *testing.T) {
+ tests := []struct {
+ stmt string
+ wantTp objectType
+ wantName string
+ }{
+ {
+ stmt: "CREATE DEFINER=`root`@`%` TRIGGER xcytestT \t\nBEFORE \n INSERT ON xcytest FOR EACH ROW\n BEGIN\n\tSET new.code=REPLACE(UUID(), '-', ''); \nEND ;;",
+ wantTp: trigger,
+ wantName: "xcytestT",
+ },
+ {
+ stmt: "CREATE DEFINER=`root`@`%` TRIGGER `ins_sum` BEFORE INSERT ON `account` FOR EACH SET @sum=@sum + NEW.price;;",
+ wantTp: trigger,
+ wantName: "ins_sum",
+ },
+ {
+ stmt: "create trigger `ins_sum` BEFORE INSERT ON `account` FOR EACH SET @sum=@sum + NEW.price;;",
+ wantTp: trigger,
+ wantName: "ins_sum",
+ },
+ {
+ stmt: "CREATE DEFINER=`root`@`%` PROCEDURE `citycount` (IN `country` CHAR(3), OUT `cities` INT)\n" +
+ "BEGIN\n" +
+ " SELECT COUNT(*) INTO cities FROM world.city\n" +
+ "WHERE CountryCode = country;\n" +
+ "END//",
+ wantTp: procedure,
+ wantName: "citycount",
+ },
+ {
+ stmt: "create procedure `citycount` (IN `country` CHAR(3), OUT `cities` INT)\n" +
+ "BEGIN\n" +
+ " SELECT COUNT(*) INTO cities FROM world.city\n" +
+ "WHERE CountryCode = country;\n" +
+ "END//",
+ wantTp: procedure,
+ wantName: "citycount",
+ },
+ {
+ stmt: "CREATE DEFINER=`root`@`%` FUNCTION `hello` (s CHAR(20)) RETURNS CHAR(50) DETERMINISTIC\n" +
+ "RETURN CONCAT('Hello, ',s,'!');",
+ wantTp: function,
+ wantName: "hello",
+ },
+ {
+ stmt: "create function `hello` (s CHAR(20)) RETURNS CHAR(50) DETERMINISTIC\n" +
+ "RETURN CONCAT('Hello, ',s,'!');",
+ wantTp: function,
+ wantName: "hello",
+ },
+ {
+ stmt: "CREATE DEFINER=`root`@`%` EVENT `test_event_01` ON SCHEDULE AT CURRENT_TIMESTAMP \n" +
+ "DO\n" +
+ " INSERT INTO message(message, created_at)\n" +
+ " VALUES('test event', NOW());",
+ wantTp: event,
+ wantName: "test_event_01",
+ },
+ {
+ stmt: "create event `test_event_01` ON SCHEDULE AT CURRENT_TIMESTAMP \n" +
+ "DO\n" +
+ " INSERT INTO message(message, created_at)\n" +
+ " VALUES('test event', NOW());",
+ wantTp: event,
+ wantName: "test_event_01",
+ },
+ }
+
+ a := require.New(t)
+ for _, test := range tests {
+ gotName, gotTp, err := extractUnsupportedObjectNameAndType(test.stmt)
+ a.NoError(err)
+ a.Equal(test.wantTp, gotTp)
+ a.Equal(test.wantName, gotName)
+ }
+}
+
+type testCase struct {
+ old string
+ new string
+ want string
+}
+
+func testDiffWithoutDisableForeignKeyCheck(t *testing.T, testCases []testCase) {
+ a := require.New(t)
+ for _, test := range testCases {
+ out, err := SchemaDiff(test.old, test.new, true /* ignoreCaseSensitive */)
+ a.NoError(err)
+ if len(out) > 0 {
+ a.Equal(disableFKCheckStmt, out[:len(disableFKCheckStmt)])
+ out = out[len(disableFKCheckStmt):]
+ a.Equal(enableFKCheckStmt, out[len(out)-len(enableFKCheckStmt):])
+ out = out[:len(out)-len(enableFKCheckStmt)]
+ }
+ a.Equalf(test.want, out, "old: %s\nnew: %s\n", test.old, test.new)
+ }
+}
diff --git a/backend/plugin/parser/tidb/differ_utils.go b/backend/plugin/parser/tidb/differ_utils.go
new file mode 100644
index 0000000000..7fbcfc680e
--- /dev/null
+++ b/backend/plugin/parser/tidb/differ_utils.go
@@ -0,0 +1,77 @@
+package tidb
+
+import (
+ "bytes"
+ "fmt"
+ "regexp"
+ "strings"
+
+ "github.com/pingcap/tidb/parser/ast"
+ "github.com/pingcap/tidb/parser/format"
+
+ "github.com/pkg/errors"
+)
+
+type objectType string
+
+const (
+ event objectType = "EVENT"
+ function objectType = "FUNCTION"
+ procedure objectType = "PROCEDURE"
+ trigger objectType = "TRIGGER"
+)
+
+// extractUnsupportedObjectNameAndType extract the object name from the CREATE TRIGGER/EVENT/FUNCTION/PROCEDURE statement and returns the object name and type.
+func extractUnsupportedObjectNameAndType(stmt string) (string, objectType, error) {
+ fs := []objectType{
+ function,
+ procedure,
+ }
+ regexFmt := "(?mUi)^CREATE\\s+(DEFINER=(`(.)+`|(.)+)@(`(.)+`|(.)+)(\\s)+)?%s\\s+(?P<OBJECT_NAME>%s)(\\s)*\\("
+ // We should support the naming likes "`abc`" or "abc".
+ namingRegex := fmt.Sprintf("(`%s`)|(%s)", "[^\\\\/?%*:|\\\"`<>]+", "[^\\\\/?%*:|\\\"`<>]+")
+ for _, obj := range fs {
+ regex := fmt.Sprintf(regexFmt, string(obj), namingRegex)
+ re := regexp.MustCompile(regex)
+ matchList := re.FindStringSubmatch(stmt)
+ index := re.SubexpIndex("OBJECT_NAME")
+ if index >= 0 && index < len(matchList) {
+ objectName := strings.Trim(matchList[index], "`")
+ return objectName, obj, nil
+ }
+ }
+ objects := []objectType{
+ trigger,
+ event,
+ }
+ regexFmt = "(?mUi)^CREATE\\s+(DEFINER=(`(.)+`|(.)+)@(`(.)+`|(.)+)(\\s)+)?%s\\s+(?P<OBJECT_NAME>%s)(\\s)+"
+ for _, obj := range objects {
+ regex := fmt.Sprintf(regexFmt, string(obj), namingRegex)
+ re := regexp.MustCompile(regex)
+ matchList := re.FindStringSubmatch(stmt)
+ index := re.SubexpIndex("OBJECT_NAME")
+ if index >= 0 && index < len(matchList) {
+ objectName := strings.Trim(matchList[index], "`")
+ return objectName, obj, nil
+ }
+ }
+ return "", "", errors.Errorf("cannot extract object name and type from %q", stmt)
+}
+
+func toString(node ast.Node) (string, error) {
+ var buf bytes.Buffer
+ restoreFlag := format.DefaultRestoreFlags | format.RestoreStringWithoutCharset | format.RestorePrettyFormat
+ if err := node.Restore(format.NewRestoreCtx(restoreFlag, &buf)); err != nil {
+ return "", errors.Wrapf(err, "cannot restore node %v", node)
+ }
+ return buf.String(), nil
+}
+
+func toLowerNameString(node ast.Node) (string, error) {
+ var buf bytes.Buffer
+ restoreFlag := format.DefaultRestoreFlags | format.RestoreStringWithoutCharset | format.RestorePrettyFormat | format.RestoreNameLowercase
+ if err := node.Restore(format.NewRestoreCtx(restoreFlag, &buf)); err != nil {
+ return "", errors.Wrapf(err, "cannot restore node %v", node)
+ }
+ return buf.String(), nil
+}
diff --git a/backend/plugin/parser/tidb/differ_utils_test.go b/backend/plugin/parser/tidb/differ_utils_test.go
new file mode 100644
index 0000000000..4b5812d5e2
--- /dev/null
+++ b/backend/plugin/parser/tidb/differ_utils_test.go
@@ -0,0 +1,84 @@
+package tidb
+
+import (
+ "testing"
+)
+
+func TestTrigger(t *testing.T) {
+ tests := []testCase{
+ {
+ old: `CREATE TABLE account(acct_num INT, amount DECIMAL(10,2));` +
+ "CREATE DEFINER=`root`@`%` TRIGGER `ins_sum` BEFORE INSERT ON account FOR EACH ROW SET @sum = @sum + NEW.amount;",
+ new: `CREATE TABLE account(acct_num INT, amount DECIMAL(10,2), price INT);` +
+ "CREATE DEFINER=`root`@`%` TRIGGER `ins_sum` BEFORE INSERT ON account FOR EACH ROW SET @sum = sum + NEW.amount * NEW.price;",
+ want: "ALTER TABLE `account` ADD COLUMN `price` INT AFTER `amount`;\n\n" +
+ "DROP TRIGGER IF EXISTS `ins_sum`;\n\n" +
+ "CREATE DEFINER=`root`@`%` TRIGGER `ins_sum` BEFORE INSERT ON account FOR EACH ROW SET @sum = sum + NEW.amount * NEW.price\n;\n\n",
+ },
+ }
+ testDiffWithoutDisableForeignKeyCheck(t, tests)
+}
+
+func TestFunction(t *testing.T) {
+ tests := []testCase{
+ {
+ old: "CREATE DEFINER=`root`@`%` FUNCTION `AddOne`(v INT) RETURNS int\n" +
+ "BEGIN DECLARE a INT; SET a = v; SET a = a + 1; RETURN a; END ;\n",
+ new: "CREATE DEFINER=`root`@`%` FUNCTION `AddOne`(v INT) RETURNS int\n" +
+ "BEGIN DECLARE a INT; SET a = v; SET a = a * 1 + 1; RETURN a; END ;\n",
+ want: "DROP FUNCTION IF EXISTS `AddOne`;\n\n" +
+ "CREATE DEFINER=`root`@`%` FUNCTION `AddOne`(v INT) RETURNS int\n" +
+ "BEGIN DECLARE a INT; SET a = v; SET a = a * 1 + 1; RETURN a; END\n;\n\n",
+ },
+ }
+ testDiffWithoutDisableForeignKeyCheck(t, tests)
+}
+
+func TestProcedure(t *testing.T) {
+ tests := []testCase{
+ {
+ old: "CREATE DEFINER=`admin`@`localhost` PROCEDURE `account_count`()\n" +
+ "SQL SECURITY INVOKER\n" +
+ "BEGIN\n" +
+ "SELECT 'Number of accounts:', COUNT(*) FROM mysql.user;\n" +
+ "END ;\n",
+ new: "CREATE DEFINER=`admin`@`localhost` PROCEDURE `account_count`()\n" +
+ "SQL SECURITY INVOKER\n" +
+ "BEGIN\n" +
+ "SELECT 'Number of accounts:', (COUNT(*)-1) FROM mysql.user;\n" +
+ "END ;\n",
+ want: "DROP PROCEDURE IF EXISTS `account_count`;\n\n" +
+ "CREATE DEFINER=`admin`@`localhost` PROCEDURE `account_count`()\n" +
+ "SQL SECURITY INVOKER\n" +
+ "BEGIN\n" +
+ "SELECT 'Number of accounts:', (COUNT(*)-1) FROM mysql.user;\n" +
+ "END\n;\n\n",
+ },
+ }
+ testDiffWithoutDisableForeignKeyCheck(t, tests)
+}
+
+func TestEvent(t *testing.T) {
+ tests := []testCase{
+ {
+ old: `CREATE EVENT purge_old_users
+ ON SCHEDULE EVERY 1 DAY STARTS '2023-07-01 00:00:00'
+ DO
+ DELETE FROM users WHERE age > 100;
+ `,
+ new: `CREATE EVENT purge_old_users
+ ON SCHEDULE EVERY 1 DAY STARTS '2023-07-01 00:00:00'
+ DO
+ DELETE FROM users WHERE age > 110;`,
+ want: "DROP EVENT IF EXISTS `purge_old_users`;\n\n" +
+ `CREATE EVENT purge_old_users
+ ON SCHEDULE EVERY 1 DAY STARTS '2023-07-01 00:00:00'
+ DO
+ DELETE FROM users WHERE age > 110
+;
+
+`,
+ },
+ }
+ testDiffWithoutDisableForeignKeyCheck(t, tests)
+}
diff --git a/backend/plugin/schema-engine/pg/testdata/parse_to_metadata.yaml b/backend/plugin/schema-engine/pg/testdata/parse_to_metadata.yaml
index 608a5c84c0..2fcea6507c 100644
--- a/backend/plugin/schema-engine/pg/testdata/parse_to_metadata.yaml
+++ b/backend/plugin/schema-engine/pg/testdata/parse_to_metadata.yaml
@@ -12,114 +12,115 @@
metadata:
name: ""
schemas:
- - name: public
- tables:
- - name: t
- columns:
- - name: c
- position: 0
- default: null
- nullable: true
- type: integer
- characterset: ""
- collation: ""
- comment: ""
- classification: ""
- usercomment: ""
- effectivemaskinglevel: 0
- - name: a
- position: 0
- default:
- value: "1"
- nullable: true
- type: integer
- characterset: ""
- collation: ""
- comment: this is a comment
- classification: ""
- usercomment: ""
- effectivemaskinglevel: 0
- - name: b
- position: 0
- default:
- value: '''NULL'''
- nullable: true
- type: character varying(20)
- characterset: ""
- collation: ""
- comment: ""
- classification: ""
- usercomment: ""
- effectivemaskinglevel: 0
- indexes:
- - name: t_pk
- expressions:
- - a
- - b
- type: ""
- unique: true
- primary: true
- visible: true
- comment: ""
- engine: ""
- collation: ""
- rowcount: 0
- datasize: 0
- indexsize: 0
- datafree: 0
- createoptions: ""
- comment: ""
- classification: ""
- usercomment: ""
- foreignkeys:
- - name: t_fk1
- columns:
- - a
- referencedschema: ""
- referencedtable: t2
- referencedcolumns:
- - b
- ondelete: ""
- onupdate: ""
- matchtype: ""
- - name: t2
- columns:
- - name: b
- position: 0
- default:
- value: "NULL"
- nullable: false
- type: integer
- characterset: ""
- collation: ""
- comment: ""
- classification: ""
- usercomment: ""
- effectivemaskinglevel: 0
- indexes:
- - name: t2_pk
- expressions:
- - b
- type: ""
- unique: true
- primary: true
- visible: true
- comment: ""
- engine: ""
- collation: ""
- rowcount: 0
- datasize: 0
- indexsize: 0
- datafree: 0
- createoptions: ""
- comment: ""
- classification: ""
- usercomment: ""
- foreignkeys: []
- views: []
- functions: []
- streams: []
- tasks: []
+ - name: public
+ tables:
+ - name: t
+ columns:
+ - name: c
+ position: 0
+ default: null
+ nullable: true
+ type: integer
+ characterset: ""
+ collation: ""
+ comment: ""
+ classification: ""
+ usercomment: ""
+ effectivemaskinglevel: 0
+ - name: a
+ position: 0
+ default:
+ value: "1"
+ nullable: true
+ type: integer
+ characterset: ""
+ collation: ""
+ comment: this is a comment
+ classification: ""
+ usercomment: ""
+ effectivemaskinglevel: 0
+ - name: b
+ position: 0
+ default:
+ value: '''NULL'''
+ nullable: true
+ type: character varying(20)
+ characterset: ""
+ collation: ""
+ comment: ""
+ classification: ""
+ usercomment: ""
+ effectivemaskinglevel: 0
+ indexes:
+ - name: t_pk
+ expressions:
+ - a
+ - b
+ type: ""
+ unique: true
+ primary: true
+ visible: true
+ comment: ""
+ engine: ""
+ collation: ""
+ rowcount: 0
+ datasize: 0
+ indexsize: 0
+ datafree: 0
+ createoptions: ""
+ comment: ""
+ classification: ""
+ usercomment: ""
+ foreignkeys:
+ - name: t_fk1
+ columns:
+ - a
+ referencedschema: ""
+ referencedtable: t2
+ referencedcolumns:
+ - b
+ ondelete: ""
+ onupdate: ""
+ matchtype: ""
+ - name: t2
+ columns:
+ - name: b
+ position: 0
+ default:
+ value: "NULL"
+ nullable: false
+ type: integer
+ characterset: ""
+ collation: ""
+ comment: ""
+ classification: ""
+ usercomment: ""
+ effectivemaskinglevel: 0
+ indexes:
+ - name: t2_pk
+ expressions:
+ - b
+ type: ""
+ unique: true
+ primary: true
+ visible: true
+ comment: ""
+ engine: ""
+ collation: ""
+ rowcount: 0
+ datasize: 0
+ indexsize: 0
+ datafree: 0
+ createoptions: ""
+ comment: ""
+ classification: ""
+ usercomment: ""
+ foreignkeys: []
+ views: []
+ functions: []
+ streams: []
+ tasks: []
characterset: ""
collation: ""
extensions: []
+ schemaconfigs: []
diff --git a/backend/runner/plancheck/statement_type_executor.go b/backend/runner/plancheck/statement_type_executor.go
index 0b2396ebff..d617b509b0 100644
--- a/backend/runner/plancheck/statement_type_executor.go
+++ b/backend/runner/plancheck/statement_type_executor.go
@@ -4,7 +4,7 @@ import (
"context"
"fmt"
- tidbparser "github.com/pingcap/tidb/parser"
+ tidbp "github.com/pingcap/tidb/parser"
tidbast "github.com/pingcap/tidb/parser/ast"
"github.com/pkg/errors"
@@ -16,6 +16,7 @@ import (
mysqlparser "github.com/bytebase/bytebase/backend/plugin/parser/mysql"
"github.com/bytebase/bytebase/backend/plugin/parser/sql/ast"
pgrawparser "github.com/bytebase/bytebase/backend/plugin/parser/sql/engine/pg"
+ tidbparser "github.com/bytebase/bytebase/backend/plugin/parser/tidb"
runnerutils "github.com/bytebase/bytebase/backend/runner/utils"
"github.com/bytebase/bytebase/backend/store"
"github.com/bytebase/bytebase/backend/utils"
@@ -351,7 +352,7 @@ func (e *StatementTypeExecutor) mysqlSDLTypeCheck(ctx context.Context, newSchema
if mysqlparser.IsTiDBUnsupportDDLStmt(stmt.Text) {
continue
}
- nodeList, _, err := tidbparser.New().Parse(stmt.Text, "", "")
+ nodeList, _, err := tidbp.New().Parse(stmt.Text, "", "")
if err != nil {
return nil, errors.Wrapf(err, "failed to parse schema %q", stmt.Text)
}
@@ -483,7 +484,7 @@ func mysqlCreateAndDropDatabaseCheck(nodeList []tidbast.StmtNode) []*storepb.Pla
func mysqlStatementTypeCheck(statement string, charset string, collation string, changeType storepb.PlanCheckRunConfig_ChangeDatabaseType) ([]*storepb.PlanCheckRunResult_Result, error) {
// Due to the limitation of TiDB parser, we should split the multi-statement into single statements, and extract
// the TiDB unsupported statements, otherwise, the parser will panic or return the error.
- unsupportStmt, supportStmt, err := mysqlparser.ExtractTiDBUnsupportedStmts(statement)
+ unsupportStmt, supportStmt, err := tidbparser.ExtractTiDBUnsupportedStmts(statement)
if err != nil {
// nolint:nilerr
return []*storepb.PlanCheckRunResult_Result{
@@ -506,7 +507,7 @@ func mysqlStatementTypeCheck(statement string, charset string, collation string,
// But we should ban the DELIMITER statement because go-sql-driver doesn't support it.
hasUnsupportDDL := len(unsupportStmt) > 0
- p := tidbparser.New()
+ p := tidbp.New()
// To support MySQL8 window function syntax.
// See https://github.com/bytebase/bytebase/issues/175.
p.EnableWindowFunc(true)