forked from influxdata/kapacitor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bolt.go
108 lines (94 loc) · 1.92 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
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
package storage
import (
"bytes"
"github.com/boltdb/bolt"
)
// Bolt implementation of Store
type Bolt struct {
db *bolt.DB
bucket []byte
}
func NewBolt(db *bolt.DB, bucket string) *Bolt {
return &Bolt{
db: db,
bucket: []byte(bucket),
}
}
func (b *Bolt) Put(key string, value []byte) error {
return b.db.Update(func(tx *bolt.Tx) error {
bucket, err := tx.CreateBucketIfNotExists(b.bucket)
if err != nil {
return err
}
err = bucket.Put([]byte(key), value)
if err != nil {
return err
}
return nil
})
}
func (b *Bolt) Get(key string) (*KeyValue, error) {
var value []byte
err := b.db.View(func(tx *bolt.Tx) error {
bucket := tx.Bucket(b.bucket)
if bucket == nil {
return ErrNoKeyExists
}
val := bucket.Get([]byte(key))
if val == nil {
return ErrNoKeyExists
}
value = make([]byte, len(val))
copy(value, val)
return nil
})
if err != nil {
return nil, err
}
return &KeyValue{
Key: key,
Value: value,
}, nil
}
func (b *Bolt) Delete(key string) error {
return b.db.Update(func(tx *bolt.Tx) error {
bucket := tx.Bucket(b.bucket)
if bucket == nil {
return nil
}
return bucket.Delete([]byte(key))
})
}
func (b *Bolt) Exists(key string) (bool, error) {
var exists bool
err := b.db.View(func(tx *bolt.Tx) error {
bucket := tx.Bucket(b.bucket)
if bucket == nil {
return nil
}
val := bucket.Get([]byte(key))
exists = val != nil
return nil
})
return exists, err
}
func (b *Bolt) List(prefix string) (kvs []*KeyValue, err error) {
err = b.db.View(func(tx *bolt.Tx) error {
bucket := tx.Bucket(b.bucket)
if bucket == nil {
return nil
}
cursor := bucket.Cursor()
prefix := []byte(prefix)
for key, v := cursor.Seek(prefix); bytes.HasPrefix(key, prefix); key, v = cursor.Next() {
value := make([]byte, len(v))
copy(value, v)
kvs = append(kvs, &KeyValue{
Key: string(key),
Value: value,
})
}
return nil
})
return kvs, err
}