-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdb.go
127 lines (92 loc) · 2.31 KB
/
db.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
package main
import (
"fmt"
"github.com/boltdb/bolt"
"log"
)
type DB struct {
Handle *bolt.DB
}
// Open the BoltDB file
func (db *DB) Open(dbfile string) {
var err error
db.Handle, err = bolt.Open(dbfile, 0600, nil)
if err != nil {
log.Fatalln(err)
}
return
}
// Close the BoltDB file
func (db *DB) Close() {
db.Handle.Close()
return
}
// Store a key/value in a BoltDB bucket
func (d *DB) Store(bucket, key, value string) error {
log.Println("Storing:", key)
err := d.Handle.Update(func(tx *bolt.Tx) error {
bkt, err := tx.CreateBucketIfNotExists([]byte(bucket))
if err != nil {
return fmt.Errorf("Could not create bucket %q", bucket)
}
err = bkt.Put([]byte(key), []byte(value))
if err != nil {
return fmt.Errorf("Could not write key %q to bucket %q: %v", key, bucket, err)
}
return nil
})
return err
}
// Delete a key from a BoltDB bucket
func (d *DB) Delete(bucket, key string) error {
log.Println("Deleting", key, "from bucket", bucket)
err := d.Handle.Update(func(tx *bolt.Tx) error {
bkt := tx.Bucket([]byte(bucket))
if bkt == nil {
return fmt.Errorf("Could not locate bucket to delete: %q", bucket)
}
err := bkt.Delete([]byte(key))
if err != nil {
return fmt.Errorf("Could not delete bucket %q: %v", bucket, err)
}
return nil
})
return err
}
// Fetch a key from a BoltDB bucket
func (d *DB) Fetch(bucket, key string) (string, error) {
var val string
log.Println("Fetching", key, "from bucket", bucket)
err := d.Handle.View(func(tx *bolt.Tx) error {
bkt := tx.Bucket([]byte(bucket))
if bkt == nil {
return fmt.Errorf("Bucket %q not found!", bucket)
}
val = string(bkt.Get([]byte(key)))
return nil
})
if val == "" {
return "", fmt.Errorf("Key %q in bucket %q not found", key, bucket)
}
return val, err
}
// Fetch every key from a BoltDB bucket
func (d *DB) FetchAll(bucket string) ([]string, error) {
var vals []string
log.Println("Fetching all from bucket", bucket)
err := d.Handle.View(func(tx *bolt.Tx) error {
bkt := tx.Bucket([]byte(bucket))
if bkt == nil {
return fmt.Errorf("Bucket %q not found!", bucket)
}
bkt.ForEach(func(k, v []byte) error {
vals = append(vals, string(v))
return nil
})
if len(vals) == 0 {
return fmt.Errorf("There are no items in bucket %v", bucket)
}
return nil
})
return vals, err
}