-
Notifications
You must be signed in to change notification settings - Fork 4
/
hub_tx.go
67 lines (61 loc) · 1.46 KB
/
hub_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
package datahub
import (
"errors"
"fmt"
)
// BeginTx create a hub with Transaction. Commit and/or Rollback need to call later on to close the transaction
func (h *Hub) BeginTx() (*Hub, error) {
conn, e := h.GetClassicConnection()
if e != nil {
return nil, fmt.Errorf("fail BeginTransaction: %s", e.Error())
}
if !conn.SupportTx() {
conn.Close()
return h, fmt.Errorf("fail BeginTransaction: connection is not supporting transaction")
}
if e = conn.BeginTx(); e != nil {
return h, fmt.Errorf("fail BeginTransaction: %s", e.Error())
}
ht := new(Hub)
ht.txconn = conn
ht._log = h._log
return ht, nil
}
// Commit commits all change into database
func (h *Hub) Commit() error {
defer func() {
if h != nil && h.txconn != nil {
h.txconn.Close()
h.txconn = nil
}
}()
if h.txconn == nil {
return errors.New("fail Commit: handler has no transactional connection")
}
if e := h.txconn.Commit(); e != nil {
return fmt.Errorf("fail Commit: %s", e.Error())
}
return nil
}
// Rollback to reverts back all change into database
func (h *Hub) Rollback() error {
defer func() {
if h != nil && h.txconn != nil {
h.txconn.Close()
h.txconn = nil
}
}()
if h.txconn == nil {
return errors.New("fail Rollback: handler has no transactional connection")
}
if e := h.txconn.RollBack(); e != nil {
return fmt.Errorf("fail Rollback: %s", e.Error())
}
return nil
}
func (h *Hub) IsTx() bool {
if h.txconn != nil {
return h.txconn.IsTx()
}
return false
}