-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbolthelper.go
103 lines (85 loc) · 2.32 KB
/
bolthelper.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
package main
import (
"encoding/json"
"github.com/boltdb/bolt"
)
// BoltGetKeys returns an array of all the keys from a given bucket
func BoltGetKeys(db *bolt.DB, bucketName string) ([]string, error) {
var keys []string
err := db.View(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte(bucketName))
b.ForEach(func(k, _ []byte) error {
keys = append(keys, string(k))
return nil
})
return nil
})
return keys, err
}
// BoltGetList will get a specific list of string (as array) from a
// boltdb bucket
func BoltGetList(db *bolt.DB, bucketName, key string) ([]string, error) {
var list []string
err := BoltGet(db, bucketName, key, &list)
return list, err
}
func BoltGet(db *bolt.DB, bucketName, key string, ptr interface{}) error {
return db.View(func(tx *bolt.Tx) error {
bucket := tx.Bucket(B(bucketName))
data := bucket.Get(B(key))
if len(data) == 0 {
// results in no changes to ptr
return nil
}
if err := json.Unmarshal(data, ptr); err != nil {
return err
}
return nil
})
}
func BoltSet(db *bolt.DB, bucketName, key string, obj interface{}) error {
return db.Update(func(tx *bolt.Tx) error {
bucket := tx.Bucket(B(bucketName))
data, _ := json.Marshal(obj)
return bucket.Put(B(key), data)
})
}
func BoltSetIfNil(db *bolt.DB, bucketName, key string, obj interface{}) error {
return db.Update(func(tx *bolt.Tx) error {
bucket := tx.Bucket(B(bucketName))
orig := bucket.Get(B(key))
if orig == nil {
data, err := json.Marshal(obj)
if err != nil {
return err
}
return bucket.Put(B(key), data)
}
return nil
})
}
func BoltDelete(db *bolt.DB, bucketName, key string) error {
return db.Update(func(tx *bolt.Tx) error {
bucket := tx.Bucket(B(bucketName))
return bucket.Delete(B(key))
})
}
// BoltAppendList appends a string to a list
func BoltAppendList(db *bolt.DB, bucketName, key, elem string) error {
return db.Update(func(tx *bolt.Tx) error {
bucket := tx.Bucket(B(bucketName))
// If already has an entry, unmarshal and append to it,
// else create a new array containing the element
var list []string
if data := bucket.Get(B(key)); data != nil {
if err := json.Unmarshal(data, &list); err != nil {
return err
}
list = append(list, elem)
} else {
list = []string{elem}
}
data, _ := json.Marshal(list)
return bucket.Put(B(key), data)
})
}