Skip to content

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

refactor: change migrationHistoryID to string from int64 (#4197)

p0ny57471d139c4e
diff --git a/api/instance.go b/api/instance.go
index 971b637b48..1e06cd0bea 100644
--- a/api/instance.go
+++ b/api/instance.go
@@ -141,7 +141,7 @@ type InstanceMigration struct {
// MigrationHistory is stored in the instance instead of our own data file, so the field
// format is a bit different from the standard format.
type MigrationHistory struct {
- ID int `jsonapi:"primary,migrationHistory"`
+ ID string `jsonapi:"primary,migrationHistory"`
// Standard fields
Creator string `jsonapi:"attr,creator"`
diff --git a/api/task.go b/api/task.go
index c1004e1116..5cef4ee279 100644
--- a/api/task.go
+++ b/api/task.go
@@ -179,10 +179,10 @@ type TaskDatabaseDataUpdatePayload struct {
// ThreadID is the ID of the connection executing the migration.
// We use it to filter the binlog events of the migration transaction.
- ThreadID string `json:"threadID,omitempty"`
+ ThreadID string `json:"threadId,omitempty"`
// MigrationID is the ID of the migration history record.
// We use it to get the schema when the transaction ran.
- MigrationID int `json:"migrationID,omitempty"`
+ MigrationID string `json:"migrationId,omitempty"`
// BinlogXxx are obtained before and after executing the migration.
// We use them to locate the range of binlog for the migration transaction.
BinlogFileStart string `json:"binlogFileStart,omitempty"`
diff --git a/api/task_run.go b/api/task_run.go
index 0c96ca0426..7f0c526765 100644
--- a/api/task_run.go
+++ b/api/task_run.go
@@ -25,7 +25,7 @@ const (
// TaskRunResultPayload is the result payload for a task run.
type TaskRunResultPayload struct {
Detail string `json:"detail,omitempty"`
- MigrationID int64 `json:"migrationId,omitempty"`
+ MigrationID string `json:"migrationId,omitempty"`
Version string `json:"version,omitempty"`
}
diff --git a/plugin/advisor/utils_for_tests.go b/plugin/advisor/utils_for_tests.go
index 72a1064c8d..72d53fbcf1 100644
--- a/plugin/advisor/utils_for_tests.go
+++ b/plugin/advisor/utils_for_tests.go
@@ -303,8 +303,8 @@ func (*MockDriver) SetupMigrationIfNeeded(_ context.Context) error {
}
// ExecuteMigration implements the Driver interface.
-func (*MockDriver) ExecuteMigration(_ context.Context, _ *database.MigrationInfo, _ string) (int64, string, error) {
- return 0, "", nil
+func (*MockDriver) ExecuteMigration(_ context.Context, _ *database.MigrationInfo, _ string) (string, string, error) {
+ return "", "", nil
}
// FindMigrationHistoryList implements the Driver interface.
diff --git a/plugin/db/clickhouse/migrate.go b/plugin/db/clickhouse/migrate.go
index 23ae57b5c6..e99939d228 100644
--- a/plugin/db/clickhouse/migrate.go
+++ b/plugin/db/clickhouse/migrate.go
@@ -114,7 +114,7 @@ func (Driver) FindLargestSequence(ctx context.Context, tx *sql.Tx, namespace str
}
// InsertPendingHistory will insert the migration record with pending status and return the inserted ID.
-func (Driver) InsertPendingHistory(ctx context.Context, tx *sql.Tx, sequence int, prevSchema string, m *db.MigrationInfo, storedVersion, statement string) (int64, error) {
+func (Driver) InsertPendingHistory(ctx context.Context, tx *sql.Tx, sequence int, prevSchema string, m *db.MigrationInfo, storedVersion, statement string) (string, error) {
const insertHistoryQuery = `
INSERT INTO bytebase.migration_history (
id,
@@ -139,22 +139,22 @@ func (Driver) InsertPendingHistory(ctx context.Context, tx *sql.Tx, sequence int
)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19)
`
- var insertedID int64
+ var insertedID string
maxIDQuery := "SELECT MAX(id)+1 FROM bytebase.migration_history"
rows, err := tx.QueryContext(ctx, maxIDQuery)
if err != nil {
- return int64(0), util.FormatErrorWithQuery(err, maxIDQuery)
+ return "", util.FormatErrorWithQuery(err, maxIDQuery)
}
defer rows.Close()
for rows.Next() {
if err := rows.Scan(
&insertedID,
); err != nil {
- return int64(0), util.FormatErrorWithQuery(err, maxIDQuery)
+ return "", util.FormatErrorWithQuery(err, maxIDQuery)
}
}
if err := rows.Err(); err != nil {
- return int64(0), util.FormatErrorWithQuery(err, maxIDQuery)
+ return "", util.FormatErrorWithQuery(err, maxIDQuery)
}
// Clickhouse sql driver doesn't support taking now() as prepared value.
now := time.Now().Unix()
@@ -180,14 +180,14 @@ func (Driver) InsertPendingHistory(ctx context.Context, tx *sql.Tx, sequence int
m.Payload,
)
if err != nil {
- return int64(0), util.FormatErrorWithQuery(err, insertHistoryQuery)
+ return "", util.FormatErrorWithQuery(err, insertHistoryQuery)
}
return insertedID, nil
}
// UpdateHistoryAsDone will update the migration record as done.
-func (Driver) UpdateHistoryAsDone(ctx context.Context, tx *sql.Tx, migrationDurationNs int64, updatedSchema string, insertedID int64) error {
+func (Driver) UpdateHistoryAsDone(ctx context.Context, tx *sql.Tx, migrationDurationNs int64, updatedSchema string, insertedID string) error {
const updateHistoryAsDoneQuery = `
ALTER TABLE
bytebase.migration_history
@@ -202,7 +202,7 @@ func (Driver) UpdateHistoryAsDone(ctx context.Context, tx *sql.Tx, migrationDura
}
// UpdateHistoryAsFailed will update the migration record as failed.
-func (Driver) UpdateHistoryAsFailed(ctx context.Context, tx *sql.Tx, migrationDurationNs int64, insertedID int64) error {
+func (Driver) UpdateHistoryAsFailed(ctx context.Context, tx *sql.Tx, migrationDurationNs int64, insertedID string) error {
const updateHistoryAsFailedQuery = `
ALTER TABLE
bytebase.migration_history
@@ -216,7 +216,7 @@ func (Driver) UpdateHistoryAsFailed(ctx context.Context, tx *sql.Tx, migrationDu
}
// ExecuteMigration will execute the migration.
-func (driver *Driver) ExecuteMigration(ctx context.Context, m *db.MigrationInfo, statement string) (int64, string, error) {
+func (driver *Driver) ExecuteMigration(ctx context.Context, m *db.MigrationInfo, statement string) (string, string, error) {
return util.ExecuteMigration(ctx, driver, m, statement, db.BytebaseDatabase)
}
diff --git a/plugin/db/driver.go b/plugin/db/driver.go
index 83827e9e53..a7b98f5694 100644
--- a/plugin/db/driver.go
+++ b/plugin/db/driver.go
@@ -311,7 +311,7 @@ func ParseSchemaFileInfo(baseDirectory, schemaPathTemplate, file string) (*Migra
// MigrationHistory is the API message for migration history.
type MigrationHistory struct {
- ID int
+ ID string
Creator string
CreatedTs int64
@@ -338,7 +338,7 @@ type MigrationHistory struct {
// MigrationHistoryFind is the API message for finding migration histories.
type MigrationHistoryFind struct {
- ID *int
+ ID *string
Database *string
Source *MigrationSource
@@ -471,7 +471,7 @@ type Driver interface {
// Execute migration will apply the statement and record the migration history, the schema after migration on success.
// The migration type is determined by m.Type. Note, it can also perform data migration (DML) in addition to schema migration (DDL).
// It returns the migration history id and the schema after migration on success.
- ExecuteMigration(ctx context.Context, m *MigrationInfo, statement string) (int64, string, error)
+ ExecuteMigration(ctx context.Context, m *MigrationInfo, statement string) (string, string, error)
// Find the migration history list and return most recent item first.
FindMigrationHistoryList(ctx context.Context, find *MigrationHistoryFind) ([]*MigrationHistory, error)
diff --git a/plugin/db/mongodb/migrate.go b/plugin/db/mongodb/migrate.go
index badbaf52b3..bd8eb6902d 100644
--- a/plugin/db/mongodb/migrate.go
+++ b/plugin/db/mongodb/migrate.go
@@ -3,6 +3,7 @@ package mongodb
import (
"context"
"database/sql"
+ "fmt"
"time"
// embed will embeds the migration schema.
@@ -114,7 +115,7 @@ func (driver *Driver) SetupMigrationIfNeeded(ctx context.Context) error {
}
// ExecuteMigration executes a migration.
-func (driver *Driver) ExecuteMigration(ctx context.Context, m *db.MigrationInfo, statement string) (int64, string, error) {
+func (driver *Driver) ExecuteMigration(ctx context.Context, m *db.MigrationInfo, statement string) (string, string, error) {
return util.ExecuteMigration(ctx, driver, m, statement, migrationHistoryDefaultDatabase)
}
@@ -175,7 +176,7 @@ func convertMigrationHistory(history MigrationHistory) (db.MigrationHistory, err
return db.MigrationHistory{}, err
}
return db.MigrationHistory{
- ID: int(history.ID),
+ ID: fmt.Sprintf("%d", history.ID),
Creator: history.CreatedBy,
CreatedTs: int64(history.CreatedTs.T),
Updater: history.UpdatedBy,
@@ -294,7 +295,7 @@ func (driver *Driver) FindLargestVersionSinceBaseline(ctx context.Context, tx *s
}
// InsertPendingHistory will insert the migration record with pending status and return the inserted ID.
-func (driver *Driver) InsertPendingHistory(ctx context.Context, _ *sql.Tx, sequence int, _ string, m *db.MigrationInfo, storedVersion, statement string) (insertedID int64, err error) {
+func (driver *Driver) InsertPendingHistory(ctx context.Context, _ *sql.Tx, sequence int, _ string, m *db.MigrationInfo, storedVersion, statement string) (insertedID string, err error) {
collection := driver.client.Database(migrationHistoryDefaultDatabase).Collection(migrationHistoryDefaultCollection)
retryTimes := 3
@@ -302,7 +303,7 @@ func (driver *Driver) InsertPendingHistory(ctx context.Context, _ *sql.Tx, seque
currentTimestamp := getMongoTimestamp()
nextID, err := driver.getMigrationHistoryNextID(ctx)
if err != nil {
- return 0, errors.Wrapf(err, "failed to get next migration history ID")
+ return "", errors.Wrapf(err, "failed to get next migration history ID")
}
document := bson.M{
@@ -339,15 +340,15 @@ func (driver *Driver) InsertPendingHistory(ctx context.Context, _ *sql.Tx, seque
continue
}
}
- return 0, errors.Wrapf(err, "failed to insert a pending migration history record")
+ return "", errors.Wrapf(err, "failed to insert a pending migration history record")
}
- return nextID, nil
+ return fmt.Sprintf("%d", nextID), nil
}
- return 0, errors.Errorf("failed to insert a pending migration history record because of the duplidate id after %d retries", retryTimes)
+ return "", errors.Errorf("failed to insert a pending migration history record because of the duplidate id after %d retries", retryTimes)
}
// UpdateHistoryAsDone will update the migration record as done.
-func (driver *Driver) UpdateHistoryAsDone(ctx context.Context, _ *sql.Tx, migrationDurationNs int64, _ string, insertedID int64) error {
+func (driver *Driver) UpdateHistoryAsDone(ctx context.Context, _ *sql.Tx, migrationDurationNs int64, _ string, insertedID string) error {
collection := driver.client.Database(migrationHistoryDefaultDatabase).Collection(migrationHistoryDefaultCollection)
filter := bson.M{
"id": insertedID,
@@ -364,13 +365,13 @@ func (driver *Driver) UpdateHistoryAsDone(ctx context.Context, _ *sql.Tx, migrat
return errors.Wrapf(err, "failed to update a migration history as done")
}
if updateResult.MatchedCount == 0 {
- return errors.Errorf("failed to find a migration history record to mark as done with ID %d ", insertedID)
+ return errors.Errorf("failed to find a migration history record to mark as done with ID %s", insertedID)
}
return nil
}
// UpdateHistoryAsFailed will update the migration record as failed.
-func (driver *Driver) UpdateHistoryAsFailed(ctx context.Context, _ *sql.Tx, migrationDurationNs int64, insertedID int64) error {
+func (driver *Driver) UpdateHistoryAsFailed(ctx context.Context, _ *sql.Tx, migrationDurationNs int64, insertedID string) error {
collection := driver.client.Database(migrationHistoryDefaultDatabase).Collection(migrationHistoryDefaultCollection)
filter := bson.M{
"id": insertedID,
@@ -386,7 +387,7 @@ func (driver *Driver) UpdateHistoryAsFailed(ctx context.Context, _ *sql.Tx, migr
return errors.Wrapf(err, "failed to update a migration history as failed")
}
if updateResult.MatchedCount == 0 {
- return errors.Errorf("failed to find a migration history record to mark as failed with ID %d ", insertedID)
+ return errors.Errorf("failed to find a migration history record to mark as failed with ID %s", insertedID)
}
return nil
}
diff --git a/plugin/db/mysql/migrate.go b/plugin/db/mysql/migrate.go
index cee3db6605..d969fed5d2 100644
--- a/plugin/db/mysql/migrate.go
+++ b/plugin/db/mysql/migrate.go
@@ -116,7 +116,7 @@ func (Driver) FindLargestSequence(ctx context.Context, tx *sql.Tx, namespace str
}
// InsertPendingHistory will insert the migration record with pending status and return the inserted ID.
-func (Driver) InsertPendingHistory(ctx context.Context, tx *sql.Tx, sequence int, prevSchema string, m *db.MigrationInfo, storedVersion, statement string) (int64, error) {
+func (Driver) InsertPendingHistory(ctx context.Context, tx *sql.Tx, sequence int, prevSchema string, m *db.MigrationInfo, storedVersion, statement string) (string, error) {
const insertHistoryQuery = `
INSERT INTO bytebase.migration_history (
created_by,
@@ -158,18 +158,18 @@ func (Driver) InsertPendingHistory(ctx context.Context, tx *sql.Tx, sequence int
m.Payload,
)
if err != nil {
- return int64(0), util.FormatErrorWithQuery(err, insertHistoryQuery)
+ return "", util.FormatErrorWithQuery(err, insertHistoryQuery)
}
insertedID, err := res.LastInsertId()
if err != nil {
- return int64(0), util.FormatErrorWithQuery(err, insertHistoryQuery)
+ return "", util.FormatErrorWithQuery(err, insertHistoryQuery)
}
- return insertedID, nil
+ return fmt.Sprintf("%d", insertedID), nil
}
// UpdateHistoryAsDone will update the migration record as done.
-func (Driver) UpdateHistoryAsDone(ctx context.Context, tx *sql.Tx, migrationDurationNs int64, updatedSchema string, insertedID int64) error {
+func (Driver) UpdateHistoryAsDone(ctx context.Context, tx *sql.Tx, migrationDurationNs int64, updatedSchema string, insertedID string) error {
const updateHistoryAsDoneQuery = `
UPDATE
bytebase.migration_history
@@ -184,7 +184,7 @@ func (Driver) UpdateHistoryAsDone(ctx context.Context, tx *sql.Tx, migrationDura
}
// UpdateHistoryAsFailed will update the migration record as failed.
-func (Driver) UpdateHistoryAsFailed(ctx context.Context, tx *sql.Tx, migrationDurationNs int64, insertedID int64) error {
+func (Driver) UpdateHistoryAsFailed(ctx context.Context, tx *sql.Tx, migrationDurationNs int64, insertedID string) error {
const updateHistoryAsFailedQuery = `
UPDATE
bytebase.migration_history
@@ -198,7 +198,7 @@ func (Driver) UpdateHistoryAsFailed(ctx context.Context, tx *sql.Tx, migrationDu
}
// ExecuteMigration will execute the migration.
-func (driver *Driver) ExecuteMigration(ctx context.Context, m *db.MigrationInfo, statement string) (int64, string, error) {
+func (driver *Driver) ExecuteMigration(ctx context.Context, m *db.MigrationInfo, statement string) (string, string, error) {
return util.ExecuteMigration(ctx, driver, m, statement, db.BytebaseDatabase)
}
diff --git a/plugin/db/pg/migrate.go b/plugin/db/pg/migrate.go
index bb9db3aaba..c4d3eaf896 100644
--- a/plugin/db/pg/migrate.go
+++ b/plugin/db/pg/migrate.go
@@ -164,7 +164,7 @@ func (*Driver) FindLargestSequence(ctx context.Context, tx *sql.Tx, namespace st
}
// InsertPendingHistory will insert the migration record with pending status and return the inserted ID.
-func (*Driver) InsertPendingHistory(ctx context.Context, tx *sql.Tx, sequence int, prevSchema string, m *db.MigrationInfo, storedVersion, statement string) (int64, error) {
+func (*Driver) InsertPendingHistory(ctx context.Context, tx *sql.Tx, sequence int, prevSchema string, m *db.MigrationInfo, storedVersion, statement string) (string, error) {
const insertHistoryQuery = `
INSERT INTO migration_history (
created_by,
@@ -189,7 +189,7 @@ func (*Driver) InsertPendingHistory(ctx context.Context, tx *sql.Tx, sequence in
VALUES ($1, EXTRACT(epoch from NOW()), $2, EXTRACT(epoch from NOW()), $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, 0, $14, $15)
RETURNING id
`
- var insertedID int64
+ var insertedID string
if err := tx.QueryRowContext(ctx, insertHistoryQuery,
m.Creator,
m.Creator,
@@ -207,13 +207,13 @@ func (*Driver) InsertPendingHistory(ctx context.Context, tx *sql.Tx, sequence in
m.IssueID,
m.Payload,
).Scan(&insertedID); err != nil {
- return 0, err
+ return "", err
}
return insertedID, nil
}
// UpdateHistoryAsDone will update the migration record as done.
-func (*Driver) UpdateHistoryAsDone(ctx context.Context, tx *sql.Tx, migrationDurationNs int64, updatedSchema string, insertedID int64) error {
+func (*Driver) UpdateHistoryAsDone(ctx context.Context, tx *sql.Tx, migrationDurationNs int64, updatedSchema string, insertedID string) error {
const updateHistoryAsDoneQuery = `
UPDATE
migration_history
@@ -228,7 +228,7 @@ func (*Driver) UpdateHistoryAsDone(ctx context.Context, tx *sql.Tx, migrationDur
}
// UpdateHistoryAsFailed will update the migration record as failed.
-func (*Driver) UpdateHistoryAsFailed(ctx context.Context, tx *sql.Tx, migrationDurationNs int64, insertedID int64) error {
+func (*Driver) UpdateHistoryAsFailed(ctx context.Context, tx *sql.Tx, migrationDurationNs int64, insertedID string) error {
const updateHistoryAsFailedQuery = `
UPDATE
migration_history
@@ -242,7 +242,7 @@ func (*Driver) UpdateHistoryAsFailed(ctx context.Context, tx *sql.Tx, migrationD
}
// ExecuteMigration will execute the migration.
-func (driver *Driver) ExecuteMigration(ctx context.Context, m *db.MigrationInfo, statement string) (int64, string, error) {
+func (driver *Driver) ExecuteMigration(ctx context.Context, m *db.MigrationInfo, statement string) (string, string, error) {
if driver.strictUseDb() {
return util.ExecuteMigration(ctx, driver, m, statement, driver.strictDatabase)
}
diff --git a/plugin/db/snowflake/migrate.go b/plugin/db/snowflake/migrate.go
index 6036a1c7ae..56be0bb68d 100644
--- a/plugin/db/snowflake/migrate.go
+++ b/plugin/db/snowflake/migrate.go
@@ -122,7 +122,7 @@ func (Driver) FindLargestSequence(ctx context.Context, tx *sql.Tx, namespace str
}
// InsertPendingHistory will insert the migration record with pending status and return the inserted ID.
-func (Driver) InsertPendingHistory(ctx context.Context, tx *sql.Tx, sequence int, prevSchema string, m *db.MigrationInfo, storedVersion, statement string) (int64, error) {
+func (Driver) InsertPendingHistory(ctx context.Context, tx *sql.Tx, sequence int, prevSchema string, m *db.MigrationInfo, storedVersion, statement string) (string, error) {
const insertHistoryQuery = `
INSERT INTO bytebase.public.migration_history (
created_by,
@@ -146,28 +146,28 @@ func (Driver) InsertPendingHistory(ctx context.Context, tx *sql.Tx, sequence int
)
VALUES (?, DATE_PART(EPOCH_SECOND, CURRENT_TIMESTAMP()), ?, DATE_PART(EPOCH_SECOND, CURRENT_TIMESTAMP()), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, ?, ?)
`
- var insertedID int64
+ var insertedID string
maxIDQuery := "SELECT MAX(id)+1 FROM bytebase.public.migration_history"
rows, err := tx.QueryContext(ctx, maxIDQuery)
if err != nil {
- return int64(0), util.FormatErrorWithQuery(err, maxIDQuery)
+ return "", util.FormatErrorWithQuery(err, maxIDQuery)
}
defer rows.Close()
- var id sql.NullInt64
+ var id sql.NullString
for rows.Next() {
if err := rows.Scan(
&id,
); err != nil {
- return int64(0), util.FormatErrorWithQuery(err, maxIDQuery)
+ return "", util.FormatErrorWithQuery(err, maxIDQuery)
}
}
if err := rows.Err(); err != nil {
- return int64(0), util.FormatErrorWithQuery(err, maxIDQuery)
+ return "", util.FormatErrorWithQuery(err, maxIDQuery)
}
if id.Valid {
- insertedID = id.Int64
+ insertedID = id.String
} else {
- insertedID = 1
+ insertedID = "1"
}
_, err = tx.ExecContext(ctx, insertHistoryQuery,
@@ -188,13 +188,13 @@ func (Driver) InsertPendingHistory(ctx context.Context, tx *sql.Tx, sequence int
m.Payload,
)
if err != nil {
- return int64(0), util.FormatErrorWithQuery(err, insertHistoryQuery)
+ return "", util.FormatErrorWithQuery(err, insertHistoryQuery)
}
return insertedID, nil
}
// UpdateHistoryAsDone will update the migration record as done.
-func (Driver) UpdateHistoryAsDone(ctx context.Context, tx *sql.Tx, migrationDurationNs int64, updatedSchema string, insertedID int64) error {
+func (Driver) UpdateHistoryAsDone(ctx context.Context, tx *sql.Tx, migrationDurationNs int64, updatedSchema string, insertedID string) error {
const updateHistoryAsDoneQuery = `
UPDATE
bytebase.public.migration_history
@@ -209,7 +209,7 @@ func (Driver) UpdateHistoryAsDone(ctx context.Context, tx *sql.Tx, migrationDura
}
// UpdateHistoryAsFailed will update the migration record as failed.
-func (Driver) UpdateHistoryAsFailed(ctx context.Context, tx *sql.Tx, migrationDurationNs int64, insertedID int64) error {
+func (Driver) UpdateHistoryAsFailed(ctx context.Context, tx *sql.Tx, migrationDurationNs int64, insertedID string) error {
const updateHistoryAsFailedQuery = `
UPDATE
bytebase.public.migration_history
@@ -223,9 +223,9 @@ func (Driver) UpdateHistoryAsFailed(ctx context.Context, tx *sql.Tx, migrationDu
}
// ExecuteMigration will execute the migration.
-func (driver *Driver) ExecuteMigration(ctx context.Context, m *db.MigrationInfo, statement string) (int64, string, error) {
+func (driver *Driver) ExecuteMigration(ctx context.Context, m *db.MigrationInfo, statement string) (string, string, error) {
if err := driver.useRole(ctx, sysAdminRole); err != nil {
- return int64(0), "", err
+ return "", "", err
}
return util.ExecuteMigration(ctx, driver, m, statement, bytebaseDatabase)
}
diff --git a/plugin/db/spanner/migrate.go b/plugin/db/spanner/migrate.go
index 094f6871de..6131dde2d6 100644
--- a/plugin/db/spanner/migrate.go
+++ b/plugin/db/spanner/migrate.go
@@ -68,7 +68,7 @@ func (d *Driver) SetupMigrationIfNeeded(ctx context.Context) error {
}
// ExecuteMigration executes a migration.
-func (*Driver) ExecuteMigration(_ context.Context, _ *db.MigrationInfo, _ string) (int64, string, error) {
+func (*Driver) ExecuteMigration(_ context.Context, _ *db.MigrationInfo, _ string) (string, string, error) {
panic("not implemented")
}
@@ -151,9 +151,9 @@ func (d *Driver) FindMigrationHistoryList(ctx context.Context, find *db.Migratio
}
var history db.MigrationHistory
var storedVersion string
- var id, sequence int64
+ var sequence int64
if err := row.Columns(
- &id,
+ &history.ID,
&history.Creator,
&history.CreatedTs,
&history.Updater,
@@ -175,7 +175,6 @@ func (d *Driver) FindMigrationHistoryList(ctx context.Context, find *db.Migratio
); err != nil {
return nil, err
}
- history.ID = int(id)
history.Sequence = int(sequence)
useSemanticVersion, version, semanticVersionSuffix, err := util.FromStoredVersion(storedVersion)
if err != nil {
diff --git a/plugin/db/sqlite/migrate.go b/plugin/db/sqlite/migrate.go
index b9cd74c282..cb6465b1d1 100644
--- a/plugin/db/sqlite/migrate.go
+++ b/plugin/db/sqlite/migrate.go
@@ -4,6 +4,7 @@ import (
"context"
"database/sql"
"fmt"
+ "strconv"
// embed will embeds the migration schema.
_ "embed"
@@ -136,7 +137,7 @@ func (Driver) FindLargestSequence(ctx context.Context, tx *sql.Tx, namespace str
}
// InsertPendingHistory will insert the migration record with pending status and return the inserted ID.
-func (Driver) InsertPendingHistory(ctx context.Context, tx *sql.Tx, sequence int, prevSchema string, m *db.MigrationInfo, storedVersion, statement string) (int64, error) {
+func (Driver) InsertPendingHistory(ctx context.Context, tx *sql.Tx, sequence int, prevSchema string, m *db.MigrationInfo, storedVersion, statement string) (string, error) {
const insertHistoryQuery = `
INSERT INTO bytebase_migration_history (
created_by,
@@ -178,18 +179,18 @@ func (Driver) InsertPendingHistory(ctx context.Context, tx *sql.Tx, sequence int
m.Payload,
)
if err != nil {
- return int64(0), util.FormatErrorWithQuery(err, insertHistoryQuery)
+ return "", util.FormatErrorWithQuery(err, insertHistoryQuery)
}
insertedID, err := res.LastInsertId()
if err != nil {
- return int64(0), util.FormatErrorWithQuery(err, insertHistoryQuery)
+ return "", util.FormatErrorWithQuery(err, insertHistoryQuery)
}
- return insertedID, nil
+ return strconv.FormatInt(insertedID, 10), nil
}
// UpdateHistoryAsDone will update the migration record as done.
-func (Driver) UpdateHistoryAsDone(ctx context.Context, tx *sql.Tx, migrationDurationNs int64, updatedSchema string, insertedID int64) error {
+func (Driver) UpdateHistoryAsDone(ctx context.Context, tx *sql.Tx, migrationDurationNs int64, updatedSchema string, insertedID string) error {
const updateHistoryAsDoneQuery = `
UPDATE
bytebase_migration_history
@@ -204,7 +205,7 @@ func (Driver) UpdateHistoryAsDone(ctx context.Context, tx *sql.Tx, migrationDura
}
// UpdateHistoryAsFailed will update the migration record as failed.
-func (Driver) UpdateHistoryAsFailed(ctx context.Context, tx *sql.Tx, migrationDurationNs int64, insertedID int64) error {
+func (Driver) UpdateHistoryAsFailed(ctx context.Context, tx *sql.Tx, migrationDurationNs int64, insertedID string) error {
const updateHistoryAsFailedQuery = `
UPDATE
bytebase_migration_history
@@ -218,7 +219,7 @@ func (Driver) UpdateHistoryAsFailed(ctx context.Context, tx *sql.Tx, migrationDu
}
// ExecuteMigration will execute the migration.
-func (driver *Driver) ExecuteMigration(ctx context.Context, m *db.MigrationInfo, statement string) (int64, string, error) {
+func (driver *Driver) ExecuteMigration(ctx context.Context, m *db.MigrationInfo, statement string) (string, string, error) {
return util.ExecuteMigration(ctx, driver, m, statement, bytebaseDatabase)
}
diff --git a/plugin/db/util/driverutil.go b/plugin/db/util/driverutil.go
index 89a424fdc5..1244e428e9 100644
--- a/plugin/db/util/driverutil.go
+++ b/plugin/db/util/driverutil.go
@@ -142,23 +142,23 @@ type MigrationExecutor interface {
// 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, storedVersion, statement string) (insertedID int64, err error)
+ InsertPendingHistory(ctx context.Context, tx *sql.Tx, sequence int, prevSchema string, m *db.MigrationInfo, storedVersion, statement string) (insertedID string, err error)
// UpdateHistoryAsDone will update the migration record as done.
- UpdateHistoryAsDone(ctx context.Context, tx *sql.Tx, migrationDurationNs int64, updatedSchema string, insertedID int64) error
+ UpdateHistoryAsDone(ctx context.Context, tx *sql.Tx, migrationDurationNs int64, updatedSchema string, insertedID string) error
// UpdateHistoryAsFailed will update the migration record as failed.
- UpdateHistoryAsFailed(ctx context.Context, tx *sql.Tx, migrationDurationNs int64, insertedID int64) error
+ UpdateHistoryAsFailed(ctx context.Context, tx *sql.Tx, migrationDurationNs int64, insertedID string) error
}
// ExecuteMigration will execute the database migration.
// Returns the created migration history id and the updated schema on success.
-func ExecuteMigration(ctx context.Context, executor MigrationExecutor, m *db.MigrationInfo, statement string, databaseName string) (migrationHistoryID int64, updatedSchema string, resErr error) {
+func ExecuteMigration(ctx context.Context, executor MigrationExecutor, m *db.MigrationInfo, statement string, databaseName string) (migrationHistoryID string, updatedSchema string, resErr error) {
var prevSchemaBuf bytes.Buffer
// Don't record schema if the database hasn't existed yet or is schemaless (e.g. Mongo).
if !m.CreateDatabase && executor.GetType() != db.MongoDB {
// For baseline migration, we also record the live schema to detect the schema drift.
// See https://bytebase.com/blog/what-is-database-schema-drift
if _, err := executor.Dump(ctx, m.Database, &prevSchemaBuf, true /*schemaOnly*/); err != nil {
- return -1, "", FormatError(err)
+ return "", "", FormatError(err)
}
}
@@ -169,7 +169,7 @@ func ExecuteMigration(ctx context.Context, executor MigrationExecutor, m *db.Mig
if common.ErrorCode(err) == common.MigrationAlreadyApplied {
return insertedID, prevSchemaBuf.String(), nil
}
- return -1, "", errors.Wrapf(err, "failed to begin migration for issue %s", m.IssueID)
+ return "", "", errors.Wrapf(err, "failed to begin migration for issue %s", m.IssueID)
}
startedNs := time.Now().UnixNano()
@@ -178,7 +178,7 @@ func ExecuteMigration(ctx context.Context, executor MigrationExecutor, m *db.Mig
if err := EndMigration(ctx, executor, startedNs, insertedID, updatedSchema, databaseName, resErr == nil /*isDone*/); err != nil {
log.Error("Failed to update migration history record",
zap.Error(err),
- zap.Int64("migration_id", migrationHistoryID),
+ zap.String("migration_id", migrationHistoryID),
)
}
}()
@@ -199,11 +199,11 @@ func ExecuteMigration(ctx context.Context, executor MigrationExecutor, m *db.Mig
// We should not call GetDBConnection() if the instance is MongoDB because it doesn't support.
if !m.CreateDatabase && executor.GetType() != db.MongoDB {
if _, err := executor.GetDBConnection(ctx, m.Database); err != nil {
- return -1, "", err
+ return "", "", err
}
}
if _, err := executor.Execute(ctx, statement, m.CreateDatabase); err != nil {
- return -1, "", FormatError(err)
+ return "", "", FormatError(err)
}
}
@@ -214,18 +214,18 @@ func ExecuteMigration(ctx context.Context, executor MigrationExecutor, m *db.Mig
// Phase 4 - Dump the schema after migration
var afterSchemaBuf bytes.Buffer
if _, err := executor.Dump(ctx, m.Database, &afterSchemaBuf, true /*schemaOnly*/); err != nil {
- return -1, "", FormatError(err)
+ return "", "", FormatError(err)
}
return insertedID, afterSchemaBuf.String(), nil
}
// 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, databaseName string) (insertedID int64, err error) {
+func BeginMigration(ctx context.Context, executor MigrationExecutor, m *db.MigrationInfo, prevSchema string, statement string, databaseName string) (insertedID string, err error) {
// Convert version to stored version.
storedVersion, err := ToStoredVersion(m.UseSemanticVersion, m.Version, m.SemanticVersionSuffix)
if err != nil {
- return 0, errors.Wrap(err, "failed to convert to stored version")
+ 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.
@@ -233,31 +233,31 @@ func BeginMigration(ctx context.Context, executor MigrationExecutor, m *db.Migra
Database: &m.Namespace,
Version: &m.Version,
}); err != nil {
- return -1, errors.Wrap(err, "failed to check duplicate version")
+ return "", errors.Wrap(err, "failed to check duplicate version")
} else if len(list) > 0 {
migrationHistory := list[0]
switch migrationHistory.Status {
case db.Done:
if migrationHistory.IssueID != m.IssueID {
- return int64(migrationHistory.ID), common.Errorf(common.MigrationFailed, "database %q has already applied version %s by issue %s", m.Database, m.Version, migrationHistory.IssueID)
+ return migrationHistory.ID, common.Errorf(common.MigrationFailed, "database %q has already applied version %s by issue %s", m.Database, m.Version, migrationHistory.IssueID)
}
- return int64(migrationHistory.ID), common.Errorf(common.MigrationAlreadyApplied, "database %q has already applied version %s", m.Database, m.Version)
+ return migrationHistory.ID, common.Errorf(common.MigrationAlreadyApplied, "database %q has already applied version %s", m.Database, m.Version)
case db.Pending:
err := errors.Errorf("database %q version %s migration is already in progress", m.Database, m.Version)
log.Debug(err.Error())
// For force migration, we will ignore the existing migration history and continue to migration.
if m.Force {
- return int64(migrationHistory.ID), nil
+ return migrationHistory.ID, nil
}
- return -1, common.Wrap(err, common.MigrationPending)
+ 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)
log.Debug(err.Error())
// For force migration, we will ignore the existing migration history and continue to migration.
if m.Force {
- return int64(migrationHistory.ID), nil
+ return migrationHistory.ID, nil
}
- return -1, common.Wrap(err, common.MigrationFailed)
+ return "", common.Wrap(err, common.MigrationFailed)
}
}
@@ -270,27 +270,27 @@ func BeginMigration(ctx context.Context, executor MigrationExecutor, m *db.Migra
// We use transaction here for the RDBMS.
sqldb, err := executor.GetDBConnection(ctx, databaseName)
if err != nil {
- return -1, err
+ return "", 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
+ return "", err
}
defer tx.Rollback()
}
largestSequence, err := executor.FindLargestSequence(ctx, tx, m.Namespace, false /* baseline */)
if err != nil {
- return -1, err
+ return "", err
}
// 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
+ return "", 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, "database %q has already applied version %s which >= %s", m.Database, *version, m.Version)
+ return "", common.Errorf(common.MigrationOutOfOrder, "database %q has already applied version %s which >= %s", m.Database, *version, m.Version)
}
// Phase 2 - Record migration history as PENDING.
@@ -299,12 +299,12 @@ func BeginMigration(ctx context.Context, executor MigrationExecutor, m *db.Migra
// update the record to DONE together with the updated schema.
statementRecord, _ := common.TruncateString(statement, common.MaxSheetSize)
if insertedID, err = executor.InsertPendingHistory(ctx, tx, largestSequence+1, prevSchema, m, storedVersion, statementRecord); err != nil {
- return -1, err
+ return "", err
}
if executor.GetType() != db.MongoDB {
if err := tx.Commit(); err != nil {
- return -1, err
+ return "", err
}
}
@@ -312,7 +312,7 @@ func BeginMigration(ctx context.Context, executor MigrationExecutor, m *db.Migra
}
// EndMigration updates the migration history record to DONE or FAILED depending on migration is done or not.
-func EndMigration(ctx context.Context, executor MigrationExecutor, startedNs int64, migrationHistoryID int64, updatedSchema string, databaseName string, isDone bool) (err error) {
+func EndMigration(ctx context.Context, executor MigrationExecutor, startedNs int64, migrationHistoryID string, updatedSchema string, databaseName string, isDone bool) (err error) {
migrationDurationNs := time.Now().UnixNano() - startedNs
var tx *sql.Tx
diff --git a/server/instance.go b/server/instance.go
index 383e1ef5bb..0ca8976561 100644
--- a/server/instance.go
+++ b/server/instance.go
@@ -278,10 +278,7 @@ func (s *Server) registerInstanceRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Instance ID is not a number: %s", c.Param("instanceID"))).SetInternal(err)
}
- historyID, err := strconv.Atoi(c.Param("historyID"))
- if err != nil {
- return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("History ID is not a number: %s", c.Param("historyID"))).SetInternal(err)
- }
+ historyID := c.Param("historyID")
instance, err := s.store.GetInstanceByID(ctx, id)
if err != nil {
@@ -302,7 +299,7 @@ func (s *Server) registerInstanceRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch migration history list").SetInternal(err)
}
if len(list) == 0 {
- return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Migration history ID %d not found for instance %q", historyID, instance.Name))
+ return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Migration history ID %q not found for instance %q", historyID, instance.Name))
}
entry := list[0]
diff --git a/server/runner/rollbackrun/runner.go b/server/runner/rollbackrun/runner.go
index 248e6ef0d6..a642aa5560 100644
--- a/server/runner/rollbackrun/runner.go
+++ b/server/runner/rollbackrun/runner.go
@@ -141,10 +141,10 @@ func (r *Runner) generateRollbackSQLImpl(ctx context.Context, task *api.Task, pa
defer driver.Close(ctx)
list, err := driver.FindMigrationHistoryList(ctx, &db.MigrationHistoryFind{ID: &payload.MigrationID})
if err != nil {
- return "", errors.WithMessagef(err, "failed to find migration history with ID %d", payload.MigrationID)
+ return "", errors.WithMessagef(err, "failed to find migration history with ID %s", payload.MigrationID)
}
if len(list) == 0 {
- return "", errors.Errorf("migration history with ID %d not found", payload.MigrationID)
+ return "", errors.Errorf("migration history with ID %s not found", payload.MigrationID)
}
if len(list) > 1 {
return "", errors.Errorf("found %d migration history record, expecting one", len(list))
diff --git a/server/runner/taskrun/executor.go b/server/runner/taskrun/executor.go
index 8639c3db1b..547f481894 100644
--- a/server/runner/taskrun/executor.go
+++ b/server/runner/taskrun/executor.go
@@ -127,13 +127,13 @@ func preMigration(ctx context.Context, store *store.Store, profile config.Profil
return mi, nil
}
-func executeMigration(ctx context.Context, store *store.Store, dbFactory *dbfactory.DBFactory, stateCfg *state.State, task *api.Task, statement string, mi *db.MigrationInfo) (migrationID int64, schema string, err error) {
+func executeMigration(ctx context.Context, store *store.Store, dbFactory *dbfactory.DBFactory, stateCfg *state.State, task *api.Task, statement string, mi *db.MigrationInfo) (migrationID string, schema string, err error) {
statement = strings.TrimSpace(statement)
databaseName := task.Database.Name
driver, err := dbFactory.GetAdminDatabaseDriver(ctx, task.Instance, databaseName)
if err != nil {
- return 0, "", err
+ return "", "", err
}
defer driver.Close(ctx)
@@ -148,29 +148,29 @@ func executeMigration(ctx context.Context, store *store.Store, dbFactory *dbfact
setup, err := driver.NeedsSetupMigration(ctx)
if err != nil {
- return 0, "", errors.Wrapf(err, "failed to check migration setup for instance %q", task.Instance.Name)
+ return "", "", errors.Wrapf(err, "failed to check migration setup for instance %q", task.Instance.Name)
}
if setup {
- return 0, "", common.Errorf(common.MigrationSchemaMissing, "missing migration schema for instance %q", task.Instance.Name)
+ return "", "", common.Errorf(common.MigrationSchemaMissing, "missing migration schema for instance %q", task.Instance.Name)
}
if task.Type == api.TaskDatabaseDataUpdate && task.Instance.Engine == db.MySQL {
updatedTask, err := setThreadIDAndStartBinlogCoordinate(ctx, driver, task, store)
if err != nil {
- return 0, "", errors.Wrap(err, "failed to update the task payload for MySQL rollback SQL")
+ return "", "", errors.Wrap(err, "failed to update the task payload for MySQL rollback SQL")
}
task = updatedTask
}
migrationID, schema, err = driver.ExecuteMigration(ctx, mi, statement)
if err != nil {
- return 0, "", err
+ return "", "", err
}
if task.Type == api.TaskDatabaseDataUpdate && task.Instance.Engine == db.MySQL {
updatedTask, err := setMigrationIDAndEndBinlogCoordinate(ctx, driver, task, store, migrationID)
if err != nil {
- return 0, "", errors.Wrap(err, "failed to update the task payload for MySQL rollback SQL")
+ return "", "", errors.Wrap(err, "failed to update the task payload for MySQL rollback SQL")
}
// The runner will periodically scan the map to generate rollback SQL asynchronously.
stateCfg.RollbackGenerateMap.Store(updatedTask.ID, updatedTask)
@@ -226,13 +226,13 @@ func setThreadIDAndStartBinlogCoordinate(ctx context.Context, driver db.Driver,
return updatedTask, nil
}
-func setMigrationIDAndEndBinlogCoordinate(ctx context.Context, driver db.Driver, task *api.Task, store *store.Store, migrationID int64) (*api.Task, error) {
+func setMigrationIDAndEndBinlogCoordinate(ctx context.Context, driver db.Driver, task *api.Task, store *store.Store, migrationID string) (*api.Task, error) {
payload := &api.TaskDatabaseDataUpdatePayload{}
if err := json.Unmarshal([]byte(task.Payload), payload); err != nil {
return nil, errors.Wrap(err, "invalid database data update payload")
}
- payload.MigrationID = int(migrationID)
+ payload.MigrationID = migrationID
db, err := driver.GetDBConnection(ctx, "")
if err != nil {
return nil, errors.Wrap(err, "failed to get the DB connection")
@@ -265,7 +265,7 @@ func setMigrationIDAndEndBinlogCoordinate(ctx context.Context, driver db.Driver,
return updatedTask, nil
}
-func postMigration(ctx context.Context, stores *store.Store, activityManager *activity.Manager, profile config.Profile, task *api.Task, vcsPushEvent *vcsPlugin.PushEvent, mi *db.MigrationInfo, migrationID int64, schema string) (bool, *api.TaskRunResultPayload, error) {
+func postMigration(ctx context.Context, stores *store.Store, activityManager *activity.Manager, profile config.Profile, task *api.Task, vcsPushEvent *vcsPlugin.PushEvent, mi *db.MigrationInfo, migrationID string, schema string) (bool, *api.TaskRunResultPayload, error) {
databaseName := task.Database.Name
issue, err := findIssueByTask(ctx, stores, task)
if err != nil {
diff --git a/server/runner/taskrun/pitr_restore_executor.go b/server/runner/taskrun/pitr_restore_executor.go
index fbb9475dd8..e5b2479c75 100644
--- a/server/runner/taskrun/pitr_restore_executor.go
+++ b/server/runner/taskrun/pitr_restore_executor.go
@@ -490,16 +490,16 @@ 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, store *store.Store, dbFactory *dbfactory.DBFactory, profile config.Profile, sourceDatabase, targetDatabase *api.Database, backup *api.Backup, task *api.Task) (int64, string, error) {
+func createBranchMigrationHistory(ctx context.Context, store *store.Store, dbFactory *dbfactory.DBFactory, profile config.Profile, sourceDatabase, targetDatabase *api.Database, backup *api.Backup, task *api.Task) (string, string, error) {
targetDriver, err := dbFactory.GetAdminDatabaseDriver(ctx, targetDatabase.Instance, targetDatabase.Name)
if err != nil {
- return -1, "", err
+ return "", "", err
}
defer targetDriver.Close(ctx)
issue, err := store.GetIssueByPipelineID(ctx, task.PipelineID)
if err != nil {
- return -1, "", errors.Wrapf(err, "failed to fetch containing issue when creating the migration history: %v", task.Name)
+ return "", "", errors.Wrapf(err, "failed to fetch containing issue when creating the migration history: %v", task.Name)
}
// Add a branch migration history record.
@@ -526,7 +526,7 @@ func createBranchMigrationHistory(ctx context.Context, store *store.Store, dbFac
}
migrationID, _, err := targetDriver.ExecuteMigration(ctx, m, "")
if err != nil {
- return -1, "", errors.Wrap(err, "failed to create migration history")
+ return "", "", errors.Wrap(err, "failed to create migration history")
}
return migrationID, m.Version, nil
}
diff --git a/server/runner/taskrun/schema_update_ghost_cutover_executor.go b/server/runner/taskrun/schema_update_ghost_cutover_executor.go
index a04f273ce5..6488bc9d51 100644
--- a/server/runner/taskrun/schema_update_ghost_cutover_executor.go
+++ b/server/runner/taskrun/schema_update_ghost_cutover_executor.go
@@ -102,32 +102,32 @@ func cutover(ctx context.Context, store *store.Store, dbFactory *dbfactory.DBFac
if err != nil {
return true, nil, err
}
- migrationID, schema, err := func() (migrationHistoryID int64, updatedSchema string, resErr error) {
+ migrationID, schema, err := func() (migrationHistoryID string, updatedSchema string, resErr error) {
driver, err := dbFactory.GetAdminDatabaseDriver(ctx, task.Instance, task.Database.Name)
if err != nil {
- return -1, "", err
+ return "", "", err
}
defer driver.Close(ctx)
needsSetup, err := driver.NeedsSetupMigration(ctx)
if err != nil {
- return -1, "", errors.Wrapf(err, "failed to check migration setup for instance %q", task.Instance.Name)
+ return "", "", errors.Wrapf(err, "failed to check migration setup for instance %q", task.Instance.Name)
}
if needsSetup {
- return -1, "", common.Errorf(common.MigrationSchemaMissing, "missing migration schema for instance %q", task.Instance.Name)
+ return "", "", common.Errorf(common.MigrationSchemaMissing, "missing migration schema for instance %q", task.Instance.Name)
}
executor := driver.(util.MigrationExecutor)
var prevSchemaBuf bytes.Buffer
if _, err := driver.Dump(ctx, mi.Database, &prevSchemaBuf, true); err != nil {
- return -1, "", err
+ return "", "", err
}
// wait for heartbeat lag.
// try to make the time gap between the migration history insertion and the actual cutover as close as possible.
cancelled := waitForCutover(ctx, migrationContext)
if cancelled {
- return -1, "", errors.Errorf("cutover poller cancelled")
+ return "", "", errors.Errorf("cutover poller cancelled")
}
insertedID, err := util.BeginMigration(ctx, executor, mi, prevSchemaBuf.String(), statement, db.BytebaseDatabase)
@@ -135,7 +135,7 @@ func cutover(ctx context.Context, store *store.Store, dbFactory *dbfactory.DBFac
if common.ErrorCode(err) == common.MigrationAlreadyApplied {
return insertedID, prevSchemaBuf.String(), nil
}
- return -1, "", errors.Wrapf(err, "failed to begin migration for issue %s", mi.IssueID)
+ return "", "", errors.Wrapf(err, "failed to begin migration for issue %s", mi.IssueID)
}
startedNs := time.Now().UnixNano()
@@ -143,22 +143,22 @@ func cutover(ctx context.Context, store *store.Store, dbFactory *dbfactory.DBFac
if err := util.EndMigration(ctx, executor, startedNs, insertedID, updatedSchema, db.BytebaseDatabase, resErr == nil /*isDone*/); err != nil {
log.Error("failed to update migration history record",
zap.Error(err),
- zap.Int64("migration_id", migrationHistoryID),
+ zap.String("migration_id", migrationHistoryID),
)
}
}()
if err := os.Remove(postponeFilename); err != nil {
- return -1, "", errors.Wrap(err, "failed to remove postpone flag file")
+ return "", "", errors.Wrap(err, "failed to remove postpone flag file")
}
if migrationErr := <-errCh; migrationErr != nil {
- return -1, "", errors.Wrapf(migrationErr, "failed to run gh-ost migration")
+ return "", "", errors.Wrapf(migrationErr, "failed to run gh-ost migration")
}
var afterSchemaBuf bytes.Buffer
if _, err := executor.Dump(ctx, mi.Database, &afterSchemaBuf, true /*schemaOnly*/); err != nil {
- return -1, "", util.FormatError(err)
+ return "", "", util.FormatError(err)
}
return insertedID, afterSchemaBuf.String(), nil
diff --git a/store/migration/dev/20230106000000##change_migration_history_id_type_to_string.sql b/store/migration/dev/20230106000000##change_migration_history_id_type_to_string.sql
new file mode 100644
index 0000000000..874924c5e0
--- /dev/null
+++ b/store/migration/dev/20230106000000##change_migration_history_id_type_to_string.sql
@@ -0,0 +1,4 @@
+UPDATE task_run
+SET result = result || jsonb_build_object('migrationId', result->>'migrationId'::TEXT)
+WHERE result ? 'migrationId';
+
diff --git a/tests/instance.go b/tests/instance.go
index 39c802f983..a437961c02 100644
--- a/tests/instance.go
+++ b/tests/instance.go
@@ -44,7 +44,7 @@ func (ctl *controller) getInstanceByID(instanceID int) (*api.Instance, error) {
return instance, nil
}
-func (ctl *controller) getInstanceMigrationHistory(find db.MigrationHistoryFind) ([]*api.MigrationHistory, error) {
+func (ctl *controller) getInstanceMigrationHistory(instanceID int, find db.MigrationHistoryFind) ([]*api.MigrationHistory, error) {
params := make(map[string]string)
if find.Database != nil {
params["database"] = *find.Database
@@ -55,7 +55,7 @@ func (ctl *controller) getInstanceMigrationHistory(find db.MigrationHistoryFind)
if find.Limit != nil {
params["limit"] = fmt.Sprintf("%d", *find.Limit)
}
- body, err := ctl.get(fmt.Sprintf("/instance/%v/migration/history", *find.ID), params)
+ body, err := ctl.get(fmt.Sprintf("/instance/%d/migration/history", instanceID), params)
if err != nil {
return nil, err
}
diff --git a/tests/schema_update_test.go b/tests/schema_update_test.go
index 7623aebe78..e9c49173dd 100644
--- a/tests/schema_update_test.go
+++ b/tests/schema_update_test.go
@@ -155,7 +155,7 @@ func TestSchemaAndDataUpdate(t *testing.T) {
a.Equal(api.TaskDone, status)
// Get migration history.
- histories, err := ctl.getInstanceMigrationHistory(db.MigrationHistoryFind{ID: &instance.ID})
+ histories, err := ctl.getInstanceMigrationHistory(instance.ID, db.MigrationHistoryFind{})
a.NoError(err)
wantHistories := []api.MigrationHistory{
{
@@ -224,7 +224,7 @@ func TestSchemaAndDataUpdate(t *testing.T) {
a.NoError(err)
a.Equal(bookDataSQLResult, result)
// Query clone migration history.
- histories, err = ctl.getInstanceMigrationHistory(db.MigrationHistoryFind{ID: &instance.ID, Database: &cloneDatabaseName})
+ histories, err = ctl.getInstanceMigrationHistory(instance.ID, db.MigrationHistoryFind{Database: &cloneDatabaseName})
a.NoError(err)
wantCloneHistories := []api.MigrationHistory{
{
@@ -580,7 +580,7 @@ func TestVCS(t *testing.T) {
a.NoError(err)
// Get migration history.
- histories, err := ctl.getInstanceMigrationHistory(db.MigrationHistoryFind{ID: &instance.ID})
+ histories, err := ctl.getInstanceMigrationHistory(instance.ID, db.MigrationHistoryFind{})
a.NoError(err)
var historiesDeref []api.MigrationHistory
@@ -1002,7 +1002,7 @@ ALTER TABLE ONLY public.users
`
- histories, err := ctl.getInstanceMigrationHistory(db.MigrationHistoryFind{ID: &instance.ID})
+ histories, err := ctl.getInstanceMigrationHistory(instance.ID, db.MigrationHistoryFind{})
a.NoError(err)
wantHistories := []api.MigrationHistory{
{
diff --git a/tests/sync_schema_test.go b/tests/sync_schema_test.go
index a09a4abf5f..2f291e4efc 100644
--- a/tests/sync_schema_test.go
+++ b/tests/sync_schema_test.go
@@ -137,8 +137,7 @@ DROP SCHEMA "schema_a";
a.NoError(err)
a.Equal(api.TaskDone, status)
- history, err := ctl.getInstanceMigrationHistory(db.MigrationHistoryFind{
- ID: &instance.ID,
+ history, err := ctl.getInstanceMigrationHistory(instance.ID, db.MigrationHistoryFind{
Database: &database.Name,
})
a.NoError(err)
diff --git a/tests/tenant_test.go b/tests/tenant_test.go
index 9c551632d6..09c0257dfd 100644
--- a/tests/tenant_test.go
+++ b/tests/tenant_test.go
@@ -185,7 +185,7 @@ func TestTenant(t *testing.T) {
hm1 := map[string]bool{}
hm2 := map[string]bool{}
for _, instance := range instances {
- histories, err := ctl.getInstanceMigrationHistory(db.MigrationHistoryFind{ID: &instance.ID, Database: &databaseName})
+ histories, err := ctl.getInstanceMigrationHistory(instance.ID, db.MigrationHistoryFind{Database: &databaseName})
a.NoError(err)
a.Equal(2, len(histories))
a.NotEqual(histories[0].Version, "")
@@ -482,8 +482,8 @@ func TestTenantVCS(t *testing.T) {
hm2 := map[string]bool{}
for _, instance := range instances {
histories, err := ctl.getInstanceMigrationHistory(
+ instance.ID,
db.MigrationHistoryFind{
- ID: &instance.ID,
Database: &databaseName,
},
)
@@ -936,8 +936,8 @@ func TestTenantVCSDatabaseNameTemplate(t *testing.T) {
tenant := fmt.Sprintf("tenant%d", i)
databaseName := baseDatabaseName + "_" + tenant
histories, err := ctl.getInstanceMigrationHistory(
+ instance.ID,
db.MigrationHistoryFind{
- ID: &instance.ID,
Database: &databaseName,
},
)
@@ -951,8 +951,8 @@ func TestTenantVCSDatabaseNameTemplate(t *testing.T) {
tenant := fmt.Sprintf("tenant%d", i)
databaseName := baseDatabaseName + "_" + tenant
histories, err := ctl.getInstanceMigrationHistory(
+ instance.ID,
db.MigrationHistoryFind{
- ID: &instance.ID,
Database: &databaseName,
},
)
@@ -1244,8 +1244,8 @@ func TestTenantVCSDatabaseNameTemplate_Empty(t *testing.T) {
tenant := fmt.Sprintf("tenant%d", i)
databaseName := baseDatabaseName + "_" + tenant
histories, err := ctl.getInstanceMigrationHistory(
+ instance.ID,
db.MigrationHistoryFind{
- ID: &instance.ID,
Database: &databaseName,
},
)
@@ -1552,8 +1552,8 @@ statement: |
// Query migration history, only the database of the first tenant should be touched
histories, err := ctl.getInstanceMigrationHistory(
+ testInstances[0].ID,
db.MigrationHistoryFind{
- ID: &testInstances[0].ID,
Database: &databases[0].Name,
},
)
@@ -1562,8 +1562,8 @@ statement: |
require.Equal(t, histories[0].Version, "ver2")
histories, err = ctl.getInstanceMigrationHistory(
+ testInstances[1].ID,
db.MigrationHistoryFind{
- ID: &testInstances[1].ID,
Database: &databases[1].Name,
},
)