forked from gofiber/storage
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bbolt.go
110 lines (87 loc) · 1.97 KB
/
bbolt.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
package bbolt
import (
"time"
"github.com/gofiber/utils/v2"
"go.etcd.io/bbolt"
)
// Storage interface that is implemented by storage providers
type Storage struct {
conn *bbolt.DB
bucket string
}
// New creates a new storage
func New(config ...Config) *Storage {
// Set default config
cfg := configDefault(config...)
conn, err := bbolt.Open(cfg.Database, 0o666, &bbolt.Options{
Timeout: cfg.Timeout,
ReadOnly: cfg.ReadOnly,
})
if err != nil {
panic(err)
}
// Reset bucket if field selected
if cfg.Reset {
if err := removeBucket(cfg, conn); err != nil {
panic(err)
}
}
// Create bucket if not exists
if err := createBucket(cfg, conn); err != nil {
panic(err)
}
return &Storage{
conn: conn,
bucket: cfg.Bucket,
}
}
// Get value by key
func (s *Storage) Get(key string) ([]byte, error) {
if len(key) <= 0 {
return nil, nil
}
var value []byte
err := s.conn.View(func(tx *bbolt.Tx) error {
b := tx.Bucket(utils.UnsafeBytes(s.bucket))
value = b.Get(utils.UnsafeBytes(key))
return nil
})
return value, err
}
// Set key with value
func (s *Storage) Set(key string, value []byte, exp time.Duration) error {
if len(key) <= 0 || len(value) <= 0 {
return nil
}
return s.conn.Update(func(tx *bbolt.Tx) error {
b := tx.Bucket(utils.UnsafeBytes(s.bucket))
return b.Put(utils.UnsafeBytes(key), value)
})
}
// Delete entry by key
func (s *Storage) Delete(key string) error {
if len(key) <= 0 {
return nil
}
return s.conn.Update(func(tx *bbolt.Tx) error {
b := tx.Bucket(utils.UnsafeBytes(s.bucket))
return b.Delete(utils.UnsafeBytes(key))
})
}
// Reset all entries
func (s *Storage) Reset() error {
return s.conn.Update(func(tx *bbolt.Tx) error {
b := tx.Bucket(utils.UnsafeBytes(s.bucket))
return b.ForEach(func(k, _ []byte) error {
return b.Delete(k)
})
})
}
// Close the database
func (s *Storage) Close() error {
return s.conn.Close()
}
// Return database client
func (s *Storage) Conn() *bbolt.DB {
return s.conn
}