Skip to content

Commit

Permalink
improve: run data migrations in a transaction
Browse files Browse the repository at this point in the history
So that any failures are rolled back. We use a single transaction for
all migrations because on-prem deploys will likely want to keep the
old schema if any of the migrations in a new version fail.
  • Loading branch information
dnephin committed Sep 9, 2022
1 parent 036ec99 commit 7e77d1d
Showing 1 changed file with 14 additions and 3 deletions.
17 changes: 14 additions & 3 deletions internal/server/data/data.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,22 +32,33 @@ func NewDB(connection gorm.Dialector, loadDBKey func(db GormTxn) error) (*DB, er
return nil, fmt.Errorf("db conn: %w", err)
}
dataDB := &DB{DB: db}
tx, err := dataDB.Begin(context.TODO())
if err != nil {
return nil, err
}

opts := migrator.Options{
InitSchema: initializeSchema,
LoadKey: func(tx migrator.DB) error {
LoadKey: func(_ migrator.DB) error {
if loadDBKey == nil {
return nil
}
// TODO: use the passed in tx instead of dataDB once the queries
// used by loadDBKey are ported to sql
return loadDBKey(dataDB)
return loadDBKey(tx)
},
}
m := migrator.New(dataDB, opts, migrations())
m := migrator.New(tx, opts, migrations())
if err := m.Migrate(); err != nil {
if err := tx.Rollback(); err != nil {
logging.L.Warn().Err(err).Msg("failed to rollback")
}
return nil, fmt.Errorf("migration failed: %w", err)
}
if err := tx.Commit(); err != nil {
return nil, fmt.Errorf("commit migrations: %w", err)
}

if err := initialize(dataDB); err != nil {
return nil, fmt.Errorf("initialize database: %w", err)
}
Expand Down

0 comments on commit 7e77d1d

Please sign in to comment.