make withTx part of SQL
This commit is contained in:
parent
070938e12a
commit
13c6be981c
1 changed files with 18 additions and 27 deletions
45
db/db.go
45
db/db.go
|
@ -698,34 +698,25 @@ type txFunc func(tx *sql.Tx) error
|
||||||
|
|
||||||
// withTx wraps a function in an sql transaction. the transaction is committed if there's no error, or rolled back if there is one.
|
// withTx wraps a function in an sql transaction. the transaction is committed if there's no error, or rolled back if there is one.
|
||||||
// if dbOrTx is an sql.DB, a new transaction is started
|
// if dbOrTx is an sql.DB, a new transaction is started
|
||||||
func withTx(dbOrTx interface{}, f txFunc) (err error) {
|
func (s *SQL) withTx(f txFunc) (err error) {
|
||||||
var tx *sql.Tx
|
tx, err := s.conn.Begin()
|
||||||
|
if err != nil {
|
||||||
switch t := dbOrTx.(type) {
|
return err
|
||||||
case *sql.Tx:
|
|
||||||
tx = t
|
|
||||||
case *sql.DB:
|
|
||||||
tx, err = t.Begin()
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
defer func() {
|
|
||||||
if p := recover(); p != nil {
|
|
||||||
if rollBackError := tx.Rollback(); rollBackError != nil {
|
|
||||||
log.Error("failed to rollback tx on panic - ", rollBackError)
|
|
||||||
}
|
|
||||||
panic(p)
|
|
||||||
} else if err != nil {
|
|
||||||
if rollBackError := tx.Rollback(); rollBackError != nil {
|
|
||||||
log.Error("failed to rollback tx on panic - ", rollBackError)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
err = errors.Err(tx.Commit())
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
default:
|
|
||||||
return errors.Err("db or tx required")
|
|
||||||
}
|
}
|
||||||
|
defer func() {
|
||||||
|
if p := recover(); p != nil {
|
||||||
|
if rollBackError := tx.Rollback(); rollBackError != nil {
|
||||||
|
log.Error("failed to rollback tx on panic - ", rollBackError)
|
||||||
|
}
|
||||||
|
panic(p)
|
||||||
|
} else if err != nil {
|
||||||
|
if rollBackError := tx.Rollback(); rollBackError != nil {
|
||||||
|
log.Error("failed to rollback tx on panic - ", rollBackError)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
err = errors.Err(tx.Commit())
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
return f(tx)
|
return f(tx)
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in a new issue