Skip to content

Commit 486f869

Browse files
committed
Introduce DB#RunInTx() method
1 parent 715b56e commit 486f869

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

database/db.go

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -763,6 +763,29 @@ func (db *DB) Delete(
763763
return db.DeleteStreamed(ctx, entityType, idsCh, onSuccess...)
764764
}
765765

766+
// RunInTx allows running a function in a database transaction without requiring manual transaction handling.
767+
//
768+
// A new transaction is started on [DB] which is then passed to fn. After fn returns, the transaction is
769+
// committed unless an error was returned. If fn returns an error, that error is returned or when failing
770+
// to start or/and commit the transaction.
771+
func (db *DB) RunInTx(ctx context.Context, fn func(context.Context, *sqlx.Tx) error) error {
772+
tx, err := db.BeginTxx(ctx, nil)
773+
if err != nil {
774+
return errors.Wrap(err, "DB.RunInTx: cannot start a database transaction")
775+
}
776+
// We don't expect meaningful errors from rolling back the tx other than the sql.ErrTxDone, so just ignore it.
777+
defer func() { _ = tx.Rollback() }()
778+
779+
if err := fn(ctx, tx); err != nil {
780+
return err
781+
}
782+
if err := tx.Commit(); err != nil {
783+
return errors.Wrap(err, "DB.RunInTx: cannot commit a database transaction")
784+
}
785+
786+
return nil
787+
}
788+
766789
func (db *DB) GetSemaphoreForTable(table string) *semaphore.Weighted {
767790
db.tableSemaphoresMu.Lock()
768791
defer db.tableSemaphoresMu.Unlock()

0 commit comments

Comments
 (0)