-
Notifications
You must be signed in to change notification settings - Fork 51
/
index.go
373 lines (302 loc) · 8.06 KB
/
index.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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
// Copyright 2019 Tim Shannon. All rights reserved.
// Use of this source code is governed by the MIT license
// that can be found in the LICENSE file.
package badgerhold
import (
"bytes"
"reflect"
"sort"
"github.com/dgraph-io/badger/v4"
)
const indexPrefix = "_bhIndex"
// size of iterator keys stored in memory before more are fetched
const iteratorKeyMinCacheSize = 100
// Index is a function that returns the indexable, encoded bytes of the passed in value
type Index struct {
IndexFunc func(name string, value interface{}) ([]byte, error)
Unique bool
}
// adds an item to the index
func (s *Store) indexAdd(storer Storer, tx *badger.Txn, key []byte, data interface{}) error {
indexes := storer.Indexes()
for name, index := range indexes {
err := s.indexUpdate(storer.Type(), name, index, tx, key, data, false)
if err != nil {
return err
}
}
return nil
}
// removes an item from the index
// be sure to pass the data from the old record, not the new one
func (s *Store) indexDelete(storer Storer, tx *badger.Txn, key []byte, originalData interface{}) error {
indexes := storer.Indexes()
for name, index := range indexes {
err := s.indexUpdate(storer.Type(), name, index, tx, key, originalData, true)
if err != nil {
return err
}
}
return nil
}
// adds or removes a specific index on an item
func (s *Store) indexUpdate(typeName, indexName string, index Index, tx *badger.Txn, key []byte, value interface{},
delete bool) error {
indexKey, err := index.IndexFunc(indexName, value)
if err != nil {
return err
}
if indexKey == nil {
return nil
}
indexValue := make(KeyList, 0)
indexKey = append(indexKeyPrefix(typeName, indexName), indexKey...)
item, err := tx.Get(indexKey)
if err != nil && err != badger.ErrKeyNotFound {
return err
}
if err != badger.ErrKeyNotFound {
if index.Unique && !delete {
return ErrUniqueExists
}
err = item.Value(func(iVal []byte) error {
return s.decode(iVal, &indexValue)
})
if err != nil {
return err
}
}
if delete {
indexValue.remove(key)
} else {
indexValue.add(key)
}
if len(indexValue) == 0 {
return tx.Delete(indexKey)
}
iVal, err := s.encode(indexValue)
if err != nil {
return err
}
return tx.Set(indexKey, iVal)
}
// indexKeyPrefix returns the prefix of the badger key where this index is stored
func indexKeyPrefix(typeName, indexName string) []byte {
return []byte(indexPrefix + ":" + typeName + ":" + indexName + ":")
}
// newIndexKey returns the badger key where this index is stored
func newIndexKey(typeName, indexName string, value []byte) []byte {
return append(indexKeyPrefix(typeName, indexName), value...)
}
// KeyList is a slice of unique, sorted keys([]byte) such as what an index points to
type KeyList [][]byte
func (v *KeyList) add(key []byte) {
i := sort.Search(len(*v), func(i int) bool {
return bytes.Compare((*v)[i], key) >= 0
})
if i < len(*v) && bytes.Equal((*v)[i], key) {
// already added
return
}
*v = append(*v, nil)
copy((*v)[i+1:], (*v)[i:])
(*v)[i] = key
}
func (v *KeyList) remove(key []byte) {
i := sort.Search(len(*v), func(i int) bool {
return bytes.Compare((*v)[i], key) >= 0
})
if i < len(*v) {
copy((*v)[i:], (*v)[i+1:])
(*v)[len(*v)-1] = nil
*v = (*v)[:len(*v)-1]
}
}
func (v *KeyList) in(key []byte) bool {
i := sort.Search(len(*v), func(i int) bool {
return bytes.Compare((*v)[i], key) >= 0
})
return (i < len(*v) && bytes.Equal((*v)[i], key))
}
func indexExists(it *badger.Iterator, typeName, indexName string) bool {
iPrefix := indexKeyPrefix(typeName, indexName)
tPrefix := typePrefix(typeName)
// test if any data exists for type
it.Seek(tPrefix)
if !it.ValidForPrefix(tPrefix) {
// store is empty for this data type so the index could possibly exist
// we don't want to fail on a "bad index" because they could simply be running a query against
// an empty dataset
return true
}
// test if an index exists
it.Seek(iPrefix)
if it.ValidForPrefix(iPrefix) {
return true
}
return false
}
type iterator struct {
keyCache [][]byte
nextKeys func(*badger.Iterator) ([][]byte, error)
iter *badger.Iterator
bookmark *iterBookmark
lastSeek []byte
tx *badger.Txn
err error
}
// iterBookmark stores a seek location in a specific iterator
// so that a single RW iterator can be shared within a single transaction
type iterBookmark struct {
iter *badger.Iterator
seekKey []byte
}
func (s *Store) newIterator(tx *badger.Txn, typeName string, query *Query, bookmark *iterBookmark) *iterator {
i := &iterator{
tx: tx,
}
if bookmark != nil {
i.iter = bookmark.iter
} else {
i.iter = tx.NewIterator(badger.DefaultIteratorOptions)
}
var prefix []byte
if query.index != "" {
query.badIndex = !indexExists(i.iter, typeName, query.index)
}
criteria := query.fieldCriteria[query.index]
if hasMatchFunc(criteria) {
// can't use indexes on matchFuncs as the entire record isn't available for testing in the passed
// in function
criteria = nil
}
// Key field or index not specified - test key against criteria (if it exists) or return everything
if query.index == "" || len(criteria) == 0 {
prefix = typePrefix(typeName)
i.iter.Seek(prefix)
i.nextKeys = func(iter *badger.Iterator) ([][]byte, error) {
var nKeys [][]byte
for len(nKeys) < iteratorKeyMinCacheSize {
if !iter.ValidForPrefix(prefix) {
return nKeys, nil
}
item := iter.Item()
key := item.KeyCopy(nil)
var ok bool
if len(criteria) == 0 {
// nothing to check return key for value testing
ok = true
} else {
val := reflect.New(query.dataType)
err := item.Value(func(v []byte) error {
return s.decode(v, val.Interface())
})
if err != nil {
return nil, err
}
ok, err = s.matchesAllCriteria(criteria, key, true, typeName, val.Interface())
if err != nil {
return nil, err
}
}
if ok {
nKeys = append(nKeys, key)
}
i.lastSeek = key
iter.Next()
}
return nKeys, nil
}
return i
}
// indexed field, get keys from index
prefix = indexKeyPrefix(typeName, query.index)
i.iter.Seek(prefix)
i.nextKeys = func(iter *badger.Iterator) ([][]byte, error) {
var nKeys [][]byte
for len(nKeys) < iteratorKeyMinCacheSize {
if !iter.ValidForPrefix(prefix) {
return nKeys, nil
}
item := iter.Item()
key := item.KeyCopy(nil)
// no currentRow on indexes as it refers to multiple rows
// remove index prefix for matching
ok, err := s.matchesAllCriteria(criteria, key[len(prefix):], true, "", nil)
if err != nil {
return nil, err
}
if ok {
err = item.Value(func(v []byte) error {
// append the slice of keys stored in the index
var keys = make(KeyList, 0)
err := s.decode(v, &keys)
if err != nil {
return err
}
nKeys = append(nKeys, [][]byte(keys)...)
return nil
})
if err != nil {
return nil, err
}
}
i.lastSeek = key
iter.Next()
}
return nKeys, nil
}
return i
}
func (i *iterator) createBookmark() *iterBookmark {
return &iterBookmark{
iter: i.iter,
seekKey: i.lastSeek,
}
}
// Next returns the next key value that matches the iterators criteria
// If no more kv's are available the return nil, if there is an error, they return nil
// and iterator.Error() will return the error
func (i *iterator) Next() (key []byte, value []byte) {
if i.err != nil {
return nil, nil
}
if len(i.keyCache) == 0 {
newKeys, err := i.nextKeys(i.iter)
if err != nil {
i.err = err
return nil, nil
}
if len(newKeys) == 0 {
return nil, nil
}
i.keyCache = append(i.keyCache, newKeys...)
}
key = i.keyCache[0]
i.keyCache = i.keyCache[1:]
item, err := i.tx.Get(key)
if err != nil {
i.err = err
return nil, nil
}
err = item.Value(func(val []byte) error {
value = val
return nil
})
if err != nil {
i.err = err
return nil, nil
}
return
}
// Error returns the last error, iterator.Next() will not continue if there is an error present
func (i *iterator) Error() error {
return i.err
}
func (i *iterator) Close() {
if i.bookmark != nil {
i.iter.Seek(i.bookmark.seekKey)
return
}
i.iter.Close()
}