Skip to content

Commit a66da14

Browse files
committed
Introduce DB#RunInTx() method
1 parent 3e9722f commit a66da14

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

database/db.go

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -652,6 +652,30 @@ func (db *DB) Delete(
652652
return db.DeleteStreamed(ctx, entityType, idsCh, onSuccess...)
653653
}
654654

655+
// RunInTx allows running a function in a database transaction without requiring manual transaction handling.
656+
//
657+
// A new transaction is started on [DB] which is then passed to fn. After fn returns, the transaction is
658+
// committed unless an error was returned. If fn returns an error, that error is returned or when failing
659+
// to start or/and commit the transaction.
660+
func (db *DB) RunInTx(ctx context.Context, fn func(tx *sqlx.Tx) error) error {
661+
tx, err := db.BeginTxx(ctx, nil)
662+
if err != nil {
663+
return errors.Wrap(err, "DB.RunInTx: cannot start a database transaction")
664+
}
665+
// We don't expect meaningful errors from rolling back the tx other than the sql.ErrTxDone, so just ignore it.
666+
defer func() { _ = tx.Rollback() }()
667+
668+
if err = fn(tx); err != nil {
669+
return err
670+
}
671+
672+
if err = tx.Commit(); err != nil {
673+
return errors.Wrap(err, "DB.RunInTx: cannot commit a database transaction")
674+
}
675+
676+
return nil
677+
}
678+
655679
func (db *DB) GetSemaphoreForTable(table string) *semaphore.Weighted {
656680
db.tableSemaphoresMu.Lock()
657681
defer db.tableSemaphoresMu.Unlock()

0 commit comments

Comments
 (0)