-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtxn.go
70 lines (56 loc) · 1.36 KB
/
txn.go
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package txn
import "context"
// Tx is the core interface for managing transactions.
type Tx interface {
// Begin starts a new transaction.
Begin(ctx context.Context) error
// Commit commits the transaction.
Commit(ctx context.Context) error
// Rollback rolls back the transaction.
Rollback(ctx context.Context) error
// Cancel cancels the transaction. This is useful in cases where you want
// to abort the transaction without waiting for the context to be canceled.
Cancel(ctx context.Context)
// Register registers an adapter for a specific data source to participate
// in the transaction.
Register(Adapter)
}
// New creates a new Tx instance.
func New() Tx {
return &txn{}
}
type txn struct {
adapters []Adapter
}
func (t *txn) Register(a Adapter) {
t.adapters = append(t.adapters, a)
}
func (t *txn) Cancel(ctx context.Context) {
for _, a := range t.adapters {
a.Rollback(ctx)
}
}
func (t *txn) Begin(ctx context.Context) error {
for _, a := range t.adapters {
if err := a.Begin(ctx); err != nil {
return err
}
}
return nil
}
func (t *txn) Commit(ctx context.Context) error {
for _, a := range t.adapters {
if err := a.Commit(ctx); err != nil {
return err
}
}
return nil
}
func (t *txn) Rollback(ctx context.Context) error {
for _, a := range t.adapters {
if err := a.Rollback(ctx); err != nil {
return err
}
}
return nil
}