I would like to know how go handle failed DB transaction. My code looks like:
func assert(e interface{}) {
if e != nil {
panic(e)
}
}
//the caller will handle panics
func SomeDBOperation(db *sql.DB) {
tx, err := db.Begin()
assert(err)
defer func() {
if e := recover(); e != nil {
tx.Rollback()
panic(e)
}
assert(tx.Commit())
}()
// some code that can possibly panic...
}
Can I simplify the error checking like this:
func SomeDBOperation(db *sql.DB) {
tx, err := db.Begin()
assert(err)
defer func() { assert(tx.Commit()) }()
// some code that can possibly panic...
}
BTW, I am using SQLite, if any answer is db-specific, I would also like to know the behavior with MySQL.
CodePudding user response:
It is important to rollback the tx if there is an error while executing any query, otherwise it is still running and holding locks. Check out this post .