Skip to content

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

feat(migration): update the logic to check migration order and pre-validation (#955)

Danny Xu9f5b94a99a27
diff --git a/plugin/db/clickhouse/clickhouse.go b/plugin/db/clickhouse/clickhouse.go
index 4af45e4051..7389c95550 100644
--- a/plugin/db/clickhouse/clickhouse.go
+++ b/plugin/db/clickhouse/clickhouse.go
@@ -407,65 +407,50 @@ func (driver *Driver) SetupMigrationIfNeeded(ctx context.Context) error {
return nil
}
-// CheckOutOfOrderVersion will return versions that are higher than the given version.
-func (Driver) CheckOutOfOrderVersion(ctx context.Context, tx *sql.Tx, namespace string, source db.MigrationSource, version string) (minVersionIfValid *string, err error) {
- const checkOutofOrderVersionQuery = `
- SELECT MIN(version) FROM bytebase.migration_history
- WHERE namespace = $1 AND source = $2 AND version > $3
+// FindLargestVersionSinceBaseline will find the largest version since last baseline or branch.
+func (driver Driver) FindLargestVersionSinceBaseline(ctx context.Context, tx *sql.Tx, namespace string) (*string, error) {
+ largestBaselineSequence, err := driver.FindLargestSequence(ctx, tx, namespace, true /* baseline */)
+ if err != nil {
+ return nil, err
+ }
+ const getLargestVersionSinceLastBaselineQuery = `
+ SELECT MAX(version) FROM bytebase.migration_history
+ WHERE namespace = $1 AND sequence >= $2
`
- row, err := tx.QueryContext(ctx, checkOutofOrderVersionQuery,
- namespace, source.String(), version,
+ row, err := tx.QueryContext(ctx, getLargestVersionSinceLastBaselineQuery,
+ namespace, largestBaselineSequence,
)
if err != nil {
- return nil, util.FormatErrorWithQuery(err, checkOutofOrderVersionQuery)
+ return nil, util.FormatErrorWithQuery(err, getLargestVersionSinceLastBaselineQuery)
}
defer row.Close()
- var minVersion sql.NullString
+ var version sql.NullString
row.Next()
- if err := row.Scan(&minVersion); err != nil {
+ if err := row.Scan(&version); err != nil {
return nil, err
}
- if minVersion.Valid {
- return &minVersion.String, nil
+ if version.Valid {
+ return &version.String, nil
}
return nil, nil
}
-// FindBaseline retruns true if any baseline is found.
-func (Driver) FindBaseline(ctx context.Context, tx *sql.Tx, namespace string) (hasBaseline bool, err error) {
- const findBaselineQuery = `
- SELECT 1 FROM bytebase.migration_history
- WHERE namespace = $1 AND type = 'BASELINE'
- `
- row, err := tx.QueryContext(ctx, findBaselineQuery,
- namespace,
- )
- if err != nil {
- return false, util.FormatErrorWithQuery(err, findBaselineQuery)
- }
- defer row.Close()
-
- if !row.Next() {
- return false, nil
+// FindLargestSequence will return the largest sequence number.
+func (Driver) FindLargestSequence(ctx context.Context, tx *sql.Tx, namespace string, baseline bool) (int, error) {
+ findLargestSequenceQuery := `
+ SELECT MAX(sequence) FROM bytebase.migration_history
+ WHERE namespace = $1`
+ if baseline {
+ findLargestSequenceQuery = fmt.Sprintf("%s AND (type = '%s' OR type = '%s')", findLargestSequenceQuery, db.Baseline, db.Branch)
}
-
- return true, nil
-}
-
-// FindNextSequence will return the highest sequence number plus one.
-func (Driver) FindNextSequence(ctx context.Context, tx *sql.Tx, namespace string, requireBaseline bool) (int, error) {
- const findNextSequenceQuery = `
- SELECT MAX(sequence) + 1 FROM bytebase.migration_history
- WHERE namespace = $1
- `
- row, err := tx.QueryContext(ctx, findNextSequenceQuery,
+ row, err := tx.QueryContext(ctx, findLargestSequenceQuery,
namespace,
)
if err != nil {
- return -1, util.FormatErrorWithQuery(err, findNextSequenceQuery)
+ return -1, util.FormatErrorWithQuery(err, findLargestSequenceQuery)
}
defer row.Close()
@@ -476,13 +461,8 @@ func (Driver) FindNextSequence(ctx context.Context, tx *sql.Tx, namespace string
}
if !sequence.Valid {
- // Returns 1 if we haven't applied any migration for this namespace and doesn't require baselining
- if !requireBaseline {
- return 1, nil
- }
-
- // This should not happen normally since we already check the baselining exist beforehand. Just in case.
- return -1, common.Errorf(common.MigrationBaselineMissing, fmt.Errorf("unable to generate next migration_sequence, no migration hisotry found for %q, do you forget to baselining?", namespace))
+ // Returns 0 if we haven't applied any migration for this namespace.
+ return 0, nil
}
return int(sequence.Int32), nil
diff --git a/plugin/db/mysql/mysql.go b/plugin/db/mysql/mysql.go
index 9c0b0c304a..ca03699887 100644
--- a/plugin/db/mysql/mysql.go
+++ b/plugin/db/mysql/mysql.go
@@ -583,65 +583,50 @@ func (driver *Driver) SetupMigrationIfNeeded(ctx context.Context) error {
return nil
}
-// CheckOutOfOrderVersion will return versions that are higher than the given version.
-func (Driver) CheckOutOfOrderVersion(ctx context.Context, tx *sql.Tx, namespace string, source db.MigrationSource, version string) (minVersionIfValid *string, err error) {
- const checkOutOfOrderVersionQuery = `
- SELECT MIN(version) FROM bytebase.migration_history
- WHERE namespace = ? AND source = ? AND version > ?
- `
- row, err := tx.QueryContext(ctx, checkOutOfOrderVersionQuery,
- namespace, source.String(), version,
+// FindLargestVersionSinceBaseline will find the largest version since last baseline or branch.
+func (driver Driver) FindLargestVersionSinceBaseline(ctx context.Context, tx *sql.Tx, namespace string) (*string, error) {
+ largestBaselineSequence, err := driver.FindLargestSequence(ctx, tx, namespace, true /* baseline */)
+ if err != nil {
+ return nil, err
+ }
+ const getLargestVersionSinceLastBaselineQuery = `
+ SELECT MAX(version) FROM bytebase.migration_history
+ WHERE namespace = ? AND sequence >= ?
+ `
+ row, err := tx.QueryContext(ctx, getLargestVersionSinceLastBaselineQuery,
+ namespace, largestBaselineSequence,
)
if err != nil {
- return nil, util.FormatErrorWithQuery(err, checkOutOfOrderVersionQuery)
+ return nil, util.FormatErrorWithQuery(err, getLargestVersionSinceLastBaselineQuery)
}
defer row.Close()
- var minVersion sql.NullString
+ var version sql.NullString
row.Next()
- if err := row.Scan(&minVersion); err != nil {
+ if err := row.Scan(&version); err != nil {
return nil, err
}
- if minVersion.Valid {
- return &minVersion.String, nil
+ if version.Valid {
+ return &version.String, nil
}
return nil, nil
}
-// FindBaseline retruns true if any baseline is found.
-func (Driver) FindBaseline(ctx context.Context, tx *sql.Tx, namespace string) (hasBaseline bool, err error) {
- const findBaselineQuery = `
- SELECT 1 FROM bytebase.migration_history
- WHERE namespace = ? AND type = 'BASELINE'
- `
- row, err := tx.QueryContext(ctx, findBaselineQuery,
- namespace,
- )
- if err != nil {
- return false, util.FormatErrorWithQuery(err, findBaselineQuery)
- }
- defer row.Close()
-
- if !row.Next() {
- return false, nil
+// FindLargestSequence will return the largest sequence number.
+func (Driver) FindLargestSequence(ctx context.Context, tx *sql.Tx, namespace string, baseline bool) (int, error) {
+ findLargestSequenceQuery := `
+ SELECT MAX(sequence) FROM bytebase.migration_history
+ WHERE namespace = ?`
+ if baseline {
+ findLargestSequenceQuery = fmt.Sprintf("%s AND (type = '%s' OR type = '%s')", findLargestSequenceQuery, db.Baseline, db.Branch)
}
-
- return true, nil
-}
-
-// FindNextSequence will return the highest sequence number plus one.
-func (Driver) FindNextSequence(ctx context.Context, tx *sql.Tx, namespace string, requireBaseline bool) (int, error) {
- const findNextSequenceQuery = `
- SELECT MAX(sequence) + 1 FROM bytebase.migration_history
- WHERE namespace = ?
- `
- row, err := tx.QueryContext(ctx, findNextSequenceQuery,
+ row, err := tx.QueryContext(ctx, findLargestSequenceQuery,
namespace,
)
if err != nil {
- return -1, util.FormatErrorWithQuery(err, findNextSequenceQuery)
+ return -1, util.FormatErrorWithQuery(err, findLargestSequenceQuery)
}
defer row.Close()
@@ -652,13 +637,8 @@ func (Driver) FindNextSequence(ctx context.Context, tx *sql.Tx, namespace string
}
if !sequence.Valid {
- // Returns 1 if we haven't applied any migration for this namespace and doesn't require baselining
- if !requireBaseline {
- return 1, nil
- }
-
- // This should not happen normally since we already check the baselining exist beforehand. Just in case.
- return -1, common.Errorf(common.MigrationBaselineMissing, fmt.Errorf("unable to generate next migration_sequence, no migration history found for %q, do you forget to baselining?", namespace))
+ // Returns 0 if we haven't applied any migration for this namespace.
+ return 0, nil
}
return int(sequence.Int32), nil
diff --git a/plugin/db/pg/pg.go b/plugin/db/pg/pg.go
index bfdaaa135d..81f2317283 100644
--- a/plugin/db/pg/pg.go
+++ b/plugin/db/pg/pg.go
@@ -506,65 +506,50 @@ func (driver *Driver) SetupMigrationIfNeeded(ctx context.Context) error {
return nil
}
-// CheckOutOfOrderVersion will return versions that are higher than the given version.
-func (Driver) CheckOutOfOrderVersion(ctx context.Context, tx *sql.Tx, namespace string, source db.MigrationSource, version string) (minVersionIfValid *string, err error) {
- const checkOutofOrderVersionQuery = `
- SELECT MIN(version) FROM migration_history
- WHERE namespace = $1 AND source = $2 AND version > $3
+// FindLargestVersionSinceBaseline will find the largest version since last baseline or branch.
+func (driver Driver) FindLargestVersionSinceBaseline(ctx context.Context, tx *sql.Tx, namespace string) (*string, error) {
+ largestBaselineSequence, err := driver.FindLargestSequence(ctx, tx, namespace, true /* baseline */)
+ if err != nil {
+ return nil, err
+ }
+ const getLargestVersionSinceLastBaselineQuery = `
+ SELECT MAX(version) FROM migration_history
+ WHERE namespace = $1 AND sequence >= $2
`
- row, err := tx.QueryContext(ctx, checkOutofOrderVersionQuery,
- namespace, source.String(), version,
+ row, err := tx.QueryContext(ctx, getLargestVersionSinceLastBaselineQuery,
+ namespace, largestBaselineSequence,
)
if err != nil {
- return nil, util.FormatErrorWithQuery(err, checkOutofOrderVersionQuery)
+ return nil, util.FormatErrorWithQuery(err, getLargestVersionSinceLastBaselineQuery)
}
defer row.Close()
- var minVersion sql.NullString
+ var version sql.NullString
row.Next()
- if err := row.Scan(&minVersion); err != nil {
+ if err := row.Scan(&version); err != nil {
return nil, err
}
- if minVersion.Valid {
- return &minVersion.String, nil
+ if version.Valid {
+ return &version.String, nil
}
return nil, nil
}
-// FindBaseline retruns true if any baseline is found.
-func (Driver) FindBaseline(ctx context.Context, tx *sql.Tx, namespace string) (hasBaseline bool, err error) {
- const findBaselineQuery = `
- SELECT 1 FROM migration_history
- WHERE namespace = $1 AND type = 'BASELINE'
- `
- row, err := tx.QueryContext(ctx, findBaselineQuery,
- namespace,
- )
- if err != nil {
- return false, util.FormatErrorWithQuery(err, findBaselineQuery)
+// FindLargestSequence will return the largest sequence number.
+func (Driver) FindLargestSequence(ctx context.Context, tx *sql.Tx, namespace string, baseline bool) (int, error) {
+ findLargestSequenceQuery := `
+ SELECT MAX(sequence) FROM migration_history
+ WHERE namespace = $1`
+ if baseline {
+ findLargestSequenceQuery = fmt.Sprintf("%s AND (type = '%s' OR type = '%s')", findLargestSequenceQuery, db.Baseline, db.Branch)
}
- defer row.Close()
-
- if !row.Next() {
- return false, nil
- }
-
- return true, nil
-}
-
-// FindNextSequence will return the highest sequence number plus one.
-func (Driver) FindNextSequence(ctx context.Context, tx *sql.Tx, namespace string, requireBaseline bool) (int, error) {
- const findNextSequenceQuery = `
- SELECT MAX(sequence) + 1 FROM migration_history
- WHERE namespace = $1
- `
- row, err := tx.QueryContext(ctx, findNextSequenceQuery,
+ row, err := tx.QueryContext(ctx, findLargestSequenceQuery,
namespace,
)
if err != nil {
- return -1, util.FormatErrorWithQuery(err, findNextSequenceQuery)
+ return -1, util.FormatErrorWithQuery(err, findLargestSequenceQuery)
}
defer row.Close()
@@ -575,13 +560,8 @@ func (Driver) FindNextSequence(ctx context.Context, tx *sql.Tx, namespace string
}
if !sequence.Valid {
- // Returns 1 if we haven't applied any migration for this namespace and doesn't require baselining
- if !requireBaseline {
- return 1, nil
- }
-
- // This should not happen normally since we already check the baselining exist beforehand. Just in case.
- return -1, common.Errorf(common.MigrationBaselineMissing, fmt.Errorf("unable to generate next migration_sequence, no migration hisotry found for %q, do you forget to baselining?", namespace))
+ // Returns 0 if we haven't applied any migration for this namespace.
+ return 0, nil
}
return int(sequence.Int32), nil
diff --git a/plugin/db/snowflake/snowflake.go b/plugin/db/snowflake/snowflake.go
index e4f13a0c3b..8ecf0f703f 100644
--- a/plugin/db/snowflake/snowflake.go
+++ b/plugin/db/snowflake/snowflake.go
@@ -11,7 +11,6 @@ import (
// embed will embeds the migration schema.
_ "embed"
- "github.com/bytebase/bytebase/common"
"github.com/bytebase/bytebase/plugin/db"
"github.com/bytebase/bytebase/plugin/db/util"
snow "github.com/snowflakedb/gosnowflake"
@@ -583,65 +582,50 @@ func (driver *Driver) SetupMigrationIfNeeded(ctx context.Context) error {
return nil
}
-// CheckOutOfOrderVersion will return versions that are higher than the given version.
-func (Driver) CheckOutOfOrderVersion(ctx context.Context, tx *sql.Tx, namespace string, source db.MigrationSource, version string) (minVersionIfValid *string, err error) {
- const checkOutofOrderVersionQuery = `
- SELECT MIN(version) FROM bytebase.public.migration_history
- WHERE namespace = ? AND source = ? AND version > ?
+// FindLargestVersionSinceBaseline will find the largest version since last baseline or branch.
+func (driver Driver) FindLargestVersionSinceBaseline(ctx context.Context, tx *sql.Tx, namespace string) (*string, error) {
+ largestBaselineSequence, err := driver.FindLargestSequence(ctx, tx, namespace, true /* baseline */)
+ if err != nil {
+ return nil, err
+ }
+ const getLargestVersionSinceLastBaselineQuery = `
+ SELECT MAX(version) FROM bytebase.public.migration_history
+ WHERE namespace = ? AND sequence >= ?
`
- row, err := tx.QueryContext(ctx, checkOutofOrderVersionQuery,
- namespace, source.String(), version,
+ row, err := tx.QueryContext(ctx, getLargestVersionSinceLastBaselineQuery,
+ namespace, largestBaselineSequence,
)
if err != nil {
- return nil, util.FormatErrorWithQuery(err, checkOutofOrderVersionQuery)
+ return nil, util.FormatErrorWithQuery(err, getLargestVersionSinceLastBaselineQuery)
}
defer row.Close()
- var minVersion sql.NullString
+ var version sql.NullString
row.Next()
- if err := row.Scan(&minVersion); err != nil {
+ if err := row.Scan(&version); err != nil {
return nil, err
}
- if minVersion.Valid {
- return &minVersion.String, nil
+ if version.Valid {
+ return &version.String, nil
}
return nil, nil
}
-// FindBaseline retruns true if any baseline is found.
-func (Driver) FindBaseline(ctx context.Context, tx *sql.Tx, namespace string) (hasBaseline bool, err error) {
- const findBaselineQuery = `
- SELECT 1 FROM bytebase.public.migration_history
- WHERE namespace = ? AND type = 'BASELINE'
- `
- row, err := tx.QueryContext(ctx, findBaselineQuery,
- namespace,
- )
- if err != nil {
- return false, util.FormatErrorWithQuery(err, findBaselineQuery)
- }
- defer row.Close()
-
- if !row.Next() {
- return false, nil
+// FindLargestSequence will return the largest sequence number.
+func (Driver) FindLargestSequence(ctx context.Context, tx *sql.Tx, namespace string, baseline bool) (int, error) {
+ findLargestSequenceQuery := `
+ SELECT MAX(sequence) FROM bytebase.public.migration_history
+ WHERE namespace = ?`
+ if baseline {
+ findLargestSequenceQuery = fmt.Sprintf("%s AND (type = '%s' OR type = '%s')", findLargestSequenceQuery, db.Baseline, db.Branch)
}
-
- return true, nil
-}
-
-// FindNextSequence will return the highest sequence number plus one.
-func (Driver) FindNextSequence(ctx context.Context, tx *sql.Tx, namespace string, requireBaseline bool) (int, error) {
- const findNextSequenceQuery = `
- SELECT MAX(sequence) + 1 FROM bytebase.public.migration_history
- WHERE namespace = ?
- `
- row, err := tx.QueryContext(ctx, findNextSequenceQuery,
+ row, err := tx.QueryContext(ctx, findLargestSequenceQuery,
namespace,
)
if err != nil {
- return -1, util.FormatErrorWithQuery(err, findNextSequenceQuery)
+ return -1, util.FormatErrorWithQuery(err, findLargestSequenceQuery)
}
defer row.Close()
@@ -652,13 +636,8 @@ func (Driver) FindNextSequence(ctx context.Context, tx *sql.Tx, namespace string
}
if !sequence.Valid {
- // Returns 1 if we haven't applied any migration for this namespace and doesn't require baselining
- if !requireBaseline {
- return 1, nil
- }
-
- // This should not happen normally since we already check the baselining exist beforehand. Just in case.
- return -1, common.Errorf(common.MigrationBaselineMissing, fmt.Errorf("unable to generate next migration_sequence, no migration hisotry found for %q, do you forget to baselining?", namespace))
+ // Returns 0 if we haven't applied any migration for this namespace.
+ return 0, nil
}
return int(sequence.Int32), nil
diff --git a/plugin/db/sqlite/sqlite.go b/plugin/db/sqlite/sqlite.go
index 828b79f988..7ee44c74a6 100644
--- a/plugin/db/sqlite/sqlite.go
+++ b/plugin/db/sqlite/sqlite.go
@@ -13,7 +13,6 @@ import (
// embed will embeds the migration schema.
_ "embed"
- "github.com/bytebase/bytebase/common"
"github.com/bytebase/bytebase/plugin/db"
"github.com/bytebase/bytebase/plugin/db/util"
"go.uber.org/zap"
@@ -431,65 +430,50 @@ func (driver *Driver) SetupMigrationIfNeeded(ctx context.Context) error {
return nil
}
-// CheckOutOfOrderVersion will return versions that are higher than the given version.
-func (Driver) CheckOutOfOrderVersion(ctx context.Context, tx *sql.Tx, namespace string, source db.MigrationSource, version string) (minVersionIfValid *string, err error) {
- const checkOutofOrderVersionQuery = `
- SELECT MIN(version) FROM bytebase_migration_history
- WHERE namespace = ? AND source = ? AND version > ?
+// FindLargestVersionSinceBaseline will find the largest version since last baseline or branch.
+func (driver Driver) FindLargestVersionSinceBaseline(ctx context.Context, tx *sql.Tx, namespace string) (*string, error) {
+ largestBaselineSequence, err := driver.FindLargestSequence(ctx, tx, namespace, true /* baseline */)
+ if err != nil {
+ return nil, err
+ }
+ const getLargestVersionSinceLastBaselineQuery = `
+ SELECT MAX(version) FROM bytebase_migration_history
+ WHERE namespace = ? AND sequence >= ?
`
- row, err := tx.QueryContext(ctx, checkOutofOrderVersionQuery,
- namespace, source.String(), version,
+ row, err := tx.QueryContext(ctx, getLargestVersionSinceLastBaselineQuery,
+ namespace, largestBaselineSequence,
)
if err != nil {
- return nil, util.FormatErrorWithQuery(err, checkOutofOrderVersionQuery)
+ return nil, util.FormatErrorWithQuery(err, getLargestVersionSinceLastBaselineQuery)
}
defer row.Close()
- var minVersion sql.NullString
+ var version sql.NullString
row.Next()
- if err := row.Scan(&minVersion); err != nil {
+ if err := row.Scan(&version); err != nil {
return nil, err
}
- if minVersion.Valid {
- return &minVersion.String, nil
+ if version.Valid {
+ return &version.String, nil
}
return nil, nil
}
-// FindBaseline retruns true if any baseline is found.
-func (Driver) FindBaseline(ctx context.Context, tx *sql.Tx, namespace string) (hasBaseline bool, err error) {
- const findBaselineQuery = `
- SELECT 1 FROM bytebase_migration_history
- WHERE namespace = ? AND type = 'BASELINE'
- `
- row, err := tx.QueryContext(ctx, findBaselineQuery,
- namespace,
- )
- if err != nil {
- return false, util.FormatErrorWithQuery(err, findBaselineQuery)
+// FindLargestSequence will return the largest sequence number.
+func (Driver) FindLargestSequence(ctx context.Context, tx *sql.Tx, namespace string, baseline bool) (int, error) {
+ findLargestSequenceQuery := `
+ SELECT MAX(sequence) FROM bytebase_migration_history
+ WHERE namespace = ?`
+ if baseline {
+ findLargestSequenceQuery = fmt.Sprintf("%s AND (type = '%s' OR type = '%s')", findLargestSequenceQuery, db.Baseline, db.Branch)
}
- defer row.Close()
-
- if !row.Next() {
- return false, nil
- }
-
- return true, nil
-}
-
-// FindNextSequence will return the highest sequence number plus one.
-func (Driver) FindNextSequence(ctx context.Context, tx *sql.Tx, namespace string, requireBaseline bool) (int, error) {
- const findNextSequenceQuery = `
- SELECT MAX(sequence) + 1 FROM bytebase_migration_history
- WHERE namespace = ?
- `
- row, err := tx.QueryContext(ctx, findNextSequenceQuery,
+ row, err := tx.QueryContext(ctx, findLargestSequenceQuery,
namespace,
)
if err != nil {
- return -1, util.FormatErrorWithQuery(err, findNextSequenceQuery)
+ return -1, util.FormatErrorWithQuery(err, findLargestSequenceQuery)
}
defer row.Close()
@@ -500,13 +484,8 @@ func (Driver) FindNextSequence(ctx context.Context, tx *sql.Tx, namespace string
}
if !sequence.Valid {
- // Returns 1 if we haven't applied any migration for this namespace and doesn't require baselining
- if !requireBaseline {
- return 1, nil
- }
-
- // This should not happen normally since we already check the baselining exist beforehand. Just in case.
- return -1, common.Errorf(common.MigrationBaselineMissing, fmt.Errorf("unable to generate next migration_sequence, no migration hisotry found for %q, do you forget to baselining?", namespace))
+ // Returns 0 if we haven't applied any migration for this namespace.
+ return 0, nil
}
return int(sequence.Int32), nil
diff --git a/plugin/db/util/driverutil.go b/plugin/db/util/driverutil.go
index 51de9a21d8..12f593b518 100644
--- a/plugin/db/util/driverutil.go
+++ b/plugin/db/util/driverutil.go
@@ -112,12 +112,11 @@ func NeedsSetupMigrationSchema(ctx context.Context, sqldb *sql.DB, query string)
// MigrationExecutor is an adapter for ExecuteMigration().
type MigrationExecutor interface {
db.Driver
- // CheckOutOfOrderVersion will return versions that are higher than the given version.
- CheckOutOfOrderVersion(ctx context.Context, tx *sql.Tx, namespace string, source db.MigrationSource, version string) (minVersionIfValid *string, err error)
- // FindBaseline retruns true if any baseline is found.
- FindBaseline(ctx context.Context, tx *sql.Tx, namespace string) (hasBaseline bool, err error)
- // FindNextSequence will return the highest sequence number plus one.
- FindNextSequence(ctx context.Context, tx *sql.Tx, namespace string, requireBaseline bool) (int, error)
+ // FindLargestVersionSinceBaseline will find the largest version since last baseline or branch.
+ FindLargestVersionSinceBaseline(ctx context.Context, tx *sql.Tx, namespace string) (*string, error)
+ // FindLargestSequence will return the largest sequence number.
+ // Returns 0 if we haven't applied any migration for this namespace.
+ FindLargestSequence(ctx context.Context, tx *sql.Tx, namespace string, baseline bool) (int, error)
// InsertPendingHistory will insert the migration record with pending status and return the inserted ID.
InsertPendingHistory(ctx context.Context, tx *sql.Tx, sequence int, prevSchema string, m *db.MigrationInfo, statement string) (insertedID int64, err error)
// UpdateHistoryAsDone will update the migration record as done.
@@ -184,18 +183,8 @@ func ExecuteMigration(ctx context.Context, l *zap.Logger, executor MigrationExec
// beginMigration checks before executing migration and inserts a migration history record with pending status.
func beginMigration(ctx context.Context, executor MigrationExecutor, m *db.MigrationInfo, prevSchema string, statement string) (insertedID int64, err error) {
- sqldb, err := executor.GetDbConnection(ctx, bytebaseDatabase)
- if err != nil {
- return -1, err
- }
- tx, err := sqldb.BeginTx(ctx, nil)
- if err != nil {
- return -1, err
- }
- defer tx.Rollback()
-
// Phase 1 - Precheck before executing migration
- // Check if the same migration version has alraedy been applied
+ // Check if the same migration version has already been applied
if list, err := executor.FindMigrationHistoryList(ctx, &db.MigrationHistoryFind{
Database: &m.Namespace,
Source: &m.Source,
@@ -216,36 +205,35 @@ func beginMigration(ctx context.Context, executor MigrationExecutor, m *db.Migra
}
}
- // Check if there is any higher version already been applied
- if version, err := executor.CheckOutOfOrderVersion(ctx, tx, m.Namespace, m.Source, m.Version); err != nil {
+ sqldb, err := executor.GetDbConnection(ctx, bytebaseDatabase)
+ if err != nil {
+ return -1, err
+ }
+ // From a concurrency perspective, there's no difference between using transaction or not. However, we use transaction here to save some code of starting a transaction inside each db engine executor.
+ tx, err := sqldb.BeginTx(ctx, nil)
+ if err != nil {
return -1, err
- } else if version != nil && len(*version) > 0 {
- // Clickhouse will always return non-nil version with empty string.
- return -1, common.Errorf(common.MigrationOutOfOrder, fmt.Errorf("database %q has already applied version %s which is higher than %s", m.Database, *version, m.Version))
- }
-
- // If the migration engine is VCS and type is not baseline and is not branch, then we can only proceed if there is existing baseline
- // This check is also wrapped in transaction to avoid edge case where two baselinings are running concurrently.
- if m.Source == db.VCS && m.Type != db.Baseline && m.Type != db.Branch {
- if hasBaseline, err := executor.FindBaseline(ctx, tx, m.Namespace); err != nil {
- return -1, err
- } else if !hasBaseline {
- return -1, common.Errorf(common.MigrationBaselineMissing, fmt.Errorf("%s has not created migration baseline yet", m.Database))
- }
}
+ defer tx.Rollback()
- // VCS based SQL migration requires existing baselining
- requireBaseline := m.Source == db.VCS && m.Type == db.Migrate
- sequence, err := executor.FindNextSequence(ctx, tx, m.Namespace, requireBaseline)
+ largestSequence, err := executor.FindLargestSequence(ctx, tx, m.Namespace, false /* baseline */)
if err != nil {
return -1, err
}
- // Phase 2 - Record migration history as PENDING
+ // Check if there is any higher version already been applied since the last baseline or branch.
+ if version, err := executor.FindLargestVersionSinceBaseline(ctx, tx, m.Namespace); err != nil {
+ return -1, err
+ } else if version != nil && len(*version) > 0 && *version >= m.Version {
+ // len(*version) > 0 is used because Clickhouse will always return non-nil version with empty string.
+ return -1, common.Errorf(common.MigrationOutOfOrder, fmt.Errorf("database %q has already applied version %s which >= %s", m.Database, *version, m.Version))
+ }
+
+ // Phase 2 - Record migration history as PENDING.
// MySQL runs DDL in its own transaction, so we can't commit migration history together with DDL in a single transaction.
// 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.
- if insertedID, err = executor.InsertPendingHistory(ctx, tx, sequence, prevSchema, m, statement); err != nil {
+ if insertedID, err = executor.InsertPendingHistory(ctx, tx, largestSequence+1, prevSchema, m, statement); err != nil {
return -1, err
}
@@ -274,7 +262,7 @@ func endMigration(ctx context.Context, l *zap.Logger, executor MigrationExecutor
// Upon success, update the migration history as 'DONE', execution_duration_ns, updated schema.
err = executor.UpdateHistoryAsDone(ctx, tx, migrationDurationNs, updatedSchema, migrationHistoryID)
} else {
- // Otherwise, update the migration history as 'FAILED', exeuction_duration
+ // Otherwise, update the migration history as 'FAILED', exeuction_duration.
err = executor.UpdateHistoryAsFailed(ctx, tx, migrationDurationNs, migrationHistoryID)
}