-
Notifications
You must be signed in to change notification settings - Fork 1
/
badger.go
89 lines (81 loc) · 2.42 KB
/
badger.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
// Copyright (c) 2017 The Alvalor Authors
//
// This file is part of Alvalor.
//
// Alvalor is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Alvalor is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with Alvalor. If not, see <http://www.gnu.org/licenses/>.
package kv
import (
"github.com/dgraph-io/badger"
"github.com/pkg/errors"
)
// Badger is a wrapper around the badger key-value stores that implements our database interface.
type Badger struct {
kv *badger.DB
}
// NewBadger creates a new KV store wraper around a badger database.
func NewBadger(kv *badger.DB) *Badger {
return &Badger{kv: kv}
}
// Put will insert a key-value pair into the database.
func (b *Badger) Put(key []byte, val []byte) error {
err := b.kv.Update(func(tx *badger.Txn) error {
err := tx.Set(key, val)
if err != nil {
return errors.Wrap(err, "could not set value for key")
}
return nil
})
return err
}
// Has will check if there is a value for the given key in the database.
func (b *Badger) Has(key []byte) (bool, error) {
var ok bool
err := b.kv.View(func(tx *badger.Txn) error {
_, err := tx.Get(key)
if err != nil {
return errors.Wrap(err, "could not get item for key")
}
ok = true
return nil
})
return ok, err
}
// Get will return the value for a given key, if it exists.
func (b *Badger) Get(key []byte) ([]byte, error) {
var val []byte
err := b.kv.View(func(tx *badger.Txn) error {
var err error
item, err := tx.Get(key)
if err != nil {
return errors.Wrap(err, "could not get item for key")
}
val, err = item.Value()
if err != nil {
return errors.Wrap(err, "could not get value from item")
}
return nil
})
return val, err
}
// Del will delete the key-value pair for the given key from the database, if it exists.
func (b *Badger) Del(key []byte) error {
err := b.kv.Update(func(tx *badger.Txn) error {
err := tx.Delete(key)
if err != nil {
return errors.Wrap(err, "could not delete value for key")
}
return nil
})
return err
}