Repository navigation
Expand file tree
/
Copy pathtransact.go
More file actions
80 lines (69 loc) · 1.47 KB
/
Copy pathtransact.go
File metadata and controls
80 lines (69 loc) · 1.47 KB
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
package sqlx
import "context"
type (
depthKey string
transactionPointer string
)
const (
dbKeyDepth = depthKey("tradeDBTXDepth")
txKey = transactionPointer("transactionPointer")
)
func getTxDepth(ctx context.Context) uint8 {
v := ctx.Value(dbKeyDepth)
if v == nil {
return 0
}
return v.(uint8)
}
func getTransactionDB(ctx context.Context) *Tx {
v := ctx.Value(txKey)
if v == nil {
return nil
}
return v.(*Tx)
}
func TransactContext(ctx context.Context, db Queryable, txFunc func(context.Context, Queryable) error) error {
depth := getTxDepth(ctx)
tx := getTransactionDB(ctx)
var err error
if tx != nil {
// already in a transaction, push down the stack
ctx = context.WithValue(ctx, dbKeyDepth, depth+1)
} else if base, ok := db.(*DB); ok {
tx, err = base.Beginx()
if err != nil {
return err
}
ctx = context.WithValue(ctx, txKey, tx)
ctx = context.WithValue(ctx, dbKeyDepth, depth+1)
}
defer func() {
if depth != 0 {
return
}
if p := recover(); p != nil {
err2 := tx.Rollback()
if err2 != nil {
err = err2
}
panic(p)
}
if ctx.Err() != nil {
// context was cancelled?
err = tx.Rollback()
return
}
if err != nil {
if inErr := tx.Rollback(); inErr != nil {
err = inErr
}
} else {
err = tx.Commit()
}
}()
err = txFunc(ctx, tx)
return err
}
func Transact(db Queryable, txFunc func(context.Context, Queryable) error) error {
return TransactContext(context.Background(), db, txFunc)
}