Repository navigation
Expand file tree
/
Copy pathdtree.cpp
More file actions
3192 lines (2865 loc) · 113 KB
/
Copy pathdtree.cpp
File metadata and controls
3192 lines (2865 loc) · 113 KB
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
/*
Yesquel Storage Engine v0.1
Copyright (c) Microsoft Corporation
All rights reserved.
MIT License
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation files
(the ""Software""), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
// dtree.cpp
#define _DTREE_C
// hack to compile things
#if (INDEX_STRUCTURE == IS_DTREE)
#include "gaia/gaiarpcaux.h"
#include "dtreeaux.h"
#include "gaia/clientlib/supervalue.h"
#include "gaia/util.h"
//#include "dtreeaux.cpp"
#include "splitter-server/dtreesplit.cpp"
#include "splitter-server/splitter-client.h"
// Header stored before the data in a data KV pair.
// This header is not used for Dtree nodes.
struct DataHeader {
int dummy;
};
/* forward definitions */
static int DtCreateTable(KVTransaction *tx, u16 dbid, Pgno *piTable, int createTabFlags, int maxcells);
int DtReadData(BtCursor *pCur);
int DtWriteData(BtCursor *pCur, u64 nkey, char *pdata, int ndata);
static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept);
static Pgno btreePagecount(BtShared *pBt);
static int GetMaxCellsForTable(void);
#ifdef SQLITE_DEBUG
static int cursorHoldsMutex(BtCursor *p);
#endif
// replace node in level with real node given its oid, and sets its index to 0
static int ReadReal(BtCursor *pCur, int level, COid newcoid){
int res;
res = auxReadReal(pCur->pBtree->tx, newcoid, pCur->node[level]);
if (res==0){
pCur->nodetype[level] = 1; // real node
pCur->nodeIndex[level]=0; // we start with leftmost pointer
}
return res;
}
/* read the root node of a database */
int ReadDbRoot(KVTransaction *tx, u16 dbid, int *len, char **buf){
COid coid;
int res;
Ptr<Valbuf> vbuf;
coid.cid = 0|BSKIPLIST_CID_BIT|((u64) dbid << 48); /* assumes cid=1|BSKIPLIST_CID_BIT, oid=0 holds database root info */
coid.oid = 0;
res=KVget(tx, coid, vbuf); if (res){ *len = 0; return res; }
assert(vbuf->type==0);
*buf = (char *) malloc(vbuf->len);
memcpy(*buf, vbuf->u.buf, vbuf->len);
*len = vbuf->len;
return res;
}
/* write the root node of a database */
int WriteDbRoot(KVTransaction *tx, u16 dbid, DbRootInfo *dri){
COid coid;
int res;
coid.cid = 0|BSKIPLIST_CID_BIT; /* assumes cid=1|BSKIPLIST_CID_BIT, oid=0 holds database root info */
coid.cid |= (u64) dbid<<48;
coid.oid = 0;
res=KVput(tx, coid, (char*) dri, sizeof(DbRootInfo));
return res;
}
struct UsedDBItem {
u16 id;
bool used;
UsedDBItem *prev, *next, *sprev, *snext;
u16 GetKey(){ return id; }
static unsigned HashKey(u16 id){ return id; }
static int CompareKey(u16 id1, u16 id2){
if (id1 < id2) return -1;
else if (id1 > id2) return +1;
else return 0;
}
};
/* create the database */
int skiplistCreateDatabase(u16 dbid){
KVTransaction *tx;
DbRootInfo dri;
Pgno table1;
int rc, res;
DTREELOG("database %x", dbid);
tx=0;
rc = 0;
bool remote = (dbid & EPHEMDB_CID_BIT) ? false : true;
beginTx(&tx, remote);
/* write the database root node */
memset((void*) &dri, 0, sizeof(DbRootInfo));
dri.readVersion = 1;
dri.writeVersion = 1;
res = WriteDbRoot(tx, dbid, &dri);
if (res){
rc = res; goto end;
}
/* create table 1 */
table1 = 1;
res = DtCreateTable(tx, dbid, &table1, BTREE_INTKEY, BSKIP_TABLE1_MAX_CELLS_PER_NODE);
if (res){
rc = res; goto end;
}
res = commitTx(tx);
if (res){
rc = res; goto end;
}
end:
freeTx(tx);
return rc;
}
#define USEDDBITEM_HASH_SIZE 256
GLOBALRWVAR RWLock UsedDBIds_l;
GLOBALRWVAR HashTable<u16,UsedDBItem> *UsedDBIds=0;
void YesqlInitGlobals(){
UsedDBIds = new HashTable<u16,UsedDBItem>(USEDDBITEM_HASH_SIZE); /* Database identifiers in use */
}
/*
** Open a database file.
**
** zFilename is the name of the database file. If zFilename is NULL
** then an ephemeral database is created. The ephemeral database might
** be exclusively in memory, or it might use a disk-based memory cache.
** Either way, the ephemeral database will be automatically deleted
** when sqlite3BtreeClose() is called.
**
** If zFilename is ":memory:" then an in-memory database is created
** that is automatically destroyed when it is closed.
**
** The "flags" parameter is a bitmask that might contain bits
** BTREE_OMIT_JOURNAL and/or BTREE_NO_READLOCK. The BTREE_NO_READLOCK
** bit is also set if the SQLITE_NoReadlock flags is set in db->flags.
** These flags are passed through into sqlite3PagerOpen() and must
** be the same values as PAGER_OMIT_JOURNAL and PAGER_NO_READLOCK.
**
** If the database is already opened in the same database connection
** and we are in shared cache mode, then the open will fail with an
** SQLITE_CONSTRAINT error. We cannot allow two or more BtShared
** objects in the same database connection since doing so will lead
** to problems with locking.
*/
SQLITE_PRIVATE int sqlite3BtreeOpen(
const char *zFilename, /* Name of the file containing the BTree database */
sqlite3 *db, /* Associated database handle */
Btree **ppBtree, /* Pointer to new Btree object written here */
int flags, /* Options */
int vfsFlags /* Flags passed through to sqlite3_vfs.xOpen() */
){
sqlite3_vfs *pVfs; /* The VFS to use for this btree */
BtShared *pBt = 0; /* Shared part of btree structure */
Btree *p; /* Handle to return */
sqlite3_mutex *mutexOpen = 0; /* Prevents a race condition. Ticket #3537 */
int rc = SQLITE_OK; /* Result code from this function */
u8 nReserve; /* Byte of unused space on each page */
u16 newdbid; /* identity of database */
int createdb; /* whether to create database or not */
int transientdb; // whether database is transient or not
int res;
UsedDBItem *useddbitem; // item for used DB ids
/* True if opening an ephemeral, temporary database */
const int isTempDb = zFilename==0 || zFilename[0]==0;
/* Set the variable isMemdb to true for an in-memory database, or
** false for a file-based database.
*/
#ifdef SQLITE_OMIT_MEMORYDB
int isMemdb = 0;
#else
int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
|| (isTempDb && sqlite3TempInMemory(db));
#endif
DTREELOG("zFilename %s flags %x vfsFlags %x", zFilename, flags, vfsFlags);
assert(db!=0);
assert(sqlite3_mutex_held(db->mutex));
assert((flags&0xff)==flags); /* flags fit in 8 bits */
assert((flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0); /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
assert((flags & BTREE_SINGLE)==0 || isTempDb); /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
transientdb = (vfsFlags & SQLITE_OPEN_TRANSIENT_DB) ? 1 : 0;
/* set flags */
if (db->flags & SQLITE_NoReadlock) flags |= BTREE_NO_READLOCK;
if (isTempDb) isMemdb=1; /* always stores temporary dbs in memory */
if (isMemdb) flags |= BTREE_MEMORY;
if ((vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb)){
vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
}
pVfs = db->pVfs;
p = (Btree*) sqlite3MallocZero(sizeof(Btree));
if (!p){
DTREELOG(" return %d", SQLITE_NOMEM); return SQLITE_NOMEM;
}
p->inTrans = TRANS_NONE;
p->db = db;
#ifndef SQLITE_OMIT_SHARED_CACHE
p->lock.pBtree = p;
p->lock.iTable = 1;
#endif
/*
** The following asserts make sure that structures used by the btree are
** the right size. This is to guard against size changes that result
** when compiling on a different architecture.
*/
assert(sizeof(i64)==8 || sizeof(i64)==4);
assert(sizeof(u64)==8 || sizeof(u64)==4);
assert(sizeof(u32)==4);
assert(sizeof(u16)==2);
assert(sizeof(Pgno)==8);
pBt = (BtShared*) sqlite3MallocZero(sizeof(*pBt));
if (pBt==0){
rc = SQLITE_NOMEM;
goto btree_open_out;
}
pBt->openFlags = (u8)flags;
pBt->db = db;
p->pBt = pBt;
pBt->pCursor = 0;
pBt->pPage1 = 0;
#ifdef SQLITE_SECURE_DELETE
pBt->secureDelete = 1;
#endif
pBt->pageSize = 512;
nReserve = 0;
pBt->pageSizeFixed = 1;
pBt->usableSize = pBt->pageSize - nReserve;
assert((pBt->pageSize & 7)==0); /* 8-byte alignment of pageSize */
*ppBtree = p;
if (flags & BTREE_MEMORY){
GLOBALRWVAR static u16 lastusedid=0;
int looped=0;
assert(UsedDBIds); // ensure it has been initialized
UsedDBIds_l.lock();
do {
++lastusedid;
if (lastusedid == 0x7fff){
if (looped) assert(1); /* no more ids available */
lastusedid=1;
looped=1;
}
} while(UsedDBIds->lookup(lastusedid) != 0);
newdbid = lastusedid;
if (transientdb || isMemdb) newdbid |= EPHEMDB_CID_BIT;
else newdbid &= ~EPHEMDB_CID_BIT;
useddbitem = new UsedDBItem;
useddbitem->id = newdbid;
useddbitem->used = true;
assert(UsedDBIds);
UsedDBIds->insert(useddbitem);
UsedDBIds_l.unlock();
createdb = 1; /* create the database */
} else {
KVTransaction *t;
COid coid;
char *tmpbuf;
int len;
assert(zFilename && *zFilename);
newdbid = (u16) strHash(zFilename, (int)strlen(zFilename));
if (transientdb) newdbid |= EPHEMDB_CID_BIT;
else newdbid &= ~EPHEMDB_CID_BIT;
assert(UsedDBIds);
UsedDBIds_l.lock();
useddbitem = new UsedDBItem;
useddbitem->id = newdbid;
useddbitem->used = true;
UsedDBIds->insert(useddbitem);
UsedDBIds_l.unlock();
coid.cid = (u64) newdbid << 48;
/* check to see if it exists */
bool remote = (newdbid & EPHEMDB_CID_BIT) ? false : true;
beginTx(&t, remote);
tmpbuf = 0;
res = ReadDbRoot(t, newdbid, &len, &tmpbuf);
if (tmpbuf) free(tmpbuf);
//abortTx(t);
freeTx(t);
if (res){
rc = SQLITE_IOERR; goto btree_open_out;
}
createdb = (len == 0); /* if len==0 then create db */
}
if (createdb){
res = skiplistCreateDatabase(newdbid); /* create the database */
if (res){
rc = SQLITE_IOERR; goto btree_open_out;
}
}
if (pBt->nPage==0) pBt->nPage++;
pBt->KVdbid = newdbid;
/* here, create the cache structures in the future */
btree_open_out:
if (rc!=SQLITE_OK){
if (pBt && pBt->pPager){
sqlite3PagerClose(pBt->pPager);
}
sqlite3_free(pBt);
sqlite3_free(p);
*ppBtree = 0;
}else{
/* If the B-Tree was successfully opened, set the pager-cache size to the
** default value. Except, when opening on an existing shared pager-cache,
** do not change the pager-cache size.
*/
if (sqlite3BtreeSchema(p, 0, 0)==0){
// JBL: No pager means no pager cahce
// sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);
}
}
if (mutexOpen){
assert(sqlite3_mutex_held(mutexOpen));
sqlite3_mutex_leave(mutexOpen);
}
DTREELOG(" return %d", rc);
return rc;
}
/*
* This function does the actual work of creating a table (sqlite3BtreeCreateTable calls it).
* Its interface is similar to the of sqlite3BtreeCreateTable, except that if *piTable!=0
* then it uses that value for the table's root page. It also takes a KVTransaction as a
* parameter instead of a Btree.
* maxcells is the maximum number of cells per bskiplist node.
*/
static int DtCreateTable(KVTransaction *tx, u16 dbid, Pgno *piTable, int createTabFlags, int maxcells){
COid coid, coidfirst;
int res;
SuperValue rootNode, firstNode;
assert((*piTable & 0xffff800000000000LL) == 0); /* top bits must be clear */
/* *!* TODO: fix this to pick a unique *piTable instead of a random one
which may already exist */
if (!*piTable){
sqlite3_randomness(sizeof(*piTable), piTable);
*piTable >>= 18; /* clear top 17 bits and last bit */
*piTable <<= 1;
if (createTabFlags == BTREE_TRANSIENT) *piTable |= 1;
assert(*piTable > 0);
}
coid.cid = *piTable | BSKIPLIST_CID_BIT; /* set bit for b-skiplist container id */
coid.cid |= (u64) dbid << 48; /* set database id bit */
coid.oid = 0;
#ifndef DTREE_NOFIRSTNODE
coidfirst.cid = coid.cid;
sqlite3_randomness(sizeof(Oid), &coidfirst.oid);
DTreeNode::InitSuperValue(&firstNode, (createTabFlags == BTREE_INTKEY) ? 0 : 1);
firstNode.Attrs[DTREENODE_ATTRIB_FLAGS] = DTREENODE_FLAG_LEAF | ((createTabFlags == BTREE_INTKEY) ? DTREENODE_FLAG_INTKEY : 0);
firstNode.Attrs[DTREENODE_ATTRIB_HEIGHT] = 0;
firstNode.Attrs[DTREENODE_ATTRIB_LASTPTR] = 0;
firstNode.Attrs[DTREENODE_ATTRIB_LEFTPTR] = 0;
firstNode.Attrs[DTREENODE_ATTRIB_RIGHTPTR] = 0;
res = KVwriteSuperValue(tx, coidfirst, &firstNode);
if (res) return SQLITE_IOERR;
#endif
DTreeNode::InitSuperValue(&rootNode, (createTabFlags == BTREE_INTKEY) ? 0 : 1);
#ifndef DTREE_NOFIRSTNODE
rootNode.Attrs[DTREENODE_ATTRIB_FLAGS] = ((createTabFlags == BTREE_INTKEY) ? DTREENODE_FLAG_INTKEY : 0);
rootNode.Attrs[DTREENODE_ATTRIB_HEIGHT] = 1;
rootNode.Attrs[DTREENODE_ATTRIB_LASTPTR] = coidfirst.oid;
#else
rootNode.Attrs[DTREENODE_ATTRIB_FLAGS] = DTREENODE_FLAG_LEAF | ((createTabFlags == BTREE_INTKEY) ? DTREENODE_FLAG_INTKEY : 0);
rootNode.Attrs[DTREENODE_ATTRIB_HEIGHT] = 0;
rootNode.Attrs[DTREENODE_ATTRIB_LASTPTR] = 0;
#endif
rootNode.Attrs[DTREENODE_ATTRIB_LEFTPTR] = 0;
rootNode.Attrs[DTREENODE_ATTRIB_RIGHTPTR] = 0;
LOG("putting first table at container %llx", coid.cid);
res = KVwriteSuperValue(tx, coid, &rootNode);
if (res) return SQLITE_IOERR;
return SQLITE_OK;
}
/*
** Create a new BTree table. Write into *piTable the page
** number for the root page of the new table.
**
** The type of type is determined by the flags parameter. Only the
** following values of flags are currently in use. Other values for
** flags might not work:
**
** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
** BTREE_ZERODATA Used for SQL indices
*/
// This function is like sqlite3BtreeCreateTable, except that it lets the
// caller choose the table number (page) by setting *piTable to a number other than zero.
int sqlite3BtreeCreateTableChooseTable(Btree *p, Pgno *piTable, int flags){
int rc, res;
BtShared *pBt = p->pBt;
KVTransaction *tx;
int maxcells;
bool createtx;
DTREELOG("btree %p flags %d", p, flags);
assert(!pBt->readOnly);
assert(pBt->inTransaction==TRANS_WRITE);
createtx = p->tx == 0; // create a transaction just for this, if p->tx is invalid
if (createtx){
bool remote = (pBt->KVdbid & EPHEMDB_CID_BIT) ? false : true;
beginTx(&tx, remote);
}
else tx = p->tx; // use transaction if it already exists
sqlite3BtreeEnter(p);
//*piTable=0;
maxcells = GetMaxCellsForTable();
rc = DtCreateTable(tx, pBt->KVdbid, piTable, flags, maxcells);
sqlite3BtreeLeave(p);
if (createtx){
res = commitTx(tx);
if (res){ DTREELOG(" return %d", SQLITE_IOERR); return SQLITE_IOERR; }
freeTx(tx);
}
DTREELOG(" return %d", rc);
return rc;
}
SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, Pgno *piTable, int flags){
*piTable = 0;
return sqlite3BtreeCreateTableChooseTable(p, piTable, flags);
}
static int dtreeRestoreCursorPosition(BtCursor *pCur);
/*
* Restore cursor position. If cursor's eState is CURSOR_VALID or CURSOR_INVALID,
* then do nothing and return SQLITE_OK. Otherwise, call btreeRestoreCursorPosition
*/
#define restoreCursorPosition(p) \
(p->eState>=CURSOR_REQUIRESEEK ? \
dtreeRestoreCursorPosition(p) : \
SQLITE_OK)
/*
** Create a new cursor for the BTree whose root is on the page
** iTable. If a read-only cursor is requested, it is assumed that
** the caller already has at least a read-only transaction open
** on the database already. If a write-cursor is requested, then
** the caller is assumed to have an open write transaction.
**
** If wrFlag==0, then the cursor can only be used for reading.
** If wrFlag==1, then the cursor can be used for reading or for
** writing if other conditions for writing are also met. These
** are the conditions that must be met in order for writing to
** be allowed:
**
** 1: The cursor must have been opened with wrFlag==1
**
** 2: Other database connections that share the same pager cache
** but which are not in the READ_UNCOMMITTED state may not have
** cursors open with wrFlag==0 on the same table. Otherwise
** the changes made by this write cursor would be visible to
** the read cursors in the other database connection.
**
** 3: The database must be writable (not on read-only media)
**
** 4: There must be an active transaction.
**
** No checking is done to make sure that page iTable really is the
** root page of a b-tree. If it is not, then the cursor acquired
** will not work correctly.
**
** It is assumed that the sqlite3BtreeCursorZero() has been called
** on pCur to initialize the memory space prior to invoking this routine.
*/
static int btreeCursor(
Btree *p, /* The btree */
Pgno iTable, /* Root page of table to open */
int wrFlag, /* 1 to write. 0 read-only */
struct KeyInfo *pKeyInfo, /* First arg to comparison function */
BtCursor *pCur /* Space for new cursor */
){
BtShared *pBt = p->pBt; /* Shared b-tree handle */
assert(sqlite3BtreeHoldsMutex(p));
assert(wrFlag==0 || wrFlag==1);
assert((iTable & 0xffff800000000000LL) == 0); /* top bits must be clear */
/* The following assert statements verify that if this is a sharable
** b-tree database, the connection is holding the required table locks,
** and that no other connection has any open cursor that conflicts with
** this lock. */
/*assert(hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, wrFlag+1));
assert(wrFlag==0 || !hasReadConflicts(p, iTable)); */
/* Assert that the caller has opened the required transaction. */
assert(p->inTrans>TRANS_NONE);
assert(wrFlag==0 || p->inTrans==TRANS_WRITE);
/*assert(pBt->pPage1 && pBt->pPage1->aData);*/
if (NEVER(wrFlag && pBt->readOnly)){
return SQLITE_READONLY;
}
if (iTable==1 && btreePagecount(pBt)==0){
return SQLITE_EMPTY;
}
/* Now that no other errors can occur, finish filling in the BtCursor
** variables and link the cursor into the BtShared list. */
pCur->rootCid = iTable | BSKIPLIST_CID_BIT | ((u64)pBt->KVdbid<<48);
pCur->pKeyInfo = pKeyInfo;
pCur->pBtree = p;
pCur->pBt = pBt;
pCur->wrFlag = (u8)wrFlag;
pCur->pNext = pBt->pCursor;
new(&pCur->data) Ptr<Valbuf>; // if this doesn't compile, try memset(&pCur->data, 0, sizeof(Ptr<Valbuf>));
pCur->intKey = pKeyInfo ? 0 : 1;
memset(pCur->node, 0, sizeof(Ptr<DTreeNode>) * DTREE_MAX_LEVELS);
//#ifndef NDEBUG
memset(pCur->nodetype, 0xff, DTREE_MAX_LEVELS);
memset(pCur->nodeIndex, 0xff, sizeof(u32) * DTREE_MAX_LEVELS);
//#endif
/* TO FILL: anything extra to initialize? */
if (pCur->pNext){
pCur->pNext->pPrev = pCur;
}
pBt->pCursor = pCur;
pCur->eState = CURSOR_INVALID;
pCur->cachedRowid = 0;
return SQLITE_OK;
}
SQLITE_PRIVATE int sqlite3BtreeCursor(
Btree *p, /* The btree */
Pgno iTable, /* Root page of table to open */
int wrFlag, /* 1 to write. 0 read-only */
struct KeyInfo *pKeyInfo, /* First arg to xCompare() */
BtCursor *pCur /* Write new cursor here */
){
int rc;
DTREELOG("btree %p iTable %I64x wrFlag %d", p, iTable, wrFlag);
sqlite3BtreeEnter(p);
rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
sqlite3BtreeLeave(p);
DTREELOG(" return %d", rc);
return rc;
}
/* compares a cell key against intKey2/pIdxKey2. Use intKey2 if pIdxKey2==0 otherwise use pIdxKey2 */
/* inline */
int compareCellWithKey(u8 *cellData1, i64 intKey2, UnpackedRecord *pIdxKey2) {
i64 nKey1;
cellData1 += getVarint(cellData1, (u64*) &nKey1);
assert(nKey1 == (int) nKey1);
if (pIdxKey2) return sqlite3VdbeRecordCompare((int) nKey1, cellData1, pIdxKey2);
else if (nKey1==intKey2) return 0;
else return (nKey1 < intKey2) ? -1 : +1;
}
/* compares a cell key against intKey2/pIdxKey2. Use intKey2 if pIdxKey2==0 otherwise use pIdxKey2 */
/* inline */
int compareNpKeyWithKey(i64 nKey1, char *pKey1, i64 nKey2, UnpackedRecord *pIdxKey2) {
if (pIdxKey2) return sqlite3VdbeRecordCompare((int)nKey1, pKey1, pIdxKey2);
else if (nKey1==nKey2) return 0;
else return (nKey1 < nKey2) ? -1 : +1;
}
// Searches the cells of a node for a given key, using binary search.
// Returns the child pointer that needs to be followed for that key.
// If biasRight!=0 then optimize for the case the key is larger than any entries in node.
// Assumes that the path at the given level has some node (real or approx).
// Guaranteed to return an index between 0 and N where N is the number of cells
// in that node (N+1 is the number of pointers).
// Returns *matches!=0 if found key, *matches==0 if did not find key.
static int CellSearchNodeUnpacked(DTreeNode &node, UnpackedRecord *pIdxKey, i64 nkey, int biasRight, int *matches=0){
int cmp;
int bottom, top, mid;
ListCell *cell;
bottom=0;
top=node.Ncells()-1; /* number of keys on node minus 1 */
if (top<0){ if (matches) *matches=0; return 0; } // there are no keys in node, so return index of only pointer there (index 0)
do {
if (biasRight){ mid = top; biasRight=0; } /* bias first search only */
else mid=(bottom+top)/2;
cell = &node.Cells()[mid];
cmp = compareNpKeyWithKey(cell->nKey, cell->pKey, nkey, pIdxKey);
if (cmp==0) break; /* found key */
if (cmp < 0) bottom=mid+1; /* mid < target */
else top=mid-1; /* mid > target */
} while (bottom <= top);
// if key was found, then mid points to its index and cmp==0
// if key was not found, then mid points to entry immediately before key (cmp<0) or after key (cmp>0)
if (cmp<0) ++mid; // now mid points to entry immediately after key or to one past the last entry
// if key is greater than all entries
// note: if key matches a cell (cmp==0), we follow the pointer to the left of the cell, which
// has the same index as the cell
if (matches) *matches = cmp == 0 ? 1 : 0;
assert(0 <= mid && mid <= node.Ncells());
return mid;
}
static int CellSearchNode(DTreeNode &node, i64 nkey, void *pkey, KeyInfo *ki, int biasRight){
UnpackedRecord *pIdxKey; /* Unpacked index key */
char aSpace[150]; /* Temp space for pIdxKey - to avoid a malloc */
int res;
if (pkey){
pIdxKey = sqlite3VdbeRecordUnpack(ki, (int)nkey, pkey, aSpace, sizeof(aSpace));
if (pIdxKey == 0) return SQLITE_NOMEM;
} else pIdxKey = 0;
res = CellSearchNodeUnpacked(node, pIdxKey, nkey, biasRight);
if (pkey) sqlite3VdbeDeleteUnpackedRecord(pIdxKey);
return res;
}
// Adjusts the index at given level so that it points to level+1.
// Assumes that level+1 exists.
// Returns 0 if index was adjusted, -1 if there were no pointers at given level to level+1.
static int AdjustIndex(BtCursor *pCur, int level){
int i, n;
Oid childoid;
DTreeNode *dtn = &pCur->node[level]; // for convenience
childoid = pCur->node[level+1].NodeOid(); // where level needs to point to
n = dtn->Ncells()+1; // number of pointers
for (i=0; i < n; ++i){
if (dtn->GetPtr(i) == childoid){ // found it
pCur->nodeIndex[level] = i; // adjust index
break;
}
}
if (i==n) return -1; // did not find it
else return 0;
}
// Find the real node that should be in the path at given level.
// Assumes
// (1) given level is higher than leaf,
// (2) current path is real at levels higher than given level, and
// (3) pCur->leafLevel is set correctly
// Returns 0 if ok, non-0 if an error occurred
int DtFindRealLevelPath(BtCursor *pCur, int level){
Oid child;
int res;
int i, n, index;
DTreeNode *dtn;
Oid childoid, oid;
COid coidtmp;
assert(level < pCur->levelLeaf);
coidtmp.cid = pCur->rootCid;
// if node at level is real
if (pCur->nodetype[level] == 1){
assert(pCur->nodeIndex[level] <= pCur->node[level].Ncells());
child = pCur->node[level].GetPtr(pCur->nodeIndex[level]);
if (child != pCur->node[level+1].NodeOid()){ // if index[level] is not correct then adjust it
res = AdjustIndex(pCur, level); assert(res==0);
}
return 0; // done
}
// read real node at level
coidtmp.oid = pCur->node[level].NodeOid(),
res = ReadReal(pCur, level, coidtmp); if (res) return res;
dtn = &pCur->node[level]; // for convenience and speed
n = dtn->Ncells()+1; // number of child pointers
childoid = pCur->node[level+1].NodeOid();
// if some child pointer matches childoid (the node at level+1)...
for (i=0; i < n; ++i){
if (dtn->GetPtr(i) == childoid){
// adjust index to be index of such child
pCur->nodeIndex[level] = i;
return 0;
}
}
// real node at level does not point to level+1, so scan from root
// search for first key at level+1 from root until given level, setting nodes[] to be real at each level
oid = DTREE_ROOT_OID;
// extract first key from leaf level
ListCell *cell=&pCur->node[pCur->levelLeaf].Cells()[0]; // for convenience and speed below
for (i=0; i <= level; ++i){
coidtmp.oid = oid;
res = ReadReal(pCur, i, coidtmp); if (res) return res;
// find index for key by doing a binary search
index = CellSearchNode(pCur->node[i], cell->nKey, cell->pKey, pCur->pKeyInfo, false);
assert(0 <= index && index <= pCur->node[i].Ncells());
pCur->nodeIndex[i] = index;
// follow child pointer to get oid of next level
oid = pCur->node[i].GetPtr(pCur->nodeIndex[i]);
}
// assert that child of node[level] points to level+1
assert(oid == pCur->node[level+1].NodeOid());
return 0;
}
// Moves pCur to the next Dtnode in the sequence.
// Assumes pCur has a path set until leaf, where leaf is real, others may not be.
// Assumes pCur->levelLeaf is correct.
// Returns 0 if ok, non-0 if error.
// Also sets nomore as follows: 1 if there are no more nodes and 0 otherwise
// Note that if there are no more nodes, the return value is 0 (ok).
int DtAdvancePath(BtCursor *pCur, int &nomore){
int level, levelleaf, res;
COid newcoid;
newcoid.cid = pCur->rootCid;
// if leaf in path is rightmost then return error
levelleaf = pCur->levelLeaf;
level = levelleaf;
if (pCur->node[level].RightPtr() == 0){ nomore=1; return 0; }
--level;
while (1){
DtFindRealLevelPath(pCur, level);
if (pCur->nodeIndex[level] < pCur->node[level].Ncells()){ // index of level not at the end
++pCur->nodeIndex[level]; // increment index
break;
}
assert(!pCur->node[level].isRoot());
--level; // need to advance next level
assert(level >= 0);
}
while (level < levelleaf){
++level;
// use node and index at level+1 to read real node at level
newcoid.oid = pCur->node[level-1].GetPtr(pCur->nodeIndex[level-1]);
res = ReadReal(pCur, level, newcoid); if (res) return res;
pCur->nodeIndex[level]=0; // we start with leftmost pointer
}
nomore=0;
return 0;
}
/*
** Reads the data of a b-skiplist node at the cursor.
** Requires the cursor to be valid and of type intKey
*/
int DtReadData(BtCursor *pCur){
COid coid;
int res;
assert(pCur->eState == CURSOR_VALID || pCur->eState == CURSOR_DIRECT);
assert(pCur->intKey);
coid.cid = DATA_CID(pCur->rootCid);
if (pCur->eState == CURSOR_DIRECT) coid.oid = pCur->directIntKey;
else { // pCur->eState == CURSOR_VALID
int levelleaf = pCur->levelLeaf;
int index = pCur->nodeIndex[levelleaf];
coid.oid = pCur->node[levelleaf].Cells()[index].nKey;
}
pCur->data=0;
res = KVget(pCur->pBtree->tx, coid, pCur->data);
return res;
}
/*
** Writes the data of a b-skiplist node at the cursor.
** Requires the cursor to be valid, of type intKey, and pCur->data != NULL.
*/
int DtWriteData(BtCursor *pCur, u64 nkey, char *pdata, int ndata){
COid coid;
int res;
DataHeader dh;
strcpy((char*) &dh.dummy, "DAT");
coid.cid = DATA_CID(pCur->rootCid);
coid.oid = nkey;
res = KVput2(pCur->pBtree->tx, coid, (char*) &dh, sizeof(DataHeader), pdata, (int)ndata);
return res;
}
// bypass Dtree and try to retrieve data directly from KV store
int DtMovetoDirect(BtCursor *pCur, UnpackedRecord *pIdxKey, i64 intKey, int *pRes){
int res;
assert(pIdxKey==0);
// create a cell for key being sought
pCur->directIntKey = intKey;
pCur->eState = CURSOR_DIRECT;
res = DtReadData(pCur);
if (res || !pCur->data.isset() || pCur->data->len < sizeof(DataHeader)){ // did not find it
pCur->data = 0;
pCur->eState = CURSOR_INVALID;
*pRes=-1;
}
else *pRes=0; // found it
return res;
}
// Traverse the Dtree to find for a given key.
// First, traverse the local cache and see if it leads to the key.
// Otherwise, start fetching nodes from TKVS as necessary to find the key.
// Returns 0 if ok, non-0 if error (with the sqlite status codes).
// Sets *pRes as follows:
// *pRes<0 No entry matches key, and the cursor is left at entry
// immediately before the key OR the table is empty
// and the cursor is left pointing to nothing.
// *pRes==0 An entry matches key, and the cursor is left pointing to it.
// *pRes>0 No entry matches key, and the cursor is left at entry
// immediately after the key.
// Sets pCur->levelLeaf
int DtMovetoUnpackedaux(BtCursor *pCur, UnpackedRecord *pIdxKey, i64 nKey, int biasRight, int *pRes, bool tryDirect){
// highest level at which key belongs inside the node. This is the negation of the situation
// where the key is smaller than the smallest key in node, or larger than the largest key.
// This is relevant for the following reason:
// - if level is at the leaf (so the node is real not approximate) and key belongs in the node,
// then the leaf node is authoritative for telling if key exists or not. On the other hand
// if key does not belong to the node, the key may be somewhere else, since we traversed
// the tree using approximate pointers
int highestNonExtremeLevel = -1;
int level, real, res, index, matches;
COid coid, coid2, prevcoid;
DTREELOG("BtCursor %p pIdxKey %p nKey %I64d biasRight %d", pCur, pIdxKey, nKey, biasRight);
assert(cursorHoldsMutex(pCur));
assert(sqlite3_mutex_held(pCur->pBtree->db->mutex));
assert(pRes);
assert((pIdxKey==0)==(pCur->pKeyInfo==0));
pCur->data=0;
prevcoid.cid = coid2.cid = coid.cid = pCur->rootCid;
if (tryDirect && pCur->eState==CURSOR_DIRECT && pCur->intKey){
if (pIdxKey==0 && pCur->directIntKey == nKey){ *pRes=0; DTREELOG(" return %d", 0); return 0; } // cursor key matches direct key
}
if (pCur->eState==CURSOR_VALID && pCur->intKey){
int levelleaf = pCur->levelLeaf;
assert(pCur->node[levelleaf].isLeaf());
if (pCur->node[levelleaf].Cells()[pCur->nodeIndex[levelleaf]].nKey == nKey){
/* cursor key already matches */
*pRes = 0;
DTREELOG(" return %d", 0);
return 0;
}
if (pCur->node[levelleaf].RightPtr() == 0 && // last node in tree
pCur->nodeIndex[levelleaf] == pCur->node[levelleaf].Ncells()-1 && // at last cell
pCur->node[levelleaf].Cells()[pCur->nodeIndex[levelleaf]].nKey < nKey){ /* cursor key is last and smaller than requested key */
*pRes = -1; /* we are before the key */
DTREELOG(" return %d", 0);
return 0;
}
}
if (tryDirect && pCur->intKey){
res = DtMovetoDirect(pCur, pIdxKey, nKey, pRes);
if (res){ DTREELOG(" return %d", SQLITE_IOERR); return SQLITE_IOERR; }
if (*pRes==0){ DTREELOG(" return %d", 0); return 0; }
}
// using cached data, traverse from root to leaf, updating current path
// during traversal, if we did not follow the extreme pointers at a level, set highestNonExtremeTraversal
// to that level. In the end, the variable ends up with the highest such level
level = 0;
coid.oid = DTREE_ROOT_OID; // start with root
do {
res = auxReadCacheOrReal(pCur->pBtree->tx, coid, pCur->node[level], real);
if (res == GAIAERR_WRONG_TYPE){ // not a supervalue
//printf("Found unexpected non-supervalue\n");
if (level == 0){ pCur->eState = CURSOR_INVALID; DTREELOG(" return %d", SQLITE_EMPTY); return SQLITE_EMPTY; } // root not supervalue, so tree is deleted
auxRemoveCache(prevcoid); // the node pointing to this non-supervalue node is bogus, remove it from cache
--level; // move up one level
goto skip_cache_traversal; // start upward real traversal
}
if (res){ pCur->eState = CURSOR_INVALID; DTREELOG(" return %d", SQLITE_IOERR); return SQLITE_IOERR; }
pCur->nodetype[level] = real ? 1 : 0;
index = CellSearchNodeUnpacked(pCur->node[level], pIdxKey, nKey, biasRight, &matches);
pCur->nodeIndex[level] = index;
if (matches || 0 < index && index < pCur->node[level].Ncells())
highestNonExtremeLevel = level; // key belongs inside the node
if (pCur->node[level].isLeaf()) break; // got to leaf
prevcoid.oid = coid.oid;
coid.oid = pCur->node[level].GetPtr(index);
++level;
} while (level < DTREE_MAX_LEVELS);
// here, level == leaf node level
if (level == DTREE_MAX_LEVELS){ // too much garbage in cache
level = 0;
goto skip_cache_traversal;
}
if (pCur->nodetype[level] == 1){ // if node is real
if (highestNonExtremeLevel == level && pCur->nodetype[level]==1){ // key belongs inside a real leaf node, so traversal was fruitful
if (matches) *pRes=0;
else *pRes=1; // because CellSearchNodeUnpacked returns an index right after the found key, not before
pCur->eState = CURSOR_VALID;
pCur->levelLeaf = level;
DTREELOG(" return %d", 0);
return 0;
}
// here index == pCur->nodeIndex[level]
// if leaf is rightmost leaf and key > largest key in node, then set pRes and return
if (pCur->node[level].RightPtr() == 0 && index == pCur->node[level].Ncells()){
if (index == 0){ // no cells in the leaf node
//assert(level==0); // must be the root node; table is empty
*pRes=-1;
pCur->eState = CURSOR_INVALID;
pCur->levelLeaf = level;
DTREELOG(" return %d", 0);
return 0;
}
--pCur->nodeIndex[level];
--index; // updating index to keep it identical to nodeIndex[level]
assert(index >= 0);
*pRes=-1; // cursor before key now
pCur->eState = CURSOR_VALID;
pCur->levelLeaf = level;
DTREELOG(" return %d", 0);
return 0;
}
// if leaf is leftmost leaf and key < smallest key in node, then set pRes and return
if (pCur->node[level].LeftPtr() == 0 && index == 0){
*pRes=1; // cursor after key
pCur->eState = CURSOR_VALID;
pCur->levelLeaf = level;
DTREELOG(" return %d", 0);
return 0;
}
}
// do the upward traversal looking for a place where key belongs inside a real node
// level = highestNonExtremeLevel; // this is just an optimization
skip_cache_traversal:
assert(level >= 0);
while (1){
if (pCur->nodetype[level] == 0){ // approx node
// fetch real node at level from TKVS
coid2.oid = pCur->node[level].NodeOid();