-
Notifications
You must be signed in to change notification settings - Fork 15
/
kcplantdb.h
3943 lines (3928 loc) · 130 KB
/
kcplantdb.h
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
/*************************************************************************************************
* Plant database
* Copyright (C) 2009-2012 FAL Labs
* This file is part of Kyoto Cabinet.
* This program is free software: you can redistribute it and/or modify it under the terms of
* the GNU General Public License as published by the Free Software Foundation, either version
* 3 of the License, or any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
* You should have received a copy of the GNU General Public License along with this program.
* If not, see <http://www.gnu.org/licenses/>.
*************************************************************************************************/
#ifndef _KCPLANTDB_H // duplication check
#define _KCPLANTDB_H
#include <kccommon.h>
#include <kcutil.h>
#include <kcthread.h>
#include <kcfile.h>
#include <kccompress.h>
#include <kccompare.h>
#include <kcmap.h>
#include <kcregex.h>
#include <kcdb.h>
#define KCPDBMETAKEY "@" ///< key of the record for meta data
#define KCPDBTMPPATHEXT "tmpkct" ///< extension of the temporary file
#define KCPDRECBUFSIZ 128 ///< size of the record buffer
namespace kyotocabinet { // common namespace
/**
* Plant database.
* @param BASEDB a class compatible with the file hash database class.
* @param DBTYPE the database type number of the class.
* @note This class template is a template for concrete classes to operate tree databases.
* Template instance classes can be inherited but overwriting methods is forbidden. The class
* TreeDB is the instance of the file tree database. The class ForestDB is the instance of the
* directory tree database. Before every database operation, it is necessary to call the
* BasicDB::open method in order to open a database file and connect the database object to it.
* To avoid data missing or corruption, it is important to close every database file by the
* BasicDB::close method when the database is no longer in use. It is forbidden for multible
* database objects in a process to open the same database at the same time. It is forbidden to
* share a database object with child processes.
*/
template <class BASEDB, uint8_t DBTYPE>
class PlantDB : public BasicDB {
public:
class Cursor;
private:
struct Record;
struct RecordComparator;
struct LeafNode;
struct Link;
struct LinkComparator;
struct InnerNode;
struct LeafSlot;
struct InnerSlot;
class ScopedVisitor;
/** An alias of array of records. */
typedef std::vector<Record*> RecordArray;
/** An alias of array of records. */
typedef std::vector<Link*> LinkArray;
/** An alias of leaf node cache. */
typedef LinkedHashMap<int64_t, LeafNode*> LeafCache;
/** An alias of inner node cache. */
typedef LinkedHashMap<int64_t, InnerNode*> InnerCache;
/** An alias of list of cursors. */
typedef std::list<Cursor*> CursorList;
/** The number of cache slots. */
static const int32_t SLOTNUM = 16;
/** The default alignment power. */
static const uint8_t DEFAPOW = 8;
/** The default free block pool power. */
static const uint8_t DEFFPOW = 10;
/** The default bucket number. */
static const int64_t DEFBNUM = 64LL << 10;
/** The default page size. */
static const int32_t DEFPSIZ = 8192;
/** The default capacity size of the page cache. */
static const int64_t DEFPCCAP = 64LL << 20;
/** The size of the header. */
static const int64_t HEADSIZ = 80;
/** The offset of the numbers. */
static const int64_t MOFFNUMS = 8;
/** The prefix of leaf nodes. */
static const char LNPREFIX = 'L';
/** The prefix of inner nodes. */
static const char INPREFIX = 'I';
/** The average number of ways of each node. */
static const size_t AVGWAY = 16;
/** The ratio of the warm cache. */
static const size_t WARMRATIO = 4;
/** The ratio of flushing inner nodes. */
static const size_t INFLRATIO = 32;
/** The default number of items in each leaf node. */
static const size_t DEFLINUM = 64;
/** The default number of items in each inner node. */
static const size_t DEFIINUM = 128;
/** The base ID number for inner nodes. */
static const int64_t INIDBASE = 1LL << 48;
/** The minimum number of links in each inner node. */
static const size_t INLINKMIN = 8;
/** The maximum level of B+ tree. */
static const int32_t LEVELMAX = 16;
/** The number of cached nodes for auto transaction. */
static const int32_t ATRANCNUM = 256;
/** The threshold of busy loop and sleep for locking. */
static const uint32_t LOCKBUSYLOOP = 8192;
public:
/**
* Cursor to indicate a record.
*/
class Cursor : public BasicDB::Cursor {
friend class PlantDB;
public:
/**
* Constructor.
* @param db the container database object.
*/
explicit Cursor(PlantDB* db) :
db_(db), stack_(), kbuf_(NULL), ksiz_(0), lid_(0), back_(false) {
_assert_(db);
ScopedRWLock lock(&db_->mlock_, true);
db_->curs_.push_back(this);
}
/**
* Destructor.
*/
virtual ~Cursor() {
_assert_(true);
if (!db_) return;
ScopedRWLock lock(&db_->mlock_, true);
if (kbuf_) clear_position();
db_->curs_.remove(this);
}
/**
* Accept a visitor to the current record.
* @param visitor a visitor object.
* @param writable true for writable operation, or false for read-only operation.
* @param step true to move the cursor to the next record, or false for no move.
* @return true on success, or false on failure.
* @note The operation for each record is performed atomically and other threads accessing
* the same record are blocked. To avoid deadlock, any explicit database operation must not
* be performed in this function.
*/
bool accept(Visitor* visitor, bool writable = true, bool step = false) {
_assert_(visitor);
bool wrlock = writable && (db_->tran_ || db_->autotran_);
if (wrlock) {
db_->mlock_.lock_writer();
} else {
db_->mlock_.lock_reader();
}
if (db_->omode_ == 0) {
db_->set_error(_KCCODELINE_, Error::INVALID, "not opened");
db_->mlock_.unlock();
return false;
}
if (writable && !(db_->writer_)) {
db_->set_error(_KCCODELINE_, Error::NOPERM, "permission denied");
db_->mlock_.unlock();
return false;
}
if (!kbuf_) {
db_->set_error(_KCCODELINE_, Error::NOREC, "no record");
db_->mlock_.unlock();
return false;
}
bool err = false;
bool hit = false;
if (lid_ > 0 && !accept_spec(visitor, writable, step, &hit)) err = true;
if (!err && !hit) {
if (!wrlock) {
db_->mlock_.unlock();
db_->mlock_.lock_writer();
}
if (kbuf_) {
bool retry = true;
while (!err && retry) {
if (!accept_atom(visitor, step, &retry)) err = true;
}
} else {
db_->set_error(_KCCODELINE_, Error::NOREC, "no record");
err = true;
}
}
db_->mlock_.unlock();
return !err;
}
/**
* Jump the cursor to the first record for forward scan.
* @return true on success, or false on failure.
*/
bool jump() {
_assert_(true);
ScopedRWLock lock(&db_->mlock_, false);
if (db_->omode_ == 0) {
db_->set_error(_KCCODELINE_, Error::INVALID, "not opened");
return false;
}
back_ = false;
if (kbuf_) clear_position();
bool err = false;
if (!set_position(db_->first_)) err = true;
return !err;
}
/**
* Jump the cursor to a record for forward scan.
* @param kbuf the pointer to the key region.
* @param ksiz the size of the key region.
* @return true on success, or false on failure.
*/
bool jump(const char* kbuf, size_t ksiz) {
_assert_(kbuf && ksiz <= MEMMAXSIZ);
ScopedRWLock lock(&db_->mlock_, false);
if (db_->omode_ == 0) {
db_->set_error(_KCCODELINE_, Error::INVALID, "not opened");
return false;
}
back_ = false;
if (kbuf_) clear_position();
set_position(kbuf, ksiz, 0);
bool err = false;
if (!adjust_position()) {
if (kbuf_) clear_position();
err = true;
}
return !err;
}
/**
* Jump the cursor to a record for forward scan.
* @note Equal to the original Cursor::jump method except that the parameter is std::string.
*/
bool jump(const std::string& key) {
_assert_(true);
return jump(key.c_str(), key.size());
}
/**
* Jump the cursor to the last record for backward scan.
* @return true on success, or false on failure.
* @note This method is dedicated to tree databases. Some database types, especially hash
* databases, may provide a dummy implementation.
*/
bool jump_back() {
_assert_(true);
ScopedRWLock lock(&db_->mlock_, false);
if (db_->omode_ == 0) {
db_->set_error(_KCCODELINE_, Error::INVALID, "not opened");
return false;
}
back_ = true;
if (kbuf_) clear_position();
bool err = false;
if (!set_position_back(db_->last_)) err = true;
return !err;
}
/**
* Jump the cursor to a record for backward scan.
* @param kbuf the pointer to the key region.
* @param ksiz the size of the key region.
* @return true on success, or false on failure.
*/
bool jump_back(const char* kbuf, size_t ksiz) {
_assert_(kbuf && ksiz <= MEMMAXSIZ);
ScopedRWLock lock(&db_->mlock_, false);
if (db_->omode_ == 0) {
db_->set_error(_KCCODELINE_, Error::INVALID, "not opened");
return false;
}
back_ = true;
if (kbuf_) clear_position();
set_position(kbuf, ksiz, 0);
bool err = false;
if (adjust_position()) {
if (db_->reccomp_.comp->compare(kbuf, ksiz, kbuf_, ksiz_) < 0) {
bool hit = false;
if (lid_ > 0 && !back_position_spec(&hit)) err = true;
if (!err && !hit) {
db_->mlock_.unlock();
db_->mlock_.lock_writer();
if (kbuf_) {
if (!back_position_atom()) err = true;
} else {
db_->set_error(_KCCODELINE_, Error::NOREC, "no record");
err = true;
}
}
}
} else {
if (kbuf_) clear_position();
if (!set_position_back(db_->last_)) err = true;
}
return !err;
}
/**
* Jump the cursor to a record for backward scan.
* @note Equal to the original Cursor::jump_back method except that the parameter is
* std::string.
*/
bool jump_back(const std::string& key) {
_assert_(true);
return jump_back(key.c_str(), key.size());
}
/**
* Step the cursor to the next record.
* @return true on success, or false on failure.
*/
bool step() {
_assert_(true);
back_ = false;
DB::Visitor visitor;
if (!accept(&visitor, false, true)) return false;
if (!kbuf_) {
db_->set_error(_KCCODELINE_, Error::NOREC, "no record");
return false;
}
return true;
}
/**
* Step the cursor to the previous record.
* @return true on success, or false on failure.
*/
bool step_back() {
_assert_(true);
db_->mlock_.lock_reader();
if (db_->omode_ == 0) {
db_->set_error(_KCCODELINE_, Error::INVALID, "not opened");
db_->mlock_.unlock();
return false;
}
if (!kbuf_) {
db_->set_error(_KCCODELINE_, Error::NOREC, "no record");
db_->mlock_.unlock();
return false;
}
back_ = true;
bool err = false;
bool hit = false;
if (lid_ > 0 && !back_position_spec(&hit)) err = true;
if (!err && !hit) {
db_->mlock_.unlock();
db_->mlock_.lock_writer();
if (kbuf_) {
if (!back_position_atom()) err = true;
} else {
db_->set_error(_KCCODELINE_, Error::NOREC, "no record");
err = true;
}
}
db_->mlock_.unlock();
return !err;
}
/**
* Get the database object.
* @return the database object.
*/
PlantDB* db() {
_assert_(true);
return db_;
}
private:
/**
* Clear the position.
*/
void clear_position() {
_assert_(true);
if (kbuf_ != stack_) delete[] kbuf_;
kbuf_ = NULL;
lid_ = 0;
}
/**
* Set the current position.
* @param kbuf the pointer to the key region.
* @param ksiz the size of the key region.
* @param id the ID of the current node.
*/
void set_position(const char* kbuf, size_t ksiz, int64_t id) {
_assert_(kbuf);
kbuf_ = ksiz > sizeof(stack_) ? new char[ksiz] : stack_;
ksiz_ = ksiz;
std::memcpy(kbuf_, kbuf, ksiz);
lid_ = id;
}
/**
* Set the current position with a record.
* @param rec the current record.
* @param id the ID of the current node.
*/
void set_position(Record* rec, int64_t id) {
_assert_(rec);
char* dbuf = (char*)rec + sizeof(*rec);
set_position(dbuf, rec->ksiz, id);
}
/**
* Set the current position at the next node.
* @param id the ID of the next node.
* @return true on success, or false on failure.
*/
bool set_position(int64_t id) {
_assert_(true);
while (id > 0) {
LeafNode* node = db_->load_leaf_node(id, false);
if (!node) {
db_->set_error(_KCCODELINE_, Error::BROKEN, "missing leaf node");
db_->db_.report(_KCCODELINE_, Logger::WARN, "id=%lld", (long long)id);
return false;
}
ScopedRWLock lock(&node->lock, false);
RecordArray& recs = node->recs;
if (!recs.empty()) {
set_position(recs.front(), id);
return true;
} else {
id = node->next;
}
}
db_->set_error(_KCCODELINE_, Error::NOREC, "no record");
return false;
}
/**
* Set the current position at the previous node.
* @param id the ID of the previous node.
* @return true on success, or false on failure.
*/
bool set_position_back(int64_t id) {
_assert_(true);
while (id > 0) {
LeafNode* node = db_->load_leaf_node(id, false);
if (!node) {
db_->set_error(_KCCODELINE_, Error::BROKEN, "missing leaf node");
db_->db_.report(_KCCODELINE_, Logger::WARN, "id=%lld", (long long)id);
return false;
}
ScopedRWLock lock(&node->lock, false);
RecordArray& recs = node->recs;
if (!recs.empty()) {
set_position(recs.back(), id);
return true;
} else {
id = node->prev;
}
}
db_->set_error(_KCCODELINE_, Error::NOREC, "no record");
return false;
}
/**
* Accept a visitor to the current record speculatively.
* @param visitor a visitor object.
* @param writable true for writable operation, or false for read-only operation.
* @param step true to move the cursor to the next record, or false for no move.
* @param hitp the pointer to the variable for the hit flag.
* @return true on success, or false on failure.
*/
bool accept_spec(Visitor* visitor, bool writable, bool step, bool* hitp) {
_assert_(visitor && hitp);
bool err = false;
bool hit = false;
char rstack[KCPDRECBUFSIZ];
size_t rsiz = sizeof(Record) + ksiz_;
char* rbuf = rsiz > sizeof(rstack) ? new char[rsiz] : rstack;
Record* rec = (Record*)rbuf;
rec->ksiz = ksiz_;
rec->vsiz = 0;
std::memcpy(rbuf + sizeof(*rec), kbuf_, ksiz_);
LeafNode* node = db_->load_leaf_node(lid_, false);
if (node) {
char lstack[KCPDRECBUFSIZ];
char* lbuf = NULL;
size_t lsiz = 0;
Link* link = NULL;
int64_t hist[LEVELMAX];
int32_t hnum = 0;
if (writable) {
node->lock.lock_writer();
} else {
node->lock.lock_reader();
}
RecordArray& recs = node->recs;
if (!recs.empty()) {
Record* frec = recs.front();
Record* lrec = recs.back();
if (!db_->reccomp_(rec, frec) && !db_->reccomp_(lrec, rec)) {
typename RecordArray::iterator ritend = recs.end();
typename RecordArray::iterator rit = std::lower_bound(recs.begin(), ritend,
rec, db_->reccomp_);
if (rit != ritend) {
hit = true;
if (db_->reccomp_(rec, *rit)) {
clear_position();
set_position(*rit, node->id);
if (rbuf != rstack) delete[] rbuf;
rsiz = sizeof(Record) + ksiz_;
rbuf = rsiz > sizeof(rstack) ? new char[rsiz] : rstack;
rec = (Record*)rbuf;
rec->ksiz = ksiz_;
rec->vsiz = 0;
std::memcpy(rbuf + sizeof(*rec), kbuf_, ksiz_);
}
rec = *rit;
char* kbuf = (char*)rec + sizeof(*rec);
size_t ksiz = rec->ksiz;
size_t vsiz;
const char* vbuf = visitor->visit_full(kbuf, ksiz, kbuf + ksiz,
rec->vsiz, &vsiz);
if (vbuf == Visitor::REMOVE) {
rsiz = sizeof(*rec) + rec->ksiz + rec->vsiz;
db_->count_ -= 1;
db_->cusage_ -= rsiz;
node->size -= rsiz;
node->dirty = true;
if (recs.size() <= 1) {
lsiz = sizeof(Link) + ksiz;
lbuf = lsiz > sizeof(lstack) ? new char[lsiz] : lstack;
link = (Link*)lbuf;
link->child = 0;
link->ksiz = ksiz;
std::memcpy(lbuf + sizeof(*link), kbuf, ksiz);
}
xfree(rec);
if (back_) {
if (rit == recs.begin()) {
step = true;
} else {
typename RecordArray::iterator ritprev = rit - 1;
set_position(*ritprev, node->id);
step = false;
}
} else {
typename RecordArray::iterator ritnext = rit + 1;
if (ritnext == ritend) {
step = true;
} else {
clear_position();
set_position(*ritnext, node->id);
step = false;
}
}
recs.erase(rit);
} else if (vbuf != Visitor::NOP) {
int64_t diff = (int64_t)vsiz - (int64_t)rec->vsiz;
db_->cusage_ += diff;
node->size += diff;
node->dirty = true;
if (vsiz > rec->vsiz) {
*rit = (Record*)xrealloc(rec, sizeof(*rec) + rec->ksiz + vsiz);
rec = *rit;
kbuf = (char*)rec + sizeof(*rec);
}
std::memcpy(kbuf + rec->ksiz, vbuf, vsiz);
rec->vsiz = vsiz;
if (node->size > db_->psiz_ && recs.size() > 1) {
lsiz = sizeof(Link) + ksiz;
lbuf = lsiz > sizeof(lstack) ? new char[lsiz] : lstack;
link = (Link*)lbuf;
link->child = 0;
link->ksiz = ksiz;
std::memcpy(lbuf + sizeof(*link), kbuf, ksiz);
}
}
if (step) {
if (back_) {
if (rit != recs.begin()) {
--rit;
set_position(*rit, node->id);
step = false;
}
} else {
++rit;
if (rit != ritend) {
clear_position();
set_position(*rit, node->id);
step = false;
}
}
}
}
}
}
bool atran = db_->autotran_ && !db_->tran_ && node->dirty;
bool async = db_->autosync_ && !db_->autotran_ && !db_->tran_ && node->dirty;
node->lock.unlock();
if (hit && step) {
clear_position();
if (back_) {
set_position_back(node->prev);
} else {
set_position(node->next);
}
}
if (hit) {
bool flush = db_->cusage_ > db_->pccap_;
if (link || flush || async) {
int64_t id = node->id;
if (atran && !link && !db_->fix_auto_transaction_leaf(node)) err = true;
db_->mlock_.unlock();
db_->mlock_.lock_writer();
if (link) {
node = db_->search_tree(link, true, hist, &hnum);
if (node) {
if (!db_->reorganize_tree(node, hist, hnum)) err = true;
if (atran && !db_->tran_ && !db_->fix_auto_transaction_tree()) err = true;
} else {
db_->set_error(_KCCODELINE_, Error::BROKEN, "search failed");
err = true;
}
} else if (flush) {
int32_t idx = id % SLOTNUM;
LeafSlot* lslot = db_->lslots_ + idx;
if (!db_->flush_leaf_cache_part(lslot)) err = true;
InnerSlot* islot = db_->islots_ + idx;
if (islot->warm->count() > lslot->warm->count() + lslot->hot->count() + 1 &&
!db_->flush_inner_cache_part(islot)) err = true;
}
if (async && !db_->fix_auto_synchronization()) err = true;
} else {
if (!db_->fix_auto_transaction_leaf(node)) err = true;
}
}
if (lbuf != lstack) delete[] lbuf;
}
if (rbuf != rstack) delete[] rbuf;
*hitp = hit;
return !err;
}
/**
* Accept a visitor to the current record atomically.
* @param visitor a visitor object.
* @param step true to move the cursor to the next record, or false for no move.
* @param retryp the pointer to the variable for the retry flag.
* @return true on success, or false on failure.
*/
bool accept_atom(Visitor* visitor, bool step, bool *retryp) {
_assert_(visitor && retryp);
bool err = false;
bool reorg = false;
*retryp = false;
char lstack[KCPDRECBUFSIZ];
size_t lsiz = sizeof(Link) + ksiz_;
char* lbuf = lsiz > sizeof(lstack) ? new char[lsiz] : lstack;
Link* link = (Link*)lbuf;
link->child = 0;
link->ksiz = ksiz_;
std::memcpy(lbuf + sizeof(*link), kbuf_, ksiz_);
int64_t hist[LEVELMAX];
int32_t hnum = 0;
LeafNode* node = db_->search_tree(link, true, hist, &hnum);
if (!node) {
db_->set_error(_KCCODELINE_, Error::BROKEN, "search failed");
if (lbuf != lstack) delete[] lbuf;
return false;
}
if (node->recs.empty()) {
if (lbuf != lstack) delete[] lbuf;
clear_position();
if (!set_position(node->next)) return false;
node = db_->load_leaf_node(lid_, false);
if (!node) {
db_->set_error(_KCCODELINE_, Error::BROKEN, "search failed");
return false;
}
lsiz = sizeof(Link) + ksiz_;
char* lbuf = lsiz > sizeof(lstack) ? new char[lsiz] : lstack;
Link* link = (Link*)lbuf;
link->child = 0;
link->ksiz = ksiz_;
std::memcpy(lbuf + sizeof(*link), kbuf_, ksiz_);
node = db_->search_tree(link, true, hist, &hnum);
if (node->id != lid_) {
db_->set_error(_KCCODELINE_, Error::BROKEN, "invalid tree");
if (lbuf != lstack) delete[] lbuf;
return false;
}
}
char rstack[KCPDRECBUFSIZ];
size_t rsiz = sizeof(Record) + ksiz_;
char* rbuf = rsiz > sizeof(rstack) ? new char[rsiz] : rstack;
Record* rec = (Record*)rbuf;
rec->ksiz = ksiz_;
rec->vsiz = 0;
std::memcpy(rbuf + sizeof(*rec), kbuf_, ksiz_);
RecordArray& recs = node->recs;
typename RecordArray::iterator ritend = recs.end();
typename RecordArray::iterator rit = std::lower_bound(recs.begin(), ritend,
rec, db_->reccomp_);
if (rit != ritend) {
if (db_->reccomp_(rec, *rit)) {
clear_position();
set_position(*rit, node->id);
if (rbuf != rstack) delete[] rbuf;
rsiz = sizeof(Record) + ksiz_;
rbuf = rsiz > sizeof(rstack) ? new char[rsiz] : rstack;
rec = (Record*)rbuf;
rec->ksiz = ksiz_;
rec->vsiz = 0;
std::memcpy(rbuf + sizeof(*rec), kbuf_, ksiz_);
}
rec = *rit;
char* kbuf = (char*)rec + sizeof(*rec);
size_t ksiz = rec->ksiz;
size_t vsiz;
const char* vbuf = visitor->visit_full(kbuf, ksiz, kbuf + ksiz,
rec->vsiz, &vsiz);
if (vbuf == Visitor::REMOVE) {
rsiz = sizeof(*rec) + rec->ksiz + rec->vsiz;
db_->count_ -= 1;
db_->cusage_ -= rsiz;
node->size -= rsiz;
node->dirty = true;
xfree(rec);
step = false;
clear_position();
if (back_) {
if (rit == recs.begin()) {
set_position_back(node->prev);
} else {
typename RecordArray::iterator ritprev = rit - 1;
set_position(*ritprev, node->id);
}
} else {
typename RecordArray::iterator ritnext = rit + 1;
if (ritnext == ritend) {
set_position(node->next);
} else {
set_position(*ritnext, node->id);
}
}
recs.erase(rit);
if (recs.empty()) reorg = true;
} else if (vbuf != Visitor::NOP) {
int64_t diff = (int64_t)vsiz - (int64_t)rec->vsiz;
db_->cusage_ += diff;
node->size += diff;
node->dirty = true;
if (vsiz > rec->vsiz) {
*rit = (Record*)xrealloc(rec, sizeof(*rec) + rec->ksiz + vsiz);
rec = *rit;
kbuf = (char*)rec + sizeof(*rec);
}
std::memcpy(kbuf + rec->ksiz, vbuf, vsiz);
rec->vsiz = vsiz;
if (node->size > db_->psiz_ && recs.size() > 1) reorg = true;
}
if (step) {
clear_position();
if (back_) {
if (rit == recs.begin()) {
set_position_back(node->prev);
} else {
--rit;
set_position(*rit, node->id);
}
} else {
++rit;
if (rit == ritend) {
set_position(node->next);
} else {
set_position(*rit, node->id);
}
}
}
bool atran = db_->autotran_ && !db_->tran_ && node->dirty;
bool async = db_->autosync_ && !db_->autotran_ && !db_->tran_ && node->dirty;
if (atran && !reorg && !db_->fix_auto_transaction_leaf(node)) err = true;
if (reorg) {
if (!db_->reorganize_tree(node, hist, hnum)) err = true;
if (atran && !db_->fix_auto_transaction_tree()) err = true;
} else if (db_->cusage_ > db_->pccap_) {
int32_t idx = node->id % SLOTNUM;
LeafSlot* lslot = db_->lslots_ + idx;
if (!db_->flush_leaf_cache_part(lslot)) err = true;
InnerSlot* islot = db_->islots_ + idx;
if (islot->warm->count() > lslot->warm->count() + lslot->hot->count() + 1 &&
!db_->flush_inner_cache_part(islot)) err = true;
}
if (async && !db_->fix_auto_synchronization()) err = true;
} else {
int64_t lid = lid_;
clear_position();
if (back_) {
if (set_position_back(node->prev)) {
if (lid_ == lid) {
db_->set_error(_KCCODELINE_, Error::BROKEN, "invalid leaf node");
err = true;
} else {
*retryp = true;
}
} else {
db_->set_error(_KCCODELINE_, Error::NOREC, "no record");
err = true;
}
} else {
if (set_position(node->next)) {
if (lid_ == lid) {
db_->set_error(_KCCODELINE_, Error::BROKEN, "invalid leaf node");
err = true;
} else {
*retryp = true;
}
} else {
db_->set_error(_KCCODELINE_, Error::NOREC, "no record");
err = true;
}
}
}
if (rbuf != rstack) delete[] rbuf;
if (lbuf != lstack) delete[] lbuf;
return !err;
}
/**
* Adjust the position to an existing record.
* @return true on success, or false on failure.
*/
bool adjust_position() {
_assert_(true);
char lstack[KCPDRECBUFSIZ];
size_t lsiz = sizeof(Link) + ksiz_;
char* lbuf = lsiz > sizeof(lstack) ? new char[lsiz] : lstack;
Link* link = (Link*)lbuf;
link->child = 0;
link->ksiz = ksiz_;
std::memcpy(lbuf + sizeof(*link), kbuf_, ksiz_);
int64_t hist[LEVELMAX];
int32_t hnum = 0;
LeafNode* node = db_->search_tree(link, true, hist, &hnum);
if (!node) {
db_->set_error(_KCCODELINE_, Error::BROKEN, "search failed");
if (lbuf != lstack) delete[] lbuf;
return false;
}
char rstack[KCPDRECBUFSIZ];
size_t rsiz = sizeof(Record) + ksiz_;
char* rbuf = rsiz > sizeof(rstack) ? new char[rsiz] : rstack;
Record* rec = (Record*)rbuf;
rec->ksiz = ksiz_;
rec->vsiz = 0;
std::memcpy(rbuf + sizeof(*rec), kbuf_, ksiz_);
bool err = false;
node->lock.lock_reader();
const RecordArray& recs = node->recs;
typename RecordArray::const_iterator ritend = node->recs.end();
typename RecordArray::const_iterator rit = std::lower_bound(recs.begin(), ritend,
rec, db_->reccomp_);
clear_position();
if (rit == ritend) {
node->lock.unlock();
if (!set_position(node->next)) err = true;
} else {
set_position(*rit, node->id);
node->lock.unlock();
}
if (rbuf != rstack) delete[] rbuf;
if (lbuf != lstack) delete[] lbuf;
return !err;
}
/**
* Back the position to the previous record speculatively.
* @param hitp the pointer to the variable for the hit flag.
* @return true on success, or false on failure.
*/
bool back_position_spec(bool* hitp) {
_assert_(hitp);
bool err = false;
bool hit = false;
char rstack[KCPDRECBUFSIZ];
size_t rsiz = sizeof(Record) + ksiz_;
char* rbuf = rsiz > sizeof(rstack) ? new char[rsiz] : rstack;
Record* rec = (Record*)rbuf;
rec->ksiz = ksiz_;
rec->vsiz = 0;
std::memcpy(rbuf + sizeof(*rec), kbuf_, ksiz_);
LeafNode* node = db_->load_leaf_node(lid_, false);
if (node) {
node->lock.lock_reader();
RecordArray& recs = node->recs;
if (recs.empty()) {
node->lock.unlock();
} else {
Record* frec = recs.front();
Record* lrec = recs.back();
if (db_->reccomp_(rec, frec)) {
hit = true;
clear_position();
node->lock.unlock();
if (!set_position_back(node->prev)) err = true;
} else if (db_->reccomp_(lrec, rec)) {
node->lock.unlock();
} else {
hit = true;
typename RecordArray::iterator ritbeg = recs.begin();
typename RecordArray::iterator ritend = recs.end();
typename RecordArray::iterator rit = std::lower_bound(recs.begin(), ritend,
rec, db_->reccomp_);
clear_position();
if (rit == ritbeg) {
node->lock.unlock();
if (!set_position_back(node->prev)) err = true;
} else {
--rit;
set_position(*rit, node->id);
node->lock.unlock();
}
}
}
}
if (rbuf != rstack) delete[] rbuf;
*hitp = hit;
return !err;
}
/**
* Back the position to the previous record atomically.
* @return true on success, or false on failure.
*/
bool back_position_atom() {
_assert_(true);
char lstack[KCPDRECBUFSIZ];
size_t lsiz = sizeof(Link) + ksiz_;
char* lbuf = lsiz > sizeof(lstack) ? new char[lsiz] : lstack;
Link* link = (Link*)lbuf;
link->child = 0;
link->ksiz = ksiz_;
std::memcpy(lbuf + sizeof(*link), kbuf_, ksiz_);
int64_t hist[LEVELMAX];
int32_t hnum = 0;
LeafNode* node = db_->search_tree(link, true, hist, &hnum);
if (!node) {
db_->set_error(_KCCODELINE_, Error::BROKEN, "search failed");
if (lbuf != lstack) delete[] lbuf;
return false;
}
char rstack[KCPDRECBUFSIZ];
size_t rsiz = sizeof(Record) + ksiz_;
char* rbuf = rsiz > sizeof(rstack) ? new char[rsiz] : rstack;
Record* rec = (Record*)rbuf;
rec->ksiz = ksiz_;
rec->vsiz = 0;
std::memcpy(rbuf + sizeof(*rec), kbuf_, ksiz_);
bool err = false;
node->lock.lock_reader();
const RecordArray& recs = node->recs;
typename RecordArray::const_iterator ritbeg = node->recs.begin();
typename RecordArray::const_iterator ritend = node->recs.end();
typename RecordArray::const_iterator rit = std::lower_bound(recs.begin(), ritend,
rec, db_->reccomp_);
clear_position();
if (rit == ritbeg) {
node->lock.unlock();
if (!set_position_back(node->prev)) err = true;
} else if (rit == ritend) {
ritend--;
set_position(*ritend, node->id);
node->lock.unlock();
} else {
--rit;
set_position(*rit, node->id);
node->lock.unlock();
}
if (rbuf != rstack) delete[] rbuf;
if (lbuf != lstack) delete[] lbuf;
return !err;
}
/** Dummy constructor to forbid the use. */
Cursor(const Cursor&);
/** Dummy Operator to forbid the use. */
Cursor& operator =(const Cursor&);
/** The inner database. */
PlantDB* db_;
/** The stack buffer for the key. */
char stack_[KCPDRECBUFSIZ];
/** The pointer to the key region. */
char* kbuf_;
/** The size of the key region. */
size_t ksiz_;
/** The last visited leaf. */
int64_t lid_;
/** The backward flag. */
bool back_;
};
/**
* Tuning options.
*/
enum Option {
TSMALL = BASEDB::TSMALL, ///< use 32-bit addressing
TLINEAR = BASEDB::TLINEAR, ///< use linear collision chaining
TCOMPRESS = BASEDB::TCOMPRESS ///< compress each record
};
/**
* Status flags.
*/
enum Flag {
FOPEN = BASEDB::FOPEN, ///< whether opened
FFATAL = BASEDB::FFATAL ///< whether with fatal error