-
Notifications
You must be signed in to change notification settings - Fork 1
/
bolt_wrapper.go
129 lines (113 loc) · 2.49 KB
/
bolt_wrapper.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
package main
import (
"errors"
"log"
"strings"
"time"
"github.com/boltdb/bolt"
)
var (
ErrorCannotFindBucket = errors.New("can't find the bucket")
ErrorPutData = errors.New("can't put data to bucket")
ErrorInvalidKey = errors.New("such key not found")
ErrorDBClosed = errors.New("DB is closed")
)
type BoltWrapper struct {
db *bolt.DB
}
func NewBoltWrapper(dbpath string) (bw *BoltWrapper, err error) {
db, err := bolt.Open(dbpath, 0644, &bolt.Options{Timeout: 1 * time.Second})
if err != nil {
return
}
bw = &BoltWrapper{
db: db,
}
return
}
func (bw *BoltWrapper) Close() (err error) {
if bw.db == nil {
err = ErrorDBClosed
return
}
err = bw.db.Close()
bw.db = nil
return
}
func (bw *BoltWrapper) CreateBucketIfNotExists(name string) (err error) {
if bw.db == nil {
err = ErrorDBClosed
return
}
return bw.db.Update(func(tx *bolt.Tx) error {
_, err = tx.CreateBucketIfNotExists([]byte(name))
return err
})
}
func (bw *BoltWrapper) PutDataToBucket(bucketName, key string, value []byte) (err error) {
if bw.db == nil {
err = ErrorDBClosed
return
}
return bw.db.Update(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte(bucketName))
if b == nil {
return ErrorCannotFindBucket
}
err = b.Put([]byte(key), value)
if err != nil {
return ErrorPutData
}
return nil
})
}
func (bw *BoltWrapper) GetDataFromBucket(bucketName, key string) (value string, err error) {
if bw.db == nil {
err = ErrorDBClosed
return
}
err = bw.db.View(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte(bucketName))
if b == nil {
return ErrorCannotFindBucket
}
data := b.Get([]byte(key))
if data == nil {
return ErrorInvalidKey
}
value = string(data)
return nil
})
return
}
func (bw *BoltWrapper) GetKeysFromBucket(bucketName string) (keys []string, err error) {
err = bw.db.View(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte(bucketName))
if b == nil {
return ErrorCannotFindBucket
}
return b.ForEach(func(k, v []byte) error {
keys = append(keys, string(k))
return nil
})
})
if err != nil {
return
}
return
}
func (bw *BoltWrapper) PrintAllData() (err error) {
if bw.db == nil {
err = ErrorDBClosed
return
}
return bw.db.View(func(tx *bolt.Tx) error {
return tx.ForEach(func(name []byte, b *bolt.Bucket) error {
log.Println("bucket:", string(name))
return b.ForEach(func(k, v []byte) error {
log.Println(" key:", string(k), "value:", strings.Split(string(v), "\n")[0])
return nil
})
})
})
}