Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
chore: change history & model.Version in migrator, clear everywhere else (#14922)
p0nyad6b00ec02f7
diff --git a/backend/migrator/migrator.go b/backend/migrator/migrator.goindex bb4c2b0cf4..f6d4830f3e 100644--- a/backend/migrator/migrator.go+++ b/backend/migrator/migrator.go@@ -18,7 +18,6 @@ import ("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"@@ -313,11 +312,11 @@ func migrate(ctx context.Context, storeInstance *store.Store, metadataDriver dbdcontinue}slog.Info(fmt.Sprintf("Migrating %s...", pv.version))+ version := model.Version{Semantic: true, Version: pv.version.String(), Suffix: time.Now().Format("20060102150405")}mi := &dbdriver.MigrationInfo{InstanceID: nil,CreatorID: api.SystemBotID,ReleaseVersion: serverVersion,- Version: model.Version{Semantic: true, Version: pv.version.String(), Suffix: time.Now().Format("20060102150405")},Namespace: databaseName,Database: databaseName,Environment: "", /* unused in execute migration */@@ -325,7 +324,7 @@ func migrate(ctx context.Context, storeInstance *store.Store, metadataDriver dbdType: dbdriver.Migrate,Description: fmt.Sprintf("Migrate version %s server version %s with files %s.", pv.version, serverVersion, pv.filename),}- if _, _, err := executeMigrationDefault(ctx, ctx, storeInstance, nil, 0, metadataDriver, mi, string(buf), nil, dbdriver.ExecuteOptions{}); err != nil {+ if _, _, err := executeMigrationDefault(ctx, ctx, storeInstance, metadataDriver, mi, string(buf), version, dbdriver.ExecuteOptions{}); err != nil {return false, err}retVersion = pv.version@@ -399,11 +398,11 @@ func migrateDev(ctx context.Context, storeInstance *store.Store, metadataDriverfor _, m := range migrations {slog.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.+ version := model.Version{Semantic: true, Version: cutoffSchemaVersion.String(), Suffix: fmt.Sprintf("dev%s", m.version)}mi := &dbdriver.MigrationInfo{InstanceID: nil,CreatorID: api.SystemBotID,ReleaseVersion: serverVersion,- Version: model.Version{Semantic: true, Version: cutoffSchemaVersion.String(), Suffix: fmt.Sprintf("dev%s", m.version)},Namespace: databaseName,Database: databaseName,Environment: "", /* unused in execute migration */@@ -411,7 +410,7 @@ func migrateDev(ctx context.Context, storeInstance *store.Store, metadataDriverType: dbdriver.Migrate,Description: fmt.Sprintf("Migrate version %s server version %s with files %s.", m.version, serverVersion, m.filename),}- if _, _, err := executeMigrationDefault(ctx, ctx, storeInstance, nil, 0, metadataDriver, mi, m.statement, nil, dbdriver.ExecuteOptions{}); err != nil {+ if _, _, err := executeMigrationDefault(ctx, ctx, storeInstance, metadataDriver, mi, m.statement, version, dbdriver.ExecuteOptions{}); err != nil {return err}}@@ -584,19 +583,19 @@ func backfillOracleSchema(ctx context.Context, stores *store.Store) error {}// 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) {+func executeMigrationDefault(ctx context.Context, driverCtx context.Context, store *store.Store, driver dbdriver.Driver, mi *dbdriver.MigrationInfo, statement string, version model.Version, 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)+ return ExecuteMigrationWithFunc(ctx, driverCtx, store, mi, statement, version, execFunc, opts)}// ExecuteMigrationWithFunc executes the migration with custom migration function.-func ExecuteMigrationWithFunc(ctx context.Context, driverCtx context.Context, s *store.Store, _ int, _ dbdriver.Driver, m *dbdriver.MigrationInfo, statement string, sheetID *int, execFunc func(ctx context.Context, execStatement string) error, _ dbdriver.ExecuteOptions) (migrationHistoryID string, updatedSchema string, resErr error) {- insertedID, err := BeginMigration(ctx, s, m, "", statement, sheetID)+func ExecuteMigrationWithFunc(ctx context.Context, driverCtx context.Context, s *store.Store, m *dbdriver.MigrationInfo, statement string, version model.Version, execFunc func(ctx context.Context, execStatement string) error, _ dbdriver.ExecuteOptions) (migrationHistoryID string, updatedSchema string, resErr error) {+ insertedID, err := BeginMigration(ctx, s, m, statement, version)if err != nil {return "", "", errors.Wrapf(err, "failed to begin migration")}@@ -604,7 +603,7 @@ func ExecuteMigrationWithFunc(ctx context.Context, driverCtx context.Context, sstartedNs := time.Now().UnixNano()defer func() {- if err := EndMigration(ctx, s, startedNs, insertedID, updatedSchema, "", sheetID, resErr == nil /* isDone */); err != nil {+ if err := EndMigration(ctx, s, startedNs, insertedID, "" /* updatedSchema */, "" /* prevSchema */, nil /* sheetID */, resErr == nil /* isDone */); err != nil {slog.Error("Failed to update migration history record",log.BBError(err),slog.String("migration_id", migrationHistoryID),@@ -647,30 +646,30 @@ func ExecuteMigrationWithFunc(ctx context.Context, driverCtx context.Context, s}// 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) {+func BeginMigration(ctx context.Context, stores *store.Store, m *dbdriver.MigrationInfo, statement string, version model.Version) (string, error) {// Phase 1 - Pre-check before executing migration// Check if the same migration version has already been applied.if list, err := stores.ListInstanceChangeHistoryForMigrator(ctx, &store.FindInstanceChangeHistoryMessage{InstanceID: m.InstanceID,DatabaseID: m.DatabaseID,- Version: &m.Version,+ Version: &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:- err := 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)+ err := common.Errorf(common.MigrationAlreadyApplied, "database %q has already applied version %s, hint: the version might be duplicate, please check the version", m.Database, version.Version)slog.Debug(err.Error())// Force migrationreturn migrationHistory.UID, nilcase dbdriver.Pending:- err := errors.Errorf("database %q version %s migration is already in progress", m.Database, m.Version.Version)+ err := errors.Errorf("database %q version %s migration is already in progress", m.Database, version.Version)slog.Debug(err.Error())// For force migration, we will ignore the existing migration history and continue to migration.return migrationHistory.UID, nilcase 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)+ 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, version.Version)slog.Debug(err.Error())// For force migration, we will ignore the existing migration history and continue to migration.return migrationHistory.UID, nil@@ -679,7 +678,7 @@ func BeginMigration(ctx context.Context, stores *store.Store, m *dbdriver.Migrat// Phase 2 - Record migration history as PENDING.statementRecord, _ := common.TruncateString(statement, common.MaxSheetSize)- insertedID, err := stores.CreatePendingInstanceChangeHistory(ctx, prevSchema, m, statementRecord, sheetID)+ insertedID, err := stores.CreatePendingInstanceChangeHistoryForMigrator(ctx, "" /* prevSchema */, m, statementRecord, nil /* sheetID */, version)if err != nil {return "", err}diff --git a/backend/plugin/db/driver.go b/backend/plugin/db/driver.goindex df10a19841..2be8650725 100644--- a/backend/plugin/db/driver.go+++ b/backend/plugin/db/driver.go@@ -13,7 +13,6 @@ import ("github.com/pkg/errors""github.com/bytebase/bytebase/backend/common/log"- "github.com/bytebase/bytebase/backend/store/model"storepb "github.com/bytebase/bytebase/proto/generated-go/store"v1pb "github.com/bytebase/bytebase/proto/generated-go/v1")@@ -158,7 +157,6 @@ type MigrationInfo struct {CreatorID intReleaseVersion string- Version model.VersionNamespace stringDatabase stringEnvironment stringdiff --git a/backend/runner/taskrun/database_create_executor.go b/backend/runner/taskrun/database_create_executor.goindex e1399ca245..47aa60a44f 100644--- a/backend/runner/taskrun/database_create_executor.go+++ b/backend/runner/taskrun/database_create_executor.go@@ -20,7 +20,6 @@ import ("github.com/bytebase/bytebase/backend/plugin/db""github.com/bytebase/bytebase/backend/runner/schemasync""github.com/bytebase/bytebase/backend/store"- "github.com/bytebase/bytebase/backend/store/model""github.com/bytebase/bytebase/backend/utils"storepb "github.com/bytebase/bytebase/proto/generated-go/store")@@ -166,10 +165,9 @@ func (exec *DatabaseCreateExecutor) RunOnce(ctx context.Context, driverCtx contesyncStatus := api.OKif _, err := exec.store.UpdateDatabase(ctx, &store.UpdateDatabaseMessage{- InstanceID: instance.ResourceID,- DatabaseName: payload.DatabaseName,- SyncState: &syncStatus,- SchemaVersion: &peerSchemaVersion,+ InstanceID: instance.ResourceID,+ DatabaseName: payload.DatabaseName,+ SyncState: &syncStatus,}, api.SystemBotID); err != nil {return true, nil, err}@@ -217,16 +215,9 @@ func (exec *DatabaseCreateExecutor) RunOnce(ctx context.Context, driverCtx conte)}- storedVersion, err := peerSchemaVersion.Marshal()- if err != nil {- slog.Error("failed to convert database schema version",- slog.String("version", peerSchemaVersion.Version),- log.BBError(err),- )- }return true, &storepb.TaskRunResult{Detail: fmt.Sprintf("Created database %q", payload.DatabaseName),- Version: storedVersion,+ Version: peerSchemaVersion,}, nil}@@ -347,24 +338,24 @@ func (exec *DatabaseCreateExecutor) reconcilePlan(ctx context.Context, project *}}-func (exec *DatabaseCreateExecutor) createInitialSchema(ctx context.Context, driverCtx context.Context, environment *store.EnvironmentMessage, instance *store.InstanceMessage, project *store.ProjectMessage, task *store.TaskMessage, taskRunUID int, database *store.DatabaseMessage) (*store.DatabaseMessage, model.Version, string, error) {+func (exec *DatabaseCreateExecutor) createInitialSchema(ctx context.Context, driverCtx context.Context, environment *store.EnvironmentMessage, instance *store.InstanceMessage, project *store.ProjectMessage, task *store.TaskMessage, taskRunUID int, database *store.DatabaseMessage) (*store.DatabaseMessage, string, string, error) {peerDatabase, schemaVersion, schema, err := exec.getSchemaFromPeerTenantDatabase(ctx, instance, project, database)if err != nil {- return nil, model.Version{}, "", err+ return nil, "", "", err}if schema == "" {- return nil, model.Version{}, "", nil+ return nil, "", "", nil}useDBOwner, err := getUseDatabaseOwner(ctx, exec.store, instance, database)if err != nil {- return nil, model.Version{}, "", errors.Wrapf(err, "failed to check if we should use database owner")+ return nil, "", "", errors.Wrapf(err, "failed to check if we should use database owner")}driver, err := exec.dbFactory.GetAdminDatabaseDriver(ctx, instance, database, db.ConnectionContext{UseDatabaseOwner: useDBOwner,})if err != nil {- return nil, model.Version{}, "", err+ return nil, "", "", err}defer driver.Close(ctx)@@ -373,7 +364,6 @@ func (exec *DatabaseCreateExecutor) createInitialSchema(ctx context.Context, driInstanceID: &task.InstanceID,CreatorID: task.CreatorID,ReleaseVersion: exec.profile.Version,- Version: schemaVersion,Namespace: database.DatabaseName,Database: database.DatabaseName,DatabaseID: &database.UID,@@ -426,7 +416,7 @@ func (exec *DatabaseCreateExecutor) createInitialSchema(ctx context.Context, dritask: task,taskRunUID: taskRunUID,taskRunName: common.FormatTaskRun(project.ResourceID, task.PipelineID, task.StageID, task.ID, taskRunUID),- version: schemaVersion.Version,+ version: schemaVersion,}if issue != nil {@@ -438,7 +428,7 @@ func (exec *DatabaseCreateExecutor) createInitialSchema(ctx context.Context, dri}if _, _, err := executeMigrationDefault(ctx, driverCtx, exec.store, exec.stateCfg, driver, mi, mc, schema, db.ExecuteOptions{}); err != nil {- return nil, model.Version{}, "", err+ return nil, "", "", err}return peerDatabase, schemaVersion, schema, nil}@@ -474,11 +464,11 @@ func getConnectionStatement(dbType storepb.Engine, databaseName string) (string,// It's used for creating a database in a tenant mode project.// When a peer tenant database doesn't exist, we will return an error if there are databases in the project with the same name.// Otherwise, we will create a blank database without schema.-func (exec *DatabaseCreateExecutor) getSchemaFromPeerTenantDatabase(ctx context.Context, instance *store.InstanceMessage, project *store.ProjectMessage, database *store.DatabaseMessage) (*store.DatabaseMessage, model.Version, string, error) {+func (exec *DatabaseCreateExecutor) getSchemaFromPeerTenantDatabase(ctx context.Context, instance *store.InstanceMessage, project *store.ProjectMessage, database *store.DatabaseMessage) (*store.DatabaseMessage, string, string, error) {// Try to find a peer tenant database from database groups.matchedDatabases, err := exec.getPeerTenantDatabasesFromDatabaseGroup(ctx, instance, project, database)if err != nil {- return nil, model.Version{}, "", errors.Wrapf(err, "Failed to fetch database groups in project ID: %v", project.UID)+ return nil, "", "", errors.Wrapf(err, "Failed to fetch database groups in project ID: %v", project.UID)}// Filter out the database itself.@@ -490,38 +480,38 @@ func (exec *DatabaseCreateExecutor) getSchemaFromPeerTenantDatabase(ctx context.}matchedDatabases = databasesif len(matchedDatabases) == 0 {- return nil, model.Version{}, "", nil+ return nil, "", "", nil}// Then we will try to find a peer tenant database from deployment schedule with the matched databases.deploymentConfig, err := exec.store.GetDeploymentConfigV2(ctx, project.UID)if err != nil {- return nil, model.Version{}, "", errors.Wrapf(err, "Failed to fetch deployment config for project ID: %v", project.UID)+ return nil, "", "", errors.Wrapf(err, "Failed to fetch deployment config for project ID: %v", project.UID)}if err := utils.ValidateDeploymentSchedule(deploymentConfig.Config.GetSchedule()); err != nil {- return nil, model.Version{}, "", errors.Errorf("Failed to get deployment schedule")+ return nil, "", "", errors.Errorf("Failed to get deployment schedule")}matrix, err := utils.GetDatabaseMatrixFromDeploymentSchedule(deploymentConfig.Config.GetSchedule(), matchedDatabases)if err != nil {- return nil, model.Version{}, "", errors.Errorf("Failed to create deployment pipeline")+ return nil, "", "", errors.Errorf("Failed to create deployment pipeline")}similarDB := getPeerTenantDatabase(matrix, instance.EnvironmentID)if similarDB == nil {- return nil, model.Version{}, "", nil+ return nil, "", "", nil}similarDBInstance, err := exec.store.GetInstanceV2(ctx, &store.FindInstanceMessage{ResourceID: &similarDB.InstanceID})if err != nil {- return nil, model.Version{}, "", err+ return nil, "", "", err}driver, err := exec.dbFactory.GetAdminDatabaseDriver(ctx, similarDBInstance, similarDB, db.ConnectionContext{})if err != nil {- return nil, model.Version{}, "", err+ return nil, "", "", err}defer driver.Close(ctx)- schemaVersion, err := getLatestDoneSchemaVersion(ctx, exec.store, similarDBInstance.UID, similarDB.UID, similarDB.DatabaseName)+ schemaVersion, err := getLatestDoneSchemaVersion(ctx, exec.store, similarDB.UID, similarDB.DatabaseName)if err != nil {- return nil, model.Version{}, "", errors.Wrapf(err, "failed to get migration history for database %q", similarDB.DatabaseName)+ return nil, "", "", errors.Wrapf(err, "failed to get migration history for database %q", similarDB.DatabaseName)}dbSchema := (*storepb.DatabaseSchemaMetadata)(nil)@@ -529,18 +519,18 @@ func (exec *DatabaseCreateExecutor) getSchemaFromPeerTenantDatabase(ctx context.// Use new driver to sync the schema to avoid the session state change, such as SET ROLE in PostgreSQL.syncDriver, err := exec.dbFactory.GetAdminDatabaseDriver(ctx, instance, similarDB, db.ConnectionContext{})if err != nil {- return nil, model.Version{}, "", errors.Wrapf(err, "failed to get driver for instance %q", instance.Title)+ return nil, "", "", errors.Wrapf(err, "failed to get driver for instance %q", instance.Title)}defer syncDriver.Close(ctx)dbSchema, err = syncDriver.SyncDBSchema(ctx)if err != nil {- return nil, model.Version{}, "", errors.Wrapf(err, "failed to get schema for database %q", similarDB.DatabaseName)+ return nil, "", "", errors.Wrapf(err, "failed to get schema for database %q", similarDB.DatabaseName)}}var schemaBuf bytes.Bufferif err := driver.Dump(ctx, &schemaBuf, dbSchema); err != nil {- return nil, model.Version{}, "", err+ return nil, "", "", err}return similarDB, schemaVersion, schemaBuf.String(), nil}@@ -586,24 +576,21 @@ func (exec *DatabaseCreateExecutor) getPeerTenantDatabasesFromDatabaseGroup(ctx}// GetLatestDoneSchemaVersion gets the latest schema version for a database.-func getLatestDoneSchemaVersion(ctx context.Context, stores *store.Store, instanceID int, databaseID int, databaseName string) (model.Version, error) {- // TODO(d): support semantic versioning.+func getLatestDoneSchemaVersion(ctx context.Context, stores *store.Store, databaseID int, databaseName string) (string, error) {limit := 1- done := db.Done- // TODO(p0ny): use changelog- history, err := stores.ListInstanceChangeHistory(ctx, &store.FindInstanceChangeHistoryMessage{- InstanceID: &instanceID,- DatabaseID: &databaseID,- Status: &done,- Limit: &limit,+ done := store.ChangelogStatusDone+ changelogs, err := stores.ListChangelogs(ctx, &store.FindChangelogMessage{+ DatabaseUID: &databaseID,+ Status: &done,+ Limit: &limit,})if err != nil {- return model.Version{}, errors.Wrapf(err, "failed to get migration history for database %q", databaseName)+ return "", errors.Wrapf(err, "failed to get migration history for database %q", databaseName)}- if len(history) == 0 {- return model.Version{}, nil+ if len(changelogs) == 0 {+ return "", nil}- return history[0].Version, nil+ return changelogs[0].Payload.Version, nil}func getPeerTenantDatabase(databaseMatrix [][]*store.DatabaseMessage, environmentID string) *store.DatabaseMessage {diff --git a/backend/runner/taskrun/executor.go b/backend/runner/taskrun/executor.goindex cc8c6f9ae6..324c776eaa 100644--- a/backend/runner/taskrun/executor.go+++ b/backend/runner/taskrun/executor.go@@ -114,7 +114,6 @@ func getMigrationInfo(ctx context.Context, stores *store.Store, profile *config.CreatorID: task.CreatorID,ReleaseVersion: profile.Version,Type: migrationType,- Version: schemaVersion,Description: task.Name,Environment: environment.ResourceID,Database: database.DatabaseName,@@ -386,9 +385,9 @@ func postMigration(ctx context.Context, stores *store.Store, mi *db.MigrationInflog.BBError(err))}- detail := fmt.Sprintf("Applied migration version %s to database %q.", mi.Version.Version, database.DatabaseName)+ detail := fmt.Sprintf("Applied migration version %s to database %q.", mc.version, database.DatabaseName)if mi.Type == db.Baseline {- detail = fmt.Sprintf("Established baseline version %s for database %q.", mi.Version.Version, database.DatabaseName)+ detail = fmt.Sprintf("Established baseline version %s for database %q.", mc.version, database.DatabaseName)}return true, &storepb.TaskRunResult{@@ -546,7 +545,7 @@ func beginMigration(ctx context.Context, stores *store.Store, mi *db.MigrationInTaskRun: mc.taskRunName,Issue: mc.issueName,Revision: 0,- ChangedResources: mi.Payload.ChangedResources,+ ChangedResources: mi.Payload.GetChangedResources(),Sheet: mc.sheetName,Version: mc.version,Type: convertTaskType(mc.task.Type),diff --git a/backend/store/changelog.go b/backend/store/changelog.goindex de321fa477..98e237a895 100644--- a/backend/store/changelog.go+++ b/backend/store/changelog.go@@ -46,6 +46,7 @@ type FindChangelogMessage struct {DatabaseUID *intTypeList []string+ Status *ChangelogStatusResourcesFilter *stringLimit *int@@ -167,6 +168,9 @@ func (s *Store) ListChangelogs(ctx context.Context, find *FindChangelogMessage)where = append(where, text)}}+ if v := find.Status; v != nil {+ where, args = append(where, fmt.Sprintf("changelog.status = $%d", len(args)+1)), append(args, string(*v))+ }if find.HasSyncHistory {where = append(where, "changelog.sync_history_id IS NOT NULL")}diff --git a/backend/store/database.go b/backend/store/database.goindex 1b348e5952..c0f2d852ea 100644--- a/backend/store/database.go+++ b/backend/store/database.go@@ -12,7 +12,6 @@ import ("github.com/bytebase/bytebase/backend/common"api "github.com/bytebase/bytebase/backend/legacyapi"- "github.com/bytebase/bytebase/backend/store/model"storepb "github.com/bytebase/bytebase/proto/generated-go/store")@@ -44,7 +43,6 @@ type UpdateDatabaseMessage struct {ProjectID *stringSyncState *api.SyncStatusSuccessfulSyncTimeTs *int64- SchemaVersion *model.VersionSourceBackupID *intSecrets *storepb.SecretsDataShare *bool@@ -349,13 +347,6 @@ func (s *Store) UpdateDatabase(ctx context.Context, patch *UpdateDatabaseMessageif v := patch.SuccessfulSyncTimeTs; v != nil {set, args = append(set, fmt.Sprintf("last_successful_sync_ts = $%d", len(args)+1)), append(args, *v)}- if v := patch.SchemaVersion; v != nil {- storedVersion, err := patch.SchemaVersion.Marshal()- if err != nil {- return nil, err- }- set, args = append(set, fmt.Sprintf("schema_version = $%d", len(args)+1)), append(args, storedVersion)- }if v := patch.Secrets; v != nil {secretsString, err := protojson.Marshal(v)if err != nil {diff --git a/backend/store/instance_change_history.go b/backend/store/instance_change_history.goindex 7096f8c218..3458fc64a6 100644--- a/backend/store/instance_change_history.go+++ b/backend/store/instance_change_history.go@@ -5,7 +5,6 @@ import ("database/sql""fmt""sort"- "strconv""strings""github.com/google/cel-go/cel"@@ -447,242 +446,6 @@ func (r *expressionRewriter) rewriteExpression(expr *exprpb.Expr) error {return nil}-// ListInstanceChangeHistory finds the instance change history.-func (s *Store) ListInstanceChangeHistory(ctx context.Context, find *FindInstanceChangeHistoryMessage) ([]*InstanceChangeHistoryMessage, error) {- where, args := []string{"TRUE"}, []any{}- if v := find.ID; v != nil {- id, err := strconv.Atoi(*v)- if err != nil {- return nil, errors.Wrapf(err, "failed to convert id %q to int", *v)- }- where, args = append(where, fmt.Sprintf("instance_change_history.id = $%d", len(args)+1)), append(args, id)- }- sheetField := "instance_change_history.sheet_id"- if v := find.InstanceID; v != nil {- where, args = append(where, fmt.Sprintf("instance_change_history.instance_id = $%d", len(args)+1)), append(args, *v)- } else {- where = append(where, "instance_change_history.instance_id is NULL AND instance_change_history.database_id is NULL")- sheetField = "NULL"- }- if v := find.DatabaseID; v != nil {- where, args = append(where, fmt.Sprintf("instance_change_history.database_id = $%d", len(args)+1)), append(args, *v)- }- if v := find.SheetID; v != nil {- where, args = append(where, fmt.Sprintf("instance_change_history.sheet_id = $%d", len(args)+1)), append(args, *v)- }- if v := find.Source; v != nil {- where, args = append(where, fmt.Sprintf("instance_change_history.source = $%d", len(args)+1)), append(args, *v)- }- if v := find.Status; v != nil {- where, args = append(where, fmt.Sprintf("instance_change_history.status = $%d", len(args)+1)), append(args, *v)- }- if v := find.Version; v != nil {- storedVersion, err := find.Version.Marshal()- if err != nil {- return nil, err- }- where, args = append(where, fmt.Sprintf("instance_change_history.version = $%d", len(args)+1)), append(args, storedVersion)- }- if v := find.ResourcesFilter; v != nil {- text, err := generateResourceFilter(*v, "instance_change_history.payload")- if err != nil {- return nil, errors.Wrapf(err, "failed to generate resource filter from %q", *v)- }- if text != "" {- where = append(where, text)- }- }-- changeTypes := []string{}- for _, changeType := range find.TypeList {- changeTypes = append(changeTypes, fmt.Sprintf(`'%s'`, string(changeType)))- }- if len(changeTypes) > 0 {- where = append(where, fmt.Sprintf("instance_change_history.type IN (%s)", strings.Join(changeTypes, ",")))- }-- statementField := "COALESCE(sheet_blob.content, instance_change_history.statement)"- if !find.ShowFull {- statementField = fmt.Sprintf("LEFT(%s, %d)", statementField, find.TruncateSize)- }- schemaField := "instance_change_history.schema"- if !find.ShowFull {- schemaField = fmt.Sprintf("LEFT(%s, %d)", schemaField, find.TruncateSize)- }- schemaPrevField := "instance_change_history.schema_prev"- if !find.ShowFull {- schemaPrevField = fmt.Sprintf("LEFT(%s, %d)", schemaPrevField, find.TruncateSize)- }- query := fmt.Sprintf(`- SELECT- instance_change_history.id,- instance_change_history.row_status,- instance_change_history.creator_id,- instance_change_history.created_ts,- instance_change_history.updater_id,- instance_change_history.updated_ts,- instance_change_history.instance_id,- instance_change_history.database_id,- instance_change_history.project_id,- instance_change_history.issue_id,- instance_change_history.release_version,- instance_change_history.sequence,- instance_change_history.source,- instance_change_history.type,- instance_change_history.status,- instance_change_history.version,- instance_change_history.description,- %s,- OCTET_LENGTH(COALESCE(sheet_blob.content, instance_change_history.statement)),- %s,- OCTET_LENGTH(instance_change_history.schema),- %s,- OCTET_LENGTH(instance_change_history.schema_prev),- %s,- instance_change_history.execution_duration_ns,- instance_change_history.payload,- COALESCE(instance.resource_id, ''),- COALESCE(db.name, '')- FROM instance_change_history- LEFT JOIN sheet ON sheet.id = instance_change_history.sheet_id- LEFT JOIN sheet_blob ON sheet.sha256 = sheet_blob.sha256- LEFT JOIN instance on instance.id = instance_change_history.instance_id- LEFT JOIN db on db.id = instance_change_history.database_id- WHERE `+strings.Join(where, " AND ")+` ORDER BY instance_change_history.instance_id, instance_change_history.database_id, instance_change_history.sequence DESC`,- statementField,- schemaField,- schemaPrevField,- sheetField,- )- if v := find.Limit; v != nil {- query += fmt.Sprintf(" LIMIT %d", *v)- }- if v := find.Offset; v != nil {- query += fmt.Sprintf(" OFFSET %d", *v)- }-- tx, err := s.db.BeginTx(ctx, &sql.TxOptions{ReadOnly: true})- if err != nil {- return nil, err- }- defer tx.Rollback()-- rows, err := tx.QueryContext(ctx, query, args...)- if err != nil {- return nil, err- }- defer rows.Close()-- var list []*InstanceChangeHistoryMessage- for rows.Next() {- var changeHistory InstanceChangeHistoryMessage- var rowStatus, storedVersion, payload string- var instanceID, databaseID, projectID, issueID, sheetID sql.NullInt32- if err := rows.Scan(- &changeHistory.UID,- &rowStatus,- &changeHistory.CreatorID,- &changeHistory.CreatedTs,- &changeHistory.UpdaterID,- &changeHistory.UpdatedTs,- &instanceID,- &databaseID,- &projectID,- &issueID,- &changeHistory.ReleaseVersion,- &changeHistory.Sequence,- &changeHistory.Source,- &changeHistory.Type,- &changeHistory.Status,- &storedVersion,- &changeHistory.Description,- &changeHistory.Statement,- &changeHistory.StatementSize,- &changeHistory.Schema,- &changeHistory.SchemaSize,- &changeHistory.SchemaPrev,- &changeHistory.SchemaPrevSize,- &sheetID,- &changeHistory.ExecutionDurationNs,- &payload,- &changeHistory.InstanceID,- &changeHistory.DatabaseName,- ); err != nil {- return nil, err- }- if instanceID.Valid {- n := int(instanceID.Int32)- changeHistory.InstanceUID = &n- }- if databaseID.Valid {- n := int(databaseID.Int32)- changeHistory.DatabaseUID = &n- }- if projectID.Valid {- n := int(projectID.Int32)- changeHistory.ProjectUID = &n- }- if issueID.Valid {- n := int(issueID.Int32)- changeHistory.IssueUID = &n- }- if sheetID.Valid {- n := int(sheetID.Int32)- changeHistory.SheetID = &n- }- version, err := model.NewVersion(storedVersion)- if err != nil {- return nil, err- }- changeHistory.Version = version- changeHistory.Payload = &storepb.InstanceChangeHistoryPayload{}- if err := common.ProtojsonUnmarshaler.Unmarshal([]byte(payload), changeHistory.Payload); err != nil {- return nil, err- }-- changeHistory.Deleted = convertRowStatusToDeleted(rowStatus)- list = append(list, &changeHistory)- }- if err := rows.Err(); err != nil {- return nil, err- }-- if err := tx.Commit(); err != nil {- return nil, err- }-- for _, changeHistory := range list {- creator, err := s.GetUserByID(ctx, changeHistory.CreatorID)- if err != nil {- return nil, errors.Wrapf(err, "failed to get creator by creatorID %q", changeHistory.CreatorID)- }- changeHistory.Creator = creator- updater, err := s.GetUserByID(ctx, changeHistory.UpdaterID)- if err != nil {- return nil, errors.Wrapf(err, "failed to get updater by updaterID %q", changeHistory.UpdaterID)- }- changeHistory.Updater = updater- }-- return list, nil-}--// GetInstanceChangeHistory gets the instance change history.-func (s *Store) GetInstanceChangeHistory(ctx context.Context, find *FindInstanceChangeHistoryMessage) (*InstanceChangeHistoryMessage, error) {- list, err := s.ListInstanceChangeHistory(ctx, find)- if err != nil {- return nil, err- }- if len(list) == 0 {- return nil, nil- }- if len(list) > 1 {- return nil, errors.Errorf("expected 1 change history, got %d", len(list))- }-- return list[0], nil-}-// UpdateInstanceChangeHistory updates an instance change history.// it deprecates the old UpdateHistoryAsDone and UpdateHistoryAsFailed.func (s *Store) UpdateInstanceChangeHistory(ctx context.Context, update *UpdateInstanceChangeHistoryMessage) error {@@ -746,8 +509,7 @@ func (*Store) getNextInstanceChangeHistorySequence(ctx context.Context, tx *Tx,}// CreatePendingInstanceChangeHistory creates an instance change history.-// it deprecates the old InsertPendingHistory.-func (s *Store) CreatePendingInstanceChangeHistory(ctx context.Context, prevSchema string, m *db.MigrationInfo, statement string, sheetID *int) (string, error) {+func (s *Store) CreatePendingInstanceChangeHistoryForMigrator(ctx context.Context, prevSchema string, m *db.MigrationInfo, statement string, sheetID *int, version model.Version) (string, error) {tx, err := s.db.BeginTx(ctx, nil)if err != nil {return "", err@@ -769,7 +531,7 @@ func (s *Store) CreatePendingInstanceChangeHistory(ctx context.Context, prevScheSource: m.Source,Type: m.Type,Status: db.Pending,- Version: m.Version,+ Version: version,Description: m.Description,Statement: statement,SheetID: sheetID,