-
Notifications
You must be signed in to change notification settings - Fork 0
/
bolt_store.go
116 lines (82 loc) · 1.65 KB
/
bolt_store.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
package main
import (
"encoding/json"
"github.com/boltdb/bolt"
)
const userBucket = "users"
type boltStore struct {
db *bolt.DB
}
// NewBoltStore creates a new implementation
// of the Store interface which uses BoltDB
func NewBoltStore(d *bolt.DB) Store {
return &boltStore{
db: d,
}
}
func (b *boltStore) Upsert(u User) error {
return b.db.Update(func(tx *bolt.Tx) error {
bucket, err := tx.CreateBucketIfNotExists([]byte(userBucket))
if err != nil {
return err
}
jsonStr, err := json.Marshal(u)
if err != nil {
return err
}
err = bucket.Put([]byte(u.State), jsonStr)
if err != nil {
return err
}
return nil
})
}
func (b *boltStore) GetByState(state string) (*User, error) {
tx, err := b.db.Begin(false)
if err != nil {
return nil, err
}
// read only transactions are always rolled back
defer tx.Rollback()
bucket := tx.Bucket([]byte(userBucket))
if bucket == nil {
return nil, nil
}
val := bucket.Get([]byte(state))
if val == nil {
return nil, nil
}
var u User
err = json.Unmarshal(val, &u)
if err != nil {
return nil, err
}
return &u, nil
}
func (b *boltStore) GetAll() ([]*User, error) {
var users []*User
err := b.db.View(func(tx *bolt.Tx) error {
bucket := tx.Bucket([]byte(userBucket))
// if bucket hasn't been created, then there are no users
if bucket == nil {
return nil
}
err := bucket.ForEach(func(k, v []byte) error {
var u User
err := json.Unmarshal(v, &u)
if err != nil {
return err
}
users = append(users, &u)
return nil
})
if err != nil {
return err
}
return nil
})
if err != nil {
return nil, err
}
return users, nil
}