forked from grafana/grafana
-
Notifications
You must be signed in to change notification settings - Fork 0
/
shared.go
71 lines (54 loc) · 1.21 KB
/
shared.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
package sqlstore
import (
"github.com/go-xorm/xorm"
"github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/log"
)
type dbTransactionFunc func(sess *xorm.Session) error
type dbTransactionFunc2 func(sess *session) error
type session struct {
*xorm.Session
events []interface{}
}
func (sess *session) publishAfterCommit(msg interface{}) {
sess.events = append(sess.events, msg)
}
func inTransaction(callback dbTransactionFunc) error {
var err error
sess := x.NewSession()
defer sess.Close()
if err = sess.Begin(); err != nil {
return err
}
err = callback(sess)
if err != nil {
sess.Rollback()
return err
} else if err = sess.Commit(); err != nil {
return err
}
return nil
}
func inTransaction2(callback dbTransactionFunc2) error {
var err error
sess := session{Session: x.NewSession()}
defer sess.Close()
if err = sess.Begin(); err != nil {
return err
}
err = callback(&sess)
if err != nil {
sess.Rollback()
return err
} else if err = sess.Commit(); err != nil {
return err
}
if len(sess.events) > 0 {
for _, e := range sess.events {
if err = bus.Publish(e); err != nil {
log.Error(3, "Failed to publish event after commit", err)
}
}
}
return nil
}