forked from nutsdb/nutsdb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb.go
1192 lines (985 loc) · 28.8 KB
/
db.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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2019 The nutsdb Author. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package nutsdb
import (
"errors"
"fmt"
"io"
"io/ioutil"
"os"
"path"
"path/filepath"
"sort"
"strings"
"sync"
"github.com/nutsdb/nutsdb/ds/list"
"github.com/nutsdb/nutsdb/ds/set"
"github.com/nutsdb/nutsdb/ds/zset"
"github.com/xujiajun/utils/filesystem"
"github.com/xujiajun/utils/strconv2"
)
var (
// ErrDBClosed is returned when db is closed.
ErrDBClosed = errors.New("db is closed")
// ErrBucket is returned when bucket is not in the HintIdx.
ErrBucket = errors.New("err bucket")
// ErrEntryIdxModeOpt is returned when set db EntryIdxMode option is wrong.
ErrEntryIdxModeOpt = errors.New("err EntryIdxMode option set")
// ErrFn is returned when fn is nil.
ErrFn = errors.New("err fn")
// ErrBucketNotFound is returned when looking for bucket that does not exist
ErrBucketNotFound = errors.New("bucket not found")
// ErrNotSupportHintBPTSparseIdxMode is returned not support mode `HintBPTSparseIdxMode`
ErrNotSupportHintBPTSparseIdxMode = errors.New("not support mode `HintBPTSparseIdxMode`")
)
const (
// DataDeleteFlag represents the data delete flag
DataDeleteFlag uint16 = iota
// DataSetFlag represents the data set flag
DataSetFlag
// DataLPushFlag represents the data LPush flag
DataLPushFlag
// DataRPushFlag represents the data RPush flag
DataRPushFlag
// DataLRemFlag represents the data LRem flag
DataLRemFlag
// DataLPopFlag represents the data LPop flag
DataLPopFlag
// DataRPopFlag represents the data RPop flag
DataRPopFlag
// DataLSetFlag represents the data LSet flag
DataLSetFlag
// DataLTrimFlag represents the data LTrim flag
DataLTrimFlag
// DataZAddFlag represents the data ZAdd flag
DataZAddFlag
// DataZRemFlag represents the data ZRem flag
DataZRemFlag
// DataZRemRangeByRankFlag represents the data ZRemRangeByRank flag
DataZRemRangeByRankFlag
// DataZPopMaxFlag represents the data ZPopMax flag
DataZPopMaxFlag
// DataZPopMinFlag represents the data aZPopMin flag
DataZPopMinFlag
// DataSetBucketDeleteFlag represents the delete Set bucket flag
DataSetBucketDeleteFlag
// DataSortedSetBucketDeleteFlag represents the delete Sorted Set bucket flag
DataSortedSetBucketDeleteFlag
// DataBPTreeBucketDeleteFlag represents the delete BPTree bucket flag
DataBPTreeBucketDeleteFlag
// DataListBucketDeleteFlag represents the delete List bucket flag
DataListBucketDeleteFlag
// LRemByIndex represents the data LRemByIndex flag
DataLRemByIndex
// DataListBucketDeleteFlag represents that set ttl for the list
DataExpireListFlag
)
const (
// UnCommitted represents the tx unCommitted status
UnCommitted uint16 = 0
// Committed represents the tx committed status
Committed uint16 = 1
// Persistent represents the data persistent flag
Persistent uint32 = 0
// ScanNoLimit represents the data scan no limit flag
ScanNoLimit int = -1
)
const (
// DataStructureSet represents the data structure set flag
DataStructureSet uint16 = iota
// DataStructureSortedSet represents the data structure sorted set flag
DataStructureSortedSet
// DataStructureBPTree represents the data structure b+ tree flag
DataStructureBPTree
// DataStructureList represents the data structure list flag
DataStructureList
// DataStructureNone represents not the data structure
DataStructureNone
)
type (
// DB represents a collection of buckets that persist on disk.
DB struct {
opt Options // the database options
BPTreeIdx BPTreeIdx // Hint Index
BPTreeRootIdxes []*BPTreeRootIdx
BPTreeKeyEntryPosMap map[string]int64 // key = bucket+key val = EntryPos
bucketMetas BucketMetasIdx
SetIdx SetIdx
SortedSetIdx SortedSetIdx
ListIdx ListIdx
ActiveFile *DataFile
ActiveBPTreeIdx *BPTree
ActiveCommittedTxIdsIdx *BPTree
committedTxIds map[uint64]struct{}
MaxFileID int64
mu sync.RWMutex
KeyCount int // total key number ,include expired, deleted, repeated.
closed bool
isMerging bool
fm *fileManager
}
// BPTreeIdx represents the B+ tree index
BPTreeIdx map[string]*BPTree
// SetIdx represents the set index
SetIdx map[string]*set.Set
// SortedSetIdx represents the sorted set index
SortedSetIdx map[string]*zset.SortedSet
// ListIdx represents the list index
ListIdx map[string]*list.List
// Entries represents entries
Entries []*Entry
// BucketMetasIdx represents the index of the bucket's meta-information
BucketMetasIdx map[string]*BucketMeta
)
// open returns a newly initialized DB object.
func open(opt Options) (*DB, error) {
db := &DB{
BPTreeIdx: make(BPTreeIdx),
SetIdx: make(SetIdx),
SortedSetIdx: make(SortedSetIdx),
ListIdx: make(ListIdx),
ActiveBPTreeIdx: NewTree(),
MaxFileID: 0,
opt: opt,
KeyCount: 0,
closed: false,
committedTxIds: make(map[uint64]struct{}),
BPTreeKeyEntryPosMap: make(map[string]int64),
bucketMetas: make(map[string]*BucketMeta),
ActiveCommittedTxIdsIdx: NewTree(),
fm: newFileManager(opt.RWMode, opt.MaxFdNumsInCache, opt.CleanFdsCacheThreshold),
}
if ok := filesystem.PathIsExist(db.opt.Dir); !ok {
if err := os.MkdirAll(db.opt.Dir, os.ModePerm); err != nil {
return nil, err
}
}
if err := db.checkEntryIdxMode(); err != nil {
return nil, err
}
if opt.EntryIdxMode == HintBPTSparseIdxMode {
bptRootIdxDir := db.opt.Dir + "/" + bptDir + "/root"
if ok := filesystem.PathIsExist(bptRootIdxDir); !ok {
if err := os.MkdirAll(bptRootIdxDir, os.ModePerm); err != nil {
return nil, err
}
}
bptTxIDIdxDir := db.opt.Dir + "/" + bptDir + "/txid"
if ok := filesystem.PathIsExist(bptTxIDIdxDir); !ok {
if err := os.MkdirAll(bptTxIDIdxDir, os.ModePerm); err != nil {
return nil, err
}
}
bucketMetaDir := db.opt.Dir + "/meta/bucket"
if ok := filesystem.PathIsExist(bucketMetaDir); !ok {
if err := os.MkdirAll(bucketMetaDir, os.ModePerm); err != nil {
return nil, err
}
}
}
if err := db.buildIndexes(); err != nil {
return nil, fmt.Errorf("db.buildIndexes error: %s", err)
}
return db, nil
}
// Open returns a newly initialized DB object with Option.
func Open(options Options, ops ...Option) (*DB, error) {
opts := &options
for _, do := range ops {
do(opts)
}
return open(*opts)
}
func (db *DB) checkEntryIdxMode() error {
hasDataFlag := false
hasBptDirFlag := false
files, err := ioutil.ReadDir(db.opt.Dir)
if err != nil {
return err
}
for _, f := range files {
id := f.Name()
fileSuffix := path.Ext(path.Base(id))
if fileSuffix == DataSuffix {
hasDataFlag = true
if hasBptDirFlag {
break
}
}
if id == bptDir {
hasBptDirFlag = true
}
}
if db.opt.EntryIdxMode != HintBPTSparseIdxMode && hasDataFlag && hasBptDirFlag {
return errors.New("not support HintBPTSparseIdxMode switch to the other EntryIdxMode")
}
if db.opt.EntryIdxMode == HintBPTSparseIdxMode && !hasBptDirFlag && hasDataFlag {
return errors.New("not support the other EntryIdxMode switch to HintBPTSparseIdxMode")
}
return nil
}
// Update executes a function within a managed read/write transaction.
func (db *DB) Update(fn func(tx *Tx) error) error {
if fn == nil {
return ErrFn
}
return db.managed(true, fn)
}
// View executes a function within a managed read-only transaction.
func (db *DB) View(fn func(tx *Tx) error) error {
if fn == nil {
return ErrFn
}
return db.managed(false, fn)
}
// Merge removes dirty data and reduce data redundancy,following these steps:
//
// 1. Filter delete or expired entry.
//
// 2. Write entry to activeFile if the key not exist,if exist miss this write operation.
//
// 3. Filter the entry which is committed.
//
// 4. At last remove the merged files.
//
// Caveat: Merge is Called means starting multiple write transactions, and it
// will affect the other write request. so execute it at the appropriate time.
func (db *DB) Merge() error {
var (
off int64
pendingMergeFIds []int
pendingMergeEntries []*Entry
)
if db.opt.EntryIdxMode == HintBPTSparseIdxMode {
return ErrNotSupportHintBPTSparseIdxMode
}
db.isMerging = true
_, pendingMergeFIds = db.getMaxFileIDAndFileIDs()
if len(pendingMergeFIds) < 2 {
db.isMerging = false
return errors.New("the number of files waiting to be merged is at least 2")
}
for _, pendingMergeFId := range pendingMergeFIds {
off = 0
path := db.getDataPath(int64(pendingMergeFId))
fr, err := newFileRecovery(path, db.opt.BufferSizeOfRecovery)
if err != nil {
db.isMerging = false
return err
}
pendingMergeEntries = []*Entry{}
for {
if entry, err := fr.readEntry(); err == nil {
if entry == nil {
break
}
var skipEntry bool
if db.isFilterEntry(entry) {
skipEntry = true
}
// check if we have a new entry with same key and bucket
if r, _ := db.getRecordFromKey(entry.Meta.Bucket, entry.Key); r != nil && !skipEntry {
if r.H.FileID > int64(pendingMergeFId) {
skipEntry = true
} else if r.H.FileID == int64(pendingMergeFId) && r.H.DataPos > uint64(off) {
skipEntry = true
}
}
if skipEntry {
off += entry.Size()
if off >= db.opt.SegmentSize {
break
}
continue
}
pendingMergeEntries = db.getPendingMergeEntries(entry, pendingMergeEntries)
off += entry.Size()
if off >= db.opt.SegmentSize {
break
}
} else {
if err == io.EOF {
break
}
if err == ErrIndexOutOfBound {
break
}
if err == io.ErrUnexpectedEOF {
break
}
return fmt.Errorf("when merge operation build hintIndex readAt err: %s", err)
}
}
if err := db.reWriteData(pendingMergeEntries); err != nil {
_ = fr.release()
return err
}
err = fr.release()
if err != nil {
return err
}
if err := os.Remove(path); err != nil {
db.isMerging = false
return fmt.Errorf("when merge err: %s", err)
}
}
return nil
}
// Backup copies the database to file directory at the given dir.
func (db *DB) Backup(dir string) error {
return db.View(func(tx *Tx) error {
return filesystem.CopyDir(db.opt.Dir, dir)
})
}
// BackupTarGZ Backup copy the database to writer.
func (db *DB) BackupTarGZ(w io.Writer) error {
return db.View(func(tx *Tx) error {
return tarGZCompress(w, db.opt.Dir)
})
}
// Close releases all db resources.
func (db *DB) Close() error {
db.mu.Lock()
defer db.mu.Unlock()
if db.closed {
return ErrDBClosed
}
db.closed = true
err := db.ActiveFile.rwManager.Release()
if err != nil {
return err
}
db.ActiveFile = nil
db.BPTreeIdx = nil
err = db.fm.close()
if err != nil {
return err
}
return nil
}
// setActiveFile sets the ActiveFile (DataFile object).
func (db *DB) setActiveFile() (err error) {
filepath := db.getDataPath(db.MaxFileID)
db.ActiveFile, err = db.fm.getDataFile(filepath, db.opt.SegmentSize)
if err != nil {
return
}
db.ActiveFile.fileID = db.MaxFileID
return nil
}
// getMaxFileIDAndFileIds returns max fileId and fileIds.
func (db *DB) getMaxFileIDAndFileIDs() (maxFileID int64, dataFileIds []int) {
files, _ := ioutil.ReadDir(db.opt.Dir)
if len(files) == 0 {
return 0, nil
}
maxFileID = 0
for _, f := range files {
id := f.Name()
fileSuffix := path.Ext(path.Base(id))
if fileSuffix != DataSuffix {
continue
}
id = strings.TrimSuffix(id, DataSuffix)
idVal, _ := strconv2.StrToInt(id)
dataFileIds = append(dataFileIds, idVal)
}
if len(dataFileIds) == 0 {
return 0, nil
}
sort.Ints(dataFileIds)
maxFileID = int64(dataFileIds[len(dataFileIds)-1])
return
}
// getActiveFileWriteOff returns the write-offset of activeFile.
func (db *DB) getActiveFileWriteOff() (off int64, err error) {
off = 0
for {
if item, err := db.ActiveFile.ReadAt(int(off)); err == nil {
if item == nil {
break
}
off += item.Size()
// set ActiveFileActualSize
db.ActiveFile.ActualSize = off
} else {
if err == io.EOF {
break
}
if err == ErrIndexOutOfBound {
break
}
return -1, fmt.Errorf("when build activeDataIndex readAt err: %s", err)
}
}
return
}
func (db *DB) parseDataFiles(dataFileIds []int) (unconfirmedRecords []*Record, committedTxIds map[uint64]struct{}, err error) {
var (
off int64
e *Entry
)
committedTxIds = make(map[uint64]struct{})
if db.opt.EntryIdxMode == HintBPTSparseIdxMode {
dataFileIds = dataFileIds[len(dataFileIds)-1:]
}
for _, dataID := range dataFileIds {
off = 0
fID := int64(dataID)
path := db.getDataPath(fID)
f, err := newFileRecovery(path, db.opt.BufferSizeOfRecovery)
if err != nil {
return nil, nil, err
}
for {
if entry, err := f.readEntry(); err == nil {
if entry == nil {
break
}
e = nil
if db.opt.EntryIdxMode == HintKeyValAndRAMIdxMode {
e = &Entry{
Key: entry.Key,
Value: entry.Value,
Meta: entry.Meta,
}
}
if entry.Meta.Status == Committed {
committedTxIds[entry.Meta.TxID] = struct{}{}
db.ActiveCommittedTxIdsIdx.Insert([]byte(strconv2.Int64ToStr(int64(entry.Meta.TxID))), nil,
&Hint{Meta: &MetaData{Flag: DataSetFlag}}, CountFlagEnabled)
}
unconfirmedRecords = append(unconfirmedRecords, &Record{
H: &Hint{
Key: entry.Key,
FileID: fID,
Meta: entry.Meta,
DataPos: uint64(off),
},
E: e,
})
if db.opt.EntryIdxMode == HintBPTSparseIdxMode {
db.BPTreeKeyEntryPosMap[string(getNewKey(string(entry.Meta.Bucket), entry.Key))] = off
}
off += entry.Size()
} else {
// whatever which logic branch it will choose, we will release the fd.
_ = f.release()
if err == io.EOF {
break
}
if err == ErrIndexOutOfBound {
break
}
if err == io.ErrUnexpectedEOF {
break
}
if off >= db.opt.SegmentSize {
break
}
if err != nil {
return nil, nil, err
}
return nil, nil, fmt.Errorf("when build hintIndex readAt err: %s", err)
}
}
if err != nil {
return nil, nil, err
}
}
return
}
func (db *DB) buildBPTreeRootIdxes(dataFileIds []int) error {
var off int64
dataFileIdsSize := len(dataFileIds)
if dataFileIdsSize == 1 {
return nil
}
for i := 0; i < len(dataFileIds[0:dataFileIdsSize-1]); i++ {
off = 0
path := db.getBPTRootPath(int64(dataFileIds[i]))
fd, err := os.OpenFile(filepath.Clean(path), os.O_RDWR, os.ModePerm)
if err != nil {
return err
}
for {
bs, err := ReadBPTreeRootIdxAt(fd, off)
if err == io.EOF || err == nil && bs == nil {
break
}
if err != nil {
return err
}
if err == nil && bs != nil {
db.BPTreeRootIdxes = append(db.BPTreeRootIdxes, bs)
off += bs.Size()
}
}
fd.Close()
}
db.committedTxIds = nil
return nil
}
func (db *DB) buildBPTreeIdx(bucket string, r *Record) error {
if _, ok := db.BPTreeIdx[bucket]; !ok {
db.BPTreeIdx[bucket] = NewTree()
}
if err := db.BPTreeIdx[bucket].Insert(r.H.Key, r.E, r.H, CountFlagEnabled); err != nil {
return fmt.Errorf("when build BPTreeIdx insert index err: %s", err)
}
return nil
}
func (db *DB) buildActiveBPTreeIdx(r *Record) error {
newKey := getNewKey(string(r.H.Meta.Bucket), r.H.Key)
if err := db.ActiveBPTreeIdx.Insert(newKey, r.E, r.H, CountFlagEnabled); err != nil {
return fmt.Errorf("when build BPTreeIdx insert index err: %s", err)
}
return nil
}
func (db *DB) buildBucketMetaIdx() error {
if db.opt.EntryIdxMode == HintBPTSparseIdxMode {
files, err := ioutil.ReadDir(db.getBucketMetaPath())
if err != nil {
return err
}
if len(files) != 0 {
for _, f := range files {
name := f.Name()
fileSuffix := path.Ext(path.Base(name))
if fileSuffix != BucketMetaSuffix {
continue
}
name = strings.TrimSuffix(name, BucketMetaSuffix)
bucketMeta, err := ReadBucketMeta(db.getBucketMetaFilePath(name))
if err == io.EOF {
break
}
if err != nil {
return err
}
db.bucketMetas[name] = bucketMeta
}
}
}
return nil
}
func (db *DB) buildOtherIdxes(bucket string, r *Record) error {
if r.H.Meta.Ds == DataStructureSet {
if err := db.buildSetIdx(bucket, r); err != nil {
return err
}
}
if r.H.Meta.Ds == DataStructureSortedSet {
if err := db.buildSortedSetIdx(bucket, r); err != nil {
return err
}
}
if r.H.Meta.Ds == DataStructureList {
if err := db.buildListIdx(bucket, r); err != nil {
return err
}
}
return nil
}
// buildHintIdx builds the Hint Indexes.
func (db *DB) buildHintIdx(dataFileIds []int) error {
unconfirmedRecords, committedTxIds, err := db.parseDataFiles(dataFileIds)
db.committedTxIds = committedTxIds
if err != nil {
return err
}
if len(unconfirmedRecords) == 0 {
return nil
}
for _, r := range unconfirmedRecords {
if _, ok := db.committedTxIds[r.H.Meta.TxID]; ok {
bucket := string(r.H.Meta.Bucket)
if r.H.Meta.Ds == DataStructureBPTree {
r.H.Meta.Status = Committed
if db.opt.EntryIdxMode == HintBPTSparseIdxMode {
if err = db.buildActiveBPTreeIdx(r); err != nil {
return err
}
} else {
if err = db.buildBPTreeIdx(bucket, r); err != nil {
return err
}
}
}
if err = db.buildOtherIdxes(bucket, r); err != nil {
return err
}
if r.H.Meta.Ds == DataStructureNone {
db.buildNotDSIdxes(bucket, r)
}
db.KeyCount++
}
}
if HintBPTSparseIdxMode == db.opt.EntryIdxMode {
if err = db.buildBPTreeRootIdxes(dataFileIds); err != nil {
return err
}
}
return nil
}
func (db *DB) buildNotDSIdxes(bucket string, r *Record) {
if r.H.Meta.Flag == DataSetBucketDeleteFlag {
db.deleteBucket(DataStructureSet, bucket)
}
if r.H.Meta.Flag == DataSortedSetBucketDeleteFlag {
db.deleteBucket(DataStructureSortedSet, bucket)
}
if r.H.Meta.Flag == DataBPTreeBucketDeleteFlag {
db.deleteBucket(DataStructureBPTree, bucket)
}
if r.H.Meta.Flag == DataListBucketDeleteFlag {
db.deleteBucket(DataStructureList, bucket)
}
}
func (db *DB) deleteBucket(ds uint16, bucket string) {
if ds == DataStructureSet {
delete(db.SetIdx, bucket)
}
if ds == DataStructureSortedSet {
delete(db.SortedSetIdx, bucket)
}
if ds == DataStructureBPTree {
delete(db.BPTreeIdx, bucket)
}
if ds == DataStructureList {
delete(db.ListIdx, bucket)
}
}
// buildSetIdx builds set index when opening the DB.
func (db *DB) buildSetIdx(bucket string, r *Record) error {
if _, ok := db.SetIdx[bucket]; !ok {
db.SetIdx[bucket] = set.New()
}
if r.E == nil {
return ErrEntryIdxModeOpt
}
if r.H.Meta.Flag == DataSetFlag {
if err := db.SetIdx[bucket].SAdd(string(r.E.Key), r.E.Value); err != nil {
return fmt.Errorf("when build SetIdx SAdd index err: %s", err)
}
}
if r.H.Meta.Flag == DataDeleteFlag {
if err := db.SetIdx[bucket].SRem(string(r.E.Key), r.E.Value); err != nil {
return fmt.Errorf("when build SetIdx SRem index err: %s", err)
}
}
return nil
}
// buildSortedSetIdx builds sorted set index when opening the DB.
func (db *DB) buildSortedSetIdx(bucket string, r *Record) error {
if _, ok := db.SortedSetIdx[bucket]; !ok {
db.SortedSetIdx[bucket] = zset.New()
}
if r.H.Meta.Flag == DataZAddFlag {
keyAndScore := strings.Split(string(r.E.Key), SeparatorForZSetKey)
if len(keyAndScore) == 2 {
key := keyAndScore[0]
score, _ := strconv2.StrToFloat64(keyAndScore[1])
if r.E == nil {
return ErrEntryIdxModeOpt
}
_ = db.SortedSetIdx[bucket].Put(key, zset.SCORE(score), r.E.Value)
}
}
if r.H.Meta.Flag == DataZRemFlag {
_ = db.SortedSetIdx[bucket].Remove(string(r.E.Key))
}
if r.H.Meta.Flag == DataZRemRangeByRankFlag {
start, _ := strconv2.StrToInt(string(r.E.Key))
end, _ := strconv2.StrToInt(string(r.E.Value))
_ = db.SortedSetIdx[bucket].GetByRankRange(start, end, true)
}
if r.H.Meta.Flag == DataZPopMaxFlag {
_ = db.SortedSetIdx[bucket].PopMax()
}
if r.H.Meta.Flag == DataZPopMinFlag {
_ = db.SortedSetIdx[bucket].PopMin()
}
return nil
}
// buildListIdx builds List index when opening the DB.
func (db *DB) buildListIdx(bucket string, r *Record) error {
if _, ok := db.ListIdx[bucket]; !ok {
db.ListIdx[bucket] = list.New()
}
if r.E == nil {
return ErrEntryIdxModeOpt
}
if IsExpired(r.E.Meta.TTL, r.E.Meta.Timestamp) {
return nil
}
switch r.H.Meta.Flag {
case DataExpireListFlag:
t, err := strconv2.StrToInt64(string(r.E.Value))
if err != nil {
return err
}
ttl := uint32(t)
db.ListIdx[bucket].TTL[string(r.E.Key)] = ttl
db.ListIdx[bucket].TimeStamp[string(r.E.Key)] = r.E.Meta.Timestamp
case DataLPushFlag:
_, _ = db.ListIdx[bucket].LPush(string(r.E.Key), r.E.Value)
case DataRPushFlag:
_, _ = db.ListIdx[bucket].RPush(string(r.E.Key), r.E.Value)
case DataLRemFlag:
countAndValueIndex := strings.Split(string(r.E.Value), SeparatorForListKey)
count, _ := strconv2.StrToInt(countAndValueIndex[0])
value := []byte(countAndValueIndex[1])
if _, err := db.ListIdx[bucket].LRem(string(r.E.Key), count, value); err != nil {
return ErrWhenBuildListIdx(err)
}
case DataLPopFlag:
if _, err := db.ListIdx[bucket].LPop(string(r.E.Key)); err != nil {
return ErrWhenBuildListIdx(err)
}
case DataRPopFlag:
if _, err := db.ListIdx[bucket].RPop(string(r.E.Key)); err != nil {
return ErrWhenBuildListIdx(err)
}
case DataLSetFlag:
keyAndIndex := strings.Split(string(r.E.Key), SeparatorForListKey)
newKey := keyAndIndex[0]
index, _ := strconv2.StrToInt(keyAndIndex[1])
if err := db.ListIdx[bucket].LSet(newKey, index, r.E.Value); err != nil {
return ErrWhenBuildListIdx(err)
}
case DataLTrimFlag:
keyAndStartIndex := strings.Split(string(r.E.Key), SeparatorForListKey)
newKey := keyAndStartIndex[0]
start, _ := strconv2.StrToInt(keyAndStartIndex[1])
end, _ := strconv2.StrToInt(string(r.E.Value))
if err := db.ListIdx[bucket].Ltrim(newKey, start, end); err != nil {
return ErrWhenBuildListIdx(err)
}
case DataLRemByIndex:
indexes, err := UnmarshalInts(r.E.Value)
if err != nil {
return err
}
if _, err := db.ListIdx[bucket].LRemByIndex(string(r.E.Key), indexes); err != nil {
return ErrWhenBuildListIdx(err)
}
}
return nil
}
// ErrWhenBuildListIdx returns err when build listIdx
func ErrWhenBuildListIdx(err error) error {
return fmt.Errorf("when build listIdx LRem err: %s", err)
}
// buildIndexes builds indexes when db initialize resource.
func (db *DB) buildIndexes() (err error) {
var (
maxFileID int64
dataFileIds []int
)
maxFileID, dataFileIds = db.getMaxFileIDAndFileIDs()
// init db.ActiveFile
db.MaxFileID = maxFileID
// set ActiveFile
if err = db.setActiveFile(); err != nil {
return
}
if dataFileIds == nil && maxFileID == 0 {
return
}
if db.ActiveFile.writeOff, err = db.getActiveFileWriteOff(); err != nil {
return
}
if err = db.buildBucketMetaIdx(); err != nil {
return
}
// build hint index
return db.buildHintIdx(dataFileIds)
}
// managed calls a block of code that is fully contained in a transaction.
func (db *DB) managed(writable bool, fn func(tx *Tx) error) (err error) {
var tx *Tx
tx, err = db.Begin(writable)
if err != nil {
return err
}