-
Notifications
You must be signed in to change notification settings - Fork 0
/
badgerdb.go
executable file
·117 lines (93 loc) · 2.15 KB
/
badgerdb.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
package badgerdb
import (
"os"
"github.com/dgraph-io/badger"
"github.com/dgraph-io/badger/options"
)
// read + write + execute for owner only
const rwxOwner = 0700
// DB holds a pointer to the badger database and the path to where it is stored.
type DB struct {
db *badger.DB
path string
}
// NewDB is a constructor for the badger persister
// It creates the files in the location given as parameter
func NewDB(path string) (s *DB, err error) {
opts := badger.DefaultOptions
opts.Dir = path
opts.ValueDir = path
opts.ValueLogLoadingMode = options.FileIO
err = os.MkdirAll(path, rwxOwner)
if err != nil {
return nil, err
}
db, err := badger.Open(opts)
if err != nil {
return nil, err
}
dbStore := &DB{
db: db,
path: path,
}
return dbStore, nil
}
// Put adds the value to the (key, val) storage medium
func (s *DB) Put(key, val []byte) error {
err := s.db.Update(func(txn *badger.Txn) error {
err := txn.Set(key, val)
return err
})
return err
}
// Get returns the value associated to the key
func (s *DB) Get(key []byte) ([]byte, error) {
var value []byte
err := s.db.View(func(txn *badger.Txn) error {
item, err := txn.Get(key)
if err != nil {
return err
}
value, err = item.ValueCopy(nil)
if err != nil {
return err
}
return nil
})
if err != nil {
return nil, err
}
return value, nil
}
// Has returns true if the given key is present in the persistance medium
func (s *DB) Has(key []byte) error {
err := s.db.View(func(txn *badger.Txn) error {
_, err := txn.Get(key)
if err != nil {
return err
}
return nil
})
return err
}
// Init initializes the storage medium and prepares it for usage
func (s *DB) Init() error {
// no special initialization needed
return nil
}
// Close closes the files/resources associated to the storage medium
func (s *DB) Close() error {
return s.db.Close()
}
// Remove removes the data associated to the given key
func (s *DB) Remove(key []byte) error {
return s.db.Update(func(txn *badger.Txn) error {
return txn.Delete(key)
})
}
// Destroy removes the storage medium stored data
func (s *DB) Destroy() error {
s.db.Close()
err := os.RemoveAll(s.path)
return err
}