Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
refactor: migrate context (#14047)
p0ny0425ed8217b0
diff --git a/backend/common/resource_name.go b/backend/common/resource_name.goindex a9ea06ba42..1c8d4c3751 100644--- a/backend/common/resource_name.go+++ b/backend/common/resource_name.go@@ -655,6 +655,10 @@ func FormatTask(projectID string, pipelineUID, stageUID, taskUID int) string {return fmt.Sprintf("%s%s/%s%d/%s%d/%s%d", ProjectNamePrefix, projectID, RolloutPrefix, pipelineUID, StagePrefix, stageUID, TaskPrefix, taskUID)}+func FormatTaskRun(projectID string, pipelineUID, stageUID, taskUID, taskRunUID int) string {+ return fmt.Sprintf("%s%s/%s%d/%s%d/%s%d/%s%d", ProjectNamePrefix, projectID, RolloutPrefix, pipelineUID, StagePrefix, stageUID, TaskPrefix, taskUID, TaskRunPrefix, taskRunUID)+}+func FormatBranchResourceID(projectID string, branchID string) string {return fmt.Sprintf("%s%s/%s%s", ProjectNamePrefix, projectID, BranchPrefix, branchID)}diff --git a/backend/runner/taskrun/database_create_executor.go b/backend/runner/taskrun/database_create_executor.goindex ed06ff2c12..35c16a1c63 100644--- a/backend/runner/taskrun/database_create_executor.go+++ b/backend/runner/taskrun/database_create_executor.go@@ -408,7 +408,17 @@ func (exec *DatabaseCreateExecutor) createInitialSchema(ctx context.Context, drimi.IssueUID = &issue.UID}- if _, _, err := executeMigrationDefault(ctx, driverCtx, exec.store, exec.stateCfg, taskRunUID, driver, mi, schema, nil, db.ExecuteOptions{}); err != nil {+ mc := &migrateContext{+ instance: instance,+ database: database,+ sheet: nil,+ task: task,+ taskRunUID: taskRunUID,+ taskRunName: common.FormatTaskRun(project.ResourceID, task.PipelineID, task.StageID, task.ID, taskRunUID),+ version: schemaVersion.Version,+ }++ if _, _, err := executeMigrationDefault(ctx, driverCtx, exec.store, exec.stateCfg, driver, mi, mc, schema, db.ExecuteOptions{}); err != nil {return nil, model.Version{}, "", err}return peerDatabase, schemaVersion, schema, nildiff --git a/backend/runner/taskrun/executor.go b/backend/runner/taskrun/executor.goindex 9065cb6abf..45294bf93a 100644--- a/backend/runner/taskrun/executor.go+++ b/backend/runner/taskrun/executor.go@@ -56,24 +56,38 @@ func RunExecutorOnce(ctx context.Context, driverCtx context.Context, exec Executreturn exec.RunOnce(ctx, driverCtx, task, taskRunUID)}-func getMigrationInfo(ctx context.Context, stores *store.Store, profile *config.Profile, task *store.TaskMessage, migrationType db.MigrationType, statement string, schemaVersion model.Version, sheetID *int) (*db.MigrationInfo, error) {+// Pointer fields are not nullable unless mentioned otherwise.+type migrateContext struct {+ instance *store.InstanceMessage+ database *store.DatabaseMessage+ // nullable if type=baseline+ sheet *store.SheetMessage+ task *store.TaskMessage++ taskRunUID int+ taskRunName string++ version string+}++func getMigrationInfo(ctx context.Context, stores *store.Store, profile *config.Profile, task *store.TaskMessage, migrationType db.MigrationType, statement string, schemaVersion model.Version, sheetID *int, taskRunUID int) (*db.MigrationInfo, *migrateContext, error) {if schemaVersion.Version == "" {- return nil, errors.Errorf("empty schema version")+ return nil, nil, errors.Errorf("empty schema version")}instance, err := stores.GetInstanceV2(ctx, &store.FindInstanceMessage{UID: &task.InstanceID})if err != nil {- return nil, err+ return nil, nil, err}database, err := stores.GetDatabaseV2(ctx, &store.FindDatabaseMessage{UID: task.DatabaseID})if err != nil {- return nil, err+ return nil, nil, err}if database == nil {- return nil, errors.Errorf("database not found")+ return nil, nil, errors.Errorf("database not found")}environment, err := stores.GetEnvironmentV2(ctx, &store.FindEnvironmentMessage{ResourceID: &database.EffectiveEnvironmentID})if err != nil {- return nil, err+ return nil, nil, err}mi := &db.MigrationInfo{@@ -90,9 +104,37 @@ func getMigrationInfo(ctx context.Context, stores *store.Store, profile *config.Payload: &storepb.InstanceChangeHistoryPayload{},}+ pipeline, err := stores.GetPipelineV2ByID(ctx, task.PipelineID)+ if err != nil {+ return nil, nil, errors.Wrapf(err, "failed to get pipeline")+ }+ if pipeline == nil {+ return nil, nil, errors.Errorf("pipeline %v not found", task.PipelineID)+ }++ mc := &migrateContext{+ instance: instance,+ database: database,+ task: task,+ version: schemaVersion.Version,+ taskRunName: common.FormatTaskRun(pipeline.ProjectID, task.PipelineID, task.StageID, task.ID, taskRunUID),+ taskRunUID: taskRunUID,+ }++ if sheetID != nil {+ sheet, err := stores.GetSheet(ctx, &store.FindSheetMessage{UID: sheetID})+ if err != nil {+ return nil, nil, errors.Wrapf(err, "failed to get sheet")+ }+ if sheet == nil {+ return nil, nil, errors.Errorf("sheet not found")+ }+ mc.sheet = sheet+ }+plans, err := stores.ListPlans(ctx, &store.FindPlanMessage{PipelineID: &task.PipelineID})if err != nil {- return nil, err+ return nil, nil, errors.Wrapf(err, "failed to list plans")}if len(plans) == 1 {planTypes := []store.PlanCheckRunType{store.PlanCheckDatabaseStatementSummaryReport}@@ -103,7 +145,7 @@ func getMigrationInfo(ctx context.Context, stores *store.Store, profile *config.Status: &status,})if err != nil {- return nil, errors.Wrap(err, "failed to list plan check runs")+ return nil, nil, errors.Wrap(err, "failed to list plan check runs")}sort.Slice(runs, func(i, j int) bool {return runs[i].UID > runs[j].UID@@ -167,9 +209,9 @@ func getMigrationInfo(ctx context.Context, stores *store.Store, profile *config.statement = strings.TrimSpace(statement)// Only baseline and SDL migration can have empty sql statement, which indicates empty database.if mi.Type != db.Baseline && mi.Type != db.MigrateSDL && statement == "" {- return nil, errors.Errorf("empty statement")+ return nil, nil, errors.Errorf("empty statement")}- return mi, nil+ return mi, mc, nil}func getCreateTaskRunLog(ctx context.Context, taskRunUID int, s *store.Store, profile *config.Profile) func(t time.Time, e *storepb.TaskRunLog) error {@@ -185,20 +227,12 @@ func doMigration(dbFactory *dbfactory.DBFactory,stateCfg *state.State,profile *config.Profile,- task *store.TaskMessage,- taskRunUID int,statement string,- sheetID *int,mi *db.MigrationInfo,+ mc *migrateContext,) (string, string, error) {- instance, err := stores.GetInstanceV2(ctx, &store.FindInstanceMessage{UID: &task.InstanceID})- if err != nil {- return "", "", err- }- database, err := stores.GetDatabaseV2(ctx, &store.FindDatabaseMessage{UID: task.DatabaseID})- if err != nil {- return "", "", err- }+ instance := mc.instance+ database := mc.databasedriver, err := dbFactory.GetAdminDatabaseDriver(ctx, instance, database, db.ConnectionContext{})if err != nil {@@ -219,14 +253,14 @@ func doMigration(opts := db.ExecuteOptions{}opts.SetConnectionID = func(id string) {- stateCfg.TaskRunConnectionID.Store(taskRunUID, id)+ stateCfg.TaskRunConnectionID.Store(mc.taskRunUID, id)}opts.DeleteConnectionID = func() {- stateCfg.TaskRunConnectionID.Delete(taskRunUID)+ stateCfg.TaskRunConnectionID.Delete(mc.taskRunUID)}if stateCfg != nil {- switch task.Type {+ switch mc.task.Type {case api.TaskDatabaseSchemaUpdate, api.TaskDatabaseDataUpdate:switch instance.Engine {case storepb.Engine_MYSQL, storepb.Engine_TIDB, storepb.Engine_OCEANBASE,@@ -234,14 +268,14 @@ func doMigration(storepb.Engine_REDSHIFT, storepb.Engine_RISINGWAVE, storepb.Engine_ORACLE,storepb.Engine_DM, storepb.Engine_OCEANBASE_ORACLE, storepb.Engine_MSSQL,storepb.Engine_DYNAMODB:- opts.CreateTaskRunLog = getCreateTaskRunLog(ctx, taskRunUID, stores, profile)+ opts.CreateTaskRunLog = getCreateTaskRunLog(ctx, mc.taskRunUID, stores, profile)default:// do nothing}}}- migrationID, schema, err := executeMigrationDefault(ctx, driverCtx, stores, stateCfg, taskRunUID, driver, mi, statement, sheetID, opts)+ migrationID, schema, err := executeMigrationDefault(ctx, driverCtx, stores, stateCfg, driver, mi, mc, statement, opts)if err != nil {return "", "", err}@@ -249,15 +283,9 @@ func doMigration(return migrationID, schema, nil}-func postMigration(ctx context.Context, stores *store.Store, task *store.TaskMessage, mi *db.MigrationInfo, migrationID string, sheetID *int) (bool, *storepb.TaskRunResult, error) {- instance, err := stores.GetInstanceV2(ctx, &store.FindInstanceMessage{UID: &task.InstanceID})- if err != nil {- return true, nil, err- }- database, err := stores.GetDatabaseV2(ctx, &store.FindDatabaseMessage{UID: task.DatabaseID})- if err != nil {- return true, nil, err- }+func postMigration(ctx context.Context, stores *store.Store, mi *db.MigrationInfo, mc *migrateContext, migrationID string, sheetID *int) (bool, *storepb.TaskRunResult, error) {+ instance := mc.instance+ database := mc.databaseif mi.Type == db.Migrate || mi.Type == db.MigrateSDL {if _, err := stores.UpdateDatabase(ctx, &store.UpdateDatabaseMessage{@@ -275,23 +303,23 @@ func postMigration(ctx context.Context, stores *store.Store, task *store.TaskMes)// Set schema config.- if sheetID != nil && task.DatabaseID != nil {+ if sheetID != nil && mc.task.DatabaseID != nil {sheet, err := stores.GetSheet(ctx, &store.FindSheetMessage{UID: sheetID,})if err != nil {slog.Error("Failed to get sheet from store", slog.Int("sheetID", *sheetID), log.BBError(err))} else if sheet.Payload != nil && (sheet.Payload.DatabaseConfig != nil || sheet.Payload.BaselineDatabaseConfig != nil) {- databaseSchema, err := stores.GetDBSchema(ctx, *task.DatabaseID)+ databaseSchema, err := stores.GetDBSchema(ctx, *mc.task.DatabaseID)if err != nil {- slog.Error("Failed to get database config from store", slog.Int("sheetID", *sheetID), slog.Int("databaseUID", *task.DatabaseID), log.BBError(err))+ slog.Error("Failed to get database config from store", slog.Int("sheetID", *sheetID), slog.Int("databaseUID", *mc.task.DatabaseID), log.BBError(err))} else {updatedDatabaseConfig := utils.MergeDatabaseConfig(sheet.Payload.DatabaseConfig, sheet.Payload.BaselineDatabaseConfig, databaseSchema.GetConfig())- err = stores.UpdateDBSchema(ctx, *task.DatabaseID, &store.UpdateDBSchemaMessage{+ err = stores.UpdateDBSchema(ctx, *mc.task.DatabaseID, &store.UpdateDBSchemaMessage{Config: updatedDatabaseConfig,}, api.SystemBotID)if err != nil {- slog.Error("Failed to update database config", slog.Int("sheetID", *sheetID), slog.Int("databaseUID", *task.DatabaseID), log.BBError(err))+ slog.Error("Failed to update database config", slog.Int("sheetID", *sheetID), slog.Int("databaseUID", *mc.task.DatabaseID), log.BBError(err))}}}@@ -299,7 +327,7 @@ func postMigration(ctx context.Context, stores *store.Store, task *store.TaskMes// Remove schema drift anomalies.if err := stores.ArchiveAnomalyV2(ctx, &store.ArchiveAnomalyMessage{- DatabaseUID: task.DatabaseID,+ DatabaseUID: mc.task.DatabaseID,Type: api.AnomalyDatabaseSchemaDrift,}); err != nil && common.ErrorCode(err) != common.NotFound {slog.Error("Failed to archive anomaly",@@ -329,33 +357,33 @@ func postMigration(ctx context.Context, stores *store.Store, task *store.TaskMes}func runMigration(ctx context.Context, driverCtx context.Context, store *store.Store, dbFactory *dbfactory.DBFactory, stateCfg *state.State, profile *config.Profile, task *store.TaskMessage, taskRunUID int, migrationType db.MigrationType, statement string, schemaVersion model.Version, sheetID *int) (terminated bool, result *storepb.TaskRunResult, err error) {- mi, err := getMigrationInfo(ctx, store, profile, task, migrationType, statement, schemaVersion, sheetID)+ mi, mc, err := getMigrationInfo(ctx, store, profile, task, migrationType, statement, schemaVersion, sheetID, taskRunUID)if err != nil {return true, nil, err}- migrationID, _, err := doMigration(ctx, driverCtx, store, dbFactory, stateCfg, profile, task, taskRunUID, statement, sheetID, mi)+ migrationID, _, err := doMigration(ctx, driverCtx, store, dbFactory, stateCfg, profile, statement, mi, mc)if err != nil {return true, nil, err}- return postMigration(ctx, store, task, mi, migrationID, sheetID)+ return postMigration(ctx, store, mi, mc, 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) {+func executeMigrationDefault(ctx context.Context, driverCtx context.Context, store *store.Store, _ *state.State, driver db.Driver, mi *db.MigrationInfo, mc *migrateContext, statement string, 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)+ return executeMigrationWithFunc(ctx, driverCtx, store, driver, mi, mc, statement, 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) {+func executeMigrationWithFunc(ctx context.Context, driverCtx context.Context, s *store.Store, driver db.Driver, mi *db.MigrationInfo, mc *migrateContext, statement string, 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() {+ if mi.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.@@ -367,7 +395,12 @@ func executeMigrationWithFunc(ctx context.Context, driverCtx context.Context, sopts.LogSchemaDumpEnd("")}- insertedID, err := beginMigration(ctx, s, m, prevSchemaBuf.String(), statement, sheetID)+ var sheetID *int+ if mc.sheet != nil {+ sheetID = &mc.sheet.UID+ }++ insertedID, err := beginMigration(ctx, s, mi, prevSchemaBuf.String(), statement, sheetID)if err != nil {return "", "", errors.Wrapf(err, "failed to begin migration")}@@ -388,21 +421,21 @@ func executeMigrationWithFunc(ctx context.Context, driverCtx context.Context, s// Baseline migration type could has non-empty sql but will not execute.// https://github.com/bytebase/bytebase/issues/394doMigrate := true- if statement == "" || m.Type == db.Baseline {+ if statement == "" || mi.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 {+ if mi.DatabaseID != nil {database, err := s.GetDatabaseV2(ctx, &store.FindDatabaseMessage{- UID: m.DatabaseID,+ UID: mi.DatabaseID,})if err != nil {return "", "", err}if database == nil {- return "", "", errors.Errorf("database %d not found", *m.DatabaseID)+ return "", "", errors.Errorf("database %d not found", *mi.DatabaseID)}materials := utils.GetSecretMapFromDatabaseMessage(database)// To avoid leak the rendered statement, the error message should use the original statement and not the rendered statement.@@ -416,7 +449,7 @@ func executeMigrationWithFunc(ctx context.Context, driverCtx context.Context, s// Phase 4 - Dump the schema after migrationvar afterSchemaBuf bytes.Buffer- if m.Type.NeedDump() {+ if mi.Type.NeedDump() {opts.LogSchemaDumpStart()if err := driver.Dump(ctx, &afterSchemaBuf); err != nil {// We will ignore the dump error if the database is dropped.diff --git a/backend/runner/taskrun/schema_update_ghost_cutover_executor.go b/backend/runner/taskrun/schema_update_ghost_cutover_executor.goindex 5973febf40..ae03ee3141 100644--- a/backend/runner/taskrun/schema_update_ghost_cutover_executor.go+++ b/backend/runner/taskrun/schema_update_ghost_cutover_executor.go@@ -132,7 +132,7 @@ func cutover(ctx context.Context, taskContext context.Context, stores *store.Storeturn true, nil, err}- mi, err := getMigrationInfo(ctx, stores, profile, task, db.Migrate, statement, schemaVersion, &sheetID)+ mi, mc, err := getMigrationInfo(ctx, stores, profile, task, db.Migrate, statement, schemaVersion, &sheetID, taskRunUID)if err != nil {return true, nil, err}@@ -151,12 +151,12 @@ func cutover(ctx context.Context, taskContext context.Context, stores *store.Storeturn true, nil, err}defer driver.Close(ctx)- migrationID, _, err := executeMigrationWithFunc(ctx, ctx, stores, taskRunUID, driver, mi, statement, &sheetID, execFunc, db.ExecuteOptions{})+ migrationID, _, err := executeMigrationWithFunc(ctx, ctx, stores, driver, mi, mc, statement, execFunc, db.ExecuteOptions{})if err != nil {return true, nil, err}- return postMigration(ctx, stores, task, mi, migrationID, &sheetID)+ return postMigration(ctx, stores, mi, mc, migrationID, &sheetID)}func waitForCutover(ctx context.Context, taskContext context.Context, migrationContext *base.MigrationContext) bool {