-
Notifications
You must be signed in to change notification settings - Fork 0
/
tx.go
70 lines (56 loc) · 1.11 KB
/
tx.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 sqlmy
import (
"context"
"database/sql"
)
// TxExec exec do in a transaction
// nested call TxExec is ok, only one transaction will be open
func TxExec(ctx context.Context, do func(dbCtx context.Context) error, opts ...*sql.TxOptions) error {
err := openTx(ctx, opts...)
if err != nil {
return err
}
err = do(ctx)
if err1 := closeTx(ctx, err == nil); err1 != nil {
logger.Error(ctx, "close tx fail: err: %v", err1)
}
return err
}
func openTx(ctx context.Context, opts ...*sql.TxOptions) error {
hc, ok := ctx.Value(_dbCtxKey).(*dbContext)
if !ok {
return ErrConnNotInit
}
if hc.tx != nil {
hc.openCount++
return nil
}
var opt *sql.TxOptions
if len(opts) == 1 {
opt = opts[0]
}
tx, err := hc.conn.BeginTx(ctx, opt)
if err != nil {
return err
}
hc.openCount++
hc.tx = tx
return nil
}
func closeTx(ctx context.Context, succ bool) error {
hc, ok := ctx.Value(_dbCtxKey).(*dbContext)
if !ok {
return ErrConnNotInit
}
if hc.tx == nil {
return ErrTxNotInit
}
hc.openCount--
if hc.openCount != 0 {
return nil
}
if succ {
return hc.tx.Commit()
}
return hc.tx.Rollback()
}