-
Notifications
You must be signed in to change notification settings - Fork 0
/
persistence.go
85 lines (75 loc) · 1.48 KB
/
persistence.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
package main
import (
"sync"
bolt "go.etcd.io/bbolt"
)
var (
radioBucket = []byte("radio")
dbMgr *dbManager
)
type dbManager struct {
sync.RWMutex
db *bolt.DB
}
func setupDbManager(refresh bool) error {
db, err := bolt.Open("record.db", 0600, nil)
if nil != err {
return err
}
err = db.Update(func(tx *bolt.Tx) error {
if refresh {
if err = tx.DeleteBucket(radioBucket); nil != err {
return err
}
}
_, err := tx.CreateBucketIfNotExists(radioBucket)
return err
})
if nil != err {
return err
}
dbMgr = &dbManager{
db: db,
}
return nil
}
func (m *dbManager) Find(key []byte) ([]byte, error) {
m.RLock()
defer m.RUnlock()
var result []byte
if err := m.db.View(func(tx *bolt.Tx) error {
bucket := tx.Bucket(radioBucket)
bytes := bucket.Get(key)
result = bytes
return nil
}); nil != err {
return nil, err
}
return result, nil
}
func (m *dbManager) All() ([][]byte, error) {
m.RLock()
defer m.RUnlock()
var result [][]byte
err := m.db.View(func(tx *bolt.Tx) error {
bucket := tx.Bucket(radioBucket)
cursor := bucket.Cursor()
for k, v := cursor.First(); k != nil; k, v = cursor.Next() {
result = append(result, v)
}
return nil
})
return result, err
}
func (m *dbManager) Insert(key, value []byte) error {
m.Lock()
defer m.Unlock()
err := m.db.Update(func(tx *bolt.Tx) error {
bucket := tx.Bucket(radioBucket)
if data := bucket.Get(key); len(data) <= 0 {
return bucket.Put(key, value)
}
return nil
})
return err
}