Skip to content

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

refactor: migrate to version model for schema version (#8593)

Danny Xu98ff2fe0f7e4
diff --git a/backend/api/gitops/legacy.go b/backend/api/gitops/legacy.go
index 848f5047c7..4bb7e34f24 100644
--- a/backend/api/gitops/legacy.go
+++ b/backend/api/gitops/legacy.go
@@ -1,6 +1,9 @@
package gitops
-import "github.com/bytebase/bytebase/backend/plugin/db"
+import (
+ "github.com/bytebase/bytebase/backend/plugin/db"
+ "github.com/bytebase/bytebase/backend/store/model"
+)
// migrationDetail is the detail for database migration such as Migrate, Data.
type migrationDetail struct {
@@ -14,7 +17,7 @@ type migrationDetail struct {
sheetID int
// schemaVersion is parsed from VCS file name.
// It is automatically generated in the UI workflow.
- schemaVersion string
+ schemaVersion model.Version
}
// MigrationFileYAMLDatabase contains the information of a database in a YAML
diff --git a/backend/api/gitops/webhook.go b/backend/api/gitops/webhook.go
index 9ccc422f97..3e74e54e6b 100644
--- a/backend/api/gitops/webhook.go
+++ b/backend/api/gitops/webhook.go
@@ -35,6 +35,7 @@ import (
mapperparser "github.com/bytebase/bytebase/backend/plugin/parser/mybatis/mapper"
"github.com/bytebase/bytebase/backend/plugin/parser/mybatis/mapper/ast"
"github.com/bytebase/bytebase/backend/plugin/vcs"
+ "github.com/bytebase/bytebase/backend/store/model"
// Register azure plugin.
"github.com/bytebase/bytebase/backend/plugin/vcs/azure"
@@ -1557,7 +1558,7 @@ func sortFilesBySchemaVersion(fileInfoList []fileInfo) []fileInfo {
if mi.Database < mj.Database {
return true
}
- if mi.Database == mj.Database && mi.Version < mj.Version {
+ if mi.Database == mj.Database && mi.Version.Version < mj.Version.Version {
return true
}
if mi.Database == mj.Database && mi.Version == mj.Version && mi.Type.GetVersionTypeSuffix() < mj.Type.GetVersionTypeSuffix() {
@@ -1582,7 +1583,7 @@ func (s *Service) createIssueFromMigrationDetailsV2(ctx context.Context, project
Type: changeType,
Target: fmt.Sprintf("projects/%s/deploymentConfigs/default", project.ResourceID),
Sheet: fmt.Sprintf("projects/%s/sheets/%d", project.ResourceID, migrationDetail.sheetID),
- SchemaVersion: migrationDetail.schemaVersion,
+ SchemaVersion: migrationDetail.schemaVersion.Version,
},
},
},
@@ -1630,7 +1631,7 @@ func (s *Service) createIssueFromMigrationDetailsV2(ctx context.Context, project
Type: getChangeType(migrationDetail.migrationType),
Target: fmt.Sprintf("instances/%s/databases/%s", database.InstanceID, database.DatabaseName),
Sheet: fmt.Sprintf("projects/%s/sheets/%d", project.ResourceID, migrationDetail.sheetID),
- SchemaVersion: migrationDetail.schemaVersion,
+ SchemaVersion: migrationDetail.schemaVersion.Version,
},
},
})
@@ -1992,7 +1993,7 @@ func (s *Service) prepareIssueFromFile(
{
migrationType: fileInfo.migrationInfo.Type,
sheetID: sheet.UID,
- schemaVersion: fmt.Sprintf("%s-%s", fileInfo.migrationInfo.Version, fileInfo.migrationInfo.Type.GetVersionTypeSuffix()),
+ schemaVersion: model.Version{Version: fmt.Sprintf("%s-%s", fileInfo.migrationInfo.Version.Version, fileInfo.migrationInfo.Type.GetVersionTypeSuffix())},
},
}, nil
}
@@ -2045,7 +2046,7 @@ func (s *Service) prepareIssueFromFile(
migrationType: fileInfo.migrationInfo.Type,
databaseID: db.UID,
sheetID: sheet.UID,
- schemaVersion: fmt.Sprintf("%s-%s", fileInfo.migrationInfo.Version, fileInfo.migrationInfo.Type.GetVersionTypeSuffix()),
+ schemaVersion: model.Version{Version: fmt.Sprintf("%s-%s", fileInfo.migrationInfo.Version.Version, fileInfo.migrationInfo.Type.GetVersionTypeSuffix())},
},
)
}
@@ -2083,14 +2084,14 @@ func (s *Service) prepareIssueFromFile(
migrationType: fileInfo.migrationInfo.Type,
databaseID: database.UID,
sheetID: sheet.UID,
- schemaVersion: fmt.Sprintf("%s-%s", fileInfo.migrationInfo.Version, fileInfo.migrationInfo.Type.GetVersionTypeSuffix()),
+ schemaVersion: model.Version{Version: fmt.Sprintf("%s-%s", fileInfo.migrationInfo.Version.Version, fileInfo.migrationInfo.Type.GetVersionTypeSuffix())},
},
)
}
return migrationDetailList, nil
}
- migrationVersion := fmt.Sprintf("%s-%s", fileInfo.migrationInfo.Version, fileInfo.migrationInfo.Type.GetVersionTypeSuffix())
+ migrationVersion := fmt.Sprintf("%s-%s", fileInfo.migrationInfo.Version.Version, fileInfo.migrationInfo.Type.GetVersionTypeSuffix())
if err := s.tryUpdateTasksFromModifiedFile(ctx, databases, fileInfo.item.FileName, migrationVersion, content, pushEvent); err != nil {
return nil, []*store.ActivityMessage{
getIgnoredFileActivityCreate(
diff --git a/backend/api/gitops/webhook_test.go b/backend/api/gitops/webhook_test.go
index 67d4e775a8..328b1c01f2 100644
--- a/backend/api/gitops/webhook_test.go
+++ b/backend/api/gitops/webhook_test.go
@@ -11,6 +11,7 @@ import (
"github.com/bytebase/bytebase/backend/plugin/db"
"github.com/bytebase/bytebase/backend/plugin/vcs"
"github.com/bytebase/bytebase/backend/store"
+ "github.com/bytebase/bytebase/backend/store/model"
storepb "github.com/bytebase/bytebase/proto/generated-go/store"
)
@@ -209,7 +210,7 @@ func TestGetFileInfo(t *testing.T) {
assert.Equal(t, fileTypeMigration, fileType)
want := &db.MigrationInfo{
- Version: "0001",
+ Version: model.Version{Version: "0001"},
Namespace: "db",
Database: "db",
Source: db.VCS,
@@ -241,7 +242,7 @@ func TestGetFileInfo(t *testing.T) {
assert.Equal(t, fileTypeMigration, fileType)
want := &db.MigrationInfo{
- Version: "0001",
+ Version: model.Version{Version: "0001"},
Namespace: "db",
Database: "db",
Source: db.VCS,
@@ -276,7 +277,7 @@ func TestGetFileInfo(t *testing.T) {
assert.Equal(t, fileTypeMigration, fileType)
want := &db.MigrationInfo{
- Version: "0001",
+ Version: model.Version{Version: "0001"},
Namespace: "db",
Database: "db",
Source: db.VCS,
diff --git a/backend/api/v1/database_service.go b/backend/api/v1/database_service.go
index 219cba1849..d85d593a55 100644
--- a/backend/api/v1/database_service.go
+++ b/backend/api/v1/database_service.go
@@ -30,7 +30,6 @@ import (
enterpriseAPI "github.com/bytebase/bytebase/backend/enterprise/api"
api "github.com/bytebase/bytebase/backend/legacyapi"
"github.com/bytebase/bytebase/backend/plugin/db"
- "github.com/bytebase/bytebase/backend/plugin/db/util"
"github.com/bytebase/bytebase/backend/plugin/parser/base"
"github.com/bytebase/bytebase/backend/plugin/parser/sql/ast"
pgrawparser "github.com/bytebase/bytebase/backend/plugin/parser/sql/engine/pg"
@@ -1091,21 +1090,6 @@ func convertToChangeHistories(h []*store.InstanceChangeHistoryMessage) ([]*v1pb.
}
func convertToChangeHistory(h *store.InstanceChangeHistoryMessage) (*v1pb.ChangeHistory, error) {
- schemaVersion := h.Version
- if h.Version != "" {
- _, version, _, err := util.FromStoredVersion(h.Version)
- if err != nil {
- slog.Error("failed to convert stored version for change history",
- slog.String("instance", h.InstanceID),
- slog.String("database", h.DatabaseName),
- slog.String("history", h.UID),
- slog.String("version", h.Version),
- log.BBError(err))
- } else {
- schemaVersion = version
- }
- }
-
v1pbHistory := &v1pb.ChangeHistory{
Name: fmt.Sprintf("%s%s/%s%s/%s%v", common.InstanceNamePrefix, h.InstanceID, common.DatabaseIDPrefix, h.DatabaseName, common.ChangeHistoryPrefix, h.UID),
Uid: h.UID,
@@ -1117,7 +1101,7 @@ func convertToChangeHistory(h *store.InstanceChangeHistoryMessage) (*v1pb.Change
Source: convertToChangeHistorySource(h.Source),
Type: convertToChangeHistoryType(h.Type),
Status: convertToChangeHistoryStatus(h.Status),
- Version: schemaVersion,
+ Version: h.Version.Version,
Description: h.Description,
Statement: h.Statement,
Schema: h.Schema,
@@ -1882,15 +1866,6 @@ func convertToDatabase(database *store.DatabaseMessage) *v1pb.Database {
if database.EffectiveEnvironmentID != "" {
effectiveEnvironment = fmt.Sprintf("%s%s", common.EnvironmentNamePrefix, database.EffectiveEnvironmentID)
}
- schemaVersion := database.SchemaVersion
- if database.SchemaVersion != "" {
- _, version, _, err := util.FromStoredVersion(database.SchemaVersion)
- if err != nil {
- schemaVersion = database.SchemaVersion
- } else {
- schemaVersion = version
- }
- }
return &v1pb.Database{
Name: fmt.Sprintf("instances/%s/databases/%s", database.InstanceID, database.DatabaseName),
Uid: fmt.Sprintf("%d", database.UID),
@@ -1899,7 +1874,7 @@ func convertToDatabase(database *store.DatabaseMessage) *v1pb.Database {
Project: fmt.Sprintf("%s%s", common.ProjectNamePrefix, database.ProjectID),
Environment: environment,
EffectiveEnvironment: effectiveEnvironment,
- SchemaVersion: schemaVersion,
+ SchemaVersion: database.SchemaVersion.Version,
Labels: database.GetEffectiveLabels(),
}
}
diff --git a/backend/api/v1/rollout_service_task.go b/backend/api/v1/rollout_service_task.go
index 37bb12bca4..776117fb45 100644
--- a/backend/api/v1/rollout_service_task.go
+++ b/backend/api/v1/rollout_service_task.go
@@ -993,12 +993,12 @@ func getOrDefaultSchemaVersion(v string) string {
if v != "" {
return v
}
- return common.DefaultMigrationVersion()
+ return common.DefaultMigrationVersion().Version
}
func getOrDefaultSchemaVersionWithSuffix(v string, suffix string) string {
if v != "" {
return v + suffix
}
- return common.DefaultMigrationVersion() + suffix
+ return common.DefaultMigrationVersion().Version + suffix
}
diff --git a/backend/common/util.go b/backend/common/util.go
index e901ae3425..b74430ba42 100644
--- a/backend/common/util.go
+++ b/backend/common/util.go
@@ -17,6 +17,8 @@ import (
"github.com/nyaruka/phonenumbers"
"github.com/pkg/errors"
+
+ "github.com/bytebase/bytebase/backend/store/model"
)
const (
@@ -105,8 +107,8 @@ func GetResourceDir(dataDir string) string {
// DefaultMigrationVersion returns the default migration version string.
// Use the current time in second to guarantee uniqueness in a monotonic increasing way.
// We cannot add task ID because tenant mode databases should use the same migration version string when applying a schema update.
-func DefaultMigrationVersion() string {
- return time.Now().Format("20060102150405")
+func DefaultMigrationVersion() model.Version {
+ return model.Version{Version: time.Now().Format("20060102150405")}
}
// ParseTemplateTokens parses the template and returns template tokens and their delimiters.
diff --git a/backend/migrator/migrator.go b/backend/migrator/migrator.go
index ee4890bd18..78c22c204d 100644
--- a/backend/migrator/migrator.go
+++ b/backend/migrator/migrator.go
@@ -12,6 +12,7 @@ import (
"sort"
"strconv"
"strings"
+ "time"
"github.com/blang/semver/v4"
"github.com/pkg/errors"
@@ -19,8 +20,8 @@ import (
"github.com/bytebase/bytebase/backend/common"
api "github.com/bytebase/bytebase/backend/legacyapi"
dbdriver "github.com/bytebase/bytebase/backend/plugin/db"
- "github.com/bytebase/bytebase/backend/plugin/db/util"
"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"
)
@@ -132,10 +133,7 @@ func initializeSchema(ctx context.Context, storeInstance *store.Store, metadataD
// We will create the database together with initial schema and data migration.
stmt := fmt.Sprintf("%s\n%s", buf, dataBuf)
- storedVersion, err := util.ToStoredVersion(true /* UseSemanticVersion */, cutoffSchemaVersion.String(), common.DefaultMigrationVersion())
- if err != nil {
- return err
- }
+ version := model.Version{Semantic: true, Version: cutoffSchemaVersion.String(), Suffix: time.Now().Format("20060102150405")}
if _, err := metadataDriver.GetDB().ExecContext(ctx, stmt); err != nil {
return err
}
@@ -150,7 +148,7 @@ func initializeSchema(ctx context.Context, storeInstance *store.Store, metadataD
Source: dbdriver.LIBRARY,
Type: dbdriver.Migrate,
Status: dbdriver.Done,
- Version: storedVersion,
+ Version: version,
Description: fmt.Sprintf("Initial migration version %s server version %s with file %s.", cutoffSchemaVersion, serverVersion, latestSchemaPath),
Statement: stmt,
Schema: stmt,
@@ -193,19 +191,15 @@ 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(fmt.Sprintf("Found %s migration history", h.Status),
slog.String("type", string(h.Type)),
- slog.String("version", h.Version),
+ slog.String("version", h.Version.Version),
slog.String("description", h.Description),
slog.String("statement", stmt),
)
continue
}
- _, version, _, err := util.FromStoredVersion(h.Version)
- if err != nil {
- return semver.Version{}, err
- }
- v, err := semver.Make(version)
+ v, err := semver.Make(h.Version.Version)
if err != nil {
- return semver.Version{}, errors.Wrapf(err, "invalid version %q", h.Version)
+ return semver.Version{}, errors.Wrapf(err, "invalid version %q", h.Version.Version)
}
return v, nil
}
@@ -339,19 +333,17 @@ func migrate(ctx context.Context, storeInstance *store.Store, metadataDriver dbd
}
slog.Info(fmt.Sprintf("Migrating %s...", pv.version))
mi := &dbdriver.MigrationInfo{
- InstanceID: nil,
- CreatorID: api.SystemBotID,
- ReleaseVersion: serverVersion,
- UseSemanticVersion: true,
- Version: pv.version.String(),
- SemanticVersionSuffix: common.DefaultMigrationVersion(),
- Namespace: databaseName,
- Database: databaseName,
- Environment: "", /* unused in execute migration */
- Source: dbdriver.LIBRARY,
- Type: dbdriver.Migrate,
- Description: fmt.Sprintf("Migrate version %s server version %s with files %s.", pv.version, serverVersion, pv.filename),
- Force: true,
+ 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 */
+ Source: dbdriver.LIBRARY,
+ Type: dbdriver.Migrate,
+ Description: fmt.Sprintf("Migrate version %s server version %s with files %s.", pv.version, serverVersion, pv.filename),
+ Force: true,
}
if _, _, err := utils.ExecuteMigrationDefault(ctx, ctx, storeInstance, metadataDriver, mi, string(buf), nil, dbdriver.ExecuteOptions{}); err != nil {
return err
@@ -428,19 +420,17 @@ func migrateDev(ctx context.Context, storeInstance *store.Store, metadataDriver
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.
mi := &dbdriver.MigrationInfo{
- InstanceID: nil,
- CreatorID: api.SystemBotID,
- ReleaseVersion: serverVersion,
- UseSemanticVersion: true,
- Version: cutoffSchemaVersion.String(),
- SemanticVersionSuffix: fmt.Sprintf("dev%s", m.version),
- Namespace: databaseName,
- Database: databaseName,
- Environment: "", /* unused in execute migration */
- Source: dbdriver.LIBRARY,
- Type: dbdriver.Migrate,
- Description: fmt.Sprintf("Migrate version %s server version %s with files %s.", m.version, serverVersion, m.filename),
- Force: true,
+ 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 */
+ Source: dbdriver.LIBRARY,
+ Type: dbdriver.Migrate,
+ Description: fmt.Sprintf("Migrate version %s server version %s with files %s.", m.version, serverVersion, m.filename),
+ Force: true,
}
if _, _, err := utils.ExecuteMigrationDefault(ctx, ctx, storeInstance, metadataDriver, mi, m.statement, nil, dbdriver.ExecuteOptions{}); err != nil {
return err
diff --git a/backend/migrator/migrator_test.go b/backend/migrator/migrator_test.go
index d736b2a1e6..2952211f98 100644
--- a/backend/migrator/migrator_test.go
+++ b/backend/migrator/migrator_test.go
@@ -12,7 +12,6 @@ import (
"github.com/bytebase/bytebase/backend/common"
dbdriver "github.com/bytebase/bytebase/backend/plugin/db"
_ "github.com/bytebase/bytebase/backend/plugin/db/pg"
- "github.com/bytebase/bytebase/backend/plugin/db/util"
"github.com/bytebase/bytebase/backend/resources/postgres"
"github.com/bytebase/bytebase/backend/store"
storepb "github.com/bytebase/bytebase/proto/generated-go/store"
@@ -204,9 +203,7 @@ func TestMigrationCompatibility(t *testing.T) {
})
require.NoError(t, err)
require.Len(t, histories, 1)
- _, version, _, err := util.FromStoredVersion(histories[0].Version)
- require.NoError(t, err)
- require.Equal(t, version, releaseVersion.String())
+ require.Equal(t, histories[0].Version.Version, releaseVersion.String())
// Check no migration after passing current version as the release cutoff version.
err = migrate(ctx, storeInstance, metadataDriver, releaseVersion, releaseVersion, common.ReleaseModeProd, serverVersion, databaseName)
diff --git a/backend/plugin/db/driver.go b/backend/plugin/db/driver.go
index dd769beebf..8bc4718fc6 100644
--- a/backend/plugin/db/driver.go
+++ b/backend/plugin/db/driver.go
@@ -16,6 +16,7 @@ import (
"github.com/pkg/errors"
"github.com/bytebase/bytebase/backend/plugin/parser/base"
+ "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"
)
@@ -146,7 +147,7 @@ type MigrationInfo struct {
CreatorID int
ReleaseVersion string
- Version string
+ Version model.Version
Namespace string
Database string
Environment string
@@ -158,14 +159,6 @@ type MigrationInfo struct {
IssueID string
// Payload contains JSON-encoded string of VCS push event if the migration is triggered by a VCS push event.
Payload *storepb.InstanceChangeHistoryPayload
- // UseSemanticVersion is whether version is a semantic version.
- // When UseSemanticVersion is set, version should be set to the format specified in Semantic Versioning 2.0.0 (https://semver.org/).
- // For example, for setting non-semantic version "hello", the values should be Version = "hello", UseSemanticVersion = false, SemanticVersionSuffix = "".
- // For setting semantic version "1.2.0", the values should be Version = "1.2.0", UseSemanticVersion = true, SemanticVersionSuffix = "20060102150405" (common.DefaultMigrationVersion).
- UseSemanticVersion bool
- // SemanticVersionSuffix should be set to timestamp format of "20060102150405" (common.DefaultMigrationVersion) if UseSemanticVersion is set.
- // Since stored version should be unique, we have to append a suffix if we allow users to baseline to the same semantic version for fixing schema drift.
- SemanticVersionSuffix string
// Force is used to execute migration disregarding any migration history with PENDING or FAILED status.
// This applies to BASELINE and MIGRATE types of migrations because most of these migrations are retry-able.
// We don't use force option for DATA type of migrations yet till there's customer needs.
@@ -228,7 +221,7 @@ func ParseMigrationInfo(filePath, filePathTemplate string, allowOmitDatabaseName
case "ENV_ID":
mi.Environment = matchList[index]
case "VERSION":
- mi.Version = matchList[index]
+ mi.Version = model.Version{Version: matchList[index]}
case "DB_NAME":
mi.Namespace = matchList[index]
mi.Database = matchList[index]
@@ -251,7 +244,7 @@ func ParseMigrationInfo(filePath, filePathTemplate string, allowOmitDatabaseName
}
}
- if mi.Version == "" {
+ if mi.Version.Version == "" {
return nil, errors.Errorf("file path %q does not contain {{VERSION}}, configured file path template %q", filePath, filePathTemplate)
}
if mi.Namespace == "" && !allowOmitDatabaseName {
diff --git a/backend/plugin/db/driver_test.go b/backend/plugin/db/driver_test.go
index e0b08fac61..a1abad30d3 100644
--- a/backend/plugin/db/driver_test.go
+++ b/backend/plugin/db/driver_test.go
@@ -6,6 +6,8 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
+
+ "github.com/bytebase/bytebase/backend/store/model"
)
func TestParseMigrationInfo(t *testing.T) {
@@ -22,7 +24,7 @@ func TestParseMigrationInfo(t *testing.T) {
filePath: "db1##001foo",
filePathTemplate: "{{DB_NAME}}##{{VERSION}}",
want: &MigrationInfo{
- Version: "001foo",
+ Version: model.Version{Version: "001foo"},
Namespace: "db1",
Database: "db1",
Environment: "",
@@ -37,7 +39,7 @@ func TestParseMigrationInfo(t *testing.T) {
filePath: "db foo_+-=_#!$.##1.2.3",
filePathTemplate: "{{DB_NAME}}##{{VERSION}}",
want: &MigrationInfo{
- Version: "1.2.3",
+ Version: model.Version{Version: "1.2.3"},
Namespace: "db foo_+-=_#!$.",
Database: "db foo_+-=_#!$.",
Environment: "",
@@ -52,7 +54,7 @@ func TestParseMigrationInfo(t *testing.T) {
filePath: "bytebase/db1##001foo",
filePathTemplate: "bytebase/{{DB_NAME}}##{{VERSION}}",
want: &MigrationInfo{
- Version: "001foo",
+ Version: model.Version{Version: "001foo"},
Namespace: "db1",
Database: "db1",
Environment: "",
@@ -67,7 +69,7 @@ func TestParseMigrationInfo(t *testing.T) {
filePath: "bytebase/dev/db1##001foo",
filePathTemplate: "bytebase/{{ENV_ID}}/{{DB_NAME}}##{{VERSION}}",
want: &MigrationInfo{
- Version: "001foo",
+ Version: model.Version{Version: "001foo"},
Namespace: "db1",
Database: "db1",
Environment: "dev",
@@ -82,7 +84,7 @@ func TestParseMigrationInfo(t *testing.T) {
filePath: "db1##001foo##create_t1",
filePathTemplate: "{{DB_NAME}}##{{VERSION}}##{{DESCRIPTION}}",
want: &MigrationInfo{
- Version: "001foo",
+ Version: model.Version{Version: "001foo"},
Namespace: "db1",
Database: "db1",
Environment: "",
@@ -97,7 +99,7 @@ func TestParseMigrationInfo(t *testing.T) {
filePath: "db1##001foo##migrate",
filePathTemplate: "{{DB_NAME}}##{{VERSION}}##{{TYPE}}",
want: &MigrationInfo{
- Version: "001foo",
+ Version: model.Version{Version: "001foo"},
Namespace: "db1",
Database: "db1",
Environment: "",
@@ -112,7 +114,7 @@ func TestParseMigrationInfo(t *testing.T) {
filePath: "db1##001foo##ddl",
filePathTemplate: "{{DB_NAME}}##{{VERSION}}##{{TYPE}}",
want: &MigrationInfo{
- Version: "001foo",
+ Version: model.Version{Version: "001foo"},
Namespace: "db1",
Database: "db1",
Environment: "",
@@ -127,7 +129,7 @@ func TestParseMigrationInfo(t *testing.T) {
filePath: "db1##001foo##dml",
filePathTemplate: "{{DB_NAME}}##{{VERSION}}##{{TYPE}}",
want: &MigrationInfo{
- Version: "001foo",
+ Version: model.Version{Version: "001foo"},
Namespace: "db1",
Database: "db1",
Environment: "",
@@ -142,7 +144,7 @@ func TestParseMigrationInfo(t *testing.T) {
filePath: "db_shop1##001foo##data",
filePathTemplate: "{{DB_NAME}}##{{VERSION}}##{{TYPE}}",
want: &MigrationInfo{
- Version: "001foo",
+ Version: model.Version{Version: "001foo"},
Namespace: "db_shop1",
Database: "db_shop1",
Environment: "",
@@ -157,7 +159,7 @@ func TestParseMigrationInfo(t *testing.T) {
filePath: "db_shop1##001foo##data##fix_customer_info",
filePathTemplate: "{{DB_NAME}}##{{VERSION}}##{{TYPE}}##{{DESCRIPTION}}",
want: &MigrationInfo{
- Version: "001foo",
+ Version: model.Version{Version: "001foo"},
Namespace: "db_shop1",
Database: "db_shop1",
Environment: "",
@@ -172,7 +174,7 @@ func TestParseMigrationInfo(t *testing.T) {
filePath: ".db##20220811.sql",
filePathTemplate: ".{{DB_NAME}}##{{VERSION}}.sql",
want: &MigrationInfo{
- Version: "20220811",
+ Version: model.Version{Version: "20220811"},
Namespace: "db",
Database: "db",
Environment: "",
@@ -187,7 +189,7 @@ func TestParseMigrationInfo(t *testing.T) {
filePath: "db1##001foo##baseline",
filePathTemplate: "{{DB_NAME}}##{{VERSION}}##{{TYPE}}",
want: &MigrationInfo{
- Version: "001foo",
+ Version: model.Version{Version: "001foo"},
Namespace: "db1",
Database: "db1",
Environment: "",
@@ -222,7 +224,7 @@ func TestParseMigrationInfo(t *testing.T) {
filePathTemplate: "{{VERSION}}##{{TYPE}}",
allowOmitDatabaseName: true,
want: &MigrationInfo{
- Version: "001foo",
+ Version: model.Version{Version: "001foo"},
Source: VCS,
Type: Migrate,
Description: "Create schema migration",
diff --git a/backend/runner/schemasync/syncer.go b/backend/runner/schemasync/syncer.go
index 33839e8fb1..e58dce5a68 100644
--- a/backend/runner/schemasync/syncer.go
+++ b/backend/runner/schemasync/syncer.go
@@ -22,8 +22,8 @@ import (
"github.com/bytebase/bytebase/backend/component/state"
enterpriseAPI "github.com/bytebase/bytebase/backend/enterprise/api"
api "github.com/bytebase/bytebase/backend/legacyapi"
- "github.com/bytebase/bytebase/backend/plugin/db/util"
"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"
)
@@ -359,7 +359,7 @@ func (s *Syncer) SyncDatabaseSchema(ctx context.Context, database *store.Databas
}
setClassificationAndUserCommentFromComment(databaseMetadata)
- var patchSchemaVersion *string
+ var patchSchemaVersion *model.Version
if 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).
@@ -438,18 +438,8 @@ func (s *Syncer) SyncDatabaseSchema(ctx context.Context, database *store.Databas
latestSchema := string(rawDump)
if len(list) > 0 {
if list[0].Schema != latestSchema {
- _, version, _, err := util.FromStoredVersion(list[0].Version)
- if err != nil {
- slog.Error("failed to convert stored version",
- slog.String("instance", instance.ResourceID),
- slog.String("database", database.DatabaseName),
- slog.String("version", list[0].Version),
- log.BBError(err))
-
- return nil
- }
anomalyPayload := api.AnomalyDatabaseSchemaDriftPayload{
- Version: version,
+ Version: list[0].Version.Version,
Expect: list[0].Schema,
Actual: latestSchema,
}
diff --git a/backend/runner/taskrun/data_update_executor.go b/backend/runner/taskrun/data_update_executor.go
index 54241e0a55..165bd63063 100644
--- a/backend/runner/taskrun/data_update_executor.go
+++ b/backend/runner/taskrun/data_update_executor.go
@@ -14,6 +14,7 @@ import (
api "github.com/bytebase/bytebase/backend/legacyapi"
"github.com/bytebase/bytebase/backend/plugin/db"
"github.com/bytebase/bytebase/backend/store"
+ "github.com/bytebase/bytebase/backend/store/model"
)
// NewDataUpdateExecutor creates a data update (DML) task executor.
@@ -49,5 +50,6 @@ func (exec *DataUpdateExecutor) RunOnce(ctx context.Context, driverCtx context.C
if err != nil {
return true, nil, err
}
- return runMigration(ctx, driverCtx, exec.store, exec.dbFactory, exec.activityManager, exec.license, exec.stateCfg, exec.profile, task, db.Data, statement, payload.SchemaVersion, &payload.SheetID)
+ version := model.Version{Version: payload.SchemaVersion}
+ return runMigration(ctx, driverCtx, exec.store, exec.dbFactory, exec.activityManager, exec.license, exec.stateCfg, exec.profile, task, db.Data, statement, version, &payload.SheetID)
}
diff --git a/backend/runner/taskrun/database_create_executor.go b/backend/runner/taskrun/database_create_executor.go
index d5b80a79b3..a473427690 100644
--- a/backend/runner/taskrun/database_create_executor.go
+++ b/backend/runner/taskrun/database_create_executor.go
@@ -19,6 +19,7 @@ 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"
)
@@ -211,29 +212,36 @@ 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, &api.TaskRunResultPayload{
Detail: fmt.Sprintf("Created database %q", payload.DatabaseName),
MigrationID: "",
- Version: peerSchemaVersion,
+ Version: storedVersion,
}, nil
}
-func (exec *DatabaseCreateExecutor) createInitialSchema(ctx context.Context, driverCtx context.Context, environment *store.EnvironmentMessage, instance *store.InstanceMessage, project *store.ProjectMessage, task *store.TaskMessage, database *store.DatabaseMessage) (string, string, error) {
+func (exec *DatabaseCreateExecutor) createInitialSchema(ctx context.Context, driverCtx context.Context, environment *store.EnvironmentMessage, instance *store.InstanceMessage, project *store.ProjectMessage, task *store.TaskMessage, database *store.DatabaseMessage) (model.Version, string, error) {
if project.TenantMode != api.TenantModeTenant {
- return "", "", nil
+ return model.Version{}, "", nil
}
schemaVersion, schema, err := exec.getSchemaFromPeerTenantDatabase(ctx, exec.store, exec.dbFactory, instance, project, database)
if err != nil {
- return "", "", err
+ return model.Version{}, "", err
}
if schema == "" {
- return "", "", nil
+ return model.Version{}, "", nil
}
driver, err := exec.dbFactory.GetAdminDatabaseDriver(ctx, instance, database)
if err != nil {
- return "", "", err
+ return model.Version{}, "", err
}
defer driver.Close(ctx)
@@ -284,7 +292,7 @@ func (exec *DatabaseCreateExecutor) createInitialSchema(ctx context.Context, dri
}
if _, _, err := utils.ExecuteMigrationDefault(ctx, driverCtx, exec.store, driver, mi, schema, nil, db.ExecuteOptions{}); err != nil {
- return "", "", err
+ return model.Version{}, "", err
}
return schemaVersion, schema, nil
}
@@ -320,13 +328,13 @@ 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 (*DatabaseCreateExecutor) getSchemaFromPeerTenantDatabase(ctx context.Context, stores *store.Store, dbFactory *dbfactory.DBFactory, instance *store.InstanceMessage, project *store.ProjectMessage, database *store.DatabaseMessage) (string, string, error) {
+func (*DatabaseCreateExecutor) getSchemaFromPeerTenantDatabase(ctx context.Context, stores *store.Store, dbFactory *dbfactory.DBFactory, instance *store.InstanceMessage, project *store.ProjectMessage, database *store.DatabaseMessage) (model.Version, string, error) {
allDatabases, err := stores.ListDatabases(ctx, &store.FindDatabaseMessage{
ProjectID: &project.ResourceID,
Engine: &instance.Engine,
})
if err != nil {
- return "", "", errors.Wrapf(err, "Failed to fetch databases in project ID: %v", project.UID)
+ return model.Version{}, "", errors.Wrapf(err, "Failed to fetch databases in project ID: %v", project.UID)
}
var databases []*store.DatabaseMessage
for _, d := range allDatabases {
@@ -337,43 +345,43 @@ func (*DatabaseCreateExecutor) getSchemaFromPeerTenantDatabase(ctx context.Conte
deploymentConfig, err := stores.GetDeploymentConfigV2(ctx, project.UID)
if err != nil {
- return "", "", errors.Wrapf(err, "Failed to fetch deployment config for project ID: %v", project.UID)
+ return model.Version{}, "", errors.Wrapf(err, "Failed to fetch deployment config for project ID: %v", project.UID)
}
apiDeploymentConfig, err := deploymentConfig.ToAPIDeploymentConfig()
if err != nil {
- return "", "", errors.Wrapf(err, "Failed to convert deployment config for project ID: %v", project.UID)
+ return model.Version{}, "", errors.Wrapf(err, "Failed to convert deployment config for project ID: %v", project.UID)
}
deploySchedule, err := api.ValidateAndGetDeploymentSchedule(apiDeploymentConfig.Payload)
if err != nil {
- return "", "", errors.Errorf("Failed to get deployment schedule")
+ return model.Version{}, "", errors.Errorf("Failed to get deployment schedule")
}
matrix, err := utils.GetDatabaseMatrixFromDeploymentSchedule(deploySchedule, databases)
if err != nil {
- return "", "", errors.Errorf("Failed to create deployment pipeline")
+ return model.Version{}, "", errors.Errorf("Failed to create deployment pipeline")
}
similarDB := getPeerTenantDatabase(matrix, instance.EnvironmentID)
if similarDB == nil {
- return "", "", nil
+ return model.Version{}, "", nil
}
similarDBInstance, err := stores.GetInstanceV2(ctx, &store.FindInstanceMessage{ResourceID: &similarDB.InstanceID})
if err != nil {
- return "", "", err
+ return model.Version{}, "", err
}
driver, err := dbFactory.GetAdminDatabaseDriver(ctx, similarDBInstance, similarDB)
if err != nil {
- return "", "", err
+ return model.Version{}, "", err
}
defer driver.Close(ctx)
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)
+ return model.Version{}, "", errors.Wrapf(err, "failed to get migration history for database %q", similarDB.DatabaseName)
}
var schemaBuf bytes.Buffer
if _, err := driver.Dump(ctx, &schemaBuf, true /* schemaOnly */); err != nil {
- return "", "", err
+ return model.Version{}, "", err
}
return schemaVersion, schemaBuf.String(), nil
}
diff --git a/backend/runner/taskrun/executor.go b/backend/runner/taskrun/executor.go
index 5dfecddb58..60ef2eb349 100644
--- a/backend/runner/taskrun/executor.go
+++ b/backend/runner/taskrun/executor.go
@@ -24,10 +24,10 @@ import (
api "github.com/bytebase/bytebase/backend/legacyapi"
"github.com/bytebase/bytebase/backend/plugin/db"
"github.com/bytebase/bytebase/backend/plugin/db/mysql"
- "github.com/bytebase/bytebase/backend/plugin/db/util"
"github.com/bytebase/bytebase/backend/plugin/parser/sql/transform"
vcsPlugin "github.com/bytebase/bytebase/backend/plugin/vcs"
"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"
)
@@ -64,7 +64,7 @@ func RunExecutorOnce(ctx context.Context, driverCtx context.Context, exec Execut
return exec.RunOnce(ctx, driverCtx, task)
}
-func getMigrationInfo(ctx context.Context, stores *store.Store, profile config.Profile, task *store.TaskMessage, migrationType db.MigrationType, statement, schemaVersion string) (*db.MigrationInfo, error) {
+func getMigrationInfo(ctx context.Context, stores *store.Store, profile config.Profile, task *store.TaskMessage, migrationType db.MigrationType, statement string, schemaVersion model.Version) (*db.MigrationInfo, error) {
instance, err := stores.GetInstanceV2(ctx, &store.FindInstanceMessage{UID: &task.InstanceID})
if err != nil {
return nil, err
@@ -87,13 +87,12 @@ func getMigrationInfo(ctx context.Context, stores *store.Store, profile config.P
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,
- Payload: &storepb.InstanceChangeHistoryPayload{},
+ Version: schemaVersion,
+ Description: task.Name,
+ Environment: environment.ResourceID,
+ Database: database.DatabaseName,
+ Namespace: database.DatabaseName,
+ Payload: &storepb.InstanceChangeHistoryPayload{},
}
plans, err := stores.ListPlans(ctx, &store.FindPlanMessage{PipelineID: &task.PipelineID})
@@ -418,18 +417,11 @@ func postMigration(ctx context.Context, stores *store.Store, activityManager *ac
return true, nil, errors.Errorf("failed to find linked repository for database %q", database.DatabaseName)
}
- storeVersion, err := util.ToStoredVersion(false, mi.Version, "")
- if err != nil {
- slog.Error("Convert to stored version",
- slog.String("version", mi.Version),
- log.BBError(err),
- )
- }
if mi.Type == db.Migrate || mi.Type == db.MigrateSDL {
if _, err := stores.UpdateDatabase(ctx, &store.UpdateDatabaseMessage{
InstanceID: instance.ResourceID,
DatabaseName: database.DatabaseName,
- SchemaVersion: &storeVersion,
+ SchemaVersion: &mi.Version,
}, api.SystemBotID); err != nil {
return true, nil, errors.Errorf("failed to update database %q for instance %q", database.DatabaseName, instance.ResourceID)
}
@@ -462,7 +454,7 @@ func postMigration(ctx context.Context, stores *store.Store, activityManager *ac
vcs, err := stores.GetExternalVersionControlV2(ctx, repo.VCSUID)
if err != nil {
- return true, nil, errors.Errorf("failed to sync schema file %s after applying migration %s to %q", latestSchemaFile, mi.Version, database.DatabaseName)
+ return true, nil, errors.Errorf("failed to sync schema file %s after applying migration %s to %q", latestSchemaFile, mi.Version.Version, database.DatabaseName)
}
if vcs == nil {
return true, nil, errors.Errorf("VCS ID not found: %d", repo.VCSUID)
@@ -508,7 +500,7 @@ func postMigration(ctx context.Context, stores *store.Store, activityManager *ac
Type: api.ActivityPipelineTaskFileCommit,
Level: api.ActivityInfo,
Comment: fmt.Sprintf("Committed the latest schema after applying migration version %s to %q.",
- mi.Version,
+ mi.Version.Version,
mi.Database,
),
Payload: string(payload),
@@ -560,16 +552,23 @@ func postMigration(ctx context.Context, stores *store.Store, activityManager *ac
log.BBError(err))
}
- detail := fmt.Sprintf("Applied migration version %s to database %q.", mi.Version, database.DatabaseName)
+ detail := fmt.Sprintf("Applied migration version %s to database %q.", mi.Version.Version, database.DatabaseName)
if mi.Type == db.Baseline {
- detail = fmt.Sprintf("Established baseline version %s for database %q.", mi.Version, database.DatabaseName)
+ detail = fmt.Sprintf("Established baseline version %s for database %q.", mi.Version.Version, database.DatabaseName)
}
+ storedVersion, err := mi.Version.Marshal()
+ if err != nil {
+ slog.Error("failed to convert database schema version",
+ slog.String("version", mi.Version.Version),
+ log.BBError(err),
+ )
+ }
return true, &api.TaskRunResultPayload{
Detail: detail,
MigrationID: migrationID,
ChangeHistory: fmt.Sprintf("instances/%s/databases/%s/changeHistories/%s", instance.ResourceID, database.DatabaseName, migrationID),
- Version: mi.Version,
+ Version: storedVersion,
}, nil
}
@@ -636,7 +635,7 @@ func isWriteBack(ctx context.Context, stores *store.Store, license enterpriseAPI
return branch, nil
}
-func runMigration(ctx context.Context, driverCtx context.Context, store *store.Store, dbFactory *dbfactory.DBFactory, activityManager *activity.Manager, license enterpriseAPI.LicenseService, stateCfg *state.State, profile config.Profile, task *store.TaskMessage, migrationType db.MigrationType, statement, schemaVersion string, sheetID *int) (terminated bool, result *api.TaskRunResultPayload, err error) {
+func runMigration(ctx context.Context, driverCtx context.Context, store *store.Store, dbFactory *dbfactory.DBFactory, activityManager *activity.Manager, license enterpriseAPI.LicenseService, stateCfg *state.State, profile config.Profile, task *store.TaskMessage, migrationType db.MigrationType, statement string, schemaVersion model.Version, sheetID *int) (terminated bool, result *api.TaskRunResultPayload, err error) {
mi, err := getMigrationInfo(ctx, store, profile, task, migrationType, statement, schemaVersion)
if err != nil {
return true, nil, err
@@ -693,7 +692,7 @@ func writeBackLatestSchema(
if mi.Type == db.Baseline {
commitMessage = fmt.Sprintf("[Bytebase] establish baseline for %q", mi.Database)
} else {
- commitTitle := fmt.Sprintf("[Bytebase] %s latest schema for %q after migration %s", verb, mi.Database, mi.Version)
+ commitTitle := fmt.Sprintf("[Bytebase] %s latest schema for %q after migration %s", verb, mi.Database, mi.Version.Version)
commitBody := "THIS COMMIT IS AUTO-GENERATED BY BYTEBASE"
if bytebaseURL != "" {
commitBody += "\n\n" + bytebaseURL
@@ -752,7 +751,7 @@ func writeBackLatestSchema(
schemaFileCommit,
)
if err != nil {
- return "", errors.Wrapf(err, "failed to create file after applying migration %s to %q", mi.Version, mi.Database)
+ return "", errors.Wrapf(err, "failed to create file after applying migration %s to %q", mi.Version.Version, mi.Database)
}
} else {
slog.Debug("Update latest schema file",
@@ -776,7 +775,7 @@ func writeBackLatestSchema(
schemaFileCommit,
)
if err != nil {
- return "", errors.Wrapf(err, "failed to create file after applying migration %s to %q", mi.Version, mi.Database)
+ return "", errors.Wrapf(err, "failed to create file after applying migration %s to %q", mi.Version.Version, mi.Database)
}
}
diff --git a/backend/runner/taskrun/pitr_restore_executor.go b/backend/runner/taskrun/pitr_restore_executor.go
index e2c15680ff..b9c5139fd1 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/store/model"
"github.com/bytebase/bytebase/backend/utils"
storepb "github.com/bytebase/bytebase/proto/generated-go/store"
)
@@ -173,11 +174,18 @@ func (exec *PITRRestoreExecutor) doBackupRestore(ctx context.Context, stores *st
)
}
+ storedVersion, err := version.Marshal()
+ if err != nil {
+ slog.Error("failed to convert database schema version",
+ slog.String("version", version.Version),
+ log.BBError(err),
+ )
+ }
return &api.TaskRunResultPayload{
Detail: fmt.Sprintf("Restored database %q from backup %q", targetDatabase.DatabaseName, backup.Name),
MigrationID: migrationID,
ChangeHistory: fmt.Sprintf("instances/%s/databases/%s/changeHistories/%s", instance.ResourceID, targetDatabase.DatabaseName, migrationID),
- Version: version,
+ Version: storedVersion,
}, nil
}
@@ -510,18 +518,18 @@ func downloadBackupFileFromCloud(ctx context.Context, s3Client *bbs3.Client, bac
// all migration history from source database because that might be expensive (e.g. we may use restore to
// create many ephemeral databases from backup for testing purpose)
// Returns migration history id and the version on success.
-func createBranchMigrationHistory(ctx context.Context, stores *store.Store, dbFactory *dbfactory.DBFactory, profile config.Profile, targetInstance *store.InstanceMessage, sourceDatabase, targetDatabase *store.DatabaseMessage, backup *store.BackupMessage, task *store.TaskMessage) (string, string, error) {
+func createBranchMigrationHistory(ctx context.Context, stores *store.Store, dbFactory *dbfactory.DBFactory, profile config.Profile, targetInstance *store.InstanceMessage, sourceDatabase, targetDatabase *store.DatabaseMessage, backup *store.BackupMessage, task *store.TaskMessage) (string, model.Version, error) {
targetInstanceEnvironment, err := stores.GetEnvironmentV2(ctx, &store.FindEnvironmentMessage{ResourceID: &targetDatabase.EffectiveEnvironmentID})
if err != nil {
- return "", "", err
+ return "", model.Version{}, err
}
targetDatabaseProject, err := stores.GetProjectV2(ctx, &store.FindProjectMessage{ResourceID: &targetDatabase.ProjectID})
if err != nil {
- return "", "", err
+ return "", model.Version{}, err
}
issue, err := stores.GetIssueV2(ctx, &store.FindIssueMessage{PipelineID: &task.PipelineID})
if err != nil {
- return "", "", errors.Wrapf(err, "failed to fetch containing issue when creating the migration history: %v", task.Name)
+ return "", model.Version{}, errors.Wrapf(err, "failed to fetch containing issue when creating the migration history: %v", task.Name)
}
// Add a branch migration history record.
issueID := ""
@@ -534,7 +542,7 @@ func createBranchMigrationHistory(ctx context.Context, stores *store.Store, dbFa
}
creator, err := stores.GetUserByID(ctx, task.CreatorID)
if err != nil {
- return "", "", err
+ return "", model.Version{}, err
}
// TODO(d): support semantic versioning.
@@ -555,13 +563,13 @@ func createBranchMigrationHistory(ctx context.Context, stores *store.Store, dbFa
}
targetDriver, err := dbFactory.GetAdminDatabaseDriver(ctx, targetInstance, targetDatabase)
if err != nil {
- return "", "", err
+ return "", model.Version{}, err
}
defer targetDriver.Close(ctx)
migrationID, _, err := utils.ExecuteMigrationDefault(ctx, ctx, stores, targetDriver, m, "", nil, db.ExecuteOptions{})
if err != nil {
- return "", "", errors.Wrap(err, "failed to create migration history")
+ return "", model.Version{}, errors.Wrap(err, "failed to create migration history")
}
return migrationID, m.Version, nil
}
diff --git a/backend/runner/taskrun/schema_baseline_executor.go b/backend/runner/taskrun/schema_baseline_executor.go
index a2d3246336..8cbe804ef0 100644
--- a/backend/runner/taskrun/schema_baseline_executor.go
+++ b/backend/runner/taskrun/schema_baseline_executor.go
@@ -17,6 +17,7 @@ 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"
)
// NewSchemaBaselineExecutor creates a schema baseline task executor.
@@ -59,7 +60,8 @@ func (exec *SchemaBaselineExecutor) RunOnce(ctx context.Context, driverCtx conte
return true, nil, err
}
- terminated, result, err := runMigration(ctx, driverCtx, exec.store, exec.dbFactory, exec.activityManager, exec.license, exec.stateCfg, exec.profile, task, db.Baseline, "" /* statement */, payload.SchemaVersion, nil /* sheetID */)
+ version := model.Version{Version: payload.SchemaVersion}
+ terminated, result, err := runMigration(ctx, driverCtx, exec.store, exec.dbFactory, exec.activityManager, exec.license, exec.stateCfg, exec.profile, task, db.Baseline, "" /* statement */, version, nil /* sheetID */)
if err := exec.schemaSyncer.SyncDatabaseSchema(ctx, database, true /* force */); err != nil {
slog.Error("failed to sync database schema",
slog.String("instanceName", instance.ResourceID),
diff --git a/backend/runner/taskrun/schema_update_executor.go b/backend/runner/taskrun/schema_update_executor.go
index 3b0065f6e4..77a38fc9d2 100644
--- a/backend/runner/taskrun/schema_update_executor.go
+++ b/backend/runner/taskrun/schema_update_executor.go
@@ -17,6 +17,7 @@ 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"
)
// NewSchemaUpdateExecutor creates a schema update (DDL) task executor.
@@ -64,7 +65,8 @@ func (exec *SchemaUpdateExecutor) RunOnce(ctx context.Context, driverCtx context
return true, nil, err
}
- terminated, result, err := runMigration(ctx, driverCtx, exec.store, exec.dbFactory, exec.activityManager, exec.license, exec.stateCfg, exec.profile, task, db.Migrate, statement, payload.SchemaVersion, &payload.SheetID)
+ version := model.Version{Version: payload.SchemaVersion}
+ terminated, result, err := runMigration(ctx, driverCtx, exec.store, exec.dbFactory, exec.activityManager, exec.license, exec.stateCfg, exec.profile, task, db.Migrate, statement, version, &payload.SheetID)
if err := exec.schemaSyncer.SyncDatabaseSchema(ctx, database, true /* force */); err != nil {
slog.Error("failed to sync database schema",
slog.String("instanceName", instance.ResourceID),
diff --git a/backend/runner/taskrun/schema_update_ghost_cutover_executor.go b/backend/runner/taskrun/schema_update_ghost_cutover_executor.go
index 6268f7ae8c..d9c9f87614 100644
--- a/backend/runner/taskrun/schema_update_ghost_cutover_executor.go
+++ b/backend/runner/taskrun/schema_update_ghost_cutover_executor.go
@@ -23,6 +23,7 @@ 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"
)
@@ -98,7 +99,8 @@ func (e *SchemaUpdateGhostCutoverExecutor) RunOnce(ctx context.Context, _ contex
sharedGhost := value.(sharedGhostState)
// not using the rendered statement here because we want to avoid leaking the rendered statement
- terminated, result, err := cutover(ctx, e.store, e.dbFactory, e.activityManager, e.license, e.profile, task, statement, payload.SheetID, payload.SchemaVersion, postponeFilename, sharedGhost.migrationContext, sharedGhost.errCh)
+ version := model.Version{Version: payload.SchemaVersion}
+ terminated, result, err := cutover(ctx, e.store, e.dbFactory, e.activityManager, e.license, e.profile, task, statement, payload.SheetID, version, postponeFilename, sharedGhost.migrationContext, sharedGhost.errCh)
if err := e.schemaSyncer.SyncDatabaseSchema(ctx, database, true /* force */); err != nil {
slog.Error("failed to sync database schema",
slog.String("instanceName", instance.ResourceID),
@@ -110,7 +112,7 @@ func (e *SchemaUpdateGhostCutoverExecutor) RunOnce(ctx context.Context, _ contex
return terminated, result, err
}
-func cutover(ctx context.Context, stores *store.Store, dbFactory *dbfactory.DBFactory, activityManager *activity.Manager, license enterpriseAPI.LicenseService, profile config.Profile, task *store.TaskMessage, statement string, sheetID int, schemaVersion string, postponeFilename string, migrationContext *base.MigrationContext, errCh <-chan error) (terminated bool, result *api.TaskRunResultPayload, err error) {
+func cutover(ctx context.Context, stores *store.Store, dbFactory *dbfactory.DBFactory, activityManager *activity.Manager, license enterpriseAPI.LicenseService, profile config.Profile, task *store.TaskMessage, statement string, sheetID int, schemaVersion model.Version, postponeFilename string, migrationContext *base.MigrationContext, errCh <-chan error) (terminated bool, result *api.TaskRunResultPayload, err error) {
statement = strings.TrimSpace(statement)
instance, err := stores.GetInstanceV2(ctx, &store.FindInstanceMessage{UID: &task.InstanceID})
if err != nil {
diff --git a/backend/runner/taskrun/schema_update_sdl_executor.go b/backend/runner/taskrun/schema_update_sdl_executor.go
index a67d5de172..8d8ed6fc7a 100644
--- a/backend/runner/taskrun/schema_update_sdl_executor.go
+++ b/backend/runner/taskrun/schema_update_sdl_executor.go
@@ -18,6 +18,7 @@ import (
"github.com/bytebase/bytebase/backend/runner/schemasync"
"github.com/bytebase/bytebase/backend/runner/utils"
"github.com/bytebase/bytebase/backend/store"
+ "github.com/bytebase/bytebase/backend/store/model"
backendutils "github.com/bytebase/bytebase/backend/utils"
)
@@ -70,11 +71,12 @@ func (exec *SchemaUpdateSDLExecutor) RunOnce(ctx context.Context, driverCtx cont
// To avoid leaking the rendered statement, the error message should use the original statement and not the rendered statement.
renderedStatement := backendutils.RenderStatement(statement, materials)
+ version := model.Version{Version: payload.SchemaVersion}
ddl, err := utils.ComputeDatabaseSchemaDiff(ctx, instance, database, exec.dbFactory, renderedStatement)
if err != nil {
return true, nil, errors.Wrap(err, "invalid database schema diff")
}
- terminated, result, err := runMigration(ctx, driverCtx, exec.store, exec.dbFactory, exec.activityManager, exec.license, exec.stateCfg, exec.profile, task, db.MigrateSDL, ddl, payload.SchemaVersion, &payload.SheetID)
+ terminated, result, err := runMigration(ctx, driverCtx, exec.store, exec.dbFactory, exec.activityManager, exec.license, exec.stateCfg, exec.profile, task, db.MigrateSDL, ddl, version, &payload.SheetID)
if err := exec.schemaSyncer.SyncDatabaseSchema(ctx, database, true /* force */); err != nil {
slog.Error("failed to sync database schema",
diff --git a/backend/store/backup.go b/backend/store/backup.go
index 0f16f04a86..602630cbce 100644
--- a/backend/store/backup.go
+++ b/backend/store/backup.go
@@ -12,6 +12,7 @@ import (
"github.com/bytebase/bytebase/backend/common"
api "github.com/bytebase/bytebase/backend/legacyapi"
+ "github.com/bytebase/bytebase/backend/store/model"
)
// BackupSettingsMatchMessage is the message to find backup settings matching the conditions.
@@ -133,7 +134,7 @@ type BackupMessage struct {
// Storage Backend is the storage backend of the backup.
StorageBackend api.BackupStorageBackend
// MigrationHistoryVersion is the migration history version of the database.
- MigrationHistoryVersion string
+ MigrationHistoryVersion model.Version
// Path is the path of the backup file.
Path string
@@ -338,6 +339,10 @@ func (s *Store) ListBackupSettingV2(ctx context.Context, find *FindBackupSetting
// CreateBackupV2 creates a backup for the given database.
func (s *Store) CreateBackupV2(ctx context.Context, create *BackupMessage, databaseUID int, principalUID int) (*BackupMessage, error) {
+ storedVersion, err := create.MigrationHistoryVersion.Marshal()
+ if err != nil {
+ return nil, err
+ }
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return nil, errors.Wrapf(err, "failed to begin transaction")
@@ -357,7 +362,7 @@ func (s *Store) CreateBackupV2(ctx context.Context, create *BackupMessage, datab
comment
)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
- RETURNING id, row_status, name, storage_backend, migration_history_version, path, created_ts, updated_ts, status, type, comment, database_id
+ RETURNING id, row_status, name, storage_backend, path, created_ts, updated_ts, status, type, comment, database_id
`
var backup BackupMessage
if err := tx.QueryRowContext(ctx, query,
@@ -368,7 +373,7 @@ func (s *Store) CreateBackupV2(ctx context.Context, create *BackupMessage, datab
create.Status,
create.BackupType,
create.StorageBackend,
- create.MigrationHistoryVersion,
+ storedVersion,
create.Path,
create.Comment,
).Scan(
@@ -376,7 +381,6 @@ func (s *Store) CreateBackupV2(ctx context.Context, create *BackupMessage, datab
&backup.RowStatus,
&backup.Name,
&backup.StorageBackend,
- &backup.MigrationHistoryVersion,
&backup.Path,
&backup.CreatedTs,
&backup.UpdatedTs,
@@ -499,6 +503,7 @@ func (s *Store) UpdateBackupV2(ctx context.Context, patch *UpdateBackupMessage)
var backup BackupMessage
var payload []byte
+ var storedVersion string
// Execute update query with RETURNING.
if err := tx.QueryRowContext(ctx, fmt.Sprintf(`
UPDATE backup
@@ -517,7 +522,7 @@ func (s *Store) UpdateBackupV2(ctx context.Context, patch *UpdateBackupMessage)
&backup.Status,
&backup.BackupType,
&backup.StorageBackend,
- &backup.MigrationHistoryVersion,
+ &storedVersion,
&backup.Path,
&backup.Comment,
&payload,
@@ -531,6 +536,11 @@ func (s *Store) UpdateBackupV2(ctx context.Context, patch *UpdateBackupMessage)
if err := tx.Commit(); err != nil {
return nil, errors.Wrapf(err, "failed to commit transaction")
}
+ version, err := model.NewVersion(storedVersion)
+ if err != nil {
+ return nil, err
+ }
+ backup.MigrationHistoryVersion = version
if err := json.Unmarshal(payload, &backup.Payload); err != nil {
return nil, err
@@ -582,13 +592,13 @@ func (*Store) listBackupImplV2(ctx context.Context, tx *Tx, find *FindBackupMess
var backupList []*BackupMessage
for rows.Next() {
var backup BackupMessage
- var payload string
+ var storedVersion, payload string
if err := rows.Scan(
&backup.UID,
&backup.RowStatus,
&backup.Name,
&backup.StorageBackend,
- &backup.MigrationHistoryVersion,
+ &storedVersion,
&backup.Path,
&backup.CreatedTs,
&backup.UpdatedTs,
@@ -603,6 +613,12 @@ func (*Store) listBackupImplV2(ctx context.Context, tx *Tx, find *FindBackupMess
if err := json.Unmarshal([]byte(payload), &backup.Payload); err != nil {
return nil, err
}
+ version, err := model.NewVersion(storedVersion)
+ if err != nil {
+ return nil, err
+ }
+ backup.MigrationHistoryVersion = version
+
backupList = append(backupList, &backup)
}
if err := rows.Err(); err != nil {
diff --git a/backend/store/database.go b/backend/store/database.go
index 3a91fbe75c..b0e84d076a 100644
--- a/backend/store/database.go
+++ b/backend/store/database.go
@@ -11,6 +11,7 @@ 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"
)
@@ -25,7 +26,7 @@ type DatabaseMessage struct {
DatabaseName string
SyncState api.SyncStatus
SuccessfulSyncTimeTs int64
- SchemaVersion string
+ SchemaVersion model.Version
Secrets *storepb.Secrets
DataShare bool
// ServiceName is the Oracle specific field.
@@ -53,7 +54,7 @@ type UpdateDatabaseMessage struct {
ProjectID *string
SyncState *api.SyncStatus
SuccessfulSyncTimeTs *int64
- SchemaVersion *string
+ SchemaVersion *model.Version
SourceBackupID *int
Secrets *storepb.Secrets
DataShare *bool
@@ -265,6 +266,10 @@ func (s *Store) UpsertDatabase(ctx context.Context, create *DatabaseMessage) (*D
}
environmentUID = &environment.UID
}
+ storedVersion, err := create.SchemaVersion.Marshal()
+ if err != nil {
+ return nil, err
+ }
secretsString, err := protojson.Marshal(create.Secrets)
if err != nil {
@@ -316,7 +321,7 @@ func (s *Store) UpsertDatabase(ctx context.Context, create *DatabaseMessage) (*D
create.DatabaseName,
api.OK,
create.SuccessfulSyncTimeTs,
- create.SchemaVersion,
+ storedVersion,
secretsString,
create.DataShare,
create.ServiceName,
@@ -372,7 +377,11 @@ func (s *Store) UpdateDatabase(ctx context.Context, patch *UpdateDatabaseMessage
set, args = append(set, fmt.Sprintf("last_successful_sync_ts = $%d", len(args)+1)), append(args, *v)
}
if v := patch.SchemaVersion; v != nil {
- set, args = append(set, fmt.Sprintf("schema_version = $%d", len(args)+1)), append(args, *v)
+ 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)
@@ -557,7 +566,7 @@ func (*Store) listDatabaseImplV2(ctx context.Context, tx *Tx, find *FindDatabase
defer rows.Close()
for rows.Next() {
databaseMessage := &DatabaseMessage{}
- var secretsString, metadataString string
+ var storedVersion, secretsString, metadataString string
if err := rows.Scan(
&databaseMessage.UID,
&databaseMessage.ProjectID,
@@ -567,7 +576,7 @@ func (*Store) listDatabaseImplV2(ctx context.Context, tx *Tx, find *FindDatabase
&databaseMessage.DatabaseName,
&databaseMessage.SyncState,
&databaseMessage.SuccessfulSyncTimeTs,
- &databaseMessage.SchemaVersion,
+ &storedVersion,
&secretsString,
&databaseMessage.DataShare,
&databaseMessage.ServiceName,
@@ -575,6 +584,13 @@ func (*Store) listDatabaseImplV2(ctx context.Context, tx *Tx, find *FindDatabase
); err != nil {
return nil, err
}
+ version, err := model.NewVersion(storedVersion)
+ if err != nil {
+ // TODO(d): remove this fallback after data backfill.
+ databaseMessage.SchemaVersion = model.Version{Version: storedVersion}
+ } else {
+ databaseMessage.SchemaVersion = version
+ }
var secret storepb.Secrets
if err := protojson.Unmarshal([]byte(secretsString), &secret); err != nil {
return nil, err
diff --git a/backend/store/instance_change_history.go b/backend/store/instance_change_history.go
index e6b52e2fb3..41656acf71 100644
--- a/backend/store/instance_change_history.go
+++ b/backend/store/instance_change_history.go
@@ -16,6 +16,7 @@ import (
exprpb "google.golang.org/genproto/googleapis/api/expr/v1alpha1"
"github.com/bytebase/bytebase/backend/plugin/db"
+ "github.com/bytebase/bytebase/backend/store/model"
storepb "github.com/bytebase/bytebase/proto/generated-go/store"
)
@@ -35,7 +36,7 @@ type InstanceChangeHistoryMessage struct {
Source db.MigrationSource
Type db.MigrationType
Status db.MigrationStatus
- Version string
+ Version model.Version
Description string
Statement string
SheetID *int
@@ -64,7 +65,7 @@ type FindInstanceChangeHistoryMessage struct {
DatabaseID *int
SheetID *int
Source *db.MigrationSource
- Version *string
+ Version *model.Version
ResourcesFilter *string
Limit *int
Offset *int
@@ -131,6 +132,10 @@ func (*Store) createInstanceChangeHistoryImpl(ctx context.Context, tx *Tx, creat
if err != nil {
return "", err
}
+ storedVersion, err := create.Version.Marshal()
+ if err != nil {
+ return "", err
+ }
var uid string
if err := tx.QueryRowContext(ctx, query,
@@ -144,7 +149,7 @@ func (*Store) createInstanceChangeHistoryImpl(ctx context.Context, tx *Tx, creat
create.Source,
create.Type,
create.Status,
- create.Version,
+ storedVersion,
create.Description,
create.Statement,
create.Schema,
@@ -186,6 +191,10 @@ func (*Store) createInstanceChangeHistoryImplForMigrator(ctx context.Context, tx
if err != nil {
return "", err
}
+ storedVersion, err := create.Version.Marshal()
+ if err != nil {
+ return "", err
+ }
var uid string
if err := tx.QueryRowContext(ctx, query,
@@ -199,7 +208,7 @@ func (*Store) createInstanceChangeHistoryImplForMigrator(ctx context.Context, tx
create.Source,
create.Type,
create.Status,
- create.Version,
+ storedVersion,
create.Description,
create.Statement,
create.Schema,
@@ -457,7 +466,11 @@ func (s *Store) ListInstanceChangeHistory(ctx context.Context, find *FindInstanc
where, args = append(where, fmt.Sprintf("instance_change_history.source = $%d", len(args)+1)), append(args, *v)
}
if v := find.Version; v != nil {
- where, args = append(where, fmt.Sprintf("instance_change_history.version = $%d", len(args)+1)), append(args, *v)
+ 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)
@@ -534,7 +547,7 @@ func (s *Store) ListInstanceChangeHistory(ctx context.Context, find *FindInstanc
var list []*InstanceChangeHistoryMessage
for rows.Next() {
var changeHistory InstanceChangeHistoryMessage
- var rowStatus, payload string
+ var rowStatus, storedVersion, payload string
var instanceID, databaseID, issueID, sheetID sql.NullInt32
if err := rows.Scan(
&changeHistory.UID,
@@ -551,7 +564,7 @@ func (s *Store) ListInstanceChangeHistory(ctx context.Context, find *FindInstanc
&changeHistory.Source,
&changeHistory.Type,
&changeHistory.Status,
- &changeHistory.Version,
+ &storedVersion,
&changeHistory.Description,
&changeHistory.Statement,
&changeHistory.Schema,
@@ -580,6 +593,11 @@ func (s *Store) ListInstanceChangeHistory(ctx context.Context, find *FindInstanc
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 := protojson.Unmarshal([]byte(payload), changeHistory.Payload); err != nil {
return nil, err
@@ -693,7 +711,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, storedVersion, statement string, sheetID *int) (string, error) {
+func (s *Store) CreatePendingInstanceChangeHistory(ctx context.Context, prevSchema string, m *db.MigrationInfo, statement string, sheetID *int) (string, error) {
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return "", err
@@ -714,7 +732,7 @@ func (s *Store) CreatePendingInstanceChangeHistory(ctx context.Context, prevSche
Source: m.Source,
Type: m.Type,
Status: db.Pending,
- Version: storedVersion,
+ Version: m.Version,
Description: m.Description,
Statement: statement,
SheetID: sheetID,
@@ -765,7 +783,11 @@ func (s *Store) ListInstanceChangeHistoryForMigrator(ctx context.Context, find *
where, args = append(where, fmt.Sprintf("instance_change_history.source = $%d", len(args)+1)), append(args, *v)
}
if v := find.Version; v != nil {
- where, args = append(where, fmt.Sprintf("instance_change_history.version = $%d", len(args)+1)), append(args, *v)
+ 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)
}
statementField := fmt.Sprintf("LEFT(instance_change_history.statement, %d)", instanceChangeHistoryTruncateLength)
@@ -832,7 +854,7 @@ func (s *Store) ListInstanceChangeHistoryForMigrator(ctx context.Context, find *
var list []*InstanceChangeHistoryMessage
for rows.Next() {
var changeHistory InstanceChangeHistoryMessage
- var rowStatus, payload string
+ var rowStatus, storedVersion, payload string
var instanceID, databaseID, issueID sql.NullInt32
if err := rows.Scan(
&changeHistory.UID,
@@ -849,7 +871,7 @@ func (s *Store) ListInstanceChangeHistoryForMigrator(ctx context.Context, find *
&changeHistory.Source,
&changeHistory.Type,
&changeHistory.Status,
- &changeHistory.Version,
+ &storedVersion,
&changeHistory.Description,
&changeHistory.Statement,
&changeHistory.Schema,
@@ -877,6 +899,11 @@ func (s *Store) ListInstanceChangeHistoryForMigrator(ctx context.Context, find *
if err := protojson.Unmarshal([]byte(payload), changeHistory.Payload); err != nil {
return nil, err
}
+ version, err := model.NewVersion(storedVersion)
+ if err != nil {
+ return nil, err
+ }
+ changeHistory.Version = version
changeHistory.Deleted = convertRowStatusToDeleted(rowStatus)
list = append(list, &changeHistory)
diff --git a/backend/store/model/change_history.go b/backend/store/model/change_history.go
index 62c74ec97e..79d8737fd2 100644
--- a/backend/store/model/change_history.go
+++ b/backend/store/model/change_history.go
@@ -20,38 +20,41 @@ type Version struct {
const nonSemanticPrefix = "0000.0000.0000-"
// NewVersion converts stored version to version.
-func NewVersion(storedVersion string) (*Version, error) {
+func NewVersion(storedVersion string) (Version, error) {
+ if storedVersion == "" {
+ return Version{}, nil
+ }
if strings.HasPrefix(storedVersion, nonSemanticPrefix) {
- return &Version{
+ return Version{
Version: strings.TrimPrefix(storedVersion, nonSemanticPrefix),
}, nil
}
idx := strings.Index(storedVersion, "-")
if idx < 0 {
- return nil, errors.Errorf("invalid stored version %q, version should contain '-'", storedVersion)
+ 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 nil, errors.Errorf("invalid stored version %q, version prefix %q should be in semantic version format", storedVersion, prefix)
+ 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 nil, errors.Errorf("invalid stored version %q, version prefix %q should be in semantic version format", storedVersion, prefix)
+ 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 nil, errors.Errorf("invalid stored version %q, version prefix %q should be in semantic version format", storedVersion, prefix)
+ 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 nil, errors.Errorf("invalid stored version %q, version prefix %q should be in semantic version format", storedVersion, prefix)
+ 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 nil, errors.Errorf("invalid stored version %q, major, minor, patch version of %q should be < 10000", storedVersion, prefix)
+ return Version{}, errors.Errorf("invalid stored version %q, major, minor, patch version of %q should be < 10000", storedVersion, prefix)
}
- return &Version{
+ return Version{
Semantic: true,
Version: fmt.Sprintf("%d.%d.%d", major, minor, patch),
Suffix: suffix,
@@ -62,6 +65,9 @@ func NewVersion(storedVersion string) (*Version, error) {
// 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
}
diff --git a/backend/utils/utils.go b/backend/utils/utils.go
index 8663673281..6278e2255b 100644
--- a/backend/utils/utils.go
+++ b/backend/utils/utils.go
@@ -27,14 +27,14 @@ import (
api "github.com/bytebase/bytebase/backend/legacyapi"
"github.com/bytebase/bytebase/backend/plugin/app/relay"
"github.com/bytebase/bytebase/backend/plugin/db"
- "github.com/bytebase/bytebase/backend/plugin/db/util"
"github.com/bytebase/bytebase/backend/plugin/vcs"
"github.com/bytebase/bytebase/backend/store"
+ "github.com/bytebase/bytebase/backend/store/model"
storepb "github.com/bytebase/bytebase/proto/generated-go/store"
)
// GetLatestSchemaVersion gets the latest schema version for a database.
-func GetLatestSchemaVersion(ctx context.Context, stores *store.Store, instanceID int, databaseID int, databaseName string) (string, error) {
+func GetLatestSchemaVersion(ctx context.Context, stores *store.Store, instanceID int, databaseID int, databaseName string) (model.Version, error) {
// TODO(d): support semantic versioning.
limit := 1
history, err := stores.ListInstanceChangeHistory(ctx, &store.FindInstanceChangeHistoryMessage{
@@ -43,13 +43,12 @@ func GetLatestSchemaVersion(ctx context.Context, stores *store.Store, instanceID
Limit: &limit,
})
if err != nil {
- return "", errors.Wrapf(err, "failed to get migration history for database %q", databaseName)
+ return model.Version{}, errors.Wrapf(err, "failed to get migration history for database %q", databaseName)
}
- var schemaVersion string
- if len(history) == 1 {
- schemaVersion = history[0].Version
+ if len(history) == 0 {
+ return model.Version{}, nil
}
- return schemaVersion, nil
+ return history[0].Version, nil
}
// DataSourceFromInstanceWithType gets a typed data source from an instance.
@@ -470,27 +469,21 @@ 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 *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 {
- return "", errors.Wrap(err, "failed to convert to stored version")
- }
// Phase 1 - Pre-check before executing migration
// Check if the same migration version has already been applied.
if list, err := stores.ListInstanceChangeHistory(ctx, &store.FindInstanceChangeHistoryMessage{
InstanceID: m.InstanceID,
DatabaseID: m.DatabaseID,
- // TODO(d): support semantic versioning.
- Version: &storedVersion,
+ Version: &m.Version,
}); err != nil {
return "", errors.Wrap(err, "failed to check duplicate version")
} else if len(list) > 0 {
migrationHistory := list[0]
switch migrationHistory.Status {
case db.Done:
- return migrationHistory.UID, 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.Version)
case db.Pending:
- err := errors.Errorf("database %q version %s migration is already in progress", m.Database, m.Version)
+ err := errors.Errorf("database %q version %s migration is already in progress", m.Database, m.Version.Version)
slog.Debug(err.Error())
// For force migration, we will ignore the existing migration history and continue to migration.
if m.Force {
@@ -498,7 +491,7 @@ func BeginMigration(ctx context.Context, stores *store.Store, m *db.MigrationInf
}
return "", common.Wrap(err, common.MigrationPending)
case db.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)
+ 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)
slog.Debug(err.Error())
// For force migration, we will ignore the existing migration history and continue to migration.
if m.Force {
@@ -513,7 +506,7 @@ func BeginMigration(ctx context.Context, stores *store.Store, m *db.MigrationInf
// 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 := stores.CreatePendingInstanceChangeHistory(ctx, prevSchema, m, storedVersion, statementRecord, sheetID)
+ insertedID, err := stores.CreatePendingInstanceChangeHistory(ctx, prevSchema, m, statementRecord, sheetID)
if err != nil {
return "", err
}