WithTransaction runs a block of code passing in an SQL transaction If the code returns an error or panics then the transactions is rolledback Otherwise the transaction is committed.
(db *sql.DB, fn func(txn *sql.Tx) error)
| 60 | // If the code returns an error or panics then the transactions is rolledback |
| 61 | // Otherwise the transaction is committed. |
| 62 | func WithTransaction(db *sql.DB, fn func(txn *sql.Tx) error) (err error) { |
| 63 | txn, err := db.Begin() |
| 64 | if err != nil { |
| 65 | return fmt.Errorf("sqlutil.WithTransaction.Begin: %w", err) |
| 66 | } |
| 67 | succeeded := false |
| 68 | defer EndTransactionWithCheck(txn, &succeeded, &err) |
| 69 | |
| 70 | err = fn(txn) |
| 71 | if err != nil { |
| 72 | return |
| 73 | } |
| 74 | |
| 75 | succeeded = true |
| 76 | return |
| 77 | } |
| 78 | |
| 79 | // TxStmt wraps an SQL stmt inside an optional transaction. |
| 80 | // If the transaction is nil then it returns the original statement that will |
no test coverage detected