Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
If migration failed, we should update the migration history to failed as well
天舟7e34dc88b9b5
diff --git a/frontend/src/components/MigrationHistoryStatusIcon.vue b/frontend/src/components/MigrationHistoryStatusIcon.vueindex b6182f389f..66d01c5f0c 100644--- a/frontend/src/components/MigrationHistoryStatusIcon.vue+++ b/frontend/src/components/MigrationHistoryStatusIcon.vue@@ -25,6 +25,13 @@/></svg></template>+ <template v-else-if="status === `FAILED`">+ <span+ class="h-2 w-2 rounded-full text-center pb-6 font-normal text-base"+ aria-hidden="true"+ >!</span+ >+ </template></span></template>@@ -49,6 +56,8 @@ export default {return iconClass + " bg-white border-2 border-info text-info";case "DONE":return iconClass + " bg-success text-white";+ case "FAILED":+ return iconClass + " bg-error text-white";}};diff --git a/frontend/src/types/instance.ts b/frontend/src/types/instance.tsindex 43d5aa1157..adbd017539 100644--- a/frontend/src/types/instance.ts+++ b/frontend/src/types/instance.ts@@ -100,7 +100,7 @@ export type MigrationEngine = "UI" | "VCS";export type MigrationType = "BASELINE" | "MIGRATE" | "BRANCH";-export type MigrationStatus = "PENDING" | "DONE";+export type MigrationStatus = "PENDING" | "DONE" | "FAILED";export type MigrationHistoryPayload = {pushEvent?: VCSPushEvent;diff --git a/plugin/db/clickhouse/clickhouse.go b/plugin/db/clickhouse/clickhouse.goindex 2d8d68e0f6..c0833afa07 100644--- a/plugin/db/clickhouse/clickhouse.go+++ b/plugin/db/clickhouse/clickhouse.go@@ -439,7 +439,7 @@ func (driver *Driver) ExecuteMigration(ctx context.Context, m *db.MigrationInfo,)VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`- updateHistoryQuery := `+ updateHistoryAsDoneQuery := `ALTER TABLEbytebase.migration_historyUPDATE@@ -448,12 +448,22 @@ func (driver *Driver) ExecuteMigration(ctx context.Context, m *db.MigrationInfo,` + "`schema` = ?" + `WHERE id = ?`+ updateHistoryAsFailedQuery := `+ ALTER TABLE+ bytebase.migration_history+ UPDATE+ status = 'FAILED',+ execution_duration = ?+ WHERE id = ?+ `+args := util.MigrationExecutionArgs{- InsertHistoryQuery: insertHistoryQuery,- UpdateHistoryQuery: updateHistoryQuery,- TablePrefix: "bytebase.",+ InsertHistoryQuery: insertHistoryQuery,+ UpdateHistoryAsDoneQuery: updateHistoryAsDoneQuery,+ UpdateHistoryAsFailedQuery: updateHistoryAsFailedQuery,+ TablePrefix: "bytebase.",}- return util.ExecuteMigration(ctx, db.ClickHouse, driver, m, statement, args)+ return util.ExecuteMigration(ctx, driver.l, db.ClickHouse, driver, m, statement, args)}func (driver *Driver) FindMigrationHistoryList(ctx context.Context, find *db.MigrationHistoryFind) ([]*db.MigrationHistory, error) {diff --git a/plugin/db/clickhouse/clickhouse_migration_schema.sql b/plugin/db/clickhouse/clickhouse_migration_schema.sqlindex 0b00807521..b58c858d41 100644--- a/plugin/db/clickhouse/clickhouse_migration_schema.sql+++ b/plugin/db/clickhouse/clickhouse_migration_schema.sql@@ -24,7 +24,7 @@ CREATE TABLE bytebase.migration_history (`type` ENUM('BASELINE' = 0, 'MIGRATE' = 1, 'BRANCH' = 2) NOT NULL,-- MySQL runs DDL in its own transaction, so we can't record DDL and migration_history into a single transaction.-- Thus, we create a "PENDING" record before applying the DDL and update that record to "DONE" after applying the DDL.- `status` ENUM('PENDING' = 0, 'DONE' = 1) NOT NULL,+ `status` ENUM('PENDING' = 0, 'DONE' = 1, 'FAILED' = 2) NOT NULL,-- Record the migration version.version TEXT NOT NULL,description TEXT NOT NULL,diff --git a/plugin/db/driver.go b/plugin/db/driver.goindex a89b22c31e..b7732d1fab 100644--- a/plugin/db/driver.go+++ b/plugin/db/driver.go@@ -152,6 +152,7 @@ type MigrationStatus stringconst (Pending MigrationStatus = "PENDING"Done MigrationStatus = "DONE"+ Failed MigrationStatus = "FAILED")func (e MigrationStatus) String() string {@@ -160,6 +161,8 @@ func (e MigrationStatus) String() string {return "PENDING"case Done:return "DONE"+ case Failed:+ return "FAILED"}return "UNKNOWN"}diff --git a/plugin/db/mysql/mysql.go b/plugin/db/mysql/mysql.goindex 10523c678e..0c9dc549ba 100644--- a/plugin/db/mysql/mysql.go+++ b/plugin/db/mysql/mysql.go@@ -595,7 +595,7 @@ func (driver *Driver) ExecuteMigration(ctx context.Context, m *db.MigrationInfo,)VALUES (?, unix_timestamp(), ?, unix_timestamp(), ?, ?, ?, ?, ?, 'PENDING', ?, ?, ?, ?, ?, 0, ?, ?)`- updateHistoryQuery := `+ updateHistoryAsDoneQuery := `UPDATEbytebase.migration_historySET@@ -604,12 +604,23 @@ func (driver *Driver) ExecuteMigration(ctx context.Context, m *db.MigrationInfo,` + "`schema` = ?" + `WHERE id = ?`++ updateHistoryAsFailedQuery := `+ UPDATE+ bytebase.migration_history+ SET+ status = 'FAILED',+ execution_duration = ?+ WHERE id = ?+ `+args := util.MigrationExecutionArgs{- InsertHistoryQuery: insertHistoryQuery,- UpdateHistoryQuery: updateHistoryQuery,- TablePrefix: "bytebase.",+ InsertHistoryQuery: insertHistoryQuery,+ UpdateHistoryAsDoneQuery: updateHistoryAsDoneQuery,+ UpdateHistoryAsFailedQuery: updateHistoryAsFailedQuery,+ TablePrefix: "bytebase.",}- return util.ExecuteMigration(ctx, db.MySQL, driver, m, statement, args)+ return util.ExecuteMigration(ctx, driver.l, db.MySQL, driver, m, statement, args)}func (driver *Driver) FindMigrationHistoryList(ctx context.Context, find *db.MigrationHistoryFind) ([]*db.MigrationHistory, error) {diff --git a/plugin/db/mysql/mysql_migration_schema.sql b/plugin/db/mysql/mysql_migration_schema.sqlindex caecfe0e92..4f63729e6f 100644--- a/plugin/db/mysql/mysql_migration_schema.sql+++ b/plugin/db/mysql/mysql_migration_schema.sql@@ -24,7 +24,7 @@ CREATE TABLE bytebase.migration_history (`type` ENUM('BASELINE', 'MIGRATE', 'BRANCH') NOT NULL,-- MySQL runs DDL in its own transaction, so we can't record DDL and migration_history into a single transaction.-- Thus, we create a "PENDING" record before applying the DDL and update that record to "DONE" after applying the DDL.- `status` ENUM('PENDING', 'DONE') NOT NULL,+ `status` ENUM('PENDING', 'DONE', 'FAILED') NOT NULL,-- Record the migration version.version TEXT NOT NULL,description TEXT NOT NULL,diff --git a/plugin/db/pg/pg.go b/plugin/db/pg/pg.goindex 230b93fccd..7d0ea8f611 100644--- a/plugin/db/pg/pg.go+++ b/plugin/db/pg/pg.go@@ -625,7 +625,7 @@ 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`- updateHistoryQuery := `+ updateHistoryAsDoneQuery := `UPDATEmigration_historySET@@ -635,12 +635,22 @@ func (driver *Driver) ExecuteMigration(ctx context.Context, m *db.MigrationInfo,WHERE id = $3`+ updateHistoryAsFailedQuery := `+ UPDATE+ migration_history+ SET+ status = 'FAILED',+ execution_duration = $1+ WHERE id = $2+`+args := util.MigrationExecutionArgs{- InsertHistoryQuery: insertHistoryQuery,- UpdateHistoryQuery: updateHistoryQuery,- TablePrefix: "",+ InsertHistoryQuery: insertHistoryQuery,+ UpdateHistoryAsDoneQuery: updateHistoryAsDoneQuery,+ UpdateHistoryAsFailedQuery: updateHistoryAsFailedQuery,+ TablePrefix: "",}- return util.ExecuteMigration(ctx, db.Postgres, driver, m, statement, args)+ return util.ExecuteMigration(ctx, driver.l, db.Postgres, driver, m, statement, args)}func (driver *Driver) FindMigrationHistoryList(ctx context.Context, find *db.MigrationHistoryFind) ([]*db.MigrationHistory, error) {diff --git a/plugin/db/pg/pg_migration_schema.sql b/plugin/db/pg/pg_migration_schema.sqlindex fb1bb33671..d9dd0db0ea 100644--- a/plugin/db/pg/pg_migration_schema.sql+++ b/plugin/db/pg/pg_migration_schema.sql@@ -24,7 +24,7 @@ CREATE TABLE migration_history (type TEXT NOT NULL CHECK (type in ('BASELINE', 'MIGRATE', 'BRANCH')),-- PostgreSQL can't do cross database transaction, so we can't record DDL and migration_history into a single transaction.-- Thus, we create a "PENDING" record before applying the DDL and update that record to "DONE" after applying the DDL.- status TEXT NOT NULL CHECK (status in ('PENDING', 'DONE')),+ status TEXT NOT NULL CHECK (status in ('PENDING', 'DONE', 'FAILED')),-- Record the migration version.version TEXT NOT NULL,description TEXT NOT NULL,diff --git a/plugin/db/util/driverutil.go b/plugin/db/util/driverutil.goindex 406813320a..2f29989a46 100644--- a/plugin/db/util/driverutil.go+++ b/plugin/db/util/driverutil.go@@ -11,6 +11,7 @@ import ("github.com/bytebase/bytebase/common""github.com/bytebase/bytebase/plugin/db"+ "go.uber.org/zap")const (@@ -106,14 +107,15 @@ func NeedsSetupMigrationSchema(ctx context.Context, sqldb *sql.DB, query string)// MigrationExecutionArgs includes the arguments for ExecuteMigration().type MigrationExecutionArgs struct {- InsertHistoryQuery string- UpdateHistoryQuery string- TablePrefix string+ InsertHistoryQuery string+ UpdateHistoryAsDoneQuery string+ UpdateHistoryAsFailedQuery string+ TablePrefix string}// ExecuteMigration will execute the database migration.// Returns the created migraiton history id and the updated schema on success.-func ExecuteMigration(ctx context.Context, dbType db.Type, driver db.Driver, m *db.MigrationInfo, statement string, args MigrationExecutionArgs) (int64, string, error) {+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) {var prevSchemaBuf bytes.Buffer// Don't record schema if the database hasn't exist yet.if !m.CreateDatabase {@@ -269,10 +271,56 @@ func ExecuteMigration(ctx context.Context, dbType db.Type, driver db.Driver, m *return -1, "", err}+ startedTs := time.Now().Unix()++ // If we have already started migration, there will be a PENDING migration record. Upon returning,+ // we will update that record to DONE or FAILED depending on whether error occurs.+ defer func() (myErr error) {+ defer func() {+ if myErr != nil {+ l.Error("Failed to update migration history record",+ zap.Error(myErr),+ zap.Int64("migration_id", insertedID),+ )+ }+ }()++ migrationDuration := time.Now().Unix() - startedTs+ afterSqldb, tmpErr := driver.GetDbConnection(ctx, bytebaseDatabase)+ if tmpErr != nil {+ return+ }+ afterTx, tmpErr := afterSqldb.BeginTx(ctx, nil)+ if tmpErr != nil {+ return+ }+ defer afterTx.Rollback()++ if resErr == nil {+ // Upon success, update the migration history as 'DONE', execution_duration, updated schema.+ _, tmpErr = afterTx.ExecContext(ctx, args.UpdateHistoryAsDoneQuery,+ migrationDuration,+ updatedSchema,+ insertedID,+ )+ } else {+ // Otherwise, update the migration history as 'FAILED', exeuction_duration+ _, tmpErr = afterTx.ExecContext(ctx, args.UpdateHistoryAsFailedQuery,+ migrationDuration,+ insertedID,+ )+ }++ if tmpErr != nil {+ return tmpErr+ }++ return afterTx.Commit()+ }()+// Phase 3 - Executing migration// Branch migration type always has empty sql.// Baseline migration type could also has empty sql when the database is newly created.- startedTs := time.Now().Unix()if statement != "" {// Switch to the database if we're creating a new databaseif !m.CreateDatabase {@@ -286,7 +334,6 @@ func ExecuteMigration(ctx context.Context, dbType db.Type, driver db.Driver, m *return -1, "", formatError(err)}}- duration := time.Now().Unix() - startedTs// Phase 4 - Dump the schema after migrationvar afterSchemaBuf bytes.Buffer@@ -294,30 +341,6 @@ func ExecuteMigration(ctx context.Context, dbType db.Type, driver db.Driver, m *return -1, "", formatError(err)}- // Phase 5 - Update the migration history with 'DONE', execution_duration, updated schema.- afterSqldb, err := driver.GetDbConnection(ctx, bytebaseDatabase)- if err != nil {- return -1, "", err- }- afterTx, err := afterSqldb.BeginTx(ctx, nil)- if err != nil {- return -1, "", err- }- defer afterTx.Rollback()- _, err = afterTx.ExecContext(ctx, args.UpdateHistoryQuery,- duration,- afterSchemaBuf.String(),- insertedID,- )-- if err != nil {- return -1, "", FormatErrorWithQuery(err, args.UpdateHistoryQuery)- }-- if err := afterTx.Commit(); err != nil {- return -1, "", err- }-return insertedID, afterSchemaBuf.String(), nil}