Skip to content

Instantly share code, notes, and snippets.

@lenstr
Created December 6, 2017 15:16
Show Gist options
  • Save lenstr/77f14466a5585f12a756143a0a610cf1 to your computer and use it in GitHub Desktop.
Save lenstr/77f14466a5585f12a756143a0a610cf1 to your computer and use it in GitHub Desktop.
func (db *DB) Transact(txFunc func(db *DB) error) (err error) {
tx := db.Begin()
if tx.Error == gorm.ErrCantStartTransaction {
// transaction already in progress
return txFunc(db)
}
defer func() {
if r := recover(); r != nil {
tx.Rollback()
panic(r)
}
if err != nil {
tx.Rollback()
return
}
err = tx.Commit().Error
}()
return txFunc(&DB{tx})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment