Created
December 6, 2017 15:16
-
-
Save lenstr/77f14466a5585f12a756143a0a610cf1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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