-
Notifications
You must be signed in to change notification settings - Fork 0
/
datastore.go
99 lines (79 loc) · 1.75 KB
/
datastore.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
// datastore.go
package naprrql
import (
"fmt"
"log"
"github.com/nsip/nias2/naprr"
"github.com/syndtr/goleveldb/leveldb"
"github.com/syndtr/goleveldb/leveldb/util"
)
var db *leveldb.DB
var dbOpen bool = false
var ge = naprr.GobEncoder{}
func GetDB() *leveldb.DB {
if !dbOpen {
log.Println("DB not initialised. Opening...")
openDB()
}
return db
}
//
// open the kv store, this must be called before any access is attempted
//
func openDB() {
workingDir := "kvs"
var dbErr error
db, dbErr = leveldb.OpenFile(workingDir, nil)
if dbErr != nil {
log.Fatalln("DB Create error: ", dbErr)
}
dbOpen = true
}
//
// Given a key or key-prefix, returns the reference ids that
// can be used in a Get operation to retreive the
// desired object
//
func getIdentifiers(keyPrefix string) []string {
db = GetDB()
objIDs := make([]string, 0)
searchKey := []byte(keyPrefix + ":")
// log.Printf("search_key: %s\n\n", searchKey)
iter := db.NewIterator(util.BytesPrefix(searchKey), nil)
for iter.Next() {
id := fmt.Sprintf("%s", iter.Value())
objIDs = append(objIDs, id)
// break
}
iter.Release()
err := iter.Error()
if err != nil {
log.Println("Iterator error: ", err)
}
return objIDs
}
//
// get objects stored against the list of keys
//
func getObjects(objIDs []string) ([]interface{}, error) {
db = GetDB()
objects := []interface{}{}
for _, objID := range objIDs {
var object interface{}
data, err := db.Get([]byte(objID), nil)
if err != nil {
log.Println("Cannot find object with key: ", string(objID))
return objects, err
}
err = ge.Decode(data, &object)
if err != nil {
log.Println("Cannot decode object with key: ", objID, err)
return objects, err
}
objects = append(objects, object)
}
return objects, nil
}
//
//
//