-
Notifications
You must be signed in to change notification settings - Fork 0
/
tx.go
99 lines (80 loc) · 2 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
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
package zeroxorm
import (
"database/sql"
"fmt"
"github.com/tal-tech/go-zero/core/stores/sqlx"
"github.com/xormplus/xorm"
)
type (
beginnable func(*xorm.Engine) (trans, error)
trans interface {
sqlx.Session
Commit() error
Rollback() error
Close() error
}
txSession struct {
*xorm.Session
}
)
func (t txSession) Exec(q string, args ...interface{}) (sql.Result, error) {
return exec(t.Session, q, args...)
}
func (t txSession) Prepare(q string) (sqlx.StmtSession, error) {
stmt := &zeroStmt{t.Session, q}
return stmt, nil
}
func (t txSession) QueryRow(v interface{}, q string, args ...interface{}) error {
return query(t.Session, v, q, args...)
}
func (t txSession) QueryRowPartial(v interface{}, q string, args ...interface{}) error {
return query(t.Session, v, q, args...)
}
func (t txSession) QueryRows(v interface{}, q string, args ...interface{}) error {
return query(t.Session, v, q, args...)
}
func (t txSession) QueryRowsPartial(v interface{}, q string, args ...interface{}) error {
return query(t.Session, v, q, args...)
}
func (t txSession) Commit() error {
return t.Session.Commit()
}
func (t txSession) Rollback() error {
return t.Session.Rollback()
}
func (t txSession) Close() error {
return t.Session.Close()
}
func begin(db *xorm.Engine) (trans, error) {
sess := db.NewSession()
sess = sess.Prepare()
err := sess.Begin()
if err != nil {
return nil, err
}
return txSession{sess}, nil
}
func transactOnConn(conn *xorm.Engine, b beginnable, fn func(sqlx.Session) error) (err error) {
var tx trans
tx, err = b(conn)
if err != nil {
return
}
defer tx.Close()
defer func() {
if p := recover(); p != nil {
if e := tx.Rollback(); e != nil {
err = fmt.Errorf("recover from %#v, rollback failed: %s", p, e)
} else {
err = fmt.Errorf("recoveer from %#v", p)
}
} else if err != nil {
if e := tx.Rollback(); e != nil {
err = fmt.Errorf("transaction failed: %s, rollback failed: %s", err, e)
}
} else {
err = tx.Commit()
}
}()
return fn(tx)
}