forked from adamlaska/boulder
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtransaction.go
More file actions
27 lines (24 loc) · 791 Bytes
/
transaction.go
File metadata and controls
27 lines (24 loc) · 791 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package db
import "context"
// txFunc represents a function that does work in the context of a transaction.
type txFunc func(txWithCtx Executor) (interface{}, error)
// WithTransaction runs the given function in a transaction, rolling back if it
// returns an error and committing if not. The provided context is also attached
// to the transaction. WithTransaction also passes through a value returned by
// `f`, if there is no error.
func WithTransaction(ctx context.Context, dbMap DatabaseMap, f txFunc) (interface{}, error) {
tx, err := dbMap.Begin()
if err != nil {
return nil, err
}
txWithCtx := tx.WithContext(ctx)
result, err := f(txWithCtx)
if err != nil {
return nil, rollback(tx, err)
}
err = tx.Commit()
if err != nil {
return nil, err
}
return result, nil
}