-
Notifications
You must be signed in to change notification settings - Fork 22
/
database.go
43 lines (32 loc) · 843 Bytes
/
database.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
package datastore
import (
"xorm.io/xorm"
"github.com/mayswind/ezbookkeeping/pkg/core"
)
// Database represents a database instance
type Database struct {
engineGroup *xorm.EngineGroup
}
// NewSession starts a new session with the specified context
func (db *Database) NewSession(c *core.Context) *xorm.Session {
return db.engineGroup.Context(NewXOrmContextAdapter(c))
}
// DoTransaction runs a new database transaction
func (db *Database) DoTransaction(c *core.Context, fn func(sess *xorm.Session) error) (err error) {
sess := db.engineGroup.NewSession()
if c != nil {
sess.Context(NewXOrmContextAdapter(c))
}
defer sess.Close()
if err = sess.Begin(); err != nil {
return err
}
if err = fn(sess); err != nil {
_ = sess.Rollback()
return err
}
if err = sess.Commit(); err != nil {
return err
}
return nil
}