Skip to content

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

feat: migrate mysql sync schema to mysql parser (#8603)

zll600ce0d3f0a2bed
diff --git a/backend/plugin/parser/mysql/compatible.go b/backend/plugin/parser/mysql/compatible.go
deleted file mode 100644
index cad48571f3..0000000000
--- a/backend/plugin/parser/mysql/compatible.go
+++ /dev/null
@@ -1,116 +0,0 @@
-package mysql
-
-import (
- "bytes"
- "fmt"
- "regexp"
- "strconv"
-
- tidbparser "github.com/pingcap/tidb/parser"
- "github.com/pingcap/tidb/parser/ast"
- "github.com/pkg/errors"
-
- "github.com/bytebase/bytebase/backend/plugin/parser/base"
-)
-
-// 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 := 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
-}
-
-// 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`
-// 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/mysql/compatible_test.go b/backend/plugin/parser/mysql/compatible_test.go
deleted file mode 100644
index c06ffc1171..0000000000
--- a/backend/plugin/parser/mysql/compatible_test.go
+++ /dev/null
@@ -1,142 +0,0 @@
-package mysql
-
-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/mysql/differ.go b/backend/plugin/parser/mysql/differ.go
index 6ff1cf7b37..c9799fb65a 100644
--- a/backend/plugin/parser/mysql/differ.go
+++ b/backend/plugin/parser/mysql/differ.go
@@ -1,29 +1,16 @@
-// Package mysql provides the MySQL differ plugin.
package mysql
import (
- "bytes"
"fmt"
- "io"
- "log/slog"
"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/antlr4-go/antlr/v4"
+ mysql "github.com/bytebase/mysql-parser"
"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() {
@@ -36,967 +23,645 @@ const (
enableFKCheckStmt string = "SET FOREIGN_KEY_CHECKS=1;\n"
)
+// SchemaDiffer is the parser for MySQL dialect.
+type SchemaDiffer struct {
+}
+
+// SchemaDiff returns the schema diff.
+// It only supports schema information from mysqldump.
+func SchemaDiff(oldStmt, newStmt string, ignoreCaseSensitive bool) (string, error) {
+ // 1. Preprocessing Stage.
+ diff := &diffNode{
+ ignoreCaseSensitive: ignoreCaseSensitive,
+ }
+ if err := diff.diffStatement(oldStmt, newStmt); err != nil {
+ return "", err
+ }
+
+ return diff.deparse()
+}
+
// 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
+ dropFunctionList []*functionDef
+ dropProcedureList []*procedureDef
+ dropEventList []*eventDef
+ dropTriggerList []*triggerDef
+
+ dropForeignKeyList []*foreignKeyDef
+ dropCheckConstraintList []*checkDef
+ dropPrimaryKeyList []*primaryKeyDef
+ dropIndexList []*indexDef
+ dropIndexConstraintList []*indexConstraintDef
+ dropViewList []*viewDef
+ dropTableList []*tableDef
+
+ createTableList []*tableDef
+ alterTableOptionList []*tableOptionDef
+ addColumnList []*columnDef
+ modifyColumnList []*columnDef
+ dropColumnList []*columnDef
+
+ createTempViewList []*viewDef
+ createIndexList []*indexDef
+ createIndexConstraintList []*indexConstraintDef
+ createPrimaryKeyList []*primaryKeyDef
+ addCheckConstraintList []*checkDef
+ addForeignKeyList []*foreignKeyDef
+ createViewList []*viewDef
+
+ createEventList []*eventDef
+ createTriggerList []*triggerDef
+ createFunctionList []*functionDef
+ createProcedureList []*procedureDef
}
-func (diff *diffNode) diffSupportedStatement(oldStatement, newStatement string) error {
- oldNodeList, _, err := parser.New().Parse(oldStatement, "", "")
+func (diff *diffNode) diffStatement(oldStatement string, newStatement string) error {
+ oldDatabaseDef, err := diff.buildSchemaInfo(oldStatement)
if err != nil {
return errors.Wrapf(err, "failed to parse old statement %q", oldStatement)
}
- newNodeList, _, err := parser.New().Parse(newStatement, "", "")
+
+ newDatabaseDef, err := diff.buildSchemaInfo(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
+ if err := diff.diffTables(oldDatabaseDef, newDatabaseDef); err != nil {
+ return errors.Wrapf(err, "failed to diff view")
}
- newSchemaInfo, err := diff.buildSchemaInfo(newNodeList)
- if err != nil {
- return err
+
+ if err := diff.diffView(oldDatabaseDef, newDatabaseDef); err != nil {
+ return errors.Wrapf(err, "failed to diff view")
}
- 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)
+ if err := diff.diffFunction(oldDatabaseDef, newDatabaseDef); err != nil {
+ return errors.Wrapf(err, "failed to diff function")
}
- for _, oldTable := range oldSchemaInfo.tableMap {
- diff.dropTableList = append(diff.dropTableList, &ast.DropTableStmt{
- IfExists: true,
- Tables: []*ast.TableName{oldTable.createTable.Table},
- })
+ if err := diff.diffProcedure(oldDatabaseDef, newDatabaseDef); err != nil {
+ return errors.Wrapf(err, "failed to diff procedure")
}
- var newViewList []*ast.CreateViewStmt
- for _, newNode := range newNodeList {
- if newView, ok := newNode.(*ast.CreateViewStmt); ok {
- newViewList = append(newViewList, newView)
- }
+ if err := diff.diffEvent(oldDatabaseDef.schemas[""], newDatabaseDef.schemas[""]); err != nil {
+ return errors.Wrapf(err, "failed to diff event")
}
- if err := diff.diffView(oldSchemaInfo.viewMap, newSchemaInfo.viewMap, newViewList); err != nil {
- return errors.Wrapf(err, "failed to diff view")
+ if err := diff.diffTrigger(oldDatabaseDef.schemas[""], newDatabaseDef.schemas[""]); err != nil {
+ return errors.Wrapf(err, "failed to diff trigger")
}
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)
+func (diff *diffNode) diffTables(oldDatabase, newDatabase *databaseDef) error {
+ for newTableName, newTable := range newDatabase.schemas[""].tables {
+ oldTable, exists := oldDatabase.schemas[""].tables[newTableName]
+ if !exists {
+ diff.createTableList = append(diff.createTableList, newTable)
+ // Create indexes.
+ for _, index := range newTable.indexes {
+ diff.createIndexList = append(diff.createIndexList, index)
}
- tempViewList = append(tempViewList, tempViewStmt)
- createViewStmt := *view
- createViewStmt.OrReplace = true
- viewList = append(viewList, &createViewStmt)
+ continue
}
+ diff.diffTable(oldTable, newTable)
+ delete(oldDatabase.schemas[""].tables, newTableName)
}
- 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)
+ for _, oldTable := range oldDatabase.schemas[""].tables {
+ diff.dropTableList = append(diff.dropTableList, oldTable)
}
+
return nil
}
-func (diff *diffNode) diffTable(oldTable, newTable *tableInfo) {
- diff.diffTableOption(oldTable, newTable)
+func (diff *diffNode) diffTable(oldTable, newTable *tableDef) {
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.diffPrimaryKey(oldTable, newTable)
+ diff.diffIndexConstraint(oldTable, newTable)
+ diff.diffForeignKey(oldTable, newTable)
+ diff.diffCheckConstraint(oldTable, newTable)
+ diff.diffTableOptions(oldTable, newTable)
+}
+
+func (diff *diffNode) diffCheckConstraint(oldTable, newTable *tableDef) {
+ for constraintName, constraint := range newTable.checks {
+ if oldConstraint, ok := oldTable.checks[strings.ToLower(constraintName)]; ok {
+ if !isCheckConstraintEqual(oldConstraint, constraint) {
+ diff.dropCheckConstraintList = append(diff.dropCheckConstraintList, oldConstraint)
+ diff.addCheckConstraintList = append(diff.addCheckConstraintList, constraint)
}
- diff.addConstraintExceptFkList = append(diff.addConstraintExceptFkList, &ast.AlterTableStmt{
- Table: newTable.createTable.Table,
- Specs: []*ast.AlterTableSpec{
- {
- Tp: ast.AlterTableAddConstraint,
- Constraint: constraint,
- },
- },
- })
+ delete(oldTable.checks, strings.ToLower(constraintName))
+ continue
}
+ diff.addCheckConstraintList = append(diff.addCheckConstraintList, 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,
- },
- },
- })
- }
+ for _, constraint := range oldTable.checks {
+ diff.dropCheckConstraintList = append(diff.dropCheckConstraintList, constraint)
}
}
-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)
+func isCheckConstraintEqual(old, new *checkDef) bool {
+ if !strings.EqualFold(old.name, new.name) {
+ return false
}
- for _, oldIndex := range oldTable.indexMap {
- diff.dropIndexList = append(diff.dropIndexList, &ast.DropIndexStmt{
- IndexName: oldIndex.createIndex.IndexName,
- Table: oldIndex.createIndex.Table,
- })
+ if old.ctx.GetText() != new.ctx.GetText() {
+ return false
}
+
+ return true
}
-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]
+func (diff *diffNode) diffTableOptions(oldTable, newTable *tableDef) {
+ for oldTp, oldOption := range oldTable.tableOptions {
+ newOption, ok := newTable.tableOptions[oldTp]
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)}
+ switch oldTp {
+ // For table engine, table charset and table collation, if oldTable has but newTable doesn't,
+ // we skip drop them.
+ case "ENGINE", "DEFAULT COLLATE", "DEFAULT CHARACTER SET":
+ continue
}
- 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)}
+ // We should drop the table option if it doesn't exist in the new table options.
+ if astOption := dropTableOption(oldOption); astOption != nil {
+ diff.alterTableOptionList = append(diff.alterTableOptionList, astOption)
}
+ continue
}
- // 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,
- })
+ if !isTableOptionEqual(oldOption, newOption) {
+ diff.alterTableOptionList = append(diff.alterTableOptionList, newOption)
}
- 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)
+ for newTp, newOption := range newTable.tableOptions {
+ if _, ok := oldTable.tableOptions[newTp]; !ok {
+ diff.alterTableOptionList = append(diff.alterTableOptionList, newOption)
+ }
}
}
-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 dropTableOption(oldOption *tableOptionDef) *tableOptionDef {
+ switch oldOption.option {
+ case "ENGINE":
+ oldOption.alterOption = fmt.Sprintf("ALTER TABLE `%s` ENGINE = InnoDB;", oldOption.tableName)
+ case "SECONDARY_ENGINE_ATTRIBUTE":
+ oldOption.alterOption = fmt.Sprintf("ALTER TABLE `%s` SECONDARY_ENGINE_ATTRIBUTE = InnoDB;", oldOption.tableName)
+ case "DEFAULT CHARACTER SET":
+ oldOption.alterOption = fmt.Sprintf("ALTER TABLE `%s` CHARACTER SET = DEFAULT;", oldOption.tableName)
+ case "DEFAULT COLLATE":
+ oldOption.alterOption = fmt.Sprintf("ALTER TABLE `%s` DEFAULT COLLATE = utf8mb4_general_ci;", oldOption.tableName)
+ case "AUTO_INCREMENT":
+ oldOption.alterOption = fmt.Sprintf("ALTER TABLE `%s` AUTO_INCREMENT = 0;", oldOption.tableName)
+ case "COMMENT":
+ oldOption.alterOption = fmt.Sprintf("ALTER TABLE `%s` COMMENT = '';", oldOption.tableName)
+ case "AVG_ROW_LENGTH":
+ oldOption.alterOption = fmt.Sprintf("ALTER TABLE `%s` AVG_ROW_LENGTH = 0;", oldOption.tableName)
+ case "CHECKSUM":
+ oldOption.alterOption = fmt.Sprintf("ALTER TABLE `%s` CHECKSUM = 0;", oldOption.tableName)
+ case "COMPRESSION":
+ oldOption.alterOption = fmt.Sprintf("ALTER TABLE `%s` COMPRESSION = 'None';", oldOption.tableName)
+ case "CONNECTION":
+ oldOption.alterOption = fmt.Sprintf("ALTER TABLE `%s` CONNECTION = '';", oldOption.tableName)
+ case "PASSWORD":
+ case "KEY_BLOCK_SIZE":
+ case "MAX_ROWS":
+ oldOption.alterOption = fmt.Sprintf("ALTER TABLE `%s` MAX_ROWS = 0;", oldOption.tableName)
+ case "MIN_ROWS":
+ oldOption.alterOption = fmt.Sprintf("ALTER TABLE `%s` MIN_ROWS = 0;", oldOption.tableName)
+ case "DELAY_KEY_WRITE":
+ oldOption.alterOption = fmt.Sprintf("ALTER TABLE `%s` DELAY_KEY_WRITE = 0;", oldOption.tableName)
+ case "ROW_FORMAT":
+ oldOption.alterOption = fmt.Sprintf("ALTER TABLE `%s` ROW_FORMAT = DEFAULT;", oldOption.tableName)
+ case "STATS_AUTO_RECALC":
+ oldOption.alterOption = fmt.Sprintf("ALTER TABLE `%s` STATS_AUTO_RECALC = DEFAULT;", oldOption.tableName)
+ case "PACK_KEYS":
+ oldOption.alterOption = fmt.Sprintf("ALTER TABLE `%s` PACK_KEYS = DEFAULT;", oldOption.tableName)
+ case "TABLESPACE":
+ case "INSERT_METHOD":
+ oldOption.alterOption = fmt.Sprintf("ALTER TABLE `%s` INSERT_METHOD = NO;", oldOption.tableName)
+ case "TABLE_CHECKSUM":
+ case "UNION":
+ case "ENCRYPTION":
+ oldOption.alterOption = fmt.Sprintf("ALTER TABLE `%s` ENCRYPTION = 'N';", oldOption.tableName)
+ }
+ return oldOption
+}
+
+// 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 isTableOptionEqual(oldOption, newOption *tableOptionDef) bool {
+ if oldOption.option == "DEFAULT CHARACTER SET" {
+ return oldOption.ctx.DefaultCharset().CharsetName().GetText() == newOption.ctx.DefaultCharset().CharsetName().GetText()
}
+ return oldOption.ctx.GetText() == newOption.ctx.GetText()
}
-func (diff *diffNode) deparse() (string, error) {
- var buf bytes.Buffer
- flag := format.DefaultRestoreFlags | format.RestoreStringWithoutCharset | format.RestorePrettyFormat
+func (diff *diffNode) diffPrimaryKey(oldTable, newTable *tableDef) {
+ oldPrimaryKey := oldTable.primaryKey
+ newPrimaryKey := newTable.primaryKey
+ if oldPrimaryKey == nil && newPrimaryKey == nil {
+ return
+ } else if oldPrimaryKey != nil && newPrimaryKey == nil {
+ diff.dropPrimaryKeyList = append(diff.dropPrimaryKeyList, oldPrimaryKey)
+ return
+ } else if oldPrimaryKey == nil && newPrimaryKey != nil {
+ diff.createPrimaryKeyList = append(diff.createPrimaryKeyList, newPrimaryKey)
+ return
+ }
+ if !isPrimaryKeyEqual(oldPrimaryKey, newPrimaryKey) {
+ diff.dropPrimaryKeyList = append(diff.dropPrimaryKeyList, oldPrimaryKey)
+ diff.createPrimaryKeyList = append(diff.createPrimaryKeyList, newPrimaryKey)
+ }
+}
- 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
- }
+// isPrimaryKeyEqual returns true if definitions of two priamry indexes are the same.
+func isPrimaryKeyEqual(old, new *primaryKeyDef) bool {
+ if old.tableName != new.tableName {
+ return false
}
- if err := sortAndWriteNodeList(&buf, diff.dropForeignKeyList, flag); err != nil {
- return "", err
+ if !isKeyPartEqual(old.columns, new.columns) {
+ return false
}
- if err := sortAndWriteNodeList(&buf, diff.dropConstraintExceptFkList, flag); err != nil {
- return "", err
+ if old.ctx.GetText() != new.ctx.GetText() {
+ return false
}
- if err := sortAndWriteNodeList(&buf, diff.dropIndexList, flag); err != nil {
- return "", err
+ return true
+}
+
+func (diff *diffNode) diffForeignKey(oldTable, newTable *tableDef) {
+ for _, foreignKey := range newTable.foreignKeys {
+ if oldForeignKey, ok := oldTable.foreignKeys[strings.ToLower(foreignKey.name)]; ok {
+ if !isForeignKeyEqual(oldForeignKey, foreignKey) {
+ diff.dropForeignKeyList = append(diff.dropForeignKeyList, oldForeignKey)
+ diff.addForeignKeyList = append(diff.addForeignKeyList, foreignKey)
+ }
+ delete(oldTable.foreignKeys, strings.ToLower(foreignKey.name))
+ continue
+ }
+ diff.addForeignKeyList = append(diff.addForeignKeyList, foreignKey)
}
- if err := sortAndWriteNodeList(&buf, diff.dropViewList, flag); err != nil {
- return "", err
+ for _, foreignKey := range oldTable.foreignKeys {
+ diff.dropForeignKeyList = append(diff.dropForeignKeyList, foreignKey)
}
- if err := sortAndWriteNodeList(&buf, diff.dropTableList, flag); err != nil {
- return "", err
+}
+
+// isForeignKeyEqual returns true if two foreign keys are the same.
+func isForeignKeyEqual(old, new *foreignKeyDef) bool {
+ if old.name != new.name {
+ return false
}
- if err := sortAndWriteNodeList(&buf, diff.createTableList, flag); err != nil {
- return "", err
+ if !isKeyPartEqual(old.columns, new.columns) {
+ return false
}
- if err := sortAndWriteNodeList(&buf, diff.alterTableOptionList, flag); err != nil {
- return "", err
+ if !isKeyPartEqual(old.referencedColumns, new.referencedColumns) {
+ return false
}
- if err := sortAndWriteNodeList(&buf, diff.addAndModifyColumnList, flag); err != nil {
- return "", err
+ if old.referencedTable != new.referencedTable {
+ return false
}
- if err := sortAndWriteNodeList(&buf, diff.dropColumnList, flag); err != nil {
- return "", err
+ return true
+}
+
+func (diff *diffNode) diffView(oldDatabase, newDatabase *databaseDef) error {
+ var tempViewList []*viewDef
+ for _, view := range newDatabase.schemas[""].views {
+ viewName := view.name
+ if diff.ignoreCaseSensitive {
+ viewName = strings.ToLower(viewName)
+ }
+
+ oldView, ok := oldDatabase.schemas[""].views[viewName]
+ if ok {
+ if !diff.isViewEqual(view, oldView) {
+ diff.createViewList = append(diff.createViewList, view)
+ }
+ // We should delete the view in the oldViewMap, because we will drop the all views in the oldViewMap explicitly at last.
+ delete(oldDatabase.schemas[""].views, viewName)
+ } else {
+ // We should create the view.
+ // We create the temporary view first and replace it to avoid break the dependency like mysqldump does.
+ tempView, err := getTempView(view)
+ if err != nil {
+ return errors.Wrapf(err, "failed to get temporary view for view %s", view.name)
+ }
+ tempViewList = append(tempViewList, tempView)
+ diff.createViewList = append(diff.createViewList, view)
+ }
}
- if err := sortAndWriteNodeList(&buf, diff.createTempViewList, flag); err != nil {
- return "", err
+ diff.createTempViewList = append(diff.createTempViewList, tempViewList...)
+ for _, view := range oldDatabase.schemas[""].views {
+ diff.dropViewList = append(diff.dropViewList, view)
}
- if err := sortAndWriteNodeList(&buf, diff.createIndexList, flag); err != nil {
- return "", err
+ return nil
+}
+
+// getTempView returns the temporary view name and the create statement.
+func getTempView(view *viewDef) (*viewDef, 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.
+ algorithm := "UNDEFINED"
+ if view.ctx.ViewReplaceOrAlgorithm() != nil {
+ if algo := view.ctx.ViewReplaceOrAlgorithm().ViewAlgorithm(); algo != nil {
+ algorithm = algo.GetAlgorithm().GetText()
+ }
}
- if err := sortAndWriteNodeList(&buf, diff.addConstraintExceptFkList, flag); err != nil {
- return "", err
+ definer := "CURRENT_USER"
+ if view.ctx.DefinerClause() != nil {
+ definer = view.ctx.DefinerClause().GetText()
}
- if err := sortAndWriteNodeList(&buf, diff.addForeignKeyList, flag); err != nil {
- return "", err
+ sqlSecurity := "DEFINER"
+ if view.ctx.ViewSuid() != nil {
+ if view.ctx.ViewSuid().INVOKER_SYMBOL() != nil {
+ sqlSecurity = "INVOKER"
+ }
}
- if err := sortAndWriteNodeList(&buf, diff.createViewList, flag); err != nil {
- return "", err
+ var selectClause strings.Builder
+ if _, err := selectClause.WriteString("SELECT SQL_NO_CACHE"); err != nil {
+ return nil, err
}
-
- sort.Strings(diff.createUnsupportedStatement)
- for _, statement := range diff.createUnsupportedStatement {
- if _, err := buf.WriteString(statement); err != nil {
- return "", err
+ for idx, column := range view.columns {
+ if idx > 0 {
+ if _, err := selectClause.WriteString(","); err != nil {
+ return nil, err
+ }
}
- if _, err := buf.WriteString("\n\n"); err != nil {
- return "", err
+ if _, err := selectClause.WriteString(fmt.Sprintf(" 1 AS `%s`", column)); err != nil {
+ return nil, 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
+ cols := ""
+ if view.ctx.ViewTail() != nil {
+ if list := view.ctx.ViewTail().ColumnInternalRefList(); list != nil {
+ cols = list.GetParser().GetTokenStream().GetTextFromRuleContext(list.GetRuleContext())
}
}
-
- 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
- }
+ var viewSQL string
+ if cols == "" {
+ viewSQL = fmt.Sprintf("CREATE OR REPLACE ALGORITHM=%s DEFINER=%s SQL SECURITY %s VIEW `%s` AS %s;\n\n", algorithm, definer, sqlSecurity, view.name, selectClause.String())
+ } else {
+ viewSQL = fmt.Sprintf("CREATE OR REPLACE ALGORITHM=%s DEFINER=%s SQL SECURITY %s VIEW `%s` %s AS %s;\n\n", algorithm, definer, sqlSecurity, view.name, cols, selectClause.String())
}
- text := buf.String()
- if len(text) > 0 {
- return fmt.Sprintf("%s%s%s", disableFKCheckStmt, buf.String(), enableFKCheckStmt), nil
+ newView := &viewDef{
+ ctx: view.ctx,
+ name: view.name,
+ dbName: view.dbName,
}
- return "", nil
+ newView.tempView = viewSQL
+ return newView, nil
}
-// constraintMap returns a map of constraint name to constraint.
-type constraintMap map[string]*ast.Constraint
+func (diff *diffNode) diffFunction(oldDatabase, newDatabase *databaseDef) error {
+ for _, function := range newDatabase.schemas[""].functions {
+ functionName := function.name
-// 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
+ oldFunction, ok := oldDatabase.schemas[""].functions[functionName]
+ if ok {
+ if !isFunctionEqual(oldFunction, function) {
+ diff.dropFunctionList = append(diff.dropFunctionList, oldFunction)
+ }
+ delete(oldDatabase.schemas[""].functions, functionName)
+ }
+ diff.createFunctionList = append(diff.createFunctionList, function)
}
- diff := &diffNode{
- ignoreCaseSensitive: ignoreCaseSensitive,
- }
- if err := diff.diffSupportedStatement(oldSupportedStmt, newSupportedStmt); err != nil {
- return "", err
- }
- if err := diff.diffUnsupportedStatement(oldUnsupportedStmtList, newUnsupportedStmtList); err != nil {
- return "", err
+ for _, function := range oldDatabase.schemas[""].functions {
+ diff.dropFunctionList = append(diff.dropFunctionList, function)
}
-
- return diff.deparse()
+ return nil
}
-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
+func isFunctionEqual(old, new *functionDef) bool {
+ return old.ctx.GetText() == new.ctx.GetText()
}
-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 (diff *diffNode) diffProcedure(oldDatabase, newDatabase *databaseDef) error {
+ for _, procedure := range newDatabase.schemas[""].procedures {
+ procedureName := procedure.name
-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)
+ oldProcedure, ok := oldDatabase.schemas[""].procedures[procedureName]
+ if ok {
+ if !isProcedureEqual(oldProcedure, procedure) {
+ diff.dropProcedureList = append(diff.dropProcedureList, oldProcedure)
}
+ delete(oldDatabase.schemas[""].functions, procedureName)
}
- 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()
+ diff.createProcedureList = append(diff.createProcedureList, procedure)
}
- 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
- }
+ for _, procedure := range oldDatabase.schemas[""].procedures {
+ diff.dropProcedureList = append(diff.dropProcedureList, procedure)
}
return nil
}
-type schemaInfo struct {
- tableMap tableMap
- viewMap viewMap
+func isProcedureEqual(old, new *procedureDef) bool {
+ return old.ctx.GetText() == new.ctx.GetText()
}
-type viewMap map[string]*ast.CreateViewStmt
+func (diff *diffNode) diffEvent(oldSchema, newSchema *schemaDef) error {
+ for _, event := range newSchema.events {
+ eventName := event.name
-type indexInfo struct {
- createIndex *ast.CreateIndexStmt
-}
-type indexMap map[string]*indexInfo
-
-func newIndexInfo(createIndex *ast.CreateIndexStmt) *indexInfo {
- return &indexInfo{
- createIndex: createIndex,
+ oldEvent, ok := oldSchema.events[eventName]
+ if ok {
+ if !isEventEqual(oldEvent, event) {
+ diff.dropEventList = append(diff.dropEventList, oldEvent)
+ }
+ delete(oldSchema.events, eventName)
+ }
+ diff.createEventList = append(diff.createEventList, event)
+ }
+ for _, event := range oldSchema.events {
+ diff.dropEventList = append(diff.dropEventList, event)
}
+ return nil
}
-type tableInfo struct {
- createTable *ast.CreateTableStmt
- indexMap indexMap
+func isEventEqual(old, new *eventDef) bool {
+ return old.ctx.GetText() == new.ctx.GetText()
}
-type tableMap map[string]*tableInfo
-func newTableInfo(createTable *ast.CreateTableStmt) (*tableInfo, error) {
- result := &tableInfo{
- createTable: createTable,
- indexMap: make(indexMap),
- }
+func (diff *diffNode) diffTrigger(oldSchema, newSchema *schemaDef) error {
+ for _, trigger := range newSchema.triggers {
+ triggerName := trigger.name
- 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())
+ oldTrigger, ok := oldSchema.triggers[triggerName]
+ if ok {
+ if !isTriggerEqual(oldTrigger, trigger) {
+ diff.dropTriggerList = append(diff.dropTriggerList, oldTrigger)
}
- result.indexMap[strings.ToLower(constraint.Name)] = newIndexInfo(createIndex)
- } else {
- newConstraintList = append(newConstraintList, constraint)
+ delete(oldSchema.triggers, triggerName)
}
+ diff.createTriggerList = append(diff.createTriggerList, trigger)
}
- createTable.Constraints = newConstraintList
-
- return result, nil
+ for _, trigger := range oldSchema.triggers {
+ diff.dropTriggerList = append(diff.dropTriggerList, trigger)
+ }
+ return 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
+func isTriggerEqual(old, new *triggerDef) bool {
+ return old.ctx.GetText() == new.ctx.GetText()
}
-// 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())
+func (diff *diffNode) diffColumn(oldTable, newTable *tableDef) {
+ // 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.
+ newColumns := convertColumnMapToSortedList(newTable.columns)
+ oldColumns := convertColumnMapToSortedList(oldTable.columns)
+ for idx, newColumnDef := range newColumns {
+ newColumnName := newColumnDef.name
+ oldColumnDef, ok := oldTable.columns[newColumnName]
+ if !ok {
+ // create
+ columnPosition := &columnPositionDef{
+ tp: "FIRST",
}
- // 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())
+ if idx > 0 {
+ columnPosition.tp = "AFTER"
+ columnPosition.relativeColumn = newColumns[idx-1].name
}
- table.indexMap[strings.ToLower(stmt.IndexName)] = newIndexInfo(stmt)
- case *ast.CreateViewStmt:
- viewName := stmt.ViewName.Name.O
- if diff.ignoreCaseSensitive {
- viewName = stmt.ViewName.Name.L
+ newColumnDef.columnPosition = columnPosition
+ diff.addColumnList = append(diff.addColumnList, newColumnDef)
+ continue
+ }
+ // update
+ columnPosition := &columnPositionDef{}
+ if hasColumnsIntersection(oldColumns[:oldColumnDef.id], newColumns[idx+1:]) {
+ if idx == 0 {
+ columnPosition.tp = "FIRST"
+ } else {
+ columnPosition.tp = "AFTER"
+ columnPosition.relativeColumn = newColumns[idx-1].name
}
- result.viewMap[viewName] = stmt
- default:
}
+ newColumnDef.columnPosition = columnPosition
+ if !isColumnEqual(oldColumnDef, newColumnDef) {
+ diff.modifyColumnList = append(diff.modifyColumnList, newColumnDef)
+ }
+
+ delete(oldTable.columns, newColumnName)
+ }
+
+ // drop
+ for _, column := range oldTable.columns {
+ diff.dropColumnList = append(diff.dropColumnList, column)
}
- 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
+func convertColumnMapToSortedList(columns map[string]*columnDef) (newColumns []*columnDef) {
+ for _, column := range columns {
+ newColumns = append(newColumns, column)
}
- return m, nil
+ sort.Slice(newColumns, func(i, j int) bool {
+ return newColumns[i].id < newColumns[j].id
+ })
+ return newColumns
}
-// 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),
- })
+// hasColumnsIntersection returns true if two column slices have column name intersection.
+func hasColumnsIntersection(a, b []*columnDef) bool {
+ bMap := make(map[string]bool)
+ for _, col := range b {
+ // MySQL column name is case insensitive.
+ bMap[col.name] = true
+ }
+ for _, col := range a {
+ // MySQL column name is case insensitive.
+ if _, ok := bMap[col.name]; ok {
+ return true
}
}
+ return false
+}
- 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
+func (diff *diffNode) diffIndexConstraint(oldTable, newTable *tableDef) {
+ // https://stackoverflow.com/questions/887590/does-dropping-a-table-in-mysql-also-drop-the-indexes
+ for indexName, newIndex := range newTable.indexConstraints {
+ if oldIndex, ok := oldTable.indexConstraints[indexName]; ok {
+ if !isIndexConstraintEqual(newIndex, oldIndex) {
+ diff.dropIndexConstraintList = append(diff.dropIndexConstraintList, oldIndex)
+ diff.createIndexConstraintList = append(diff.createIndexConstraintList, newIndex)
}
- 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")
+ delete(oldTable.indexConstraints, indexName)
+ continue
}
- return nil, errors.Errorf("unsupported create view statement %q which select is not supported node", stmtStr)
+ diff.createIndexConstraintList = append(diff.createIndexConstraintList, newIndex)
}
-}
-// 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
+ for _, oldIndex := range oldTable.indexConstraints {
+ diff.dropIndexConstraintList = append(diff.dropIndexConstraintList, oldIndex)
}
- 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
+func isIndexConstraintEqual(new, old *indexConstraintDef) bool {
+ if old.name != new.name {
+ return false
}
- 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:
- }
+ if old.ctx.GetText() != new.ctx.GetText() {
+ return false
}
- return primaryKey, constraintMap
+ return true
}
-// 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
+func (diff *diffNode) diffIndex(oldTable, newTable *tableDef) {
+ // https://stackoverflow.com/questions/887590/does-dropping-a-table-in-mysql-also-drop-the-indexes
+ for indexName, newIndex := range newTable.indexes {
+ if oldIndex, ok := oldTable.indexes[indexName]; ok {
+ if !isIndexEqual(newIndex, oldIndex) {
+ diff.dropIndexList = append(diff.dropIndexList, oldIndex)
+ diff.createIndexList = append(diff.createIndexList, newIndex)
+ }
+ delete(oldTable.indexes, indexName)
+ continue
+ }
+ diff.createIndexList = append(diff.createIndexList, newIndex)
}
- if !isColumnOptionsEqual(old.Options, new.Options) {
- return false
+
+ for _, oldIndex := range oldTable.indexes {
+ diff.dropIndexList = append(diff.dropIndexList, oldIndex)
}
- return true
}
-func isColumnTypesEqual(old, new *ast.ColumnDef) bool {
- return old.Tp.String() == new.Tp.String()
+func (diff *diffNode) buildSchemaInfo(statement string) (*databaseDef, error) {
+ return diff.parseMySQLSchemaStringToSchemDef(statement)
}
-func isColumnOptionsEqual(old, new []*ast.ColumnOption) bool {
- oldCollate, oldNormalizeOptions := normalizeColumnOptions(old)
- newCollate, newNormalizeOptions := normalizeColumnOptions(new)
- if len(oldNormalizeOptions) != len(newNormalizeOptions) {
+// isViewEqual checks whether two views with same name are equal.
+func (*diffNode) isViewEqual(old, new *viewDef) bool {
+ if old.name != new.name {
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
- }
+
+ if old.ctx.GetText() != new.ctx.GetText() {
+ 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
+// isColumnEqual returns true if definitions of two columns with the same name are the same.
+func isColumnEqual(old, new *columnDef) bool {
+ // column name
+ return old.ctx.GetText() == new.ctx.GetText()
}
// isIndexEqual returns true if definitions of two indexes are the same.
-func isIndexEqual(old, new *ast.CreateIndexStmt) bool {
+func isIndexEqual(old, new *indexDef) bool {
// CREATE [UNIQUE | FULLTEXT | SPATIAL] INDEX index_name
// [index_type]
// ON tbl_name (key_part,...)
@@ -1004,585 +669,1486 @@ func isIndexEqual(old, new *ast.CreateIndexStmt) bool {
// [algorithm_option | lock_option] ...
// MySQL index names are case insensitive.
- if !strings.EqualFold(old.IndexName, new.IndexName) {
+ if !strings.EqualFold(old.name, new.name) {
return false
}
- if (old.IndexOption == nil) != (new.IndexOption == nil) {
+ if old.ctx.GetText() != new.ctx.GetText() {
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) {
+func isKeyPartEqual(old, new []string) bool {
+ if len(old) != len(new) {
return false
}
- if old.Option != nil && new.Option != nil {
- if old.Option.Tp != new.Option.Tp {
+
+ for idx, oldKey := range old {
+ if oldKey != new[idx] {
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
+func (diff *diffNode) deparse() (string, error) {
+ var buf strings.Builder
+ if err := sortAndWriteDropFunctionList(&buf, diff.dropFunctionList); err != nil {
+ return "", err
}
- // 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.
+ if err := sortAndWriteDropProcedureList(&buf, diff.dropProcedureList); err != nil {
+ return "", err
+ }
+ if err := sortAndWriteDropEventList(&buf, diff.dropEventList); err != nil {
+ return "", err
+ }
+ if err := sortAndWriteDropTriggerList(&buf, diff.dropTriggerList); err != nil {
+ return "", err
}
- 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 err := sortAndWriteDropForeignKeyList(&buf, diff.dropForeignKeyList); err != nil {
+ return "", err
+ }
+ if err := sortAndWriteDropCheckConstraintList(&buf, diff.dropCheckConstraintList); err != nil {
+ return "", err
}
- if old == nil && new == nil {
- return true
+ if err := sortAndWriteDropPrimaryIndexList(&buf, diff.dropPrimaryKeyList); err != nil {
+ return "", err
}
- if old.KeyBlockSize != new.KeyBlockSize {
- return false
+ if err := sortAndWriteDropIndexList(&buf, diff.dropIndexList); err != nil {
+ return "", err
}
- if old.Tp != new.Tp {
- return false
+ if err := sortAndWriteDropIndexConstraintList(&buf, diff.dropIndexConstraintList); err != nil {
+ return "", err
}
- if old.ParserName.O != new.ParserName.O {
- return false
+ if err := sortAndWriteDropViewList(&buf, diff.dropViewList); err != nil {
+ return "", err
}
- if old.Comment != new.Comment {
- return false
+ if err := sortAndWriteDropTableList(&buf, diff.dropTableList); err != nil {
+ return "", err
}
- if old.Visibility != new.Visibility {
- return false
+ if err := sortAndWriteCreateTableList(&buf, diff.createTableList); err != nil {
+ return "", err
+ }
+ if err := sortAndWriteAlertTableOptionList(&buf, diff.alterTableOptionList); err != nil {
+ return "", err
}
- // 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 err := sortAndWriteAddColumnList(&buf, diff.addColumnList); err != nil {
+ return "", err
}
- if !isKeyPartEqual(old.Keys, new.Keys) {
- return false
+ if err := sortAndWriteModifyColumnList(&buf, diff.modifyColumnList); err != nil {
+ return "", err
}
- if !isReferenceDefinitionEqual(old.Refer, new.Refer) {
- return false
+ if err := sortAndWriteDropColumnList(&buf, diff.dropColumnList); err != nil {
+ return "", err
}
- 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 err := sortAndWriteCreateTempViewList(&buf, diff.createTempViewList); err != nil {
+ return "", err
}
- if len(old.IndexPartSpecifications) != len(new.IndexPartSpecifications) {
- return false
+ if err := sortAndWriteCreateIndexList(&buf, diff.createIndexList); err != nil {
+ return "", err
}
- for idx, oldIndexColName := range old.IndexPartSpecifications {
- newIndexColName := new.IndexPartSpecifications[idx]
- if oldIndexColName.Column.Name.String() != newIndexColName.Column.Name.String() {
- return false
- }
+
+ if err := sortAndWriteCreateIndexConstraintList(&buf, diff.createIndexConstraintList); err != nil {
+ return "", err
}
- if old.Match != new.Match {
- return false
+ if err := sortAndWriteCreatePrimaryIndexList(&buf, diff.createPrimaryKeyList); err != nil {
+ return "", err
}
- if (old.OnDelete == nil) != (new.OnDelete == nil) {
- return false
+ if err := sortAndWriteAddCheckConstraintList(&buf, diff.addCheckConstraintList); err != nil {
+ return "", err
}
- if old.OnDelete != nil && new.OnDelete != nil && old.OnDelete.ReferOpt != new.OnDelete.ReferOpt {
- return false
+
+ if err := sortAndWriteAddForeignKeyList(&buf, diff.addForeignKeyList); err != nil {
+ return "", err
+ }
+ if err := sortAndWriteCreateViewList(&buf, diff.createViewList); err != nil {
+ return "", err
}
- if (old.OnUpdate == nil) != (new.OnUpdate == nil) {
- return false
+ if err := sortAndWriteCreateFunctionList(&buf, diff.createFunctionList); err != nil {
+ return "", err
}
- if old.OnUpdate != nil && new.OnUpdate != nil && old.OnUpdate.ReferOpt != new.OnUpdate.ReferOpt {
- return false
+ if err := sortAndWriteCreateProcedureList(&buf, diff.createProcedureList); err != nil {
+ return "", err
}
- return true
+ if err := sortAndWriteCreateEventList(&buf, diff.createEventList); err != nil {
+ return "", err
+ }
+ if err := sortAndWriteCreateTriggerList(&buf, diff.createTriggerList); err != nil {
+ return "", err
+ }
+
+ text := buf.String()
+ if len(text) > 0 {
+ return fmt.Sprintf("%s%s%s", disableFKCheckStmt, buf.String(), enableFKCheckStmt), nil
+ }
+ return "", nil
}
-// 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
+func sortAndWriteAlertTableOptionList(buf *strings.Builder, tableOptions []*tableOptionDef) error {
+ sort.Slice(tableOptions, func(i, j int) bool {
+ return tableOptions[i].tableName < tableOptions[j].tableName
+ })
+
+ for _, tableOption := range tableOptions {
+ if err := writeAlertTableOptionStatement(buf, tableOption); err != nil {
+ return err
}
}
- return result
+ return nil
}
-// 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
+func writeAlertTableOptionStatement(buf *strings.Builder, tableOption *tableOptionDef) error {
+ if _, err := buf.WriteString(tableOption.alterOption + "\n\n"); err != nil {
+ return err
}
+ return nil
+}
- if old.Enforced != new.Enforced {
- return false
- }
+func sortAndWriteDropCheckConstraintList(buf *strings.Builder, checks []*checkDef) error {
+ sort.Slice(checks, func(i, j int) bool {
+ c1 := fmt.Sprintf("%s.%s", checks[i].tableName, checks[i].name)
+ c2 := fmt.Sprintf("%s.%s", checks[j].tableName, checks[j].name)
+ return c1 < c2
+ })
- 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)
+ for _, check := range checks {
+ if err := writeDropCheckConstraintStatement(buf, check); err != nil {
+ return err
}
}
- if len(options) == 0 {
- return nil
- }
- return &ast.AlterTableStmt{
- Table: tableName,
- Specs: []*ast.AlterTableSpec{
- {
- Tp: ast.AlterTableOption,
- Options: options,
- },
- },
- }
+ return nil
}
-// 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
+func writeDropCheckConstraintStatement(buf *strings.Builder, check *checkDef) error {
+ if _, err := buf.WriteString(fmt.Sprintf("ALTER TABLE `%s` DROP CHECK `%s`;\n\n", check.tableName, check.name)); err != nil {
+ return err
}
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
- }
+func sortAndWriteAddCheckConstraintList(buf *strings.Builder, checks []*checkDef) error {
+ sort.Slice(checks, func(i, j int) bool {
+ c1 := fmt.Sprintf("%s.%s", checks[i].tableName, checks[i].name)
+ c2 := fmt.Sprintf("%s.%s", checks[j].tableName, checks[j].name)
+ return c1 < c2
+ })
+
+ for _, check := range checks {
+ if err := writeAddCheckConstraintStatement(buf, check); err != nil {
+ return err
}
- return true
}
- return true
+ return nil
}
-// 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
+func writeAddCheckConstraintStatement(buf *strings.Builder, check *checkDef) error {
+ if _, err := buf.WriteString(fmt.Sprintf("ALTER TABLE `%s` ADD ", check.tableName)); err != nil {
+ return err
}
- oldViewStr, err := toString(old)
- if err != nil {
- slog.Error("fail to convert old view to string", log.BBError(err))
- return false
+ if _, err := buf.WriteString(check.ctx.GetParser().GetTokenStream().GetTextFromRuleContext(check.ctx.GetRuleContext())); err != nil {
+ return err
}
- newViewStr, err := toString(new)
- if err != nil {
- slog.Error("fail to convert new view to string", log.BBError(err))
- return false
+ if _, err := buf.WriteString(";\n\n"); err != nil {
+ return err
}
- return oldViewStr == newViewStr
+ return nil
}
-// 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
-}
+func sortAndWriteAddForeignKeyList(buf *strings.Builder, fks []*foreignKeyDef) error {
+ sort.Slice(fks, func(i, j int) bool {
+ c1 := fmt.Sprintf("%s.%s", fks[i].tableName, fks[i].name)
+ c2 := fmt.Sprintf("%s.%s", fks[j].tableName, fks[j].name)
+ return c1 < c2
+ })
-// 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 _, fk := range fks {
+ if err := writeAddForeignKeyStatement(buf, fk); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func writeAddForeignKeyStatement(buf *strings.Builder, fk *foreignKeyDef) error {
+ if _, err := buf.WriteString("ALTER TABLE " + fk.tableName + " ADD "); err != nil {
+ return err
+ }
+ if _, err := buf.WriteString(fk.ctx.GetParser().GetTokenStream().GetTextFromRuleContext(fk.ctx.GetRuleContext())); err != nil {
+ return err
+ }
+ if _, err := buf.WriteString(";\n\n"); err != nil {
+ return err
+ }
+ return nil
+}
+
+func sortAndWriteDropForeignKeyList(buf *strings.Builder, fks []*foreignKeyDef) error {
+ sort.Slice(fks, func(i, j int) bool {
+ c1 := fmt.Sprintf("%s.%s", fks[i].tableName, fks[i].name)
+ c2 := fmt.Sprintf("%s.%s", fks[j].tableName, fks[j].name)
+ return c1 < c2
+ })
+
+ for _, fk := range fks {
+ if err := writeDropForeignKeyStatement(buf, fk); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func writeDropForeignKeyStatement(buf *strings.Builder, fk *foreignKeyDef) error {
+ if _, err := buf.WriteString(fmt.Sprintf("ALTER TABLE `%s` DROP FOREIGN KEY `%s`;\n\n", fk.tableName, fk.name)); err != nil {
+ return err
+ }
+ return nil
+}
+
+func sortAndWriteDropFunctionList(buf *strings.Builder, functions []*functionDef) error {
+ for _, function := range functions {
+ if err := writeDropFunctionStatement(buf, function); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func writeDropFunctionStatement(buf *strings.Builder, function *functionDef) error {
+ if _, err := buf.WriteString(fmt.Sprintf("DROP FUNCTION IF EXISTS `%s`;\n\n", function.name)); err != nil {
+ return err
+ }
+
+ return nil
+}
+
+func sortAndWriteCreateFunctionList(buf *strings.Builder, functions []*functionDef) error {
+ for _, function := range functions {
+ if err := writeCreateFunctionStatement(buf, function); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func writeCreateFunctionStatement(buf *strings.Builder, function *functionDef) error {
+ var def strings.Builder
+ if _, err := def.WriteString("CREATE "); err != nil {
+ return err
+ }
+ if _, err := def.WriteString(function.ctx.GetParser().GetTokenStream().GetTextFromRuleContext(function.ctx.GetRuleContext())); err != nil {
+ return err
+ }
+ if _, err := def.WriteString(";;"); err != nil {
+ return err
+ }
+
+ if _, err := buf.WriteString(fmt.Sprintf("DELIMITER ;;\n%s\nDELIMITER ;\n\n", def.String())); err != nil {
+ return err
+ }
+ return nil
+}
+
+func sortAndWriteDropProcedureList(buf *strings.Builder, procedures []*procedureDef) error {
+ for _, procedure := range procedures {
+ if err := writeDropProcedureStatement(buf, procedure); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func writeDropProcedureStatement(buf *strings.Builder, procedure *procedureDef) error {
+ if _, err := buf.WriteString(fmt.Sprintf("DROP PROCEDURE IF EXISTS `%s`;\n\n", procedure.name)); err != nil {
+ return err
+ }
+
+ return nil
+}
+
+func sortAndWriteCreateProcedureList(buf *strings.Builder, procedures []*procedureDef) error {
+ for _, procedure := range procedures {
+ if err := writeCreateProcedureStatement(buf, procedure); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func writeCreateProcedureStatement(buf *strings.Builder, procedure *procedureDef) error {
+ var def strings.Builder
+ if _, err := def.WriteString("CREATE "); err != nil {
+ return err
+ }
+ if _, err := def.WriteString(procedure.ctx.GetParser().GetTokenStream().GetTextFromRuleContext(procedure.ctx.GetRuleContext())); err != nil {
+ return err
+ }
+ if _, err := def.WriteString(";;"); err != nil {
+ return err
+ }
+
+ if _, err := buf.WriteString(fmt.Sprintf("DELIMITER ;;\n%s\nDELIMITER ;\n\n", def.String())); err != nil {
+ return err
+ }
+ return nil
+}
+
+func sortAndWriteDropEventList(buf *strings.Builder, events []*eventDef) error {
+ for _, event := range events {
+ if err := writeDropEventStatement(buf, event); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func writeDropEventStatement(buf *strings.Builder, event *eventDef) error {
+ if _, err := buf.WriteString(fmt.Sprintf("DROP EVENT IF EXISTS `%s`;\n\n", event.name)); err != nil {
+ return err
+ }
+
+ return nil
+}
+
+func sortAndWriteCreateEventList(buf *strings.Builder, events []*eventDef) error {
+ for _, event := range events {
+ if err := writeCreateEventStatement(buf, event); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func writeCreateEventStatement(buf *strings.Builder, event *eventDef) error {
+ var def strings.Builder
+ if _, err := def.WriteString("CREATE "); err != nil {
+ return err
+ }
+ if _, err := def.WriteString(event.ctx.GetParser().GetTokenStream().GetTextFromRuleContext(event.ctx.GetRuleContext())); err != nil {
+ return err
+ }
+ if _, err := def.WriteString(";;"); err != nil {
+ return err
+ }
+
+ if _, err := buf.WriteString(fmt.Sprintf("DELIMITER ;;\n%s\nDELIMITER ;\n\n", def.String())); err != nil {
+ return err
+ }
+ return nil
+}
+
+func sortAndWriteDropTriggerList(buf *strings.Builder, triggers []*triggerDef) error {
+ for _, trigger := range triggers {
+ if err := writeDropTriggerStatement(buf, trigger); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func writeDropTriggerStatement(buf *strings.Builder, trigger *triggerDef) error {
+ if _, err := buf.WriteString(fmt.Sprintf("DROP TRIGGER IF EXISTS `%s`;\n\n", trigger.name)); err != nil {
+ return err
+ }
+
+ return nil
+}
+
+func sortAndWriteCreateTriggerList(buf *strings.Builder, triggers []*triggerDef) error {
+ for _, trigger := range triggers {
+ if err := writeCreateTriggerStatement(buf, trigger); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func writeCreateTriggerStatement(buf *strings.Builder, trigger *triggerDef) error {
+ var def strings.Builder
+ if _, err := def.WriteString("CREATE "); err != nil {
+ return err
+ }
+ if _, err := def.WriteString(trigger.ctx.GetParser().GetTokenStream().GetTextFromRuleContext(trigger.ctx.GetRuleContext())); err != nil {
+ return err
+ }
+ if _, err := def.WriteString(";;"); err != nil {
+ return err
+ }
+
+ if _, err := buf.WriteString(fmt.Sprintf("DELIMITER ;;\n%s\nDELIMITER ;\n\n", def.String())); err != nil {
+ return err
+ }
+ return nil
+}
+
+func sortAndWriteDropIndexList(buf *strings.Builder, indexes []*indexDef) error {
+ sort.Slice(indexes, func(i, j int) bool {
+ c1 := fmt.Sprintf("%s.%s", indexes[i].tableName, indexes[i].name)
+ c2 := fmt.Sprintf("%s.%s", indexes[j].tableName, indexes[j].name)
+ return c1 < c2
+ })
+
+ for _, index := range indexes {
+ if err := writeDropIndexStatement(buf, index); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func writeDropIndexStatement(buf *strings.Builder, index *indexDef) error {
+ if _, err := buf.WriteString(fmt.Sprintf("DROP INDEX `%s` ON `%s`;\n\n", index.name, index.tableName)); err != nil {
+ return err
+ }
+ return nil
+}
+
+func sortAndWriteDropIndexConstraintList(buf *strings.Builder, indexes []*indexConstraintDef) error {
+ sort.Slice(indexes, func(i, j int) bool {
+ c1 := fmt.Sprintf("%s.%s", indexes[i].tableName, indexes[i].name)
+ c2 := fmt.Sprintf("%s.%s", indexes[j].tableName, indexes[j].name)
+ return c1 < c2
+ })
+
+ for _, index := range indexes {
+ if err := writeDropIndexConstraintStatement(buf, index); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func writeDropIndexConstraintStatement(buf *strings.Builder, index *indexConstraintDef) error {
+ if _, err := buf.WriteString(fmt.Sprintf("DROP INDEX `%s` ON `%s`;\n\n", index.name, index.tableName)); err != nil {
+ return err
+ }
+ return nil
+}
+
+func sortAndWriteDropViewList(buf *strings.Builder, views []*viewDef) error {
+ sort.Slice(views, func(i, j int) bool {
+ return views[i].name < views[j].name
+ })
+
+ for _, view := range views {
+ if err := writeDropViewStatement(buf, view); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func writeDropViewStatement(buf *strings.Builder, view *viewDef) error {
+ if _, err := buf.WriteString(fmt.Sprintf("DROP VIEW IF EXISTS `%s`;\n\n", view.name)); err != nil {
+ return err
+ }
+
+ return nil
+}
+
+func sortAndWriteDropTableList(buf *strings.Builder, ns []*tableDef) error {
+ sort.Slice(ns, func(i, j int) bool {
+ return ns[i].id < ns[j].id
+ })
+
+ for _, table := range ns {
+ if err := writeDropTableStatement(buf, table); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func writeDropTableStatement(buf *strings.Builder, table *tableDef) error {
+ if _, err := buf.WriteString(fmt.Sprintf("DROP TABLE IF EXISTS `%s`;\n\n", table.name)); err != nil {
+ return err
+ }
+ return nil
+}
+
+func sortAndWriteCreateTableList(buf *strings.Builder, ns []*tableDef) error {
+ sort.Slice(ns, func(i, j int) bool {
+ return ns[i].name < ns[j].name
+ })
+
+ for _, table := range ns {
+ if err := writeCreateTableStatement(buf, table); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func writeCreateTableStatement(buf *strings.Builder, table *tableDef) error {
+ stmt := fmt.Sprintf("CREATE %s;\n\n", table.ctx.GetParser().GetTokenStream().GetTextFromRuleContext(table.ctx.GetRuleContext()))
+ if stmt[0:12] == "CREATE TABLE" {
+ stmt = stmt[0:12] + " IF NOT EXISTS" + stmt[12:]
+ }
+
+ if _, err := buf.WriteString(stmt); err != nil {
+ return err
+ }
+ return nil
+}
+
+func sortAndWriteDropColumnList(buf *strings.Builder, columns []*columnDef) error {
+ sort.Slice(columns, func(i, j int) bool {
+ c1 := fmt.Sprintf("%s.%s", columns[i].tableName, columns[i].name)
+ c2 := fmt.Sprintf("%s.%s", columns[j].tableName, columns[j].name)
+ return c1 < c2
+ })
+
+ for _, column := range columns {
+ if err := writeDropColumnStatement(buf, column); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func writeDropColumnStatement(buf *strings.Builder, column *columnDef) error {
+ if _, err := buf.WriteString(fmt.Sprintf("ALTER TABLE `%s` DROP COLUMN `%s`;\n\n", column.tableName, column.name)); err != nil {
+ return err
+ }
+ return nil
+}
+
+func sortAndWriteAddColumnList(buf *strings.Builder, columns []*columnDef) error {
+ // we do not sort the columns here for maintaining the relative position between columns;
+ for _, column := range columns {
+ if err := writeAddColumnStatement(buf, column); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func writeAddColumnStatement(buf *strings.Builder, column *columnDef) error {
+ if _, err := buf.WriteString(fmt.Sprintf("ALTER TABLE `%s` ADD COLUMN ", column.tableName)); err != nil {
+ return err
+ }
+ if _, err := buf.WriteString(column.ctx.GetParser().GetTokenStream().GetTextFromRuleContext(column.ctx.GetRuleContext())); err != nil {
+ return err
+ }
+ // TODO: add column position.
+ if column.columnPosition != nil {
+ pos := ""
+ if column.columnPosition.tp == "FIRST" {
+ pos = " FIRST"
+ } else if column.columnPosition.tp == "AFTER" {
+ pos = fmt.Sprintf(" AFTER `%s`", column.columnPosition.relativeColumn)
+ }
+ if _, err := buf.WriteString(pos); err != nil {
+ return err
+ }
+ }
+ if _, err := buf.WriteString(";\n\n"); err != nil {
+ return err
+ }
+ return nil
+}
+
+func sortAndWriteCreateTempViewList(buf *strings.Builder, views []*viewDef) error {
+ sort.Slice(views, func(i, j int) bool {
+ return views[i].name < views[j].name
+ })
+
+ for _, view := range views {
+ if err := writeCreateTempViewStatement(buf, view); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func writeCreateTempViewStatement(buf *strings.Builder, view *viewDef) error {
+ if _, err := buf.WriteString(view.tempView); err != nil {
+ return err
+ }
+
+ return nil
+}
+
+func sortAndWriteCreateViewList(buf *strings.Builder, views []*viewDef) error {
+ sort.Slice(views, func(i, j int) bool {
+ return views[i].name < views[j].name
+ })
+
+ for _, view := range views {
+ if err := writeCreateViewStatement(buf, view); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func writeCreateViewStatement(buf *strings.Builder, view *viewDef) error {
+ algorithm := "UNDEFINED"
+ if view.ctx.ViewReplaceOrAlgorithm() != nil {
+ if algo := view.ctx.ViewReplaceOrAlgorithm().ViewAlgorithm(); algo != nil {
+ algorithm = algo.GetAlgorithm().GetText()
+ }
+ }
+
+ definer := "CURRENT_USER"
+ if view.ctx.DefinerClause() != nil {
+ definer = view.ctx.DefinerClause().GetText()
+ }
+ sqlSecurity := "DEFINER"
+ if view.ctx.ViewSuid() != nil {
+ if view.ctx.ViewSuid().INVOKER_SYMBOL() != nil {
+ sqlSecurity = "INVOKER"
+ }
+ }
+
+ cols, selectExpr := "", ""
+ if view.ctx.ViewTail() != nil {
+ if list := view.ctx.ViewTail().ColumnInternalRefList(); list != nil {
+ cols = list.GetParser().GetTokenStream().GetTextFromRuleContext(list.GetRuleContext())
+ }
+ if viewSelect := view.ctx.ViewTail().ViewSelect(); viewSelect != nil {
+ selectExpr = viewSelect.GetParser().GetTokenStream().GetTextFromRuleContext(viewSelect.GetRuleContext())
+ }
+ } else {
+ return errors.Errorf("view %s has no select expr", view.name)
+ }
+ var viewSQL string
+ if cols == "" {
+ viewSQL = fmt.Sprintf("CREATE OR REPLACE ALGORITHM=%s DEFINER=%s SQL SECURITY %s VIEW `%s` AS %s;\n\n", algorithm, definer, sqlSecurity, view.name, selectExpr)
+ } else {
+ viewSQL = fmt.Sprintf("CREATE OR REPLACE ALGORITHM=%s DEFINER=%s SQL SECURITY %s VIEW `%s` %s AS %s;\n\n", algorithm, definer, sqlSecurity, view.name, cols, selectExpr)
+ }
+
+ if _, err := buf.WriteString(viewSQL); err != nil {
+ return err
+ }
+
+ return nil
+}
+
+func sortAndWriteModifyColumnList(buf *strings.Builder, columns []*columnDef) error {
+ sort.Slice(columns, func(i, j int) bool {
+ c1 := fmt.Sprintf("%s.%s", columns[i].tableName, columns[i].name)
+ c2 := fmt.Sprintf("%s.%s", columns[j].tableName, columns[j].name)
+ return c1 < c2
+ })
+
+ for _, column := range columns {
+ if err := writeModifyColumnStatement(buf, column); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func writeModifyColumnStatement(buf *strings.Builder, column *columnDef) error {
+ if _, err := buf.WriteString(fmt.Sprintf("ALTER TABLE `%s` ", column.tableName)); err != nil {
+ return err
+ }
+
+ if _, err := buf.WriteString("MODIFY COLUMN "); err != nil {
+ return err
}
- for _, col := range a {
- // MySQL column name is case insensitive.
- if _, ok := bMap[col.Name.Name.L]; ok {
- return true
+
+ if _, err := buf.WriteString(column.ctx.GetParser().GetTokenStream().GetTextFromRuleContext(column.ctx.GetRuleContext())); err != nil {
+ return err
+ }
+
+ if _, err := buf.WriteString(";\n\n"); err != nil {
+ return err
+ }
+ return nil
+}
+
+func sortAndWriteCreateIndexList(buf *strings.Builder, indexes []*indexDef) error {
+ sort.Slice(indexes, func(i, j int) bool {
+ c1 := fmt.Sprintf("%s.%s", indexes[i].tableName, indexes[i].name)
+ c2 := fmt.Sprintf("%s.%s", indexes[j].tableName, indexes[j].name)
+ return c1 < c2
+ })
+
+ for _, index := range indexes {
+ if err := writeCreateIndexStatement(buf, index); err != nil {
+ return err
}
}
- return false
+ return nil
+}
+
+func writeCreateIndexStatement(buf *strings.Builder, index *indexDef) error {
+ if _, err := buf.WriteString("CREATE "); err != nil {
+ return err
+ }
+ if _, err := buf.WriteString(index.ctx.GetParser().GetTokenStream().GetTextFromRuleContext(index.ctx.GetRuleContext())); err != nil {
+ return err
+ }
+ if _, err := buf.WriteString(";\n\n"); err != nil {
+ return err
+ }
+ return nil
+}
+
+func sortAndWriteCreateIndexConstraintList(buf *strings.Builder, indexes []*indexConstraintDef) error {
+ sort.Slice(indexes, func(i, j int) bool {
+ c1 := fmt.Sprintf("%s.%s", indexes[i].tableName, indexes[i].name)
+ c2 := fmt.Sprintf("%s.%s", indexes[j].tableName, indexes[j].name)
+ return c1 < c2
+ })
+
+ for _, index := range indexes {
+ if err := writeCreateIndexConstraintStatement(buf, index); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func writeCreateIndexConstraintStatement(buf *strings.Builder, index *indexConstraintDef) error {
+ indexType := ""
+ if nameAndType := index.ctx.IndexNameAndType(); nameAndType != nil {
+ indexType = nameAndType.GetParser().GetTokenStream().GetTextFromInterval(antlr.Interval{
+ Start: nameAndType.IndexName().GetStop().GetTokenIndex() + 1,
+ Stop: nameAndType.GetStop().GetTokenIndex(),
+ })
+ }
+ keyList := index.ctx.KeyListVariants().GetParser().GetTokenStream().GetTextFromRuleContext(index.ctx.KeyListVariants().GetRuleContext())
+ indexOption := index.ctx.GetParser().GetTokenStream().GetTextFromInterval(antlr.Interval{
+ Start: index.ctx.KeyListVariants().GetStop().GetTokenIndex() + 1,
+ Stop: index.ctx.GetStop().GetTokenIndex(),
+ })
+ if _, err := buf.WriteString(fmt.Sprintf("CREATE INDEX `%s` ON `%s`%s%s%s;\n\n", index.name, index.tableName, keyList, indexType, indexOption)); err != nil {
+ return err
+ }
+ return nil
+}
+
+func sortAndWriteCreatePrimaryIndexList(buf *strings.Builder, primaryKeys []*primaryKeyDef) error {
+ sort.Slice(primaryKeys, func(i, j int) bool {
+ return primaryKeys[i].tableName < primaryKeys[j].tableName
+ })
+
+ for _, primaryKey := range primaryKeys {
+ if err := writeCreatePrimaryIndexStatement(buf, primaryKey); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func writeCreatePrimaryIndexStatement(buf *strings.Builder, primary *primaryKeyDef) error {
+ keyList := primary.ctx.KeyListVariants().GetParser().GetTokenStream().GetTextFromRuleContext(primary.ctx.KeyListVariants().GetRuleContext())
+ indexOption := primary.ctx.GetParser().GetTokenStream().GetTextFromInterval(antlr.Interval{
+ Start: primary.ctx.KeyListVariants().GetStop().GetTokenIndex() + 1,
+ Stop: primary.ctx.GetStop().GetTokenIndex(),
+ })
+ if _, err := buf.WriteString(fmt.Sprintf("ALTER TABLE `%s` ADD PRIMARY KEY %s%s;\n\n", primary.tableName, keyList, indexOption)); err != nil {
+ return err
+ }
+ return nil
+}
+
+func sortAndWriteDropPrimaryIndexList(buf *strings.Builder, primaryKeys []*primaryKeyDef) error {
+ sort.Slice(primaryKeys, func(i, j int) bool {
+ return primaryKeys[i].tableName < primaryKeys[j].tableName
+ })
+
+ for _, primaryKey := range primaryKeys {
+ if err := writeDropPrimaryIndexStatement(buf, primaryKey); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func writeDropPrimaryIndexStatement(buf *strings.Builder, primary *primaryKeyDef) error {
+ if _, err := buf.WriteString(fmt.Sprintf("ALTER TABLE `%s` DROP PRIMARY KEY;\n\n", primary.tableName)); err != nil {
+ return err
+ }
+ return nil
+}
+
+type databaseDef struct {
+ name string
+ schemas map[string]*schemaDef
+}
+
+func newDatabaseDef() *databaseDef {
+ return &databaseDef{
+ schemas: make(map[string]*schemaDef),
+ }
+}
+
+type viewDef struct {
+ ctx *mysql.CreateViewContext
+ name string
+ dbName string
+ tempView string
+ columns []string
+}
+
+type functionDef struct {
+ ctx *mysql.CreateFunctionContext
+ name string
+}
+
+type procedureDef struct {
+ ctx *mysql.CreateProcedureContext
+ name string
+}
+
+type schemaDef struct {
+ name string
+ // todo: check for duplicate names.
+ tables map[string]*tableDef
+ views map[string]*viewDef
+ events map[string]*eventDef
+ triggers map[string]*triggerDef
+ functions map[string]*functionDef
+ procedures map[string]*procedureDef
+}
+
+func newSchemaDef() *schemaDef {
+ return &schemaDef{
+ tables: make(map[string]*tableDef),
+ views: make(map[string]*viewDef),
+ events: make(map[string]*eventDef),
+ triggers: make(map[string]*triggerDef),
+ functions: make(map[string]*functionDef),
+ procedures: make(map[string]*procedureDef),
+ }
+}
+
+type eventDef struct {
+ ctx *mysql.CreateEventContext
+ name string
+}
+
+type triggerDef struct {
+ ctx *mysql.CreateTriggerContext
+ name string
+}
+
+type tableDef struct {
+ ctx *mysql.CreateTableContext
+ id int
+ name string
+ columns map[string]*columnDef
+ indexes map[string]*indexDef
+ indexConstraints map[string]*indexConstraintDef
+ foreignKeys map[string]*foreignKeyDef
+ checks map[string]*checkDef
+ tableOptions map[string]*tableOptionDef
+ primaryKey *primaryKeyDef
+}
+
+func newTableDef(id int, name string) *tableDef {
+ return &tableDef{
+ id: id,
+ name: name,
+ columns: make(map[string]*columnDef),
+ indexes: make(map[string]*indexDef),
+ indexConstraints: make(map[string]*indexConstraintDef),
+ foreignKeys: make(map[string]*foreignKeyDef),
+ checks: make(map[string]*checkDef),
+ tableOptions: make(map[string]*tableOptionDef),
+ }
+}
+
+type primaryKeyDef struct {
+ ctx *mysql.TableConstraintDefContext
+ columns []string
+ tableName string
+}
+
+type indexConstraintDef struct {
+ ctx *mysql.TableConstraintDefContext
+ name string
+ tableName string
+}
+
+type foreignKeyDef struct {
+ ctx *mysql.TableConstraintDefContext
+ id int
+ name string
+ columns []string
+ referencedTable string
+ referencedColumns []string
+ tableName string
+}
+
+type checkDef struct {
+ ctx *mysql.TableConstraintDefContext
+ id int
+ name string
+ enforced bool
+ tableName string
+}
+
+type tableOptionDef struct {
+ ctx *mysql.CreateTableOptionContext
+ option string
+ alterOption string
+ tableName string
+}
+
+type indexDef struct {
+ ctx *mysql.CreateIndexContext
+ id int
+ name string
+ keys []string
+ tp string
+ tableName string
+}
+
+type columnPositionDef struct {
+ tp string
+ relativeColumn string
+}
+
+type columnDef struct {
+ ctx *mysql.ColumnDefinitionContext
+ id int
+ name string
+ tp string
+ defaultValue string
+ comment string
+ nullable bool
+ visible bool
+ tableName string
+ columnPosition *columnPositionDef
+}
+
+type mysqlTransformer struct {
+ *mysql.BaseMySQLParserListener
+
+ db *databaseDef
+ currentTable string
+ currView string
+ err error
+ ignoreCaseSensitive bool
+}
+
+func (diff *diffNode) parseMySQLSchemaStringToSchemDef(schema string) (*databaseDef, error) {
+ list, err := ParseMySQL(schema)
+ if err != nil {
+ return nil, err
+ }
+
+ listener := &mysqlTransformer{
+ db: newDatabaseDef(),
+ ignoreCaseSensitive: diff.ignoreCaseSensitive,
+ }
+ listener.db.schemas[""] = newSchemaDef()
+ listener.db.schemas[""].name = ""
+
+ for _, stmt := range list {
+ antlr.ParseTreeWalkerDefault.Walk(listener, stmt.Tree)
+ }
+
+ return listener.db, nil
+}
+
+// EnterCreateTable is called when production createTable is entered.
+func (t *mysqlTransformer) EnterCreateTable(ctx *mysql.CreateTableContext) {
+ if t.err != nil {
+ return
+ }
+
+ databaseName, tableName := NormalizeMySQLTableName(ctx.TableName())
+ if t.ignoreCaseSensitive {
+ databaseName = strings.ToLower(databaseName)
+ tableName = strings.ToLower(tableName)
+ }
+ if databaseName != "" {
+ if t.db.name == "" {
+ t.db.name = databaseName
+ } else if t.db.name != databaseName {
+ t.err = errors.New("multiple database names found: " + t.db.name + ", " + databaseName)
+ return
+ }
+ }
+ schema := t.db.schemas[""]
+ if _, ok := schema.tables[tableName]; ok {
+ t.err = errors.New("multiple table names found: " + tableName)
+ return
+ }
+
+ schema.tables[tableName] = newTableDef(len(schema.tables), tableName)
+ schema.tables[tableName].ctx = ctx
+ t.currentTable = tableName
+}
+
+// ExitCreateTable is called when production createTable is exited.
+func (t *mysqlTransformer) ExitCreateTable(_ *mysql.CreateTableContext) {
+ t.currentTable = ""
+}
+
+// EnterCreateTableOptions is called when production createTableOptions is entered.
+func (t *mysqlTransformer) EnterCreateTableOptions(ctx *mysql.CreateTableOptionsContext) {
+ if t.err != nil || t.currentTable == "" {
+ return
+ }
+
+ for _, option := range ctx.AllCreateTableOption() {
+ if tableOption, ok := option.(*mysql.CreateTableOptionContext); ok {
+ newTableOption := &tableOptionDef{
+ ctx: tableOption,
+ tableName: t.currentTable,
+ alterOption: fmt.Sprintf("ALTER TABLE `%s` %s;", t.currentTable, tableOption.GetParser().GetTokenStream().GetTextFromRuleContext(tableOption.GetRuleContext())),
+ }
+
+ switch {
+ case tableOption.ENGINE_SYMBOL() != nil:
+ newTableOption.option = "ENGINE"
+ case tableOption.SECONDARY_ENGINE_SYMBOL() != nil:
+ newTableOption.option = "SECONDARY_ENGINE"
+ case tableOption.DefaultCharset() != nil:
+ newTableOption.option = "DEFAULT CHARACTER SET"
+ case tableOption.DefaultCollation() != nil:
+ newTableOption.option = "DEFAULT COLLATE"
+ case tableOption.AUTO_INCREMENT_SYMBOL() != nil:
+ newTableOption.option = "AUTO_INCREMENT"
+ case tableOption.COMMENT_SYMBOL() != nil:
+ newTableOption.option = "COMMENT"
+ case tableOption.AVG_ROW_LENGTH_SYMBOL() != nil:
+ newTableOption.option = "AVG_ROW_LENGTH"
+ case tableOption.CHECKSUM_SYMBOL() != nil:
+ newTableOption.option = "CHECKSUM"
+ case tableOption.COMPRESSION_SYMBOL() != nil:
+ newTableOption.option = "COMPRESSION"
+ case tableOption.CONNECTION_SYMBOL() != nil:
+ newTableOption.option = "CONNECTION"
+ case tableOption.PASSWORD_SYMBOL() != nil:
+ newTableOption.option = "PASSWORD"
+ case tableOption.KEY_BLOCK_SIZE_SYMBOL() != nil:
+ newTableOption.option = "KEY_BLOCK_SIZE"
+ case tableOption.MAX_ROWS_SYMBOL() != nil:
+ newTableOption.option = "MAX_ROWS"
+ case tableOption.MIN_ROWS_SYMBOL() != nil:
+ newTableOption.option = "MIN_ROWS"
+ case tableOption.DELAY_KEY_WRITE_SYMBOL() != nil:
+ newTableOption.option = "DELAY_KEY_WRITE"
+ case tableOption.ROW_FORMAT_SYMBOL() != nil:
+ newTableOption.option = "ROW_FORMAT"
+ case tableOption.STATS_PERSISTENT_SYMBOL() != nil:
+ newTableOption.option = "STATS_PERSISTENT"
+ case tableOption.STATS_AUTO_RECALC_SYMBOL() != nil:
+ newTableOption.option = "STATS_AUTO_RECALC"
+ case tableOption.PACK_KEYS_SYMBOL() != nil:
+ newTableOption.option = "PACK_KEYS"
+ case tableOption.TABLESPACE_SYMBOL() != nil:
+ newTableOption.option = "TABLESPACE"
+ case tableOption.STORAGE_SYMBOL() != nil:
+ newTableOption.option = "STORAGE"
+ case tableOption.STATS_SAMPLE_PAGES_SYMBOL() != nil:
+ newTableOption.option = "STATS_SAMPLE_PAGES"
+ case tableOption.INSERT_METHOD_SYMBOL() != nil:
+ newTableOption.option = "INSERT_METHOD"
+ case tableOption.TABLE_CHECKSUM_SYMBOL() != nil:
+ newTableOption.option = "TABLE_CHECKSUM"
+ case tableOption.UNION_SYMBOL() != nil:
+ newTableOption.option = "UNION"
+ case tableOption.ENCRYPTION_SYMBOL() != nil:
+ newTableOption.option = "ENCRYPTION"
+ case tableOption.DATA_SYMBOL() != nil && tableOption.DIRECTORY_SYMBOL() != nil:
+ newTableOption.option = "DATA DIRECTORY"
+ }
+ table := t.db.schemas[""].tables[t.currentTable]
+ table.tableOptions[newTableOption.option] = newTableOption
+ }
+ }
+}
+
+// EnterTableConstraintDef is called when production tableConstraintDef is entered.
+func (t *mysqlTransformer) EnterTableConstraintDef(ctx *mysql.TableConstraintDefContext) {
+ if t.err != nil || t.currentTable == "" {
+ return
+ }
+
+ table := t.db.schemas[""].tables[t.currentTable]
+ if ctx.GetType_() != nil {
+ switch strings.ToUpper(ctx.GetType_().GetText()) {
+ case "PRIMARY":
+ list := extractKeyListVariants(ctx.KeyListVariants())
+ table.primaryKey = &primaryKeyDef{
+ ctx: ctx,
+ columns: list,
+ tableName: t.currentTable,
+ }
+ case "FOREIGN":
+ var name string
+ if ctx.ConstraintName() != nil && ctx.ConstraintName().Identifier() != nil {
+ name = NormalizeMySQLIdentifier(ctx.ConstraintName().Identifier())
+ } else if ctx.IndexName() != nil {
+ name = NormalizeMySQLIdentifier(ctx.IndexName().Identifier())
+ }
+ keys := extractKeyList(ctx.KeyList())
+ if table.foreignKeys[name] != nil {
+ t.err = errors.New("multiple foreign keys found: " + name)
+ return
+ }
+ referencedTable, referencedColumns := extractReference(ctx.References())
+ fk := &foreignKeyDef{
+ ctx: ctx,
+ id: len(table.foreignKeys),
+ name: name,
+ columns: keys,
+ referencedTable: referencedTable,
+ referencedColumns: referencedColumns,
+ tableName: t.currentTable,
+ }
+ table.foreignKeys[name] = fk
+ case "KEY", "INDEX", "UNIQUE":
+ indexName := strings.ToLower(ctx.IndexNameAndType().IndexName().GetText())
+ if indexName != `''` && len(indexName) > 2 {
+ indexName = indexName[1 : len(indexName)-1]
+ }
+ index := &indexConstraintDef{
+ ctx: ctx,
+ name: indexName,
+ tableName: t.currentTable,
+ }
+ table.indexConstraints[index.name] = index
+ case "FULLTEXT", "SPATIAL":
+ indexName := strings.ToLower(ctx.IndexName().GetText())
+ if indexName != `''` && len(indexName) > 2 {
+ indexName = indexName[1 : len(indexName)-1]
+ }
+ index := &indexConstraintDef{
+ ctx: ctx,
+ name: indexName,
+ tableName: t.currentTable,
+ }
+ table.indexConstraints[index.name] = index
+ }
+ }
+
+ if ctx.CheckConstraint() != nil {
+ if _, ok := ctx.CheckConstraint().(*mysql.CheckConstraintContext); ok {
+ var name string
+ if ctx.ConstraintName() != nil && ctx.ConstraintName().Identifier() != nil {
+ name = NormalizeMySQLIdentifier(ctx.ConstraintName().Identifier())
+ }
+
+ enforced := true
+ if ctx.ConstraintEnforcement() != nil {
+ if ctx.ConstraintEnforcement().NOT_SYMBOL() != nil {
+ enforced = false
+ }
+ }
+
+ table := t.db.schemas[""].tables[t.currentTable]
+ ck := &checkDef{
+ ctx: ctx,
+ id: len(table.checks),
+ name: name,
+ enforced: enforced,
+ tableName: t.currentTable,
+ }
+ table.checks[ck.name] = ck
+ }
+ }
+}
+
+// extract table name and column names.
+func extractReference(ctx mysql.IReferencesContext) (string, []string) {
+ _, table := NormalizeMySQLTableRef(ctx.TableRef())
+ if ctx.IdentifierListWithParentheses() != nil {
+ columns := extractIdentifierList(ctx.IdentifierListWithParentheses().IdentifierList())
+ return table, columns
+ }
+ return table, nil
+}
+
+// extract column names.
+func extractIdentifierList(ctx mysql.IIdentifierListContext) []string {
+ var result []string
+ for _, identifier := range ctx.AllIdentifier() {
+ result = append(result, NormalizeMySQLIdentifier(identifier))
+ }
+ return result
+}
+
+// extract column names.
+func extractKeyListVariants(ctx mysql.IKeyListVariantsContext) []string {
+ if ctx.KeyList() != nil {
+ return extractKeyList(ctx.KeyList())
+ }
+ if ctx.KeyListWithExpression() != nil {
+ return extractKeyListWithExpression(ctx.KeyListWithExpression())
+ }
+ return nil
+}
+
+// extract column names.
+func extractKeyListWithExpression(ctx mysql.IKeyListWithExpressionContext) []string {
+ var result []string
+ for _, key := range ctx.AllKeyPartOrExpression() {
+ if key.KeyPart() != nil {
+ keyText := NormalizeMySQLIdentifier(key.KeyPart().Identifier())
+ result = append(result, keyText)
+ } else if key.ExprWithParentheses() != nil {
+ keyText := key.GetParser().GetTokenStream().GetTextFromRuleContext(key.ExprWithParentheses())
+ result = append(result, keyText)
+ }
+ }
+ return result
+}
+
+// extract column names.
+func extractKeyList(ctx mysql.IKeyListContext) []string {
+ var result []string
+ for _, key := range ctx.AllKeyPart() {
+ keyText := NormalizeMySQLIdentifier(key.Identifier())
+ result = append(result, keyText)
+ }
+ return result
+}
+
+// EnterColumnDefinition is called when production columnDefinition is entered.
+func (t *mysqlTransformer) EnterColumnDefinition(ctx *mysql.ColumnDefinitionContext) {
+ if t.err != nil || t.currentTable == "" {
+ return
+ }
+
+ _, _, columnName := NormalizeMySQLColumnName(ctx.ColumnName())
+ dataType := ctx.GetParser().GetTokenStream().GetTextFromRuleContext(ctx.FieldDefinition().DataType())
+ table := t.db.schemas[""].tables[t.currentTable]
+ if _, ok := table.columns[columnName]; ok {
+ t.err = errors.New("multiple column names found: " + columnName + " in table " + t.currentTable)
+ return
+ }
+ columnState := &columnDef{
+ ctx: ctx,
+ id: len(table.columns),
+ name: columnName,
+ tp: dataType,
+ defaultValue: "",
+ comment: "",
+ nullable: true,
+ visible: true,
+ tableName: t.currentTable,
+ }
+
+ for _, attribute := range ctx.FieldDefinition().AllColumnAttribute() {
+ switch {
+ case attribute.NullLiteral() != nil && attribute.NOT_SYMBOL() != nil:
+ columnState.nullable = false
+ case attribute.DEFAULT_SYMBOL() != nil && attribute.SERIAL_SYMBOL() == nil:
+ defaultValueStart := nextDefaultChannelTokenIndex(ctx.GetParser().GetTokenStream(), attribute.DEFAULT_SYMBOL().GetSymbol().GetTokenIndex())
+ defaultValue := attribute.GetParser().GetTokenStream().GetTextFromInterval(antlr.Interval{
+ Start: defaultValueStart,
+ Stop: attribute.GetStop().GetTokenIndex(),
+ })
+ columnState.defaultValue = defaultValue
+ case attribute.COMMENT_SYMBOL() != nil:
+ commentStart := nextDefaultChannelTokenIndex(ctx.GetParser().GetTokenStream(), attribute.COMMENT_SYMBOL().GetSymbol().GetTokenIndex())
+ comment := attribute.GetParser().GetTokenStream().GetTextFromInterval(antlr.Interval{
+ Start: commentStart,
+ Stop: attribute.GetStop().GetTokenIndex(),
+ })
+ if comment != `''` && len(comment) > 2 {
+ columnState.comment = comment[1 : len(comment)-1]
+ }
+ case attribute.INVISIBLE_SYMBOL() != nil:
+ columnState.visible = false
+ }
+ }
+ // todo: need handle more types.
+ if strings.ToLower(dataType) == "serial" {
+ columnState.nullable = false
+ }
+
+ table.columns[columnName] = columnState
+}
+
+func nextDefaultChannelTokenIndex(tokens antlr.TokenStream, currentIndex int) int {
+ for i := currentIndex + 1; i < tokens.Size(); i++ {
+ if tokens.Get(i).GetChannel() == antlr.TokenDefaultChannel {
+ return i
+ }
+ }
+ return 0
+}
+
+// EnterCreateIndex is called when production createIndex is entered.
+func (t *mysqlTransformer) EnterCreateIndex(ctx *mysql.CreateIndexContext) {
+ _, tableName := NormalizeMySQLTableRef(ctx.CreateIndexTarget().TableRef())
+ if t.ignoreCaseSensitive {
+ tableName = strings.ToLower(tableName)
+ }
+ indexName := NormalizeMySQLIdentifier(ctx.IndexName().Identifier())
+ table, exists := t.db.schemas[""].tables[tableName]
+ if !exists {
+ t.err = errors.Errorf("Try to create index `%s` on table `%s`, but table not found", indexName, tableName)
+ return
+ }
+ // Index names are always case insensitive
+ if _, exists := table.indexes[strings.ToLower(indexName)]; exists {
+ t.err = errors.Errorf("Try to create index `%s` on table `%s`, but index already exists", indexName, tableName)
+ return
+ }
+ if _, exists := table.indexConstraints[strings.ToLower(indexName)]; exists {
+ t.err = errors.Errorf("Try to create index `%s` on table `%s`, but index already exists", indexName, tableName)
+ return
+ }
+ cols := extractKeyListVariants(ctx.CreateIndexTarget().KeyListVariants())
+ index := &indexDef{
+ ctx: ctx,
+ id: len(table.indexes),
+ name: indexName,
+ keys: cols,
+ tableName: tableName,
+ }
+
+ table.indexes[strings.ToLower(indexName)] = index
+ if ctx.GetType_() != nil {
+ switch strings.ToUpper(ctx.GetType_().GetText()) {
+ case "UNIQUE":
+ index.tp = "UNIQUE"
+ case "FULLTEXT":
+ index.tp = "FULLTEXT"
+ case "SPATIAL":
+ index.tp = "SPATIAL"
+ }
+ }
+}
+
+// EnterCreateView is called when production createView is entered.
+func (t *mysqlTransformer) EnterCreateView(ctx *mysql.CreateViewContext) {
+ _, viewName := NormalizeMySQLViewName(ctx.ViewName())
+ t.currView = viewName
+ if t.ignoreCaseSensitive {
+ viewName = strings.ToLower(viewName)
+ }
+
+ t.db.schemas[""].views[viewName] = &viewDef{
+ ctx: ctx,
+ name: viewName,
+ }
+}
+
+func (t *mysqlTransformer) ExitCreateView(ctx *mysql.CreateViewContext) {
+ if t.err != nil {
+ return
+ }
+
+ view := t.db.schemas[""].views[t.currView]
+
+ var tableSchemaList []base.TableSchema
+ for _, table := range t.db.schemas[""].tables {
+ var columnList []base.ColumnInfo
+ for _, col := range table.columns {
+ columnInfo := base.ColumnInfo{
+ Name: col.name,
+ }
+ columnList = append(columnList, columnInfo)
+ }
+ tableSchema := base.TableSchema{
+ Name: table.name,
+ ColumnList: columnList,
+ }
+ tableSchemaList = append(tableSchemaList, tableSchema)
+ }
+ var viewSchemaList []base.ViewSchema
+ for _, view := range t.db.schemas[""].views {
+ viewSchema := base.ViewSchema{
+ Name: view.name,
+ Definition: fmt.Sprintf("CREATE %s;", view.ctx.GetParser().GetTokenStream().GetTextFromRuleContext(view.ctx.GetRuleContext())),
+ }
+ viewSchemaList = append(viewSchemaList, viewSchema)
+ }
+ schemaList := []base.SchemaSchema{
+ {
+ Name: "",
+ TableList: tableSchemaList,
+ ViewList: viewSchemaList,
+ },
+ }
+
+ schemaInfo := &base.SensitiveSchemaInfo{
+ DatabaseList: []base.DatabaseSchema{
+ {
+ Name: t.db.name,
+ SchemaList: schemaList,
+ },
+ },
+ }
+
+ extractor := &fieldExtractor{
+ currentDatabase: view.dbName,
+ schemaInfo: schemaInfo,
+ }
+
+ fields, err := extractor.mysqlExtractCreateView(ctx)
+ if err != nil {
+ t.err = err
+ return
+ }
+
+ var result []string
+ for _, field := range fields {
+ result = append(result, field.Name)
+ }
+ view.columns = result
+}
+
+// EnterCreateEvent is called when production createEvent is entered.
+func (t *mysqlTransformer) EnterCreateEvent(ctx *mysql.CreateEventContext) {
+ _, eventName := NormalizeMySQLEventName(ctx.EventName())
+ if t.ignoreCaseSensitive {
+ eventName = strings.ToLower(eventName)
+ }
+
+ t.db.schemas[""].events[eventName] = &eventDef{
+ ctx: ctx,
+ name: eventName,
+ }
+}
+
+// EnterCreateTrigger is called when production createTrigger is entered.
+func (t *mysqlTransformer) EnterCreateTrigger(ctx *mysql.CreateTriggerContext) {
+ _, triggerName := NormalizeMySQLTriggerName(ctx.TriggerName())
+ if t.ignoreCaseSensitive {
+ triggerName = strings.ToLower(triggerName)
+ }
+
+ t.db.schemas[""].triggers[triggerName] = &triggerDef{
+ ctx: ctx,
+ name: triggerName,
+ }
+}
+
+// EnterCreateFunction is called when production createFunction is entered.
+func (t *mysqlTransformer) EnterCreateFunction(ctx *mysql.CreateFunctionContext) {
+ _, functionName := NormalizeMySQLFunctionName(ctx.FunctionName())
+ if t.ignoreCaseSensitive {
+ functionName = strings.ToLower(functionName)
+ }
+
+ t.db.schemas[""].functions[functionName] = &functionDef{
+ ctx: ctx,
+ name: functionName,
+ }
+}
+
+// EnterCreateProcedure is called when production createProcedure is entered.
+func (t *mysqlTransformer) EnterCreateProcedure(ctx *mysql.CreateProcedureContext) {
+ _, procedureName := NormalizeMySQLProcedureName(ctx.ProcedureName())
+ if t.ignoreCaseSensitive {
+ procedureName = strings.ToLower(procedureName)
+ }
+
+ t.db.schemas[""].procedures[procedureName] = &procedureDef{
+ ctx: ctx,
+ name: procedureName,
+ }
}
diff --git a/backend/plugin/parser/mysql/differ_column_test.go b/backend/plugin/parser/mysql/differ_column_test.go
deleted file mode 100644
index 818d3ad069..0000000000
--- a/backend/plugin/parser/mysql/differ_column_test.go
+++ /dev/null
@@ -1,298 +0,0 @@
-package mysql
-
-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/mysql/differ_constraint_test.go b/backend/plugin/parser/mysql/differ_constraint_test.go
deleted file mode 100644
index 8e3a9cfda0..0000000000
--- a/backend/plugin/parser/mysql/differ_constraint_test.go
+++ /dev/null
@@ -1,530 +0,0 @@
-package mysql
-
-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/mysql/differ_table_test.go b/backend/plugin/parser/mysql/differ_table_test.go
deleted file mode 100644
index 1f567a399d..0000000000
--- a/backend/plugin/parser/mysql/differ_table_test.go
+++ /dev/null
@@ -1,347 +0,0 @@
-package mysql
-
-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/mysql/differ_test.go b/backend/plugin/parser/mysql/differ_test.go
index c8a1722656..778da67736 100644
--- a/backend/plugin/parser/mysql/differ_test.go
+++ b/backend/plugin/parser/mysql/differ_test.go
@@ -1,106 +1,100 @@
package mysql
import (
+ "io"
+ "os"
+ "path/filepath"
"testing"
"github.com/stretchr/testify/require"
+ "gopkg.in/yaml.v3"
)
-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",
- },
+type DifferTestData struct {
+ OldSchema string `yaml:"oldSchema"`
+ NewSchema string `yaml:"newSchema"`
+ Diff string `yal:"diff"`
+}
+
+func runDifferTest(t *testing.T, file string, record bool) {
+ var tests []DifferTestData
+ filepath := filepath.Join("test-data", file)
+ yamlFile, err := os.Open(filepath)
+ require.NoError(t, err)
+ defer yamlFile.Close()
+
+ byteValue, err := io.ReadAll(yamlFile)
+ require.NoError(t, err)
+ err = yaml.Unmarshal(byteValue, &tests)
+ require.NoError(t, err)
+
+ for i, test := range tests {
+ diff, err := SchemaDiff(test.OldSchema, test.NewSchema, false /* ignoreCaseSensitive */)
+ require.NoError(t, err)
+ if len(diff) > 0 {
+ require.Equal(t, disableFKCheckStmt, diff[:len(disableFKCheckStmt)])
+ diff = diff[len(disableFKCheckStmt):]
+ require.Equal(t, enableFKCheckStmt, diff[len(diff)-len(enableFKCheckStmt):])
+ diff = diff[:len(diff)-len(enableFKCheckStmt)]
+ }
+ if record {
+ tests[i].Diff = diff
+ } else {
+ require.Equal(t, test.Diff, diff, test.OldSchema)
+ }
}
- 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)
+ if record {
+ err := yamlFile.Close()
+ require.NoError(t, err)
+ byteValue, err = yaml.Marshal(tests)
+ require.NoError(t, err)
+ err = os.WriteFile(filepath, byteValue, 0644)
+ require.NoError(t, err)
}
}
-type testCase struct {
- old string
- new string
- want string
+func TestSchemaDiffTable(t *testing.T) {
+ testFile := "test_differ_table.yaml"
+ runDifferTest(t, testFile, false /* record */)
}
-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)
- }
+func TestSchemaDiffColumn(t *testing.T) {
+ testFile := "test_differ_column.yaml"
+ runDifferTest(t, testFile, false /* record */)
+}
+
+func TestSchemaDiffIndex(t *testing.T) {
+ testFile := "test_differ_index.yaml"
+ runDifferTest(t, testFile, false /* record */)
+}
+
+func TestSchemaDiffView(t *testing.T) {
+ testFile := "test_differ_view.yaml"
+ runDifferTest(t, testFile, false /* record */)
+}
+
+func TestSchemaDiffFunction(t *testing.T) {
+ testFile := "test_differ_function.yaml"
+ runDifferTest(t, testFile, false /* record */)
+}
+
+func TestSchemaDiffProcedure(t *testing.T) {
+ testFile := "test_differ_procedure.yaml"
+ runDifferTest(t, testFile, false /* record */)
+}
+
+func TestSchemaDiffEvent(t *testing.T) {
+ testFile := "test_differ_event.yaml"
+ runDifferTest(t, testFile, false /* record */)
+}
+
+func TestSchemaDiffTrigger(t *testing.T) {
+ testFile := "test_differ_trigger.yaml"
+ runDifferTest(t, testFile, false /* record */)
+}
+
+func TestSchemaDiffConstraint(t *testing.T) {
+ testFile := "test_differ_constraint.yaml"
+ runDifferTest(t, testFile, false /* record */)
}
diff --git a/backend/plugin/parser/mysql/differ_utils.go b/backend/plugin/parser/mysql/differ_utils.go
deleted file mode 100644
index bd24879a82..0000000000
--- a/backend/plugin/parser/mysql/differ_utils.go
+++ /dev/null
@@ -1,77 +0,0 @@
-package mysql
-
-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/mysql/differ_utils_test.go b/backend/plugin/parser/mysql/differ_utils_test.go
deleted file mode 100644
index 02ad128b72..0000000000
--- a/backend/plugin/parser/mysql/differ_utils_test.go
+++ /dev/null
@@ -1,84 +0,0 @@
-package mysql
-
-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/parser/mysql/normalize.go b/backend/plugin/parser/mysql/normalize.go
index dd780c4ac7..5f208ff4e4 100644
--- a/backend/plugin/parser/mysql/normalize.go
+++ b/backend/plugin/parser/mysql/normalize.go
@@ -94,3 +94,46 @@ func NormalizeMySQLIdentifierList(ctx parser.IIdentifierListContext) []string {
}
return result
}
+
+// NormalizeMySQLTableRef normalizes the given view name.
+func NormalizeMySQLViewName(ctx parser.IViewNameContext) (string, string) {
+ if ctx.QualifiedIdentifier() != nil {
+ return normalizeMySQLQualifiedIdentifier(ctx.QualifiedIdentifier())
+ }
+ if ctx.DotIdentifier() != nil {
+ return "", NormalizeMySQLIdentifier(ctx.DotIdentifier().Identifier())
+ }
+ return "", ""
+}
+
+// NormalizeMySQLTableRef normalizes the given event name.
+func NormalizeMySQLEventName(ctx parser.IEventNameContext) (string, string) {
+ if ctx.QualifiedIdentifier() != nil {
+ return normalizeMySQLQualifiedIdentifier(ctx.QualifiedIdentifier())
+ }
+ return "", ""
+}
+
+// NormalizeMySQLTableRef normalizes the given trigger name.
+func NormalizeMySQLTriggerName(ctx parser.ITriggerNameContext) (string, string) {
+ if ctx.QualifiedIdentifier() != nil {
+ return normalizeMySQLQualifiedIdentifier(ctx.QualifiedIdentifier())
+ }
+ return "", ""
+}
+
+// NormalizeMySQLTableRef normalizes the given function name.
+func NormalizeMySQLFunctionName(ctx parser.IFunctionNameContext) (string, string) {
+ if ctx.QualifiedIdentifier() != nil {
+ return normalizeMySQLQualifiedIdentifier(ctx.QualifiedIdentifier())
+ }
+ return "", ""
+}
+
+// NormalizeMySQLTableRef normalizes the given function name.
+func NormalizeMySQLProcedureName(ctx parser.IProcedureNameContext) (string, string) {
+ if ctx.QualifiedIdentifier() != nil {
+ return normalizeMySQLQualifiedIdentifier(ctx.QualifiedIdentifier())
+ }
+ return "", ""
+}
diff --git a/backend/plugin/parser/mysql/test-data/test_differ_column.yaml b/backend/plugin/parser/mysql/test-data/test_differ_column.yaml
new file mode 100644
index 0000000000..10adca11ef
--- /dev/null
+++ b/backend/plugin/parser/mysql/test-data/test_differ_column.yaml
@@ -0,0 +1,483 @@
+- oldSchema: |
+ CREATE TABLE `t1` (`id` INT, `name` VARCHAR(55));
+ newSchema: |
+ CREATE TABLE `t1` (`id` INT);
+ diff: |+
+ ALTER TABLE `t1` DROP COLUMN `name`;
+
+- oldSchema: |
+ CREATE TABLE `t1` (`id` INT);
+ newSchema: |
+ CREATE TABLE `t1` (`id` INT, `name` VARCHAR(55));
+ diff: |+
+ ALTER TABLE `t1` ADD COLUMN `name` VARCHAR(55) AFTER `id`;
+
+- oldSchema: |
+ CREATE TABLE `t1` (`id` INT, `name` VARCHAR(55));
+ newSchema: |
+ CREATE TABLE `t1` (`id` INT, `name` INT);
+ diff: |+
+ ALTER TABLE `t1` MODIFY COLUMN `name` INT;
+
+- oldSchema: |
+ CREATE TABLE `t1` (
+ `a` int,
+ `b` char(20),
+ `c` int
+ );
+ newSchema: |
+ CREATE TABLE `t1` ( `a` int);
+ diff: |+
+ ALTER TABLE `t1` DROP COLUMN `b`;
+
+ ALTER TABLE `t1` DROP COLUMN `c`;
+
+- oldSchema: |
+ CREATE TABLE `t1` (`a` int);
+ newSchema: |
+ CREATE TABLE `t1` (
+ `a` int,
+ `b` char(20),
+ `c` int
+ );
+ diff: |+
+ ALTER TABLE `t1` ADD COLUMN `b` char(20) AFTER `a`;
+
+ ALTER TABLE `t1` ADD COLUMN `c` int AFTER `b`;
+
+- oldSchema: |
+ CREATE TABLE `t` (
+ `a` int,
+ `b` varchar(220),
+ `c` date,
+ `d` bit(4),
+ `e` json,
+ `f` bit(2)
+ );
+ newSchema: |
+ CREATE TABLE t (
+ `a` integer,
+ `b` varchar(20),
+ `c` boolean,
+ `d` bit(2),
+ `e` json,
+ `f` bit(4)
+ );
+ diff: |+
+ ALTER TABLE `t` MODIFY COLUMN `a` integer;
+
+ ALTER TABLE `t` MODIFY COLUMN `b` varchar(20);
+
+ ALTER TABLE `t` MODIFY COLUMN `c` boolean;
+
+ ALTER TABLE `t` MODIFY COLUMN `d` bit(2);
+
+ ALTER TABLE `t` MODIFY COLUMN `f` bit(4);
+
+- oldSchema: |
+ CREATE TABLE `book` (`id` INT, PRIMARY KEY(`id`));
+ newSchema: |
+ CREATE TABLE `book` (`id` INT, `price` INT, PRIMARY KEY(`id`));
+ diff: |+
+ ALTER TABLE `book` ADD COLUMN `price` INT AFTER `id`;
+
+- oldSchema: |
+ CREATE TABLE `book` (`id` INT, PRIMARY KEY(`id`));
+ newSchema: |
+ CREATE TABLE `book` (`id` INT, `price` INT, `code` VARCHAR(50), PRIMARY KEY(`id`));
+ diff: |+
+ ALTER TABLE `book` ADD COLUMN `price` INT AFTER `id`;
+
+ ALTER TABLE `book` ADD COLUMN `code` VARCHAR(50) AFTER `price`;
+
+- oldSchema: |
+ CREATE TABLE `book1` (`id` INT, PRIMARY KEY(`id`));
+ newSchema: |
+ CREATE TABLE `book` (`id` INT, `price` INT, `code` VARCHAR(50), PRIMARY KEY(`id`));
+ diff: |+
+ DROP TABLE IF EXISTS `book1`;
+
+ CREATE TABLE IF NOT EXISTS `book` (`id` INT, `price` INT, `code` VARCHAR(50), PRIMARY KEY(`id`));
+
+- oldSchema: |
+ CREATE TABLE `book` (`id` INT, `price` INT, `code` VARCHAR(50), PRIMARY KEY(`id`));
+ newSchema: |
+ CREATE TABLE `book` (`id` INT);
+ diff: |+
+ ALTER TABLE `book` DROP PRIMARY KEY;
+
+ ALTER TABLE `book` DROP COLUMN `code`;
+
+ ALTER TABLE `book` DROP COLUMN `price`;
+
+- oldSchema: |
+ CREATE TABLE `book` (`id` INT);
+ newSchema: |
+ CREATE TABLE `book` (`id` VARCHAR(50));
+ diff: |+
+ ALTER TABLE `book` MODIFY COLUMN `id` VARCHAR(50);
+
+- oldSchema: |
+ CREATE TABLE `book` (`id` INT, `a` VARCHAR(50));
+ newSchema: |
+ CREATE TABLE `book` (`id` INT, `a` VARCHAR(50));
+ diff: ""
+- oldSchema: |
+ CREATE TABLE `book` (`id` INT, `a` VARCHAR(50));
+ newSchema: |
+ CREATE TABLE `book` (`id` VARCHAR(50), `a` INT);
+ diff: |+
+ ALTER TABLE `book` MODIFY COLUMN `a` INT;
+
+ ALTER TABLE `book` MODIFY COLUMN `id` VARCHAR(50);
+
+- oldSchema: |
+ CREATE TABLE `book` (`id` INT COLUMN_FORMAT FIXED, PRIMARY KEY(`id`)) ;
+ newSchema: |
+ CREATE TABLE `book` (`id` INT COLUMN_FORMAT DYNAMIC, PRIMARY KEY(`id`)) ;
+ diff: |+
+ ALTER TABLE `book` MODIFY COLUMN `id` INT COLUMN_FORMAT DYNAMIC;
+
+- oldSchema: |
+ CREATE TABLE `book` (`id` INT NOT NULL);
+ newSchema: |
+ CREATE TABLE `book` (`id` INT NULL);
+ diff: |+
+ ALTER TABLE `book` MODIFY COLUMN `id` INT NULL;
+
+- oldSchema: |
+ CREATE TABLE `book` (`id` INT NOT NULL);
+ newSchema: |
+ CREATE TABLE `book` (`id` INT);
+ diff: |+
+ ALTER TABLE `book` MODIFY COLUMN `id` INT;
+
+- oldSchema: |
+ CREATE TABLE `book` (`name` VARCHAR(50) NOT NULL DEFAULT 'Harry Potter');
+ newSchema: |
+ CREATE TABLE `book` (`name` VARCHAR(50) NULL DEFAULT 'Harry Potter');
+ diff: |+
+ ALTER TABLE `book` MODIFY COLUMN `name` VARCHAR(50) NULL DEFAULT 'Harry Potter';
+
+- oldSchema: |
+ CREATE TABLE `book` (`name` VARCHAR(50) NOT NULL DEFAULT 'Harry Potter');
+ newSchema: |
+ CREATE TABLE `book` (`name` VARCHAR(50) DEFAULT 'Harry Potter');
+ diff: |+
+ ALTER TABLE `book` MODIFY COLUMN `name` VARCHAR(50) DEFAULT 'Harry Potter';
+
+- oldSchema: |
+ CREATE TABLE `book` (`name` VARCHAR(50) NULL);
+ newSchema: |
+ CREATE TABLE `book` (`name` VARCHAR(50) NULL);
+ diff: ""
+- oldSchema: |
+ CREATE TABLE `book` (`name` VARCHAR(50) NOT NULL);
+ newSchema: |
+ CREATE TABLE `book` (`name` VARCHAR(50) NOT NULL);
+ diff: ""
+- oldSchema: |
+ CREATE TABLE `book` (`name` VARCHAR(50) NOT NULL COMMENT 'Author Name');
+ newSchema: |
+ CREATE TABLE `book` (`name` VARCHAR(50) NOT NULL COMMENT 'Book Name');
+ diff: |+
+ ALTER TABLE `book` MODIFY COLUMN `name` VARCHAR(50) NOT NULL COMMENT 'Book Name';
+
+- oldSchema: |
+ CREATE TABLE `book` (`name` VARCHAR(50) COMMENT 'Author Name');
+ newSchema: |
+ CREATE TABLE `book` (`name` VARCHAR(50) COMMENT 'Book Name');
+ diff: |+
+ ALTER TABLE `book` MODIFY COLUMN `name` VARCHAR(50) COMMENT 'Book Name';
+
+- oldSchema: |
+ CREATE TABLE `book` (`name` VARCHAR(50) NOT NULL);
+ newSchema: |
+ CREATE TABLE `book` (`name` VARCHAR(50) NOT NULL COMMENT 'Book Name');
+ diff: |+
+ ALTER TABLE `book` MODIFY COLUMN `name` VARCHAR(50) NOT NULL COMMENT 'Book Name';
+
+- oldSchema: |
+ CREATE TABLE `book` (`name` VARCHAR(50) NOT NULL COMMENT 'Book Name');
+ newSchema: |
+ CREATE TABLE `book` (`name` VARCHAR(50) NOT NULL COMMENT 'Book Name');
+ diff: ""
+- oldSchema: |
+ CREATE TABLE `book` (`name` VARCHAR(50) NOT NULL DEFAULT 'Harry Potter');
+ newSchema: |
+ CREATE TABLE `book` (`name` VARCHAR(50) NOT NULL);
+ diff: |+
+ ALTER TABLE `book` MODIFY COLUMN `name` VARCHAR(50) NOT NULL;
+
+- oldSchema: |
+ CREATE TABLE `book` (`name` VARCHAR(50) NOT NULL);
+ newSchema: |
+ CREATE TABLE `book` (`name` VARCHAR(50) NOT NULL DEFAULT 'Harry Potter');
+ diff: |+
+ ALTER TABLE `book` MODIFY COLUMN `name` VARCHAR(50) NOT NULL DEFAULT 'Harry Potter';
+
+- oldSchema: |
+ CREATE TABLE `book` (`name` VARCHAR(50) NOT NULL DEFAULT "Holmes");
+ newSchema: |
+ CREATE TABLE `book` (`name` VARCHAR(50) NOT NULL DEFAULT 'Harry Potter');
+ diff: |+
+ ALTER TABLE `book` MODIFY COLUMN `name` VARCHAR(50) NOT NULL DEFAULT 'Harry Potter';
+
+- oldSchema: |
+ CREATE TABLE `book` (`name` VARCHAR(50) NOT NULL COMMENT 'Holmes');
+ newSchema: |
+ CREATE TABLE `book` (`name` VARCHAR(50) NOT NULL COMMENT 'Holmes');
+ diff: ""
+- oldSchema: |
+ CREATE TABLE `book` (`id` INT NOT NULL DEFAULT 0);
+ newSchema: |
+ CREATE TABLE `book` (`id` INT NULL);
+ diff: |+
+ ALTER TABLE `book` MODIFY COLUMN `id` INT NULL;
+
+- oldSchema: |
+ CREATE TABLE `book` (`name` VARCHAR(50) COMMENT 'Author Name' NOT NULL);
+ newSchema: |
+ CREATE TABLE `book` (`name` VARCHAR(50) COMMENT 'Book Name' NOT NULL);
+ diff: |+
+ ALTER TABLE `book` MODIFY COLUMN `name` VARCHAR(50) COMMENT 'Book Name' NOT NULL;
+
+- oldSchema: |
+ CREATE TABLE `book` (`name` VARCHAR(50) COMMENT 'Author Name' NOT NULL);
+ newSchema: |
+ CREATE TABLE `book` (`name` VARCHAR(50) COMMENT 'Book Name' NOT NULL);
+ diff: |+
+ ALTER TABLE `book` MODIFY COLUMN `name` VARCHAR(50) COMMENT 'Book Name' NOT NULL;
+
+- oldSchema: |
+ CREATE TABLE `book` (`name` VARCHAR(50) COMMENT 'Author Name' NOT NULL);
+ newSchema: |
+ CREATE TABLE `book` (`name` VARCHAR(50) COMMENT 'AUTHOR NAME' NOT NULL);
+ diff: |+
+ ALTER TABLE `book` MODIFY COLUMN `name` VARCHAR(50) COMMENT 'AUTHOR NAME' NOT NULL;
+
+- oldSchema: |
+ CREATE TABLE `book` (`name` VARCHAR(50) NOT NULL);
+ newSchema: |
+ CREATE TABLE `book` (`name` VARCHAR(50) COMMENT 'AUTHOR NAME' NOT NULL);
+ diff: |+
+ ALTER TABLE `book` MODIFY COLUMN `name` VARCHAR(50) COMMENT 'AUTHOR NAME' NOT NULL;
+
+- oldSchema: |
+ CREATE TABLE `book` (`name` VARCHAR(50) COMMENT 'AUTHOR NAME' NOT NULL);
+ newSchema: |
+ CREATE TABLE `book` (`name` VARCHAR(50) NOT NULL);
+ diff: |+
+ ALTER TABLE `book` MODIFY COLUMN `name` VARCHAR(50) NOT NULL;
+
+- oldSchema: |
+ CREATE TABLE `book` (`name` VARCHAR(50) COMMENT 'AUTHOR NAME' NOT NULL);
+ newSchema: |
+ CREATE TABLE `book` (`name` VARCHAR(50) COMMENT 'AUTHOR NAME' NOT NULL);
+ diff: ""
+- oldSchema: |
+ CREATE TABLE `book` (`name` VARCHAR(50) NOT NULL);
+ newSchema: |
+ CREATE TABLE `book` (`name` VARCHAR(50) NOT NULL);
+ diff: ""
+- oldSchema: |
+ CREATE TABLE `book` (`name` VARCHAR(50) DEFAULT 'Harry Potter' NOT NULL);
+ newSchema: |
+ CREATE TABLE `book` (`name` VARCHAR(50) NOT NULL);
+ diff: |+
+ ALTER TABLE `book` MODIFY COLUMN `name` VARCHAR(50) NOT NULL;
+
+- oldSchema: |
+ CREATE TABLE `book` (`name` VARCHAR(50) NOT NULL);
+ newSchema: |
+ CREATE TABLE `book` (`name` VARCHAR(50) DEFAULT 'Harry Potter' NOT NULL);
+ diff: |+
+ ALTER TABLE `book` MODIFY COLUMN `name` VARCHAR(50) DEFAULT 'Harry Potter' NOT NULL;
+
+- oldSchema: |
+ CREATE TABLE `book` (`name` VARCHAR(50) DEFAULT 'Holmes' NOT NULL);
+ newSchema: |
+ CREATE TABLE `book` (`name` VARCHAR(50) DEFAULT 'Harry Potter' NOT NULL);
+ diff: |+
+ ALTER TABLE `book` MODIFY COLUMN `name` VARCHAR(50) DEFAULT 'Harry Potter' NOT NULL;
+
+- oldSchema: |
+ CREATE TABLE `book` (`id` INT DEFAULT 0 NOT NULL);
+ newSchema: |
+ CREATE TABLE `book` (`id` INT NOT NULL);
+ diff: |+
+ ALTER TABLE `book` MODIFY COLUMN `id` INT NOT NULL;
+
+- oldSchema: |
+ CREATE TABLE `book` (`id` INT DEFAULT 0 NOT NULL);
+ newSchema: |
+ CREATE TABLE `book` (`id` INT DEFAULT 1 NOT NULL);
+ diff: |+
+ ALTER TABLE `book` MODIFY COLUMN `id` INT DEFAULT 1 NOT NULL;
+
+- oldSchema: |
+ CREATE TABLE `book` (`name` VARCHAR(50) DEFAULT 'Holmes' NOT NULL);
+ newSchema: |
+ CREATE TABLE `book` (`name` VARCHAR(50) DEFAULT 'Holmes' NOT NULL);
+ diff: ""
+- oldSchema: |
+ CREATE TABLE `book` (`name` VARCHAR(50) NOT NULL);
+ newSchema: |
+ CREATE TABLE `book` (`name` VARCHAR(50) NOT NULL);
+ diff: ""
+- oldSchema: |
+ CREATE TABLE `action` (
+ `action_id` smallint(5) unsigned NOT NULL AUTO_INCREMENT,
+ `last_update` timestamp not null default current_timestamp
+ );
+ newSchema: |
+ CREATE TABLE `action` (
+ `action_id` smallint(5) unsigned NOT NULL AUTO_INCREMENT,
+ `last_update` timestamp not null default current_timestamp(1)
+ );
+ diff: |+
+ ALTER TABLE `action` MODIFY COLUMN `last_update` timestamp not null default current_timestamp(1);
+
+- oldSchema: |
+ CREATE TABLE `book` (`name` VARCHAR(50) COLLATE utf8mb4_bin DEFAULT 'Harry Potter' NOT NULL);
+ newSchema: |
+ CREATE TABLE `book` (`name` VARCHAR(50) COLLATE utf8mb4_polish_ci DEFAULT 'Harry Potter' NOT NULL);
+ diff: |+
+ ALTER TABLE `book` MODIFY COLUMN `name` VARCHAR(50) COLLATE utf8mb4_polish_ci DEFAULT 'Harry Potter' NOT NULL;
+
+- oldSchema: |
+ CREATE TABLE `book` (`name` VARCHAR(50) DEFAULT 'Harry Potter' NOT NULL);
+ newSchema: |
+ CREATE TABLE `book` (`name` VARCHAR(50) COLLATE utf8mb4_polish_ci DEFAULT 'Harry Potter' NOT NULL);
+ diff: |+
+ ALTER TABLE `book` MODIFY COLUMN `name` VARCHAR(50) COLLATE utf8mb4_polish_ci DEFAULT 'Harry Potter' NOT NULL;
+
+- oldSchema: |
+ CREATE TABLE `book` (`name` VARCHAR(50) DEFAULT 'Harry Potter' NOT NULL);
+ newSchema: |
+ CREATE TABLE `book` (`name` VARCHAR(50) DEFAULT 'Harry Potter' NOT NULL);
+ diff: ""
+- oldSchema: |
+ CREATE TABLE `book` (`name` VARCHAR(50) COLLATE utf8mb4_bin DEFAULT 'Harry Potter' NOT NULL);
+ newSchema: |
+ CREATE TABLE `book` (`name` VARCHAR(50) COLLATE utf8mb4_bin DEFAULT 'Harry Potter' NOT NULL);
+ diff: ""
+- oldSchema: |
+ CREATE TABLE `book` (`id` INT PRIMARY KEY);
+ newSchema: |
+ CREATE TABLE `book` (
+ `id` INT PRIMARY KEY,
+ `name` VARCHAR(50) NOT NULL,
+ `author` VARCHAR(50) NOT NULL
+ );
+ diff: |+
+ ALTER TABLE `book` ADD COLUMN `name` VARCHAR(50) NOT NULL AFTER `id`;
+
+ ALTER TABLE `book` ADD COLUMN `author` VARCHAR(50) NOT NULL AFTER `name`;
+
+- oldSchema: |
+ CREATE TABLE `book` (`author` VARCHAR(50) NOT NULL);
+ newSchema: |
+ CREATE TABLE `book` (
+ `id` INT PRIMARY KEY,
+ `name` VARCHAR(50) NOT NULL,
+ `author` VARCHAR(50) NOT NULL
+ );
+ diff: |+
+ ALTER TABLE `book` ADD COLUMN `id` INT PRIMARY KEY FIRST;
+
+ ALTER TABLE `book` ADD COLUMN `name` VARCHAR(50) NOT NULL AFTER `id`;
+
+- oldSchema: |
+ CREATE TABLE `book` (
+ `id` INT PRIMARY KEY,
+ `author` VARCHAR(50) NOT NULL
+ );
+ newSchema: |
+ CREATE TABLE `book` (
+ `id` INT PRIMARY KEY,
+ `name` VARCHAR(50) NOT NULL,
+ `author` VARCHAR(50) NOT NULL
+ );
+ diff: |+
+ ALTER TABLE `book` ADD COLUMN `name` VARCHAR(50) NOT NULL AFTER `id`;
+
+- oldSchema: |
+ CREATE TABLE `book` (
+ `author` VARCHAR(50) NOT NULL,
+ `id` INT PRIMARY KEY,
+ `name` VARCHAR(50) NOT NULL
+ );
+ newSchema: |
+ CREATE TABLE `book` (
+ `id` INT PRIMARY KEY,
+ `name` VARCHAR(50) NOT NULL,
+ `author` VARCHAR(50) NOT NULL
+ );
+ diff: ""
+- oldSchema: |
+ CREATE TABLE `book` (
+ `name` VARCHAR(50) NOT NULL
+ );
+ newSchema: |
+ CREATE TABLE `book` (
+ `author` VARCHAR(50) NOT NULL
+ );
+ diff: |+
+ ALTER TABLE `book` ADD COLUMN `author` VARCHAR(50) NOT NULL FIRST;
+
+ ALTER TABLE `book` DROP COLUMN `name`;
+
+- oldSchema: |
+ CREATE TABLE `book` (
+ `c1` INT,
+ `c2` INT,
+ `c3` INT,
+ `c4` INT,
+ `c8` INT
+ );
+ newSchema: |
+ CREATE TABLE `book` (
+ `c9` INT,
+ `c8` VARCHAR(10),
+ `c4` INT,
+ `c2` VARCHAR(10)
+ );
+ diff: |+
+ ALTER TABLE `book` ADD COLUMN `c9` INT FIRST;
+
+ ALTER TABLE `book` MODIFY COLUMN `c2` VARCHAR(10);
+
+ ALTER TABLE `book` MODIFY COLUMN `c8` VARCHAR(10);
+
+ ALTER TABLE `book` DROP COLUMN `c1`;
+
+ ALTER TABLE `book` DROP COLUMN `c3`;
+
+- oldSchema: |
+ CREATE TABLE `book` (
+ `c1` INT,
+ `c2` INT,
+ `c3` INT,
+ `c4` INT,
+ `c5` INT
+ );
+ newSchema: |
+ CREATE TABLE `book` (
+ `c6` INT,
+ `c2` INT,
+ `c3` INT,
+ `c7` INT,
+ `c8` INT,
+ `c4` INT,
+ `c5` INT
+ );
+ diff: |+
+ ALTER TABLE `book` ADD COLUMN `c6` INT FIRST;
+
+ ALTER TABLE `book` ADD COLUMN `c7` INT AFTER `c3`;
+
+ ALTER TABLE `book` ADD COLUMN `c8` INT AFTER `c7`;
+
+ ALTER TABLE `book` DROP COLUMN `c1`;
+
diff --git a/backend/plugin/parser/mysql/test-data/test_differ_constraint.yaml b/backend/plugin/parser/mysql/test-data/test_differ_constraint.yaml
new file mode 100644
index 0000000000..bff39e49cb
--- /dev/null
+++ b/backend/plugin/parser/mysql/test-data/test_differ_constraint.yaml
@@ -0,0 +1,242 @@
+- oldSchema: |
+ create table t1(
+ a int,
+ b int,
+ constraint check_a check(a > 1),
+ constraint check_b check(b > 1)
+ );
+ newSchema: |
+ create table t1(
+ a int,
+ b int,
+ constraint check_b check(b > 1),
+ constraint check_a check(a > 1)
+ )
+ diff: ""
+- oldSchema: |
+ create table `t1` (
+ `a` INT,
+ `b` INT,
+ CONSTRAINT `check_a` CHECK((`a`>`b`)),
+ CONSTRAINT `check_b` CHECK((`b`>1))
+ );
+ newSchema: |
+ create table `t1` (
+ `a` INT,
+ `b` INT,
+ CONSTRAINT `check_b` CHECK((`b`>`a`)),
+ CONSTRAINT `check_c` CHECK((`a`>1))
+ );
+ diff: |+
+ ALTER TABLE `t1` DROP CHECK `check_a`;
+
+ ALTER TABLE `t1` DROP CHECK `check_b`;
+
+ ALTER TABLE `t1` ADD CONSTRAINT `check_b` CHECK((`b`>`a`));
+
+ ALTER TABLE `t1` ADD CONSTRAINT `check_c` CHECK((`a`>1));
+
+- oldSchema: |
+ create table `book` (
+ `a` INT,
+ CONSTRAINT `t1_chk_1` CHECK((`a`> 0))
+ );
+ newSchema: |
+ create table `book` (
+ `a` INT,
+ CONSTRAINT `t1_chk_1` CHECK((`a`> 0))
+ );
+ diff: ""
+- oldSchema: |
+ create table `book` (
+ `id` INT,
+ `price` INT,
+ PRIMARY KEY(`id`),
+ CONSTRAINT `check_price` CHECK((price > 0))
+ );
+ newSchema: |
+ create table `book` (
+ `id` INT,
+ `price` INT,
+ PRIMARY KEY(`id`),
+ CONSTRAINT `check_price` CHECK((price > 1))
+ );
+ diff: |+
+ ALTER TABLE `book` DROP CHECK `check_price`;
+
+ ALTER TABLE `book` ADD CONSTRAINT `check_price` CHECK((price > 1));
+
+- oldSchema: |
+ create table `book` (
+ `id` INT,
+ `price` INT,
+ PRIMARY KEY(`id`),
+ CONSTRAINT `check_price` CHECK((price > 0))
+ );
+ newSchema: |
+ create table `book` (
+ `id` INT,
+ `price` INT,
+ PRIMARY KEY(`id`),
+ CONSTRAINT `check_price` CHECK((price > 1)) NOT ENFORCED
+ );
+ diff: |+
+ ALTER TABLE `book` DROP CHECK `check_price`;
+
+ ALTER TABLE `book` ADD CONSTRAINT `check_price` CHECK((price > 1)) NOT ENFORCED;
+
+- oldSchema: |
+ create table `book` (
+ `id` INT,
+ `price` INT,
+ PRIMARY KEY(`id`),
+ CONSTRAINT `check_price` CHECK((price > 0))
+ );
+ newSchema: |
+ create table `book` (
+ `id` INT,
+ `price` INT,
+ PRIMARY KEY(`id`),
+ CONSTRAINT `check_price` CHECK((price > 0)) NOT ENFORCED
+ );
+ diff: |+
+ ALTER TABLE `book` DROP CHECK `check_price`;
+
+ ALTER TABLE `book` ADD CONSTRAINT `check_price` CHECK((price > 0)) NOT ENFORCED;
+
+- oldSchema: |
+ create table `book` (
+ `id` INT,
+ `price` INT,
+ PRIMARY KEY(`id`),
+ CONSTRAINT `check_price` CHECK((`price` > 0)),
+ CONSTRAINT `check_price2` CHECK((`price` > 1))
+ );
+ newSchema: |
+ create table `book` (
+ `id` INT,
+ `price` INT,
+ PRIMARY KEY(`id`),
+ CONSTRAINT `check_price` CHECK((price > 0)) NOT ENFORCED
+ );
+ diff: |+
+ ALTER TABLE `book` DROP CHECK `check_price`;
+
+ ALTER TABLE `book` DROP CHECK `check_price2`;
+
+ ALTER TABLE `book` ADD CONSTRAINT `check_price` CHECK((price > 0)) NOT ENFORCED;
+
+- oldSchema: |
+ 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(`department`), FOREIGN KEY employee_ibfk_1(department_id) REFERENCES department(`id`));
+ newSchema: |
+ 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(`department`), FOREIGN KEY fk_2(department_id) REFERENCES department(`id`));
+ diff: |+
+ ALTER TABLE `employee` DROP FOREIGN KEY `employee_ibfk_1`;
+
+ ALTER TABLE employee ADD FOREIGN KEY fk_2(department_id) REFERENCES department(`id`);
+
+- oldSchema: |
+ 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(`department`),
+ 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;;
+ newSchema: |
+ 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(`department`),
+ 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;;
+ diff: |+
+ ALTER TABLE `employee` DROP FOREIGN KEY `employee_ibfk_1`;
+
+ DROP INDEX `id_name_idx` ON `department`;
+
+ DROP INDEX `department_id_name_idx` ON `employee`;
+
+ CREATE INDEX `id_idx` ON `department`(`id`);
+
+ CREATE INDEX `department_id_idx` ON `employee`(`department_id`);
+
+ ALTER TABLE employee ADD CONSTRAINT `employee_ibfk_1` FOREIGN KEY (`department_id`) REFERENCES `department`(`id`);
+
+- oldSchema: |
+ CREATE TABLE `employee` (
+ `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 `employee`(`id`)
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;;
+ newSchema: |
+ CREATE TABLE `employee` (
+ `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`) REFERENCES `employee`(`id`)
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;;
+ diff: |+
+ ALTER TABLE `employee` DROP FOREIGN KEY `employee_ibfk_1`;
+
+ ALTER TABLE `employee` ADD COLUMN `manager_id` INT DEFAULT NULL AFTER `leader_id`;
+
+ ALTER TABLE employee ADD CONSTRAINT `employee_ibfk_1` FOREIGN KEY (`manager`) REFERENCES `employee`(`id`);
+
+- oldSchema: |
+ create table `book` (
+ `a` INT,
+ CONSTRAINT `t1_chk_1` CHECK((`a`> 0))
+ );
+ newSchema: |
+ create table `book` (
+ `a` INT,
+ CONSTRAINT `t1_chk_1` CHECK((`a`> 0))
+ );
+ diff: ""
+- oldSchema: |
+ create table `book` (
+ `id` INT,
+ `price` INT,
+ PRIMARY KEY(`id`),
+ CONSTRAINT `check_price` CHECK((price > 0))
+ );
+ newSchema: |
+ create table `book` (
+ `id` INT,
+ `price` INT,
+ PRIMARY KEY(`id`),
+ CONSTRAINT `check_price` CHECK((price > 1))
+ );
+ diff: |+
+ ALTER TABLE `book` DROP CHECK `check_price`;
+
+ ALTER TABLE `book` ADD CONSTRAINT `check_price` CHECK((price > 1));
+
diff --git a/backend/plugin/parser/mysql/test-data/test_differ_event.yaml b/backend/plugin/parser/mysql/test-data/test_differ_event.yaml
new file mode 100644
index 0000000000..5aef4600f6
--- /dev/null
+++ b/backend/plugin/parser/mysql/test-data/test_differ_event.yaml
@@ -0,0 +1,29 @@
+- oldSchema: ""
+ newSchema: |
+ DELIMITER ;;
+ CREATE EVENT e_totals ON SCHEDULE AT '2006-02-10 23:59:00' DO INSERT INTO test.totals VALUES(NOW());;
+ DELIMITER ;
+ diff: |+
+ DELIMITER ;;
+ CREATE EVENT e_totals ON SCHEDULE AT '2006-02-10 23:59:00' DO INSERT INTO test.totals VALUES(NOW());;
+ DELIMITER ;
+
+- oldSchema: |
+ DELIMITER ;;
+ CREATE EVENT e_totals ON SCHEDULE AT '2006-02-10 23:59:00' DO INSERT INTO test.totals VALUES(NOW());;
+ DELIMITER ;
+ newSchema: ""
+ diff: |+
+ DROP EVENT IF EXISTS `e_totals`;
+
+- oldSchema: |
+ CREATE EVENT `purge_old_users` ON SCHEDULE EVERY 1 DAY STARTS '2023-07-01 00:00:00' DO DELETE FROM users WHERE age > 100;
+ newSchema: |
+ CREATE EVENT `purge_old_users` ON SCHEDULE EVERY 1 DAY STARTS '2023-07-01 00:00:00' DO DELETE FROM users WHERE age > 110;
+ diff: |+
+ DROP EVENT IF EXISTS `purge_old_users`;
+
+ DELIMITER ;;
+ CREATE EVENT `purge_old_users` ON SCHEDULE EVERY 1 DAY STARTS '2023-07-01 00:00:00' DO DELETE FROM users WHERE age > 110;;
+ DELIMITER ;
+
diff --git a/backend/plugin/parser/mysql/test-data/test_differ_function.yaml b/backend/plugin/parser/mysql/test-data/test_differ_function.yaml
new file mode 100644
index 0000000000..0ec19ba01d
--- /dev/null
+++ b/backend/plugin/parser/mysql/test-data/test_differ_function.yaml
@@ -0,0 +1,44 @@
+- oldSchema: ""
+ newSchema: |
+ DELIMITER ;;
+ CREATE FUNCTION no_of_years(date1 date) RETURNS int DETERMINISTIC
+ BEGIN
+ DECLARE date2 DATE;
+ Select current_date()into date2;
+ RETURN year(date2)-year(date1);
+ END;;
+ DELIMITER ;
+ diff: |+
+ DELIMITER ;;
+ CREATE FUNCTION no_of_years(date1 date) RETURNS int DETERMINISTIC
+ BEGIN
+ DECLARE date2 DATE;
+ Select current_date()into date2;
+ RETURN year(date2)-year(date1);
+ END;;
+ DELIMITER ;
+
+- oldSchema: |
+ DELIMITER ;;
+ CREATE FUNCTION no_of_years(date1 date) RETURNS int DETERMINISTIC
+ BEGIN
+ DECLARE date2 DATE;
+ Select current_date()into date2;
+ RETURN year(date2)-year(date1);
+ END;;
+ DELIMITER ;
+ newSchema: ""
+ diff: |+
+ DROP FUNCTION IF EXISTS `no_of_years`;
+
+- oldSchema: |
+ CREATE DEFINER=`root`@`%` FUNCTION `AddOne`(`v` INT) RETURNS int BEGIN DECLARE a INT; SET a = v; SET a = a + 1; RETURN a; END;
+ newSchema: |
+ CREATE DEFINER=`root`@`%` FUNCTION `AddOne`(`v` INT) RETURNS int BEGIN DECLARE a INT; SET a = v; SET a = a * 1 + 1; RETURN a; END;
+ diff: |+
+ DROP FUNCTION IF EXISTS `AddOne`;
+
+ DELIMITER ;;
+ CREATE DEFINER=`root`@`%` FUNCTION `AddOne`(`v` INT) RETURNS int BEGIN DECLARE a INT; SET a = v; SET a = a * 1 + 1; RETURN a; END;;
+ DELIMITER ;
+
diff --git a/backend/plugin/parser/mysql/test-data/test_differ_index.yaml b/backend/plugin/parser/mysql/test-data/test_differ_index.yaml
new file mode 100644
index 0000000000..a721cd6a3e
--- /dev/null
+++ b/backend/plugin/parser/mysql/test-data/test_differ_index.yaml
@@ -0,0 +1,186 @@
+- oldSchema: |
+ CREATE TABLE `t1` (`id` INT);
+ newSchema: |
+ CREATE TABLE `t1` (`id` INT);
+ CREATE INDEX `i1` ON `t1` (`id`);
+ diff: |+
+ CREATE INDEX `i1` ON `t1` (`id`);
+
+- oldSchema: |
+ CREATE TABLE `t1` (`id` INT);
+ CREATE INDEX `i1` ON `t1` (id);
+ newSchema: |
+ CREATE TABLE `t1` (`id` INT);
+ diff: |+
+ DROP INDEX `i1` ON `t1`;
+
+- oldSchema: |
+ CREATE TABLE `t1` (
+ `a` INT NOT NULL,
+ `b` INT NOT NULL,
+ `c` INT NOT NULL
+ );
+ CREATE INDEX `idx1` ON `t1` (`a`, `b`, (`c`+1)) USING BTREE;
+ CREATE INDEX `idx2` ON `t1` (`a`) USING HASH;
+ newSchema: |
+ CREATE TABLE `t1` (
+ `a` INT NOT NULL,
+ `b` INT NOT NULL,
+ `c` INT NOT NULL
+ );
+ CREATE INDEX `idx2` ON `t1` (`a`) USING btree;
+ CREATE INDEX `idx3` ON `t1` (`a`, `b`) USING btree;
+ diff: |+
+ DROP INDEX `idx1` ON `t1`;
+
+ DROP INDEX `idx2` ON `t1`;
+
+ CREATE INDEX `idx2` ON `t1` (`a`) USING btree;
+
+ CREATE INDEX `idx3` ON `t1` (`a`, `b`) USING btree;
+
+- oldSchema: "CREATE TABLE `t1` (\n `a` char(20),\n `b` char(20) \n);\nCREATE INDEX `i1` ON `t1`(`a`) USING BTREE;\nCREATE INDEX `i2` ON `t1`(`a`) USING BTREE;\n"
+ newSchema: "CREATE TABLE `t1` (\n `a` char(20),\n `b` char(20) \n);\nCREATE INDEX `i1` ON `t1`(`a`) USING BTREE;\nCREATE INDEX `i2` ON `t1`(`b`) USING BTREE;\n"
+ diff: |+
+ DROP INDEX `i2` ON `t1`;
+
+ CREATE INDEX `i2` ON `t1`(`b`) USING BTREE;
+
+- oldSchema: |
+ CREATE TABLE `book` (`name` VARCHAR(50) NOT NULL, INDEX `book_idx` (`name`) KEY_BLOCK_SIZE=30);
+ newSchema: |
+ CREATE TABLE `book` (`name` VARCHAR(50) NOT NULL, INDEX `book_idx` (`name`) KEY_BLOCK_SIZE=50);
+ diff: |+
+ DROP INDEX `book_idx` ON `book`;
+
+ CREATE INDEX `book_idx` ON `book`(`name`) KEY_BLOCK_SIZE=50;
+
+- oldSchema: |
+ CREATE TABLE `book` (`name` VARCHAR(50) NOT NULL, INDEX `book_idx` (`name`) COMMENT 'comment_a');
+ newSchema: |
+ CREATE TABLE `book` (`name` VARCHAR(50) NOT NULL, INDEX `book_idx` (`name`) COMMENT 'comment_b');
+ diff: |+
+ DROP INDEX `book_idx` ON `book`;
+
+ CREATE INDEX `book_idx` ON `book`(`name`) COMMENT 'comment_b';
+
+- oldSchema: |
+ CREATE TABLE `book` (`name` VARCHAR(50) NOT NULL, INDEX `book_idx` (`name`) VISIBLE);
+ newSchema: |
+ CREATE TABLE `book` (`name` VARCHAR(50) NOT NULL, INDEX `book_idx` (`name`) INVISIBLE);
+ diff: |+
+ DROP INDEX `book_idx` ON `book`;
+
+ CREATE INDEX `book_idx` ON `book`(`name`) INVISIBLE;
+
+- oldSchema: |
+ CREATE TABLE `book` (`name` VARCHAR(50) NOT NULL, FULLTEXT INDEX `book_idx` (`name`) KEY_BLOCK_SIZE=30 COMMENT 'no difference');
+ newSchema: |
+ CREATE TABLE `book` (`name` VARCHAR(50) NOT NULL, FULLTEXT INDEX `book_idx` (`name`) KEY_BLOCK_SIZE=30 COMMENT 'no difference');
+ diff: ""
+- oldSchema: |
+ CREATE TABLE `book` (`name` VARCHAR(50) NOT NULL, CONSTRAINT PRIMARY KEY (`name`) KEY_BLOCK_SIZE=30);
+ newSchema: |
+ CREATE TABLE `book` (`name` VARCHAR(50) NOT NULL, CONSTRAINT PRIMARY KEY (`name`) KEY_BLOCK_SIZE=50);
+ diff: |+
+ ALTER TABLE `book` DROP PRIMARY KEY;
+
+ ALTER TABLE `book` ADD PRIMARY KEY (`name`) KEY_BLOCK_SIZE=50;
+
+- oldSchema: |
+ CREATE TABLE `book` (`name` VARCHAR(50) NOT NULL, CONSTRAINT PRIMARY KEY (`name`) VISIBLE);
+ newSchema: |
+ CREATE TABLE `book` (`name` VARCHAR(50) NOT NULL, CONSTRAINT PRIMARY KEY (`name`) INVISIBLE);
+ diff: |+
+ ALTER TABLE `book` DROP PRIMARY KEY;
+
+ ALTER TABLE `book` ADD PRIMARY KEY (`name`) INVISIBLE;
+
+- oldSchema: |
+ CREATE TABLE `book` (`name` VARCHAR(50) NOT NULL, CONSTRAINT PRIMARY KEY (`name`) KEY_BLOCK_SIZE=30 COMMENT 'no difference');
+ newSchema: |
+ CREATE TABLE `book` (`name` VARCHAR(50) NOT NULL, CONSTRAINT PRIMARY KEY (`name`) KEY_BLOCK_SIZE=30 COMMENT 'no difference');
+ diff: ""
+- oldSchema: |
+ CREATE TABLE `book` (`id` INT, `name` VARCHAR(50) NOT NULL, INDEX `book_idx` USING BTREE (`id`, `name`) COMMENT 'comment_a');
+ newSchema: |
+ CREATE TABLE `book` (`id` INT, `name` VARCHAR(50) NOT NULL, INDEX `book_idx` USING BTREE (`id`) COMMENT 'comment_a');
+ diff: |+
+ DROP INDEX `book_idx` ON `book`;
+
+ CREATE INDEX `book_idx` ON `book`(`id`) USING BTREE COMMENT 'comment_a';
+
+- oldSchema: |
+ CREATE TABLE `book` (`id` INT, `name` VARCHAR(50) NOT NULL, INDEX `book_idx` TYPE BTREE (`id`, `name`) COMMENT 'comment_a');
+ newSchema: |
+ CREATE TABLE `book` (`id` INT, `name` VARCHAR(50) NOT NULL, INDEX `book_idx` TYPE BTREE (`id`) COMMENT 'comment_a');
+ diff: |+
+ DROP INDEX `book_idx` ON `book`;
+
+ CREATE INDEX `book_idx` ON `book`(`id`) TYPE BTREE COMMENT 'comment_a';
+
+- oldSchema: |
+ CREATE TABLE `book` (`id` INT, `name` VARCHAR(50) NOT NULL, INDEX `book_idx` USING BTREE (`id`) COMMENT 'comment_a');
+ newSchema: |
+ CREATE TABLE `book` (`id` INT, `name` VARCHAR(50) NOT NULL, INDEX `book_idx` USING BTREE ((`id` + 1)) COMMENT 'comment_a');
+ diff: |+
+ DROP INDEX `book_idx` ON `book`;
+
+ CREATE INDEX `book_idx` ON `book`((`id` + 1)) USING BTREE COMMENT 'comment_a';
+
+- oldSchema: |
+ CREATE TABLE `book` (`id` INT, `name` VARCHAR(50) NOT NULL, INDEX `book_idx` USING BTREE ((`id` + 1)) COMMENT 'comment_a');
+ newSchema: |
+ CREATE TABLE `book` (`id` INT, `name` VARCHAR(50) NOT NULL, INDEX `book_idx` USING BTREE ((`id` + 2)) COMMENT 'comment_a');
+ diff: |+
+ DROP INDEX `book_idx` ON `book`;
+
+ CREATE INDEX `book_idx` ON `book`((`id` + 2)) USING BTREE COMMENT 'comment_a';
+
+- oldSchema: |
+ CREATE TABLE `book` (`id` INT, `name` VARCHAR(50) NOT NULL, INDEX `book_idx` USING BTREE (`id`, `name`) COMMENT 'comment_a');
+ newSchema: |
+ CREATE TABLE `book` (`id` INT, `name` VARCHAR(50) NOT NULL, INDEX `book_idx` USING BTREE (`id`, `name`) COMMENT 'comment_a');
+ diff: ""
+- oldSchema: |
+ CREATE TABLE `book` (`id` INT, `name` VARCHAR(50) NOT NULL, INDEX `book_idx` USING BTREE ((`id` + 1)) COMMENT 'comment_a');
+ newSchema: |
+ CREATE TABLE `book` (`id` INT, `name` VARCHAR(50) NOT NULL, INDEX `book_idx` USING BTREE ((`id` + 1)) COMMENT 'comment_a');
+ diff: ""
+- oldSchema: |
+ CREATE TABLE `book` (`id` INT, `name` VARCHAR(50) NOT NULL, CONSTRAINT PRIMARY KEY (`id`, `name`) COMMENT 'comment_a');
+ newSchema: |
+ CREATE TABLE `book` (`id` INT, `name` VARCHAR(50) NOT NULL, CONSTRAINT PRIMARY KEY (`name`) COMMENT 'comment_b');
+ diff: |+
+ ALTER TABLE `book` DROP PRIMARY KEY;
+
+ ALTER TABLE `book` ADD PRIMARY KEY (`name`) COMMENT 'comment_b';
+
+- oldSchema: |
+ CREATE TABLE `book` (`id` INT, `name` VARCHAR(50) NOT NULL, CONSTRAINT PRIMARY KEY (`id`) COMMENT 'comment_a');
+ newSchema: |
+ CREATE TABLE `book` (`id` INT, `name` VARCHAR(50) NOT NULL, CONSTRAINT PRIMARY KEY ((`id` + 1)) COMMENT 'comment_b');
+ diff: |+
+ ALTER TABLE `book` DROP PRIMARY KEY;
+
+ ALTER TABLE `book` ADD PRIMARY KEY ((`id` + 1)) COMMENT 'comment_b';
+
+- oldSchema: |
+ CREATE TABLE `book` (`id` INT, `name` VARCHAR(50) NOT NULL, CONSTRAINT PRIMARY KEY ((`id` + 1)) COMMENT 'comment_b');
+ newSchema: |
+ CREATE TABLE `book` (`id` INT, `name` VARCHAR(50) NOT NULL, CONSTRAINT PRIMARY KEY ((`id` + 2)) COMMENT 'comment_b');
+ diff: |+
+ ALTER TABLE `book` DROP PRIMARY KEY;
+
+ ALTER TABLE `book` ADD PRIMARY KEY ((`id` + 2)) COMMENT 'comment_b';
+
+- oldSchema: |
+ CREATE TABLE `book` (`id` INT, `name` VARCHAR(50) NOT NULL, CONSTRAINT PRIMARY KEY (`id`, `name`) COMMENT 'comment_a');
+ newSchema: |
+ CREATE TABLE `book` (`id` INT, `name` VARCHAR(50) NOT NULL, CONSTRAINT PRIMARY KEY (`id`, `name`) COMMENT 'comment_a');
+ diff: ""
+- oldSchema: |
+ CREATE TABLE `book` (`id` INT, `name` VARCHAR(50) NOT NULL, CONSTRAINT PRIMARY KEY ((`id` + 1)) COMMENT 'comment_b');
+ newSchema: |
+ CREATE TABLE `book` (`id` INT, `name` VARCHAR(50) NOT NULL, CONSTRAINT PRIMARY KEY ((`id` + 1)) COMMENT 'comment_b');
+ diff: ""
diff --git a/backend/plugin/parser/mysql/test-data/test_differ_procedure.yaml b/backend/plugin/parser/mysql/test-data/test_differ_procedure.yaml
new file mode 100644
index 0000000000..6aec54c24a
--- /dev/null
+++ b/backend/plugin/parser/mysql/test-data/test_differ_procedure.yaml
@@ -0,0 +1,55 @@
+- oldSchema: ""
+ newSchema: |
+ DELIMITER ;;
+ CREATE PROCEDURE citycount (IN country CHAR(3), OUT cities INT)
+ BEGIN
+ SELECT COUNT(*) INTO cities FROM world.city
+ WHERE CountryCode = country;
+ END;;
+ DELIMITER ;
+ diff: |+
+ DELIMITER ;;
+ CREATE PROCEDURE citycount (IN country CHAR(3), OUT cities INT)
+ BEGIN
+ SELECT COUNT(*) INTO cities FROM world.city
+ WHERE CountryCode = country;
+ END;;
+ DELIMITER ;
+
+- oldSchema: |
+ DELIMITER ;;
+ CREATE PROCEDURE citycount (IN country CHAR(3), OUT cities INT)
+ BEGIN
+ SELECT COUNT(*) INTO cities FROM world.city
+ WHERE CountryCode = country;
+ END;;
+ DELIMITER ;
+ newSchema: ""
+ diff: |+
+ DROP PROCEDURE IF EXISTS `citycount`;
+
+- oldSchema: |
+ CREATE DEFINER=`admin`@`localhost` PROCEDURE `account_count`()
+ SQL SECURITY INVOKER
+ BEGIN
+ SELECT 'Number of accounts:', COUNT(*) FROM mysql.user;
+ END;
+ newSchema: |
+ CREATE DEFINER=`admin`@`localhost` PROCEDURE `account_count`()
+ SQL SECURITY INVOKER
+ BEGIN
+ SELECT 'Number of accounts:', (COUNT(*)-1) FROM mysql.user;
+ END ;
+ diff: |+
+ DROP PROCEDURE IF EXISTS `account_count`;
+
+ DROP PROCEDURE IF EXISTS `account_count`;
+
+ DELIMITER ;;
+ CREATE DEFINER=`admin`@`localhost` PROCEDURE `account_count`()
+ SQL SECURITY INVOKER
+ BEGIN
+ SELECT 'Number of accounts:', (COUNT(*)-1) FROM mysql.user;
+ END;;
+ DELIMITER ;
+
diff --git a/backend/plugin/parser/mysql/test-data/test_differ_table.yaml b/backend/plugin/parser/mysql/test-data/test_differ_table.yaml
new file mode 100644
index 0000000000..1e379e5541
--- /dev/null
+++ b/backend/plugin/parser/mysql/test-data/test_differ_table.yaml
@@ -0,0 +1,157 @@
+- oldSchema: |
+ CREATE TABLE `t1` (`id` INT);
+ newSchema: |
+ CREATE TABLE `t2` (`id` INT);
+ diff: |+
+ DROP TABLE IF EXISTS `t1`;
+
+ CREATE TABLE IF NOT EXISTS `t2` (`id` INT);
+
+- oldSchema: |
+ CREATE TABLE `t1` (
+ `id` INT PRIMARY KEY,
+ `username` VARCHAR(55) NOT NULL
+ );
+ newSchema: |
+ CREATE TABLE `t2` (`id` INT);
+ CREATE TABLE `t1` (
+ `id` INT PRIMARY KEY,
+ `username` VARCHAR(55) NOT NULL
+ );
+ diff: |+
+ CREATE TABLE IF NOT EXISTS `t2` (`id` INT);
+
+- oldSchema: |
+ CREATE TABLE `projects` (`id` INT);
+ newSchema: |
+ CREATE TABLE `users` (
+ `id` INT NOT NULL,
+ `username` VARCHAR(25) NOT NULL,
+ PRIMARY KEY (`id`)
+ );
+ CREATE TABLE `projects` (`id` INT);
+
+ CREATE TABLE `repositories` (
+ `id` INT NOT NULL,
+ PRIMARY KEY (`id`)
+ );
+ diff: |+
+ CREATE TABLE IF NOT EXISTS `repositories` (
+ `id` INT NOT NULL,
+ PRIMARY KEY (`id`)
+ );
+
+ CREATE TABLE IF NOT EXISTS `users` (
+ `id` INT NOT NULL,
+ `username` VARCHAR(25) NOT NULL,
+ PRIMARY KEY (`id`)
+ );
+
+- oldSchema: |
+ CREATE TABLE `t1` (
+ `a` int,
+ `b` int,
+ `c` int
+ );
+ CREATE INDEX `idx_t1_a` ON `t1`(`a`);
+ newSchema: ""
+ diff: |+
+ DROP TABLE IF EXISTS `t1`;
+
+- oldSchema: |
+ CREATE TABLE `t1` (
+ `id` INT
+ );
+ newSchema: |
+ CREATE TABLE `book` (
+ `id` INT,
+ `price` INT,
+ PRIMARY KEY(`id`)
+ );
+ CREATE TABLE `author` (
+ `id` INT,
+ `name` VARCHAR(255),
+ PRIMARY KEY(`id`)
+ );
+ diff: |+
+ DROP TABLE IF EXISTS `t1`;
+
+ CREATE TABLE IF NOT EXISTS `author` (
+ `id` INT,
+ `name` VARCHAR(255),
+ PRIMARY KEY(`id`)
+ );
+
+ CREATE TABLE IF NOT EXISTS `book` (
+ `id` INT,
+ `price` INT,
+ PRIMARY KEY(`id`)
+ );
+
+- oldSchema: |
+ CREATE TABLE `book` (
+ `id` INT,
+ `price` INT,
+ PRIMARY KEY(`id`)
+ );;
+ newSchema: |
+ CREATE TABLE `author` (
+ `id` INT,
+ `name` VARCHAR(255),
+ PRIMARY KEY(`id`)
+ );
+ diff: |+
+ DROP TABLE IF EXISTS `book`;
+
+ CREATE TABLE IF NOT EXISTS `author` (
+ `id` INT,
+ `name` VARCHAR(255),
+ PRIMARY KEY(`id`)
+ );
+
+- oldSchema: |
+ CREATE TABLE `book` (
+ `id` INT,
+ `price` INT,
+ PRIMARY KEY(`id`)
+ );
+ CREATE TABLE `author` (
+ `id` INT,
+ `name` VARCHAR(255),
+ PRIMARY KEY(`id`)
+ );
+ newSchema: |
+ CREATE TABLE `book` (
+ `id` INT,
+ `price` INT,
+ PRIMARY KEY(`id`)
+ );
+ CREATE TABLE `author` (
+ `id` INT,
+ `name` VARCHAR(255),
+ PRIMARY KEY(`id`)
+ );
+ diff: ""
+- oldSchema: |
+ CREATE TABLE `book` (
+ `id` INT,
+ `price` INT,
+ PRIMARY KEY(`id`),
+ CONSTRAINT `fk_price_id` FOREIGN KEY (`price`) REFERENCES price(`id`)
+ );
+ CREATE TABLE `price` (
+ `id` INT,
+ PRIMARY KEY(`id`)
+ );
+ newSchema: |
+ CREATE TABLE `book` (
+ `id` INT,
+ PRIMARY KEY(`id`)
+ );
+ diff: |+
+ ALTER TABLE `book` DROP FOREIGN KEY `fk_price_id`;
+
+ DROP TABLE IF EXISTS `price`;
+
+ ALTER TABLE `book` DROP COLUMN `price`;
+
diff --git a/backend/plugin/parser/mysql/test-data/test_differ_tableoption.yaml b/backend/plugin/parser/mysql/test-data/test_differ_tableoption.yaml
new file mode 100644
index 0000000000..2f3ddd6a77
--- /dev/null
+++ b/backend/plugin/parser/mysql/test-data/test_differ_tableoption.yaml
@@ -0,0 +1,485 @@
+# AUTO_INCREMENT
+- oldSchema: |
+ CREATE TABLE `book` (
+ `id` INT AUTO_INCREMENT,
+ PRIMARY KEY(`id`)
+ ) AUTO_INCREMENT = 4;
+ newSchema: |
+ CREATE TABLE `book` (
+ `id` INT AUTO_INCREMENT,
+ PRIMARY KEY(`id`)
+ ) AUTO_INCREMENT = 10;
+ diff: |+
+ ALTER TABLE `book` AUTO_INCREMENT = 10;
+
+- oldSchema: |
+ CREATE TABLE `book` (
+ `id` INT AUTO_INCREMENT,
+ PRIMARY KEY(`id`)
+ ) AUTO_INCREMENT = 4;
+ newSchema: |
+ CREATE TABLE `book` (
+ `id` INT AUTO_INCREMENT,
+ PRIMARY KEY(`id`)
+ );
+ diff: |+
+ ALTER TABLE `book` AUTO_INCREMENT = 0;
+
+- oldSchema: |
+ CREATE TABLE `book` (
+ `id` INT,
+ PRIMARY KEY(`id`)
+ ) AVG_ROW_LENGTH = 1;
+ newSchema: |
+ CREATE TABLE `book` (
+ `id` INT,
+ PRIMARY KEY(`id`)
+ ) AVG_ROW_LENGTH = 2;
+ diff: |+
+ ALTER TABLE `book` AUTO_INCREMENT = 2;
+
+# AVG_ROW_LENGTH
+- oldSchema: |
+ CREATE TABLE `book` (
+ `id` INT,
+ PRIMARY KEY(`id`)
+ ) AVG_ROW_LENGTH = 1;
+ newSchema: |
+ CREATE TABLE `book` (
+ `id` INT,
+ PRIMARY KEY(`id`)
+ );
+ diff: |+
+ ALTER TABLE `book` AVG_ROW_LENGTH = 0;
+
+- oldSchema: |
+ CREATE TABLE `book` (
+ `id` INT,
+ PRIMARY KEY(`id`)
+ ) AVG_ROW_LENGTH = 1;
+ newSchema: |
+ CREATE TABLE `book` (
+ `id` INT,
+ PRIMARY KEY(`id`)
+ ) AVG_ROW_LENGTH = 2;
+ diff: |+
+ ALTER TABLE `book` AVG_ROW_LENGTH = 2;
+
+# DEFAULT CHARSET
+- oldSchema: |
+ CREATE TABLE `book` (
+ `id` INT,
+ PRIMARY KEY(`id`)
+ ) DEFAULT CHARACTER SET = utf8;
+ newSchema: |
+ CREATE TABLE `book` (
+ `id` INT,
+ PRIMARY KEY(`id`)
+ ) DEFAULT CHARACTER SET = utf8mb4;
+ diff: |+
+ ALTER TABLE `book` DEFAULT CHARACTER SET = utf8mb4;
+
+- oldSchema: |
+ CREATE TABLE `book` (
+ `id` INT,
+ PRIMARY KEY(`id`)
+ ) DEFAULT CHARSET = utf8;
+ newSchema: |
+ CREATE TABLE `book` (
+ `id` INT,
+ PRIMARY KEY(`id`)
+ ) DEFAULT CHARACTER SET = utf8;
+ diff: ""
+
+- oldSchema: |
+ CREATE TABLE `book` (
+ `id` INT,
+ PRIMARY KEY(`id`)
+ ) DEFAULT CHARSET = utf8;
+ newSchema: |
+ CREATE TABLE `book` (
+ `id` INT,
+ PRIMARY KEY(`id`)
+ );
+ diff: ""
+
+# DEFAULT COLLATE
+- oldSchema: |
+ CREATE TABLE `book` (
+ `id` INT,
+ PRIMARY KEY(`id`)
+ ) DEFAULT COLLATE = latin1_swedish_ci;
+ newSchema: |
+ CREATE TABLE `book` (
+ `id` INT,
+ PRIMARY KEY(`id`)
+ ) DEFAULT COLLATE = utf8mb4_general_ci;
+ diff: |+
+ ALTER TABLE `book` DEFAULT COLLATE = utf8mb4_general_ci;
+
+- oldSchema: |
+ CREATE TABLE `book` (
+ `id` INT,
+ PRIMARY KEY(`id`)
+ ) DEFAULT COLLATE = latin1_swedish_ci;
+ newSchema: |
+ CREATE TABLE `book` (
+ `id` INT,
+ PRIMARY KEY(`id`)
+ );
+ diff:
+
+# CHECKSUM
+- oldSchema: |
+ CREATE TABLE `book` (
+ `id` INT,
+ PRIMARY KEY(`id`)
+ ) CHECKSUM = 1;
+ newSchema: |
+ CREATE TABLE `book` (
+ `id` INT,
+ PRIMARY KEY(`id`)
+ ) CHECKSUM = 0;
+ diff: |+
+ ALTER TABLE `book` CHECKSUM = 0;
+
+- oldSchema: |
+ CREATE TABLE `book` (
+ `id` INT,
+ PRIMARY KEY(`id`)
+ ) CHECKSUM = 1;
+ newSchema: |
+ CREATE TABLE `book` (
+ `id` INT,
+ PRIMARY KEY(`id`)
+ );
+ diff: |+
+ ALTER TABLE `book` CHECKSUM = 0;
+
+# COMMENT
+- oldSchema: |
+ CREATE TABLE `book` (
+ `id` INT,
+ PRIMARY KEY(`id`)
+ ) COMMENT = 'old';
+ newSchema: |
+ CREATE TABLE `book` (
+ `id` INT,
+ PRIMARY KEY(`id`)
+ ) COMMENT = 'new';
+ diff: |+
+ ALTER TABLE `book` COMMENT = 'new';
+
+- oldSchema: |
+ CREATE TABLE `book` (
+ `id` INT,
+ PRIMARY KEY(`id`)
+ ) COMMENT = 'old';
+ newSchema: |
+ CREATE TABLE `book` (
+ `id` INT,
+ PRIMARY KEY(`id`)
+ );
+ diff: |+
+ ALTER TABLE `book` COMMENT = '';
+
+# COMPRESSION
+- oldSchema: |
+ CREATE TABLE `book` (
+ `id` INT,
+ PRIMARY KEY(`id`)
+ ) COMPRESSION = 'LZ4';
+ newSchema: |
+ CREATE TABLE `book` (
+ `id` INT,
+ PRIMARY KEY(`id`)
+ ) COMPRESSION = 'ZLIB';
+ diff: |+
+ ALTER TABLE `book` COMPRESSION = 'ZLIB';
+
+- oldSchema: |
+ CREATE TABLE `book` (
+ `id` INT,
+ PRIMARY KEY(`id`)
+ ) COMPRESSION = 'LZ4';
+ newSchema: |
+ CREATE TABLE `book` (
+ `id` INT,
+ PRIMARY KEY(`id`)
+ );
+ diff: |+
+ ALTER TABLE `book` COMPRESSION = 'None';
+
+# CONNECTION
+- oldSchema: |
+ CREATE TABLE `book` (
+ `id` INT,
+ PRIMARY KEY(`id`)
+ ) CONNECTION = 'old';
+ newSchema: |
+ CREATE TABLE `book` (
+ `id` INT,
+ PRIMARY KEY(`id`)
+ );
+ diff: |+
+ ALTER TABLE `book` CONNECTION = '';
+
+- oldSchema: |
+ CREATE TABLE `book` (
+ `id` INT,
+ PRIMARY KEY(`id`)
+ ) CONNECTION = 'old';
+ newSchema: |
+ CREATE TABLE `book` (
+ `id` INT,
+ PRIMARY KEY(`id`)
+ ) CONNECTION = 'new';
+ diff: |+
+ ALTER TABLE `book` CONNECTION = 'new';
+
+# DELAY_KEY_WRITE
+- oldSchema: |
+ CREATE TABLE `book` (
+ `id` INT,
+ PRIMARY KEY(`id`)
+ ) DELAY_KEY_WRITE = 1;
+ newSchema: |
+ CREATE TABLE `book` (
+ `id` INT,
+ PRIMARY KEY(`id`)
+ ) DELAY_KEY_WRITE = 0;
+ diff: |+
+ ALTER TABLE `book` DELAY_KEY_WRITE = 0;
+
+- oldSchema: |
+ CREATE TABLE `book` (
+ `id` INT,
+ PRIMARY KEY(`id`)
+ ) DELAY_KEY_WRITE = 1;
+ newSchema: |
+ CREATE TABLE `book` (
+ `id` INT,
+ PRIMARY KEY(`id`)
+ );
+ diff: |+
+ ALTER TABLE `book` DELAY_KEY_WRITE = 0;
+
+# ENCRYPTION
+- oldSchema: |
+ CREATE TABLE `book` (
+ `id` INT,
+ PRIMARY KEY(`id`)
+ ) ENCRYPTION = 'Y';
+ newSchema: |
+ CREATE TABLE `book` (
+ `id` INT,
+ PRIMARY KEY(`id`)
+ ) ENCRYPTION = 'N' ;
+ diff: |+
+ ALTER TABLE `book` ENCRYPTION = 'N';
+
+- oldSchema: |
+ CREATE TABLE `book` (
+ `id` INT,
+ PRIMARY KEY(`id`)
+ ) ENCRYPTION = 'Y';
+ newSchema: |
+ CREATE TABLE `book` (
+ `id` INT,
+ PRIMARY KEY(`id`)
+ );
+ diff: |+
+ ALTER TABLE `book` ENCRYPTION = 'N';
+
+# INSERT_METHOD
+- oldSchema: |
+ CREATE TABLE `book` (
+ `id` INT,
+ PRIMARY KEY(`id`)
+ ) INSERT_METHOD = LAST;
+ newSchema: |
+ CREATE TABLE `book` (
+ `id` INT,
+ PRIMARY KEY(`id`)
+ ) INSERT_METHOD = FIRST;
+ diff: |+
+ ALTER TABLE `book` INSERT_METHOD = FIRST;
+
+- oldSchema: |
+ CREATE TABLE `book` (
+ `id` INT,
+ PRIMARY KEY(`id`)
+ ) INSERT_METHOD = LAST;
+ newSchema: |
+ CREATE TABLE `book` (
+ `id` INT,
+ PRIMARY KEY(`id`)
+ );
+ diff: |+
+ ALTER TABLE `book` INSERT_METHOD = NO;
+
+# MAX_ROWS
+- oldSchema: |
+ CREATE TABLE `book` (
+ `id` INT,
+ PRIMARY KEY(`id`)
+ ) MAX_ROWS = 100;
+ newSchema: |
+ CREATE TABLE `book` (
+ `id` INT,
+ PRIMARY KEY(`id`)
+ ) MAX_ROWS = 200;
+ diff: |+
+ ALTER TABLE `book` MAX_ROWS = 200;
+
+- oldSchema: |
+ CREATE TABLE `book` (
+ `id` INT,
+ PRIMARY KEY(`id`)
+ ) MAX_ROWS = 100;
+ newSchema: |
+ CREATE TABLE `book` (
+ `id` INT,
+ PRIMARY KEY(`id`)
+ );
+ diff: |+
+ ALTER TABLE `book` MAX_ROWS = 0;
+
+- oldSchema: |
+ CREATE TABLE `book` (
+ `id` INT,
+ PRIMARY KEY(`id`)
+ ) MAX_ROWS = 100;
+ newSchema: |
+ CREATE TABLE `book` (
+ `id` INT,
+ PRIMARY KEY(`id`)
+ );
+ diff: |+
+ ALTER TABLE `book` MAX_ROWS = 0;
+
+- oldSchema: |
+ CREATE TABLE `book` (
+ `id` INT,
+ PRIMARY KEY(`id`)
+ ) MAX_ROWS = 100;
+ newSchema: |
+ CREATE TABLE `book` (
+ `id` INT,
+ PRIMARY KEY(`id`)
+ );
+ diff: |+
+ ALTER TABLE `book` MAX_ROWS = 0;
+
+# MIN_ROWS
+- oldSchema: |
+ CREATE TABLE `book` (
+ `id` INT,
+ PRIMARY KEY(`id`)
+ ) MIN_ROWS = 100;
+ newSchema: |
+ CREATE TABLE `book` (
+ `id` INT,
+ PRIMARY KEY(`id`)
+ );
+ diff: |+
+ ALTER TABLE `book` MIN_ROWS = 0;
+
+- oldSchema: |
+ CREATE TABLE `book` (
+ `id` INT,
+ PRIMARY KEY(`id`)
+ ) MIN_ROWS = 100;
+ newSchema: |
+ CREATE TABLE `book` (
+ `id` INT,
+ PRIMARY KEY(`id`)
+ ) MIN_ROWS = 200;
+ diff: |+
+ ALTER TABLE `book` MIN_ROWS = 200;
+
+# PACK_KEYS
+- oldSchema: |
+ CREATE TABLE `book` (
+ `id` INT,
+ PRIMARY KEY(`id`)
+ ) PACK_KEYS = 1;
+ newSchema: |
+ CREATE TABLE `book` (
+ `id` INT,
+ PRIMARY KEY(`id`)
+ );
+ diff: |+
+ ALTER TABLE `book` PACK_KEYS = DEFAULT;
+
+# ROW_FORMAT
+- oldSchema: |
+ CREATE TABLE `book` (
+ `id` INT,
+ PRIMARY KEY(`id`)
+ ) ROW_FORMAT = DYNAMIC;
+ newSchema: |
+ CREATE TABLE `book` (
+ `id` INT,
+ PRIMARY KEY(`id`)
+ ) ROW_FORMAT = COMPRESSED;
+ diff: |+
+ ALTER TABLE `book` ROW_FORMAT = COMPRESSED;
+
+- oldSchema: |
+ CREATE TABLE `book` (
+ `id` INT,
+ PRIMARY KEY(`id`)
+ ) ROW_FORMAT = DYNAMIC;
+ newSchema: |
+ CREATE TABLE `book` (
+ `id` INT,
+ PRIMARY KEY(`id`)
+ );
+ diff: |+
+ ALTER TABLE `book` ROW_FORMAT = DEFAULT;
+
+# STATS_AUTO_RECALC
+- oldSchema: |
+ CREATE TABLE `book` (
+ `id` INT,
+ PRIMARY KEY(`id`)
+ ) STATS_AUTO_RECALC = 1;
+ newSchema: |
+ CREATE TABLE `book` (
+ `id` INT,
+ PRIMARY KEY(`id`)
+ ) STATS_AUTO_RECALC = 0;
+ diff: |+
+ ALTER TABLE `book` STATS_AUTO_RECALC = 0;
+
+- oldSchema: |
+ CREATE TABLE `book` (
+ `id` INT,
+ PRIMARY KEY(`id`)
+ ) STATS_AUTO_RECALC = 1;
+ newSchema: |
+ CREATE TABLE `book` (
+ `id` INT,
+ PRIMARY KEY(`id`)
+ );
+ diff: |+
+ ALTER TABLE `book` STATS_AUTO_RECALC = DEFAULT;
+
+# UNION
+- oldSchema: |
+ CREATE TABLE `book` (
+ `id` INT,
+ PRIMARY KEY(`id`)
+ ) UNION = (`book2`);
+ newSchema: |
+ CREATE TABLE `book` (
+ `id` INT,
+ PRIMARY KEY(`id`)
+ ) UNION = (`book2`, `book3`);
+ diff: |+
+ ALTER TABLE `book` UNION = (`book2`, `book3`);
+
+
+
+
diff --git a/backend/plugin/parser/mysql/test-data/test_differ_trigger.yaml b/backend/plugin/parser/mysql/test-data/test_differ_trigger.yaml
new file mode 100644
index 0000000000..693ee24f31
--- /dev/null
+++ b/backend/plugin/parser/mysql/test-data/test_differ_trigger.yaml
@@ -0,0 +1,36 @@
+- oldSchema: ""
+ newSchema: |
+ DELIMITER ;;
+ CREATE TRIGGER ins_sum BEFORE INSERT ON account
+ FOR EACH ROW SET @sum = @sum + NEW.amount;;
+ DELIMITER ;
+ diff: |+
+ DELIMITER ;;
+ CREATE TRIGGER ins_sum BEFORE INSERT ON account
+ FOR EACH ROW SET @sum = @sum + NEW.amount;;
+ DELIMITER ;
+
+- oldSchema: |
+ DELIMITER ;;
+ CREATE TRIGGER ins_sum BEFORE INSERT ON account
+ FOR EACH ROW SET @sum = @sum + NEW.amount;;
+ DELIMITER ;
+ newSchema: ""
+ diff: |+
+ DROP TRIGGER IF EXISTS `ins_sum`;
+
+- oldSchema: |
+ 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;
+ newSchema: |
+ 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;
+ diff: |+
+ DROP TRIGGER IF EXISTS `ins_sum`;
+
+ ALTER TABLE `account` ADD COLUMN `price` INT AFTER `amount`;
+
+ DELIMITER ;;
+ CREATE DEFINER=`root`@`%` TRIGGER `ins_sum` BEFORE INSERT ON account FOR EACH ROW SET @sum = sum + NEW.amount * NEW.price;;
+ DELIMITER ;
+
diff --git a/backend/plugin/parser/mysql/test-data/test_differ_view.yaml b/backend/plugin/parser/mysql/test-data/test_differ_view.yaml
new file mode 100644
index 0000000000..3959788be2
--- /dev/null
+++ b/backend/plugin/parser/mysql/test-data/test_differ_view.yaml
@@ -0,0 +1,85 @@
+- oldSchema: |
+ CREATE VIEW `a` AS SELECT 1 AS id, 1 AS name;
+ CREATE VIEW `a` AS SELECT `id`, `name` FROM `book`;
+ newSchema: |
+ CREATE VIEW `a` AS SELECT 1 AS id;
+ CREATE VIEW `a` AS SELECT `id` FROM `book`;
+ diff: |+
+ CREATE OR REPLACE ALGORITHM=UNDEFINED DEFINER=CURRENT_USER SQL SECURITY DEFINER VIEW `a` AS SELECT `id` FROM `book`;
+
+- oldSchema: |
+ CREATE TABLE `book` (`id` INT, `name` VARCHAR(25));
+ CREATE VIEW `a` AS SELECT `id`, `name` FROM `book`;
+ newSchema: |
+ CREATE TABLE `book` (`id` INT, `name` VARCHAR(25));
+ CREATE VIEW `a` AS SELECT `id` FROM `book`;
+ CREATE VIEW `b` AS SELECT `id` FROM `a`;
+ diff: |+
+ CREATE OR REPLACE ALGORITHM=UNDEFINED DEFINER=CURRENT_USER SQL SECURITY DEFINER VIEW `b` AS SELECT SQL_NO_CACHE 1 AS `id`;
+
+ CREATE OR REPLACE ALGORITHM=UNDEFINED DEFINER=CURRENT_USER SQL SECURITY DEFINER VIEW `a` AS SELECT `id` FROM `book`;
+
+ CREATE OR REPLACE ALGORITHM=UNDEFINED DEFINER=CURRENT_USER SQL SECURITY DEFINER VIEW `b` AS SELECT `id` FROM `a`;
+
+- oldSchema: |
+ CREATE TABLE `book` (`id` INT, `name` VARCHAR(25));
+ CREATE VIEW `a` AS SELECT `id`, `name` FROM `book`;
+ newSchema: |
+ CREATE TABLE `book` (`id` INT, `name` VARCHAR(25));
+ CREATE VIEW `a` AS SELECT `id` AS `a_id` FROM `book`;
+ CREATE VIEW `b` AS SELECT `id` AS `b_id` FROM `a`;
+ diff: |+
+ CREATE OR REPLACE ALGORITHM=UNDEFINED DEFINER=CURRENT_USER SQL SECURITY DEFINER VIEW `b` AS SELECT SQL_NO_CACHE 1 AS `b_id`;
+
+ CREATE OR REPLACE ALGORITHM=UNDEFINED DEFINER=CURRENT_USER SQL SECURITY DEFINER VIEW `a` AS SELECT `id` AS `a_id` FROM `book`;
+
+ CREATE OR REPLACE ALGORITHM=UNDEFINED DEFINER=CURRENT_USER SQL SECURITY DEFINER VIEW `b` AS SELECT `id` AS `b_id` FROM `a`;
+
+- oldSchema: |
+ CREATE TABLE `book` (`id` INT, `name` VARCHAR(25));
+ CREATE VIEW `a` AS SELECT `id` FROM `book`;
+ newSchema: |
+ CREATE TABLE `book` (`id` INT, `name` VARCHAR(25));
+ CREATE VIEW `a` AS SELECT * FROM `book`;
+ CREATE VIEW `b` AS SELECT * FROM `a`;
+ diff: |+
+ CREATE OR REPLACE ALGORITHM=UNDEFINED DEFINER=CURRENT_USER SQL SECURITY DEFINER VIEW `b` AS SELECT SQL_NO_CACHE 1 AS `id`, 1 AS `name`;
+
+ CREATE OR REPLACE ALGORITHM=UNDEFINED DEFINER=CURRENT_USER SQL SECURITY DEFINER VIEW `a` AS SELECT * FROM `book`;
+
+ CREATE OR REPLACE ALGORITHM=UNDEFINED DEFINER=CURRENT_USER SQL SECURITY DEFINER VIEW `b` AS SELECT * FROM `a`;
+
+- oldSchema: ""
+ newSchema: |
+ CREATE TABLE `book` (`id` INT, `name` VARCHAR(25));
+ CREATE TABLE `e` (`c` INT, `d` INT);
+ CREATE VIEW `a` AS WITH `cte` AS (SELECT `id`, `name` FROM `book`) SELECT `id`, `name` FROM `cte` UNION SELECT `c`, `d` FROM `e`;
+ diff: |+
+ CREATE TABLE IF NOT EXISTS `book` (`id` INT, `name` VARCHAR(25));
+
+ CREATE TABLE IF NOT EXISTS `e` (`c` INT, `d` INT);
+
+ CREATE OR REPLACE ALGORITHM=UNDEFINED DEFINER=CURRENT_USER SQL SECURITY DEFINER VIEW `a` AS SELECT SQL_NO_CACHE 1 AS `id`, 1 AS `name`;
+
+ 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`;
+
+- oldSchema: |
+ CREATE TABLE `book1` (`id` INT);
+ CREATE VIEW `book` AS SELECT * FROM `book1`;
+ newSchema: |
+ CREATE TABLE `book2` (`id` INT);
+ CREATE VIEW `book` AS SELECT * FROM `book2`;
+ diff: |+
+ DROP TABLE IF EXISTS `book1`;
+
+ CREATE TABLE IF NOT EXISTS `book2` (`id` INT);
+
+ CREATE OR REPLACE ALGORITHM=UNDEFINED DEFINER=CURRENT_USER SQL SECURITY DEFINER VIEW `book` AS SELECT * FROM `book2`;
+
+- oldSchema: |
+ CREATE VIEW `order_incomes` AS SELECT `order_id`, `customer_name`, SUM((`ordered_quantity` * `product_price`)) AS `total` FROM `order_details` INNER JOIN `orders` USING (`order_id`) INNER JOIN `customers` USING (`customer_name`) GROUP BY `order_id`;
+ newSchema: |
+ CREATE VIEW order_incomes AS SELECT `order_id`, `customer_name`, SUM((`ordered_quantity` * `product_price`)) + 1 AS `total` FROM `order_details` INNER JOIN `orders` USING (`order_id`) INNER JOIN `customers` USING (`customer_name`) GROUP BY `order_id`;
+ diff: |+
+ 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` INNER JOIN `orders` USING (`order_id`) INNER JOIN `customers` USING (`customer_name`) GROUP BY `order_id`;
+
diff --git a/backend/plugin/parser/sql/transform/mysql/transform.go b/backend/plugin/parser/sql/transform/mysql/transform.go
index 8091272f76..df700f53a8 100644
--- a/backend/plugin/parser/sql/transform/mysql/transform.go
+++ b/backend/plugin/parser/sql/transform/mysql/transform.go
@@ -14,6 +14,7 @@ import (
"github.com/pkg/errors"
mysqlparser "github.com/bytebase/bytebase/backend/plugin/parser/mysql"
+ tidbparser "github.com/bytebase/bytebase/backend/plugin/parser/tidb"
storepb "github.com/bytebase/bytebase/proto/generated-go/store"
"github.com/bytebase/bytebase/backend/plugin/parser/sql/transform"
@@ -112,7 +113,7 @@ func (t *SchemaTransformer) Normalize(schema string, standard string) (string, e
remainingStatement = append(remainingStatement, stmt.Text)
continue
}
- if mysqlparser.IsTiDBUnsupportDDLStmt(stmt.Text) {
+ if tidbparser.IsTiDBUnsupportDDLStmt(stmt.Text) {
remainingStatement = append(remainingStatement, stmt.Text)
continue
}
@@ -145,7 +146,7 @@ func (t *SchemaTransformer) Normalize(schema string, standard string) (string, e
}
for _, stmt := range standardList {
- if mysqlparser.IsTiDBUnsupportDDLStmt(stmt.Text) {
+ if tidbparser.IsTiDBUnsupportDDLStmt(stmt.Text) {
// TODO(rebelice): consider the unsupported DDL.
continue
}
@@ -182,7 +183,7 @@ func (t *SchemaTransformer) Normalize(schema string, standard string) (string, e
// 3. missing indexes for existed table are below of this table and as the origin order.
// 4. missing tables are below of existed tables and as the origin order.
for _, stmt := range standardList {
- if mysqlparser.IsTiDBUnsupportDDLStmt(stmt.Text) {
+ if tidbparser.IsTiDBUnsupportDDLStmt(stmt.Text) {
// TODO(rebelice): consider the unsupported DDL.
continue
}
@@ -364,7 +365,7 @@ func (*SchemaTransformer) Check(schema string) (int, error) {
// So we need to skip the statement if the delimiter is not `;`.
continue
}
- if mysqlparser.IsTiDBUnsupportDDLStmt(stmt.Text) {
+ if tidbparser.IsTiDBUnsupportDDLStmt(stmt.Text) {
continue
}
nodeList, _, err := parser.New().Parse(stmt.Text, "", "")
@@ -458,7 +459,7 @@ func (*SchemaTransformer) Transform(schema string) (string, error) {
result = append(result, stmt.Text+"\n\n")
continue
}
- if mysqlparser.IsTiDBUnsupportDDLStmt(stmt.Text) {
+ if tidbparser.IsTiDBUnsupportDDLStmt(stmt.Text) {
result = append(result, stmt.Text+"\n\n")
continue
}
diff --git a/backend/runner/plancheck/statement_report_executor.go b/backend/runner/plancheck/statement_report_executor.go
index b921cf67f4..aba57587f6 100644
--- a/backend/runner/plancheck/statement_report_executor.go
+++ b/backend/runner/plancheck/statement_report_executor.go
@@ -19,9 +19,9 @@ import (
api "github.com/bytebase/bytebase/backend/legacyapi"
"github.com/bytebase/bytebase/backend/plugin/advisor"
"github.com/bytebase/bytebase/backend/plugin/parser/base"
- 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"
+ tidb "github.com/bytebase/bytebase/backend/plugin/parser/tidb"
"github.com/bytebase/bytebase/backend/store"
"github.com/bytebase/bytebase/backend/utils"
storepb "github.com/bytebase/bytebase/proto/generated-go/store"
@@ -417,7 +417,7 @@ func reportForMySQL(ctx context.Context, sqlDB *sql.DB, engine storepb.Engine, d
if stmt.Empty {
continue
}
- if mysqlparser.IsTiDBUnsupportDDLStmt(stmt.Text) {
+ if tidb.IsTiDBUnsupportDDLStmt(stmt.Text) {
continue
}
root, _, err := p.Parse(stmt.Text, charset, collation)
diff --git a/backend/runner/plancheck/statement_type_executor.go b/backend/runner/plancheck/statement_type_executor.go
index d617b509b0..ba9d2ca0e7 100644
--- a/backend/runner/plancheck/statement_type_executor.go
+++ b/backend/runner/plancheck/statement_type_executor.go
@@ -13,7 +13,6 @@ import (
api "github.com/bytebase/bytebase/backend/legacyapi"
"github.com/bytebase/bytebase/backend/plugin/advisor"
"github.com/bytebase/bytebase/backend/plugin/parser/base"
- 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"
@@ -349,7 +348,7 @@ func (e *StatementTypeExecutor) mysqlSDLTypeCheck(ctx context.Context, newSchema
var results []*storepb.PlanCheckRunResult_Result
for _, stmt := range list {
- if mysqlparser.IsTiDBUnsupportDDLStmt(stmt.Text) {
+ if tidbparser.IsTiDBUnsupportDDLStmt(stmt.Text) {
continue
}
nodeList, _, err := tidbp.New().Parse(stmt.Text, "", "")