| 1 |
package db |
| 2 |
|
| 3 |
import "database/sql" |
| 4 |
|
| 5 |
// ExecTx executes a function within a database transaction. If the function returns an error, |
| 6 |
// the transaction is rolled back. Otherwise, the transaction is committed. |
| 7 |
func ExecTx(db Beginner, f func(tx *sql.Tx) error) error { |
| 8 |
tx, err := db.Begin() |
| 9 |
if err != nil { |
| 10 |
return err |
| 11 |
} |
| 12 |
defer tx.Rollback() |
| 13 |
if err := f(tx); err != nil { |
| 14 |
return err |
| 15 |
} |
| 16 |
return tx.Commit() |
| 17 |
} |
| 18 |
|
| 19 |
// QueryTx executes a function within a database transaction and returns the result. If the function |
| 20 |
// returns an error, the transaction is rolled back. Otherwise, the transaction is committed. |
| 21 |
func QueryTx[T any](db Beginner, f func(tx *sql.Tx) (T, error)) (T, error) { |
| 22 |
tx, err := db.Begin() |
| 23 |
if err != nil { |
| 24 |
var zero T |
| 25 |
return zero, err |
| 26 |
} |
| 27 |
defer tx.Rollback() |
| 28 |
t, err := f(tx) |
| 29 |
if err != nil { |
| 30 |
return t, err |
| 31 |
} |
| 32 |
if err := tx.Commit(); err != nil { |
| 33 |
return t, err |
| 34 |
} |
| 35 |
return t, nil |
| 36 |
} |