Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
chore: cleanup execute migration (#5430)
Danny Xuf8a9413eec6d
diff --git a/backend/bin/bb/cmd/migrate.go b/backend/bin/bb/cmd/migrate.goindex 68aa794579..7cddee3136 100644--- a/backend/bin/bb/cmd/migrate.go+++ b/backend/bin/bb/cmd/migrate.go@@ -5,15 +5,11 @@ import ("context""io""os"- "os/user""strings""github.com/pkg/errors""github.com/spf13/cobra""github.com/xo/dburl"-- "github.com/bytebase/bytebase/backend/common"- "github.com/bytebase/bytebase/backend/plugin/db")func newMigrateCmd() *cobra.Command {@@ -52,7 +48,7 @@ func newMigrateCmd() *cobra.Command {}sqlReader := io.MultiReader(sqlReaders...)- return migrateDatabase(context.Background(), u, description, issueID, false /* createDatabase */, sqlReader)+ return migrateDatabase(context.Background(), u, sqlReader)}}migrateCmd.Flags().StringVar(&dsn, "dsn", "", dsnUsage)@@ -63,34 +59,18 @@ func newMigrateCmd() *cobra.Command {return migrateCmd}-func migrateDatabase(ctx context.Context, u *dburl.URL, description, issueID string, createDatabase bool, sqlReader io.Reader) error {+func migrateDatabase(ctx context.Context, u *dburl.URL, sqlReader io.Reader) error {driver, err := open(ctx, u)if err != nil {return err}defer driver.Close(ctx)- migrationCreator := "bb-unknown-creator"- if currentUser, err := user.Current(); err == nil {- migrationCreator = currentUser.Username- }-var buf bytes.Bufferif _, err := io.Copy(&buf, sqlReader); err != nil {return errors.Wrap(err, "failed to read sql file")}- // TODO(d): support semantic versioning.- if _, _, err := driver.ExecuteMigration(ctx, &db.MigrationInfo{- ReleaseVersion: version,- Version: common.DefaultMigrationVersion(),- Database: getDatabase(u),- Source: db.LIBRARY,- Type: db.Migrate,- Description: description,- Creator: migrationCreator,- IssueID: issueID,- CreateDatabase: createDatabase,- }, buf.String()); err != nil {+ if _, err := driver.Execute(ctx, buf.String(), false /* createDatabase */); err != nil {return errors.Wrap(err, "failed to migrate database")}return nildiff --git a/backend/plugin/advisor/utils_for_tests.go b/backend/plugin/advisor/utils_for_tests.goindex eff276b035..309a2654c6 100644--- a/backend/plugin/advisor/utils_for_tests.go+++ b/backend/plugin/advisor/utils_for_tests.go@@ -302,11 +302,6 @@ func (*MockDriver) SetupMigrationIfNeeded(_ context.Context) error {return nil}-// ExecuteMigration implements the Driver interface.-func (*MockDriver) ExecuteMigration(_ context.Context, _ *database.MigrationInfo, _ string) (string, string, error) {- return "", "", nil-}-// FindMigrationHistoryList implements the Driver interface.func (*MockDriver) FindMigrationHistoryList(_ context.Context, _ *database.MigrationHistoryFind) ([]*database.MigrationHistory, error) {return nil, nildiff --git a/backend/plugin/db/clickhouse/migrate.go b/backend/plugin/db/clickhouse/migrate.goindex 86a56a06d6..91f7594d49 100644--- a/backend/plugin/db/clickhouse/migrate.go+++ b/backend/plugin/db/clickhouse/migrate.go@@ -8,12 +8,6 @@ import ("github.com/bytebase/bytebase/backend/plugin/db/util")-// ExecuteMigration will execute the migration.-func (driver *Driver) ExecuteMigration(ctx context.Context, m *db.MigrationInfo, statement string) (string, string, error) {- _, err := driver.Execute(ctx, statement, m.CreateDatabase)- return "", "", err-}-// FindMigrationHistoryList finds the migration history.func (driver *Driver) FindMigrationHistoryList(ctx context.Context, find *db.MigrationHistoryFind) ([]*db.MigrationHistory, error) {baseQuery := `diff --git a/backend/plugin/db/driver.go b/backend/plugin/db/driver.goindex 76a56725d8..edde413048 100644--- a/backend/plugin/db/driver.go+++ b/backend/plugin/db/driver.go@@ -480,9 +480,6 @@ type Driver interface {// DeleteRole deletes the role by name.DeleteRole(ctx context.Context, roleName string) error- // Execute migration will apply the statement.- // The migration type is determined by m.Type. Note, it can also perform data migration (DML) in addition to schema migration (DDL).- 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/backend/plugin/db/mongodb/migrate.go b/backend/plugin/db/mongodb/migrate.goindex 1016e7a4cb..a301fd6adf 100644--- a/backend/plugin/db/mongodb/migrate.go+++ b/backend/plugin/db/mongodb/migrate.go@@ -2,7 +2,6 @@ package mongodbimport ("context"- "database/sql""fmt""strconv"@@ -44,12 +43,6 @@ type MigrationHistory struct {Payload string `bson:"payload"`}-// ExecuteMigration executes a migration.-func (driver *Driver) ExecuteMigration(ctx context.Context, m *db.MigrationInfo, statement string) (string, string, error) {- _, err := driver.Execute(ctx, statement, m.CreateDatabase)- return "", "", err-}-// FindMigrationHistoryList finds the migration history list.func (driver *Driver) FindMigrationHistoryList(ctx context.Context, find *db.MigrationHistoryFind) ([]*db.MigrationHistory, error) {database := driver.client.Database(migrationHistoryDefaultDatabase)@@ -132,51 +125,3 @@ func convertMigrationHistory(history MigrationHistory) (db.MigrationHistory, errSemanticVersionSuffix: semanticVersionSuffix,}, nil}--// FindLargestSequence finds the largest sequence, return 0 if not found.-func (driver *Driver) FindLargestSequence(ctx context.Context, _ *sql.Tx, namespace string, baseline bool) (int, error) {- collection := driver.client.Database(migrationHistoryDefaultDatabase).Collection(migrationHistoryDefaultCollection)- filter := bson.M{- "namespace": namespace,- }- if baseline {- filter["type"] = bson.M{"$in": []string{string(db.Baseline), string(db.Branch)}}- }-- // Set up MAX(sequence) aggregation.- aggregation := []bson.M{- {- "$match": filter,- },- {- "$group": bson.M{- "_id": nil,- "sequence": bson.M{"$max": "$sequence"},- },- },- }-- cursor, err := collection.Aggregate(ctx, aggregation)- if err != nil {- return 0, errors.Wrapf(err, "failed to aggregate migration history list to find largest sequence")- }- defer cursor.Close(ctx)-- var result bson.M- if cursor.Next(ctx) {- if err := cursor.Decode(&result); err != nil {- return 0, errors.Wrapf(err, "failed to decode find largest sequence aggregation result")- }- if sequence, ok := result["sequence"]; ok {- if sequenceInt, ok := sequence.(int64); ok {- return int(sequenceInt), nil- }- }- return 0, errors.Errorf("failed to get sequence from find largest sequence aggregation result: %+v", result)- }- // If cursor contains no data, we check the err, if err is nil, it means that the query is successful, but there is no data.- if err := cursor.Err(); err != nil {- return 0, errors.Wrapf(err, "failed to find largest sequence")- }- return 0, nil-}diff --git a/backend/plugin/db/mssql/migrate.go b/backend/plugin/db/mssql/migrate.goindex 3b2d321de5..1fc8d267b8 100644--- a/backend/plugin/db/mssql/migrate.go+++ b/backend/plugin/db/mssql/migrate.go@@ -5,19 +5,8 @@ import ("errors""github.com/bytebase/bytebase/backend/plugin/db"- "github.com/bytebase/bytebase/backend/plugin/db/util")-// ExecuteMigration executes a migration.-// ExecuteMigration will execute the database migration.-// Returns the created migration history id and the updated schema on success.-func (d *Driver) ExecuteMigration(ctx context.Context, m *db.MigrationInfo, statement string) (migrationHistoryID string, updatedSchema string, resErr error) {- if _, err := d.Execute(ctx, statement, m.CreateDatabase); err != nil {- return "", "", util.FormatError(err)- }- return "", "", nil-}-// FindMigrationHistoryList finds the migration history list and return most recent item first.func (*Driver) FindMigrationHistoryList(context.Context, *db.MigrationHistoryFind) ([]*db.MigrationHistory, error) {return nil, errors.New("unsupported")diff --git a/backend/plugin/db/mysql/migrate.go b/backend/plugin/db/mysql/migrate.goindex 9e69b10df2..bf5992f629 100644--- a/backend/plugin/db/mysql/migrate.go+++ b/backend/plugin/db/mysql/migrate.go@@ -8,12 +8,6 @@ import ("github.com/bytebase/bytebase/backend/plugin/db/util")-// ExecuteMigration will execute the migration.-func (driver *Driver) ExecuteMigration(ctx context.Context, m *db.MigrationInfo, statement string) (string, string, error) {- _, err := driver.Execute(ctx, statement, m.CreateDatabase)- return "", "", err-}-// FindMigrationHistoryList finds the migration history.func (driver *Driver) FindMigrationHistoryList(ctx context.Context, find *db.MigrationHistoryFind) ([]*db.MigrationHistory, error) {baseQuery := `diff --git a/backend/plugin/db/oracle/migrate.go b/backend/plugin/db/oracle/migrate.goindex b5533b990d..668f292935 100644--- a/backend/plugin/db/oracle/migrate.go+++ b/backend/plugin/db/oracle/migrate.go@@ -9,17 +9,9 @@ import ("github.com/bytebase/bytebase/backend/plugin/db/util")-// ExecuteMigration executes a migration.-// ExecuteMigration will execute the database migration.-// Returns the created migration history id and the updated schema on success.-func (d *Driver) ExecuteMigration(ctx context.Context, m *db.MigrationInfo, statement string) (migrationHistoryID string, updatedSchema string, resErr error) {- return d.ExecuteMigrationWithBeforeCommitTxFunc(ctx, m, statement, nil)-}-// ExecuteMigrationWithBeforeCommitTxFunc executes the migration, `beforeCommitTxFunc` will be called before transaction commit and after executing `statement`.//// Callers can use `beforeCommitTx` to do some extra work before transaction commit, like get the transaction id.-//// Any error returned by `beforeCommitTx` will rollback the transaction, so it is the callers' responsibility to return nil if the error occurs in `beforeCommitTx` is not fatal.func (d *Driver) ExecuteMigrationWithBeforeCommitTxFunc(ctx context.Context, m *db.MigrationInfo, statement string, beforeCommitTxFunc func(tx *sql.Tx) error) (migrationHistoryID string, updatedSchema string, resErr error) {if m.CreateDatabase {diff --git a/backend/plugin/db/pg/migrate.go b/backend/plugin/db/pg/migrate.goindex 9f11447232..a5dd62d0bc 100644--- a/backend/plugin/db/pg/migrate.go+++ b/backend/plugin/db/pg/migrate.go@@ -1,9 +1,12 @@package pgimport (+ "bytes""context""database/sql""fmt"+ "strings"+ "time"// embed will embeds the migration schema._ "embed"@@ -11,6 +14,7 @@ import ("github.com/pkg/errors""go.uber.org/zap"+ "github.com/bytebase/bytebase/backend/common""github.com/bytebase/bytebase/backend/common/log""github.com/bytebase/bytebase/backend/plugin/db""github.com/bytebase/bytebase/backend/plugin/db/util"@@ -19,8 +23,6 @@ import (var (//go:embed pg_migration_schema.sqlmigrationSchema string-- _ util.MigrationExecutor = (*Driver)(nil))// NeedsSetupMigration returns whether it needs to setup migration.@@ -46,7 +48,20 @@ func (driver *Driver) NeedsSetupMigration(ctx context.Context) (bool, error) {WHERE table_name = 'migration_history'`- return util.NeedsSetupMigrationSchema(ctx, driver.db, query)+ rows, err := driver.db.QueryContext(ctx, query)+ if err != nil {+ return false, err+ }+ defer rows.Close()++ if rows.Next() {+ return false, nil+ }+ if err := rows.Err(); err != nil {+ return false, err+ }++ return true, nil}// SetupMigrationIfNeeded sets up migration if needed.@@ -241,18 +256,193 @@ func (*Driver) UpdateHistoryAsFailed(ctx context.Context, tx *sql.Tx, migrationDreturn err}-// ExecuteMigration will execute the migration.-func (driver *Driver) ExecuteMigration(ctx context.Context, m *db.MigrationInfo, statement string) (string, string, error) {- _, err := driver.Execute(ctx, statement, m.CreateDatabase)- return "", "", err-}-// ExecuteMigrationUsingMigrationHistory will execute the migration and stores the record to migration history.func (driver *Driver) ExecuteMigrationUsingMigrationHistory(ctx context.Context, m *db.MigrationInfo, statement string) (string, string, error) {if driver.strictUseDb() {- return util.ExecuteMigration(ctx, driver, m, statement, driver.strictDatabase)+ return driver.executeMigration(ctx, m, statement, driver.strictDatabase)+ }+ return driver.executeMigration(ctx, m, statement, db.BytebaseDatabase)+}++// executeMigration will execute the database migration.+// Returns the created migration history id and the updated schema on success.+func (driver *Driver) executeMigration(ctx context.Context, 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 {+ // 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 := driver.Dump(ctx, m.Database, &prevSchemaBuf, true /* schemaOnly */); err != nil {+ return "", "", err+ }+ }++ // Phase 1 - Pre-check before executing migration+ // Phase 2 - Record migration history as PENDING+ insertedID, err := driver.beginMigration(ctx, m, prevSchemaBuf.String(), statement, databaseName)+ if err != nil {+ if common.ErrorCode(err) == common.MigrationAlreadyApplied {+ return insertedID, prevSchemaBuf.String(), nil+ }+ return "", "", errors.Wrapf(err, "failed to begin migration for issue %s", m.IssueID)+ }++ startedNs := time.Now().UnixNano()++ defer func() {+ if err := driver.endMigration(ctx, startedNs, insertedID, updatedSchema, databaseName, resErr == nil /* isDone */); err != nil {+ log.Error("Failed to update migration history record",+ zap.Error(err),+ zap.String("migration_id", migrationHistoryID),+ )+ }+ }()++ // Phase 3 - Executing migration+ // Branch migration type always has empty sql.+ // Baseline migration type could has non-empty sql but will not execute.+ // https://github.com/bytebase/bytebase/issues/394+ doMigrate := true+ if statement == "" {+ doMigrate = false+ }+ if m.Type == db.Baseline {+ doMigrate = false+ }+ if doMigrate {+ // Switch to the target database only if we're NOT creating this target database.+ // We should not call GetDBConnection() if the instance is MongoDB because it doesn't support.+ if !m.CreateDatabase {+ if _, err := driver.GetDBConnection(ctx, m.Database); err != nil {+ return "", "", err+ }+ }+ if _, err := driver.Execute(ctx, statement, m.CreateDatabase); err != nil {+ return "", "", err+ }+ }++ // Phase 4 - Dump the schema after migration+ var afterSchemaBuf bytes.Buffer+ if _, err := driver.Dump(ctx, m.Database, &afterSchemaBuf, true /* schemaOnly */); err != nil {+ // We will ignore the dump error if the database is dropped.+ if strings.Contains(err.Error(), "not found") {+ return insertedID, "", nil+ }+ return "", "", err+ }++ return insertedID, afterSchemaBuf.String(), nil+}++// beginMigration checks before executing migration and inserts a migration history record with pending status.+func (driver *Driver) beginMigration(ctx context.Context, m *db.MigrationInfo, prevSchema string, statement string, databaseName string) (insertedID string, err 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 := driver.FindMigrationHistoryList(ctx, &db.MigrationHistoryFind{+ Database: &m.Namespace,+ 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:+ if migrationHistory.IssueID != m.IssueID {+ return migrationHistory.ID, common.Errorf(common.MigrationFailed, "database %q has already applied version %s by issue %s", m.Database, m.Version, migrationHistory.IssueID)+ }+ return migrationHistory.ID, common.Errorf(common.MigrationAlreadyApplied, "database %q has already applied version %s", m.Database, m.Version)+ 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 migrationHistory.ID, nil+ }+ 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 migrationHistory.ID, nil+ }+ return "", common.Wrap(err, common.MigrationFailed)+ }+ }++ // We use transaction here for the RDBMS.+ sqldb, err := driver.GetDBConnection(ctx, databaseName)+ if err != nil {+ 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 "", err+ }+ defer tx.Rollback()++ largestSequence, err := driver.FindLargestSequence(ctx, tx, m.Namespace, false /* baseline */)+ if err != nil {+ return "", err+ }++ // Check if there is any higher version already been applied since the last baseline or branch.+ if version, err := driver.FindLargestVersionSinceBaseline(ctx, tx, m.Namespace); err != nil {+ 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 "", 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.+ // 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.+ statementRecord, _ := common.TruncateString(statement, common.MaxSheetSize)+ if insertedID, err = driver.InsertPendingHistory(ctx, tx, largestSequence+1, prevSchema, m, storedVersion, statementRecord); err != nil {+ return "", err+ }++ if err := tx.Commit(); err != nil {+ return "", err+ }++ return insertedID, nil+}++// endMigration updates the migration history record to DONE or FAILED depending on migration is done or not.+func (driver *Driver) endMigration(ctx context.Context, startedNs int64, migrationHistoryID string, updatedSchema string, databaseName string, isDone bool) (err error) {+ migrationDurationNs := time.Now().UnixNano() - startedNs++ sqldb, err := driver.GetDBConnection(ctx, databaseName)+ if err != nil {+ return err+ }+ tx, err := sqldb.BeginTx(ctx, nil)+ if err != nil {+ return err+ }+ defer tx.Rollback()++ if isDone {+ // Upon success, update the migration history as 'DONE', execution_duration_ns, updated schema.+ err = driver.UpdateHistoryAsDone(ctx, tx, migrationDurationNs, updatedSchema, migrationHistoryID)+ } else {+ // Otherwise, update the migration history as 'FAILED', execution_duration.+ err = driver.UpdateHistoryAsFailed(ctx, tx, migrationDurationNs, migrationHistoryID)+ }++ if err != nil {+ return err}- return util.ExecuteMigration(ctx, driver, m, statement, db.BytebaseDatabase)+ return tx.Commit()}// FindMigrationHistoryList finds the migration history.diff --git a/backend/plugin/db/redis/migrate.go b/backend/plugin/db/redis/migrate.goindex d7fc12c66b..e245b70dae 100644--- a/backend/plugin/db/redis/migrate.go+++ b/backend/plugin/db/redis/migrate.go@@ -6,22 +6,8 @@ import ("github.com/pkg/errors""github.com/bytebase/bytebase/backend/plugin/db"- "github.com/bytebase/bytebase/backend/plugin/db/util")-// ExecuteMigration executes a migration.-// ExecuteMigration will execute the database migration.-// Returns the created migration history id and the updated schema on success.-func (d *Driver) ExecuteMigration(ctx context.Context, m *db.MigrationInfo, statement string) (migrationHistoryID string, updatedSchema string, resErr error) {- if m.CreateDatabase {- return "", "", errors.New("redis: creating databases is not supported")- }- if _, err := d.Execute(ctx, statement, m.CreateDatabase); err != nil {- return "", "", util.FormatError(err)- }- return "", "", nil-}-// FindMigrationHistoryList finds the migration history list and return most recent item first.func (*Driver) FindMigrationHistoryList(context.Context, *db.MigrationHistoryFind) ([]*db.MigrationHistory, error) {return nil, errors.New("redis: not supported")diff --git a/backend/plugin/db/redshift/migrate.go b/backend/plugin/db/redshift/migrate.goindex 381f34ca3f..7c5ffef245 100644--- a/backend/plugin/db/redshift/migrate.go+++ b/backend/plugin/db/redshift/migrate.go@@ -5,19 +5,8 @@ import ("errors""github.com/bytebase/bytebase/backend/plugin/db"- "github.com/bytebase/bytebase/backend/plugin/db/util")-// ExecuteMigration executes a migration.-// ExecuteMigration will execute the database migration.-// Returns the created migration history id and the updated schema on success.-func (d *Driver) ExecuteMigration(ctx context.Context, m *db.MigrationInfo, statement string) (migrationHistoryID string, updatedSchema string, resErr error) {- if _, err := d.Execute(ctx, statement, m.CreateDatabase); err != nil {- return "", "", util.FormatError(err)- }- return "", "", nil-}-// FindMigrationHistoryList finds the migration history list and return most recent item first.func (*Driver) FindMigrationHistoryList(context.Context, *db.MigrationHistoryFind) ([]*db.MigrationHistory, error) {return nil, errors.New("unsupported")diff --git a/backend/plugin/db/snowflake/migrate.go b/backend/plugin/db/snowflake/migrate.goindex 665a5c3f0a..551615554b 100644--- a/backend/plugin/db/snowflake/migrate.go+++ b/backend/plugin/db/snowflake/migrate.go@@ -8,12 +8,6 @@ import ("github.com/bytebase/bytebase/backend/plugin/db/util")-// ExecuteMigration will execute the migration.-func (driver *Driver) ExecuteMigration(ctx context.Context, m *db.MigrationInfo, statement string) (string, string, error) {- _, err := driver.Execute(ctx, statement, m.CreateDatabase)- return "", "", err-}-// FindMigrationHistoryList finds the migration history.func (driver *Driver) FindMigrationHistoryList(ctx context.Context, find *db.MigrationHistoryFind) ([]*db.MigrationHistory, error) {baseQuery := `diff --git a/backend/plugin/db/spanner/migrate.go b/backend/plugin/db/spanner/migrate.goindex be27d55f41..f9cda6fffa 100644--- a/backend/plugin/db/spanner/migrate.go+++ b/backend/plugin/db/spanner/migrate.go@@ -9,8 +9,6 @@ import ("cloud.google.com/go/spanner/admin/database/apiv1/databasepb""go.uber.org/zap"- "github.com/pkg/errors"-"github.com/bytebase/bytebase/backend/common/log""github.com/bytebase/bytebase/backend/plugin/db""github.com/bytebase/bytebase/backend/plugin/db/util"@@ -47,36 +45,6 @@ func (d *Driver) creataDatabase(ctx context.Context, createStatement string, extreturn nil}-// ExecuteMigration executes a migration.-// ExecuteMigration will execute the database migration.-func (d *Driver) ExecuteMigration(ctx context.Context, m *db.MigrationInfo, statement string) (migrationHistoryID string, updatedSchema string, resErr error) {- if statement == "" || m.Type == db.Baseline {- return "", "", nil- }-- if !m.CreateDatabase {- if _, err := d.Execute(ctx, statement, m.CreateDatabase); err != nil {- return "", "", util.FormatError(err)- }- } else {- stmts, err := sanitizeSQL(statement)- if err != nil {- return "", "", errors.Wrapf(err, "failed to sanitize %v", statement)- }- if len(stmts) == 0 {- return "", "", errors.Errorf("expect sanitized SQLs to have at least one entry, original statement: %v", statement)- }- if !strings.HasPrefix(stmts[0], "CREATE DATABASE") {- return "", "", errors.Errorf("expect the first entry of the sanitized SQLs to start with 'CREATE DATABASE', sql %v", stmts[0])- }- if err := d.creataDatabase(ctx, stmts[0], stmts[1:]); err != nil {- return "", "", errors.Wrap(err, "failed to create database")- }- }-- return "", "", nil-}-// FindMigrationHistoryList finds the migration history list.func (d *Driver) FindMigrationHistoryList(ctx context.Context, find *db.MigrationHistoryFind) ([]*db.MigrationHistory, error) {defer func(db string) {diff --git a/backend/plugin/db/spanner/spanner.go b/backend/plugin/db/spanner/spanner.goindex cca9c0c992..1a9a558304 100644--- a/backend/plugin/db/spanner/spanner.go+++ b/backend/plugin/db/spanner/spanner.go@@ -147,8 +147,22 @@ func (*Driver) GetDBConnection(_ context.Context, _ string) (*sql.DB, error) {// Execute executes a SQL statement.func (d *Driver) Execute(ctx context.Context, statement string, createDatabase bool) (int64, error) {if createDatabase {- return 0, errors.Errorf("cannot set createDatabase to true")+ stmts, err := sanitizeSQL(statement)+ if err != nil {+ return 0, errors.Wrapf(err, "failed to sanitize %v", statement)+ }+ if len(stmts) == 0 {+ return 0, errors.Errorf("expect sanitized SQLs to have at least one entry, original statement: %v", statement)+ }+ if !strings.HasPrefix(stmts[0], "CREATE DATABASE") {+ return 0, errors.Errorf("expect the first entry of the sanitized SQLs to start with 'CREATE DATABASE', sql %v", stmts[0])+ }+ if err := d.creataDatabase(ctx, stmts[0], stmts[1:]); err != nil {+ return 0, errors.Wrap(err, "failed to create database")+ }+ return 0, nil}+var rowCount int64stmts, err := sanitizeSQL(statement)if err != nil {diff --git a/backend/plugin/db/sqlite/migrate.go b/backend/plugin/db/sqlite/migrate.goindex 23360c9f92..efcad289b8 100644--- a/backend/plugin/db/sqlite/migrate.go+++ b/backend/plugin/db/sqlite/migrate.go@@ -8,12 +8,6 @@ import ("github.com/bytebase/bytebase/backend/plugin/db/util")-// ExecuteMigration will execute the migration.-func (driver *Driver) ExecuteMigration(ctx context.Context, m *db.MigrationInfo, statement string) (string, string, error) {- _, err := driver.Execute(ctx, statement, m.CreateDatabase)- return "", "", err-}-// FindMigrationHistoryList finds the migration history.func (driver *Driver) FindMigrationHistoryList(ctx context.Context, find *db.MigrationHistoryFind) ([]*db.MigrationHistory, error) {baseQuery := `diff --git a/backend/plugin/db/util/driverutil.go b/backend/plugin/db/util/driverutil.goindex 562ab1042f..fc3bddcaee 100644--- a/backend/plugin/db/util/driverutil.go+++ b/backend/plugin/db/util/driverutil.go@@ -3,7 +3,6 @@ package utilimport ("bufio"- "bytes""context""database/sql""fmt"@@ -21,10 +20,8 @@ import ("github.com/paulmach/orb/encoding/wkt""github.com/pkg/errors""github.com/shopspring/decimal"- "go.uber.org/zap""github.com/bytebase/bytebase/backend/common"- "github.com/bytebase/bytebase/backend/common/log""github.com/bytebase/bytebase/backend/plugin/db")@@ -121,244 +118,6 @@ func ApplyMultiStatements(sc io.Reader, f func(string) error) error {return nil}-// NeedsSetupMigrationSchema will return whether it's needed to setup migration schema.-func NeedsSetupMigrationSchema(ctx context.Context, sqldb *sql.DB, query string) (bool, error) {- rows, err := sqldb.QueryContext(ctx, query)- if err != nil {- return false, FormatErrorWithQuery(err, query)- }- defer rows.Close()-- if rows.Next() {- return false, nil- }- if err := rows.Err(); err != nil {- return false, err- }-- return true, nil-}--// MigrationExecutor is an adapter for ExecuteMigration().-type MigrationExecutor interface {- db.Driver- // 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, 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 string) error- // UpdateHistoryAsFailed will update the migration record as failed.- 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 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 "", "", FormatError(err)- }- }-- // Phase 1 - Pre-check before executing migration- // Phase 2 - Record migration history as PENDING- insertedID, err := BeginMigration(ctx, executor, m, prevSchemaBuf.String(), statement, databaseName)- if err != nil {- if common.ErrorCode(err) == common.MigrationAlreadyApplied {- return insertedID, prevSchemaBuf.String(), nil- }- return "", "", errors.Wrapf(err, "failed to begin migration for issue %s", m.IssueID)- }-- startedNs := time.Now().UnixNano()-- defer func() {- 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.String("migration_id", migrationHistoryID),- )- }- }()-- // Phase 3 - Executing migration- // Branch migration type always has empty sql.- // Baseline migration type could has non-empty sql but will not execute.- // https://github.com/bytebase/bytebase/issues/394- doMigrate := true- if statement == "" {- doMigrate = false- }- if m.Type == db.Baseline {- doMigrate = false- }- if doMigrate {- // Switch to the target database only if we're NOT creating this target database.- // 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 "", "", err- }- }- if _, err := executor.Execute(ctx, statement, m.CreateDatabase); err != nil {- return "", "", FormatError(err)- }- }-- if executor.GetType() == db.MongoDB {- // Skip schema dump for MongoDB because it's schemaless.- return insertedID, "", nil- }- // Phase 4 - Dump the schema after migration- var afterSchemaBuf bytes.Buffer- if _, err := executor.Dump(ctx, m.Database, &afterSchemaBuf, true /* schemaOnly */); err != nil {- // We will ignore the dump error if the database is dropped.- if strings.Contains(err.Error(), "not found") {- return insertedID, "", nil- }- 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 string, err error) {- // Convert version to stored version.- storedVersion, err := 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 := executor.FindMigrationHistoryList(ctx, &db.MigrationHistoryFind{- Database: &m.Namespace,- 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:- if migrationHistory.IssueID != m.IssueID {- return migrationHistory.ID, common.Errorf(common.MigrationFailed, "database %q has already applied version %s by issue %s", m.Database, m.Version, migrationHistory.IssueID)- }- return migrationHistory.ID, common.Errorf(common.MigrationAlreadyApplied, "database %q has already applied version %s", m.Database, m.Version)- 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 migrationHistory.ID, nil- }- 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 migrationHistory.ID, nil- }- return "", common.Wrap(err, common.MigrationFailed)- }- }-- var tx *sql.Tx- // We don't use transaction for MongoDB for the following reasons:- // 1. MongoDB support transaction only in replica set mode or shard cluster mode. But we need to- // support standalone mode as well. https://stackoverflow.com/a/51462024/19075342- // 2. We use mongodb driver, it has not implemented the SQL interface. So we can't use the same code.- if executor.GetType() != db.MongoDB {- // We use transaction here for the RDBMS.- sqldb, err := executor.GetDBConnection(ctx, databaseName)- if err != nil {- 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 "", err- }- defer tx.Rollback()- }-- largestSequence, err := executor.FindLargestSequence(ctx, tx, m.Namespace, false /* baseline */)- if err != nil {- 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 "", 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 "", 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.- // 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.- statementRecord, _ := common.TruncateString(statement, common.MaxSheetSize)- if insertedID, err = executor.InsertPendingHistory(ctx, tx, largestSequence+1, prevSchema, m, storedVersion, statementRecord); err != nil {- return "", err- }-- if executor.GetType() != db.MongoDB {- if err := tx.Commit(); err != nil {- return "", err- }- }-- return insertedID, nil-}--// 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 string, updatedSchema string, databaseName string, isDone bool) (err error) {- migrationDurationNs := time.Now().UnixNano() - startedNs-- var tx *sql.Tx- // We don't use transaction for MongoDB for the following reasons:- // 1. MongoDB support transaction only in replica set mode or shard cluster mode. But we need to- // support standalone mode as well. https://stackoverflow.com/a/51462024/19075342- // 2. We use mongodb driver, it had not implment the sql interface. So we can't use the same code.- if executor.GetType() != db.MongoDB {- sqldb, err := executor.GetDBConnection(ctx, databaseName)- if err != nil {- return err- }- tx, err = sqldb.BeginTx(ctx, nil)- if err != nil {- return err- }- defer tx.Rollback()- }-- if isDone {- // 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', execution_duration.- err = executor.UpdateHistoryAsFailed(ctx, tx, migrationDurationNs, migrationHistoryID)- }-- if err != nil {- return err- }- if executor.GetType() != db.MongoDB {- return tx.Commit()- }- return nil-}-// Query will execute a readonly / SELECT query.// The result is then JSON marshaled and returned to the frontend.func Query(ctx context.Context, dbType db.Type, conn *sql.Conn, statement string, queryContext *db.QueryContext) ([]any, error) {diff --git a/backend/utils/utils.go b/backend/utils/utils.goindex d7e2b0d9c1..130a1a8f27 100644--- a/backend/utils/utils.go+++ b/backend/utils/utils.go@@ -525,7 +525,7 @@ func ExecuteMigration(ctx context.Context, store *store.Store, driver db.Driver,return "", "", err}} else {- if _, _, err := driver.ExecuteMigration(ctx, m, statement); err != nil {+ if _, err := driver.Execute(ctx, statement, m.CreateDatabase); err != nil {return "", "", err}}