Skip to content

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

chore: don't generate disable foreign key check statement if no difference between two schema (#3092)

h3n4lac4708fe9bdc
diff --git a/plugin/parser/differ/mysql/differ.go b/plugin/parser/differ/mysql/differ.go
index dfa47f0e95..940a711e23 100644
--- a/plugin/parser/differ/mysql/differ.go
+++ b/plugin/parser/differ/mysql/differ.go
@@ -41,6 +41,9 @@ const (
procedure objectType = "PROCEDURE"
trigger objectType = "TRIGGER"
)
+const (
+ disableFKCheckStmt string = "SET FOREIGN_KEY_CHECKS=0;\n"
+)
// SchemaDiffer it the parser for MySQL dialect.
type SchemaDiffer struct {
@@ -394,17 +397,19 @@ func (*SchemaDiffer) SchemaDiff(oldStmt, newStmt string) (string, error) {
}
var buf bytes.Buffer
- _, _ = buf.Write([]byte("SET FOREIGN_KEY_CHECKS=0;\n"))
-
if err := deparse(&buf, newNodeList, newNodeStmt, inplaceUpdate,
inplaceAddNodeList, inplaceAddStmt, inplaceDropNodeList,
inplaceDropStmt, dropNodeList, dropStmt, viewStmts,
format.DefaultRestoreFlags|format.RestoreStringWithoutCharset); err != nil {
return "", errors.Wrapf(err, "deparse failed")
}
- return buf.String(), nil
+ if buf.Len() > 0 {
+ return fmt.Sprintf("%s%s", disableFKCheckStmt, buf.String()), nil
+ }
+ return "", nil
}
+// deparse deparses the ast node list and stmt list to sql string and write it to the out.
func deparse(out io.Writer, newNodeList []ast.Node, newNodeStmt []string, inplaceUpdate []ast.Node,
inplaceAdd []ast.Node, inplaceAddStmt []string, inplaceDrop []ast.Node,
inplaceDropStmt []string, dropNodeList []ast.Node, dropStmt []string,
diff --git a/plugin/parser/differ/mysql/differ_test.go b/plugin/parser/differ/mysql/differ_test.go
index e8eb640055..ea09b856cb 100644
--- a/plugin/parser/differ/mysql/differ_test.go
+++ b/plugin/parser/differ/mysql/differ_test.go
@@ -88,12 +88,13 @@ type testCase struct {
func testDiffWithoutDisableForeignKeyCheck(t *testing.T, testCases []testCase) {
a := require.New(t)
mysqlDiffer := &SchemaDiffer{}
- disableFK := "SET FOREIGN_KEY_CHECKS=0;\n"
for _, test := range testCases {
out, err := mysqlDiffer.SchemaDiff(test.old, test.new)
a.NoError(err)
- a.Equal(disableFK, out[:len(disableFK)])
- trimPrefix := out[len(disableFK):]
- a.Equalf(test.want, trimPrefix, "old: %s\nnew: %s\n", test.old, test.new)
+ if len(out) > 0 {
+ a.Equal(disableFKCheckStmt, out[:len(disableFKCheckStmt)])
+ out = out[len(disableFKCheckStmt):]
+ }
+ a.Equalf(test.want, out, "old: %s\nnew: %s\n", test.old, test.new)
}
}