Skip to content

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

refactor: execute migration (#14038)

p0ny77a0d0cea407
diff --git a/backend/migrator/migrator.go b/backend/migrator/migrator.go
index 3ff402a766..5cab643e50 100644
--- a/backend/migrator/migrator.go
+++ b/backend/migrator/migrator.go
@@ -2,6 +2,7 @@
package migrator
import (
+ "bytes"
"context"
"embed"
"fmt"
@@ -17,6 +18,8 @@ import (
"github.com/pkg/errors"
"github.com/bytebase/bytebase/backend/common"
+ "github.com/bytebase/bytebase/backend/common/log"
+ "github.com/bytebase/bytebase/backend/component/state"
api "github.com/bytebase/bytebase/backend/legacyapi"
dbdriver "github.com/bytebase/bytebase/backend/plugin/db"
"github.com/bytebase/bytebase/backend/store"
@@ -323,7 +326,7 @@ func migrate(ctx context.Context, storeInstance *store.Store, metadataDriver dbd
Type: dbdriver.Migrate,
Description: fmt.Sprintf("Migrate version %s server version %s with files %s.", pv.version, serverVersion, pv.filename),
}
- if _, _, err := utils.ExecuteMigrationDefault(ctx, ctx, storeInstance, nil, 0, metadataDriver, mi, string(buf), nil, dbdriver.ExecuteOptions{}); err != nil {
+ if _, _, err := executeMigrationDefault(ctx, ctx, storeInstance, nil, 0, metadataDriver, mi, string(buf), nil, dbdriver.ExecuteOptions{}); err != nil {
return false, err
}
retVersion = pv.version
@@ -409,7 +412,7 @@ func migrateDev(ctx context.Context, storeInstance *store.Store, metadataDriver
Type: dbdriver.Migrate,
Description: fmt.Sprintf("Migrate version %s server version %s with files %s.", m.version, serverVersion, m.filename),
}
- if _, _, err := utils.ExecuteMigrationDefault(ctx, ctx, storeInstance, nil, 0, metadataDriver, mi, m.statement, nil, dbdriver.ExecuteOptions{}); err != nil {
+ if _, _, err := executeMigrationDefault(ctx, ctx, storeInstance, nil, 0, metadataDriver, mi, m.statement, nil, dbdriver.ExecuteOptions{}); err != nil {
return err
}
}
@@ -580,3 +583,156 @@ func backfillOracleSchema(ctx context.Context, stores *store.Store) error {
}
return nil
}
+
+// executeMigrationDefault executes migration.
+func executeMigrationDefault(ctx context.Context, driverCtx context.Context, store *store.Store, _ *state.State, taskRunUID int, driver dbdriver.Driver, mi *dbdriver.MigrationInfo, statement string, sheetID *int, opts dbdriver.ExecuteOptions) (migrationHistoryID string, updatedSchema string, resErr error) {
+ execFunc := func(ctx context.Context, execStatement string) error {
+ if _, err := driver.Execute(ctx, execStatement, opts); err != nil {
+ return err
+ }
+ return nil
+ }
+ return ExecuteMigrationWithFunc(ctx, driverCtx, store, taskRunUID, driver, mi, statement, sheetID, execFunc, opts)
+}
+
+// ExecuteMigrationWithFunc executes the migration with custom migration function.
+func ExecuteMigrationWithFunc(ctx context.Context, driverCtx context.Context, s *store.Store, _ int, driver dbdriver.Driver, m *dbdriver.MigrationInfo, statement string, sheetID *int, execFunc func(ctx context.Context, execStatement string) error, opts dbdriver.ExecuteOptions) (migrationHistoryID string, updatedSchema string, resErr error) {
+ var prevSchemaBuf bytes.Buffer
+ if m.Type.NeedDump() {
+ opts.LogSchemaDumpStart()
+ // Don't record schema if the database hasn't existed yet or is schemaless, e.g. MongoDB.
+ // For baseline migration, we also record the live schema to detect the schema drift.
+ // See https://bytebase.com/blog/what-is-database-schema-drift
+ if err := driver.Dump(ctx, &prevSchemaBuf); err != nil {
+ opts.LogSchemaDumpEnd(err.Error())
+ return "", "", err
+ }
+ opts.LogSchemaDumpEnd("")
+ }
+
+ insertedID, err := BeginMigration(ctx, s, m, prevSchemaBuf.String(), statement, sheetID)
+ if err != nil {
+ return "", "", errors.Wrapf(err, "failed to begin migration")
+ }
+
+ startedNs := time.Now().UnixNano()
+
+ defer func() {
+ if err := EndMigration(ctx, s, startedNs, insertedID, updatedSchema, prevSchemaBuf.String(), sheetID, resErr == nil /* isDone */); err != nil {
+ slog.Error("Failed to update migration history record",
+ log.BBError(err),
+ slog.String("migration_id", migrationHistoryID),
+ )
+ }
+ }()
+
+ // Phase 3 - Executing migration
+ // Branch migration type always has empty sql.
+ // Baseline migration type could has non-empty sql but will not execute.
+ // https://github.com/bytebase/bytebase/issues/394
+ doMigrate := true
+ if statement == "" || m.Type == dbdriver.Baseline {
+ doMigrate = false
+ }
+ if doMigrate {
+ renderedStatement := statement
+ // The m.DatabaseID is nil means the migration is a instance level migration
+ if m.DatabaseID != nil {
+ database, err := s.GetDatabaseV2(ctx, &store.FindDatabaseMessage{
+ UID: m.DatabaseID,
+ })
+ if err != nil {
+ return "", "", err
+ }
+ if database == nil {
+ return "", "", errors.Errorf("database %d not found", *m.DatabaseID)
+ }
+ materials := utils.GetSecretMapFromDatabaseMessage(database)
+ // To avoid leak the rendered statement, the error message should use the original statement and not the rendered statement.
+ renderedStatement = utils.RenderStatement(statement, materials)
+ }
+
+ if err := execFunc(driverCtx, renderedStatement); err != nil {
+ return "", "", err
+ }
+ }
+
+ // Phase 4 - Dump the schema after migration
+ var afterSchemaBuf bytes.Buffer
+ if m.Type.NeedDump() {
+ opts.LogSchemaDumpStart()
+ if err := driver.Dump(ctx, &afterSchemaBuf); err != nil {
+ // We will ignore the dump error if the database is dropped.
+ if strings.Contains(err.Error(), "not found") {
+ return insertedID, "", nil
+ }
+ opts.LogSchemaDumpEnd(err.Error())
+ return "", "", err
+ }
+ opts.LogSchemaDumpEnd("")
+ }
+
+ return insertedID, afterSchemaBuf.String(), nil
+}
+
+// BeginMigration checks before executing migration and inserts a migration history record with pending status.
+func BeginMigration(ctx context.Context, stores *store.Store, m *dbdriver.MigrationInfo, prevSchema, statement string, sheetID *int) (string, error) {
+ // Phase 1 - Pre-check before executing migration
+ // Check if the same migration version has already been applied.
+ if list, err := stores.ListInstanceChangeHistory(ctx, &store.FindInstanceChangeHistoryMessage{
+ InstanceID: m.InstanceID,
+ DatabaseID: m.DatabaseID,
+ Version: &m.Version,
+ }); err != nil {
+ return "", errors.Wrap(err, "failed to check duplicate version")
+ } else if len(list) > 0 {
+ migrationHistory := list[0]
+ switch migrationHistory.Status {
+ case dbdriver.Done:
+ return "", common.Errorf(common.MigrationAlreadyApplied, "database %q has already applied version %s, hint: the version might be duplicate, please check the version", m.Database, m.Version.Version)
+ case dbdriver.Pending:
+ err := errors.Errorf("database %q version %s migration is already in progress", m.Database, m.Version.Version)
+ slog.Debug(err.Error())
+ // For force migration, we will ignore the existing migration history and continue to migration.
+ return migrationHistory.UID, nil
+ case dbdriver.Failed:
+ err := errors.Errorf("database %q version %s migration has failed, please check your database to make sure things are fine and then start a new migration using a new version", m.Database, m.Version.Version)
+ slog.Debug(err.Error())
+ // For force migration, we will ignore the existing migration history and continue to migration.
+ return migrationHistory.UID, nil
+ }
+ }
+
+ // Phase 2 - Record migration history as PENDING.
+ statementRecord, _ := common.TruncateString(statement, common.MaxSheetSize)
+ insertedID, err := stores.CreatePendingInstanceChangeHistory(ctx, prevSchema, m, statementRecord, sheetID)
+ if err != nil {
+ return "", err
+ }
+
+ return insertedID, nil
+}
+
+// EndMigration updates the migration history record to DONE or FAILED depending on migration is done or not.
+func EndMigration(ctx context.Context, storeInstance *store.Store, startedNs int64, insertedID string, updatedSchema, schemaPrev string, sheetID *int, isDone bool) error {
+ migrationDurationNs := time.Now().UnixNano() - startedNs
+ update := &store.UpdateInstanceChangeHistoryMessage{
+ ID: insertedID,
+ ExecutionDurationNs: &migrationDurationNs,
+ // Update the sheet ID just in case it has been updated.
+ Sheet: sheetID,
+ // Update schemaPrev because we might be re-using a previous change history entry.
+ SchemaPrev: &schemaPrev,
+ }
+ if isDone {
+ // Upon success, update the migration history as 'DONE', execution_duration_ns, updated schema.
+ status := dbdriver.Done
+ update.Status = &status
+ update.Schema = &updatedSchema
+ } else {
+ // Otherwise, update the migration history as 'FAILED', execution_duration.
+ status := dbdriver.Failed
+ update.Status = &status
+ }
+ return storeInstance.UpdateInstanceChangeHistory(ctx, update)
+}
diff --git a/backend/plugin/db/driver.go b/backend/plugin/db/driver.go
index f38e7427ae..8d84c3d1b0 100644
--- a/backend/plugin/db/driver.go
+++ b/backend/plugin/db/driver.go
@@ -164,6 +164,9 @@ type MigrationInfo struct {
Creator string
// Payload contains JSON-encoded string of VCS push event if the migration is triggered by a VCS push event.
Payload *storepb.InstanceChangeHistoryPayload
+
+ SheetUID *int
+ Sheet *string
}
// ConnectionConfig is the configuration for connections.
diff --git a/backend/runner/taskrun/database_create_executor.go b/backend/runner/taskrun/database_create_executor.go
index c1d1b513cc..ed06ff2c12 100644
--- a/backend/runner/taskrun/database_create_executor.go
+++ b/backend/runner/taskrun/database_create_executor.go
@@ -408,7 +408,7 @@ func (exec *DatabaseCreateExecutor) createInitialSchema(ctx context.Context, dri
mi.IssueUID = &issue.UID
}
- if _, _, err := utils.ExecuteMigrationDefault(ctx, driverCtx, exec.store, exec.stateCfg, taskRunUID, driver, mi, schema, nil, db.ExecuteOptions{}); err != nil {
+ if _, _, err := executeMigrationDefault(ctx, driverCtx, exec.store, exec.stateCfg, taskRunUID, driver, mi, schema, nil, db.ExecuteOptions{}); err != nil {
return nil, model.Version{}, "", err
}
return peerDatabase, schemaVersion, schema, nil
diff --git a/backend/runner/taskrun/executor.go b/backend/runner/taskrun/executor.go
index dde699f518..9065cb6abf 100644
--- a/backend/runner/taskrun/executor.go
+++ b/backend/runner/taskrun/executor.go
@@ -1,6 +1,7 @@
package taskrun
import (
+ "bytes"
"context"
"fmt"
"log/slog"
@@ -177,7 +178,7 @@ func getCreateTaskRunLog(ctx context.Context, taskRunUID int, s *store.Store, pr
}
}
-func executeMigration(
+func doMigration(
ctx context.Context,
driverCtx context.Context,
stores *store.Store,
@@ -240,7 +241,7 @@ func executeMigration(
}
}
- migrationID, schema, err := utils.ExecuteMigrationDefault(ctx, driverCtx, stores, stateCfg, taskRunUID, driver, mi, statement, sheetID, opts)
+ migrationID, schema, err := executeMigrationDefault(ctx, driverCtx, stores, stateCfg, taskRunUID, driver, mi, statement, sheetID, opts)
if err != nil {
return "", "", err
}
@@ -333,9 +334,162 @@ func runMigration(ctx context.Context, driverCtx context.Context, store *store.S
return true, nil, err
}
- migrationID, _, err := executeMigration(ctx, driverCtx, store, dbFactory, stateCfg, profile, task, taskRunUID, statement, sheetID, mi)
+ migrationID, _, err := doMigration(ctx, driverCtx, store, dbFactory, stateCfg, profile, task, taskRunUID, statement, sheetID, mi)
if err != nil {
return true, nil, err
}
return postMigration(ctx, store, task, mi, migrationID, sheetID)
}
+
+// executeMigrationDefault executes migration.
+func executeMigrationDefault(ctx context.Context, driverCtx context.Context, store *store.Store, _ *state.State, taskRunUID int, driver db.Driver, mi *db.MigrationInfo, statement string, sheetID *int, opts db.ExecuteOptions) (migrationHistoryID string, updatedSchema string, resErr error) {
+ execFunc := func(ctx context.Context, execStatement string) error {
+ if _, err := driver.Execute(ctx, execStatement, opts); err != nil {
+ return err
+ }
+ return nil
+ }
+ return executeMigrationWithFunc(ctx, driverCtx, store, taskRunUID, driver, mi, statement, sheetID, execFunc, opts)
+}
+
+// executeMigrationWithFunc executes the migration with custom migration function.
+func executeMigrationWithFunc(ctx context.Context, driverCtx context.Context, s *store.Store, _ int, driver db.Driver, m *db.MigrationInfo, statement string, sheetID *int, execFunc func(ctx context.Context, execStatement string) error, opts db.ExecuteOptions) (migrationHistoryID string, updatedSchema string, resErr error) {
+ var prevSchemaBuf bytes.Buffer
+ if m.Type.NeedDump() {
+ opts.LogSchemaDumpStart()
+ // Don't record schema if the database hasn't existed yet or is schemaless, e.g. MongoDB.
+ // For baseline migration, we also record the live schema to detect the schema drift.
+ // See https://bytebase.com/blog/what-is-database-schema-drift
+ if err := driver.Dump(ctx, &prevSchemaBuf); err != nil {
+ opts.LogSchemaDumpEnd(err.Error())
+ return "", "", err
+ }
+ opts.LogSchemaDumpEnd("")
+ }
+
+ insertedID, err := beginMigration(ctx, s, m, prevSchemaBuf.String(), statement, sheetID)
+ if err != nil {
+ return "", "", errors.Wrapf(err, "failed to begin migration")
+ }
+
+ startedNs := time.Now().UnixNano()
+
+ defer func() {
+ if err := endMigration(ctx, s, startedNs, insertedID, updatedSchema, prevSchemaBuf.String(), sheetID, resErr == nil /* isDone */); err != nil {
+ slog.Error("Failed to update migration history record",
+ log.BBError(err),
+ slog.String("migration_id", migrationHistoryID),
+ )
+ }
+ }()
+
+ // Phase 3 - Executing migration
+ // Branch migration type always has empty sql.
+ // Baseline migration type could has non-empty sql but will not execute.
+ // https://github.com/bytebase/bytebase/issues/394
+ doMigrate := true
+ if statement == "" || m.Type == db.Baseline {
+ doMigrate = false
+ }
+ if doMigrate {
+ renderedStatement := statement
+ // The m.DatabaseID is nil means the migration is a instance level migration
+ if m.DatabaseID != nil {
+ database, err := s.GetDatabaseV2(ctx, &store.FindDatabaseMessage{
+ UID: m.DatabaseID,
+ })
+ if err != nil {
+ return "", "", err
+ }
+ if database == nil {
+ return "", "", errors.Errorf("database %d not found", *m.DatabaseID)
+ }
+ materials := utils.GetSecretMapFromDatabaseMessage(database)
+ // To avoid leak the rendered statement, the error message should use the original statement and not the rendered statement.
+ renderedStatement = utils.RenderStatement(statement, materials)
+ }
+
+ if err := execFunc(driverCtx, renderedStatement); err != nil {
+ return "", "", err
+ }
+ }
+
+ // Phase 4 - Dump the schema after migration
+ var afterSchemaBuf bytes.Buffer
+ if m.Type.NeedDump() {
+ opts.LogSchemaDumpStart()
+ if err := driver.Dump(ctx, &afterSchemaBuf); err != nil {
+ // We will ignore the dump error if the database is dropped.
+ if strings.Contains(err.Error(), "not found") {
+ return insertedID, "", nil
+ }
+ opts.LogSchemaDumpEnd(err.Error())
+ return "", "", err
+ }
+ opts.LogSchemaDumpEnd("")
+ }
+
+ return insertedID, afterSchemaBuf.String(), nil
+}
+
+// beginMigration checks before executing migration and inserts a migration history record with pending status.
+func beginMigration(ctx context.Context, stores *store.Store, m *db.MigrationInfo, prevSchema, statement string, sheetID *int) (string, error) {
+ // Phase 1 - Pre-check before executing migration
+ // Check if the same migration version has already been applied.
+ if list, err := stores.ListInstanceChangeHistory(ctx, &store.FindInstanceChangeHistoryMessage{
+ InstanceID: m.InstanceID,
+ DatabaseID: m.DatabaseID,
+ Version: &m.Version,
+ }); err != nil {
+ return "", errors.Wrap(err, "failed to check duplicate version")
+ } else if len(list) > 0 {
+ migrationHistory := list[0]
+ switch migrationHistory.Status {
+ case db.Done:
+ return "", common.Errorf(common.MigrationAlreadyApplied, "database %q has already applied version %s, hint: the version might be duplicate, please check the version", m.Database, m.Version.Version)
+ case db.Pending:
+ err := errors.Errorf("database %q version %s migration is already in progress", m.Database, m.Version.Version)
+ slog.Debug(err.Error())
+ // For force migration, we will ignore the existing migration history and continue to migration.
+ return migrationHistory.UID, nil
+ case db.Failed:
+ err := errors.Errorf("database %q version %s migration has failed, please check your database to make sure things are fine and then start a new migration using a new version", m.Database, m.Version.Version)
+ slog.Debug(err.Error())
+ // For force migration, we will ignore the existing migration history and continue to migration.
+ return migrationHistory.UID, nil
+ }
+ }
+
+ // Phase 2 - Record migration history as PENDING.
+ statementRecord, _ := common.TruncateString(statement, common.MaxSheetSize)
+ insertedID, err := stores.CreatePendingInstanceChangeHistory(ctx, prevSchema, m, statementRecord, sheetID)
+ if err != nil {
+ return "", err
+ }
+
+ return insertedID, nil
+}
+
+// endMigration updates the migration history record to DONE or FAILED depending on migration is done or not.
+func endMigration(ctx context.Context, storeInstance *store.Store, startedNs int64, insertedID string, updatedSchema, schemaPrev string, sheetID *int, isDone bool) error {
+ migrationDurationNs := time.Now().UnixNano() - startedNs
+ update := &store.UpdateInstanceChangeHistoryMessage{
+ ID: insertedID,
+ ExecutionDurationNs: &migrationDurationNs,
+ // Update the sheet ID just in case it has been updated.
+ Sheet: sheetID,
+ // Update schemaPrev because we might be re-using a previous change history entry.
+ SchemaPrev: &schemaPrev,
+ }
+ if isDone {
+ // Upon success, update the migration history as 'DONE', execution_duration_ns, updated schema.
+ status := db.Done
+ update.Status = &status
+ update.Schema = &updatedSchema
+ } else {
+ // Otherwise, update the migration history as 'FAILED', execution_duration.
+ status := db.Failed
+ update.Status = &status
+ }
+ return storeInstance.UpdateInstanceChangeHistory(ctx, update)
+}
diff --git a/backend/runner/taskrun/schema_update_ghost_cutover_executor.go b/backend/runner/taskrun/schema_update_ghost_cutover_executor.go
index 3a130a0f05..5973febf40 100644
--- a/backend/runner/taskrun/schema_update_ghost_cutover_executor.go
+++ b/backend/runner/taskrun/schema_update_ghost_cutover_executor.go
@@ -151,7 +151,7 @@ func cutover(ctx context.Context, taskContext context.Context, stores *store.Sto
return true, nil, err
}
defer driver.Close(ctx)
- migrationID, _, err := utils.ExecuteMigrationWithFunc(ctx, ctx, stores, taskRunUID, driver, mi, statement, &sheetID, execFunc, db.ExecuteOptions{})
+ migrationID, _, err := executeMigrationWithFunc(ctx, ctx, stores, taskRunUID, driver, mi, statement, &sheetID, execFunc, db.ExecuteOptions{})
if err != nil {
return true, nil, err
}
diff --git a/backend/utils/utils.go b/backend/utils/utils.go
index aaad17ff4d..e339284c39 100644
--- a/backend/utils/utils.go
+++ b/backend/utils/utils.go
@@ -2,18 +2,15 @@
package utils
import (
- "bytes"
"context"
"encoding/json"
"fmt"
"io"
- "log/slog"
"reflect"
"regexp"
"sort"
"strconv"
"strings"
- "time"
"unicode"
"github.com/pkg/errors"
@@ -28,11 +25,8 @@ import (
"google.golang.org/protobuf/encoding/protojson"
"github.com/bytebase/bytebase/backend/common"
- "github.com/bytebase/bytebase/backend/common/log"
- "github.com/bytebase/bytebase/backend/component/state"
api "github.com/bytebase/bytebase/backend/legacyapi"
"github.com/bytebase/bytebase/backend/plugin/app/relay"
- "github.com/bytebase/bytebase/backend/plugin/db"
"github.com/bytebase/bytebase/backend/store"
storepb "github.com/bytebase/bytebase/proto/generated-go/store"
)
@@ -233,159 +227,6 @@ func MergeTaskCreateLists(taskCreateLists [][]*store.TaskMessage, taskIndexDAGLi
return resTaskCreateList, resTaskIndexDAGList, nil
}
-// ExecuteMigrationDefault executes migration.
-func ExecuteMigrationDefault(ctx context.Context, driverCtx context.Context, store *store.Store, _ *state.State, taskRunUID int, driver db.Driver, mi *db.MigrationInfo, statement string, sheetID *int, opts db.ExecuteOptions) (migrationHistoryID string, updatedSchema string, resErr error) {
- execFunc := func(ctx context.Context, execStatement string) error {
- if _, err := driver.Execute(ctx, execStatement, opts); err != nil {
- return err
- }
- return nil
- }
- return ExecuteMigrationWithFunc(ctx, driverCtx, store, taskRunUID, driver, mi, statement, sheetID, execFunc, opts)
-}
-
-// ExecuteMigrationWithFunc executes the migration with custom migration function.
-func ExecuteMigrationWithFunc(ctx context.Context, driverCtx context.Context, s *store.Store, _ int, driver db.Driver, m *db.MigrationInfo, statement string, sheetID *int, execFunc func(ctx context.Context, execStatement string) error, opts db.ExecuteOptions) (migrationHistoryID string, updatedSchema string, resErr error) {
- var prevSchemaBuf bytes.Buffer
- if m.Type.NeedDump() {
- opts.LogSchemaDumpStart()
- // Don't record schema if the database hasn't existed yet or is schemaless, e.g. MongoDB.
- // For baseline migration, we also record the live schema to detect the schema drift.
- // See https://bytebase.com/blog/what-is-database-schema-drift
- if err := driver.Dump(ctx, &prevSchemaBuf); err != nil {
- opts.LogSchemaDumpEnd(err.Error())
- return "", "", err
- }
- opts.LogSchemaDumpEnd("")
- }
-
- insertedID, err := BeginMigration(ctx, s, m, prevSchemaBuf.String(), statement, sheetID)
- if err != nil {
- return "", "", errors.Wrapf(err, "failed to begin migration")
- }
-
- startedNs := time.Now().UnixNano()
-
- defer func() {
- if err := EndMigration(ctx, s, startedNs, insertedID, updatedSchema, prevSchemaBuf.String(), sheetID, resErr == nil /* isDone */); err != nil {
- slog.Error("Failed to update migration history record",
- log.BBError(err),
- slog.String("migration_id", migrationHistoryID),
- )
- }
- }()
-
- // Phase 3 - Executing migration
- // Branch migration type always has empty sql.
- // Baseline migration type could has non-empty sql but will not execute.
- // https://github.com/bytebase/bytebase/issues/394
- doMigrate := true
- if statement == "" || m.Type == db.Baseline {
- doMigrate = false
- }
- if doMigrate {
- renderedStatement := statement
- // The m.DatabaseID is nil means the migration is a instance level migration
- if m.DatabaseID != nil {
- database, err := s.GetDatabaseV2(ctx, &store.FindDatabaseMessage{
- UID: m.DatabaseID,
- })
- if err != nil {
- return "", "", err
- }
- if database == nil {
- return "", "", errors.Errorf("database %d not found", *m.DatabaseID)
- }
- materials := GetSecretMapFromDatabaseMessage(database)
- // To avoid leak the rendered statement, the error message should use the original statement and not the rendered statement.
- renderedStatement = RenderStatement(statement, materials)
- }
-
- if err := execFunc(driverCtx, renderedStatement); err != nil {
- return "", "", err
- }
- }
-
- // Phase 4 - Dump the schema after migration
- var afterSchemaBuf bytes.Buffer
- if m.Type.NeedDump() {
- opts.LogSchemaDumpStart()
- if err := driver.Dump(ctx, &afterSchemaBuf); err != nil {
- // We will ignore the dump error if the database is dropped.
- if strings.Contains(err.Error(), "not found") {
- return insertedID, "", nil
- }
- opts.LogSchemaDumpEnd(err.Error())
- return "", "", err
- }
- opts.LogSchemaDumpEnd("")
- }
-
- return insertedID, afterSchemaBuf.String(), nil
-}
-
-// BeginMigration checks before executing migration and inserts a migration history record with pending status.
-func BeginMigration(ctx context.Context, stores *store.Store, m *db.MigrationInfo, prevSchema, statement string, sheetID *int) (string, error) {
- // Phase 1 - Pre-check before executing migration
- // Check if the same migration version has already been applied.
- if list, err := stores.ListInstanceChangeHistory(ctx, &store.FindInstanceChangeHistoryMessage{
- InstanceID: m.InstanceID,
- DatabaseID: m.DatabaseID,
- Version: &m.Version,
- }); err != nil {
- return "", errors.Wrap(err, "failed to check duplicate version")
- } else if len(list) > 0 {
- migrationHistory := list[0]
- switch migrationHistory.Status {
- case db.Done:
- return "", common.Errorf(common.MigrationAlreadyApplied, "database %q has already applied version %s, hint: the version might be duplicate, please check the version", m.Database, m.Version.Version)
- case db.Pending:
- err := errors.Errorf("database %q version %s migration is already in progress", m.Database, m.Version.Version)
- slog.Debug(err.Error())
- // For force migration, we will ignore the existing migration history and continue to migration.
- return migrationHistory.UID, nil
- case db.Failed:
- err := errors.Errorf("database %q version %s migration has failed, please check your database to make sure things are fine and then start a new migration using a new version", m.Database, m.Version.Version)
- slog.Debug(err.Error())
- // For force migration, we will ignore the existing migration history and continue to migration.
- return migrationHistory.UID, nil
- }
- }
-
- // Phase 2 - Record migration history as PENDING.
- statementRecord, _ := common.TruncateString(statement, common.MaxSheetSize)
- insertedID, err := stores.CreatePendingInstanceChangeHistory(ctx, prevSchema, m, statementRecord, sheetID)
- if err != nil {
- return "", err
- }
-
- return insertedID, nil
-}
-
-// EndMigration updates the migration history record to DONE or FAILED depending on migration is done or not.
-func EndMigration(ctx context.Context, storeInstance *store.Store, startedNs int64, insertedID string, updatedSchema, schemaPrev string, sheetID *int, isDone bool) error {
- migrationDurationNs := time.Now().UnixNano() - startedNs
- update := &store.UpdateInstanceChangeHistoryMessage{
- ID: insertedID,
- ExecutionDurationNs: &migrationDurationNs,
- // Update the sheet ID just in case it has been updated.
- Sheet: sheetID,
- // Update schemaPrev because we might be re-using a previous change history entry.
- SchemaPrev: &schemaPrev,
- }
- if isDone {
- // Upon success, update the migration history as 'DONE', execution_duration_ns, updated schema.
- status := db.Done
- update.Status = &status
- update.Schema = &updatedSchema
- } else {
- // Otherwise, update the migration history as 'FAILED', execution_duration.
- status := db.Failed
- update.Status = &status
- }
- return storeInstance.UpdateInstanceChangeHistory(ctx, update)
-}
-
// FindNextPendingStep finds the next pending step in the approval flow.
func FindNextPendingStep(template *storepb.ApprovalTemplate, approvers []*storepb.IssuePayloadApproval_Approver) *storepb.ApprovalStep {
// We can do the finding like this for now because we are presuming that