forked from dymensionxyz/dymint
/
kv.go
67 lines (59 loc) · 1.8 KB
/
kv.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
package store
import (
"path/filepath"
"github.com/dgraph-io/badger/v3"
)
// KVStore encapsulates key-value store abstraction, in minimalistic interface.
//
// KVStore MUST be thread safe.
type KVStore interface {
Get(key []byte) ([]byte, error) // Get gets the value for a key.
Set(key []byte, value []byte) error // Set updates the value for a key.
Delete(key []byte) error // Delete deletes a key.
NewBatch() Batch // NewBatch creates a new batch.
PrefixIterator(prefix []byte) Iterator // PrefixIterator creates iterator to traverse given prefix.
}
// Batch enables batching of transactions.
type Batch interface {
Set(key, value []byte) error // Accumulates KV entries in a transaction.
Delete(key []byte) error // Deletes the given key.
Commit() error // Commits the transaction.
Discard() // Discards the transaction.
}
// Iterator enables traversal over a given prefix.
type Iterator interface {
Valid() bool
Next()
Key() []byte
Value() []byte
Error() error
Discard()
}
// NewDefaultInMemoryKVStore builds KVStore that works in-memory (without accessing disk).
func NewDefaultInMemoryKVStore() KVStore {
db, err := badger.Open(badger.DefaultOptions("").WithInMemory(true))
if err != nil {
panic(err)
}
return &BadgerKV{
db: db,
}
}
// NewDefaultKVStore creates instance of default key-value store.
func NewDefaultKVStore(rootDir, dbPath, dbName string) KVStore {
path := filepath.Join(rootify(rootDir, dbPath), dbName)
db, err := badger.Open(badger.DefaultOptions(path))
if err != nil {
panic(err)
}
return &BadgerKV{
db: db,
}
}
// rootify works just like in cosmos-sdk
func rootify(rootDir, dbPath string) string {
if filepath.IsAbs(dbPath) {
return dbPath
}
return filepath.Join(rootDir, dbPath)
}