Skip to content

Commit

Permalink
Introduce DB#RunInTx() method
Browse files Browse the repository at this point in the history
  • Loading branch information
yhabteab committed Sep 17, 2024
1 parent 296f480 commit db40fe1
Showing 1 changed file with 24 additions and 0 deletions.
24 changes: 24 additions & 0 deletions database/db.go
Original file line number Diff line number Diff line change
Expand Up @@ -769,6 +769,30 @@ func (db *DB) Delete(
return db.DeleteStreamed(ctx, entityType, idsCh, onSuccess...)
}

// ExecTx allows running a function in a database transaction without requiring manual transaction handling.
//
// A new transaction is started on [DB] which is then passed to fn. After fn returns, the transaction is
// committed unless an error was returned. If fn returns an error, that error is returned or when failing
// to start or/and commit the transaction.
func (db *DB) ExecTx(ctx context.Context, fn func(context.Context, *sqlx.Tx) error) error {
tx, err := db.BeginTxx(ctx, nil)
if err != nil {
return errors.Wrap(err, "cannot start transaction")
}
// We don't expect meaningful errors from rolling back the tx other than the sql.ErrTxDone, so just ignore it.
defer func() { _ = tx.Rollback() }()

if err := fn(ctx, tx); err != nil {
return errors.WithStack(err)
}

if err := tx.Commit(); err != nil {
return errors.Wrap(err, "cannot commit transaction")
}

return nil
}

func (db *DB) GetSemaphoreForTable(table string) *semaphore.Weighted {
db.tableSemaphoresMu.Lock()
defer db.tableSemaphoresMu.Unlock()
Expand Down

0 comments on commit db40fe1

Please sign in to comment.