Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
fork migration history on database restore task.
spinningbot450b92c8402b
diff --git a/server/backup_runner.go b/server/backup_runner.goindex 9f3bc89b5e..5e30073f42 100644--- a/server/backup_runner.go+++ b/server/backup_runner.go@@ -91,16 +91,22 @@ func (s *BackupRunner) scheduleBackupTask(database *api.Database, backupName strreturn err}- backupCreate := &api.BackupCreate{- CreatorId: api.SYSTEM_BOT_ID,- DatabaseId: database.ID,- Name: backupName,- Status: api.BackupStatusPendingCreate,- Type: api.BackupTypeAutomatic,- StorageBackend: api.BackupStorageBackendLocal,- Path: path,+ // Store the migration history version if exists.+ migrationHistoryVersion, err := getMigrationVersion(database, s.l)+ if err != nil {+ return fmt.Errorf("failed to get migration history for database %q: %v", database.Name, err)}+ backupCreate := &api.BackupCreate{+ CreatorId: api.SYSTEM_BOT_ID,+ DatabaseId: database.ID,+ Name: backupName,+ Status: api.BackupStatusPendingCreate,+ Type: api.BackupTypeAutomatic,+ MigrationHistoryVersion: migrationHistoryVersion,+ StorageBackend: api.BackupStorageBackendLocal,+ Path: path,+ }backup, err := s.server.BackupService.CreateBackup(context.Background(), backupCreate)if err != nil {if bytebase.ErrorCode(err) == bytebase.ECONFLICT {diff --git a/server/database.go b/server/database.goindex e88ff1cd71..0872fd1b56 100644--- a/server/database.go+++ b/server/database.go@@ -288,14 +288,14 @@ func (s *Server) registerDatabaseRoutes(g *echo.Group) {return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to create backup directory for database ID: %v", id)).SetInternal(err)}- // Require version if using VCS.- if database.Project.WorkflowType == api.VCS_WORKFLOW {- version, err := getMigrationVersion(database, s.l)- if err != nil {- return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Migration history not found for database %q using VCS workflow", database.Name)).SetInternal(err)- }- backupCreate.MigrationHistoryVersion = version+ version, err := getMigrationVersion(database, s.l)+ if err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("failed to get migration history for database %q", database.Name)).SetInternal(err)}+ if database.Project.WorkflowType == api.VCS_WORKFLOW && version == "" {+ return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Migration history configuration is required for backups if database %q uses VCS workflow", database.Name)).SetInternal(err)+ }+ backupCreate.MigrationHistoryVersion = versionbackup, err := s.BackupService.CreateBackup(context.Background(), backupCreate)if err != nil {@@ -402,8 +402,6 @@ func (s *Server) registerDatabaseRoutes(g *echo.Group) {return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.Param("id"))).SetInternal(err)}- // TODO(spinningbot): need to clone migration history.-restoreBackup := &api.RestoreBackup{}if err := jsonapi.UnmarshalPayload(c.Request().Body, restoreBackup); err != nil {return echo.NewHTTPError(http.StatusBadRequest, "Malformatted restore from backup request").SetInternal(err)@@ -625,5 +623,6 @@ func (s *Server) ComposeBackupRelationship(ctx context.Context, backup *api.Backif err != nil {return err}+ s.ComposeDatabaseRelationship()return nil}diff --git a/server/task_executor_database_backup.go b/server/task_executor_database_backup.goindex 75d0864bba..8bbd73dde0 100644--- a/server/task_executor_database_backup.go+++ b/server/task_executor_database_backup.go@@ -165,9 +165,8 @@ func getMigrationVersion(database *api.Database, logger *zap.Logger) (string, erif err != nil {return "", fmt.Errorf("failed to fetch migration history list: %v", err)}- if len(list) != 1 {- return "", fmt.Errorf("database %q has no migration history", database.Name)+ if len(list) == 0 {+ return "", nil}-return list[0].Version, nil}diff --git a/server/task_executor_database_restore.go b/server/task_executor_database_restore.goindex 66c8deffb6..d6ddedcbcc 100644--- a/server/task_executor_database_restore.go+++ b/server/task_executor_database_restore.go@@ -10,6 +10,7 @@ import ("github.com/bytebase/bytebase/api""github.com/bytebase/bytebase/bin/bb/connect""github.com/bytebase/bytebase/bin/bb/restore/mysqlrestore"+ "github.com/bytebase/bytebase/db""go.uber.org/zap")@@ -69,7 +70,22 @@ func (exec *DatabaseRestoreTaskExecutor) RunOnce(ctx context.Context, server *Sezap.String("database", task.Database.Name),zap.String("backup", backup.Name),)+ databaseFind := &api.DatabaseFind{+ ID: &backup.DatabaseId,+ }+ backup.Database, err = server.ComposeDatabaseByFind(context.Background(), databaseFind)+ if err != nil {+ return true, "", err+ }+ // Fork migration history.+ if backup.MigrationHistoryVersion != "" {+ if err := forkMigrationHistory(backup.Database, task.Database, backup.MigrationHistoryVersion, exec.l); err != nil {+ return true, "", err+ }+ }++ // Restore the database to the target database.if err := restoreDatabase(task.Database, backup); err != nil {return true, "", err}@@ -96,3 +112,82 @@ func restoreDatabase(database *api.Database, backup *api.Backup) error {}return nil}++// forkMigrationHistory will fork the migration history from source database to target database based on backup migration history version.+// This is needed only when backup migration history version is not empty.+func forkMigrationHistory(sourceDatabase, targetDatabase *api.Database, migrationHistoryVersion string, logger *zap.Logger) error {+ sourceDriver, err := getDatabaseDriver(sourceDatabase, logger)+ if err != nil {+ return err+ }+ defer sourceDriver.Close(context.Background())++ targetDriver, err := getDatabaseDriver(targetDatabase, logger)+ if err != nil {+ return err+ }+ defer targetDriver.Close(context.Background())++ find := &db.MigrationHistoryFind{+ Database: &sourceDatabase.Name,+ }+ list, err := sourceDriver.FindMigrationHistoryList(context.Background(), find)+ if err != nil {+ return fmt.Errorf("failed to fetch migration history list: %v", err)+ }++ var forkList []*db.MigrationHistory+ for i := len(list) - 1; i >= 0; i-- {+ history := list[i]+ history.Namespace = targetDatabase.Name+ forkList = append(forkList, history)+ // Fork the history up to the backup version.+ if history.Version == migrationHistoryVersion {+ break+ }+ }+ // TODO(spinningbot): add a new BRANCH migration history.++ for _, history := range forkList {+ m := &db.MigrationInfo{+ Version: history.Version,+ Namespace: history.Namespace,+ Database: targetDatabase.Name,+ Environment: targetDatabase.Instance.Environment.Name,+ Engine: history.Engine,+ Type: history.Type,+ Description: history.Description,+ Creator: history.Creator,+ IssueId: history.IssueId,+ Payload: history.Payload,+ }+ if err := targetDriver.ExecuteMigration(context.Background(), m, history.Statement); err != nil {+ return err+ }+ }++ return nil+}++func getDatabaseDriver(database *api.Database, logger *zap.Logger) (db.Driver, error) {+ instance := database.Instance+ driver, err := db.Open(+ instance.Engine,+ db.DriverConfig{Logger: logger},+ db.ConnectionConfig{+ Username: instance.Username,+ Password: instance.Password,+ Host: instance.Host,+ Port: instance.Port,+ Database: database.Name,+ },+ db.ConnectionContext{+ EnvironmentName: instance.Environment.Name,+ InstanceName: instance.Name,+ },+ )+ if err != nil {+ return nil, fmt.Errorf("failed to connect instance: %v with user: %v. %w", instance.Name, instance.Username, err)+ }+ return driver, nil+}