Skip to content

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

feat(flashback): generate rollback SQL from binlog (#3333)

Yilong Li5b2126a9eacf
diff --git a/plugin/db/mysql/binlog_stream_parser.go b/plugin/db/mysql/binlog_stream_parser.go
index 0ec7f1315c..ac7887d009 100644
--- a/plugin/db/mysql/binlog_stream_parser.go
+++ b/plugin/db/mysql/binlog_stream_parser.go
@@ -110,6 +110,7 @@ func ParseBinlogStream(stream io.Reader) ([]BinlogTransaction, error) {
}
// FilterBinlogTransactionsByThreadID filters the binlog transaction by thread ID.
+// TODO(dragonly): refactor to streaming process.
func FilterBinlogTransactionsByThreadID(txnList []BinlogTransaction, threadID string) ([]BinlogTransaction, error) {
var ret []BinlogTransaction
for _, txn := range txnList {
diff --git a/plugin/db/mysql/rollback.go b/plugin/db/mysql/rollback.go
index ace7c79956..911937de9e 100644
--- a/plugin/db/mysql/rollback.go
+++ b/plugin/db/mysql/rollback.go
@@ -1,7 +1,10 @@
package mysql
import (
+ "bufio"
+ "context"
"fmt"
+ "os/exec"
"regexp"
"strings"
@@ -11,8 +14,11 @@ import (
"github.com/pingcap/tidb/parser"
"github.com/pingcap/tidb/parser/ast"
"github.com/pkg/errors"
+ "go.uber.org/zap"
+ "github.com/bytebase/bytebase/common/log"
bbparser "github.com/bytebase/bytebase/plugin/parser"
+ "github.com/bytebase/bytebase/resources/mysqlutil"
)
var (
@@ -42,6 +48,101 @@ func (txn BinlogTransaction) GetRollbackSQL(tables map[string][]string) (string,
return strings.Join(sqlList, "\n"), nil
}
+// GenerateRollbackSQL generates the rollback SQL statements from the binlog.
+// binlogFileNameList is a list of binlog file names, such as ["binlog.000001", "binlog.000002"].
+// binlogPosStart is the start position in the first binlog file.
+// binlogPosEnd is the end position in the last binlog file.
+// The binlog file names and positions are used to specify the binlog events range for rollback SQL generation.
+// tableCatalog is a map from table names to column names. It is used to map positional placeholders in the binlog events to the actual columns to generate valid SQL statements.
+func (driver *Driver) GenerateRollbackSQL(ctx context.Context, binlogFileNameList []string, binlogPosStart, binlogPosEnd int64, tableCatalog map[string][]string) (string, error) {
+ args := binlogFileNameList
+ args = append(args,
+ "--read-from-remote-server",
+ // Verify checksum binlog events.
+ "--verify-binlog-checksum",
+ // Tell mysqlbinlog to suppress the BINLOG statements for row events, which reduces the unneeded output.
+ "--base64-output=DECODE-ROWS",
+ // Reconstruct pseudo-SQL statements out of row events. This is where we parse the data changes.
+ "--verbose",
+ "--host", driver.connCfg.Host,
+ "--user", driver.connCfg.Username,
+ // Start decoding the binary log at the log position, this option applies to the first log file named on the command line.
+ "--start-position", fmt.Sprintf("%d", binlogPosStart),
+ // Stop decoding the binary log at the log position, this option applies to the last log file named on the command line.
+ "--stop-position", fmt.Sprintf("%d", binlogPosEnd),
+ )
+ if driver.connCfg.Port != "" {
+ args = append(args, "--port", driver.connCfg.Port)
+ }
+ cmd := exec.CommandContext(ctx, mysqlutil.GetPath(mysqlutil.MySQLBinlog, driver.resourceDir), args...)
+ log.Debug("mysqlbinlog", zap.String("command", cmd.String()))
+ if driver.connCfg.Password != "" {
+ cmd.Env = append(cmd.Env, fmt.Sprintf("MYSQL_PWD=%s", driver.connCfg.Password))
+ }
+ pr, err := cmd.StdoutPipe()
+ if err != nil {
+ return "", errors.Wrap(err, "failed to create stdout pipe")
+ }
+
+ errPipe, err := cmd.StderrPipe()
+ if err != nil {
+ return "", errors.Wrap(err, "failed to create stderr pipe")
+ }
+ defer errPipe.Close()
+ errScanner := bufio.NewScanner(errPipe)
+
+ if err := cmd.Start(); err != nil {
+ return "", errors.Wrap(err, "failed to run mysqlbinlog")
+ }
+
+ txnList, err := ParseBinlogStream(pr)
+ if err != nil {
+ return "", errors.WithMessage(err, "failed to parse binlog stream")
+ }
+
+ threadID, err := driver.GetMigrationConnID(ctx)
+ if err != nil {
+ return "", err
+ }
+ txnList, err = FilterBinlogTransactionsByThreadID(txnList, threadID)
+ if err != nil {
+ return "", errors.WithMessage(err, "failed to filter binlog transactions by thread ID")
+ }
+
+ var rollbackSQLList []string
+ for i := len(txnList) - 1; i >= 0; i-- {
+ sql, err := txnList[i].GetRollbackSQL(tableCatalog)
+ if err != nil {
+ return "", errors.WithMessage(err, "failed to generate rollback SQL statement for transaction")
+ }
+ rollbackSQLList = append(rollbackSQLList, sql)
+ }
+
+ var errBuilder strings.Builder
+ for errScanner.Scan() {
+ line := errScanner.Text()
+ // Log the error, but return the first 1024 characters in the error to users.
+ log.Warn(line)
+ if errBuilder.Len() < 1024 {
+ if _, err := errBuilder.WriteString(line); err != nil {
+ return "", errors.Wrap(err, "failed to write mysqlbinlog error string")
+ }
+ if _, err := errBuilder.WriteString("\n"); err != nil {
+ return "", errors.Wrap(err, "failed to write mysqlbinlog error string")
+ }
+ }
+ }
+ if errScanner.Err() != nil {
+ return "", errors.Wrap(errScanner.Err(), "error scanner failed")
+ }
+
+ if err = cmd.Wait(); err != nil {
+ return "", errors.Wrapf(err, "mysqlbinlog error: %s", errBuilder.String())
+ }
+
+ return strings.Join(rollbackSQLList, "\n\n"), nil
+}
+
// GetTableColumns parses the schema to get the table columns map.
// This is used to generate rollback SQL from the binlog events.
func GetTableColumns(schema string) (map[string][]string, error) {
diff --git a/plugin/db/mysql/rollback_test.go b/plugin/db/mysql/rollback_test.go
index 180e4195a6..123dd5e65e 100644
--- a/plugin/db/mysql/rollback_test.go
+++ b/plugin/db/mysql/rollback_test.go
@@ -8,18 +8,18 @@ import (
func TestGetRollbackSQL(t *testing.T) {
tests := []struct {
- name string
- txn BinlogTransaction
- tableMap map[string][]string
- rollbackSQL string
- err bool
+ name string
+ txn BinlogTransaction
+ tableCatalog map[string][]string
+ rollbackSQL string
+ err bool
}{
{
- name: "empty",
- txn: BinlogTransaction{},
- tableMap: map[string][]string{},
- rollbackSQL: "",
- err: false,
+ name: "empty",
+ txn: BinlogTransaction{},
+ tableCatalog: map[string][]string{},
+ rollbackSQL: "",
+ err: false,
},
{
name: "INSERT",
@@ -58,7 +58,7 @@ BEGIN
`,
},
},
- tableMap: map[string][]string{
+ tableCatalog: map[string][]string{
"user": {"id", "name", "balance"},
},
rollbackSQL: `DELETE FROM ` + "`binlog_test`.`user`" + `
@@ -122,7 +122,7 @@ BEGIN
`,
},
},
- tableMap: map[string][]string{
+ tableCatalog: map[string][]string{
"user": {"id", "name", "balance"},
},
rollbackSQL: `UPDATE ` + "`binlog_test`.`user`" + `
@@ -181,7 +181,7 @@ DELIMITER ;
/*!50530 SET @@SESSION.PSEUDO_SLAVE_MODE=0*/;`,
},
},
- tableMap: map[string][]string{
+ tableCatalog: map[string][]string{
"user": {"id", "name", "balance"},
},
rollbackSQL: `INSERT INTO ` + "`binlog_test`.`user`" + `
@@ -209,7 +209,7 @@ SET
### @3=0`,
},
},
- tableMap: map[string][]string{
+ tableCatalog: map[string][]string{
"user": {"id", "name", "balance", "new_column"},
},
rollbackSQL: "",
@@ -220,7 +220,7 @@ SET
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
a := require.New(t)
- sql, err := test.txn.GetRollbackSQL(test.tableMap)
+ sql, err := test.txn.GetRollbackSQL(test.tableCatalog)
if test.err {
a.Error(err)
} else {
diff --git a/tests/rollback_test.go b/tests/rollback_test.go
index c85432acf1..4dead517cf 100644
--- a/tests/rollback_test.go
+++ b/tests/rollback_test.go
@@ -3,9 +3,8 @@ package tests
import (
"context"
"fmt"
- "os"
- "os/exec"
- "path"
+ "math"
+ "strconv"
"testing"
"github.com/stretchr/testify/require"
@@ -20,85 +19,47 @@ func TestRollback(t *testing.T) {
a := require.New(t)
ctx := context.Background()
port := getTestPort(t.Name())
+ database := "funny\ndatabase"
- instance, stopFn := resourcemysql.SetupTestInstance(t, port)
- binlogDir := instance.DataDir()
+ _, stopFn := resourcemysql.SetupTestInstance(t, port)
defer stopFn()
- resourceDir := t.TempDir()
- err := mysqlutil.Install(resourceDir)
- a.NoError(err)
-
- database := "funny\ndatabase"
db, err := connectTestMySQL(port, "")
a.NoError(err)
defer db.Close()
- _, err = db.ExecContext(ctx, fmt.Sprintf("CREATE DATABASE `%s`; USE `%s`;", database, database))
- a.NoError(err)
- _, err = db.ExecContext(ctx, "CREATE TABLE user (id INT PRIMARY KEY, name VARCHAR(64), balance INT);")
+ _, err = db.ExecContext(ctx, fmt.Sprintf("CREATE DATABASE `%s`; USE `%s`; CREATE TABLE user (id INT PRIMARY KEY, name VARCHAR(64), balance INT);", database, database))
a.NoError(err)
_, err = db.ExecContext(ctx, "INSERT INTO user VALUES (1, 'alice\nalice', 100), (2, 'bob', 100), (3, 'cindy', 100);")
a.NoError(err)
-
- txn, err := db.BeginTx(ctx, nil)
- a.NoError(err)
- _, err = txn.ExecContext(ctx, "UPDATE user SET balance=90 WHERE id=1;")
- a.NoError(err)
- _, err = txn.ExecContext(ctx, "UPDATE user SET balance=110 WHERE id=2;")
+ _, err = db.ExecContext(ctx, "UPDATE user SET balance=90 WHERE id=1; UPDATE user SET balance=110 WHERE id=2; DELETE FROM user WHERE id=3;")
a.NoError(err)
- _, err = txn.ExecContext(ctx, "DELETE FROM user WHERE id=3;")
+
+ resourceDir := t.TempDir()
+ err = mysqlutil.Install(resourceDir)
a.NoError(err)
- err = txn.Commit()
+ driver, err := getTestMySQLDriver(ctx, t, strconv.Itoa(port), database, resourceDir)
a.NoError(err)
+ defer driver.Close(ctx)
// Rotate to binlog.000002 so that it's easy to rollback the following transactions and check that the state is the same as now.
_, err = db.ExecContext(ctx, "FLUSH BINARY LOGS;")
a.NoError(err)
- _, err = db.ExecContext(ctx, "UPDATE user SET balance=0;")
+ err = driver.Execute(ctx, "UPDATE user SET balance=0;", false)
a.NoError(err)
- _, err = db.ExecContext(ctx, "DELETE FROM user;")
+ err = driver.Execute(ctx, "DELETE FROM user;", false)
a.NoError(err)
- t.Log("Set up mysqlbinlog")
- args := []string{
- path.Join(binlogDir, "binlog.000002"),
- "--verify-binlog-checksum",
- "-v",
- "--base64-output=DECODE-ROWS",
+ // Restore data using generated rollback SQL.
+ mysqlDriver, ok := driver.(*mysql.Driver)
+ a.Equal(true, ok)
+ binlogFileList := []string{"binlog.000002"}
+ tableCatalog := map[string][]string{
+ "user": {"id", "name", "balance"},
}
- cmd := exec.CommandContext(ctx, mysqlutil.GetPath(mysqlutil.MySQLBinlog, resourceDir), args...)
- cmd.Stderr = os.Stderr
- pr, err := cmd.StdoutPipe()
+ rollbackSQL, err := mysqlDriver.GenerateRollbackSQL(ctx, binlogFileList, 0, math.MaxInt64, tableCatalog)
a.NoError(err)
- err = cmd.Start()
+ _, err = db.ExecContext(ctx, rollbackSQL)
a.NoError(err)
- defer func() {
- err = pr.Close()
- a.NoError(err)
- err = cmd.Process.Kill()
- a.NoError(err)
- }()
-
- txList, err := mysql.ParseBinlogStream(pr)
- a.NoError(err)
- a.Equal(2, len(txList))
- var rollbackSQLList []string
- tableMap := map[string][]string{
- "user": {"id", "name", "balance"},
- }
- for _, tx := range txList {
- sql, err := tx.GetRollbackSQL(tableMap)
- a.NoError(err)
- rollbackSQLList = append(rollbackSQLList, sql)
- }
-
- // Execute the rollback SQL in reversed order.
- for i := len(rollbackSQLList) - 1; i >= 0; i-- {
- sql := rollbackSQLList[i]
- t.Log(sql)
- _, err = db.ExecContext(ctx, sql)
- a.NoError(err)
- }
// Check for rollback state.
rows, err := db.QueryContext(ctx, "SELECT * FROM user;")