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: migrate driverutil to instace change history (#5081)
p0nyaaf4c6f667d2
diff --git a/backend/legacyapi/instance.go b/backend/legacyapi/instance.goindex 74f20439bc..2fdeea225a 100644--- a/backend/legacyapi/instance.go+++ b/backend/legacyapi/instance.go@@ -116,6 +116,7 @@ type InstanceMigration struct {// MigrationHistory is stored in the instance instead of our own data file, so the field// format is a bit different from the standard format.+// TODO(p0ny): migrate to instance change history.type MigrationHistory struct {ID string `jsonapi:"primary,migrationHistory"`diff --git a/backend/plugin/db/clickhouse/migrate.go b/backend/plugin/db/clickhouse/migrate.goindex d8ea1bf3f9..9e516e6f5a 100644--- a/backend/plugin/db/clickhouse/migrate.go+++ b/backend/plugin/db/clickhouse/migrate.go@@ -217,7 +217,8 @@ func (Driver) UpdateHistoryAsFailed(ctx context.Context, tx *sql.Tx, migrationDu// ExecuteMigration will execute the migration.func (driver *Driver) ExecuteMigration(ctx context.Context, m *db.MigrationInfo, statement string) (string, string, error) {- return util.ExecuteMigration(ctx, driver, m, statement, db.BytebaseDatabase)+ _, err := driver.Execute(ctx, statement, m.CreateDatabase)+ return "", "", err}// FindMigrationHistoryList finds the migration history.diff --git a/backend/plugin/db/driver.go b/backend/plugin/db/driver.goindex 1dd016b5ab..3229d5854d 100644--- a/backend/plugin/db/driver.go+++ b/backend/plugin/db/driver.go@@ -147,21 +147,23 @@ type MigrationInfoPayload struct {// MigrationInfo is the API message for migration info.type MigrationInfo struct {+ // fields for instance change history+ InstanceID *int+ DatabaseID *int+ IssueIDInt *int+ CreatorID int+ReleaseVersion stringVersion stringNamespace string- InstanceID *intDatabase string- DatabaseID *intEnvironment stringSource MigrationSourceType MigrationTypeStatus MigrationStatusDescription stringCreator string- CreatorID intIssueID string- IssueIDInt *int// Payload contains JSON-encoded string of VCS push event if the migration is triggered by a VCS push event.Payload stringCreateDatabase bool@@ -319,6 +321,7 @@ func ParseSchemaFileInfo(baseDirectory, schemaPathTemplate, file string) (*Migra}// MigrationHistory is the API message for migration history.+// TODO(p0ny): migrate to instance change history.type MigrationHistory struct {ID string@@ -466,9 +469,8 @@ type Driver interface {NeedsSetupMigration(ctx context.Context) (bool, error)// Create or upgrade migration related tablesSetupMigrationIfNeeded(ctx context.Context) error- // Execute migration will apply the statement and record the migration history, the schema after migration on success.+ // Execute migration will apply the statement.// The migration type is determined by m.Type. Note, it can also perform data migration (DML) in addition to schema migration (DDL).- // It returns the migration history id and the schema after migration on success.ExecuteMigration(ctx context.Context, m *MigrationInfo, statement string) (string, string, error)// Find the migration history list and return most recent item first.FindMigrationHistoryList(ctx context.Context, find *MigrationHistoryFind) ([]*MigrationHistory, error)diff --git a/backend/plugin/db/mongodb/migrate.go b/backend/plugin/db/mongodb/migrate.goindex 059cdd0d2f..74a697555f 100644--- a/backend/plugin/db/mongodb/migrate.go+++ b/backend/plugin/db/mongodb/migrate.go@@ -117,7 +117,8 @@ func (driver *Driver) SetupMigrationIfNeeded(ctx context.Context) error {// ExecuteMigration executes a migration.func (driver *Driver) ExecuteMigration(ctx context.Context, m *db.MigrationInfo, statement string) (string, string, error) {- return util.ExecuteMigration(ctx, driver, m, statement, migrationHistoryDefaultDatabase)+ _, err := driver.Execute(ctx, statement, m.CreateDatabase)+ return "", "", err}// FindMigrationHistoryList finds the migration history list.diff --git a/backend/plugin/db/mysql/migrate.go b/backend/plugin/db/mysql/migrate.goindex 1e95d5bd27..3875275019 100644--- a/backend/plugin/db/mysql/migrate.go+++ b/backend/plugin/db/mysql/migrate.go@@ -199,7 +199,8 @@ func (Driver) UpdateHistoryAsFailed(ctx context.Context, tx *sql.Tx, migrationDu// ExecuteMigration will execute the migration.func (driver *Driver) ExecuteMigration(ctx context.Context, m *db.MigrationInfo, statement string) (string, string, error) {- return util.ExecuteMigration(ctx, driver, m, statement, db.BytebaseDatabase)+ _, err := driver.Execute(ctx, statement, m.CreateDatabase)+ return "", "", err}// FindMigrationHistoryList finds the migration history.diff --git a/backend/plugin/db/pg/migrate.go b/backend/plugin/db/pg/migrate.goindex bc777bdd05..d13c231b08 100644--- a/backend/plugin/db/pg/migrate.go+++ b/backend/plugin/db/pg/migrate.go@@ -243,6 +243,12 @@ func (*Driver) UpdateHistoryAsFailed(ctx context.Context, tx *sql.Tx, migrationD// ExecuteMigration will execute the migration.func (driver *Driver) ExecuteMigration(ctx context.Context, m *db.MigrationInfo, statement string) (string, string, error) {+ _, err := driver.Execute(ctx, statement, m.CreateDatabase)+ return "", "", err+}++// ExecuteMigrationUsingMigrationHistory will execute the migration and stores the record to migration history.+func (driver *Driver) ExecuteMigrationUsingMigrationHistory(ctx context.Context, m *db.MigrationInfo, statement string) (string, string, error) {if driver.strictUseDb() {return util.ExecuteMigration(ctx, driver, m, statement, driver.strictDatabase)}diff --git a/backend/plugin/db/snowflake/migrate.go b/backend/plugin/db/snowflake/migrate.goindex fdaf7f6055..18d668717c 100644--- a/backend/plugin/db/snowflake/migrate.go+++ b/backend/plugin/db/snowflake/migrate.go@@ -227,7 +227,8 @@ func (driver *Driver) ExecuteMigration(ctx context.Context, m *db.MigrationInfo,if err := driver.useRole(ctx, sysAdminRole); err != nil {return "", "", err}- return util.ExecuteMigration(ctx, driver, m, statement, bytebaseDatabase)+ _, err := driver.Execute(ctx, statement, m.CreateDatabase)+ return "", "", err}// FindMigrationHistoryList finds the migration history.diff --git a/backend/plugin/db/sqlite/migrate.go b/backend/plugin/db/sqlite/migrate.goindex 9307ca1371..436816a4e0 100644--- a/backend/plugin/db/sqlite/migrate.go+++ b/backend/plugin/db/sqlite/migrate.go@@ -220,7 +220,8 @@ func (Driver) UpdateHistoryAsFailed(ctx context.Context, tx *sql.Tx, migrationDu// ExecuteMigration will execute the migration.func (driver *Driver) ExecuteMigration(ctx context.Context, m *db.MigrationInfo, statement string) (string, string, error) {- return util.ExecuteMigration(ctx, driver, m, statement, bytebaseDatabase)+ _, err := driver.Execute(ctx, statement, m.CreateDatabase)+ return "", "", err}// FindMigrationHistoryList finds the migration history.diff --git a/backend/runner/anomaly/scanner.go b/backend/runner/anomaly/scanner.goindex 6ec0cc6233..29e81dd15c 100644--- a/backend/runner/anomaly/scanner.go+++ b/backend/runner/anomaly/scanner.go@@ -189,40 +189,6 @@ func (s *Scanner) checkInstanceAnomaly(ctx context.Context, instance *store.Instzap.String("type", string(api.AnomalyInstanceConnection)),zap.Error(err))}-- // Check migration schema- {- setup, err := driver.NeedsSetupMigration(ctx)- if err != nil {- log.Error("Failed to check migration schema",- zap.String("instance", instance.ResourceID),- zap.String("type", string(api.AnomalyInstanceMigrationSchema)),- zap.Error(err))- } else {- if setup {- if _, err = s.store.UpsertActiveAnomalyV2(ctx, api.SystemBotID, &store.AnomalyMessage{- InstanceUID: instance.UID,- Type: api.AnomalyInstanceMigrationSchema,- }); err != nil {- log.Error("Failed to create anomaly",- zap.String("instance", instance.ResourceID),- zap.String("type", string(api.AnomalyInstanceMigrationSchema)),- zap.Error(err))- }- } else {- err := s.store.ArchiveAnomalyV2(ctx, &store.ArchiveAnomalyMessage{- InstanceUID: &instance.UID,- Type: api.AnomalyInstanceMigrationSchema,- })- if err != nil && common.ErrorCode(err) != common.NotFound {- log.Error("Failed to close anomaly",- zap.String("instance", instance.ResourceID),- zap.String("type", string(api.AnomalyInstanceMigrationSchema)),- zap.Error(err))- }- }- }- }}func (s *Scanner) checkDatabaseAnomaly(ctx context.Context, instance *store.InstanceMessage, database *store.DatabaseMessage) {@@ -272,22 +238,10 @@ func (s *Scanner) checkDatabaseAnomaly(ctx context.Context, instance *store.Inst// Check schema driftif s.licenseService.IsFeatureEnabled(api.FeatureSchemaDrift) {// Redis and MongoDB are schemaless.+ // TODO(zp): remove oracle.if instance.Engine == db.Redis || instance.Engine == db.MongoDB || instance.Engine == db.Oracle {return}- setup, err := driver.NeedsSetupMigration(ctx)- if err != nil {- log.Debug("Failed to check anomaly",- zap.String("instance", instance.ResourceID),- zap.String("database", database.DatabaseName),- zap.String("type", string(api.AnomalyDatabaseSchemaDrift)),- zap.Error(err))- return- }- // Skip drift check if migration schema is not ready (we have instance anomaly to cover that)- if setup {- return- }var schemaBuf bytes.Bufferif _, err := driver.Dump(ctx, database.DatabaseName, &schemaBuf, true /*schemaOnly*/); err != nil {if common.ErrorCode(err) == common.NotFound {@@ -306,9 +260,11 @@ func (s *Scanner) checkDatabaseAnomaly(ctx context.Context, instance *store.Instreturn}limit := 1- list, err := driver.FindMigrationHistoryList(ctx, &db.MigrationHistoryFind{- Database: &database.DatabaseName,- Limit: &limit,+ list, err := s.store.FindInstanceChangeHistoryList(ctx, &db.MigrationHistoryFind{+ InstanceID: &instance.UID,+ DatabaseID: &database.UID,+ Database: &database.DatabaseName,+ Limit: &limit,})if err != nil {log.Error("Failed to check anomaly",diff --git a/backend/runner/backuprun/runner.go b/backend/runner/backuprun/runner.goindex af1ac0da14..474e9f61e6 100644--- a/backend/runner/backuprun/runner.go+++ b/backend/runner/backuprun/runner.go@@ -423,7 +423,7 @@ func (r *Runner) ScheduleBackupTask(ctx context.Context, database *store.Databas}defer driver.Close(ctx)- migrationHistoryVersion, err := utils.GetLatestSchemaVersion(ctx, r.store, driver, instance.UID, database.UID, database.DatabaseName)+ migrationHistoryVersion, err := utils.GetLatestSchemaVersion(ctx, r.store, instance.UID, database.UID, database.DatabaseName)if err != nil {return nil, errors.Wrapf(err, "failed to get migration history for database %q", database.DatabaseName)}diff --git a/backend/runner/rollbackrun/runner.go b/backend/runner/rollbackrun/runner.goindex bdc2f9a732..53efc661d0 100644--- a/backend/runner/rollbackrun/runner.go+++ b/backend/runner/rollbackrun/runner.go@@ -159,7 +159,7 @@ func (r *Runner) generateRollbackSQLImpl(ctx context.Context, task *store.TaskMereturn "", errors.WithMessage(err, "failed to get admin database driver")}defer driver.Close(ctx)- list, err := driver.FindMigrationHistoryList(ctx, &db.MigrationHistoryFind{ID: &payload.MigrationID})+ list, err := r.store.FindInstanceChangeHistoryList(ctx, &db.MigrationHistoryFind{InstanceID: &instance.UID, ID: &payload.MigrationID})if err != nil {return "", errors.WithMessagef(err, "failed to find migration history with ID %s", payload.MigrationID)}diff --git a/backend/runner/schemasync/syncer.go b/backend/runner/schemasync/syncer.goindex 29ffe006c0..63a8c5f1a5 100644--- a/backend/runner/schemasync/syncer.go+++ b/backend/runner/schemasync/syncer.go@@ -274,7 +274,7 @@ func (s *Syncer) SyncDatabaseSchema(ctx context.Context, database *store.Databasif force {// When there are too many databases, this might have performance issue and will// cause frontend timeout since we set a 30s limit (INSTANCE_OPERATION_TIMEOUT).- schemaVersion, err := utils.GetLatestSchemaVersion(ctx, s.store, driver, instance.UID, database.UID, databaseMetadata.Name)+ schemaVersion, err := utils.GetLatestSchemaVersion(ctx, s.store, instance.UID, database.UID, databaseMetadata.Name)if err != nil {return err}diff --git a/backend/runner/taskcheck/migration_schema_executor.go b/backend/runner/taskcheck/migration_schema_executor.goindex dfae898a85..e3b563681a 100644--- a/backend/runner/taskcheck/migration_schema_executor.go+++ b/backend/runner/taskcheck/migration_schema_executor.go@@ -26,6 +26,7 @@ type MigrationSchemaExecutor struct {// Run will run the task check migration schema executor once.func (e *MigrationSchemaExecutor) Run(ctx context.Context, _ *store.TaskCheckRunMessage, task *store.TaskMessage) (result []api.TaskCheckResult, err error) {+ // TODO(p0ny): remove this task check because we no longer create migration history table on user instances.instance, err := e.store.GetInstanceV2(ctx, &store.FindInstanceMessage{UID: &task.InstanceID})if err != nil {return []api.TaskCheckResult{}, err@@ -37,23 +38,6 @@ func (e *MigrationSchemaExecutor) Run(ctx context.Context, _ *store.TaskCheckRun}defer driver.Close(ctx)- setup, err := driver.NeedsSetupMigration(ctx)- if err != nil {- return []api.TaskCheckResult{}, err- }-- if setup {- return []api.TaskCheckResult{- {- Status: api.TaskCheckStatusError,- Namespace: api.BBNamespace,- Code: common.MigrationSchemaMissing.Int(),- Title: "Error",- Content: fmt.Sprintf("Missing migration schema for instance %q", instance.Title),- },- }, nil- }-return []api.TaskCheckResult{{Status: api.TaskCheckStatusSuccess,diff --git a/backend/runner/taskrun/database_create_executor.go b/backend/runner/taskrun/database_create_executor.goindex f017c7e53e..040d123741 100644--- a/backend/runner/taskrun/database_create_executor.go+++ b/backend/runner/taskrun/database_create_executor.go@@ -130,6 +130,8 @@ func (exec *DatabaseCreateExecutor) RunOnce(ctx context.Context, task *store.Tas// Create a migrate migration history upon creating the database.// TODO(d): support semantic versioning.mi := &db.MigrationInfo{+ InstanceID: &task.InstanceID,+ CreatorID: task.CreatorID,ReleaseVersion: exec.profile.Version,Version: schemaVersion,Namespace: payload.DatabaseName,@@ -169,19 +171,11 @@ func (exec *DatabaseCreateExecutor) RunOnce(ctx context.Context, task *store.Tas)} else {mi.IssueID = strconv.Itoa(issue.UID)+ mi.IssueIDInt = &issue.UID}- // TODO(p0ny): migrate to instance change history- var migrationID string- if instance.Engine == db.Spanner {- migrationID, _, err = utils.ExecuteMigration(ctx, exec.store, driver, mi, statement)- } else {- migrationID, _, err = driver.ExecuteMigration(ctx, mi, statement)- }- if err != nil {- return true, nil, err- }-+ // Upsert first because we need database id in instance change history.+ // The sync status is NOT_FOUND, which will be updated to OK if succeeds.labels := make(map[string]string)if payload.Labels != "" {var databaseLabels []*api.DatabaseLabel@@ -197,7 +191,7 @@ func (exec *DatabaseCreateExecutor) RunOnce(ctx context.Context, task *store.TasEnvironmentID: environment.ResourceID,InstanceID: instance.ResourceID,DatabaseName: payload.DatabaseName,- SyncState: api.OK,+ SyncState: api.NotFound,SuccessfulSyncTimeTs: time.Now().Unix(),SchemaVersion: schemaVersion,Labels: labels,@@ -206,6 +200,23 @@ func (exec *DatabaseCreateExecutor) RunOnce(ctx context.Context, task *store.Tasreturn true, nil, err}+ mi.DatabaseID = &database.UID++ migrationID, _, err := utils.ExecuteMigration(ctx, exec.store, driver, mi, statement)+ if err != nil {+ return true, nil, err+ }++ syncStatus := api.OK+ if _, err := exec.store.UpdateDatabase(ctx, &store.UpdateDatabaseMessage{+ EnvironmentID: environment.ResourceID,+ InstanceID: instance.ResourceID,+ DatabaseName: payload.DatabaseName,+ SyncState: &syncStatus,+ }, api.SystemBotID); err != nil {+ return true, nil, err+ }+// After the task related database entry created successfully,// we need to update task's database_id and statement with the newly created database immediately.// Here is the main reason:@@ -301,7 +312,7 @@ func (*DatabaseCreateExecutor) getSchemaFromPeerTenantDatabase(ctx context.Contereturn "", "", err}defer driver.Close(ctx)- schemaVersion, err := utils.GetLatestSchemaVersion(ctx, stores, driver, instance.UID, similarDB.UID, similarDB.DatabaseName)+ schemaVersion, err := utils.GetLatestSchemaVersion(ctx, stores, similarDBInstance.UID, similarDB.UID, similarDB.DatabaseName)if err != nil {return "", "", errors.Wrapf(err, "failed to get migration history for database %q", similarDB.DatabaseName)}diff --git a/backend/runner/taskrun/executor.go b/backend/runner/taskrun/executor.goindex 7fce45a4d2..3439febb7c 100644--- a/backend/runner/taskrun/executor.go+++ b/backend/runner/taskrun/executor.go@@ -79,13 +79,15 @@ func preMigration(ctx context.Context, stores *store.Store, profile config.Profimi := &db.MigrationInfo{InstanceID: &instance.UID,DatabaseID: &database.UID,- CreatorID: api.SystemBotID,+ CreatorID: task.CreatorID,ReleaseVersion: profile.Version,Type: migrationType,// TODO(d): support semantic versioning.Version: schemaVersion,Description: task.Name,Environment: environment.ResourceID,+ Database: database.DatabaseName,+ Namespace: database.DatabaseName,}issue, err := stores.GetIssueV2(ctx, &store.FindIssueMessage{PipelineID: &task.PipelineID})@@ -127,9 +129,6 @@ func preMigration(ctx context.Context, stores *store.Store, profile config.Profimi.Payload = string(bytes)}- mi.Database = database.DatabaseName- mi.Namespace = database.DatabaseName-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 == "" {@@ -171,14 +170,6 @@ func executeMigration(ctx context.Context, stores *store.Store, dbFactory *dbfaczap.String("statement", statementRecord),)- setup, err := driver.NeedsSetupMigration(ctx)- if err != nil {- return "", "", errors.Wrapf(err, "failed to check migration setup for instance %q", instance.ResourceID)- }- if setup {- return "", "", common.Errorf(common.MigrationSchemaMissing, "missing migration schema for instance %q", instance.ResourceID)- }-if task.Type == api.TaskDatabaseDataUpdate && instance.Engine == db.MySQL {updatedTask, err := setThreadIDAndStartBinlogCoordinate(ctx, driver, task, stores)if err != nil {@@ -187,17 +178,9 @@ func executeMigration(ctx context.Context, stores *store.Store, dbFactory *dbfactask = updatedTask}- // TODO(p0ny): migrate to instance change history- if instance.Engine == db.Redis || instance.Engine == db.Oracle || instance.Engine == db.Spanner {- migrationID, schema, err = utils.ExecuteMigration(ctx, stores, driver, mi, statement)- if err != nil {- return "", "", err- }- } else {- migrationID, schema, err = driver.ExecuteMigration(ctx, mi, statement)- if err != nil {- return "", "", err- }+ migrationID, schema, err = utils.ExecuteMigration(ctx, stores, driver, mi, statement)+ if err != nil {+ return "", "", err}if task.Type == api.TaskDatabaseDataUpdate && instance.Engine == db.MySQL {diff --git a/backend/runner/taskrun/pitr_cutover_executor.go b/backend/runner/taskrun/pitr_cutover_executor.goindex 579dad1dd0..7c67ebd1aa 100644--- a/backend/runner/taskrun/pitr_cutover_executor.go+++ b/backend/runner/taskrun/pitr_cutover_executor.go@@ -24,6 +24,7 @@ import ("github.com/bytebase/bytebase/backend/runner/backuprun""github.com/bytebase/bytebase/backend/runner/schemasync""github.com/bytebase/bytebase/backend/store"+ "github.com/bytebase/bytebase/backend/utils")// NewPITRCutoverExecutor creates a PITR cutover task executor.@@ -138,21 +139,23 @@ func (exec *PITRCutoverExecutor) pitrCutover(ctx context.Context, dbFactory *dbf// database's migration history, and append a new BRANCH migration.log.Debug("Appending new migration history record")m := &db.MigrationInfo{+ InstanceID: &task.InstanceID,ReleaseVersion: profile.Version,Version: common.DefaultMigrationVersion(),Namespace: database.DatabaseName,Database: database.DatabaseName,+ DatabaseID: &database.UID,Environment: environment.ResourceID,Source: db.MigrationSource(project.Workflow),Type: db.Branch,Status: db.Done,Description: fmt.Sprintf("PITR: restoring database %s", database.DatabaseName),Creator: creator.Name,+ CreatorID: creator.ID,IssueID: strconv.Itoa(issue.UID),}- // TODO(p0ny): migrate to instance change history- if _, _, err := driver.ExecuteMigration(ctx, m, "/* pitr cutover */"); err != nil {+ if _, _, err := utils.ExecuteMigration(ctx, exec.store, driver, m, "/* pitr cutover */"); err != nil {log.Error("Failed to add migration history record", zap.Error(err))return true, nil, errors.Wrap(err, "failed to add migration history record")}diff --git a/backend/runner/taskrun/pitr_restore_executor.go b/backend/runner/taskrun/pitr_restore_executor.goindex 248c79c297..81775ba794 100644--- a/backend/runner/taskrun/pitr_restore_executor.go+++ b/backend/runner/taskrun/pitr_restore_executor.go@@ -27,6 +27,7 @@ import ("github.com/bytebase/bytebase/backend/runner/backuprun""github.com/bytebase/bytebase/backend/runner/schemasync""github.com/bytebase/bytebase/backend/store"+ "github.com/bytebase/bytebase/backend/utils")// NewPITRRestoreExecutor creates a PITR restore task executor.@@ -532,15 +533,18 @@ func createBranchMigrationHistory(ctx context.Context, stores *store.Store, dbFa// TODO(d): support semantic versioning.m := &db.MigrationInfo{+ InstanceID: &task.InstanceID,ReleaseVersion: profile.Version,Version: common.DefaultMigrationVersion(),Namespace: targetDatabase.DatabaseName,Database: targetDatabase.DatabaseName,+ DatabaseID: &targetDatabase.UID,Environment: targetInstanceEnvironment.ResourceID,Source: db.MigrationSource(targetDatabaseProject.Workflow),Type: db.Branch,Description: description,Creator: creator.Name,+ CreatorID: creator.ID,IssueID: issueID,}targetDriver, err := dbFactory.GetAdminDatabaseDriver(ctx, targetInstance, targetDatabase.DatabaseName)@@ -548,8 +552,7 @@ func createBranchMigrationHistory(ctx context.Context, stores *store.Store, dbFareturn "", "", err}defer targetDriver.Close(ctx)- // TODO(p0ny): migrate to instance change history- migrationID, _, err := targetDriver.ExecuteMigration(ctx, m, "")+ migrationID, _, err := utils.ExecuteMigration(ctx, stores, targetDriver, m, "")if err != nil {return "", "", errors.Wrap(err, "failed to create migration history")}diff --git a/backend/runner/taskrun/schema_update_ghost_cutover_executor.go b/backend/runner/taskrun/schema_update_ghost_cutover_executor.goindex 15912ea489..d1c80d3a04 100644--- a/backend/runner/taskrun/schema_update_ghost_cutover_executor.go+++ b/backend/runner/taskrun/schema_update_ghost_cutover_executor.go@@ -125,13 +125,6 @@ func cutover(ctx context.Context, stores *store.Store, dbFactory *dbfactory.DBFareturn "", "", err}defer driver.Close(ctx)- needsSetup, err := driver.NeedsSetupMigration(ctx)- if err != nil {- return "", "", errors.Wrapf(err, "failed to check migration setup for instance %q", instance.ResourceID)- }- if needsSetup {- return "", "", common.Errorf(common.MigrationSchemaMissing, "missing migration schema for instance %q", instance.ResourceID)- }executor := driver.(util.MigrationExecutor)@@ -147,7 +140,7 @@ func cutover(ctx context.Context, stores *store.Store, dbFactory *dbfactory.DBFareturn "", "", errors.Errorf("cutover poller cancelled")}- insertedID, err := util.BeginMigration(ctx, executor, mi, prevSchemaBuf.String(), statement, db.BytebaseDatabase)+ insertedID, err := utils.BeginMigration(ctx, stores, mi, prevSchemaBuf.String(), statement)if err != nil {if common.ErrorCode(err) == common.MigrationAlreadyApplied {return insertedID, prevSchemaBuf.String(), nil@@ -157,7 +150,7 @@ func cutover(ctx context.Context, stores *store.Store, dbFactory *dbfactory.DBFastartedNs := time.Now().UnixNano()defer func() {- if err := util.EndMigration(ctx, executor, startedNs, insertedID, updatedSchema, db.BytebaseDatabase, resErr == nil /*isDone*/); err != nil {+ if err := utils.EndMigration(ctx, stores, startedNs, insertedID, updatedSchema, db.BytebaseDatabase, resErr == nil /*isDone*/); err != nil {log.Error("failed to update migration history record",zap.Error(err),zap.String("migration_id", migrationHistoryID),diff --git a/backend/server/instance.go b/backend/server/instance.goindex 61e0c6c0ce..9d43944feb 100644--- a/backend/server/instance.go+++ b/backend/server/instance.go@@ -91,18 +91,10 @@ func (s *Server) registerInstanceRoutes(g *echo.Group) {if err != nil {return err}- // Try creating the "bytebase" db in the added instance if needed.- // Since we allow user to add new instance upfront even providing the incorrect username/password,- // thus it's OK if it fails. Frontend will surface relevant info suggesting the "bytebase" db hasn't created yet.+driver, err := s.dbFactory.GetAdminDatabaseDriver(ctx, instance, "" /* databaseName */)if err == nil {defer driver.Close(ctx)- if err := driver.SetupMigrationIfNeeded(ctx); err != nil {- log.Warn("Failed to setup migration schema on instance creation",- zap.String("instance", instance.ResourceID),- zap.String("engine", string(instance.Engine)),- zap.Error(err))- }if _, err := s.SchemaSyncer.SyncInstance(ctx, instance); err != nil {log.Warn("Failed to sync instance",zap.String("instance", instance.ResourceID),@@ -288,6 +280,7 @@ func (s *Server) registerInstanceRoutes(g *echo.Group) {})g.POST("/instance/:instanceID/migration", func(c echo.Context) error {+ // TODO(p0ny): remove this endpoint because we no longer create migration history table on user instances.ctx := c.Request().Context()id, err := strconv.Atoi(c.Param("instanceID"))if err != nil {@@ -303,15 +296,6 @@ func (s *Server) registerInstanceRoutes(g *echo.Group) {}resultSet := &api.SQLResultSet{}- db, err := s.dbFactory.GetAdminDatabaseDriver(ctx, instance, "" /* databaseName */)- if err != nil {- resultSet.Error = err.Error()- } else {- defer db.Close(ctx)- if err := db.SetupMigrationIfNeeded(ctx); err != nil {- resultSet.Error = err.Error()- }- }c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)if err := jsonapi.MarshalPayload(c.Response().Writer, resultSet); err != nil {@@ -321,6 +305,7 @@ func (s *Server) registerInstanceRoutes(g *echo.Group) {})g.GET("/instance/:instanceID/migration/status", func(c echo.Context) error {+ // TODO(p0ny): remove this endpoint because we no longer create migration history table on user instances.ctx := c.Request().Context()id, err := strconv.Atoi(c.Param("instanceID"))if err != nil {@@ -335,22 +320,8 @@ func (s *Server) registerInstanceRoutes(g *echo.Group) {return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Instance ID not found: %d", id))}- instanceMigration := &api.InstanceMigration{}- db, err := s.dbFactory.GetAdminDatabaseDriver(ctx, instance, "" /* databaseName */)- if err != nil {- instanceMigration.Status = api.InstanceMigrationSchemaUnknown- instanceMigration.Error = err.Error()- } else {- defer db.Close(ctx)- setup, err := db.NeedsSetupMigration(ctx)- if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to check migration setup status for instance %q", instance.Title)).SetInternal(err)- }- if setup {- instanceMigration.Status = api.InstanceMigrationSchemaNotExist- } else {- instanceMigration.Status = api.InstanceMigrationSchemaOK- }+ instanceMigration := &api.InstanceMigration{+ Status: api.InstanceMigrationSchemaOK,}c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)@@ -380,30 +351,14 @@ func (s *Server) registerInstanceRoutes(g *echo.Group) {var entry *db.MigrationHistoryfind := &db.MigrationHistoryFind{ID: &historyID, InstanceID: &instanceID}- if instance.Engine == db.Redis || instance.Engine == db.Oracle {- list, err := s.store.FindInstanceChangeHistoryList(ctx, find)- if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch migration history list").SetInternal(err)- }- if len(list) == 0 {- return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Migration history ID %q not found for instance %q", historyID, instance.Title))- }- entry = list[0]- } else {- driver, err := s.dbFactory.GetAdminDatabaseDriver(ctx, instance, "" /* databaseName */)- if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch migration history ID %v for instance %q", historyID, instance.Title)).SetInternal(err)- }- defer driver.Close(ctx)- list, err := driver.FindMigrationHistoryList(ctx, find)- if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch migration history list").SetInternal(err)- }- if len(list) == 0 {- return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Migration history ID %q not found for instance %q", historyID, instance.Title))- }- entry = list[0]+ list, err := s.store.FindInstanceChangeHistoryList(ctx, find)+ if err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch migration history list").SetInternal(err)}+ if len(list) == 0 {+ return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Migration history ID %q not found for instance %q", historyID, instance.Title))+ }+ entry = list[0]if isSDL {var engineType parser.EngineType@@ -466,66 +421,37 @@ func (s *Server) registerInstanceRoutes(g *echo.Group) {return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Instance ID not found: %d", id))}- var migrationHistoryList []*db.MigrationHistoryfind := &db.MigrationHistoryFind{InstanceID: &instance.UID,}- if instance.Engine == db.Redis || instance.Engine == db.Oracle {- if databaseStr := c.QueryParams().Get("database"); databaseStr != "" {- database, err := s.store.GetDatabaseV2(ctx, &store.FindDatabaseMessage{- InstanceID: &instance.ResourceID,- DatabaseName: &databaseStr,- })- if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to get database %q from instance ID %v", databaseStr, instance.ResourceID)).SetInternal(err)- }- if database == nil {- return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Cannot find database %q from instance ID %v", databaseStr, instance.ResourceID)).SetInternal(err)- }- find.Database = &databaseStr- find.DatabaseID = &database.UID- }- if versionStr := c.QueryParams().Get("version"); versionStr != "" {- find.Version = &versionStr- }- if limitStr := c.QueryParam("limit"); limitStr != "" {- limit, err := strconv.Atoi(limitStr)- if err != nil {- return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("limit query parameter is not a number: %s", limitStr)).SetInternal(err)- }- find.Limit = &limit- }-- list, err := s.store.FindInstanceChangeHistoryList(ctx, find)+ if databaseStr := c.QueryParams().Get("database"); databaseStr != "" {+ database, err := s.store.GetDatabaseV2(ctx, &store.FindDatabaseMessage{+ InstanceID: &instance.ResourceID,+ DatabaseName: &databaseStr,+ })if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch migration history list").SetInternal(err)- }- migrationHistoryList = list- } else {- if databaseStr := c.QueryParams().Get("database"); databaseStr != "" {- find.Database = &databaseStr- }- if versionStr := c.QueryParams().Get("version"); versionStr != "" {- find.Version = &versionStr+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to get database %q from instance ID %v", databaseStr, instance.ResourceID)).SetInternal(err)}- if limitStr := c.QueryParam("limit"); limitStr != "" {- limit, err := strconv.Atoi(limitStr)- if err != nil {- return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("limit query parameter is not a number: %s", limitStr)).SetInternal(err)- }- find.Limit = &limit- }-- driver, err := s.dbFactory.GetAdminDatabaseDriver(ctx, instance, "" /* databaseName */)- if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch migration history for instance %q", instance.Title)).SetInternal(err)+ if database == nil {+ return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Cannot find database %q from instance ID %v", databaseStr, instance.ResourceID)).SetInternal(err)}- defer driver.Close(ctx)- list, err := driver.FindMigrationHistoryList(ctx, find)+ find.Database = &databaseStr+ find.DatabaseID = &database.UID+ }+ if versionStr := c.QueryParams().Get("version"); versionStr != "" {+ find.Version = &versionStr+ }+ if limitStr := c.QueryParam("limit"); limitStr != "" {+ limit, err := strconv.Atoi(limitStr)if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch migration history list").SetInternal(err)+ return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("limit query parameter is not a number: %s", limitStr)).SetInternal(err)}- migrationHistoryList = list+ find.Limit = &limit+ }++ migrationHistoryList, err := s.store.FindInstanceChangeHistoryList(ctx, find)+ if err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch migration history list").SetInternal(err)}historyList := []*api.MigrationHistory{}diff --git a/backend/server/server.go b/backend/server/server.goindex 320848fd1e..c4e89d19f4 100644--- a/backend/server/server.go+++ b/backend/server/server.go@@ -913,16 +913,6 @@ func (s *Server) generateOnboardingData(ctx context.Context, userID int) error {return errors.Wrapf(err, "failed to create onboarding instance")}- // Try creating the migration history database.- driver, err := s.dbFactory.GetAdminDatabaseDriver(ctx, instance, postgres.SampleDatabase)- if err != nil {- return errors.Wrapf(err, "failed to connect onboarding instance")- }- defer driver.Close(ctx)- if err := driver.SetupMigrationIfNeeded(ctx); err != nil {- return errors.Wrapf(err, "failed to set up migration schema on onboarding instance")- }-// Sync the instance schema so we can transfer the sample database later.if _, err := s.SchemaSyncer.SyncInstance(ctx, instance); err != nil {return errors.Wrapf(err, "failed to sync onboarding instance")diff --git a/backend/store/instance_change_history.go b/backend/store/instance_change_history.goindex c79966827d..83569dbf85 100644--- a/backend/store/instance_change_history.go+++ b/backend/store/instance_change_history.go@@ -270,6 +270,23 @@ func (s *Store) FindInstanceChangeHistoryList(ctx context.Context, find *db.Migrif err != nil {return nil, err}+ if change.DatabaseID != nil {+ database, err := s.GetDatabaseV2(ctx, &FindDatabaseMessage{UID: change.DatabaseID})+ if err != nil {+ return nil, err+ }+ migrationHistory.Namespace = database.DatabaseName+ }+ creator, err := s.GetPrincipalByID(ctx, change.CreatorID)+ if err != nil {+ return nil, err+ }+ migrationHistory.Creator = creator.Name+ updater, err := s.GetPrincipalByID(ctx, change.UpdaterID)+ if err != nil {+ return nil, err+ }+ migrationHistory.Updater = updater.NamemigrationHistoryList = append(migrationHistoryList, migrationHistory)}@@ -390,7 +407,7 @@ func (s *Store) UpdateInstanceChangeHistoryAsDone(ctx context.Context, migrationStatus: &status,Schema: &updatedSchema,}- return s.updateInstanceChangeHistory(ctx, update)+ return s.UpdateInstanceChangeHistory(ctx, update)}// UpdateInstanceChangeHistoryAsFailed updates a change history to failed.@@ -405,12 +422,12 @@ func (s *Store) UpdateInstanceChangeHistoryAsFailed(ctx context.Context, migratiExecutionDurationNs: &migrationDurationNs,Status: &status,}- return s.updateInstanceChangeHistory(ctx, update)+ return s.UpdateInstanceChangeHistory(ctx, update)}// UpdateInstanceChangeHistory updates an instance change history.// it deprecates the old UpdateHistoryAsDone and UpdateHistoryAsFailed.-func (s *Store) updateInstanceChangeHistory(ctx context.Context, update *UpdateInstanceChangeHistoryMessage) error {+func (s *Store) UpdateInstanceChangeHistory(ctx context.Context, update *UpdateInstanceChangeHistoryMessage) error {set, args := []string{}, []interface{}{}if v := update.Status; v != nil {set, args = append(set, fmt.Sprintf("status = $%d", len(args)+1)), append(args, *v)@@ -421,6 +438,9 @@ func (s *Store) updateInstanceChangeHistory(ctx context.Context, update *UpdateIif v := update.Schema; v != nil {set, args = append(set, fmt.Sprintf("schema = $%d", len(args)+1)), append(args, *v)}+ if len(set) == 0 {+ return nil+ }query := `UPDATE instance_change_historySET ` + strings.Join(set, ", ") + `diff --git a/backend/store/pg_engine.go b/backend/store/pg_engine.goindex 7a1361de45..8e6cc40379 100644--- a/backend/store/pg_engine.go+++ b/backend/store/pg_engine.go@@ -20,7 +20,7 @@ import (dbdriver "github.com/bytebase/bytebase/backend/plugin/db"// Register postgres driver.- _ "github.com/bytebase/bytebase/backend/plugin/db/pg"+ "github.com/bytebase/bytebase/backend/plugin/db/pg""github.com/bytebase/bytebase/backend/common")@@ -146,7 +146,8 @@ func (db *DB) Open(ctx context.Context) (schemaVersion *semver.Version, err erroreturn nil, errors.Wrap(err, "failed to get current schema version")}- if err := migrate(ctx, d, verBefore, db.mode, db.connCfg.StrictUseDb, db.serverVersion, databaseName); err != nil {+ pgDriver := d.(*pg.Driver)+ if err := migrate(ctx, pgDriver, verBefore, db.mode, db.connCfg.StrictUseDb, db.serverVersion, databaseName); err != nil {return nil, errors.Wrap(err, "failed to migrate")}@@ -298,7 +299,7 @@ const (// file run in a transaction to prevent partial migrations.//// The procedure follows https://github.com/bytebase/bytebase/blob/main/docs/schema-update-guide.md.-func migrate(ctx context.Context, d dbdriver.Driver, curVer *semver.Version, mode common.ReleaseMode, strictDb bool, serverVersion, databaseName string) error {+func migrate(ctx context.Context, d *pg.Driver, curVer *semver.Version, mode common.ReleaseMode, strictDb bool, serverVersion, databaseName string) error {log.Info("Apply database migration if needed...")if curVer == nil {log.Info("The database schema has not been setup.")@@ -356,9 +357,10 @@ func migrate(ctx context.Context, d dbdriver.Driver, curVer *semver.Version, mod}// TODO(p0ny): migrate to instance change history- if _, _, err := d.ExecuteMigration(+ if _, _, err := d.ExecuteMigrationUsingMigrationHistory(ctx,&dbdriver.MigrationInfo{+ InstanceID: nil,ReleaseVersion: serverVersion,UseSemanticVersion: true,Version: cutoffSchemaVersion.String(),@@ -420,9 +422,10 @@ func migrate(ctx context.Context, d dbdriver.Driver, curVer *semver.Version, mod}log.Info(fmt.Sprintf("Migrating %s...", pv.version))// TODO(p0ny): migrate to instance change history- if _, _, err := d.ExecuteMigration(+ if _, _, err := d.ExecuteMigrationUsingMigrationHistory(ctx,&dbdriver.MigrationInfo{+ InstanceID: nil,ReleaseVersion: serverVersion,UseSemanticVersion: true,Version: pv.version.String(),@@ -488,7 +491,7 @@ func getProdCutoffVersion() (semver.Version, error) {return patchVersions[len(patchVersions)-1].version, nil}-func migrateDev(ctx context.Context, d dbdriver.Driver, serverVersion, databaseName string, cutoffSchemaVersion semver.Version, histories []*dbdriver.MigrationHistory) error {+func migrateDev(ctx context.Context, d *pg.Driver, serverVersion, databaseName string, cutoffSchemaVersion semver.Version, histories []*dbdriver.MigrationHistory) error {devMigrations, err := getDevMigrations()if err != nil {return err@@ -512,9 +515,10 @@ func migrateDev(ctx context.Context, d dbdriver.Driver, serverVersion, databaseNlog.Info(fmt.Sprintf("Migrating dev %s...", m.filename))// We expect to use semantic versioning for dev environment too because getLatestVersion() always expect to get the latest version in semantic format.// TODO(p0ny): migrate to instance change history- if _, _, err := d.ExecuteMigration(+ if _, _, err := d.ExecuteMigrationUsingMigrationHistory(ctx,&dbdriver.MigrationInfo{+ InstanceID: nil,ReleaseVersion: serverVersion,UseSemanticVersion: true,Version: cutoffSchemaVersion.String(),diff --git a/backend/store/pg_engine_test.go b/backend/store/pg_engine_test.goindex 56265e0c4b..e52ac9d853 100644--- a/backend/store/pg_engine_test.go+++ b/backend/store/pg_engine_test.go@@ -13,6 +13,7 @@ import ("github.com/bytebase/bytebase/backend/common""github.com/bytebase/bytebase/backend/common/log"dbdriver "github.com/bytebase/bytebase/backend/plugin/db"+ "github.com/bytebase/bytebase/backend/plugin/db/pg""github.com/bytebase/bytebase/backend/resources/postgres")@@ -160,7 +161,7 @@ func TestMigrationCompatibility(t *testing.T) {Host: common.GetPostgresSocketDir(),Port: fmt.Sprintf("%d", pgPort),}- d, err := dbdriver.Open(+ driver, err := dbdriver.Open(ctx,dbdriver.Postgres,dbdriver.DriverConfig{DbBinDir: pgBinDir},@@ -168,7 +169,8 @@ func TestMigrationCompatibility(t *testing.T) {dbdriver.ConnectionContext{},)require.NoError(t, err)- defer d.Close(ctx)+ defer driver.Close(ctx)+ d := driver.(*pg.Driver)err = d.SetupMigrationIfNeeded(ctx)require.NoError(t, err)diff --git a/backend/utils/utils.go b/backend/utils/utils.goindex 835e52afd0..28fe2dadef 100644--- a/backend/utils/utils.go+++ b/backend/utils/utils.go@@ -25,7 +25,7 @@ import ()// GetLatestSchemaVersion gets the latest schema version for a database.-func GetLatestSchemaVersion(ctx context.Context, store *store.Store, driver db.Driver, instanceID int, databaseID int, databaseName string) (string, error) {+func GetLatestSchemaVersion(ctx context.Context, store *store.Store, instanceID int, databaseID int, databaseName string) (string, error) {// TODO(d): support semantic versioning.limit := 1find := &db.MigrationHistoryFind{@@ -35,19 +35,7 @@ func GetLatestSchemaVersion(ctx context.Context, store *store.Store, driver db.DLimit: &limit,}- if driver.GetType() == db.Redis || driver.GetType() == db.Oracle {- history, err := store.FindInstanceChangeHistoryList(ctx, find)- if err != nil {- return "", errors.Wrapf(err, "failed to get migration history for database %q", databaseName)- }- var schemaVersion string- if len(history) == 1 {- schemaVersion = history[0].Version- }- return schemaVersion, nil- }-- history, err := driver.FindMigrationHistoryList(ctx, find)+ history, err := store.FindInstanceChangeHistoryList(ctx, find)if err != nil {return "", errors.Wrapf(err, "failed to get migration history for database %q", databaseName)}@@ -501,7 +489,7 @@ func ExecuteMigration(ctx context.Context, store *store.Store, driver db.Driver,}}- insertedID, err := beginMigration(ctx, store, m, prevSchemaBuf.String(), statement)+ insertedID, err := BeginMigration(ctx, store, m, prevSchemaBuf.String(), statement)if err != nil {if common.ErrorCode(err) == common.MigrationAlreadyApplied {return insertedID, prevSchemaBuf.String(), nil@@ -512,7 +500,7 @@ func ExecuteMigration(ctx context.Context, store *store.Store, driver db.Driver,startedNs := time.Now().UnixNano()defer func() {- if err := endMigration(ctx, store, startedNs, insertedID, updatedSchema, db.BytebaseDatabase, resErr == nil /*isDone*/); err != nil {+ if err := EndMigration(ctx, store, startedNs, insertedID, updatedSchema, db.BytebaseDatabase, resErr == nil /*isDone*/); err != nil {log.Error("Failed to update migration history record",zap.Error(err),zap.String("migration_id", migrationHistoryID),@@ -532,7 +520,6 @@ func ExecuteMigration(ctx context.Context, store *store.Store, driver db.Driver,doMigrate = false}if doMigrate {- // TODO(p0ny): migrate to instance change historyif _, _, err := driver.ExecuteMigration(ctx, m, statement); err != nil {return "", "", err}@@ -551,8 +538,8 @@ func ExecuteMigration(ctx context.Context, store *store.Store, driver db.Driver,return insertedID, afterSchemaBuf.String(), nil}-// beginMigration checks before executing migration and inserts a migration history record with pending status.-func beginMigration(ctx context.Context, store *store.Store, m *db.MigrationInfo, prevSchema string, statement string) (string, error) {+// BeginMigration checks before executing migration and inserts a migration history record with pending status.+func BeginMigration(ctx context.Context, store *store.Store, m *db.MigrationInfo, prevSchema string, statement string) (string, error) {// Convert version to stored version.storedVersion, err := util.ToStoredVersion(m.UseSemanticVersion, m.Version, m.SemanticVersionSuffix)if err != nil {@@ -619,7 +606,8 @@ func beginMigration(ctx context.Context, store *store.Store, m *db.MigrationInforeturn insertedID, nil}-func endMigration(ctx context.Context, store *store.Store, startedNs int64, insertedID string, updatedSchema string, _ string, isDone bool) error {+// EndMigration updates the migration history record to DONE or FAILED depending on migration is done or not.+func EndMigration(ctx context.Context, store *store.Store, startedNs int64, insertedID string, updatedSchema string, _ string, isDone bool) error {var err errormigrationDurationNs := time.Now().UnixNano() - startedNs