-
Notifications
You must be signed in to change notification settings - Fork 1
/
bolt.go
89 lines (77 loc) · 1.73 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
package sse
import (
"errors"
"github.com/boltdb/bolt"
)
type BoltDB struct {
Conn *bolt.DB
}
func BoltDBOpen() (BoltDB, error) {
db, err := bolt.Open("my.db", 0600, nil)
if err != nil {
return BoltDB{}, err
}
conn := BoltDB{Conn: db}
return conn, nil
}
func (db BoltDB) Init() error {
err := db.Conn.Update(func(tx *bolt.Tx) error {
_, err := tx.CreateBucketIfNotExists([]byte(DOCUMENTS))
if err != nil {
return err
}
_, err = tx.CreateBucketIfNotExists([]byte(COUNTS))
if err != nil {
return err
}
_, err = tx.CreateBucketIfNotExists([]byte(INDEX))
if err != nil {
return err
}
return nil
})
return err
}
func (db BoltDB) Get(bucket string, id []byte) ([]byte, error) {
var value []byte
// Use View() to enforce read-only access to BoltDB.
err := db.Conn.View(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte(bucket))
if b == nil {
return errors.New("BoltDB: bucket not found")
}
temp := b.Get(id)
value = make([]byte, len(temp))
copy(value, temp)
return nil
})
return value, err
}
func (db BoltDB) Put(bucket string, id, value []byte) error {
// Use Update() to enforce read-write access to BoltDB.
err := db.Conn.Update(func(tx *bolt.Tx) error {
// TODO: Put logic
b := tx.Bucket([]byte(bucket))
if b == nil {
return errors.New("BoltDB: bucket not found")
}
err := b.Put(id, value)
return err
})
return err
}
func (db BoltDB) Delete(bucket string, id []byte) error {
// Use Update() to enforce read-write access to BoltDB.
err := db.Conn.Update(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte(bucket))
if b == nil {
return errors.New("BoltDB: bucket not found")
}
err := b.Delete(id)
return err
})
return err
}
func (db BoltDB) Close() {
db.Conn.Close()
}