Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat(PITR): find the backup and binlog info for the given PITR time. (#1343)
Yilong Lib99d3fe4eaa1
diff --git a/api/backup.go b/api/backup.goindex ecc3f068fc..065cc894e0 100644--- a/api/backup.go+++ b/api/backup.go@@ -76,6 +76,22 @@ func (e BackupStorageBackend) String() string {return "UNKNOWN"}+// BinlogInfo is the binlog coordination for MySQL.+type BinlogInfo struct {+ FileName string `json:"fileName"`+ Position int64 `json:"position"`+}++// BackupPayload contains backup related database specific info, it differs for different database types.+// It is encoded in JSON and stored in the backup table.+type BackupPayload struct {+ // MySQL related fields+ // BinlogInfo is recorded when taking the backup.+ // It is recorded within the same transaction as the dump so that the binlog position is consistent with the dump.+ // Please refer to https://github.com/bytebase/bytebase/blob/main/docs/design/pitr-mysql.md#full-backup for details.+ BinlogInfo BinlogInfo `json:"binlogInfo"`+}+// Backup is the API message for a backup.type Backup struct {ID int `jsonapi:"primary,backup"`@@ -101,6 +117,9 @@ type Backup struct {MigrationHistoryVersion string `jsonapi:"attr,migrationHistoryVersion"`Path string `jsonapi:"attr,path"`Comment string `jsonapi:"attr,comment"`+ // Payload contains data such as binlog position info which will not be created at first.+ // It is filled when the backup task executor takes database backups.+ Payload BackupPayload `jsonapi:"attr,payload"`}// BackupCreate is the API message for creating a backup.diff --git a/docs/design/pitr-mysql.md b/docs/design/pitr-mysql.mdindex 42587f4f7c..bf0c2dce3b 100644--- a/docs/design/pitr-mysql.md+++ b/docs/design/pitr-mysql.md@@ -90,6 +90,21 @@ The partial backup dump should be discarded if Bytebase encounters an unrecoveraTo check the integrity of the logical dump, Bytebase will save file size in the backup metadata. When using a logical backup to recover, we should first validate the file size of the dump file and the metadata matches.+#### Why bother?++The full backup process seems very sophisticated. Why don't we just dump the logical backup and use `SHOW MASTER STATUS` to get the binlog coordinates? Well, let's look at an example.++If we start to dump a logical backup called bk at time t, and the backup SQL runs for 10s and finishes at t+10. Then we get the binlog coordinates at t+10 and save it together with the backup metadata. When we want to do a PITR to the database state at t+20, we would restore the logical backup bk and replay the binlog from t+10 to t+20.++Here is the problem: the logical backup is a [consistent read](https://dev.mysql.com/doc/refman/8.0/en/innodb-consistent-read.html) of the database, which means that no matter how long it takes to run the SQL, **the backup content is just like reading a snapshot of the database at time t**.++Now let's reconsider the binlog replay. After the logical backup bk is restored, the database is at the state of t. If we want to incrementally restore to t+20, we should replay the binlog from **t to t+20** instead of t+10 to t+20 as is described above. In short, this "simpler implementation" is actually buggy.++The current design of full backup process in [this section](#full-backup) ensures that:++1. No data is inserted between we dump a logical backup with the consistent read semantic and get the binlog coordinates.+2. The locking time is minimal so that the backup process has the minimal impact on other workloads in the same database.+## Incremental BackupOnce the backup is enabled for a database, Bytebase will periodically download binlog from the MySQL server via `mysqlbinlog` with parameter [`--read-from-remote-server`](https://dev.mysql.com/doc/refman/8.0/en/mysqlbinlog.html#option_mysqlbinlog_read-from-remote-server), which reads data via the [binlog network stream](https://dev.mysql.com/doc/internals/en/binlog-network-stream.html). The binlog downloading process is described below.diff --git a/plugin/db/mysql/mysql.go b/plugin/db/mysql/mysql.goindex 55c30da560..184877e930 100644--- a/plugin/db/mysql/mysql.go+++ b/plugin/db/mysql/mysql.go@@ -14,6 +14,7 @@ import (// embed will embeds the migration schema._ "embed"+ "github.com/bytebase/bytebase/api""github.com/bytebase/bytebase/common""github.com/bytebase/bytebase/plugin/db""github.com/bytebase/bytebase/plugin/db/util"@@ -46,26 +47,12 @@ func init() {db.Register(db.TiDB, newDriver)}-// BinlogInfo is the binlog coordination for MySQL.-type BinlogInfo struct {- FileName string `json:"fileName"`- Position int64 `json:"position"`-}-// BinlogFile is the metadata of the MySQL binlog filetype BinlogFile struct {Name stringSize int64}-// This is encoded in JSON and stored in the backup table, representing PITR related info.-type backupPayload struct {- BinlogInfo BinlogInfo `json:"binlogInfo"`- // Imprecise UNIX timestamp to the second which is the rough time when this backup is taken.- // Mainly for UI purpose.- Ts int64 `json:"ts"`-}-// Driver is the MySQL driver.type Driver struct {l *zap.Logger@@ -940,15 +927,11 @@ func (driver *Driver) Dump(ctx context.Context, database string, out io.Writer,zap.String("filename", binlog.FileName),zap.Int64("position", binlog.Position))- ts, err := getServerTime(ctx, driver.db)if err != nil {return "", err}- payload := backupPayload{- BinlogInfo: binlog,- Ts: ts,- }+ payload := api.BackupPayload{BinlogInfo: binlog}payloadBytes, err = json.Marshal(payload)if err != nil {return "", err@@ -969,7 +952,7 @@ func (driver *Driver) Dump(ctx context.Context, database string, out io.Writer,}defer txn.Rollback()- driver.l.Debug("begin to dump database")+ driver.l.Debug("begin to dump database", zap.String("database", database))if err := dumpTxn(ctx, txn, database, out, schemaOnly); err != nil {return "", err}@@ -1007,19 +990,6 @@ func (driver *Driver) Restore(ctx context.Context, sc *bufio.Scanner) (err errorreturn nil}-func getServerTime(ctx context.Context, db *sql.DB) (int64, error) {- var timestamp int64- rows, err := db.QueryContext(ctx, "SELECT UNIX_TIMESTAMP(CURRENT_TIMESTAMP());")- if err != nil {- return 0, err- }- rows.Next()- if err := rows.Scan(×tamp); err != nil {- return 0, err- }- return timestamp, nil-}-func flushTablesWithReadLock(ctx context.Context, conn *sql.Conn, database string) error {// The lock acquiring could take a long time if there are concurrent exclusive locks on the tables.// We ensures that the execution is canceled after 30 seconds, otherwise we may get dead lock and stuck forever.@@ -1188,18 +1158,18 @@ func getDatabases(ctx context.Context, txn *sql.Tx) ([]string, error) {return dbNames, nil}-func getBinlogInfo(ctx context.Context, conn *sql.Conn) (BinlogInfo, error) {+func getBinlogInfo(ctx context.Context, conn *sql.Conn) (api.BinlogInfo, error) {rows, err := conn.QueryContext(ctx, "SHOW MASTER STATUS;")if err != nil {- return BinlogInfo{}, err+ return api.BinlogInfo{}, err}defer rows.Close()rows.Next()- binlogInfo := BinlogInfo{}+ binlogInfo := api.BinlogInfo{}var unused interface{}if err := rows.Scan(&binlogInfo.FileName, &binlogInfo.Position, &unused, &unused, &unused); err != nil {- return BinlogInfo{}, err+ return api.BinlogInfo{}, err}return binlogInfo, nildiff --git a/plugin/restore/mysql/mysql.go b/plugin/restore/mysql/mysql.goindex 4b5025e06d..b0ad9a97bc 100644--- a/plugin/restore/mysql/mysql.go+++ b/plugin/restore/mysql/mysql.go@@ -2,18 +2,23 @@ package mysqlimport ("bufio"+ "bytes""context""fmt""io/ioutil"+ "math""os""os/exec"+ "path""path/filepath""strings"+ "time"- "github.com/blang/semver/v4""github.com/bytebase/bytebase/api"- mysql "github.com/bytebase/bytebase/plugin/db/mysql"+ "github.com/bytebase/bytebase/plugin/db/mysql""github.com/bytebase/bytebase/resources/mysqlutil"++ "github.com/blang/semver/v4")const (@@ -40,14 +45,15 @@ func New(driver *mysql.Driver, instance *mysqlutil.Instance) *Restore {}}-// RestoreBinlog restores the database using incremental backup in time range of [config.Start, config.End).-func (r *Restore) RestoreBinlog(ctx context.Context, config mysql.BinlogInfo) error {+// replayBinlog restores the database using incremental backup in time range of [config.Start, config.End).+func replayBinlog(ctx context.Context, config api.BinlogInfo) error {return fmt.Errorf("Unimplemented")}-// RestorePITR is a wrapper for restore a full backup and a range of incremental backup.+// RestorePITR is a wrapper to perform PITR. It restores a full backup followed by replaying the binlog.// It performs the step 1 of the restore process.-func (r *Restore) RestorePITR(ctx context.Context, fullBackup *bufio.Scanner, binlog mysql.BinlogInfo, database string, suffixTs int64) error {+// TODO(dragonly): Refactor so that the first part is in driver.Restore, and remove this wrapper.+func (r *Restore) RestorePITR(ctx context.Context, fullBackup *bufio.Scanner, binlog api.BinlogInfo, database string, suffixTs int64) error {pitrDatabaseName := getPITRDatabaseName(database, suffixTs)query := fmt.Sprintf(""+// Create the pitr database.@@ -77,12 +83,120 @@ func (r *Restore) RestorePITR(ctx context.Context, fullBackup *bufio.Scanner, bireturn err}- // TODO(dragonly): implement RestoreBinlog in mysql driver- _ = r.RestoreBinlog(ctx, binlog)+ if err := replayBinlog(ctx, binlog); err != nil {+ // TODO(dragonly)/TODO(zp): Handle the error when implement replayBinlog.+ return nil+ }return nil}+// Locate the binlog event at (filename, position), parse the event and return its timestamp.+// The current mechanism is by invoking mysqlbinlog and parse the output string.+// Maybe we should parse the raw binlog header to get better documented structure?+// nolint+func (r *Restore) parseBinlogEventTimestamp(ctx context.Context, binlogInfo api.BinlogInfo, binlogDir string) (int64, error) {+ args := []string{+ path.Join(binlogDir, binlogInfo.FileName),+ fmt.Sprintf("--start-position %d", binlogInfo.Position),+ // This will trick mysqlbinlog to output the binlog event header followed by a warning message telling that+ // the --stop-position is in the middle of the binlog event.+ // It's OK, since we are only parsing for the timestamp in the binlog event header.+ fmt.Sprintf("--stop-position %d", binlogInfo.Position+1),+ }+ var buf bytes.Buffer+ cmd := exec.CommandContext(ctx, r.mysqlutil.GetPath(mysqlutil.MySQLBinlog), args...)+ cmd.Stderr = os.Stderr+ cmd.Stdout = &buf++ if err := cmd.Run(); err != nil {+ return 0, err+ }++ timestamp, err := parseBinlogEventTimestampImpl(buf.String())+ if err != nil {+ return timestamp, fmt.Errorf("failed to parse binlog event timestamp, filename[%s], position[%d], error[%w]", binlogInfo.FileName, binlogInfo.Position, err)+ }++ return timestamp, nil+}++func parseBinlogEventTimestampImpl(output string) (int64, error) {+ lines := strings.Split(output, "\n")+ // The mysqlbinlog output will contains a line starting with "#220421 14:49:26 server id 1",+ // which has the timestamp we are looking for.+ // The first occurrence is the target.+ for _, line := range lines {+ if strings.Contains(line, "server id") {+ fields := strings.Fields(line)+ // fields should starts with ["#220421", "14:49:26", "server", "id"]+ if len(fields) < 4 ||+ (len(fields[0]) != 7 && len(fields[1]) != 8 && fields[2] != "server" && fields[3] != "id") {+ return 0, fmt.Errorf("invalid mysqlbinlog output line: %q", line)+ }+ date, err := time.ParseInLocation("060102 15:04:05", fmt.Sprintf("%s %s", fields[0][1:], fields[1]), time.Local)+ if err != nil {+ return 0, err+ }+ return date.Unix(), nil+ }+ }+ return 0, fmt.Errorf("no timestamp found in mysqlbinlog output")+}++// Find the latest logical backup and corresponding binlog info whose time is before or equal to `targetTs`.+// The backupList should only contain DONE backups.+// TODO(dragonly)/TODO(zp): Use this when the apply binlog PR is ready, and remove the nolint comments.+// nolint+func (r *Restore) getLatestBackupBeforeOrEqualTs(ctx context.Context, backupList []*api.Backup, targetTs int64, binlogDir string) (*api.Backup, error) {+ if len(backupList) == 0 {+ return nil, fmt.Errorf("no valid backup")+ }++ var eventTsList []int64+ for _, b := range backupList {+ eventTs, err := r.parseBinlogEventTimestamp(ctx, b.Payload.BinlogInfo, binlogDir)+ if err != nil {+ return nil, fmt.Errorf("failed to parse binlog event timestamp, error[%w]", err)+ }+ eventTsList = append(eventTsList, eventTs)+ }++ backup, err := getLatestBackupBeforeOrEqualTsImpl(backupList, eventTsList, targetTs)+ if err != nil {+ return nil, err+ }+ return backup, nil++}++// The backupList must 1 to 1 maps to the eventTsList, and the sorting order is not required.+func getLatestBackupBeforeOrEqualTsImpl(backupList []*api.Backup, eventTsList []int64, targetTs int64) (*api.Backup, error) {+ var maxEventTsLETargetTs int64+ var minEventTs int64 = math.MaxInt64+ var backup *api.Backup+ emptyBinlogInfo := api.BinlogInfo{}+ for i, b := range backupList {+ // Parse the binlog files and convert binlog positions into MySQL server timestamps.+ if b.Payload.BinlogInfo == emptyBinlogInfo {+ continue+ }+ eventTs := eventTsList[i]+ if eventTs <= targetTs && eventTs > maxEventTsLETargetTs {+ maxEventTsLETargetTs = eventTs+ backup = b+ }+ // This is only for composing the error message when no valid backup found.+ if eventTs < minEventTs {+ minEventTs = eventTs+ }+ }+ if maxEventTsLETargetTs == 0 {+ return nil, fmt.Errorf("the target restore timestamp[%d] is earlier than the oldest backup time[%d]", targetTs, minEventTs)+ }+ return backup, nil+}+// SwapPITRDatabase renames the pitr database to the target, and the original to the old database// It returns the pitr and old database names after swap.// It performs the step 2 of the restore process.@@ -176,7 +290,7 @@ func getPITROldDatabaseName(database string, suffixTs int64) string {return getSafeName(database, suffix)}-// SyncArchivedBinlogFiles syncs the binlogs between the instance and `saveDir`,+// SyncArchivedBinlogFiles syncs the binlog files between the instance and `saveDir`,// but exclude latest binlog. We will download the latest binlog only when doing PITR.func (r *Restore) SyncArchivedBinlogFiles(ctx context.Context, instance *api.Instance, saveDir string) error {binlogFilesLocal, err := ioutil.ReadDir(saveDir)@@ -279,7 +393,7 @@ func (r *Restore) downloadBinlogFile(ctx context.Context, instance *api.Instancereturn nil}-// getBinlogFilesMetaOnServer returns the metadata of binlogs+// getBinlogFilesMetaOnServer returns the metadata of binlog files.func (r *Restore) getBinlogFilesMetaOnServer(ctx context.Context) ([]mysql.BinlogFile, error) {db, err := r.driver.GetDbConnection(ctx, "")if err != nil {diff --git a/plugin/restore/mysql/mysql_test.go b/plugin/restore/mysql/mysql_test.goindex ff26713d85..bb5b5f08a4 100644--- a/plugin/restore/mysql/mysql_test.go+++ b/plugin/restore/mysql/mysql_test.go@@ -2,7 +2,9 @@ package mysqlimport ("testing"+ "time"+ "github.com/bytebase/bytebase/api""github.com/stretchr/testify/require")@@ -123,3 +125,130 @@ func TestCheckVersionForPITR(t *testing.T) {}}}++func TestParseBinlogEventTimestampImpl(t *testing.T) {+ a := require.New(t)+ tests := []struct {+ binlogText string+ timestamp int64+ err bool+ }{+ // This is a real one from mysqlbinlog output.+ {+ binlogText: `# The proper term is pseudo_replica_mode, but we use this compatibility alias+# to make the statement usable on server versions 8.0.24 and older.+/*!50530 SET @@SESSION.PSEUDO_SLAVE_MODE=1*/;+/*!50003 SET @OLD_COMPLETION_TYPE=@@COMPLETION_TYPE,COMPLETION_TYPE=0*/;+DELIMITER /*!*/;+# at 24500+#220421 14:49:26 server id 1 end_log_pos 0 CRC32 0xbb5866d6 Start: binlog v 4, server v 8.0.28 created 220421 14:49:26+BINLOG '+dv5gYg8BAAAAegAAAAAAAAAAAAQAOC4wLjI4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA+AAAAAAAAAAAAAAAAAAAAAAAAEwANAAgAAAAABAAEAAAAYgAEGggAAAAICAgCAAAACgoKKioAEjQA+CigAAdZmWLs=+'/*!*/;+# at 24500+#220425 17:32:13 server id 1 end_log_pos 24604 CRC32 0x6a465388 Table_map: ` + "`bytebase`.`migration_history`" + ` mapped to number 172+WARNING: The range of printed events ends with a row event or a table map event that does not have the STMT_END_F flag set. This might be because the last statement was not fully written to the log, or because you are using a --stop-position or --stop-datetime that refers to an event in the middle of a statement. The event(s) from the partial statement have not been written to output.+SET @@SESSION.GTID_NEXT= 'AUTOMATIC' /* added by mysqlbinlog */ /*!*/;+DELIMITER ;+# End of log file+/*!50003 SET COMPLETION_TYPE=@OLD_COMPLETION_TYPE*/;+/*!50530 SET @@SESSION.PSEUDO_SLAVE_MODE=0*/;`,+ timestamp: time.Date(2022, 4, 21, 14, 49, 26, 0, time.UTC).Unix(),+ err: false,+ },+ // Edge case: invalid mysqlbinlog option+ {+ binlogText: "mysqlbinlog: [ERROR] mysqlbinlog: unknown option '-n'.",+ timestamp: 0,+ err: true,+ },+ }++ for _, test := range tests {+ timestamp, err := parseBinlogEventTimestampImpl(test.binlogText)+ a.Equal(test.timestamp, timestamp)+ if test.err {+ a.Error(err)+ } else {+ a.NoError(err)+ }+ }+}++func TestGetLatestBackupBeforeOrEqualTsImpl(t *testing.T) {+ a := require.New(t)+ tests := []struct {+ backupList []*api.Backup+ eventTsList []int64+ targetTs int64+ targetBackup *api.Backup+ err bool+ }{+ // normal case+ {+ backupList: []*api.Backup{+ {Payload: api.BackupPayload{BinlogInfo: api.BinlogInfo{FileName: "binlog.000001", Position: 10}}},+ {Payload: api.BackupPayload{BinlogInfo: api.BinlogInfo{FileName: "binlog.000001", Position: 20}}},+ {Payload: api.BackupPayload{BinlogInfo: api.BinlogInfo{FileName: "binlog.000002", Position: 10}}},+ },+ eventTsList: []int64{1, 2, 3},+ targetTs: 2,+ targetBackup: &api.Backup{+ Payload: api.BackupPayload{BinlogInfo: api.BinlogInfo{FileName: "binlog.000001", Position: 20}},+ },+ err: false,+ },+ // backup list not in sorted order+ {+ backupList: []*api.Backup{+ {Payload: api.BackupPayload{BinlogInfo: api.BinlogInfo{FileName: "binlog.000001", Position: 20}}},+ {Payload: api.BackupPayload{BinlogInfo: api.BinlogInfo{FileName: "binlog.000001", Position: 10}}},+ {Payload: api.BackupPayload{BinlogInfo: api.BinlogInfo{FileName: "binlog.000002", Position: 10}}},+ },+ eventTsList: []int64{2, 1, 3},+ targetTs: 2,+ targetBackup: &api.Backup{+ Payload: api.BackupPayload{BinlogInfo: api.BinlogInfo{FileName: "binlog.000001", Position: 20}},+ },+ err: false,+ },+ // backup with empty binlog info does not count+ {+ backupList: []*api.Backup{+ {Payload: api.BackupPayload{BinlogInfo: api.BinlogInfo{FileName: "binlog.000001", Position: 10}}},+ {Payload: api.BackupPayload{BinlogInfo: api.BinlogInfo{}}},+ {Payload: api.BackupPayload{BinlogInfo: api.BinlogInfo{FileName: "binlog.000002", Position: 10}}},+ },+ eventTsList: []int64{1, 2, 3},+ targetTs: 2,+ targetBackup: &api.Backup{+ Payload: api.BackupPayload{BinlogInfo: api.BinlogInfo{FileName: "binlog.000001", Position: 10}},+ },+ err: false,+ },+ // no valid backup found+ {+ backupList: []*api.Backup{+ {Payload: api.BackupPayload{BinlogInfo: api.BinlogInfo{FileName: "binlog.000001", Position: 10}}},+ {Payload: api.BackupPayload{BinlogInfo: api.BinlogInfo{FileName: "binlog.000001", Position: 20}}},+ {Payload: api.BackupPayload{BinlogInfo: api.BinlogInfo{FileName: "binlog.000002", Position: 10}}},+ },+ eventTsList: []int64{1, 2, 3},+ targetTs: 0,+ targetBackup: nil,+ err: true,+ },+ }++ for _, test := range tests {+ backup, err := getLatestBackupBeforeOrEqualTsImpl(test.backupList, test.eventTsList, test.targetTs)+ a.Equal(test.targetBackup, backup)+ if test.err {+ a.Error(err)+ } else {+ a.NoError(err)+ }+ }+}diff --git a/server/cache.go b/server/cache.goindex 07fbaf057d..ac2d1b585f 100644--- a/server/cache.go+++ b/server/cache.go@@ -8,7 +8,6 @@ import ("github.com/VictoriaMetrics/fastcache""github.com/bytebase/bytebase/api"- "go.uber.org/zap")var (@@ -20,15 +19,12 @@ var (// CacheService implements a cache.type CacheService struct {cache *fastcache.Cache-- l *zap.Logger}// NewCacheService creates a cache service.-func NewCacheService(logger *zap.Logger) *CacheService {+func NewCacheService() *CacheService {return &CacheService{cache: fastcache.New(cacheSize),- l: logger,}}diff --git a/server/server.go b/server/server.goindex 06229ba3f4..7d25d94fc0 100644--- a/server/server.go+++ b/server/server.go@@ -135,7 +135,7 @@ func NewServer(ctx context.Context, prof Profile, logger *zap.Logger, loggerLevereturn nil, fmt.Errorf("cannot open db: %w", err)}- cacheService := NewCacheService(logger)+ cacheService := NewCacheService()storeInstance := store.New(logger, storeDB, cacheService)s.store = storeInstancediff --git a/server/task_executor_pitr_restore.go b/server/task_executor_pitr_restore.goindex b494bf4d5a..21b9998d1b 100644--- a/server/task_executor_pitr_restore.go+++ b/server/task_executor_pitr_restore.go@@ -78,7 +78,8 @@ func (exec *PITRRestoreTaskExecutor) doPITRRestore(ctx context.Context, task *ap}mysqlRestore := restoremysql.New(mysqlDriver, exec.mysqlutil)- config := pluginmysql.BinlogInfo{}++ binlogInfo := api.BinlogInfo{}// TODO(dragonly): Search and put the file io of the logical backup file here.// Currently, let's just use the empty backup dump as a placeholder.var buf bytes.Buffer@@ -92,7 +93,7 @@ func (exec *PITRRestoreTaskExecutor) doPITRRestore(ctx context.Context, task *ap// RestorePITR will create the pitr database.// Since it's ephemeral and will be renamed to the original database soon, we will reuse the original// database's migration history, and append a new BASELINE migration.- if err := mysqlRestore.RestorePITR(ctx, bufio.NewScanner(&buf), config, database.Name, issue.CreatedTs); err != nil {+ if err := mysqlRestore.RestorePITR(ctx, bufio.NewScanner(&buf), binlogInfo, database.Name, issue.CreatedTs); err != nil {exec.l.Error("failed to perform a PITR restore in the PITR database",zap.Int("issueID", issue.ID),zap.String("database", database.Name),diff --git a/store/backup.go b/store/backup.goindex 4a331ca27f..7217cf7402 100644--- a/store/backup.go+++ b/store/backup.go@@ -3,6 +3,7 @@ package storeimport ("context""database/sql"+ "encoding/json""fmt""strings"@@ -32,7 +33,9 @@ type backupRaw struct {MigrationHistoryVersion stringPath stringComment string- Payload string+ // Payload contains data like PITR info, which will not be created at first.+ // When backup runner executes the real backup job, it will fill this field.+ Payload api.BackupPayload}// toBackup creates an instance of Backup based on the backupRaw.@@ -58,6 +61,7 @@ func (raw *backupRaw) toBackup() *api.Backup {MigrationHistoryVersion: raw.MigrationHistoryVersion,Path: raw.Path,Comment: raw.Comment,+ Payload: raw.Payload,}}@@ -453,7 +457,67 @@ func (s *Store) findBackupImpl(ctx context.Context, tx *sql.Tx, find *api.Backupwhere, args = append(where, fmt.Sprintf("status = $%d", len(args)+1)), append(args, *v)}- rows, err := tx.QueryContext(ctx, `+ if s.db.mode == common.ReleaseModeDev {+ rows, err := tx.QueryContext(ctx, `+ SELECT+ id,+ creator_id,+ created_ts,+ updater_id,+ updated_ts,+ database_id,+ name,+ status,+ type,+ storage_backend,+ migration_history_version,+ path,+ comment,+ payload+ FROM backup+ WHERE `+strings.Join(where, " AND ")+` ORDER BY updated_ts DESC`,+ args...,+ )+ if err != nil {+ return nil, FormatError(err)+ }+ defer rows.Close()++ // Iterate over result set and deserialize rows into backupRawList.+ var backupRawList []*backupRaw+ for rows.Next() {+ var backupRaw backupRaw+ var payload []byte+ if err := rows.Scan(+ &backupRaw.ID,+ &backupRaw.CreatorID,+ &backupRaw.CreatedTs,+ &backupRaw.UpdaterID,+ &backupRaw.UpdatedTs,+ &backupRaw.DatabaseID,+ &backupRaw.Name,+ &backupRaw.Status,+ &backupRaw.Type,+ &backupRaw.StorageBackend,+ &backupRaw.MigrationHistoryVersion,+ &backupRaw.Path,+ &backupRaw.Comment,+ &payload,+ ); err != nil {+ return nil, FormatError(err)+ }+ if err := json.Unmarshal(payload, &backupRaw.Payload); err != nil {+ return nil, err+ }+ backupRawList = append(backupRawList, &backupRaw)+ }+ if err := rows.Err(); err != nil {+ return nil, FormatError(err)+ }++ return backupRawList, nil+ } else {+ rows, err := tx.QueryContext(ctx, `SELECTid,creator_id,@@ -470,42 +534,42 @@ func (s *Store) findBackupImpl(ctx context.Context, tx *sql.Tx, find *api.BackupcommentFROM backupWHERE `+strings.Join(where, " AND ")+` ORDER BY updated_ts DESC`,- args...,- )- if err != nil {- return nil, FormatError(err)- }- defer rows.Close()+ args...,+ )+ if err != nil {+ return nil, FormatError(err)+ }+ defer rows.Close()- // Iterate over result set and deserialize rows into backupRawList.- var backupRawList []*backupRaw- for rows.Next() {- var backupRaw backupRaw- if err := rows.Scan(- &backupRaw.ID,- &backupRaw.CreatorID,- &backupRaw.CreatedTs,- &backupRaw.UpdaterID,- &backupRaw.UpdatedTs,- &backupRaw.DatabaseID,- &backupRaw.Name,- &backupRaw.Status,- &backupRaw.Type,- &backupRaw.StorageBackend,- &backupRaw.MigrationHistoryVersion,- &backupRaw.Path,- &backupRaw.Comment,- ); err != nil {+ // Iterate over result set and deserialize rows into backupRawList.+ var backupRawList []*backupRaw+ for rows.Next() {+ var backupRaw backupRaw+ if err := rows.Scan(+ &backupRaw.ID,+ &backupRaw.CreatorID,+ &backupRaw.CreatedTs,+ &backupRaw.UpdaterID,+ &backupRaw.UpdatedTs,+ &backupRaw.DatabaseID,+ &backupRaw.Name,+ &backupRaw.Status,+ &backupRaw.Type,+ &backupRaw.StorageBackend,+ &backupRaw.MigrationHistoryVersion,+ &backupRaw.Path,+ &backupRaw.Comment,+ ); err != nil {+ return nil, FormatError(err)+ }+ backupRawList = append(backupRawList, &backupRaw)+ }+ if err := rows.Err(); err != nil {return nil, FormatError(err)}- backupRawList = append(backupRawList, &backupRaw)- }- if err := rows.Err(); err != nil {- return nil, FormatError(err)+ return backupRawList, nil}-- return backupRawList, nil}// patchBackupImpl updates a backup by ID. Returns the new state of the backup after update.@@ -539,6 +603,7 @@ func (s *Store) patchBackupImpl(ctx context.Context, tx *sql.Tx, patch *api.Backif row.Next() {var backupRaw backupRaw+ var payload []byteif err := row.Scan(&backupRaw.ID,&backupRaw.CreatorID,@@ -553,10 +618,13 @@ func (s *Store) patchBackupImpl(ctx context.Context, tx *sql.Tx, patch *api.Back&backupRaw.MigrationHistoryVersion,&backupRaw.Path,&backupRaw.Comment,- &backupRaw.Payload,+ &payload,); err != nil {return nil, FormatError(err)}+ if err := json.Unmarshal(payload, &backupRaw.Payload); err != nil {+ return nil, err+ }return &backupRaw, nil}} else {diff --git a/tests/backup_restore_test.go b/tests/backup_restore_test.goindex b73ceaaf07..ef8ac8ae4c 100644--- a/tests/backup_restore_test.go+++ b/tests/backup_restore_test.go@@ -13,6 +13,7 @@ import ("testing""time"+ "github.com/bytebase/bytebase/api"dbplugin "github.com/bytebase/bytebase/plugin/db"pluginmysql "github.com/bytebase/bytebase/plugin/db/mysql"restoremysql "github.com/bytebase/bytebase/plugin/restore/mysql"@@ -123,7 +124,7 @@ func TestPITR(t *testing.T) {t.Log("install mysqlbinlog binary")tmpDir := t.TempDir()- mysqlbinlogIns, err := mysqlutil.Install(tmpDir)+ mysqlutilIns, err := mysqlutil.Install(tmpDir)a.NoError(err)// test cases@@ -161,9 +162,9 @@ func TestPITR(t *testing.T) {createPITRIssueTimestamp := time.Now().Unix()mysqlDriver, ok := driver.(*pluginmysql.Driver)a.Equal(true, ok)- mysqlRestore := restoremysql.New(mysqlDriver, mysqlbinlogIns)- config := pluginmysql.BinlogInfo{}- err = mysqlRestore.RestorePITR(ctx, bufio.NewScanner(buf), config, database, createPITRIssueTimestamp)+ mysqlRestore := restoremysql.New(mysqlDriver, mysqlutilIns)+ binlogInfo := api.BinlogInfo{}+ err = mysqlRestore.RestorePITR(ctx, bufio.NewScanner(buf), binlogInfo, database, createPITRIssueTimestamp)a.NoError(err)t.Log("cutover stage")@@ -234,9 +235,9 @@ func TestPITR(t *testing.T) {createPITRIssueTimestamp := time.Now().Unix()mysqlDriver, ok := driver.(*pluginmysql.Driver)a.Equal(true, ok)- mysqlRestore := restoremysql.New(mysqlDriver, mysqlbinlogIns)- config := pluginmysql.BinlogInfo{}- err = mysqlRestore.RestorePITR(ctx, bufio.NewScanner(buf), config, database, createPITRIssueTimestamp)+ mysqlRestore := restoremysql.New(mysqlDriver, mysqlutilIns)+ binlogInfo := api.BinlogInfo{}+ err = mysqlRestore.RestorePITR(ctx, bufio.NewScanner(buf), binlogInfo, database, createPITRIssueTimestamp)a.NoError(err)t.Log("cutover stage")@@ -284,9 +285,9 @@ func TestPITR(t *testing.T) {t.Log("restore to pitr database")mysqlDriver, ok := driver.(*pluginmysql.Driver)a.Equal(true, ok)- mysqlRestore := restoremysql.New(mysqlDriver, mysqlbinlogIns)- config := pluginmysql.BinlogInfo{}- err = mysqlRestore.RestorePITR(ctx, bufio.NewScanner(buf), config, database, createPITRIssueTimestamp)+ mysqlRestore := restoremysql.New(mysqlDriver, mysqlutilIns)+ binlogInfo := api.BinlogInfo{}+ err = mysqlRestore.RestorePITR(ctx, bufio.NewScanner(buf), binlogInfo, database, createPITRIssueTimestamp)a.NoError(err)t.Log("cutover stage")