Skip to content

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

refactor: clean legacy migration history (#8421)

Danny Xu9ad2bcfb51c2
diff --git a/backend/plugin/db/driver.go b/backend/plugin/db/driver.go
index 0f496e4bec..01a6bd84a9 100644
--- a/backend/plugin/db/driver.go
+++ b/backend/plugin/db/driver.go
@@ -15,7 +15,6 @@ import (
"github.com/pkg/errors"
- "github.com/bytebase/bytebase/backend/plugin/vcs"
storepb "github.com/bytebase/bytebase/proto/generated-go/store"
v1pb "github.com/bytebase/bytebase/proto/generated-go/v1"
)
@@ -175,11 +174,6 @@ const (
Failed MigrationStatus = "FAILED"
)
-// MigrationInfoPayload is the API message for migration info payload.
-type MigrationInfoPayload struct {
- VCSPushEvent *vcs.PushEvent `json:"pushEvent,omitempty"`
-}
-
// MigrationInfo is the API message for migration info.
type MigrationInfo struct {
// fields for instance change history
@@ -366,52 +360,6 @@ func ParseSchemaFileInfo(baseDirectory, schemaPathTemplate, file string) (*Migra
}, nil
}
-// MigrationHistory is the API message for migration history.
-// TODO(p0ny): migrate to instance change history.
-type MigrationHistory struct {
- ID string
-
- Creator string
- CreatedTs int64
- Updater string
- UpdatedTs int64
-
- ReleaseVersion string
- Namespace string
- Sequence int
- Source MigrationSource
- Type MigrationType
- Status MigrationStatus
- Version string
- Description string
- Statement string
- SheetID *int
- Schema string
- SchemaPrev string
- ExecutionDurationNs int64
- IssueID string
- Payload string
- UseSemanticVersion bool
- SemanticVersionSuffix string
-}
-
-// MigrationHistoryFind is the API message for finding migration histories.
-type MigrationHistoryFind struct {
- ID *string
-
- Database *string
- Source *MigrationSource
- Version *string
- ResourcesFilter *string
- // If specified, then it will only fetch "Limit" most recent migration histories
- Limit *int
- Offset *int
-
- // Fields below should be set if fetching from metaDB instance_change_history table.
- DatabaseID *int
- InstanceID *int
-}
-
// ConnectionConfig is the configuration for connections.
type ConnectionConfig struct {
Host string
diff --git a/backend/plugin/db/pg/migrate.go b/backend/plugin/db/pg/migrate.go
deleted file mode 100644
index ef998c8d8e..0000000000
--- a/backend/plugin/db/pg/migrate.go
+++ /dev/null
@@ -1,64 +0,0 @@
-package pg
-
-import (
- "context"
- "fmt"
-
- "github.com/bytebase/bytebase/backend/plugin/db"
- "github.com/bytebase/bytebase/backend/plugin/db/util"
-)
-
-// FindMigrationHistoryList finds the migration history.
-func (driver *Driver) FindMigrationHistoryList(ctx context.Context, find *db.MigrationHistoryFind) ([]*db.MigrationHistory, error) {
- baseQuery := `
- SELECT
- id,
- created_by,
- created_ts,
- updated_by,
- updated_ts,
- release_version,
- namespace,
- sequence,
- source,
- type,
- status,
- version,
- description,
- statement,
- ` + `"schema",` + `
- schema_prev,
- execution_duration_ns,
- issue_id,
- payload
- FROM migration_history `
- paramNames, params := []string{}, []any{}
- if v := find.ID; v != nil {
- paramNames, params = append(paramNames, "id"), append(params, *v)
- }
- if v := find.Database; v != nil {
- paramNames, params = append(paramNames, "namespace"), append(params, *v)
- }
- if v := find.Version; v != nil {
- // TODO(d): support semantic versioning.
- storedVersion, err := util.ToStoredVersion(false, *v, "")
- if err != nil {
- return nil, err
- }
- paramNames, params = append(paramNames, "version"), append(params, storedVersion)
- }
- if v := find.Source; v != nil {
- paramNames, params = append(paramNames, "source"), append(params, *v)
- }
- var query = baseQuery +
- db.FormatParamNameInNumberedPosition(paramNames) +
- `ORDER BY id DESC`
- if v := find.Limit; v != nil {
- query += fmt.Sprintf(" LIMIT %d", *v)
- }
- if v := find.Offset; v != nil {
- query += fmt.Sprintf(" OFFSET %d", *v)
- }
-
- return util.FindMigrationHistoryList(ctx, query, params, driver.db)
-}
diff --git a/backend/plugin/db/risingwave/migrate.go b/backend/plugin/db/risingwave/migrate.go
deleted file mode 100644
index 63bb31ad18..0000000000
--- a/backend/plugin/db/risingwave/migrate.go
+++ /dev/null
@@ -1,64 +0,0 @@
-package risingwave
-
-import (
- "context"
- "fmt"
-
- "github.com/bytebase/bytebase/backend/plugin/db"
- "github.com/bytebase/bytebase/backend/plugin/db/util"
-)
-
-// FindMigrationHistoryList finds the migration history.
-func (driver *Driver) FindMigrationHistoryList(ctx context.Context, find *db.MigrationHistoryFind) ([]*db.MigrationHistory, error) {
- baseQuery := `
- SELECT
- id,
- created_by,
- created_ts,
- updated_by,
- updated_ts,
- release_version,
- namespace,
- sequence,
- source,
- type,
- status,
- version,
- description,
- statement,
- ` + `"schema",` + `
- schema_prev,
- execution_duration_ns,
- issue_id,
- payload
- FROM migration_history `
- paramNames, params := []string{}, []any{}
- if v := find.ID; v != nil {
- paramNames, params = append(paramNames, "id"), append(params, *v)
- }
- if v := find.Database; v != nil {
- paramNames, params = append(paramNames, "namespace"), append(params, *v)
- }
- if v := find.Version; v != nil {
- // TODO(d): support semantic versioning.
- storedVersion, err := util.ToStoredVersion(false, *v, "")
- if err != nil {
- return nil, err
- }
- paramNames, params = append(paramNames, "version"), append(params, storedVersion)
- }
- if v := find.Source; v != nil {
- paramNames, params = append(paramNames, "source"), append(params, *v)
- }
- var query = baseQuery +
- db.FormatParamNameInNumberedPosition(paramNames) +
- `ORDER BY id DESC`
- if v := find.Limit; v != nil {
- query += fmt.Sprintf(" LIMIT %d", *v)
- }
- if v := find.Offset; v != nil {
- query += fmt.Sprintf(" OFFSET %d", *v)
- }
-
- return util.FindMigrationHistoryList(ctx, query, params, driver.db)
-}
diff --git a/backend/plugin/db/util/driverutil.go b/backend/plugin/db/util/driverutil.go
index 9487cfdf7d..c83532fda4 100644
--- a/backend/plugin/db/util/driverutil.go
+++ b/backend/plugin/db/util/driverutil.go
@@ -447,69 +447,6 @@ func getMySQLStatementWithResultLimit(stmt string, limit int) string {
return fmt.Sprintf("SELECT * FROM (%s) result LIMIT %d;", stmt, limit)
}
-// FindMigrationHistoryList will find the list of migration history.
-func FindMigrationHistoryList(ctx context.Context, findMigrationHistoryListQuery string, queryParams []any, sqldb *sql.DB) ([]*db.MigrationHistory, error) {
- // To support `pg` option, the util layer will not know which database where `migration_history` table is,
- // so we need to connect to the database provided by params.
- tx, err := sqldb.BeginTx(ctx, nil)
- if err != nil {
- return nil, err
- }
- defer tx.Rollback()
-
- rows, err := tx.QueryContext(ctx, findMigrationHistoryListQuery, queryParams...)
- if err != nil {
- return nil, FormatErrorWithQuery(err, findMigrationHistoryListQuery)
- }
- defer rows.Close()
-
- // Iterate over result set and deserialize rows into migrationHistoryList.
- var migrationHistoryList []*db.MigrationHistory
- for rows.Next() {
- var history db.MigrationHistory
- var storedVersion string
- if err := rows.Scan(
- &history.ID,
- &history.Creator,
- &history.CreatedTs,
- &history.Updater,
- &history.UpdatedTs,
- &history.ReleaseVersion,
- &history.Namespace,
- &history.Sequence,
- &history.Source,
- &history.Type,
- &history.Status,
- &storedVersion,
- &history.Description,
- &history.Statement,
- &history.Schema,
- &history.SchemaPrev,
- &history.ExecutionDurationNs,
- &history.IssueID,
- &history.Payload,
- ); err != nil {
- return nil, err
- }
-
- useSemanticVersion, version, semanticVersionSuffix, err := FromStoredVersion(storedVersion)
- if err != nil {
- return nil, err
- }
- history.UseSemanticVersion, history.Version, history.SemanticVersionSuffix = useSemanticVersion, version, semanticVersionSuffix
- migrationHistoryList = append(migrationHistoryList, &history)
- }
- if err := rows.Err(); err != nil {
- return nil, err
- }
-
- if err := tx.Commit(); err != nil {
- return nil, err
- }
-
- return migrationHistoryList, nil
-}
-
// NonSemanticPrefix is the prefix for non-semantic version.
const NonSemanticPrefix = "0000.0000.0000-"
diff --git a/backend/runner/rollbackrun/runner.go b/backend/runner/rollbackrun/runner.go
index 985316d215..2e93809311 100644
--- a/backend/runner/rollbackrun/runner.go
+++ b/backend/runner/rollbackrun/runner.go
@@ -285,7 +285,7 @@ func (r *Runner) generateMySQLRollbackSQLImpl(ctx context.Context, payload *api.
return "", errors.WithMessage(err, "failed to get admin database driver")
}
defer driver.Close(ctx)
- list, err := r.store.FindInstanceChangeHistoryList(ctx, &db.MigrationHistoryFind{InstanceID: &instance.UID, ID: &payload.MigrationID})
+ list, err := r.store.ListInstanceChangeHistory(ctx, &store.FindInstanceChangeHistoryMessage{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.go
index 0f57ef7401..4e2e075d0e 100644
--- a/backend/runner/schemasync/syncer.go
+++ b/backend/runner/schemasync/syncer.go
@@ -422,10 +422,9 @@ func (s *Syncer) SyncDatabaseSchema(ctx context.Context, database *store.Databas
return nil
}
limit := 1
- list, err := s.store.FindInstanceChangeHistoryList(ctx, &db.MigrationHistoryFind{
+ list, err := s.store.ListInstanceChangeHistory(ctx, &store.FindInstanceChangeHistoryMessage{
InstanceID: &instance.UID,
DatabaseID: &database.UID,
- Database: &database.DatabaseName,
Limit: &limit,
})
if err != nil {
diff --git a/backend/store/instance_change_history.go b/backend/store/instance_change_history.go
index cc6816b565..e6b52e2fb3 100644
--- a/backend/store/instance_change_history.go
+++ b/backend/store/instance_change_history.go
@@ -16,7 +16,6 @@ import (
exprpb "google.golang.org/genproto/googleapis/api/expr/v1alpha1"
"github.com/bytebase/bytebase/backend/plugin/db"
- "github.com/bytebase/bytebase/backend/plugin/db/util"
storepb "github.com/bytebase/bytebase/proto/generated-go/store"
)
@@ -214,94 +213,6 @@ func (*Store) createInstanceChangeHistoryImplForMigrator(ctx context.Context, tx
return uid, nil
}
-func convertInstanceChangeHistoryToMigrationHistory(change *InstanceChangeHistoryMessage) (*db.MigrationHistory, error) {
- var issueID string
- if v := change.IssueUID; v != nil {
- issueID = strconv.Itoa(*v)
- }
-
- useSemanticVersion, version, semanticVersionSuffix, err := util.FromStoredVersion(change.Version)
- if err != nil {
- return nil, err
- }
-
- payload, err := protojson.Marshal(change.Payload)
- if err != nil {
- return nil, err
- }
-
- return &db.MigrationHistory{
- ID: change.UID,
- Creator: "",
- CreatedTs: change.CreatedTs,
- Updater: "",
- UpdatedTs: change.UpdatedTs,
- ReleaseVersion: change.ReleaseVersion,
- Namespace: "",
- Sequence: int(change.Sequence),
- Source: change.Source,
- Type: change.Type,
- Status: change.Status,
- Version: version,
- Description: change.Description,
- Statement: change.Statement,
- Schema: change.Schema,
- SheetID: change.SheetID,
- SchemaPrev: change.SchemaPrev,
- ExecutionDurationNs: change.ExecutionDurationNs,
- IssueID: issueID,
- Payload: string(payload),
- UseSemanticVersion: useSemanticVersion,
- SemanticVersionSuffix: semanticVersionSuffix,
- }, nil
-}
-
-// FindInstanceChangeHistoryList finds a list of instance change history and returns as a list of migration history.
-func (s *Store) FindInstanceChangeHistoryList(ctx context.Context, find *db.MigrationHistoryFind) ([]*db.MigrationHistory, error) {
- findMessage := &FindInstanceChangeHistoryMessage{
- ID: find.ID,
- InstanceID: find.InstanceID,
- DatabaseID: find.DatabaseID,
- Source: find.Source,
- Version: find.Version,
- ResourcesFilter: find.ResourcesFilter,
- Limit: find.Limit,
- ShowFull: true,
- }
-
- list, err := s.ListInstanceChangeHistory(ctx, findMessage)
- if err != nil {
- return nil, err
- }
- var migrationHistoryList []*db.MigrationHistory
- for _, change := range list {
- migrationHistory, err := convertInstanceChangeHistoryToMigrationHistory(change)
- if err != nil {
- return nil, err
- }
- if change.DatabaseUID != nil {
- database, err := s.GetDatabaseV2(ctx, &FindDatabaseMessage{UID: change.DatabaseUID})
- 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.Name
- migrationHistoryList = append(migrationHistoryList, migrationHistory)
- }
-
- return migrationHistoryList, nil
-}
-
type resourceDatabase struct {
name string
schemas schemaMap
diff --git a/backend/utils/utils.go b/backend/utils/utils.go
index 0d110ee9c8..8663673281 100644
--- a/backend/utils/utils.go
+++ b/backend/utils/utils.go
@@ -34,17 +34,14 @@ import (
)
// GetLatestSchemaVersion gets the latest schema version for a database.
-func GetLatestSchemaVersion(ctx context.Context, store *store.Store, instanceID int, databaseID int, databaseName string) (string, error) {
+func GetLatestSchemaVersion(ctx context.Context, stores *store.Store, instanceID int, databaseID int, databaseName string) (string, error) {
// TODO(d): support semantic versioning.
limit := 1
- find := &db.MigrationHistoryFind{
+ history, err := stores.ListInstanceChangeHistory(ctx, &store.FindInstanceChangeHistoryMessage{
InstanceID: &instanceID,
- Database: &databaseName,
DatabaseID: &databaseID,
Limit: &limit,
- }
-
- history, err := store.FindInstanceChangeHistoryList(ctx, find)
+ })
if err != nil {
return "", errors.Wrapf(err, "failed to get migration history for database %q", databaseName)
}
@@ -472,7 +469,7 @@ 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, store *store.Store, m *db.MigrationInfo, prevSchema, statement string, sheetID *int) (string, error) {
+func BeginMigration(ctx context.Context, stores *store.Store, m *db.MigrationInfo, prevSchema, statement string, sheetID *int) (string, error) {
// Convert version to stored version.
storedVersion, err := util.ToStoredVersion(m.UseSemanticVersion, m.Version, m.SemanticVersionSuffix)
if err != nil {
@@ -480,7 +477,7 @@ func BeginMigration(ctx context.Context, store *store.Store, m *db.MigrationInfo
}
// Phase 1 - Pre-check before executing migration
// Check if the same migration version has already been applied.
- if list, err := store.FindInstanceChangeHistoryList(ctx, &db.MigrationHistoryFind{
+ if list, err := stores.ListInstanceChangeHistory(ctx, &store.FindInstanceChangeHistoryMessage{
InstanceID: m.InstanceID,
DatabaseID: m.DatabaseID,
// TODO(d): support semantic versioning.
@@ -491,16 +488,13 @@ func BeginMigration(ctx context.Context, store *store.Store, m *db.MigrationInfo
migrationHistory := list[0]
switch migrationHistory.Status {
case db.Done:
- if migrationHistory.IssueID != m.IssueID {
- return migrationHistory.ID, common.Errorf(common.MigrationFailed, "database %q has already applied version %s by issue %s", m.Database, m.Version, migrationHistory.IssueID)
- }
- return migrationHistory.ID, common.Errorf(common.MigrationAlreadyApplied, "database %q has already applied version %s", m.Database, m.Version)
+ return migrationHistory.UID, common.Errorf(common.MigrationAlreadyApplied, "database %q has already applied version %s", m.Database, m.Version)
case db.Pending:
err := errors.Errorf("database %q version %s migration is already in progress", m.Database, m.Version)
slog.Debug(err.Error())
// For force migration, we will ignore the existing migration history and continue to migration.
if m.Force {
- return migrationHistory.ID, nil
+ return migrationHistory.UID, nil
}
return "", common.Wrap(err, common.MigrationPending)
case db.Failed:
@@ -508,7 +502,7 @@ func BeginMigration(ctx context.Context, store *store.Store, m *db.MigrationInfo
slog.Debug(err.Error())
// For force migration, we will ignore the existing migration history and continue to migration.
if m.Force {
- return migrationHistory.ID, nil
+ return migrationHistory.UID, nil
}
return "", common.Wrap(err, common.MigrationFailed)
}
@@ -519,7 +513,7 @@ func BeginMigration(ctx context.Context, store *store.Store, m *db.MigrationInfo
// Thus we sort of doing a 2-phase commit, where we first write a PENDING migration record, and after migration completes, we then
// update the record to DONE together with the updated schema.
statementRecord, _ := common.TruncateString(statement, common.MaxSheetSize)
- insertedID, err := store.CreatePendingInstanceChangeHistory(ctx, prevSchema, m, storedVersion, statementRecord, sheetID)
+ insertedID, err := stores.CreatePendingInstanceChangeHistory(ctx, prevSchema, m, storedVersion, statementRecord, sheetID)
if err != nil {
return "", err
}