Skip to content

Commit 785a486

Browse files
committed
Introduce DB#RunInTx() method
1 parent 069bc9c commit 785a486

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
@@ -647,6 +647,30 @@ func (db *DB) Delete(
647647
return db.DeleteStreamed(ctx, entityType, idsCh, onSuccess...)
648648
}
649649

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

0 commit comments

Comments
 (0)