Skip to content

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

feat: support diff TRIGGER/PROCEDURE/FUNCTION/EVENT (#3084)

h3n4lfe288bd1893e
diff --git a/plugin/parser/differ/mysql/differ.go b/plugin/parser/differ/mysql/differ.go
index 879c4344c3..fa9491e603 100644
--- a/plugin/parser/differ/mysql/differ.go
+++ b/plugin/parser/differ/mysql/differ.go
@@ -3,7 +3,10 @@ package mysql
import (
"bytes"
+ "fmt"
+ "regexp"
"sort"
+ "strings"
"github.com/pingcap/tidb/parser"
"github.com/pingcap/tidb/parser/ast"
@@ -29,6 +32,15 @@ func init() {
differ.Register(bbparser.TiDB, &SchemaDiffer{})
}
+type objectType string
+
+const (
+ event objectType = "EVENT"
+ function objectType = "FUNCTION"
+ procedure objectType = "PROCEDURE"
+ trigger objectType = "TRIGGER"
+)
+
// SchemaDiffer it the parser for MySQL dialect.
type SchemaDiffer struct {
}
@@ -39,11 +51,34 @@ type constraintMap map[string]*ast.Constraint
// SchemaDiff returns the schema diff.
// It only supports schema information from mysqldump.
func (*SchemaDiffer) SchemaDiff(oldStmt, newStmt string) (string, error) {
- oldNodes, _, err := parser.New().Parse(oldStmt, "", "")
+ // TiDB parser doesn't support some statements like `CREATE EVENT`, so we need to extract them out and diff them based on string compare.
+ oldUnsupportStmts, oldSupportStmts, err := bbparser.ExtractTiDBUnsupportStmts(oldStmt)
+ if err != nil {
+ return "", errors.Wrapf(err, "failed to extract TiDB unsupport statements from old statements %q", oldStmt)
+ }
+ var oldUnsupportFilterStmts []string
+ for _, stmt := range oldUnsupportStmts {
+ if !bbparser.IsDelimiter(stmt) {
+ oldUnsupportFilterStmts = append(oldUnsupportFilterStmts, stmt)
+ }
+ }
+
+ newUnsupportStmts, newSupportStmts, err := bbparser.ExtractTiDBUnsupportStmts(newStmt)
+ if err != nil {
+ return "", errors.Wrapf(err, "failed to extract TiDB unsupport statements from old statements %q", oldStmt)
+ }
+ var newUnsupportFilterStmts []string
+ for _, stmt := range newUnsupportStmts {
+ if !bbparser.IsDelimiter(stmt) {
+ newUnsupportFilterStmts = append(newUnsupportFilterStmts, stmt)
+ }
+ }
+
+ oldNodes, _, err := parser.New().Parse(oldSupportStmts, "", "")
if err != nil {
return "", errors.Wrapf(err, "failed to parse old statement %q", oldStmt)
}
- newNodes, _, err := parser.New().Parse(newStmt, "", "")
+ newNodes, _, err := parser.New().Parse(newSupportStmts, "", "")
if err != nil {
return "", errors.Wrapf(err, "failed to parse new statement %q", newStmt)
}
@@ -277,6 +312,43 @@ func (*SchemaDiffer) SchemaDiff(oldStmt, newStmt string) (string, error) {
}
}
+ // We compare the CREATE TRIGGER/EVENT/FUNCTION/PROCEDURE statements based on strcmp.
+ var newNodeStmt []string
+ var inplaceDropStmt []string
+ var inplaceAddStmt []string
+ var dropStmt []string
+
+ oldUnsupportMap, err := buildUnsupportObjectMap(oldUnsupportFilterStmts)
+ if err != nil {
+ return "", err
+ }
+ newUnsupportMap, err := buildUnsupportObjectMap(newUnsupportFilterStmts)
+ if err != nil {
+ return "", err
+ }
+ for tp, objs := range newUnsupportMap {
+ for newName, newStmt := range objs {
+ if oldStmt, ok := oldUnsupportMap[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
+ inplaceDropStmt = append(inplaceDropStmt, fmt.Sprintf("DROP %s IF EXISTS `%s`;", tp, newName))
+ inplaceAddStmt = append(inplaceAddStmt, newStmt)
+ }
+ delete(oldUnsupportMap[tp], newName)
+ continue
+ }
+ newNodeStmt = append(newNodeStmt, newStmt)
+ }
+ }
+ // drop remaining TiDB unsupported objects
+ for tp, objs := range oldUnsupportMap {
+ for name := range objs {
+ dropStmt = append(dropStmt, fmt.Sprintf("DROP %s IF EXISTS `%s`;", tp, name))
+ }
+ }
+
var tempViewList []*ast.CreateViewStmt
var viewList []*ast.CreateViewStmt
for _, view := range newViewList {
@@ -320,10 +392,16 @@ func (*SchemaDiffer) SchemaDiff(oldStmt, newStmt string) (string, error) {
dropNodeList = append(dropNodeList, dropViewStmt)
}
- return deparse(newNodeList, inplaceUpdate, inplaceAddNodeList, inplaceDropNodeList, dropNodeList, viewStmts, format.DefaultRestoreFlags|format.RestoreStringWithoutCharset)
+ return deparse(newNodeList, newNodeStmt, inplaceUpdate,
+ inplaceAddNodeList, inplaceAddStmt, inplaceDropNodeList,
+ inplaceDropStmt, dropNodeList, dropStmt, viewStmts,
+ format.DefaultRestoreFlags|format.RestoreStringWithoutCharset)
}
-func deparse(newNodeList []ast.Node, inplaceUpdate []ast.Node, inplaceAdd []ast.Node, inplaceDrop []ast.Node, dropNodeList []ast.Node, viewStmts []*ast.CreateViewStmt, flag format.RestoreFlags) (string, error) {
+func deparse(newNodeList []ast.Node, newNodeStmt []string, inplaceUpdate []ast.Node,
+ inplaceAdd []ast.Node, inplaceAddStmt []string, inplaceDrop []ast.Node,
+ inplaceDropStmt []string, dropNodeList []ast.Node, dropStmt []string,
+ viewStmts []*ast.CreateViewStmt, flag format.RestoreFlags) (string, error) {
var buf bytes.Buffer
// We should following the right order to avoid break the dependency:
// Additions for new nodes.
@@ -339,6 +417,14 @@ func deparse(newNodeList []ast.Node, inplaceUpdate []ast.Node, inplaceAdd []ast.
return "", err
}
}
+ for _, stmt := range newNodeStmt {
+ if _, err := buf.Write([]byte(stmt)); err != nil {
+ return "", err
+ }
+ if _, err := buf.Write([]byte("\n")); err != nil {
+ return "", err
+ }
+ }
for _, node := range inplaceUpdate {
if err := node.Restore(format.NewRestoreCtx(flag, &buf)); err != nil {
@@ -357,6 +443,14 @@ func deparse(newNodeList []ast.Node, inplaceUpdate []ast.Node, inplaceAdd []ast.
return "", err
}
}
+ for i := len(inplaceDropStmt) - 1; i >= 0; i-- {
+ if _, err := buf.Write([]byte(inplaceDropStmt[i])); err != nil {
+ return "", err
+ }
+ if _, err := buf.Write([]byte("\n")); err != nil {
+ return "", err
+ }
+ }
for i := len(inplaceAdd) - 1; i >= 0; i-- {
if err := inplaceAdd[i].Restore(format.NewRestoreCtx(flag, &buf)); err != nil {
@@ -366,6 +460,14 @@ func deparse(newNodeList []ast.Node, inplaceUpdate []ast.Node, inplaceAdd []ast.
return "", err
}
}
+ for _, stmt := range inplaceAddStmt {
+ if _, err := buf.Write([]byte(stmt)); err != nil {
+ return "", err
+ }
+ if _, err := buf.Write([]byte("\n")); err != nil {
+ return "", err
+ }
+ }
for i := len(dropNodeList) - 1; i >= 0; i-- {
if err := dropNodeList[i].Restore(format.NewRestoreCtx(flag, &buf)); err != nil {
@@ -375,6 +477,14 @@ func deparse(newNodeList []ast.Node, inplaceUpdate []ast.Node, inplaceAdd []ast.
return "", err
}
}
+ for i := len(dropStmt) - 1; i >= 0; i-- {
+ if _, err := buf.Write([]byte(dropStmt[i])); err != nil {
+ return "", err
+ }
+ if _, err := buf.Write([]byte("\n")); err != nil {
+ return "", err
+ }
+ }
for _, node := range viewStmts {
if err := node.Restore(format.NewRestoreCtx(flag, &buf)); err != nil {
@@ -413,6 +523,23 @@ func buildViewMap(nodes []ast.StmtNode) map[string]*ast.CreateViewStmt {
return viewMap
}
+// buildUnsupportObjectMap builds map for trigger, function, procedure, event to correspond create object string statements.
+func buildUnsupportObjectMap(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 := extractUnsupportObjNameAndType(stmt)
+ if err != nil {
+ return nil, err
+ }
+ m[objType][objName] = stmt
+ }
+ return m, nil
+}
+
// getTempView returns the temporary view name and the create statement.
func getTempView(stmt *ast.CreateViewStmt) *ast.CreateViewStmt {
// We create the temp view similar to what mysqldump does.
@@ -1082,3 +1209,39 @@ func buildTableOptionMap(options []*ast.TableOption) map[ast.TableOptionType]*as
}
return m
}
+
+// extractUnsupportObjNameAndType extract the object name from the CREATE TRIGGER/EVENT/FUNCTION/PROCEDURE statement and returns the object name and type.
+func extractUnsupportObjNameAndType(stmt string) (string, objectType, error) {
+ fs := []objectType{
+ function,
+ procedure,
+ }
+ regexFmt := "(?i)^CREATE\\s+(DEFINER=`(.)+`@`(.)+`(\\s)+)?%s\\s+(?P<OBJECT_NAME>%s)(\\s)*\\("
+ namingRegex := "`[^\\\\/?%*:|\\\"`<>]+`"
+ 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 = "(?i)^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)
+}
diff --git a/plugin/parser/differ/mysql/differ_test.go b/plugin/parser/differ/mysql/differ_test.go
new file mode 100644
index 0000000000..371061c894
--- /dev/null
+++ b/plugin/parser/differ/mysql/differ_test.go
@@ -0,0 +1,80 @@
+package mysql
+
+import (
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+func TestExtractUnsupportObjNameAndType(t *testing.T) {
+ tests := []struct {
+ stmt string
+ wantTp objectType
+ wantName string
+ }{
+ {
+ stmt: "CREATE DEFINER=`root`@`%` TRIGGER `ins_sum` BEFORE INSERT ON `account` FOR EACH SET @sum=@sum + NEW.price;;",
+ wantTp: trigger,
+ wantName: "ins_sum",
+ },
+ {
+ stmt: "create trigger `ins_sum` BEFORE INSERT ON `account` FOR EACH SET @sum=@sum + NEW.price;;",
+ wantTp: trigger,
+ wantName: "ins_sum",
+ },
+ {
+ stmt: "CREATE DEFINER=`root`@`%` PROCEDURE `citycount` (IN `country` CHAR(3), OUT `cities` INT)\n" +
+ "BEGIN\n" +
+ " SELECT COUNT(*) INTO cities FROM world.city\n" +
+ "WHERE CountryCode = country;\n" +
+ "END//",
+ wantTp: procedure,
+ wantName: "citycount",
+ },
+ {
+ stmt: "create procedure `citycount` (IN `country` CHAR(3), OUT `cities` INT)\n" +
+ "BEGIN\n" +
+ " SELECT COUNT(*) INTO cities FROM world.city\n" +
+ "WHERE CountryCode = country;\n" +
+ "END//",
+ wantTp: procedure,
+ wantName: "citycount",
+ },
+ {
+ stmt: "CREATE DEFINER=`root`@`%` FUNCTION `hello` (s CHAR(20)) RETURNS CHAR(50) DETERMINISTIC\n" +
+ "RETURN CONCAT('Hello, ',s,'!');",
+ wantTp: function,
+ wantName: "hello",
+ },
+ {
+ stmt: "create function `hello` (s CHAR(20)) RETURNS CHAR(50) DETERMINISTIC\n" +
+ "RETURN CONCAT('Hello, ',s,'!');",
+ wantTp: function,
+ wantName: "hello",
+ },
+ {
+ stmt: "CREATE DEFINER=`root`@`%` EVENT `test_event_01` ON SCHEDULE AT CURRENT_TIMESTAMP \n" +
+ "DO\n" +
+ " INSERT INTO message(message, created_at)\n" +
+ " VALUES('test event', NOW());",
+ wantTp: event,
+ wantName: "test_event_01",
+ },
+ {
+ stmt: "create event `test_event_01` ON SCHEDULE AT CURRENT_TIMESTAMP \n" +
+ "DO\n" +
+ " INSERT INTO message(message, created_at)\n" +
+ " VALUES('test event', NOW());",
+ wantTp: event,
+ wantName: "test_event_01",
+ },
+ }
+
+ a := require.New(t)
+ for _, test := range tests {
+ gotName, gotTp, err := extractUnsupportObjNameAndType(test.stmt)
+ a.NoError(err)
+ a.Equal(test.wantTp, gotTp)
+ a.Equal(test.wantName, gotName)
+ }
+}
diff --git a/plugin/parser/differ/mysql/unsupport_object_test.go b/plugin/parser/differ/mysql/unsupport_object_test.go
new file mode 100644
index 0000000000..3300edb786
--- /dev/null
+++ b/plugin/parser/differ/mysql/unsupport_object_test.go
@@ -0,0 +1,136 @@
+package mysql
+
+import (
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+func TestTrigger(t *testing.T) {
+ tests := []struct {
+ old string
+ new string
+ want string
+ }{
+ {
+ 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);\n" +
+ "DROP TRIGGER IF EXISTS `ins_sum`;\n" +
+ "CREATE DEFINER=`root`@`%` TRIGGER `ins_sum` BEFORE INSERT ON account FOR EACH ROW SET @sum = sum + NEW.amount * NEW.price;\n",
+ },
+ }
+ a := require.New(t)
+ mysqlDiffer := &SchemaDiffer{}
+ for _, test := range tests {
+ out, err := mysqlDiffer.SchemaDiff(test.old, test.new)
+ a.NoError(err)
+ a.Equalf(test.want, out, "old: %s\nnew: %s\n", test.old, test.new)
+ }
+}
+
+func TestFunction(t *testing.T) {
+ tests := []struct {
+ old string
+ new string
+ want string
+ }{
+ {
+ old: "DELIMITER ;;\n" +
+ "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" +
+ "DELIMITER ;\n",
+ new: "DELIMITER ;;\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" +
+ "DELIMITER ;\n",
+ want: "DROP FUNCTION IF EXISTS `AddOne`;\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",
+ },
+ }
+ a := require.New(t)
+ mysqlDiffer := &SchemaDiffer{}
+ for _, test := range tests {
+ out, err := mysqlDiffer.SchemaDiff(test.old, test.new)
+ a.NoError(err)
+ a.Equalf(test.want, out, "old: %s\nnew: %s\n", test.old, test.new)
+ }
+}
+
+func TestProcedure(t *testing.T) {
+ tests := []struct {
+ old string
+ new string
+ want string
+ }{
+ {
+ old: "DELIMITER ;;\n" +
+ "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" +
+ "DELIMITER ;\n",
+ new: "DELIMITER ;;\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" +
+ "DELIMITER ;\n",
+ want: "DROP PROCEDURE IF EXISTS `account_count`;\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",
+ },
+ }
+ a := require.New(t)
+ mysqlDiffer := &SchemaDiffer{}
+ for _, test := range tests {
+ out, err := mysqlDiffer.SchemaDiff(test.old, test.new)
+ a.NoError(err)
+ a.Equalf(test.want, out, "old: %s\nnew: %s\n", test.old, test.new)
+ }
+}
+
+func TestEvent(t *testing.T) {
+ tests := []struct {
+ old string
+ new string
+ want string
+ }{
+ {
+ old: "DELIMITER ;;\n" +
+ "CREATE DEFINER=`root`@`%` EVENT `e_daily` ON SCHEDULE EVERY 1 DAY STARTS '2022-10-19 10:10:42' ON COMPLETION NOT PRESERVE ENABLE COMMENT 'Saves total number of sessions then clears the table each day' DO BEGIN\n" +
+ "INSERT INTO site_activity.totals (time, total)\n" +
+ "FROM site_activity.sessions;\n" +
+ "END ;;\n" +
+ "DELIMITER ;\n",
+ new: "DELIMITER ;;\n" +
+ "CREATE DEFINER=`root`@`%` EVENT `e_daily` ON SCHEDULE EVERY 1 DAY STARTS '2022-10-19 10:10:42' ON COMPLETION NOT PRESERVE ENABLE COMMENT 'Saves total number of sessions then clears the table each day' DO BEGIN\n" +
+ "INSERT INTO site_activity.totals (time, total)\n" +
+ "FROM site_activity.sessions;\n" +
+ "DELITE FROM site_activity.sessions;\n" +
+ "END ;;\n" +
+ "DELIMITER ;\n",
+ want: "DROP EVENT IF EXISTS `e_daily`;\n" +
+ "CREATE DEFINER=`root`@`%` EVENT `e_daily` ON SCHEDULE EVERY 1 DAY STARTS '2022-10-19 10:10:42' ON COMPLETION NOT PRESERVE ENABLE COMMENT 'Saves total number of sessions then clears the table each day' DO BEGIN\n" +
+ "INSERT INTO site_activity.totals (time, total)\n" +
+ "FROM site_activity.sessions;\n" +
+ "DELITE FROM site_activity.sessions;\n" +
+ "END ;;\n",
+ },
+ }
+ a := require.New(t)
+ mysqlDiffer := &SchemaDiffer{}
+ for _, test := range tests {
+ out, err := mysqlDiffer.SchemaDiff(test.old, test.new)
+ a.NoError(err)
+ a.Equalf(test.want, out, "old: %s\nnew: %s\n", test.old, test.new)
+ }
+}
diff --git a/plugin/parser/utils.go b/plugin/parser/utils.go
index 6e3572d33f..42c7259bec 100644
--- a/plugin/parser/utils.go
+++ b/plugin/parser/utils.go
@@ -101,9 +101,7 @@ func isTiDBUnsupportStmt(stmt string) bool {
// Match DELIMITER statement
// Now, we assume that all input comes from our mysqldump, and the tokenizer can split the mysqldump DELIMITER statement
// in one singleSQL correctly, so we can handle it easily here by checking the prefix.
- delimiterRegex := `(?i)^DELIMITER\s+`
- re := regexp.MustCompile(delimiterRegex)
- return re.MatchString(stmt)
+ return IsDelimiter(stmt)
}
// isTiDBUnsupportStmt checks whether the `stmt` is unsupported DDL statement in TiDB, the following statements are unsupported:
@@ -128,3 +126,10 @@ func isTiDBUnsupportDDLStmt(stmt string) bool {
}
return false
}
+
+// IsDelimiter returns true if the statement is a delimiter statement.
+func IsDelimiter(stmt string) bool {
+ delimiterRegex := `(?i)^DELIMITER\s+`
+ re := regexp.MustCompile(delimiterRegex)
+ return re.MatchString(stmt)
+}
diff --git a/plugin/parser/utils_test.go b/plugin/parser/utils_test.go
index 4f5663928e..d46bea2233 100644
--- a/plugin/parser/utils_test.go
+++ b/plugin/parser/utils_test.go
@@ -81,7 +81,7 @@ func TestIsTiDBUnsupportStmt(t *testing.T) {
want: true,
},
{
- stmt: "CREATE DEFINER=`root`@`%` FUNCTION `hello` (s CHAR(20)) RETURNS CHAR(50) DETERMINISTIC\n" +
+ stmt: "CREATE DEFINER=`root`@`%` FUNCTION `hello`(s CHAR(20)) RETURNS CHAR(50) DETERMINISTIC\n" +
"RETURN CONCAT('Hello, ',s,'!');",
want: true,
},