-
Notifications
You must be signed in to change notification settings - Fork 1
/
data.go
131 lines (109 loc) · 2.14 KB
/
data.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
128
129
130
131
package main
import (
"errors"
"fmt"
"github.com/boltdb/bolt"
"github.com/sirupsen/logrus"
"github.com/snapcore/snapd/osutil"
"time"
)
var db *bolt.DB
const (
dbPath = "data.db"
dbBucket = "records"
)
var (
errBucketEmpty = errors.New("[error] bucket are empty")
errValEmpty = errors.New("[error] value are empty")
)
func init() {
if !osutil.FileExists(dbPath) {
if err := startUp(false); err != nil {
logrus.Fatal(err)
}
defer func() {
if err := db.Close(); err != nil {
logrus.Fatal(err)
}
}()
}
}
func startUp(readOnly bool) error {
var err error
db, err = bolt.Open(dbPath, 0666,
&bolt.Options{
Timeout: 1 * time.Second,
ReadOnly: readOnly,
},
)
if err != nil {
return fmt.Errorf("[error opening the database] %s", err.Error())
}
return nil
}
func dbWrite(key, val []byte) error {
if err := startUp(false); err != nil {
return err
}
defer func() {
if err := db.Close(); err != nil {
logrus.Fatalf("[error closing the database] %s", err.Error())
}
}()
return db.Update(func(tx *bolt.Tx) error {
b, err := tx.CreateBucketIfNotExists([]byte(dbBucket))
if err != nil {
return err
}
if err = b.Put(key, val); err != nil {
return err
}
return nil
})
}
func dbRead(key string) ([]byte, error) {
err := startUp(true)
if err != nil {
return nil, err
}
defer func() {
if err := db.Close(); err != nil {
logrus.Fatalf("[error closing the database] %s", err.Error())
}
}()
var val []byte
if err = db.View(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte(dbBucket))
if b == nil {
return errBucketEmpty
}
result := b.Get([]byte(key))
val = make([]byte, len(result))
copy(val, result)
if len(val) == 0 {
return errValEmpty
}
return nil
}); err != nil {
return nil, err
}
return val, nil
}
func dbDelete(key string) error {
err := startUp(false)
if err != nil {
return err
}
defer func() {
if err := db.Close(); err != nil {
logrus.Fatalf("Error close db: %s", err)
}
}()
return db.Update(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte(dbBucket))
if b == nil {
return errBucketEmpty
}
return b.Delete([]byte(key))
})
}