-
Notifications
You must be signed in to change notification settings - Fork 0
/
bolt.go
79 lines (61 loc) · 1.05 KB
/
bolt.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
package resources
import (
"encoding/binary"
"time"
"go.etcd.io/bbolt"
)
var BoltRootBucket = []byte("root")
type Bolt struct {
*bbolt.DB
path string
}
func NewBolt(path string) *Bolt {
return &Bolt{
path: path,
}
}
func (s *Bolt) GetName() string {
return "bolt"
}
func (s *Bolt) Start() error {
db, err := bbolt.Open(s.path, 0600, &bbolt.Options{Timeout: 1 * time.Second})
if err != nil {
return err
}
s.DB = db
return db.Update(func(tx *bbolt.Tx) error {
_, err = tx.CreateBucketIfNotExists(BoltRootBucket)
if err != nil {
return err
}
return nil
})
}
func (s *Bolt) Stop() error {
return s.DB.Close()
}
func Itob(v int) []byte {
b := make([]byte, 8)
binary.BigEndian.PutUint64(b, uint64(v))
return b
}
func (d *Bolt) Transaction(fn func() error) error {
tx, err := d.Begin(true)
if err != nil {
return err
}
defer func(tx *bbolt.Tx) {
err := tx.Rollback()
if err != nil {
panic(err)
}
}(tx)
err = fn()
if err != nil {
return err
}
if err := tx.Commit(); err != nil {
return err
}
return nil
}