-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathtransaction.go
101 lines (80 loc) · 2.05 KB
/
transaction.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package pgxv4
import (
"context"
"sync"
"github.com/jackc/pgx/v4"
"github.com/avito-tech/go-transaction-manager/trm/v2"
"github.com/avito-tech/go-transaction-manager/trm/v2/drivers"
)
// Transaction is trm.Transaction for pgx.Tx.
type Transaction struct {
mu sync.Mutex
tx pgx.Tx
isClosed *drivers.IsClosed
}
func newDefaultTransaction(tx pgx.Tx) *Transaction {
return &Transaction{
mu: sync.Mutex{},
tx: tx,
isClosed: drivers.NewIsClosed(),
}
}
// NewTransaction creates trm.Transaction for pgx.Tx.
func NewTransaction(
ctx context.Context,
opts pgx.TxOptions,
db Transactional,
) (context.Context, *Transaction, error) {
tx, err := db.BeginTx(ctx, opts)
if err != nil {
return ctx, nil, err
}
tr := newDefaultTransaction(tx)
go tr.awaitDone(ctx)
return ctx, tr, nil
}
func (t *Transaction) awaitDone(ctx context.Context) {
if ctx.Done() == nil {
return
}
select {
case <-ctx.Done():
_ = t.Rollback(ctx)
case <-t.isClosed.Closed():
}
}
// Transaction returns the real transaction pgx.Tx.
func (t *Transaction) Transaction() interface{} {
return t.tx
}
// Begin nested transaction by save point.
func (t *Transaction) Begin(ctx context.Context, _ trm.Settings) (context.Context, trm.Transaction, error) {
tx, err := t.tx.Begin(ctx)
if err != nil {
return ctx, nil, err
}
tr := newDefaultTransaction(tx)
return ctx, tr, nil
}
// Commit the trm.Transaction.
func (t *Transaction) Commit(ctx context.Context) error {
t.mu.Lock()
defer t.mu.Unlock()
defer t.isClosed.Close()
return t.tx.Commit(ctx)
}
// Rollback the trm.Transaction.
func (t *Transaction) Rollback(ctx context.Context) error {
t.mu.Lock()
defer t.mu.Unlock()
defer t.isClosed.Close()
return t.tx.Rollback(ctx)
}
// IsActive returns true if the transaction started but not committed or rolled back.
func (t *Transaction) IsActive() bool {
return t.isClosed.IsActive()
}
// Closed returns a channel that's closed when transaction committed or rolled back.
func (t *Transaction) Closed() <-chan struct{} {
return t.isClosed.Closed()
}