-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathleveldb.go
104 lines (91 loc) · 2.19 KB
/
leveldb.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
package golkeyval
import (
"fmt"
"os"
leveldb "github.com/syndtr/goleveldb/leveldb"
"github.com/syndtr/goleveldb/leveldb/filter"
"github.com/syndtr/goleveldb/leveldb/opt"
golerror "github.com/abhishekkr/gol/golerror"
)
/*
LevelDB struct with required leveldb details.
*/
type LevelDB struct {
DBPath string
GolDB *leveldb.DB
}
/*
init registers leveldb (GO implemented LevelDB) to DBEngines.
*/
func init() {
RegisterDBEngine("leveldb", new(LevelDB))
}
/*
Configure populates LevelDB required configs.
*/
func (levelDB *LevelDB) Configure(cfg map[string]string) {
levelDB.DBPath = cfg["DBPath"]
}
/*
CreateDB creates a leveldb db at provided DBPath.
*/
func (levelDB *LevelDB) CreateDB() {
var errDB error
opts := &opt.Options{
Filter: filter.NewBloomFilter(10),
}
levelDB.GolDB, errDB = leveldb.OpenFile(levelDB.DBPath, opts)
if errDB != nil {
errMsg := fmt.Sprintf("DB %s Creation failed. %q", levelDB.DBPath, errDB)
golerror.Boohoo(errMsg, true)
}
}
/*
CloseDB closes a db given handle.
*/
func (levelDB *LevelDB) CloseDB() {
levelDB.GolDB.Close()
}
/*
CloseAndDeleteDB closes and deletes a db given handle and DBPath.
Useful in use and throw implementations. And also tests.
*/
func (levelDB *LevelDB) CloseAndDeleteDB() {
levelDB.CloseDB()
if os.RemoveAll(levelDB.DBPath) != nil {
panic("Fail: Temporary DB files are still present at: " + levelDB.DBPath)
}
}
/*
PushKeyVal pushes key-val in provided DB handle.
*/
func (levelDB *LevelDB) PushKeyVal(key string, val string) bool {
err := levelDB.GolDB.Put([]byte(key), []byte(val), nil)
if err != nil {
golerror.Boohoo("Key "+key+" insertion failed. It's value was "+val, false)
return false
}
return true
}
/*
GetVal return string-ified value of key from provided db handle.
*/
func (levelDB *LevelDB) GetVal(key string) string {
data, err := levelDB.GolDB.Get([]byte(key), nil)
if err != nil {
golerror.Boohoo("Key "+key+" query failed.", false)
return ""
}
return string(data)
}
/*
DelKey deletes key from provided DB handle.
*/
func (levelDB *LevelDB) DelKey(key string) bool {
err := levelDB.GolDB.Delete([]byte(key), nil)
if err != nil {
golerror.Boohoo("Key "+key+" query failed.", false)
return false
}
return true
}