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: instance change history version (#15304)
Danny Xu6ae72e799c6c
diff --git a/backend/migrator/migrator.go b/backend/migrator/migrator.goindex 03d2f2de18..aa211da441 100644--- a/backend/migrator/migrator.go+++ b/backend/migrator/migrator.go@@ -20,7 +20,6 @@ import ("github.com/bytebase/bytebase/backend/common/log"dbdriver "github.com/bytebase/bytebase/backend/plugin/db""github.com/bytebase/bytebase/backend/store"- "github.com/bytebase/bytebase/backend/store/model"storepb "github.com/bytebase/bytebase/proto/generated-go/store")@@ -82,6 +81,19 @@ func MigrateSchema(ctx context.Context, storeDB *store.DB, storeInstance *store.CREATE UNIQUE INDEX IF NOT EXISTS idx_instance_change_history_unique_version ON instance_change_history (version);`); err != nil {return nil, err}+ if _, err := metadataDriver.GetDB().ExecContext(ctx, `+ UPDATE instance_change_history+ SET+ version = ARRAY_TO_STRING(+ (STRING_TO_ARRAY(+ SUBSTRING(version, 0, 15),+ '.'+ )::integer[])::text[],+ '.'+ )+ WHERE version LIKE '%-%';`); err != nil {+ return nil, err+ }verBefore, err := getLatestVersion(ctx, storeInstance)if err != nil {@@ -121,7 +133,7 @@ func initializeSchema(ctx context.Context, storeInstance *store.Store, metadataD}stmt := string(buf)- version := model.Version{Semantic: true, Version: cutoffSchemaVersion.String(), Suffix: time.Now().Format("20060102150405")}+ version := cutoffSchemaVersion.String()// Set role to database owner so that the schema owner and database owner are consistent.owner, err := getCurrentDatabaseOwner(ctx, metadataDriver)if err != nil {@@ -213,13 +225,13 @@ func getLatestVersion(ctx context.Context, storeInstance *store.Store) (semver.V// schema has already been applied. Thus emitting a warning here will assist debugging.slog.Warn("Found stale migration history",slog.String("status", string(h.Status)),- slog.String("version", h.Version.Version),+ slog.String("version", h.Version),)continue}- v, err := semver.Make(h.Version.Version)+ v, err := semver.Make(h.Version)if err != nil {- return semver.Version{}, errors.Wrapf(err, "invalid version %q", h.Version.Version)+ return semver.Version{}, errors.Wrapf(err, "invalid version %q", h.Version)}return v, nil}@@ -273,7 +285,7 @@ func migrate(ctx context.Context, storeInstance *store.Store, metadataDriver dbdreturn false, errors.Wrapf(err, "failed to read migration file %q", pv.filename)}slog.Info(fmt.Sprintf("Migrating %s...", pv.version))- version := model.Version{Semantic: true, Version: pv.version.String(), Suffix: time.Now().Format("20060102150405")}+ version := pv.version.String()if _, _, err := executeMigrationDefault(ctx, storeInstance, metadataDriver, string(buf), version); err != nil {return false, err}@@ -408,7 +420,7 @@ func getMinorVersions(names []string) ([]semver.Version, error) {}// executeMigrationDefault executes migration.-func executeMigrationDefault(ctx context.Context, stores *store.Store, driver dbdriver.Driver, statement string, version model.Version) (migrationHistoryID string, updatedSchema string, resErr error) {+func executeMigrationDefault(ctx context.Context, stores *store.Store, driver dbdriver.Driver, statement string, version string) (migrationHistoryID string, updatedSchema string, resErr error) {insertedID, err := beginMigration(ctx, stores, version)if err != nil {return "", "", errors.Wrapf(err, "failed to begin migration")@@ -433,7 +445,7 @@ func executeMigrationDefault(ctx context.Context, stores *store.Store, driver db}// beginMigration checks before executing migration and inserts a migration history record with pending status.-func beginMigration(ctx context.Context, stores *store.Store, version model.Version) (string, error) {+func beginMigration(ctx context.Context, stores *store.Store, version string) (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{@@ -444,17 +456,17 @@ func beginMigration(ctx context.Context, stores *store.Store, version model.VersmigrationHistory := list[0]switch migrationHistory.Status {case dbdriver.Done:- err := common.Errorf(common.MigrationAlreadyApplied, "already applied version %s, hint: the version might be duplicate, please check the version", version.Version)+ err := common.Errorf(common.MigrationAlreadyApplied, "already applied version %s, hint: the version might be duplicate, please check the version", version)slog.Debug(err.Error())// Force migrationreturn migrationHistory.UID, nilcase dbdriver.Pending:- err := errors.Errorf("version %s migration is already in progress", version.Version)+ err := errors.Errorf("version %s migration is already in progress", 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("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", version.Version)+ err := errors.Errorf("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", version)slog.Debug(err.Error())// For force migration, we will ignore the existing migration history and continue to migration.return migrationHistory.UID, nildiff --git a/backend/migrator/migrator_test.go b/backend/migrator/migrator_test.goindex da107b948e..67edb36782 100644--- a/backend/migrator/migrator_test.go+++ b/backend/migrator/migrator_test.go@@ -198,7 +198,7 @@ func TestMigrationCompatibility(t *testing.T) {histories, err := storeInstance.ListInstanceChangeHistoryForMigrator(ctx, &store.FindInstanceChangeHistoryMessage{})require.NoError(t, err)require.Len(t, histories, 1)- require.Equal(t, histories[0].Version.Version, releaseVersion.String())+ require.Equal(t, histories[0].Version, releaseVersion.String())// Check no migration after passing current version as the release cutoff version._, err = migrate(ctx, storeInstance, metadataDriver, releaseVersion)diff --git a/backend/store/instance_change_history.go b/backend/store/instance_change_history.goindex b16efdc00f..52e3888ef4 100644--- a/backend/store/instance_change_history.go+++ b/backend/store/instance_change_history.go@@ -7,14 +7,13 @@ import ("strings""github.com/bytebase/bytebase/backend/plugin/db"- "github.com/bytebase/bytebase/backend/store/model")// InstanceChangeHistoryMessage records the change history of an instance.// it deprecates the old MigrationHistory.type InstanceChangeHistoryMessage struct {Status db.MigrationStatus- Version model.Version+ Version stringExecutionDurationNs int64// Output only@@ -23,7 +22,7 @@ type InstanceChangeHistoryMessage struct {// FindInstanceChangeHistoryMessage is for listing a list of instance change history.type FindInstanceChangeHistoryMessage struct {- Version *model.Version+ Version *string}// UpdateInstanceChangeHistoryMessage is for updating an instance change history.@@ -49,7 +48,7 @@ func (s *Store) CreateInstanceChangeHistoryForMigrator(ctx context.Context, crea}// CreatePendingInstanceChangeHistory creates an instance change history.-func (s *Store) CreatePendingInstanceChangeHistoryForMigrator(ctx context.Context, version model.Version) (string, error) {+func (s *Store) CreatePendingInstanceChangeHistoryForMigrator(ctx context.Context, version string) (string, error) {tx, err := s.db.BeginTx(ctx, nil)if err != nil {return "", err@@ -84,15 +83,10 @@ func (*Store) createInstanceChangeHistoryImplForMigrator(ctx context.Context, tx) VALUES ($1, $2, $3)RETURNING id`- storedVersion, err := create.Version.Marshal()- if err != nil {- return "", err- }-var uid stringif err := tx.QueryRowContext(ctx, query,create.Status,- storedVersion,+ create.Version,create.ExecutionDurationNs,).Scan(&uid); err != nil {return "", err@@ -137,13 +131,10 @@ func (s *Store) UpdateInstanceChangeHistory(ctx context.Context, update *UpdateIfunc (s *Store) ListInstanceChangeHistoryForMigrator(ctx context.Context, find *FindInstanceChangeHistoryMessage) ([]*InstanceChangeHistoryMessage, error) {where, args := []string{"TRUE"}, []any{}if v := find.Version; v != nil {- storedVersion, err := find.Version.Marshal()- if err != nil {- return nil, err- }- where, args = append(where, fmt.Sprintf("version = $%d", len(args)+1)), append(args, storedVersion)+ where, args = append(where, fmt.Sprintf("version = $%d", len(args)+1)), append(args, *v)}+ // Ordering by ID is enough to ensure the correct version order.query := `SELECTid,@@ -168,21 +159,14 @@ func (s *Store) ListInstanceChangeHistoryForMigrator(ctx context.Context, find *var list []*InstanceChangeHistoryMessagefor rows.Next() {var changeHistory InstanceChangeHistoryMessage- var storedVersion stringif err := rows.Scan(&changeHistory.UID,&changeHistory.Status,- &storedVersion,+ &changeHistory.Version,&changeHistory.ExecutionDurationNs,); err != nil {return nil, err}- version, err := model.NewVersion(storedVersion)- if err != nil {- return nil, err- }- changeHistory.Version = version-list = append(list, &changeHistory)}if err := rows.Err(); err != nil {diff --git a/backend/store/model/change_history.go b/backend/store/model/change_history.godeleted file mode 100644index 79d8737fd2..0000000000--- a/backend/store/model/change_history.go+++ /dev/null@@ -1,83 +0,0 @@-package model--import (- "fmt"- "strconv"- "strings"-- "github.com/blang/semver/v4"- "github.com/pkg/errors"-)--// Version is the message representing the change history version.-type Version struct {- Semantic bool- Version string- Suffix string-}--// nonSemanticPrefix is the prefix for non-semantic version.-const nonSemanticPrefix = "0000.0000.0000-"--// NewVersion converts stored version to version.-func NewVersion(storedVersion string) (Version, error) {- if storedVersion == "" {- return Version{}, nil- }- if strings.HasPrefix(storedVersion, nonSemanticPrefix) {- return Version{- Version: strings.TrimPrefix(storedVersion, nonSemanticPrefix),- }, nil- }-- idx := strings.Index(storedVersion, "-")- if idx < 0 {- return Version{}, errors.Errorf("invalid stored version %q, version should contain '-'", storedVersion)- }- prefix, suffix := storedVersion[:idx], storedVersion[idx+1:]- parts := strings.Split(prefix, ".")- if len(parts) != 3 {- return Version{}, errors.Errorf("invalid stored version %q, version prefix %q should be in semantic version format", storedVersion, prefix)- }- major, err := strconv.Atoi(parts[0])- if err != nil {- return Version{}, errors.Errorf("invalid stored version %q, version prefix %q should be in semantic version format", storedVersion, prefix)- }- minor, err := strconv.Atoi(parts[1])- if err != nil {- return Version{}, errors.Errorf("invalid stored version %q, version prefix %q should be in semantic version format", storedVersion, prefix)- }- patch, err := strconv.Atoi(parts[2])- if err != nil {- return Version{}, errors.Errorf("invalid stored version %q, version prefix %q should be in semantic version format", storedVersion, prefix)- }- if major >= 10000 || minor >= 10000 || patch >= 10000 {- return Version{}, errors.Errorf("invalid stored version %q, major, minor, patch version of %q should be < 10000", storedVersion, prefix)- }- return Version{- Semantic: true,- Version: fmt.Sprintf("%d.%d.%d", major, minor, patch),- Suffix: suffix,- }, nil-}--// Marshal converts version to stored version format.-// Non-semantic version will have additional "0000.0000.0000-" prefix.-// Semantic version will add zero padding to MAJOR, MINOR, PATCH version with a timestamp suffix.-func (v *Version) Marshal() (string, error) {- if v.Version == "" {- return "", nil- }- if !v.Semantic {- return fmt.Sprintf("%s%s", nonSemanticPrefix, v.Version), nil- }- sv, err := semver.Make(v.Version)- if err != nil {- return "", err- }- major, minor, patch := fmt.Sprintf("%d", sv.Major), fmt.Sprintf("%d", sv.Minor), fmt.Sprintf("%d", sv.Patch)- if len(major) > 4 || len(minor) > 4 || len(patch) > 4 {- return "", errors.Errorf("invalid version %q, major, minor, patch version should be < 10000", v.Version)- }- return fmt.Sprintf("%04s.%04s.%04s-%s", major, minor, patch, v.Suffix), nil-}diff --git a/backend/store/model/change_history_test.go b/backend/store/model/change_history_test.godeleted file mode 100644index 346842e3fa..0000000000--- a/backend/store/model/change_history_test.go+++ /dev/null@@ -1,71 +0,0 @@-package model--import (- "testing"-- "github.com/stretchr/testify/require"-)--func TestToStoredVersion(t *testing.T) {- type test struct {- useSemanticVersion bool- version string- semanticVersionSuffix string- want string- wantErr string- }- tests := []test{- {false, "hello", "", "0000.0000.0000-hello", ""},- {false, "hello", "world", "0000.0000.0000-hello", ""},- {true, "hello", "world", "", "No Major.Minor.Patch elements found"},- {true, "v1.2.3", "world", "", "Invalid character(s) found in major number"},- {true, "1.10000.3", "world", "", "major, minor, patch version should be < 10000"},- {true, "1.2.3", "world", "0001.0002.0003-world", ""},- {true, "2021.1.13", "world", "2021.0001.0013-world", ""},- }- for _, tc := range tests {- version := Version{Semantic: tc.useSemanticVersion, Version: tc.version, Suffix: tc.semanticVersionSuffix}- got, err := version.Marshal()- if tc.wantErr != "" {- require.Contains(t, err.Error(), tc.wantErr)- continue- }- require.NoError(t, err)- require.Equal(t, tc.want, got)- }-}--func TestFromStoredVersion(t *testing.T) {- type test struct {- storedVersion string- wantUseSemanticVersion bool- wantVersion string- wantSemanticVersionSuffix string- wantErr string- }- tests := []test{- {"0000.0000.0000-hello", false, "hello", "", ""},- {"0001.0001.0000-hello", true, "1.1.0", "hello", ""},- {"2021.0001.0013-world", true, "2021.1.13", "world", ""},- {"2021.0001.0013-hello-world", true, "2021.1.13", "hello-world", ""},- {"2021.0001.0013", false, "", "", "should contain '-'"},- {"2021.0001.0013.1234-hello", false, "", "", "should be in semantic version"},- {"2021.0001-hello", false, "", "", "should be in semantic version"},- {"2a21.0001.0013-hello", false, "", "", "should be in semantic version"},- {"10000.0001.0000-hello", false, "", "", "should be < 10000"},- {"", false, "", "", ""},- {"hello", false, "", "", "should contain '-'"},- {"1.2.3", false, "", "", "should contain '-'"},- }- for _, tc := range tests {- version, err := NewVersion(tc.storedVersion)- if tc.wantErr != "" {- require.Contains(t, err.Error(), tc.wantErr)- continue- }- require.NoError(t, err)- require.Equal(t, tc.wantUseSemanticVersion, version.Semantic)- require.Equal(t, tc.wantVersion, version.Version)- require.Equal(t, tc.wantSemanticVersionSuffix, version.Suffix)- }-}