Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
refactor(db-plugin): move ExecuteMigration steps to drivers (#559)
qsliu884581a6952f
diff --git a/docs/design/db-plugin-development-guide.md b/docs/design/db-plugin-development-guide.mdnew file mode 100644index 0000000000..aaeefba504--- /dev/null+++ b/docs/design/db-plugin-development-guide.md@@ -0,0 +1,15 @@+# DB Plugin Development Guide++This document introduces how to develop a database plugin for Bytebase.++## Concepts++Internally, Bytebase creates a table in database to record migration history.++## Develop a plugin+1. Under `plugin/db`, create a go package named driver's name.+1. Implement `github.com/bytebase/bytebase/plugin/db#Driver` interface.+1. \[Optional\] There are some common implementations in package `github.com/bytebase/bytebase/plugin/db/util`. To use these utils, additional adapters are needed usually.++ For instance, `util#ExecuteMigration` is a helper function to implement `db.Driver#ExecuteMigration`. And this function needs a `util.MigrationExecutor` adapter.+1. Register plugin. In `init()` function, call `github.com/bytebase/bytebase/plugin/db#Register` to register plugin factory with specific db type.diff --git a/plugin/db/clickhouse/clickhouse.go b/plugin/db/clickhouse/clickhouse.goindex 7cbf51c8d2..e2c62c6822 100644--- a/plugin/db/clickhouse/clickhouse.go+++ b/plugin/db/clickhouse/clickhouse.go@@ -29,7 +29,8 @@ var ("INFORMATION_SCHEMA": true,}- _ db.Driver = (*Driver)(nil)+ _ db.Driver = (*Driver)(nil)+ _ util.MigrationExecutor = (*Driver)(nil))func init() {@@ -408,9 +409,110 @@ func (driver *Driver) SetupMigrationIfNeeded(ctx context.Context) error {return nil}-// ExecuteMigration will execute the migration.-func (driver *Driver) ExecuteMigration(ctx context.Context, m *db.MigrationInfo, statement string) (int64, string, error) {- insertHistoryQuery := `+// CheckDuplicateVersion will check whether the version is already applied.+func (Driver) CheckDuplicateVersion(ctx context.Context, tx *sql.Tx, namespace string, engine db.MigrationEngine, version string) (bool, error) {+ const checkDuplicateVersionQuery = `+ SELECT 1 FROM bytebase.migration_history+ WHERE namespace = $1 AND engine= $2 AND version = $3+ `+ row, err := tx.QueryContext(ctx, checkDuplicateVersionQuery,+ namespace, engine.String(), version,+ )+ if err != nil {+ return false, util.FormatErrorWithQuery(err, checkDuplicateVersionQuery)+ }+ defer row.Close()++ if row.Next() {+ return true, nil+ }+ return false, nil+}++// CheckOutOfOrderVersion will return versions that are higher than the given version.+func (Driver) CheckOutOfOrderVersion(ctx context.Context, tx *sql.Tx, namespace string, engine db.MigrationEngine, version string) (minVersionIfValid *string, err error) {+ const checkOutofOrderVersionQuery = `+ SELECT MIN(version) FROM bytebase.migration_history+ WHERE namespace = $1 AND engine = $2 AND version > $3+ `+ row, err := tx.QueryContext(ctx, checkOutofOrderVersionQuery,+ namespace, engine.String(), version,+ )+ if err != nil {+ return nil, util.FormatErrorWithQuery(err, checkOutofOrderVersionQuery)+ }+ defer row.Close()++ var minVersion sql.NullString+ row.Next()+ if err := row.Scan(&minVersion); err != nil {+ return nil, err+ }++ if minVersion.Valid {+ return &minVersion.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+ }++ 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,+ namespace,+ )+ if err != nil {+ return -1, util.FormatErrorWithQuery(err, findNextSequenceQuery)+ }+ defer row.Close()++ var sequence sql.NullInt32+ row.Next()+ if err := row.Scan(&sequence); err != nil {+ return -1, err+ }++ 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))+ }++ return int(sequence.Int32), nil+}++// 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, statement string) (int64, error) {+ const insertHistoryQuery = `INSERT INTO bytebase.migration_history (id,created_by,@@ -434,8 +536,56 @@ func (driver *Driver) ExecuteMigration(ctx context.Context, m *db.MigrationInfo,)VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19)`+ var insertedID int64+ 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)+ }+ defer rows.Close()+ for rows.Next() {+ if err := rows.Scan(+ &insertedID,+ ); err != nil {+ return int64(0), util.FormatErrorWithQuery(err, maxIDQuery)+ }+ }+ if err := rows.Err(); err != nil {+ return int64(0), util.FormatErrorWithQuery(err, maxIDQuery)+ }+ // Clickhouse sql driver doesn't support taking now() as prepared value.+ now := time.Now().Unix()+ _, err = tx.ExecContext(ctx, insertHistoryQuery,+ insertedID,+ m.Creator,+ now,+ m.Creator,+ now,+ m.ReleaseVersion,+ m.Namespace,+ sequence,+ m.Engine,+ m.Type,+ "PENDING",+ m.Version,+ m.Description,+ statement,+ prevSchema,+ prevSchema,+ 0,+ m.IssueID,+ m.Payload,+ )+ if err != nil {+ return int64(0), util.FormatErrorWithQuery(err, insertHistoryQuery)+ }++ return insertedID, nil+}- updateHistoryAsDoneQuery := `+// UpdateHistoryAsDone will update the migration record as done.+func (Driver) UpdateHistoryAsDone(ctx context.Context, tx *sql.Tx, migrationDurationNs int64, updatedSchema string, insertedID int64) error {+ const updateHistoryAsDoneQuery = `ALTER TABLEbytebase.migration_historyUPDATE@@ -444,8 +594,13 @@ func (driver *Driver) ExecuteMigration(ctx context.Context, m *db.MigrationInfo,` + "`schema` = $2" + `WHERE id = $3`+ _, err := tx.ExecContext(ctx, updateHistoryAsDoneQuery, migrationDurationNs, updatedSchema, insertedID)+ return err+}- updateHistoryAsFailedQuery := `+// UpdateHistoryAsFailed will update the migration record as failed.+func (Driver) UpdateHistoryAsFailed(ctx context.Context, tx *sql.Tx, migrationDurationNs int64, insertedID int64) error {+ const updateHistoryAsFailedQuery = `ALTER TABLEbytebase.migration_historyUPDATE@@ -453,85 +608,13 @@ func (driver *Driver) ExecuteMigration(ctx context.Context, m *db.MigrationInfo,execution_duration_ns = $1WHERE id = $2`+ _, err := tx.ExecContext(ctx, updateHistoryAsFailedQuery, migrationDurationNs, insertedID)+ return err+}- checkDuplicateVersionQuery := `- SELECT 1 FROM bytebase.migration_history- WHERE namespace = $1 AND engine= $2 AND version = $3- `-- findBaselineQuery := `- SELECT 1 FROM bytebase.migration_history- WHERE namespace = $1 AND type = 'BASELINE'- `-- checkOutofOrderVersionQuery := `- SELECT MIN(version) FROM bytebase.migration_history- WHERE namespace = $1 AND engine = $2 AND version > $3- `-- findNextSequenceQuery := `- SELECT MAX(sequence) + 1 FROM bytebase.migration_history- WHERE namespace = $1- `-- insertPendingFunc := func(tx *sql.Tx, sequence int, prevSchema string) (int64, error) {- var insertedID int64- 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)- }- defer rows.Close()- for rows.Next() {- if err := rows.Scan(- &insertedID,- ); err != nil {- return int64(0), util.FormatErrorWithQuery(err, maxIDQuery)- }- }- if err := rows.Err(); err != nil {- return int64(0), util.FormatErrorWithQuery(err, maxIDQuery)- }- // Clickhouse sql driver doesn't support taking now() as prepared value.- now := time.Now().Unix()- _, err = tx.ExecContext(ctx, insertHistoryQuery,- insertedID,- m.Creator,- now,- m.Creator,- now,- m.ReleaseVersion,- m.Namespace,- sequence,- m.Engine,- m.Type,- "PENDING",- m.Version,- m.Description,- statement,- prevSchema,- prevSchema,- 0,- m.IssueID,- m.Payload,- )- if err != nil {- return int64(0), util.FormatErrorWithQuery(err, insertHistoryQuery)- }-- return insertedID, nil- }-- args := util.MigrationExecutionArgs{- UpdateHistoryAsDoneQuery: updateHistoryAsDoneQuery,- UpdateHistoryAsFailedQuery: updateHistoryAsFailedQuery,- CheckDuplicateVersionQuery: checkDuplicateVersionQuery,- FindBaselineQuery: findBaselineQuery,- CheckOutofOrderVersionQuery: checkOutofOrderVersionQuery,- FindNextSequenceQuery: findNextSequenceQuery,- InsertPendingHistoryFunc: insertPendingFunc,- }- return util.ExecuteMigration(ctx, driver.l, db.ClickHouse, driver, m, statement, args)+// ExecuteMigration will execute the migration.+func (driver *Driver) ExecuteMigration(ctx context.Context, m *db.MigrationInfo, statement string) (int64, string, error) {+ return util.ExecuteMigration(ctx, driver.l, driver, m, statement)}// FindMigrationHistoryList finds the migration history.diff --git a/plugin/db/mysql/mysql.go b/plugin/db/mysql/mysql.goindex 3b59b22759..c1586e1d84 100644--- a/plugin/db/mysql/mysql.go+++ b/plugin/db/mysql/mysql.go@@ -34,7 +34,8 @@ var (baseTableType = "BASE TABLE"excludeAutoIncrement = regexp.MustCompile(`AUTO_INCREMENT=\d+ `)- _ db.Driver = (*Driver)(nil)+ _ db.Driver = (*Driver)(nil)+ _ util.MigrationExecutor = (*Driver)(nil))func init() {@@ -589,109 +590,191 @@ func (driver *Driver) SetupMigrationIfNeeded(ctx context.Context) error {return nil}-// ExecuteMigration will execute the migration.-func (driver *Driver) ExecuteMigration(ctx context.Context, m *db.MigrationInfo, statement string) (int64, string, error) {- insertHistoryQuery := `- INSERT INTO bytebase.migration_history (- created_by,- created_ts,- updated_by,- updated_ts,- release_version,- namespace,- sequence,- engine,- type,- status,- version,- description,- statement,- ` + "`schema`," + `- schema_prev,- execution_duration_ns,- issue_id,- payload+// CheckDuplicateVersion will check whether the version is already applied.+func (Driver) CheckDuplicateVersion(ctx context.Context, tx *sql.Tx, namespace string, engine db.MigrationEngine, version string) (bool, error) {+ const checkDuplicateVersionQuery = `+ SELECT 1 FROM bytebase.migration_history+ WHERE namespace = ? AND engine = ? AND version = ?+ `+ row, err := tx.QueryContext(ctx, checkDuplicateVersionQuery,+ namespace, engine.String(), version,)- VALUES (?, unix_timestamp(), ?, unix_timestamp(), ?, ?, ?, ?, ?, 'PENDING', ?, ?, ?, ?, ?, 0, ?, ?)- `+ if err != nil {+ return false, util.FormatErrorWithQuery(err, checkDuplicateVersionQuery)+ }+ defer row.Close()- updateHistoryAsDoneQuery := `- UPDATE- bytebase.migration_history- SET- status = 'DONE',- execution_duration_ns = ?,- ` + "`schema` = ?" + `- WHERE id = ?- `+ if row.Next() {+ return true, nil+ }+ return false, nil+}- updateHistoryAsFailedQuery := `- UPDATE- bytebase.migration_history- SET- status = 'FAILED',- execution_duration_ns = ?- WHERE id = ?- `+// CheckOutOfOrderVersion will return versions that are higher than the given version.+func (Driver) CheckOutOfOrderVersion(ctx context.Context, tx *sql.Tx, namespace string, engine db.MigrationEngine, version string) (minVersionIfValid *string, err error) {+ const checkOutofOrderVersionQuery = `+ SELECT MIN(version) FROM bytebase.migration_history+ WHERE namespace = ? AND engine = ? AND version > ?+ `+ row, err := tx.QueryContext(ctx, checkOutofOrderVersionQuery,+ namespace, engine.String(), version,+ )+ if err != nil {+ return nil, util.FormatErrorWithQuery(err, checkOutofOrderVersionQuery)+ }+ defer row.Close()- checkDuplicateVersionQuery := `- SELECT 1 FROM bytebase.migration_history- WHERE namespace = ? AND engine = ? AND version = ?- `+ var minVersion sql.NullString+ row.Next()+ if err := row.Scan(&minVersion); err != nil {+ return nil, err+ }- findBaselineQuery := `+ if minVersion.Valid {+ return &minVersion.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_historyWHERE namespace = ? AND type = 'BASELINE'- `+ `+ row, err := tx.QueryContext(ctx, findBaselineQuery,+ namespace,+ )+ if err != nil {+ return false, util.FormatErrorWithQuery(err, findBaselineQuery)+ }+ defer row.Close()- checkOutofOrderVersionQuery := `- SELECT MIN(version) FROM bytebase.migration_history- WHERE namespace = ? AND engine = ? AND version > ?- `+ if !row.Next() {+ return false, nil+ }++ return true, nil+}- findNextSequenceQuery := `+// 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_historyWHERE namespace = ?- `+ `+ row, err := tx.QueryContext(ctx, findNextSequenceQuery,+ namespace,+ )+ if err != nil {+ return -1, util.FormatErrorWithQuery(err, findNextSequenceQuery)+ }+ defer row.Close()++ var sequence sql.NullInt32+ row.Next()+ if err := row.Scan(&sequence); err != nil {+ return -1, err+ }++ 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))+ }++ return int(sequence.Int32), nil+}- insertPendingFunc := func(tx *sql.Tx, sequence int, prevSchema string) (int64, error) {- res, err := tx.ExecContext(ctx, insertHistoryQuery,- m.Creator,- m.Creator,- m.ReleaseVersion,- m.Namespace,+// 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, statement string) (int64, error) {+ const insertHistoryQuery = `+ INSERT INTO bytebase.migration_history (+ created_by,+ created_ts,+ updated_by,+ updated_ts,+ release_version,+ namespace,sequence,- m.Engine,- m.Type,- m.Version,- m.Description,+ engine,+ type,+ status,+ version,+ description,statement,- prevSchema,- prevSchema,- m.IssueID,- m.Payload,+ ` + "`schema`," + `+ schema_prev,+ execution_duration_ns,+ issue_id,+ payload)- if err != nil {- return int64(0), util.FormatErrorWithQuery(err, insertHistoryQuery)- }-- insertedID, err := res.LastInsertId()- if err != nil {- return int64(0), util.FormatErrorWithQuery(err, insertHistoryQuery)- }- return insertedID, nil+ VALUES (?, unix_timestamp(), ?, unix_timestamp(), ?, ?, ?, ?, ?, 'PENDING', ?, ?, ?, ?, ?, 0, ?, ?)+ `+ res, err := tx.ExecContext(ctx, insertHistoryQuery,+ m.Creator,+ m.Creator,+ m.ReleaseVersion,+ m.Namespace,+ sequence,+ m.Engine,+ m.Type,+ m.Version,+ m.Description,+ statement,+ prevSchema,+ prevSchema,+ m.IssueID,+ m.Payload,+ )+ if err != nil {+ return int64(0), util.FormatErrorWithQuery(err, insertHistoryQuery)}- args := util.MigrationExecutionArgs{- UpdateHistoryAsDoneQuery: updateHistoryAsDoneQuery,- UpdateHistoryAsFailedQuery: updateHistoryAsFailedQuery,- CheckDuplicateVersionQuery: checkDuplicateVersionQuery,- FindBaselineQuery: findBaselineQuery,- CheckOutofOrderVersionQuery: checkOutofOrderVersionQuery,- FindNextSequenceQuery: findNextSequenceQuery,- InsertPendingHistoryFunc: insertPendingFunc,+ insertedID, err := res.LastInsertId()+ if err != nil {+ return int64(0), util.FormatErrorWithQuery(err, insertHistoryQuery)}- return util.ExecuteMigration(ctx, driver.l, db.MySQL, driver, m, statement, args)+ 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 {+ const updateHistoryAsDoneQuery = `+ UPDATE+ bytebase.migration_history+ SET+ status = 'DONE',+ execution_duration_ns = ?,+ ` + "`schema` = ?" + `+ WHERE id = ?+ `+ _, err := tx.ExecContext(ctx, updateHistoryAsDoneQuery, migrationDurationNs, updatedSchema, insertedID)+ return err+}++// UpdateHistoryAsFailed will update the migration record as failed.+func (Driver) UpdateHistoryAsFailed(ctx context.Context, tx *sql.Tx, migrationDurationNs int64, insertedID int64) error {+ const updateHistoryAsFailedQuery = `+ UPDATE+ bytebase.migration_history+ SET+ status = 'FAILED',+ execution_duration_ns = ?+ WHERE id = ?+ `+ _, err := tx.ExecContext(ctx, updateHistoryAsFailedQuery, migrationDurationNs, insertedID)+ return err+}++// ExecuteMigration will execute the migration.+func (driver *Driver) ExecuteMigration(ctx context.Context, m *db.MigrationInfo, statement string) (int64, string, error) {+ return util.ExecuteMigration(ctx, driver.l, driver, m, statement)}// FindMigrationHistoryList finds the migration history.diff --git a/plugin/db/pg/pg.go b/plugin/db/pg/pg.goindex 1c44b9cdb8..4addc8c4e8 100644--- a/plugin/db/pg/pg.go+++ b/plugin/db/pg/pg.go@@ -185,7 +185,8 @@ var (bytebaseDatabase = "bytebase"createBytebaseDatabaseStmt = "CREATE DATABASE bytebase;"- _ db.Driver = (*Driver)(nil)+ _ db.Driver = (*Driver)(nil)+ _ util.MigrationExecutor = (*Driver)(nil))func init() {@@ -648,9 +649,110 @@ func (driver *Driver) SetupMigrationIfNeeded(ctx context.Context) error {return nil}-// ExecuteMigration will execute the migration.-func (driver *Driver) ExecuteMigration(ctx context.Context, m *db.MigrationInfo, statement string) (int64, string, error) {- insertHistoryQuery := `+// CheckDuplicateVersion will check whether the version is already applied.+func (Driver) CheckDuplicateVersion(ctx context.Context, tx *sql.Tx, namespace string, engine db.MigrationEngine, version string) (bool, error) {+ const checkDuplicateVersionQuery = `+ SELECT 1 FROM migration_history+ WHERE namespace = $1 AND engine = $2 AND version = $3+ `+ row, err := tx.QueryContext(ctx, checkDuplicateVersionQuery,+ namespace, engine.String(), version,+ )+ if err != nil {+ return false, util.FormatErrorWithQuery(err, checkDuplicateVersionQuery)+ }+ defer row.Close()++ if row.Next() {+ return true, nil+ }+ return false, nil+}++// CheckOutOfOrderVersion will return versions that are higher than the given version.+func (Driver) CheckOutOfOrderVersion(ctx context.Context, tx *sql.Tx, namespace string, engine db.MigrationEngine, version string) (minVersionIfValid *string, err error) {+ const checkOutofOrderVersionQuery = `+ SELECT MIN(version) FROM migration_history+ WHERE namespace = $1 AND engine = $2 AND version > $3+ `+ row, err := tx.QueryContext(ctx, checkOutofOrderVersionQuery,+ namespace, engine.String(), version,+ )+ if err != nil {+ return nil, util.FormatErrorWithQuery(err, checkOutofOrderVersionQuery)+ }+ defer row.Close()++ var minVersion sql.NullString+ row.Next()+ if err := row.Scan(&minVersion); err != nil {+ return nil, err+ }++ if minVersion.Valid {+ return &minVersion.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)+ }+ 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,+ namespace,+ )+ if err != nil {+ return -1, util.FormatErrorWithQuery(err, findNextSequenceQuery)+ }+ defer row.Close()++ var sequence sql.NullInt32+ row.Next()+ if err := row.Scan(&sequence); err != nil {+ return -1, err+ }++ 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))+ }++ return int(sequence.Int32), nil+}++// 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, statement string) (int64, error) {+ const insertHistoryQuery = `INSERT INTO migration_history (created_by,created_ts,@@ -674,8 +776,29 @@ func (driver *Driver) ExecuteMigration(ctx context.Context, m *db.MigrationInfo,VALUES ($1, EXTRACT(epoch from NOW()), $2, EXTRACT(epoch from NOW()), $3, $4, $5, $6, $7, 'PENDING', $8, $9, $10, $11, $12, 0, $13, $14)RETURNING id`+ var insertedID int64+ tx.QueryRowContext(ctx, insertHistoryQuery,+ m.Creator,+ m.Creator,+ m.ReleaseVersion,+ m.Namespace,+ sequence,+ m.Engine,+ m.Type,+ m.Version,+ m.Description,+ statement,+ prevSchema,+ prevSchema,+ m.IssueID,+ m.Payload,+ ).Scan(&insertedID)+ return insertedID, nil+}- updateHistoryAsDoneQuery := `+// UpdateHistoryAsDone will update the migration record as done.+func (Driver) UpdateHistoryAsDone(ctx context.Context, tx *sql.Tx, migrationDurationNs int64, updatedSchema string, insertedID int64) error {+ const updateHistoryAsDoneQuery = `UPDATEmigration_historySET@@ -684,8 +807,13 @@ func (driver *Driver) ExecuteMigration(ctx context.Context, m *db.MigrationInfo,"schema" = $2WHERE id = $3`+ _, err := tx.ExecContext(ctx, updateHistoryAsDoneQuery, migrationDurationNs, updatedSchema, insertedID)+ return err+}- updateHistoryAsFailedQuery := `+// UpdateHistoryAsFailed will update the migration record as failed.+func (Driver) UpdateHistoryAsFailed(ctx context.Context, tx *sql.Tx, migrationDurationNs int64, insertedID int64) error {+ const updateHistoryAsFailedQuery = `UPDATEmigration_historySET@@ -693,58 +821,13 @@ func (driver *Driver) ExecuteMigration(ctx context.Context, m *db.MigrationInfo,execution_duration_ns = $1WHERE id = $2`+ _, err := tx.ExecContext(ctx, updateHistoryAsFailedQuery, migrationDurationNs, insertedID)+ return err+}- checkDuplicateVersionQuery := `- SELECT 1 FROM migration_history- WHERE namespace = $1 AND engine = $2 AND version = $3- `-- findBaselineQuery := `- SELECT 1 FROM migration_history- WHERE namespace = $1 AND type = 'BASELINE'- `-- checkOutofOrderVersionQuery := `- SELECT MIN(version) FROM migration_history- WHERE namespace = $1 AND engine = $2 AND version > $3- `-- findNextSequenceQuery := `- SELECT MAX(sequence) + 1 FROM migration_history- WHERE namespace = $1- `-- insertPendingFunc := func(tx *sql.Tx, sequence int, prevSchema string) (int64, error) {- var insertedID int64- tx.QueryRowContext(ctx, insertHistoryQuery,- m.Creator,- m.Creator,- m.ReleaseVersion,- m.Namespace,- sequence,- m.Engine,- m.Type,- m.Version,- m.Description,- statement,- prevSchema,- prevSchema,- m.IssueID,- m.Payload,- ).Scan(&insertedID)- return insertedID, nil- }-- args := util.MigrationExecutionArgs{- UpdateHistoryAsDoneQuery: updateHistoryAsDoneQuery,- UpdateHistoryAsFailedQuery: updateHistoryAsFailedQuery,- CheckDuplicateVersionQuery: checkDuplicateVersionQuery,- FindBaselineQuery: findBaselineQuery,- CheckOutofOrderVersionQuery: checkOutofOrderVersionQuery,- FindNextSequenceQuery: findNextSequenceQuery,- InsertPendingHistoryFunc: insertPendingFunc,- }- return util.ExecuteMigration(ctx, driver.l, db.Postgres, driver, m, statement, args)+// ExecuteMigration will execute the migration.+func (driver *Driver) ExecuteMigration(ctx context.Context, m *db.MigrationInfo, statement string) (int64, string, error) {+ return util.ExecuteMigration(ctx, driver.l, driver, m, statement)}// FindMigrationHistoryList finds the migration history.diff --git a/plugin/db/snowflake/snowflake.go b/plugin/db/snowflake/snowflake.goindex ff86d526df..bbdb00631b 100644--- a/plugin/db/snowflake/snowflake.go+++ b/plugin/db/snowflake/snowflake.go@@ -11,6 +11,7 @@ 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"@@ -28,7 +29,8 @@ var (sysAdminRole = "SYSADMIN"accountAdminRole = "ACCOUNTADMIN"- _ db.Driver = (*Driver)(nil)+ _ db.Driver = (*Driver)(nil)+ _ util.MigrationExecutor = (*Driver)(nil))func init() {@@ -581,12 +583,110 @@ func (driver *Driver) SetupMigrationIfNeeded(ctx context.Context) error {return nil}-// ExecuteMigration will execute the migration.-func (driver *Driver) ExecuteMigration(ctx context.Context, m *db.MigrationInfo, statement string) (int64, string, error) {- if err := driver.useRole(ctx, sysAdminRole); err != nil {- return int64(0), "", err+// CheckDuplicateVersion will check whether the version is already applied.+func (Driver) CheckDuplicateVersion(ctx context.Context, tx *sql.Tx, namespace string, engine db.MigrationEngine, version string) (bool, error) {+ const checkDuplicateVersionQuery = `+ SELECT 1 FROM bytebase.public.migration_history+ WHERE namespace = ? AND engine = ? AND version = ?+ `+ row, err := tx.QueryContext(ctx, checkDuplicateVersionQuery,+ namespace, engine.String(), version,+ )+ if err != nil {+ return false, util.FormatErrorWithQuery(err, checkDuplicateVersionQuery)+ }+ defer row.Close()++ if row.Next() {+ return true, nil+ }+ return false, nil+}++// CheckOutOfOrderVersion will return versions that are higher than the given version.+func (Driver) CheckOutOfOrderVersion(ctx context.Context, tx *sql.Tx, namespace string, engine db.MigrationEngine, version string) (minVersionIfValid *string, err error) {+ const checkOutofOrderVersionQuery = `+ SELECT MIN(version) FROM bytebase.public.migration_history+ WHERE namespace = ? AND engine = ? AND version > ?+ `+ row, err := tx.QueryContext(ctx, checkOutofOrderVersionQuery,+ namespace, engine.String(), version,+ )+ if err != nil {+ return nil, util.FormatErrorWithQuery(err, checkOutofOrderVersionQuery)+ }+ defer row.Close()++ var minVersion sql.NullString+ row.Next()+ if err := row.Scan(&minVersion); err != nil {+ return nil, err+ }++ if minVersion.Valid {+ return &minVersion.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}- insertHistoryQuery := `++ 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,+ namespace,+ )+ if err != nil {+ return -1, util.FormatErrorWithQuery(err, findNextSequenceQuery)+ }+ defer row.Close()++ var sequence sql.NullInt32+ row.Next()+ if err := row.Scan(&sequence); err != nil {+ return -1, err+ }++ 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))+ }++ return int(sequence.Int32), nil+}++// 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, statement string) (int64, error) {+ const insertHistoryQuery = `INSERT INTO bytebase.public.migration_history (created_by,created_ts,@@ -609,8 +709,55 @@ func (driver *Driver) ExecuteMigration(ctx context.Context, m *db.MigrationInfo,)VALUES (?, DATE_PART(EPOCH_SECOND, CURRENT_TIMESTAMP()), ?, DATE_PART(EPOCH_SECOND, CURRENT_TIMESTAMP()), ?, ?, ?, ?, ?, 'PENDING', ?, ?, ?, ?, ?, 0, ?, ?)`+ var insertedID int64+ 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)+ }+ defer rows.Close()+ var id sql.NullInt64+ for rows.Next() {+ if err := rows.Scan(+ &id,+ ); err != nil {+ return int64(0), util.FormatErrorWithQuery(err, maxIDQuery)+ }+ }+ if err := rows.Err(); err != nil {+ return int64(0), util.FormatErrorWithQuery(err, maxIDQuery)+ }+ if id.Valid {+ insertedID = id.Int64+ } else {+ insertedID = 1+ }- updateHistoryAsDoneQuery := `+ _, err = tx.ExecContext(ctx, insertHistoryQuery,+ m.Creator,+ m.Creator,+ m.ReleaseVersion,+ m.Namespace,+ sequence,+ m.Engine,+ m.Type,+ m.Version,+ m.Description,+ statement,+ prevSchema,+ prevSchema,+ m.IssueID,+ m.Payload,+ )+ if err != nil {+ return int64(0), 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 {+ const updateHistoryAsDoneQuery = `UPDATEbytebase.public.migration_historySET@@ -619,8 +766,13 @@ func (driver *Driver) ExecuteMigration(ctx context.Context, m *db.MigrationInfo,schema = ?WHERE id = ?`+ _, err := tx.ExecContext(ctx, updateHistoryAsDoneQuery, migrationDurationNs, updatedSchema, insertedID)+ return err+}- updateHistoryAsFailedQuery := `+// UpdateHistoryAsFailed will update the migration record as failed.+func (Driver) UpdateHistoryAsFailed(ctx context.Context, tx *sql.Tx, migrationDurationNs int64, insertedID int64) error {+ const updateHistoryAsFailedQuery = `UPDATEbytebase.public.migration_historySET@@ -628,84 +780,16 @@ func (driver *Driver) ExecuteMigration(ctx context.Context, m *db.MigrationInfo,execution_duration_ns = ?WHERE id = ?`+ _, err := tx.ExecContext(ctx, updateHistoryAsFailedQuery, migrationDurationNs, insertedID)+ return err+}- checkDuplicateVersionQuery := `- SELECT 1 FROM bytebase.public.migration_history- WHERE namespace = ? AND engine = ? AND version = ?- `-- findBaselineQuery := `- SELECT 1 FROM bytebase.public.migration_history- WHERE namespace = ? AND type = 'BASELINE'- `-- checkOutofOrderVersionQuery := `- SELECT MIN(version) FROM bytebase.public.migration_history- WHERE namespace = ? AND engine = ? AND version > ?- `-- findNextSequenceQuery := `- SELECT MAX(sequence) + 1 FROM bytebase.public.migration_history- WHERE namespace = ?- `-- insertPendingFunc := func(tx *sql.Tx, sequence int, prevSchema string) (int64, error) {- var insertedID int64- 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)- }- defer rows.Close()- var id sql.NullInt64- for rows.Next() {- if err := rows.Scan(- &id,- ); err != nil {- return int64(0), util.FormatErrorWithQuery(err, maxIDQuery)- }- }- if err := rows.Err(); err != nil {- return int64(0), util.FormatErrorWithQuery(err, maxIDQuery)- }- if id.Valid {- insertedID = id.Int64- } else {- insertedID = 1- }-- _, err = tx.ExecContext(ctx, insertHistoryQuery,- m.Creator,- m.Creator,- m.ReleaseVersion,- m.Namespace,- sequence,- m.Engine,- m.Type,- m.Version,- m.Description,- statement,- prevSchema,- prevSchema,- m.IssueID,- m.Payload,- )- if err != nil {- return int64(0), util.FormatErrorWithQuery(err, insertHistoryQuery)- }- return insertedID, nil- }-- args := util.MigrationExecutionArgs{- UpdateHistoryAsDoneQuery: updateHistoryAsDoneQuery,- UpdateHistoryAsFailedQuery: updateHistoryAsFailedQuery,- CheckDuplicateVersionQuery: checkDuplicateVersionQuery,- FindBaselineQuery: findBaselineQuery,- CheckOutofOrderVersionQuery: checkOutofOrderVersionQuery,- FindNextSequenceQuery: findNextSequenceQuery,- InsertPendingHistoryFunc: insertPendingFunc,+// ExecuteMigration will execute the migration.+func (driver *Driver) ExecuteMigration(ctx context.Context, m *db.MigrationInfo, statement string) (int64, string, error) {+ if err := driver.useRole(ctx, sysAdminRole); err != nil {+ return int64(0), "", err}- return util.ExecuteMigration(ctx, driver.l, db.Snowflake, driver, m, statement, args)+ return util.ExecuteMigration(ctx, driver.l, driver, m, statement)}// FindMigrationHistoryList finds the migration history.diff --git a/plugin/db/sqlite/sqlite.go b/plugin/db/sqlite/sqlite.goindex b572ba1146..1d00a935cc 100644--- a/plugin/db/sqlite/sqlite.go+++ b/plugin/db/sqlite/sqlite.go@@ -13,6 +13,7 @@ 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"@@ -28,7 +29,8 @@ var (bytebaseDatabase: true,}- _ db.Driver = (*Driver)(nil)+ _ db.Driver = (*Driver)(nil)+ _ util.MigrationExecutor = (*Driver)(nil))func init() {@@ -257,9 +259,110 @@ func (driver *Driver) SetupMigrationIfNeeded(ctx context.Context) error {return nil}-// ExecuteMigration will execute the migration.-func (driver *Driver) ExecuteMigration(ctx context.Context, m *db.MigrationInfo, statement string) (int64, string, error) {- insertHistoryQuery := `+// CheckDuplicateVersion will check whether the version is already applied.+func (Driver) CheckDuplicateVersion(ctx context.Context, tx *sql.Tx, namespace string, engine db.MigrationEngine, version string) (bool, error) {+ const checkDuplicateVersionQuery = `+ SELECT 1 FROM bytebase_migration_history+ WHERE namespace = ? AND engine = ? AND version = ?+ `+ row, err := tx.QueryContext(ctx, checkDuplicateVersionQuery,+ namespace, engine.String(), version,+ )+ if err != nil {+ return false, util.FormatErrorWithQuery(err, checkDuplicateVersionQuery)+ }+ defer row.Close()++ if row.Next() {+ return true, nil+ }+ return false, nil+}++// CheckOutOfOrderVersion will return versions that are higher than the given version.+func (Driver) CheckOutOfOrderVersion(ctx context.Context, tx *sql.Tx, namespace string, engine db.MigrationEngine, version string) (minVersionIfValid *string, err error) {+ const checkOutofOrderVersionQuery = `+ SELECT MIN(version) FROM bytebase_migration_history+ WHERE namespace = ? AND engine = ? AND version > ?+ `+ row, err := tx.QueryContext(ctx, checkOutofOrderVersionQuery,+ namespace, engine.String(), version,+ )+ if err != nil {+ return nil, util.FormatErrorWithQuery(err, checkOutofOrderVersionQuery)+ }+ defer row.Close()++ var minVersion sql.NullString+ row.Next()+ if err := row.Scan(&minVersion); err != nil {+ return nil, err+ }++ if minVersion.Valid {+ return &minVersion.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+ }++ 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,+ namespace,+ )+ if err != nil {+ return -1, util.FormatErrorWithQuery(err, findNextSequenceQuery)+ }+ defer row.Close()++ var sequence sql.NullInt32+ row.Next()+ if err := row.Scan(&sequence); err != nil {+ return -1, err+ }++ 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))+ }++ return int(sequence.Int32), nil+}++// 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, statement string) (int64, error) {+ const insertHistoryQuery = `INSERT INTO bytebase_migration_history (created_by,created_ts,@@ -282,8 +385,36 @@ func (driver *Driver) ExecuteMigration(ctx context.Context, m *db.MigrationInfo,)VALUES (?, strftime('%s', 'now'), ?, strftime('%s', 'now'), ?, ?, ?, ?, ?, 'PENDING', ?, ?, ?, ?, ?, 0, ?, ?)`+ res, err := tx.ExecContext(ctx, insertHistoryQuery,+ m.Creator,+ m.Creator,+ m.ReleaseVersion,+ m.Namespace,+ sequence,+ m.Engine,+ m.Type,+ m.Version,+ m.Description,+ statement,+ prevSchema,+ prevSchema,+ m.IssueID,+ m.Payload,+ )+ if err != nil {+ return int64(0), util.FormatErrorWithQuery(err, insertHistoryQuery)+ }++ insertedID, err := res.LastInsertId()+ if err != nil {+ return int64(0), util.FormatErrorWithQuery(err, insertHistoryQuery)+ }+ return insertedID, nil+}- updateHistoryAsDoneQuery := `+// UpdateHistoryAsDone will update the migration record as done.+func (Driver) UpdateHistoryAsDone(ctx context.Context, tx *sql.Tx, migrationDurationNs int64, updatedSchema string, insertedID int64) error {+ const updateHistoryAsDoneQuery = `UPDATEbytebase_migration_historySET@@ -292,8 +423,13 @@ func (driver *Driver) ExecuteMigration(ctx context.Context, m *db.MigrationInfo,schema = ?WHERE id = ?`+ _, err := tx.ExecContext(ctx, updateHistoryAsDoneQuery, migrationDurationNs, updatedSchema, insertedID)+ return err+}- updateHistoryAsFailedQuery := `+// UpdateHistoryAsFailed will update the migration record as failed.+func (Driver) UpdateHistoryAsFailed(ctx context.Context, tx *sql.Tx, migrationDurationNs int64, insertedID int64) error {+ const updateHistoryAsFailedQuery = `UPDATEbytebase_migration_historySET@@ -301,65 +437,13 @@ func (driver *Driver) ExecuteMigration(ctx context.Context, m *db.MigrationInfo,execution_duration_ns = ?WHERE id = ?`+ _, err := tx.ExecContext(ctx, updateHistoryAsFailedQuery, migrationDurationNs, insertedID)+ return err+}- checkDuplicateVersionQuery := `- SELECT 1 FROM bytebase_migration_history- WHERE namespace = ? AND engine = ? AND version = ?- `-- findBaselineQuery := `- SELECT 1 FROM bytebase_migration_history- WHERE namespace = ? AND type = 'BASELINE'- `-- checkOutofOrderVersionQuery := `- SELECT MIN(version) FROM bytebase_migration_history- WHERE namespace = ? AND engine = ? AND version > ?- `-- findNextSequenceQuery := `- SELECT MAX(sequence) + 1 FROM bytebase_migration_history- WHERE namespace = ?- `-- insertPendingFunc := func(tx *sql.Tx, sequence int, prevSchema string) (int64, error) {- res, err := tx.ExecContext(ctx, insertHistoryQuery,- m.Creator,- m.Creator,- m.ReleaseVersion,- m.Namespace,- sequence,- m.Engine,- m.Type,- m.Version,- m.Description,- statement,- prevSchema,- prevSchema,- m.IssueID,- m.Payload,- )- if err != nil {- return int64(0), util.FormatErrorWithQuery(err, insertHistoryQuery)- }-- insertedID, err := res.LastInsertId()- if err != nil {- return int64(0), util.FormatErrorWithQuery(err, insertHistoryQuery)- }- return insertedID, nil- }-- args := util.MigrationExecutionArgs{- UpdateHistoryAsDoneQuery: updateHistoryAsDoneQuery,- UpdateHistoryAsFailedQuery: updateHistoryAsFailedQuery,- CheckDuplicateVersionQuery: checkDuplicateVersionQuery,- FindBaselineQuery: findBaselineQuery,- CheckOutofOrderVersionQuery: checkOutofOrderVersionQuery,- FindNextSequenceQuery: findNextSequenceQuery,- InsertPendingHistoryFunc: insertPendingFunc,- }- return util.ExecuteMigration(ctx, driver.l, db.SQLite, driver, m, statement, args)+// ExecuteMigration will execute the migration.+func (driver *Driver) ExecuteMigration(ctx context.Context, m *db.MigrationInfo, statement string) (int64, string, error) {+ return util.ExecuteMigration(ctx, driver.l, driver, m, statement)}// FindMigrationHistoryList finds the migration history.diff --git a/plugin/db/util/driverutil.go b/plugin/db/util/driverutil.goindex 1de292fd25..94a1b515b5 100644--- a/plugin/db/util/driverutil.go+++ b/plugin/db/util/driverutil.go@@ -109,30 +109,37 @@ func NeedsSetupMigrationSchema(ctx context.Context, sqldb *sql.DB, query string)return true, nil}-// MigrationExecutionArgs includes the arguments for ExecuteMigration().-type MigrationExecutionArgs struct {- UpdateHistoryAsDoneQuery string- UpdateHistoryAsFailedQuery string- CheckDuplicateVersionQuery string- FindBaselineQuery string- CheckOutofOrderVersionQuery string- FindNextSequenceQuery string- FindMigrationHistoryListQuery string- InsertPendingHistoryFunc func(tx *sql.Tx, sequence int, prevSchema string) (int64, error)+// MigrationExecutor is an adapter for ExecuteMigration().+type MigrationExecutor interface {+ db.Driver+ // CheckDuplicateVersion will check whether the version is already applied.+ CheckDuplicateVersion(ctx context.Context, tx *sql.Tx, namespace string, engine db.MigrationEngine, version string) (isDuplicate bool, err error)+ // CheckOutOfOrderVersion will return versions that are higher than the given version.+ CheckOutOfOrderVersion(ctx context.Context, tx *sql.Tx, namespace string, engine db.MigrationEngine, 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)+ // 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.+ UpdateHistoryAsDone(ctx context.Context, tx *sql.Tx, migrationDurationNs int64, updatedSchema string, insertedID int64) error+ // UpdateHistoryAsFailed will update the migration record as failed.+ UpdateHistoryAsFailed(ctx context.Context, tx *sql.Tx, migrationDurationNs int64, insertedID int64) error}// ExecuteMigration will execute the database migration.// Returns the created migraiton history id and the updated schema on success.-func ExecuteMigration(ctx context.Context, l *zap.Logger, dbType db.Type, driver db.Driver, m *db.MigrationInfo, statement string, args MigrationExecutionArgs) (migrationHistoryID int64, updatedSchema string, resErr error) {+func ExecuteMigration(ctx context.Context, l *zap.Logger, executor MigrationExecutor, m *db.MigrationInfo, statement string) (migrationHistoryID int64, updatedSchema string, resErr error) {var prevSchemaBuf bytes.Buffer// Don't record schema if the database hasn't exist yet.if !m.CreateDatabase {- if err := driver.Dump(ctx, m.Database, &prevSchemaBuf, true /*schemaOnly*/); err != nil {+ if err := executor.Dump(ctx, m.Database, &prevSchemaBuf, true /*schemaOnly*/); err != nil {return -1, "", formatError(err)}}- sqldb, err := driver.GetDbConnection(ctx, bytebaseDatabase)+ sqldb, err := executor.GetDbConnection(ctx, bytebaseDatabase)if err != nil {return -1, "", err}@@ -144,7 +151,7 @@ func ExecuteMigration(ctx context.Context, l *zap.Logger, dbType db.Type, driver// Phase 1 - Precheck before executing migration// Check if the same migration version has alraedy been applied- duplicate, err := checkDuplicateVersion(ctx, args.CheckDuplicateVersionQuery, tx, m.Namespace, m.Engine, m.Version)+ duplicate, err := executor.CheckDuplicateVersion(ctx, tx, m.Namespace, m.Engine, m.Version)if err != nil {return -1, "", err}@@ -153,7 +160,7 @@ func ExecuteMigration(ctx context.Context, l *zap.Logger, dbType db.Type, driver}// Check if there is any higher version already been applied- version, err := checkOutofOrderVersion(ctx, args.CheckOutofOrderVersionQuery, tx, m.Namespace, m.Engine, m.Version)+ version, err := executor.CheckOutOfOrderVersion(ctx, tx, m.Namespace, m.Engine, m.Version)if err != nil {return -1, "", err}@@ -165,7 +172,7 @@ func ExecuteMigration(ctx context.Context, l *zap.Logger, dbType db.Type, driver// 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.Engine == db.VCS && m.Type != db.Baseline && m.Type != db.Branch {- hasBaseline, err := findBaseline(ctx, args.FindBaselineQuery, tx, m.Namespace)+ hasBaseline, err := executor.FindBaseline(ctx, tx, m.Namespace)if err != nil {return -1, "", err}@@ -177,7 +184,7 @@ func ExecuteMigration(ctx context.Context, l *zap.Logger, dbType db.Type, driver// VCS based SQL migration requires existing baseliningrequireBaseline := m.Engine == db.VCS && m.Type == db.Migrate- sequence, err := findNextSequence(ctx, args.FindNextSequenceQuery, tx, m.Namespace, requireBaseline)+ sequence, err := executor.FindNextSequence(ctx, tx, m.Namespace, requireBaseline)if err != nil {return -1, "", err}@@ -186,7 +193,7 @@ func ExecuteMigration(ctx context.Context, l *zap.Logger, dbType db.Type, driver// 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.- insertedID, err := args.InsertPendingHistoryFunc(tx, sequence, prevSchemaBuf.String())+ insertedID, err := executor.InsertPendingHistory(ctx, tx, sequence, prevSchemaBuf.String(), m, statement)if err != nil {return -1, "", err}@@ -210,7 +217,7 @@ func ExecuteMigration(ctx context.Context, l *zap.Logger, dbType db.Type, driver}()migrationDurationNs := time.Now().UnixNano() - startedNs- afterSqldb, tmpErr := driver.GetDbConnection(ctx, bytebaseDatabase)+ afterSqldb, tmpErr := executor.GetDbConnection(ctx, bytebaseDatabase)if tmpErr != nil {return}@@ -222,17 +229,10 @@ func ExecuteMigration(ctx context.Context, l *zap.Logger, dbType db.Type, driverif resErr == nil {// Upon success, update the migration history as 'DONE', execution_duration_ns, updated schema.- _, tmpErr = afterTx.ExecContext(ctx, args.UpdateHistoryAsDoneQuery,- migrationDurationNs,- updatedSchema,- insertedID,- )+ tmpErr = executor.UpdateHistoryAsDone(ctx, afterTx, migrationDurationNs, prevSchemaBuf.String(), insertedID)} else {// Otherwise, update the migration history as 'FAILED', exeuction_duration- _, tmpErr = afterTx.ExecContext(ctx, args.UpdateHistoryAsFailedQuery,- migrationDurationNs,- insertedID,- )+ tmpErr = executor.UpdateHistoryAsFailed(ctx, afterTx, migrationDurationNs, insertedID)}if tmpErr != nil {@@ -249,7 +249,7 @@ func ExecuteMigration(ctx context.Context, l *zap.Logger, dbType db.Type, driverif statement != "" && (m.Type != db.Baseline || m.CreateDatabase) {// Switch to the target database only if we're NOT creating this target database.if !m.CreateDatabase {- _, err := driver.GetDbConnection(ctx, m.Database)+ _, err := executor.GetDbConnection(ctx, m.Database)if err != nil {return -1, "", err}@@ -257,14 +257,14 @@ func ExecuteMigration(ctx context.Context, l *zap.Logger, dbType db.Type, driver// MySQL executes DDL in its own transaction, so there is no need to supply a transaction from previous migration history updates.// Also, we don't use transaction for creating databases in Postgres.// https://github.com/bytebase/bytebase/issues/202- if err = driver.Execute(ctx, statement, !m.CreateDatabase); err != nil {+ if err = executor.Execute(ctx, statement, !m.CreateDatabase); err != nil {return -1, "", formatError(err)}}// Phase 4 - Dump the schema after migrationvar afterSchemaBuf bytes.Buffer- if err = driver.Dump(ctx, m.Database, &afterSchemaBuf, true /*schemaOnly*/); err != nil {+ if err = executor.Dump(ctx, m.Database, &afterSchemaBuf, true /*schemaOnly*/); err != nil {return -1, "", formatError(err)}@@ -348,87 +348,6 @@ func Query(ctx context.Context, l *zap.Logger, db *sql.DB, statement string, limreturn resultSet, nil}-func findBaseline(ctx context.Context, findBaselineQuery string, tx *sql.Tx, namespace string) (bool, error) {- row, err := tx.QueryContext(ctx, findBaselineQuery,- namespace,- )- if err != nil {- return false, FormatErrorWithQuery(err, findBaselineQuery)- }- defer row.Close()-- if !row.Next() {- return false, nil- }-- return true, nil-}--func checkDuplicateVersion(ctx context.Context, checkDuplicateVersionQuery string, tx *sql.Tx, namespace string, engine db.MigrationEngine, version string) (bool, error) {- row, err := tx.QueryContext(ctx, checkDuplicateVersionQuery,- namespace, engine.String(), version,- )- if err != nil {- return false, FormatErrorWithQuery(err, checkDuplicateVersionQuery)- }- defer row.Close()-- if row.Next() {- return true, nil- }- return false, nil-}--func checkOutofOrderVersion(ctx context.Context, checkOutofOrderVersionQuery string, tx *sql.Tx, namespace string, engine db.MigrationEngine, version string) (*string, error) {- row, err := tx.QueryContext(ctx, checkOutofOrderVersionQuery,- namespace, engine.String(), version,- )- if err != nil {- return nil, FormatErrorWithQuery(err, checkOutofOrderVersionQuery)- }- defer row.Close()-- var minVersion sql.NullString- row.Next()- if err := row.Scan(&minVersion); err != nil {- return nil, err- }-- if minVersion.Valid {- return &minVersion.String, nil- }-- return nil, nil-}--func findNextSequence(ctx context.Context, findNextSequenceQuery string, tx *sql.Tx, namespace string, requireBaseline bool) (int, error) {- row, err := tx.QueryContext(ctx, findNextSequenceQuery,- namespace,- )- if err != nil {- return -1, FormatErrorWithQuery(err, findNextSequenceQuery)- }- defer row.Close()-- var sequence sql.NullInt32- row.Next()- if err := row.Scan(&sequence); err != nil {- return -1, err- }-- 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))- }-- return int(sequence.Int32), nil-}-// FindMigrationHistoryList will find the list of migration history.func FindMigrationHistoryList(ctx context.Context, findMigrationHistoryListQuery string, queryParams []interface{}, driver db.Driver, find *db.MigrationHistoryFind, baseQuery string) ([]*db.MigrationHistory, error) {sqldb, err := driver.GetDbConnection(ctx, bytebaseDatabase)