Skip to content

Commit 836afd7

Browse files
committed
added db.OptionalTransaction
1 parent 1c6907f commit 836afd7

File tree

1 file changed

+11
-0
lines changed

1 file changed

+11
-0
lines changed

db/transaction.go

+11
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,17 @@ func Transaction(ctx context.Context, txFunc func(context.Context) error) error
6868
})
6969
}
7070

71+
// OptionalTransaction executes txFunc within a database transaction if doTransaction is true.
72+
// If doTransaction is false, then txFunc is executed without a transaction.
73+
//
74+
// See [Transaction] for more details.
75+
func OptionalTransaction(ctx context.Context, doTransaction bool, txFunc func(context.Context) error) error {
76+
if !doTransaction {
77+
return txFunc(ctx)
78+
}
79+
return Transaction(ctx, txFunc)
80+
}
81+
7182
// SerializedTransaction executes txFunc "serially" within a database transaction that is passed in to txFunc via the context.
7283
// Use db.Conn(ctx) to get the transaction connection within txFunc.
7384
// Transaction returns all errors from txFunc or transaction commit errors happening after txFunc.

0 commit comments

Comments
 (0)