-
Notifications
You must be signed in to change notification settings - Fork 0
/
transaction.go
59 lines (54 loc) · 1.35 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
package transaction_manager
import (
"fmt"
. "github.com/xormplus/xorm"
)
type transactionManager struct {
manager SynchronizeManager
engine EngineInterface
}
func (s transactionManager) SessionFunc() DynamicSession {
return func() *Session {
return s.manager.Get()
}
}
func (s transactionManager) Do(do TransactionFunc, transactionDefinition ...int) error {
var result error
var session *Session
//remove session on sessionStack
defer s.manager.Remove()
// close session
defer func() {
if err := session.Close(); err != nil {
panic(fmt.Errorf("close transaction error:%v", err))
}
}()
// rollback or nothing to do when catch err
defer func() {
if err := recover(); err != nil {
result = err.(error)
if rollbackErr := session.Rollback(); rollbackErr != nil {
panic(fmt.Errorf("rollback transaction error:%v", err))
}
}
}()
var sourceSession *Session
sourceSession = s.manager.Get()
trans, err := sourceSession.
BeginTrans(transactionDefinition...)
if err != nil {
panic(fmt.Errorf("begin transacation error"))
}
session = trans.Session()
s.manager.Add(session)
if err := do(trans); err != nil {
panic(err)
}
if err := trans.CommitTrans(); err != nil {
panic(err)
}
return result
}
func New(param EngineInterface) TransactionManager {
return transactionManager{manager: NewSynchronizeManager(param), engine: param}
}