remove files generated buy build automatically
[sqlcipher.git] / src / btree.c
blob3ca60583e3c8e31200f973e0e9c4536258b26439
1 /*
2 ** 2004 April 6
3 **
4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing:
6 **
7 ** May you do good and not evil.
8 ** May you find forgiveness for yourself and forgive others.
9 ** May you share freely, never taking more than you give.
11 *************************************************************************
12 ** This file implements a external (disk-based) database using BTrees.
13 ** See the header comment on "btreeInt.h" for additional information.
14 ** Including a description of file format and an overview of operation.
16 #include "btreeInt.h"
19 ** The header string that appears at the beginning of every
20 ** SQLite database.
22 static const char zMagicHeader[] = SQLITE_FILE_HEADER;
25 ** Set this global variable to 1 to enable tracing using the TRACE
26 ** macro.
28 #if 0
29 int sqlite3BtreeTrace=1; /* True to enable tracing */
30 # define TRACE(X) if(sqlite3BtreeTrace){printf X;fflush(stdout);}
31 #else
32 # define TRACE(X)
33 #endif
36 ** Extract a 2-byte big-endian integer from an array of unsigned bytes.
37 ** But if the value is zero, make it 65536.
39 ** This routine is used to extract the "offset to cell content area" value
40 ** from the header of a btree page. If the page size is 65536 and the page
41 ** is empty, the offset should be 65536, but the 2-byte value stores zero.
42 ** This routine makes the necessary adjustment to 65536.
44 #define get2byteNotZero(X) (((((int)get2byte(X))-1)&0xffff)+1)
47 ** Values passed as the 5th argument to allocateBtreePage()
49 #define BTALLOC_ANY 0 /* Allocate any page */
50 #define BTALLOC_EXACT 1 /* Allocate exact page if possible */
51 #define BTALLOC_LE 2 /* Allocate any page <= the parameter */
54 ** Macro IfNotOmitAV(x) returns (x) if SQLITE_OMIT_AUTOVACUUM is not
55 ** defined, or 0 if it is. For example:
57 ** bIncrVacuum = IfNotOmitAV(pBtShared->incrVacuum);
59 #ifndef SQLITE_OMIT_AUTOVACUUM
60 #define IfNotOmitAV(expr) (expr)
61 #else
62 #define IfNotOmitAV(expr) 0
63 #endif
65 #ifndef SQLITE_OMIT_SHARED_CACHE
67 ** A list of BtShared objects that are eligible for participation
68 ** in shared cache. This variable has file scope during normal builds,
69 ** but the test harness needs to access it so we make it global for
70 ** test builds.
72 ** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
74 #ifdef SQLITE_TEST
75 BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
76 #else
77 static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
78 #endif
79 #endif /* SQLITE_OMIT_SHARED_CACHE */
81 #ifndef SQLITE_OMIT_SHARED_CACHE
83 ** Enable or disable the shared pager and schema features.
85 ** This routine has no effect on existing database connections.
86 ** The shared cache setting effects only future calls to
87 ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
89 int sqlite3_enable_shared_cache(int enable){
90 sqlite3GlobalConfig.sharedCacheEnabled = enable;
91 return SQLITE_OK;
93 #endif
97 #ifdef SQLITE_OMIT_SHARED_CACHE
99 ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
100 ** and clearAllSharedCacheTableLocks()
101 ** manipulate entries in the BtShared.pLock linked list used to store
102 ** shared-cache table level locks. If the library is compiled with the
103 ** shared-cache feature disabled, then there is only ever one user
104 ** of each BtShared structure and so this locking is not necessary.
105 ** So define the lock related functions as no-ops.
107 #define querySharedCacheTableLock(a,b,c) SQLITE_OK
108 #define setSharedCacheTableLock(a,b,c) SQLITE_OK
109 #define clearAllSharedCacheTableLocks(a)
110 #define downgradeAllSharedCacheTableLocks(a)
111 #define hasSharedCacheTableLock(a,b,c,d) 1
112 #define hasReadConflicts(a, b) 0
113 #endif
115 #ifndef SQLITE_OMIT_SHARED_CACHE
117 #ifdef SQLITE_DEBUG
119 **** This function is only used as part of an assert() statement. ***
121 ** Check to see if pBtree holds the required locks to read or write to the
122 ** table with root page iRoot. Return 1 if it does and 0 if not.
124 ** For example, when writing to a table with root-page iRoot via
125 ** Btree connection pBtree:
127 ** assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
129 ** When writing to an index that resides in a sharable database, the
130 ** caller should have first obtained a lock specifying the root page of
131 ** the corresponding table. This makes things a bit more complicated,
132 ** as this module treats each table as a separate structure. To determine
133 ** the table corresponding to the index being written, this
134 ** function has to search through the database schema.
136 ** Instead of a lock on the table/index rooted at page iRoot, the caller may
137 ** hold a write-lock on the schema table (root page 1). This is also
138 ** acceptable.
140 static int hasSharedCacheTableLock(
141 Btree *pBtree, /* Handle that must hold lock */
142 Pgno iRoot, /* Root page of b-tree */
143 int isIndex, /* True if iRoot is the root of an index b-tree */
144 int eLockType /* Required lock type (READ_LOCK or WRITE_LOCK) */
146 Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
147 Pgno iTab = 0;
148 BtLock *pLock;
150 /* If this database is not shareable, or if the client is reading
151 ** and has the read-uncommitted flag set, then no lock is required.
152 ** Return true immediately.
154 if( (pBtree->sharable==0)
155 || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommitted))
157 return 1;
160 /* If the client is reading or writing an index and the schema is
161 ** not loaded, then it is too difficult to actually check to see if
162 ** the correct locks are held. So do not bother - just return true.
163 ** This case does not come up very often anyhow.
165 if( isIndex && (!pSchema || (pSchema->flags&DB_SchemaLoaded)==0) ){
166 return 1;
169 /* Figure out the root-page that the lock should be held on. For table
170 ** b-trees, this is just the root page of the b-tree being read or
171 ** written. For index b-trees, it is the root page of the associated
172 ** table. */
173 if( isIndex ){
174 HashElem *p;
175 for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
176 Index *pIdx = (Index *)sqliteHashData(p);
177 if( pIdx->tnum==(int)iRoot ){
178 iTab = pIdx->pTable->tnum;
181 }else{
182 iTab = iRoot;
185 /* Search for the required lock. Either a write-lock on root-page iTab, a
186 ** write-lock on the schema table, or (if the client is reading) a
187 ** read-lock on iTab will suffice. Return 1 if any of these are found. */
188 for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
189 if( pLock->pBtree==pBtree
190 && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
191 && pLock->eLock>=eLockType
193 return 1;
197 /* Failed to find the required lock. */
198 return 0;
200 #endif /* SQLITE_DEBUG */
202 #ifdef SQLITE_DEBUG
204 **** This function may be used as part of assert() statements only. ****
206 ** Return true if it would be illegal for pBtree to write into the
207 ** table or index rooted at iRoot because other shared connections are
208 ** simultaneously reading that same table or index.
210 ** It is illegal for pBtree to write if some other Btree object that
211 ** shares the same BtShared object is currently reading or writing
212 ** the iRoot table. Except, if the other Btree object has the
213 ** read-uncommitted flag set, then it is OK for the other object to
214 ** have a read cursor.
216 ** For example, before writing to any part of the table or index
217 ** rooted at page iRoot, one should call:
219 ** assert( !hasReadConflicts(pBtree, iRoot) );
221 static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
222 BtCursor *p;
223 for(p=pBtree->pBt->pCursor; p; p=p->pNext){
224 if( p->pgnoRoot==iRoot
225 && p->pBtree!=pBtree
226 && 0==(p->pBtree->db->flags & SQLITE_ReadUncommitted)
228 return 1;
231 return 0;
233 #endif /* #ifdef SQLITE_DEBUG */
236 ** Query to see if Btree handle p may obtain a lock of type eLock
237 ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
238 ** SQLITE_OK if the lock may be obtained (by calling
239 ** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
241 static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
242 BtShared *pBt = p->pBt;
243 BtLock *pIter;
245 assert( sqlite3BtreeHoldsMutex(p) );
246 assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
247 assert( p->db!=0 );
248 assert( !(p->db->flags&SQLITE_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 );
250 /* If requesting a write-lock, then the Btree must have an open write
251 ** transaction on this file. And, obviously, for this to be so there
252 ** must be an open write transaction on the file itself.
254 assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
255 assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
257 /* This routine is a no-op if the shared-cache is not enabled */
258 if( !p->sharable ){
259 return SQLITE_OK;
262 /* If some other connection is holding an exclusive lock, the
263 ** requested lock may not be obtained.
265 if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){
266 sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
267 return SQLITE_LOCKED_SHAREDCACHE;
270 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
271 /* The condition (pIter->eLock!=eLock) in the following if(...)
272 ** statement is a simplification of:
274 ** (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
276 ** since we know that if eLock==WRITE_LOCK, then no other connection
277 ** may hold a WRITE_LOCK on any table in this file (since there can
278 ** only be a single writer).
280 assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
281 assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
282 if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
283 sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
284 if( eLock==WRITE_LOCK ){
285 assert( p==pBt->pWriter );
286 pBt->btsFlags |= BTS_PENDING;
288 return SQLITE_LOCKED_SHAREDCACHE;
291 return SQLITE_OK;
293 #endif /* !SQLITE_OMIT_SHARED_CACHE */
295 #ifndef SQLITE_OMIT_SHARED_CACHE
297 ** Add a lock on the table with root-page iTable to the shared-btree used
298 ** by Btree handle p. Parameter eLock must be either READ_LOCK or
299 ** WRITE_LOCK.
301 ** This function assumes the following:
303 ** (a) The specified Btree object p is connected to a sharable
304 ** database (one with the BtShared.sharable flag set), and
306 ** (b) No other Btree objects hold a lock that conflicts
307 ** with the requested lock (i.e. querySharedCacheTableLock() has
308 ** already been called and returned SQLITE_OK).
310 ** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM
311 ** is returned if a malloc attempt fails.
313 static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
314 BtShared *pBt = p->pBt;
315 BtLock *pLock = 0;
316 BtLock *pIter;
318 assert( sqlite3BtreeHoldsMutex(p) );
319 assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
320 assert( p->db!=0 );
322 /* A connection with the read-uncommitted flag set will never try to
323 ** obtain a read-lock using this function. The only read-lock obtained
324 ** by a connection in read-uncommitted mode is on the sqlite_master
325 ** table, and that lock is obtained in BtreeBeginTrans(). */
326 assert( 0==(p->db->flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK );
328 /* This function should only be called on a sharable b-tree after it
329 ** has been determined that no other b-tree holds a conflicting lock. */
330 assert( p->sharable );
331 assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
333 /* First search the list for an existing lock on this table. */
334 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
335 if( pIter->iTable==iTable && pIter->pBtree==p ){
336 pLock = pIter;
337 break;
341 /* If the above search did not find a BtLock struct associating Btree p
342 ** with table iTable, allocate one and link it into the list.
344 if( !pLock ){
345 pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
346 if( !pLock ){
347 return SQLITE_NOMEM;
349 pLock->iTable = iTable;
350 pLock->pBtree = p;
351 pLock->pNext = pBt->pLock;
352 pBt->pLock = pLock;
355 /* Set the BtLock.eLock variable to the maximum of the current lock
356 ** and the requested lock. This means if a write-lock was already held
357 ** and a read-lock requested, we don't incorrectly downgrade the lock.
359 assert( WRITE_LOCK>READ_LOCK );
360 if( eLock>pLock->eLock ){
361 pLock->eLock = eLock;
364 return SQLITE_OK;
366 #endif /* !SQLITE_OMIT_SHARED_CACHE */
368 #ifndef SQLITE_OMIT_SHARED_CACHE
370 ** Release all the table locks (locks obtained via calls to
371 ** the setSharedCacheTableLock() procedure) held by Btree object p.
373 ** This function assumes that Btree p has an open read or write
374 ** transaction. If it does not, then the BTS_PENDING flag
375 ** may be incorrectly cleared.
377 static void clearAllSharedCacheTableLocks(Btree *p){
378 BtShared *pBt = p->pBt;
379 BtLock **ppIter = &pBt->pLock;
381 assert( sqlite3BtreeHoldsMutex(p) );
382 assert( p->sharable || 0==*ppIter );
383 assert( p->inTrans>0 );
385 while( *ppIter ){
386 BtLock *pLock = *ppIter;
387 assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree );
388 assert( pLock->pBtree->inTrans>=pLock->eLock );
389 if( pLock->pBtree==p ){
390 *ppIter = pLock->pNext;
391 assert( pLock->iTable!=1 || pLock==&p->lock );
392 if( pLock->iTable!=1 ){
393 sqlite3_free(pLock);
395 }else{
396 ppIter = &pLock->pNext;
400 assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter );
401 if( pBt->pWriter==p ){
402 pBt->pWriter = 0;
403 pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
404 }else if( pBt->nTransaction==2 ){
405 /* This function is called when Btree p is concluding its
406 ** transaction. If there currently exists a writer, and p is not
407 ** that writer, then the number of locks held by connections other
408 ** than the writer must be about to drop to zero. In this case
409 ** set the BTS_PENDING flag to 0.
411 ** If there is not currently a writer, then BTS_PENDING must
412 ** be zero already. So this next line is harmless in that case.
414 pBt->btsFlags &= ~BTS_PENDING;
419 ** This function changes all write-locks held by Btree p into read-locks.
421 static void downgradeAllSharedCacheTableLocks(Btree *p){
422 BtShared *pBt = p->pBt;
423 if( pBt->pWriter==p ){
424 BtLock *pLock;
425 pBt->pWriter = 0;
426 pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
427 for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
428 assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
429 pLock->eLock = READ_LOCK;
434 #endif /* SQLITE_OMIT_SHARED_CACHE */
436 static void releasePage(MemPage *pPage); /* Forward reference */
439 ***** This routine is used inside of assert() only ****
441 ** Verify that the cursor holds the mutex on its BtShared
443 #ifdef SQLITE_DEBUG
444 static int cursorHoldsMutex(BtCursor *p){
445 return sqlite3_mutex_held(p->pBt->mutex);
447 #endif
450 #ifndef SQLITE_OMIT_INCRBLOB
452 ** Invalidate the overflow page-list cache for cursor pCur, if any.
454 static void invalidateOverflowCache(BtCursor *pCur){
455 assert( cursorHoldsMutex(pCur) );
456 sqlite3_free(pCur->aOverflow);
457 pCur->aOverflow = 0;
461 ** Invalidate the overflow page-list cache for all cursors opened
462 ** on the shared btree structure pBt.
464 static void invalidateAllOverflowCache(BtShared *pBt){
465 BtCursor *p;
466 assert( sqlite3_mutex_held(pBt->mutex) );
467 for(p=pBt->pCursor; p; p=p->pNext){
468 invalidateOverflowCache(p);
473 ** This function is called before modifying the contents of a table
474 ** to invalidate any incrblob cursors that are open on the
475 ** row or one of the rows being modified.
477 ** If argument isClearTable is true, then the entire contents of the
478 ** table is about to be deleted. In this case invalidate all incrblob
479 ** cursors open on any row within the table with root-page pgnoRoot.
481 ** Otherwise, if argument isClearTable is false, then the row with
482 ** rowid iRow is being replaced or deleted. In this case invalidate
483 ** only those incrblob cursors open on that specific row.
485 static void invalidateIncrblobCursors(
486 Btree *pBtree, /* The database file to check */
487 i64 iRow, /* The rowid that might be changing */
488 int isClearTable /* True if all rows are being deleted */
490 BtCursor *p;
491 BtShared *pBt = pBtree->pBt;
492 assert( sqlite3BtreeHoldsMutex(pBtree) );
493 for(p=pBt->pCursor; p; p=p->pNext){
494 if( p->isIncrblobHandle && (isClearTable || p->info.nKey==iRow) ){
495 p->eState = CURSOR_INVALID;
500 #else
501 /* Stub functions when INCRBLOB is omitted */
502 #define invalidateOverflowCache(x)
503 #define invalidateAllOverflowCache(x)
504 #define invalidateIncrblobCursors(x,y,z)
505 #endif /* SQLITE_OMIT_INCRBLOB */
508 ** Set bit pgno of the BtShared.pHasContent bitvec. This is called
509 ** when a page that previously contained data becomes a free-list leaf
510 ** page.
512 ** The BtShared.pHasContent bitvec exists to work around an obscure
513 ** bug caused by the interaction of two useful IO optimizations surrounding
514 ** free-list leaf pages:
516 ** 1) When all data is deleted from a page and the page becomes
517 ** a free-list leaf page, the page is not written to the database
518 ** (as free-list leaf pages contain no meaningful data). Sometimes
519 ** such a page is not even journalled (as it will not be modified,
520 ** why bother journalling it?).
522 ** 2) When a free-list leaf page is reused, its content is not read
523 ** from the database or written to the journal file (why should it
524 ** be, if it is not at all meaningful?).
526 ** By themselves, these optimizations work fine and provide a handy
527 ** performance boost to bulk delete or insert operations. However, if
528 ** a page is moved to the free-list and then reused within the same
529 ** transaction, a problem comes up. If the page is not journalled when
530 ** it is moved to the free-list and it is also not journalled when it
531 ** is extracted from the free-list and reused, then the original data
532 ** may be lost. In the event of a rollback, it may not be possible
533 ** to restore the database to its original configuration.
535 ** The solution is the BtShared.pHasContent bitvec. Whenever a page is
536 ** moved to become a free-list leaf page, the corresponding bit is
537 ** set in the bitvec. Whenever a leaf page is extracted from the free-list,
538 ** optimization 2 above is omitted if the corresponding bit is already
539 ** set in BtShared.pHasContent. The contents of the bitvec are cleared
540 ** at the end of every transaction.
542 static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
543 int rc = SQLITE_OK;
544 if( !pBt->pHasContent ){
545 assert( pgno<=pBt->nPage );
546 pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
547 if( !pBt->pHasContent ){
548 rc = SQLITE_NOMEM;
551 if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
552 rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
554 return rc;
558 ** Query the BtShared.pHasContent vector.
560 ** This function is called when a free-list leaf page is removed from the
561 ** free-list for reuse. It returns false if it is safe to retrieve the
562 ** page from the pager layer with the 'no-content' flag set. True otherwise.
564 static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
565 Bitvec *p = pBt->pHasContent;
566 return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
570 ** Clear (destroy) the BtShared.pHasContent bitvec. This should be
571 ** invoked at the conclusion of each write-transaction.
573 static void btreeClearHasContent(BtShared *pBt){
574 sqlite3BitvecDestroy(pBt->pHasContent);
575 pBt->pHasContent = 0;
579 ** Release all of the apPage[] pages for a cursor.
581 static void btreeReleaseAllCursorPages(BtCursor *pCur){
582 int i;
583 for(i=0; i<=pCur->iPage; i++){
584 releasePage(pCur->apPage[i]);
585 pCur->apPage[i] = 0;
587 pCur->iPage = -1;
592 ** Save the current cursor position in the variables BtCursor.nKey
593 ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
595 ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
596 ** prior to calling this routine.
598 static int saveCursorPosition(BtCursor *pCur){
599 int rc;
601 assert( CURSOR_VALID==pCur->eState );
602 assert( 0==pCur->pKey );
603 assert( cursorHoldsMutex(pCur) );
605 rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
606 assert( rc==SQLITE_OK ); /* KeySize() cannot fail */
608 /* If this is an intKey table, then the above call to BtreeKeySize()
609 ** stores the integer key in pCur->nKey. In this case this value is
610 ** all that is required. Otherwise, if pCur is not open on an intKey
611 ** table, then malloc space for and store the pCur->nKey bytes of key
612 ** data.
614 if( 0==pCur->apPage[0]->intKey ){
615 void *pKey = sqlite3Malloc( (int)pCur->nKey );
616 if( pKey ){
617 rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
618 if( rc==SQLITE_OK ){
619 pCur->pKey = pKey;
620 }else{
621 sqlite3_free(pKey);
623 }else{
624 rc = SQLITE_NOMEM;
627 assert( !pCur->apPage[0]->intKey || !pCur->pKey );
629 if( rc==SQLITE_OK ){
630 btreeReleaseAllCursorPages(pCur);
631 pCur->eState = CURSOR_REQUIRESEEK;
634 invalidateOverflowCache(pCur);
635 return rc;
639 ** Save the positions of all cursors (except pExcept) that are open on
640 ** the table with root-page iRoot. Usually, this is called just before cursor
641 ** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()).
643 static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
644 BtCursor *p;
645 assert( sqlite3_mutex_held(pBt->mutex) );
646 assert( pExcept==0 || pExcept->pBt==pBt );
647 for(p=pBt->pCursor; p; p=p->pNext){
648 if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ){
649 if( p->eState==CURSOR_VALID ){
650 int rc = saveCursorPosition(p);
651 if( SQLITE_OK!=rc ){
652 return rc;
654 }else{
655 testcase( p->iPage>0 );
656 btreeReleaseAllCursorPages(p);
660 return SQLITE_OK;
664 ** Clear the current cursor position.
666 void sqlite3BtreeClearCursor(BtCursor *pCur){
667 assert( cursorHoldsMutex(pCur) );
668 sqlite3_free(pCur->pKey);
669 pCur->pKey = 0;
670 pCur->eState = CURSOR_INVALID;
674 ** In this version of BtreeMoveto, pKey is a packed index record
675 ** such as is generated by the OP_MakeRecord opcode. Unpack the
676 ** record and then call BtreeMovetoUnpacked() to do the work.
678 static int btreeMoveto(
679 BtCursor *pCur, /* Cursor open on the btree to be searched */
680 const void *pKey, /* Packed key if the btree is an index */
681 i64 nKey, /* Integer key for tables. Size of pKey for indices */
682 int bias, /* Bias search to the high end */
683 int *pRes /* Write search results here */
685 int rc; /* Status code */
686 UnpackedRecord *pIdxKey; /* Unpacked index key */
687 char aSpace[150]; /* Temp space for pIdxKey - to avoid a malloc */
688 char *pFree = 0;
690 if( pKey ){
691 assert( nKey==(i64)(int)nKey );
692 pIdxKey = sqlite3VdbeAllocUnpackedRecord(
693 pCur->pKeyInfo, aSpace, sizeof(aSpace), &pFree
695 if( pIdxKey==0 ) return SQLITE_NOMEM;
696 sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey, pIdxKey);
697 }else{
698 pIdxKey = 0;
700 rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
701 if( pFree ){
702 sqlite3DbFree(pCur->pKeyInfo->db, pFree);
704 return rc;
708 ** Restore the cursor to the position it was in (or as close to as possible)
709 ** when saveCursorPosition() was called. Note that this call deletes the
710 ** saved position info stored by saveCursorPosition(), so there can be
711 ** at most one effective restoreCursorPosition() call after each
712 ** saveCursorPosition().
714 static int btreeRestoreCursorPosition(BtCursor *pCur){
715 int rc;
716 assert( cursorHoldsMutex(pCur) );
717 assert( pCur->eState>=CURSOR_REQUIRESEEK );
718 if( pCur->eState==CURSOR_FAULT ){
719 return pCur->skipNext;
721 pCur->eState = CURSOR_INVALID;
722 rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &pCur->skipNext);
723 if( rc==SQLITE_OK ){
724 sqlite3_free(pCur->pKey);
725 pCur->pKey = 0;
726 assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
728 return rc;
731 #define restoreCursorPosition(p) \
732 (p->eState>=CURSOR_REQUIRESEEK ? \
733 btreeRestoreCursorPosition(p) : \
734 SQLITE_OK)
737 ** Determine whether or not a cursor has moved from the position it
738 ** was last placed at. Cursors can move when the row they are pointing
739 ** at is deleted out from under them.
741 ** This routine returns an error code if something goes wrong. The
742 ** integer *pHasMoved is set to one if the cursor has moved and 0 if not.
744 int sqlite3BtreeCursorHasMoved(BtCursor *pCur, int *pHasMoved){
745 int rc;
747 rc = restoreCursorPosition(pCur);
748 if( rc ){
749 *pHasMoved = 1;
750 return rc;
752 if( pCur->eState!=CURSOR_VALID || pCur->skipNext!=0 ){
753 *pHasMoved = 1;
754 }else{
755 *pHasMoved = 0;
757 return SQLITE_OK;
760 #ifndef SQLITE_OMIT_AUTOVACUUM
762 ** Given a page number of a regular database page, return the page
763 ** number for the pointer-map page that contains the entry for the
764 ** input page number.
766 ** Return 0 (not a valid page) for pgno==1 since there is
767 ** no pointer map associated with page 1. The integrity_check logic
768 ** requires that ptrmapPageno(*,1)!=1.
770 static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
771 int nPagesPerMapPage;
772 Pgno iPtrMap, ret;
773 assert( sqlite3_mutex_held(pBt->mutex) );
774 if( pgno<2 ) return 0;
775 nPagesPerMapPage = (pBt->usableSize/5)+1;
776 iPtrMap = (pgno-2)/nPagesPerMapPage;
777 ret = (iPtrMap*nPagesPerMapPage) + 2;
778 if( ret==PENDING_BYTE_PAGE(pBt) ){
779 ret++;
781 return ret;
785 ** Write an entry into the pointer map.
787 ** This routine updates the pointer map entry for page number 'key'
788 ** so that it maps to type 'eType' and parent page number 'pgno'.
790 ** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
791 ** a no-op. If an error occurs, the appropriate error code is written
792 ** into *pRC.
794 static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
795 DbPage *pDbPage; /* The pointer map page */
796 u8 *pPtrmap; /* The pointer map data */
797 Pgno iPtrmap; /* The pointer map page number */
798 int offset; /* Offset in pointer map page */
799 int rc; /* Return code from subfunctions */
801 if( *pRC ) return;
803 assert( sqlite3_mutex_held(pBt->mutex) );
804 /* The master-journal page number must never be used as a pointer map page */
805 assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
807 assert( pBt->autoVacuum );
808 if( key==0 ){
809 *pRC = SQLITE_CORRUPT_BKPT;
810 return;
812 iPtrmap = PTRMAP_PAGENO(pBt, key);
813 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
814 if( rc!=SQLITE_OK ){
815 *pRC = rc;
816 return;
818 offset = PTRMAP_PTROFFSET(iPtrmap, key);
819 if( offset<0 ){
820 *pRC = SQLITE_CORRUPT_BKPT;
821 goto ptrmap_exit;
823 assert( offset <= (int)pBt->usableSize-5 );
824 pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
826 if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
827 TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
828 *pRC= rc = sqlite3PagerWrite(pDbPage);
829 if( rc==SQLITE_OK ){
830 pPtrmap[offset] = eType;
831 put4byte(&pPtrmap[offset+1], parent);
835 ptrmap_exit:
836 sqlite3PagerUnref(pDbPage);
840 ** Read an entry from the pointer map.
842 ** This routine retrieves the pointer map entry for page 'key', writing
843 ** the type and parent page number to *pEType and *pPgno respectively.
844 ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
846 static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
847 DbPage *pDbPage; /* The pointer map page */
848 int iPtrmap; /* Pointer map page index */
849 u8 *pPtrmap; /* Pointer map page data */
850 int offset; /* Offset of entry in pointer map */
851 int rc;
853 assert( sqlite3_mutex_held(pBt->mutex) );
855 iPtrmap = PTRMAP_PAGENO(pBt, key);
856 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
857 if( rc!=0 ){
858 return rc;
860 pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
862 offset = PTRMAP_PTROFFSET(iPtrmap, key);
863 if( offset<0 ){
864 sqlite3PagerUnref(pDbPage);
865 return SQLITE_CORRUPT_BKPT;
867 assert( offset <= (int)pBt->usableSize-5 );
868 assert( pEType!=0 );
869 *pEType = pPtrmap[offset];
870 if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
872 sqlite3PagerUnref(pDbPage);
873 if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
874 return SQLITE_OK;
877 #else /* if defined SQLITE_OMIT_AUTOVACUUM */
878 #define ptrmapPut(w,x,y,z,rc)
879 #define ptrmapGet(w,x,y,z) SQLITE_OK
880 #define ptrmapPutOvflPtr(x, y, rc)
881 #endif
884 ** Given a btree page and a cell index (0 means the first cell on
885 ** the page, 1 means the second cell, and so forth) return a pointer
886 ** to the cell content.
888 ** This routine works only for pages that do not contain overflow cells.
890 #define findCell(P,I) \
891 ((P)->aData + ((P)->maskPage & get2byte(&(P)->aCellIdx[2*(I)])))
892 #define findCellv2(D,M,O,I) (D+(M&get2byte(D+(O+2*(I)))))
896 ** This a more complex version of findCell() that works for
897 ** pages that do contain overflow cells.
899 static u8 *findOverflowCell(MemPage *pPage, int iCell){
900 int i;
901 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
902 for(i=pPage->nOverflow-1; i>=0; i--){
903 int k;
904 k = pPage->aiOvfl[i];
905 if( k<=iCell ){
906 if( k==iCell ){
907 return pPage->apOvfl[i];
909 iCell--;
912 return findCell(pPage, iCell);
916 ** Parse a cell content block and fill in the CellInfo structure. There
917 ** are two versions of this function. btreeParseCell() takes a
918 ** cell index as the second argument and btreeParseCellPtr()
919 ** takes a pointer to the body of the cell as its second argument.
921 ** Within this file, the parseCell() macro can be called instead of
922 ** btreeParseCellPtr(). Using some compilers, this will be faster.
924 static void btreeParseCellPtr(
925 MemPage *pPage, /* Page containing the cell */
926 u8 *pCell, /* Pointer to the cell text. */
927 CellInfo *pInfo /* Fill in this structure */
929 u16 n; /* Number bytes in cell content header */
930 u32 nPayload; /* Number of bytes of cell payload */
932 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
934 pInfo->pCell = pCell;
935 assert( pPage->leaf==0 || pPage->leaf==1 );
936 n = pPage->childPtrSize;
937 assert( n==4-4*pPage->leaf );
938 if( pPage->intKey ){
939 if( pPage->hasData ){
940 n += getVarint32(&pCell[n], nPayload);
941 }else{
942 nPayload = 0;
944 n += getVarint(&pCell[n], (u64*)&pInfo->nKey);
945 pInfo->nData = nPayload;
946 }else{
947 pInfo->nData = 0;
948 n += getVarint32(&pCell[n], nPayload);
949 pInfo->nKey = nPayload;
951 pInfo->nPayload = nPayload;
952 pInfo->nHeader = n;
953 testcase( nPayload==pPage->maxLocal );
954 testcase( nPayload==pPage->maxLocal+1 );
955 if( likely(nPayload<=pPage->maxLocal) ){
956 /* This is the (easy) common case where the entire payload fits
957 ** on the local page. No overflow is required.
959 if( (pInfo->nSize = (u16)(n+nPayload))<4 ) pInfo->nSize = 4;
960 pInfo->nLocal = (u16)nPayload;
961 pInfo->iOverflow = 0;
962 }else{
963 /* If the payload will not fit completely on the local page, we have
964 ** to decide how much to store locally and how much to spill onto
965 ** overflow pages. The strategy is to minimize the amount of unused
966 ** space on overflow pages while keeping the amount of local storage
967 ** in between minLocal and maxLocal.
969 ** Warning: changing the way overflow payload is distributed in any
970 ** way will result in an incompatible file format.
972 int minLocal; /* Minimum amount of payload held locally */
973 int maxLocal; /* Maximum amount of payload held locally */
974 int surplus; /* Overflow payload available for local storage */
976 minLocal = pPage->minLocal;
977 maxLocal = pPage->maxLocal;
978 surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
979 testcase( surplus==maxLocal );
980 testcase( surplus==maxLocal+1 );
981 if( surplus <= maxLocal ){
982 pInfo->nLocal = (u16)surplus;
983 }else{
984 pInfo->nLocal = (u16)minLocal;
986 pInfo->iOverflow = (u16)(pInfo->nLocal + n);
987 pInfo->nSize = pInfo->iOverflow + 4;
990 #define parseCell(pPage, iCell, pInfo) \
991 btreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo))
992 static void btreeParseCell(
993 MemPage *pPage, /* Page containing the cell */
994 int iCell, /* The cell index. First cell is 0 */
995 CellInfo *pInfo /* Fill in this structure */
997 parseCell(pPage, iCell, pInfo);
1001 ** Compute the total number of bytes that a Cell needs in the cell
1002 ** data area of the btree-page. The return number includes the cell
1003 ** data header and the local payload, but not any overflow page or
1004 ** the space used by the cell pointer.
1006 static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
1007 u8 *pIter = &pCell[pPage->childPtrSize];
1008 u32 nSize;
1010 #ifdef SQLITE_DEBUG
1011 /* The value returned by this function should always be the same as
1012 ** the (CellInfo.nSize) value found by doing a full parse of the
1013 ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
1014 ** this function verifies that this invariant is not violated. */
1015 CellInfo debuginfo;
1016 btreeParseCellPtr(pPage, pCell, &debuginfo);
1017 #endif
1019 if( pPage->intKey ){
1020 u8 *pEnd;
1021 if( pPage->hasData ){
1022 pIter += getVarint32(pIter, nSize);
1023 }else{
1024 nSize = 0;
1027 /* pIter now points at the 64-bit integer key value, a variable length
1028 ** integer. The following block moves pIter to point at the first byte
1029 ** past the end of the key value. */
1030 pEnd = &pIter[9];
1031 while( (*pIter++)&0x80 && pIter<pEnd );
1032 }else{
1033 pIter += getVarint32(pIter, nSize);
1036 testcase( nSize==pPage->maxLocal );
1037 testcase( nSize==pPage->maxLocal+1 );
1038 if( nSize>pPage->maxLocal ){
1039 int minLocal = pPage->minLocal;
1040 nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
1041 testcase( nSize==pPage->maxLocal );
1042 testcase( nSize==pPage->maxLocal+1 );
1043 if( nSize>pPage->maxLocal ){
1044 nSize = minLocal;
1046 nSize += 4;
1048 nSize += (u32)(pIter - pCell);
1050 /* The minimum size of any cell is 4 bytes. */
1051 if( nSize<4 ){
1052 nSize = 4;
1055 assert( nSize==debuginfo.nSize );
1056 return (u16)nSize;
1059 #ifdef SQLITE_DEBUG
1060 /* This variation on cellSizePtr() is used inside of assert() statements
1061 ** only. */
1062 static u16 cellSize(MemPage *pPage, int iCell){
1063 return cellSizePtr(pPage, findCell(pPage, iCell));
1065 #endif
1067 #ifndef SQLITE_OMIT_AUTOVACUUM
1069 ** If the cell pCell, part of page pPage contains a pointer
1070 ** to an overflow page, insert an entry into the pointer-map
1071 ** for the overflow page.
1073 static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
1074 CellInfo info;
1075 if( *pRC ) return;
1076 assert( pCell!=0 );
1077 btreeParseCellPtr(pPage, pCell, &info);
1078 assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
1079 if( info.iOverflow ){
1080 Pgno ovfl = get4byte(&pCell[info.iOverflow]);
1081 ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
1084 #endif
1088 ** Defragment the page given. All Cells are moved to the
1089 ** end of the page and all free space is collected into one
1090 ** big FreeBlk that occurs in between the header and cell
1091 ** pointer array and the cell content area.
1093 static int defragmentPage(MemPage *pPage){
1094 int i; /* Loop counter */
1095 int pc; /* Address of a i-th cell */
1096 int hdr; /* Offset to the page header */
1097 int size; /* Size of a cell */
1098 int usableSize; /* Number of usable bytes on a page */
1099 int cellOffset; /* Offset to the cell pointer array */
1100 int cbrk; /* Offset to the cell content area */
1101 int nCell; /* Number of cells on the page */
1102 unsigned char *data; /* The page data */
1103 unsigned char *temp; /* Temp area for cell content */
1104 int iCellFirst; /* First allowable cell index */
1105 int iCellLast; /* Last possible cell index */
1108 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
1109 assert( pPage->pBt!=0 );
1110 assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
1111 assert( pPage->nOverflow==0 );
1112 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1113 temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
1114 data = pPage->aData;
1115 hdr = pPage->hdrOffset;
1116 cellOffset = pPage->cellOffset;
1117 nCell = pPage->nCell;
1118 assert( nCell==get2byte(&data[hdr+3]) );
1119 usableSize = pPage->pBt->usableSize;
1120 cbrk = get2byte(&data[hdr+5]);
1121 memcpy(&temp[cbrk], &data[cbrk], usableSize - cbrk);
1122 cbrk = usableSize;
1123 iCellFirst = cellOffset + 2*nCell;
1124 iCellLast = usableSize - 4;
1125 for(i=0; i<nCell; i++){
1126 u8 *pAddr; /* The i-th cell pointer */
1127 pAddr = &data[cellOffset + i*2];
1128 pc = get2byte(pAddr);
1129 testcase( pc==iCellFirst );
1130 testcase( pc==iCellLast );
1131 #if !defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
1132 /* These conditions have already been verified in btreeInitPage()
1133 ** if SQLITE_ENABLE_OVERSIZE_CELL_CHECK is defined
1135 if( pc<iCellFirst || pc>iCellLast ){
1136 return SQLITE_CORRUPT_BKPT;
1138 #endif
1139 assert( pc>=iCellFirst && pc<=iCellLast );
1140 size = cellSizePtr(pPage, &temp[pc]);
1141 cbrk -= size;
1142 #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
1143 if( cbrk<iCellFirst ){
1144 return SQLITE_CORRUPT_BKPT;
1146 #else
1147 if( cbrk<iCellFirst || pc+size>usableSize ){
1148 return SQLITE_CORRUPT_BKPT;
1150 #endif
1151 assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
1152 testcase( cbrk+size==usableSize );
1153 testcase( pc+size==usableSize );
1154 memcpy(&data[cbrk], &temp[pc], size);
1155 put2byte(pAddr, cbrk);
1157 assert( cbrk>=iCellFirst );
1158 put2byte(&data[hdr+5], cbrk);
1159 data[hdr+1] = 0;
1160 data[hdr+2] = 0;
1161 data[hdr+7] = 0;
1162 memset(&data[iCellFirst], 0, cbrk-iCellFirst);
1163 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
1164 if( cbrk-iCellFirst!=pPage->nFree ){
1165 return SQLITE_CORRUPT_BKPT;
1167 return SQLITE_OK;
1171 ** Allocate nByte bytes of space from within the B-Tree page passed
1172 ** as the first argument. Write into *pIdx the index into pPage->aData[]
1173 ** of the first byte of allocated space. Return either SQLITE_OK or
1174 ** an error code (usually SQLITE_CORRUPT).
1176 ** The caller guarantees that there is sufficient space to make the
1177 ** allocation. This routine might need to defragment in order to bring
1178 ** all the space together, however. This routine will avoid using
1179 ** the first two bytes past the cell pointer area since presumably this
1180 ** allocation is being made in order to insert a new cell, so we will
1181 ** also end up needing a new cell pointer.
1183 static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
1184 const int hdr = pPage->hdrOffset; /* Local cache of pPage->hdrOffset */
1185 u8 * const data = pPage->aData; /* Local cache of pPage->aData */
1186 int nFrag; /* Number of fragmented bytes on pPage */
1187 int top; /* First byte of cell content area */
1188 int gap; /* First byte of gap between cell pointers and cell content */
1189 int rc; /* Integer return code */
1190 int usableSize; /* Usable size of the page */
1192 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
1193 assert( pPage->pBt );
1194 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1195 assert( nByte>=0 ); /* Minimum cell size is 4 */
1196 assert( pPage->nFree>=nByte );
1197 assert( pPage->nOverflow==0 );
1198 usableSize = pPage->pBt->usableSize;
1199 assert( nByte < usableSize-8 );
1201 nFrag = data[hdr+7];
1202 assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
1203 gap = pPage->cellOffset + 2*pPage->nCell;
1204 top = get2byteNotZero(&data[hdr+5]);
1205 if( gap>top ) return SQLITE_CORRUPT_BKPT;
1206 testcase( gap+2==top );
1207 testcase( gap+1==top );
1208 testcase( gap==top );
1210 if( nFrag>=60 ){
1211 /* Always defragment highly fragmented pages */
1212 rc = defragmentPage(pPage);
1213 if( rc ) return rc;
1214 top = get2byteNotZero(&data[hdr+5]);
1215 }else if( gap+2<=top ){
1216 /* Search the freelist looking for a free slot big enough to satisfy
1217 ** the request. The allocation is made from the first free slot in
1218 ** the list that is large enough to accomadate it.
1220 int pc, addr;
1221 for(addr=hdr+1; (pc = get2byte(&data[addr]))>0; addr=pc){
1222 int size; /* Size of the free slot */
1223 if( pc>usableSize-4 || pc<addr+4 ){
1224 return SQLITE_CORRUPT_BKPT;
1226 size = get2byte(&data[pc+2]);
1227 if( size>=nByte ){
1228 int x = size - nByte;
1229 testcase( x==4 );
1230 testcase( x==3 );
1231 if( x<4 ){
1232 /* Remove the slot from the free-list. Update the number of
1233 ** fragmented bytes within the page. */
1234 memcpy(&data[addr], &data[pc], 2);
1235 data[hdr+7] = (u8)(nFrag + x);
1236 }else if( size+pc > usableSize ){
1237 return SQLITE_CORRUPT_BKPT;
1238 }else{
1239 /* The slot remains on the free-list. Reduce its size to account
1240 ** for the portion used by the new allocation. */
1241 put2byte(&data[pc+2], x);
1243 *pIdx = pc + x;
1244 return SQLITE_OK;
1249 /* Check to make sure there is enough space in the gap to satisfy
1250 ** the allocation. If not, defragment.
1252 testcase( gap+2+nByte==top );
1253 if( gap+2+nByte>top ){
1254 rc = defragmentPage(pPage);
1255 if( rc ) return rc;
1256 top = get2byteNotZero(&data[hdr+5]);
1257 assert( gap+nByte<=top );
1261 /* Allocate memory from the gap in between the cell pointer array
1262 ** and the cell content area. The btreeInitPage() call has already
1263 ** validated the freelist. Given that the freelist is valid, there
1264 ** is no way that the allocation can extend off the end of the page.
1265 ** The assert() below verifies the previous sentence.
1267 top -= nByte;
1268 put2byte(&data[hdr+5], top);
1269 assert( top+nByte <= (int)pPage->pBt->usableSize );
1270 *pIdx = top;
1271 return SQLITE_OK;
1275 ** Return a section of the pPage->aData to the freelist.
1276 ** The first byte of the new free block is pPage->aDisk[start]
1277 ** and the size of the block is "size" bytes.
1279 ** Most of the effort here is involved in coalesing adjacent
1280 ** free blocks into a single big free block.
1282 static int freeSpace(MemPage *pPage, int start, int size){
1283 int addr, pbegin, hdr;
1284 int iLast; /* Largest possible freeblock offset */
1285 unsigned char *data = pPage->aData;
1287 assert( pPage->pBt!=0 );
1288 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
1289 assert( start>=pPage->hdrOffset+6+pPage->childPtrSize );
1290 assert( (start + size) <= (int)pPage->pBt->usableSize );
1291 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1292 assert( size>=0 ); /* Minimum cell size is 4 */
1294 if( pPage->pBt->btsFlags & BTS_SECURE_DELETE ){
1295 /* Overwrite deleted information with zeros when the secure_delete
1296 ** option is enabled */
1297 memset(&data[start], 0, size);
1300 /* Add the space back into the linked list of freeblocks. Note that
1301 ** even though the freeblock list was checked by btreeInitPage(),
1302 ** btreeInitPage() did not detect overlapping cells or
1303 ** freeblocks that overlapped cells. Nor does it detect when the
1304 ** cell content area exceeds the value in the page header. If these
1305 ** situations arise, then subsequent insert operations might corrupt
1306 ** the freelist. So we do need to check for corruption while scanning
1307 ** the freelist.
1309 hdr = pPage->hdrOffset;
1310 addr = hdr + 1;
1311 iLast = pPage->pBt->usableSize - 4;
1312 assert( start<=iLast );
1313 while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
1314 if( pbegin<addr+4 ){
1315 return SQLITE_CORRUPT_BKPT;
1317 addr = pbegin;
1319 if( pbegin>iLast ){
1320 return SQLITE_CORRUPT_BKPT;
1322 assert( pbegin>addr || pbegin==0 );
1323 put2byte(&data[addr], start);
1324 put2byte(&data[start], pbegin);
1325 put2byte(&data[start+2], size);
1326 pPage->nFree = pPage->nFree + (u16)size;
1328 /* Coalesce adjacent free blocks */
1329 addr = hdr + 1;
1330 while( (pbegin = get2byte(&data[addr]))>0 ){
1331 int pnext, psize, x;
1332 assert( pbegin>addr );
1333 assert( pbegin <= (int)pPage->pBt->usableSize-4 );
1334 pnext = get2byte(&data[pbegin]);
1335 psize = get2byte(&data[pbegin+2]);
1336 if( pbegin + psize + 3 >= pnext && pnext>0 ){
1337 int frag = pnext - (pbegin+psize);
1338 if( (frag<0) || (frag>(int)data[hdr+7]) ){
1339 return SQLITE_CORRUPT_BKPT;
1341 data[hdr+7] -= (u8)frag;
1342 x = get2byte(&data[pnext]);
1343 put2byte(&data[pbegin], x);
1344 x = pnext + get2byte(&data[pnext+2]) - pbegin;
1345 put2byte(&data[pbegin+2], x);
1346 }else{
1347 addr = pbegin;
1351 /* If the cell content area begins with a freeblock, remove it. */
1352 if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
1353 int top;
1354 pbegin = get2byte(&data[hdr+1]);
1355 memcpy(&data[hdr+1], &data[pbegin], 2);
1356 top = get2byte(&data[hdr+5]) + get2byte(&data[pbegin+2]);
1357 put2byte(&data[hdr+5], top);
1359 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
1360 return SQLITE_OK;
1364 ** Decode the flags byte (the first byte of the header) for a page
1365 ** and initialize fields of the MemPage structure accordingly.
1367 ** Only the following combinations are supported. Anything different
1368 ** indicates a corrupt database files:
1370 ** PTF_ZERODATA
1371 ** PTF_ZERODATA | PTF_LEAF
1372 ** PTF_LEAFDATA | PTF_INTKEY
1373 ** PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
1375 static int decodeFlags(MemPage *pPage, int flagByte){
1376 BtShared *pBt; /* A copy of pPage->pBt */
1378 assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
1379 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1380 pPage->leaf = (u8)(flagByte>>3); assert( PTF_LEAF == 1<<3 );
1381 flagByte &= ~PTF_LEAF;
1382 pPage->childPtrSize = 4-4*pPage->leaf;
1383 pBt = pPage->pBt;
1384 if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
1385 pPage->intKey = 1;
1386 pPage->hasData = pPage->leaf;
1387 pPage->maxLocal = pBt->maxLeaf;
1388 pPage->minLocal = pBt->minLeaf;
1389 }else if( flagByte==PTF_ZERODATA ){
1390 pPage->intKey = 0;
1391 pPage->hasData = 0;
1392 pPage->maxLocal = pBt->maxLocal;
1393 pPage->minLocal = pBt->minLocal;
1394 }else{
1395 return SQLITE_CORRUPT_BKPT;
1397 pPage->max1bytePayload = pBt->max1bytePayload;
1398 return SQLITE_OK;
1402 ** Initialize the auxiliary information for a disk block.
1404 ** Return SQLITE_OK on success. If we see that the page does
1405 ** not contain a well-formed database page, then return
1406 ** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
1407 ** guarantee that the page is well-formed. It only shows that
1408 ** we failed to detect any corruption.
1410 static int btreeInitPage(MemPage *pPage){
1412 assert( pPage->pBt!=0 );
1413 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1414 assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
1415 assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
1416 assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
1418 if( !pPage->isInit ){
1419 u16 pc; /* Address of a freeblock within pPage->aData[] */
1420 u8 hdr; /* Offset to beginning of page header */
1421 u8 *data; /* Equal to pPage->aData */
1422 BtShared *pBt; /* The main btree structure */
1423 int usableSize; /* Amount of usable space on each page */
1424 u16 cellOffset; /* Offset from start of page to first cell pointer */
1425 int nFree; /* Number of unused bytes on the page */
1426 int top; /* First byte of the cell content area */
1427 int iCellFirst; /* First allowable cell or freeblock offset */
1428 int iCellLast; /* Last possible cell or freeblock offset */
1430 pBt = pPage->pBt;
1432 hdr = pPage->hdrOffset;
1433 data = pPage->aData;
1434 if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
1435 assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
1436 pPage->maskPage = (u16)(pBt->pageSize - 1);
1437 pPage->nOverflow = 0;
1438 usableSize = pBt->usableSize;
1439 pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
1440 pPage->aDataEnd = &data[usableSize];
1441 pPage->aCellIdx = &data[cellOffset];
1442 top = get2byteNotZero(&data[hdr+5]);
1443 pPage->nCell = get2byte(&data[hdr+3]);
1444 if( pPage->nCell>MX_CELL(pBt) ){
1445 /* To many cells for a single page. The page must be corrupt */
1446 return SQLITE_CORRUPT_BKPT;
1448 testcase( pPage->nCell==MX_CELL(pBt) );
1450 /* A malformed database page might cause us to read past the end
1451 ** of page when parsing a cell.
1453 ** The following block of code checks early to see if a cell extends
1454 ** past the end of a page boundary and causes SQLITE_CORRUPT to be
1455 ** returned if it does.
1457 iCellFirst = cellOffset + 2*pPage->nCell;
1458 iCellLast = usableSize - 4;
1459 #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
1461 int i; /* Index into the cell pointer array */
1462 int sz; /* Size of a cell */
1464 if( !pPage->leaf ) iCellLast--;
1465 for(i=0; i<pPage->nCell; i++){
1466 pc = get2byte(&data[cellOffset+i*2]);
1467 testcase( pc==iCellFirst );
1468 testcase( pc==iCellLast );
1469 if( pc<iCellFirst || pc>iCellLast ){
1470 return SQLITE_CORRUPT_BKPT;
1472 sz = cellSizePtr(pPage, &data[pc]);
1473 testcase( pc+sz==usableSize );
1474 if( pc+sz>usableSize ){
1475 return SQLITE_CORRUPT_BKPT;
1478 if( !pPage->leaf ) iCellLast++;
1480 #endif
1482 /* Compute the total free space on the page */
1483 pc = get2byte(&data[hdr+1]);
1484 nFree = data[hdr+7] + top;
1485 while( pc>0 ){
1486 u16 next, size;
1487 if( pc<iCellFirst || pc>iCellLast ){
1488 /* Start of free block is off the page */
1489 return SQLITE_CORRUPT_BKPT;
1491 next = get2byte(&data[pc]);
1492 size = get2byte(&data[pc+2]);
1493 if( (next>0 && next<=pc+size+3) || pc+size>usableSize ){
1494 /* Free blocks must be in ascending order. And the last byte of
1495 ** the free-block must lie on the database page. */
1496 return SQLITE_CORRUPT_BKPT;
1498 nFree = nFree + size;
1499 pc = next;
1502 /* At this point, nFree contains the sum of the offset to the start
1503 ** of the cell-content area plus the number of free bytes within
1504 ** the cell-content area. If this is greater than the usable-size
1505 ** of the page, then the page must be corrupted. This check also
1506 ** serves to verify that the offset to the start of the cell-content
1507 ** area, according to the page header, lies within the page.
1509 if( nFree>usableSize ){
1510 return SQLITE_CORRUPT_BKPT;
1512 pPage->nFree = (u16)(nFree - iCellFirst);
1513 pPage->isInit = 1;
1515 return SQLITE_OK;
1519 ** Set up a raw page so that it looks like a database page holding
1520 ** no entries.
1522 static void zeroPage(MemPage *pPage, int flags){
1523 unsigned char *data = pPage->aData;
1524 BtShared *pBt = pPage->pBt;
1525 u8 hdr = pPage->hdrOffset;
1526 u16 first;
1528 assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
1529 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
1530 assert( sqlite3PagerGetData(pPage->pDbPage) == data );
1531 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
1532 assert( sqlite3_mutex_held(pBt->mutex) );
1533 if( pBt->btsFlags & BTS_SECURE_DELETE ){
1534 memset(&data[hdr], 0, pBt->usableSize - hdr);
1536 data[hdr] = (char)flags;
1537 first = hdr + 8 + 4*((flags&PTF_LEAF)==0 ?1:0);
1538 memset(&data[hdr+1], 0, 4);
1539 data[hdr+7] = 0;
1540 put2byte(&data[hdr+5], pBt->usableSize);
1541 pPage->nFree = (u16)(pBt->usableSize - first);
1542 decodeFlags(pPage, flags);
1543 pPage->hdrOffset = hdr;
1544 pPage->cellOffset = first;
1545 pPage->aDataEnd = &data[pBt->usableSize];
1546 pPage->aCellIdx = &data[first];
1547 pPage->nOverflow = 0;
1548 assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
1549 pPage->maskPage = (u16)(pBt->pageSize - 1);
1550 pPage->nCell = 0;
1551 pPage->isInit = 1;
1556 ** Convert a DbPage obtained from the pager into a MemPage used by
1557 ** the btree layer.
1559 static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
1560 MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
1561 pPage->aData = sqlite3PagerGetData(pDbPage);
1562 pPage->pDbPage = pDbPage;
1563 pPage->pBt = pBt;
1564 pPage->pgno = pgno;
1565 pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
1566 return pPage;
1570 ** Get a page from the pager. Initialize the MemPage.pBt and
1571 ** MemPage.aData elements if needed.
1573 ** If the noContent flag is set, it means that we do not care about
1574 ** the content of the page at this time. So do not go to the disk
1575 ** to fetch the content. Just fill in the content with zeros for now.
1576 ** If in the future we call sqlite3PagerWrite() on this page, that
1577 ** means we have started to be concerned about content and the disk
1578 ** read should occur at that point.
1580 static int btreeGetPage(
1581 BtShared *pBt, /* The btree */
1582 Pgno pgno, /* Number of the page to fetch */
1583 MemPage **ppPage, /* Return the page in this parameter */
1584 int noContent, /* Do not load page content if true */
1585 int bReadonly /* True if a read-only (mmap) page is ok */
1587 int rc;
1588 DbPage *pDbPage;
1589 int flags = (noContent ? PAGER_ACQUIRE_NOCONTENT : 0)
1590 | (bReadonly ? PAGER_ACQUIRE_READONLY : 0);
1592 assert( noContent==0 || bReadonly==0 );
1593 assert( sqlite3_mutex_held(pBt->mutex) );
1594 rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, flags);
1595 if( rc ) return rc;
1596 *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
1597 return SQLITE_OK;
1601 ** Retrieve a page from the pager cache. If the requested page is not
1602 ** already in the pager cache return NULL. Initialize the MemPage.pBt and
1603 ** MemPage.aData elements if needed.
1605 static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
1606 DbPage *pDbPage;
1607 assert( sqlite3_mutex_held(pBt->mutex) );
1608 pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
1609 if( pDbPage ){
1610 return btreePageFromDbPage(pDbPage, pgno, pBt);
1612 return 0;
1616 ** Return the size of the database file in pages. If there is any kind of
1617 ** error, return ((unsigned int)-1).
1619 static Pgno btreePagecount(BtShared *pBt){
1620 return pBt->nPage;
1622 u32 sqlite3BtreeLastPage(Btree *p){
1623 assert( sqlite3BtreeHoldsMutex(p) );
1624 assert( ((p->pBt->nPage)&0x8000000)==0 );
1625 return (int)btreePagecount(p->pBt);
1629 ** Get a page from the pager and initialize it. This routine is just a
1630 ** convenience wrapper around separate calls to btreeGetPage() and
1631 ** btreeInitPage().
1633 ** If an error occurs, then the value *ppPage is set to is undefined. It
1634 ** may remain unchanged, or it may be set to an invalid value.
1636 static int getAndInitPage(
1637 BtShared *pBt, /* The database file */
1638 Pgno pgno, /* Number of the page to get */
1639 MemPage **ppPage, /* Write the page pointer here */
1640 int bReadonly /* True if a read-only (mmap) page is ok */
1642 int rc;
1643 assert( sqlite3_mutex_held(pBt->mutex) );
1645 if( pgno>btreePagecount(pBt) ){
1646 rc = SQLITE_CORRUPT_BKPT;
1647 }else{
1648 rc = btreeGetPage(pBt, pgno, ppPage, 0, bReadonly);
1649 if( rc==SQLITE_OK ){
1650 rc = btreeInitPage(*ppPage);
1651 if( rc!=SQLITE_OK ){
1652 releasePage(*ppPage);
1657 testcase( pgno==0 );
1658 assert( pgno!=0 || rc==SQLITE_CORRUPT );
1659 return rc;
1663 ** Release a MemPage. This should be called once for each prior
1664 ** call to btreeGetPage.
1666 static void releasePage(MemPage *pPage){
1667 if( pPage ){
1668 assert( pPage->aData );
1669 assert( pPage->pBt );
1670 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
1671 assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
1672 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1673 sqlite3PagerUnref(pPage->pDbPage);
1678 ** During a rollback, when the pager reloads information into the cache
1679 ** so that the cache is restored to its original state at the start of
1680 ** the transaction, for each page restored this routine is called.
1682 ** This routine needs to reset the extra data section at the end of the
1683 ** page to agree with the restored data.
1685 static void pageReinit(DbPage *pData){
1686 MemPage *pPage;
1687 pPage = (MemPage *)sqlite3PagerGetExtra(pData);
1688 assert( sqlite3PagerPageRefcount(pData)>0 );
1689 if( pPage->isInit ){
1690 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1691 pPage->isInit = 0;
1692 if( sqlite3PagerPageRefcount(pData)>1 ){
1693 /* pPage might not be a btree page; it might be an overflow page
1694 ** or ptrmap page or a free page. In those cases, the following
1695 ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
1696 ** But no harm is done by this. And it is very important that
1697 ** btreeInitPage() be called on every btree page so we make
1698 ** the call for every page that comes in for re-initing. */
1699 btreeInitPage(pPage);
1705 ** Invoke the busy handler for a btree.
1707 static int btreeInvokeBusyHandler(void *pArg){
1708 BtShared *pBt = (BtShared*)pArg;
1709 assert( pBt->db );
1710 assert( sqlite3_mutex_held(pBt->db->mutex) );
1711 return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
1715 ** Open a database file.
1717 ** zFilename is the name of the database file. If zFilename is NULL
1718 ** then an ephemeral database is created. The ephemeral database might
1719 ** be exclusively in memory, or it might use a disk-based memory cache.
1720 ** Either way, the ephemeral database will be automatically deleted
1721 ** when sqlite3BtreeClose() is called.
1723 ** If zFilename is ":memory:" then an in-memory database is created
1724 ** that is automatically destroyed when it is closed.
1726 ** The "flags" parameter is a bitmask that might contain bits like
1727 ** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY.
1729 ** If the database is already opened in the same database connection
1730 ** and we are in shared cache mode, then the open will fail with an
1731 ** SQLITE_CONSTRAINT error. We cannot allow two or more BtShared
1732 ** objects in the same database connection since doing so will lead
1733 ** to problems with locking.
1735 int sqlite3BtreeOpen(
1736 sqlite3_vfs *pVfs, /* VFS to use for this b-tree */
1737 const char *zFilename, /* Name of the file containing the BTree database */
1738 sqlite3 *db, /* Associated database handle */
1739 Btree **ppBtree, /* Pointer to new Btree object written here */
1740 int flags, /* Options */
1741 int vfsFlags /* Flags passed through to sqlite3_vfs.xOpen() */
1743 BtShared *pBt = 0; /* Shared part of btree structure */
1744 Btree *p; /* Handle to return */
1745 sqlite3_mutex *mutexOpen = 0; /* Prevents a race condition. Ticket #3537 */
1746 int rc = SQLITE_OK; /* Result code from this function */
1747 u8 nReserve; /* Byte of unused space on each page */
1748 unsigned char zDbHeader[100]; /* Database header content */
1750 /* True if opening an ephemeral, temporary database */
1751 const int isTempDb = zFilename==0 || zFilename[0]==0;
1753 /* Set the variable isMemdb to true for an in-memory database, or
1754 ** false for a file-based database.
1756 #ifdef SQLITE_OMIT_MEMORYDB
1757 const int isMemdb = 0;
1758 #else
1759 const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
1760 || (isTempDb && sqlite3TempInMemory(db))
1761 || (vfsFlags & SQLITE_OPEN_MEMORY)!=0;
1762 #endif
1764 assert( db!=0 );
1765 assert( pVfs!=0 );
1766 assert( sqlite3_mutex_held(db->mutex) );
1767 assert( (flags&0xff)==flags ); /* flags fit in 8 bits */
1769 /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
1770 assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
1772 /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
1773 assert( (flags & BTREE_SINGLE)==0 || isTempDb );
1775 if( isMemdb ){
1776 flags |= BTREE_MEMORY;
1778 if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
1779 vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
1781 p = sqlite3MallocZero(sizeof(Btree));
1782 if( !p ){
1783 return SQLITE_NOMEM;
1785 p->inTrans = TRANS_NONE;
1786 p->db = db;
1787 #ifndef SQLITE_OMIT_SHARED_CACHE
1788 p->lock.pBtree = p;
1789 p->lock.iTable = 1;
1790 #endif
1792 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
1794 ** If this Btree is a candidate for shared cache, try to find an
1795 ** existing BtShared object that we can share with
1797 if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){
1798 if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
1799 int nFullPathname = pVfs->mxPathname+1;
1800 char *zFullPathname = sqlite3Malloc(nFullPathname);
1801 MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
1802 p->sharable = 1;
1803 if( !zFullPathname ){
1804 sqlite3_free(p);
1805 return SQLITE_NOMEM;
1807 if( isMemdb ){
1808 memcpy(zFullPathname, zFilename, sqlite3Strlen30(zFilename)+1);
1809 }else{
1810 rc = sqlite3OsFullPathname(pVfs, zFilename,
1811 nFullPathname, zFullPathname);
1812 if( rc ){
1813 sqlite3_free(zFullPathname);
1814 sqlite3_free(p);
1815 return rc;
1818 #if SQLITE_THREADSAFE
1819 mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
1820 sqlite3_mutex_enter(mutexOpen);
1821 mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
1822 sqlite3_mutex_enter(mutexShared);
1823 #endif
1824 for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
1825 assert( pBt->nRef>0 );
1826 if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0))
1827 && sqlite3PagerVfs(pBt->pPager)==pVfs ){
1828 int iDb;
1829 for(iDb=db->nDb-1; iDb>=0; iDb--){
1830 Btree *pExisting = db->aDb[iDb].pBt;
1831 if( pExisting && pExisting->pBt==pBt ){
1832 sqlite3_mutex_leave(mutexShared);
1833 sqlite3_mutex_leave(mutexOpen);
1834 sqlite3_free(zFullPathname);
1835 sqlite3_free(p);
1836 return SQLITE_CONSTRAINT;
1839 p->pBt = pBt;
1840 pBt->nRef++;
1841 break;
1844 sqlite3_mutex_leave(mutexShared);
1845 sqlite3_free(zFullPathname);
1847 #ifdef SQLITE_DEBUG
1848 else{
1849 /* In debug mode, we mark all persistent databases as sharable
1850 ** even when they are not. This exercises the locking code and
1851 ** gives more opportunity for asserts(sqlite3_mutex_held())
1852 ** statements to find locking problems.
1854 p->sharable = 1;
1856 #endif
1858 #endif
1859 if( pBt==0 ){
1861 ** The following asserts make sure that structures used by the btree are
1862 ** the right size. This is to guard against size changes that result
1863 ** when compiling on a different architecture.
1865 assert( sizeof(i64)==8 || sizeof(i64)==4 );
1866 assert( sizeof(u64)==8 || sizeof(u64)==4 );
1867 assert( sizeof(u32)==4 );
1868 assert( sizeof(u16)==2 );
1869 assert( sizeof(Pgno)==4 );
1871 pBt = sqlite3MallocZero( sizeof(*pBt) );
1872 if( pBt==0 ){
1873 rc = SQLITE_NOMEM;
1874 goto btree_open_out;
1876 rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
1877 EXTRA_SIZE, flags, vfsFlags, pageReinit);
1878 if( rc==SQLITE_OK ){
1879 sqlite3PagerSetMmapLimit(pBt->pPager, db->szMmap);
1880 rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
1882 if( rc!=SQLITE_OK ){
1883 goto btree_open_out;
1885 pBt->openFlags = (u8)flags;
1886 pBt->db = db;
1887 sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
1888 p->pBt = pBt;
1890 pBt->pCursor = 0;
1891 pBt->pPage1 = 0;
1892 if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY;
1893 #ifdef SQLITE_SECURE_DELETE
1894 pBt->btsFlags |= BTS_SECURE_DELETE;
1895 #endif
1896 pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
1897 if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
1898 || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
1899 pBt->pageSize = 0;
1900 #ifndef SQLITE_OMIT_AUTOVACUUM
1901 /* If the magic name ":memory:" will create an in-memory database, then
1902 ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
1903 ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
1904 ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
1905 ** regular file-name. In this case the auto-vacuum applies as per normal.
1907 if( zFilename && !isMemdb ){
1908 pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
1909 pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
1911 #endif
1912 nReserve = 0;
1913 }else{
1914 nReserve = zDbHeader[20];
1915 pBt->btsFlags |= BTS_PAGESIZE_FIXED;
1916 #ifndef SQLITE_OMIT_AUTOVACUUM
1917 pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
1918 pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
1919 #endif
1921 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
1922 if( rc ) goto btree_open_out;
1923 pBt->usableSize = pBt->pageSize - nReserve;
1924 assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */
1926 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
1927 /* Add the new BtShared object to the linked list sharable BtShareds.
1929 if( p->sharable ){
1930 MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
1931 pBt->nRef = 1;
1932 MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);)
1933 if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
1934 pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
1935 if( pBt->mutex==0 ){
1936 rc = SQLITE_NOMEM;
1937 db->mallocFailed = 0;
1938 goto btree_open_out;
1941 sqlite3_mutex_enter(mutexShared);
1942 pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
1943 GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
1944 sqlite3_mutex_leave(mutexShared);
1946 #endif
1949 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
1950 /* If the new Btree uses a sharable pBtShared, then link the new
1951 ** Btree into the list of all sharable Btrees for the same connection.
1952 ** The list is kept in ascending order by pBt address.
1954 if( p->sharable ){
1955 int i;
1956 Btree *pSib;
1957 for(i=0; i<db->nDb; i++){
1958 if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
1959 while( pSib->pPrev ){ pSib = pSib->pPrev; }
1960 if( p->pBt<pSib->pBt ){
1961 p->pNext = pSib;
1962 p->pPrev = 0;
1963 pSib->pPrev = p;
1964 }else{
1965 while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
1966 pSib = pSib->pNext;
1968 p->pNext = pSib->pNext;
1969 p->pPrev = pSib;
1970 if( p->pNext ){
1971 p->pNext->pPrev = p;
1973 pSib->pNext = p;
1975 break;
1979 #endif
1980 *ppBtree = p;
1982 btree_open_out:
1983 if( rc!=SQLITE_OK ){
1984 if( pBt && pBt->pPager ){
1985 sqlite3PagerClose(pBt->pPager);
1987 sqlite3_free(pBt);
1988 sqlite3_free(p);
1989 *ppBtree = 0;
1990 }else{
1991 /* If the B-Tree was successfully opened, set the pager-cache size to the
1992 ** default value. Except, when opening on an existing shared pager-cache,
1993 ** do not change the pager-cache size.
1995 if( sqlite3BtreeSchema(p, 0, 0)==0 ){
1996 sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);
1999 if( mutexOpen ){
2000 assert( sqlite3_mutex_held(mutexOpen) );
2001 sqlite3_mutex_leave(mutexOpen);
2003 return rc;
2007 ** Decrement the BtShared.nRef counter. When it reaches zero,
2008 ** remove the BtShared structure from the sharing list. Return
2009 ** true if the BtShared.nRef counter reaches zero and return
2010 ** false if it is still positive.
2012 static int removeFromSharingList(BtShared *pBt){
2013 #ifndef SQLITE_OMIT_SHARED_CACHE
2014 MUTEX_LOGIC( sqlite3_mutex *pMaster; )
2015 BtShared *pList;
2016 int removed = 0;
2018 assert( sqlite3_mutex_notheld(pBt->mutex) );
2019 MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
2020 sqlite3_mutex_enter(pMaster);
2021 pBt->nRef--;
2022 if( pBt->nRef<=0 ){
2023 if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
2024 GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
2025 }else{
2026 pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
2027 while( ALWAYS(pList) && pList->pNext!=pBt ){
2028 pList=pList->pNext;
2030 if( ALWAYS(pList) ){
2031 pList->pNext = pBt->pNext;
2034 if( SQLITE_THREADSAFE ){
2035 sqlite3_mutex_free(pBt->mutex);
2037 removed = 1;
2039 sqlite3_mutex_leave(pMaster);
2040 return removed;
2041 #else
2042 return 1;
2043 #endif
2047 ** Make sure pBt->pTmpSpace points to an allocation of
2048 ** MX_CELL_SIZE(pBt) bytes.
2050 static void allocateTempSpace(BtShared *pBt){
2051 if( !pBt->pTmpSpace ){
2052 pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
2057 ** Free the pBt->pTmpSpace allocation
2059 static void freeTempSpace(BtShared *pBt){
2060 sqlite3PageFree( pBt->pTmpSpace);
2061 pBt->pTmpSpace = 0;
2065 ** Close an open database and invalidate all cursors.
2067 int sqlite3BtreeClose(Btree *p){
2068 BtShared *pBt = p->pBt;
2069 BtCursor *pCur;
2071 /* Close all cursors opened via this handle. */
2072 assert( sqlite3_mutex_held(p->db->mutex) );
2073 sqlite3BtreeEnter(p);
2074 pCur = pBt->pCursor;
2075 while( pCur ){
2076 BtCursor *pTmp = pCur;
2077 pCur = pCur->pNext;
2078 if( pTmp->pBtree==p ){
2079 sqlite3BtreeCloseCursor(pTmp);
2083 /* Rollback any active transaction and free the handle structure.
2084 ** The call to sqlite3BtreeRollback() drops any table-locks held by
2085 ** this handle.
2087 sqlite3BtreeRollback(p, SQLITE_OK);
2088 sqlite3BtreeLeave(p);
2090 /* If there are still other outstanding references to the shared-btree
2091 ** structure, return now. The remainder of this procedure cleans
2092 ** up the shared-btree.
2094 assert( p->wantToLock==0 && p->locked==0 );
2095 if( !p->sharable || removeFromSharingList(pBt) ){
2096 /* The pBt is no longer on the sharing list, so we can access
2097 ** it without having to hold the mutex.
2099 ** Clean out and delete the BtShared object.
2101 assert( !pBt->pCursor );
2102 sqlite3PagerClose(pBt->pPager);
2103 if( pBt->xFreeSchema && pBt->pSchema ){
2104 pBt->xFreeSchema(pBt->pSchema);
2106 sqlite3DbFree(0, pBt->pSchema);
2107 freeTempSpace(pBt);
2108 sqlite3_free(pBt);
2111 #ifndef SQLITE_OMIT_SHARED_CACHE
2112 assert( p->wantToLock==0 );
2113 assert( p->locked==0 );
2114 if( p->pPrev ) p->pPrev->pNext = p->pNext;
2115 if( p->pNext ) p->pNext->pPrev = p->pPrev;
2116 #endif
2118 sqlite3_free(p);
2119 return SQLITE_OK;
2123 ** Change the limit on the number of pages allowed in the cache.
2125 ** The maximum number of cache pages is set to the absolute
2126 ** value of mxPage. If mxPage is negative, the pager will
2127 ** operate asynchronously - it will not stop to do fsync()s
2128 ** to insure data is written to the disk surface before
2129 ** continuing. Transactions still work if synchronous is off,
2130 ** and the database cannot be corrupted if this program
2131 ** crashes. But if the operating system crashes or there is
2132 ** an abrupt power failure when synchronous is off, the database
2133 ** could be left in an inconsistent and unrecoverable state.
2134 ** Synchronous is on by default so database corruption is not
2135 ** normally a worry.
2137 int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
2138 BtShared *pBt = p->pBt;
2139 assert( sqlite3_mutex_held(p->db->mutex) );
2140 sqlite3BtreeEnter(p);
2141 sqlite3PagerSetCachesize(pBt->pPager, mxPage);
2142 sqlite3BtreeLeave(p);
2143 return SQLITE_OK;
2147 ** Change the limit on the amount of the database file that may be
2148 ** memory mapped.
2150 int sqlite3BtreeSetMmapLimit(Btree *p, sqlite3_int64 szMmap){
2151 BtShared *pBt = p->pBt;
2152 assert( sqlite3_mutex_held(p->db->mutex) );
2153 sqlite3BtreeEnter(p);
2154 sqlite3PagerSetMmapLimit(pBt->pPager, szMmap);
2155 sqlite3BtreeLeave(p);
2156 return SQLITE_OK;
2160 ** Change the way data is synced to disk in order to increase or decrease
2161 ** how well the database resists damage due to OS crashes and power
2162 ** failures. Level 1 is the same as asynchronous (no syncs() occur and
2163 ** there is a high probability of damage) Level 2 is the default. There
2164 ** is a very low but non-zero probability of damage. Level 3 reduces the
2165 ** probability of damage to near zero but with a write performance reduction.
2167 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
2168 int sqlite3BtreeSetSafetyLevel(
2169 Btree *p, /* The btree to set the safety level on */
2170 int level, /* PRAGMA synchronous. 1=OFF, 2=NORMAL, 3=FULL */
2171 int fullSync, /* PRAGMA fullfsync. */
2172 int ckptFullSync /* PRAGMA checkpoint_fullfync */
2174 BtShared *pBt = p->pBt;
2175 assert( sqlite3_mutex_held(p->db->mutex) );
2176 assert( level>=1 && level<=3 );
2177 sqlite3BtreeEnter(p);
2178 sqlite3PagerSetSafetyLevel(pBt->pPager, level, fullSync, ckptFullSync);
2179 sqlite3BtreeLeave(p);
2180 return SQLITE_OK;
2182 #endif
2185 ** Return TRUE if the given btree is set to safety level 1. In other
2186 ** words, return TRUE if no sync() occurs on the disk files.
2188 int sqlite3BtreeSyncDisabled(Btree *p){
2189 BtShared *pBt = p->pBt;
2190 int rc;
2191 assert( sqlite3_mutex_held(p->db->mutex) );
2192 sqlite3BtreeEnter(p);
2193 assert( pBt && pBt->pPager );
2194 rc = sqlite3PagerNosync(pBt->pPager);
2195 sqlite3BtreeLeave(p);
2196 return rc;
2200 ** Change the default pages size and the number of reserved bytes per page.
2201 ** Or, if the page size has already been fixed, return SQLITE_READONLY
2202 ** without changing anything.
2204 ** The page size must be a power of 2 between 512 and 65536. If the page
2205 ** size supplied does not meet this constraint then the page size is not
2206 ** changed.
2208 ** Page sizes are constrained to be a power of two so that the region
2209 ** of the database file used for locking (beginning at PENDING_BYTE,
2210 ** the first byte past the 1GB boundary, 0x40000000) needs to occur
2211 ** at the beginning of a page.
2213 ** If parameter nReserve is less than zero, then the number of reserved
2214 ** bytes per page is left unchanged.
2216 ** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size
2217 ** and autovacuum mode can no longer be changed.
2219 int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
2220 int rc = SQLITE_OK;
2221 BtShared *pBt = p->pBt;
2222 assert( nReserve>=-1 && nReserve<=255 );
2223 sqlite3BtreeEnter(p);
2224 if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){
2225 sqlite3BtreeLeave(p);
2226 return SQLITE_READONLY;
2228 if( nReserve<0 ){
2229 nReserve = pBt->pageSize - pBt->usableSize;
2231 assert( nReserve>=0 && nReserve<=255 );
2232 if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
2233 ((pageSize-1)&pageSize)==0 ){
2234 assert( (pageSize & 7)==0 );
2235 assert( !pBt->pPage1 && !pBt->pCursor );
2236 pBt->pageSize = (u32)pageSize;
2237 freeTempSpace(pBt);
2239 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
2240 pBt->usableSize = pBt->pageSize - (u16)nReserve;
2241 if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED;
2242 sqlite3BtreeLeave(p);
2243 return rc;
2247 ** Return the currently defined page size
2249 int sqlite3BtreeGetPageSize(Btree *p){
2250 return p->pBt->pageSize;
2253 #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_DEBUG)
2255 ** This function is similar to sqlite3BtreeGetReserve(), except that it
2256 ** may only be called if it is guaranteed that the b-tree mutex is already
2257 ** held.
2259 ** This is useful in one special case in the backup API code where it is
2260 ** known that the shared b-tree mutex is held, but the mutex on the
2261 ** database handle that owns *p is not. In this case if sqlite3BtreeEnter()
2262 ** were to be called, it might collide with some other operation on the
2263 ** database handle that owns *p, causing undefined behavior.
2265 int sqlite3BtreeGetReserveNoMutex(Btree *p){
2266 assert( sqlite3_mutex_held(p->pBt->mutex) );
2267 return p->pBt->pageSize - p->pBt->usableSize;
2269 #endif /* SQLITE_HAS_CODEC || SQLITE_DEBUG */
2271 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
2273 ** Return the number of bytes of space at the end of every page that
2274 ** are intentually left unused. This is the "reserved" space that is
2275 ** sometimes used by extensions.
2277 int sqlite3BtreeGetReserve(Btree *p){
2278 int n;
2279 sqlite3BtreeEnter(p);
2280 n = p->pBt->pageSize - p->pBt->usableSize;
2281 sqlite3BtreeLeave(p);
2282 return n;
2286 ** Set the maximum page count for a database if mxPage is positive.
2287 ** No changes are made if mxPage is 0 or negative.
2288 ** Regardless of the value of mxPage, return the maximum page count.
2290 int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
2291 int n;
2292 sqlite3BtreeEnter(p);
2293 n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
2294 sqlite3BtreeLeave(p);
2295 return n;
2299 ** Set the BTS_SECURE_DELETE flag if newFlag is 0 or 1. If newFlag is -1,
2300 ** then make no changes. Always return the value of the BTS_SECURE_DELETE
2301 ** setting after the change.
2303 int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
2304 int b;
2305 if( p==0 ) return 0;
2306 sqlite3BtreeEnter(p);
2307 if( newFlag>=0 ){
2308 p->pBt->btsFlags &= ~BTS_SECURE_DELETE;
2309 if( newFlag ) p->pBt->btsFlags |= BTS_SECURE_DELETE;
2311 b = (p->pBt->btsFlags & BTS_SECURE_DELETE)!=0;
2312 sqlite3BtreeLeave(p);
2313 return b;
2315 #endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
2318 ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
2319 ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
2320 ** is disabled. The default value for the auto-vacuum property is
2321 ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
2323 int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
2324 #ifdef SQLITE_OMIT_AUTOVACUUM
2325 return SQLITE_READONLY;
2326 #else
2327 BtShared *pBt = p->pBt;
2328 int rc = SQLITE_OK;
2329 u8 av = (u8)autoVacuum;
2331 sqlite3BtreeEnter(p);
2332 if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){
2333 rc = SQLITE_READONLY;
2334 }else{
2335 pBt->autoVacuum = av ?1:0;
2336 pBt->incrVacuum = av==2 ?1:0;
2338 sqlite3BtreeLeave(p);
2339 return rc;
2340 #endif
2344 ** Return the value of the 'auto-vacuum' property. If auto-vacuum is
2345 ** enabled 1 is returned. Otherwise 0.
2347 int sqlite3BtreeGetAutoVacuum(Btree *p){
2348 #ifdef SQLITE_OMIT_AUTOVACUUM
2349 return BTREE_AUTOVACUUM_NONE;
2350 #else
2351 int rc;
2352 sqlite3BtreeEnter(p);
2353 rc = (
2354 (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
2355 (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
2356 BTREE_AUTOVACUUM_INCR
2358 sqlite3BtreeLeave(p);
2359 return rc;
2360 #endif
2365 ** Get a reference to pPage1 of the database file. This will
2366 ** also acquire a readlock on that file.
2368 ** SQLITE_OK is returned on success. If the file is not a
2369 ** well-formed database file, then SQLITE_CORRUPT is returned.
2370 ** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
2371 ** is returned if we run out of memory.
2373 static int lockBtree(BtShared *pBt){
2374 int rc; /* Result code from subfunctions */
2375 MemPage *pPage1; /* Page 1 of the database file */
2376 int nPage; /* Number of pages in the database */
2377 int nPageFile = 0; /* Number of pages in the database file */
2378 int nPageHeader; /* Number of pages in the database according to hdr */
2380 assert( sqlite3_mutex_held(pBt->mutex) );
2381 assert( pBt->pPage1==0 );
2382 rc = sqlite3PagerSharedLock(pBt->pPager);
2383 if( rc!=SQLITE_OK ) return rc;
2384 rc = btreeGetPage(pBt, 1, &pPage1, 0, 0);
2385 if( rc!=SQLITE_OK ) return rc;
2387 /* Do some checking to help insure the file we opened really is
2388 ** a valid database file.
2390 nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
2391 sqlite3PagerPagecount(pBt->pPager, &nPageFile);
2392 if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
2393 nPage = nPageFile;
2395 if( nPage>0 ){
2396 u32 pageSize;
2397 u32 usableSize;
2398 u8 *page1 = pPage1->aData;
2399 rc = SQLITE_NOTADB;
2400 if( memcmp(page1, zMagicHeader, 16)!=0 ){
2401 goto page1_init_failed;
2404 #ifdef SQLITE_OMIT_WAL
2405 if( page1[18]>1 ){
2406 pBt->btsFlags |= BTS_READ_ONLY;
2408 if( page1[19]>1 ){
2409 goto page1_init_failed;
2411 #else
2412 if( page1[18]>2 ){
2413 pBt->btsFlags |= BTS_READ_ONLY;
2415 if( page1[19]>2 ){
2416 goto page1_init_failed;
2419 /* If the write version is set to 2, this database should be accessed
2420 ** in WAL mode. If the log is not already open, open it now. Then
2421 ** return SQLITE_OK and return without populating BtShared.pPage1.
2422 ** The caller detects this and calls this function again. This is
2423 ** required as the version of page 1 currently in the page1 buffer
2424 ** may not be the latest version - there may be a newer one in the log
2425 ** file.
2427 if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
2428 int isOpen = 0;
2429 rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
2430 if( rc!=SQLITE_OK ){
2431 goto page1_init_failed;
2432 }else if( isOpen==0 ){
2433 releasePage(pPage1);
2434 return SQLITE_OK;
2436 rc = SQLITE_NOTADB;
2438 #endif
2440 /* The maximum embedded fraction must be exactly 25%. And the minimum
2441 ** embedded fraction must be 12.5% for both leaf-data and non-leaf-data.
2442 ** The original design allowed these amounts to vary, but as of
2443 ** version 3.6.0, we require them to be fixed.
2445 if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
2446 goto page1_init_failed;
2448 pageSize = (page1[16]<<8) | (page1[17]<<16);
2449 if( ((pageSize-1)&pageSize)!=0
2450 || pageSize>SQLITE_MAX_PAGE_SIZE
2451 || pageSize<=256
2453 goto page1_init_failed;
2455 assert( (pageSize & 7)==0 );
2456 usableSize = pageSize - page1[20];
2457 if( (u32)pageSize!=pBt->pageSize ){
2458 /* After reading the first page of the database assuming a page size
2459 ** of BtShared.pageSize, we have discovered that the page-size is
2460 ** actually pageSize. Unlock the database, leave pBt->pPage1 at
2461 ** zero and return SQLITE_OK. The caller will call this function
2462 ** again with the correct page-size.
2464 releasePage(pPage1);
2465 pBt->usableSize = usableSize;
2466 pBt->pageSize = pageSize;
2467 freeTempSpace(pBt);
2468 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
2469 pageSize-usableSize);
2470 return rc;
2472 if( (pBt->db->flags & SQLITE_RecoveryMode)==0 && nPage>nPageFile ){
2473 rc = SQLITE_CORRUPT_BKPT;
2474 goto page1_init_failed;
2476 if( usableSize<480 ){
2477 goto page1_init_failed;
2479 pBt->pageSize = pageSize;
2480 pBt->usableSize = usableSize;
2481 #ifndef SQLITE_OMIT_AUTOVACUUM
2482 pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
2483 pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
2484 #endif
2487 /* maxLocal is the maximum amount of payload to store locally for
2488 ** a cell. Make sure it is small enough so that at least minFanout
2489 ** cells can will fit on one page. We assume a 10-byte page header.
2490 ** Besides the payload, the cell must store:
2491 ** 2-byte pointer to the cell
2492 ** 4-byte child pointer
2493 ** 9-byte nKey value
2494 ** 4-byte nData value
2495 ** 4-byte overflow page pointer
2496 ** So a cell consists of a 2-byte pointer, a header which is as much as
2497 ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
2498 ** page pointer.
2500 pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
2501 pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
2502 pBt->maxLeaf = (u16)(pBt->usableSize - 35);
2503 pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
2504 if( pBt->maxLocal>127 ){
2505 pBt->max1bytePayload = 127;
2506 }else{
2507 pBt->max1bytePayload = (u8)pBt->maxLocal;
2509 assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
2510 pBt->pPage1 = pPage1;
2511 pBt->nPage = nPage;
2512 return SQLITE_OK;
2514 page1_init_failed:
2515 releasePage(pPage1);
2516 pBt->pPage1 = 0;
2517 return rc;
2520 #ifndef NDEBUG
2522 ** Return the number of cursors open on pBt. This is for use
2523 ** in assert() expressions, so it is only compiled if NDEBUG is not
2524 ** defined.
2526 ** Only write cursors are counted if wrOnly is true. If wrOnly is
2527 ** false then all cursors are counted.
2529 ** For the purposes of this routine, a cursor is any cursor that
2530 ** is capable of reading or writing to the databse. Cursors that
2531 ** have been tripped into the CURSOR_FAULT state are not counted.
2533 static int countValidCursors(BtShared *pBt, int wrOnly){
2534 BtCursor *pCur;
2535 int r = 0;
2536 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
2537 if( (wrOnly==0 || pCur->wrFlag) && pCur->eState!=CURSOR_FAULT ) r++;
2539 return r;
2541 #endif
2544 ** If there are no outstanding cursors and we are not in the middle
2545 ** of a transaction but there is a read lock on the database, then
2546 ** this routine unrefs the first page of the database file which
2547 ** has the effect of releasing the read lock.
2549 ** If there is a transaction in progress, this routine is a no-op.
2551 static void unlockBtreeIfUnused(BtShared *pBt){
2552 assert( sqlite3_mutex_held(pBt->mutex) );
2553 assert( countValidCursors(pBt,0)==0 || pBt->inTransaction>TRANS_NONE );
2554 if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
2555 assert( pBt->pPage1->aData );
2556 assert( sqlite3PagerRefcount(pBt->pPager)==1 );
2557 assert( pBt->pPage1->aData );
2558 releasePage(pBt->pPage1);
2559 pBt->pPage1 = 0;
2564 ** If pBt points to an empty file then convert that empty file
2565 ** into a new empty database by initializing the first page of
2566 ** the database.
2568 static int newDatabase(BtShared *pBt){
2569 MemPage *pP1;
2570 unsigned char *data;
2571 int rc;
2573 assert( sqlite3_mutex_held(pBt->mutex) );
2574 if( pBt->nPage>0 ){
2575 return SQLITE_OK;
2577 pP1 = pBt->pPage1;
2578 assert( pP1!=0 );
2579 data = pP1->aData;
2580 rc = sqlite3PagerWrite(pP1->pDbPage);
2581 if( rc ) return rc;
2582 memcpy(data, zMagicHeader, sizeof(zMagicHeader));
2583 assert( sizeof(zMagicHeader)==16 );
2584 data[16] = (u8)((pBt->pageSize>>8)&0xff);
2585 data[17] = (u8)((pBt->pageSize>>16)&0xff);
2586 data[18] = 1;
2587 data[19] = 1;
2588 assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
2589 data[20] = (u8)(pBt->pageSize - pBt->usableSize);
2590 data[21] = 64;
2591 data[22] = 32;
2592 data[23] = 32;
2593 memset(&data[24], 0, 100-24);
2594 zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
2595 pBt->btsFlags |= BTS_PAGESIZE_FIXED;
2596 #ifndef SQLITE_OMIT_AUTOVACUUM
2597 assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
2598 assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
2599 put4byte(&data[36 + 4*4], pBt->autoVacuum);
2600 put4byte(&data[36 + 7*4], pBt->incrVacuum);
2601 #endif
2602 pBt->nPage = 1;
2603 data[31] = 1;
2604 return SQLITE_OK;
2608 ** Initialize the first page of the database file (creating a database
2609 ** consisting of a single page and no schema objects). Return SQLITE_OK
2610 ** if successful, or an SQLite error code otherwise.
2612 int sqlite3BtreeNewDb(Btree *p){
2613 int rc;
2614 sqlite3BtreeEnter(p);
2615 p->pBt->nPage = 0;
2616 rc = newDatabase(p->pBt);
2617 sqlite3BtreeLeave(p);
2618 return rc;
2622 ** Attempt to start a new transaction. A write-transaction
2623 ** is started if the second argument is nonzero, otherwise a read-
2624 ** transaction. If the second argument is 2 or more and exclusive
2625 ** transaction is started, meaning that no other process is allowed
2626 ** to access the database. A preexisting transaction may not be
2627 ** upgraded to exclusive by calling this routine a second time - the
2628 ** exclusivity flag only works for a new transaction.
2630 ** A write-transaction must be started before attempting any
2631 ** changes to the database. None of the following routines
2632 ** will work unless a transaction is started first:
2634 ** sqlite3BtreeCreateTable()
2635 ** sqlite3BtreeCreateIndex()
2636 ** sqlite3BtreeClearTable()
2637 ** sqlite3BtreeDropTable()
2638 ** sqlite3BtreeInsert()
2639 ** sqlite3BtreeDelete()
2640 ** sqlite3BtreeUpdateMeta()
2642 ** If an initial attempt to acquire the lock fails because of lock contention
2643 ** and the database was previously unlocked, then invoke the busy handler
2644 ** if there is one. But if there was previously a read-lock, do not
2645 ** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is
2646 ** returned when there is already a read-lock in order to avoid a deadlock.
2648 ** Suppose there are two processes A and B. A has a read lock and B has
2649 ** a reserved lock. B tries to promote to exclusive but is blocked because
2650 ** of A's read lock. A tries to promote to reserved but is blocked by B.
2651 ** One or the other of the two processes must give way or there can be
2652 ** no progress. By returning SQLITE_BUSY and not invoking the busy callback
2653 ** when A already has a read lock, we encourage A to give up and let B
2654 ** proceed.
2656 int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
2657 sqlite3 *pBlock = 0;
2658 BtShared *pBt = p->pBt;
2659 int rc = SQLITE_OK;
2661 sqlite3BtreeEnter(p);
2662 btreeIntegrity(p);
2664 /* If the btree is already in a write-transaction, or it
2665 ** is already in a read-transaction and a read-transaction
2666 ** is requested, this is a no-op.
2668 if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
2669 goto trans_begun;
2671 assert( IfNotOmitAV(pBt->bDoTruncate)==0 );
2673 /* Write transactions are not possible on a read-only database */
2674 if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){
2675 rc = SQLITE_READONLY;
2676 goto trans_begun;
2679 #ifndef SQLITE_OMIT_SHARED_CACHE
2680 /* If another database handle has already opened a write transaction
2681 ** on this shared-btree structure and a second write transaction is
2682 ** requested, return SQLITE_LOCKED.
2684 if( (wrflag && pBt->inTransaction==TRANS_WRITE)
2685 || (pBt->btsFlags & BTS_PENDING)!=0
2687 pBlock = pBt->pWriter->db;
2688 }else if( wrflag>1 ){
2689 BtLock *pIter;
2690 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
2691 if( pIter->pBtree!=p ){
2692 pBlock = pIter->pBtree->db;
2693 break;
2697 if( pBlock ){
2698 sqlite3ConnectionBlocked(p->db, pBlock);
2699 rc = SQLITE_LOCKED_SHAREDCACHE;
2700 goto trans_begun;
2702 #endif
2704 /* Any read-only or read-write transaction implies a read-lock on
2705 ** page 1. So if some other shared-cache client already has a write-lock
2706 ** on page 1, the transaction cannot be opened. */
2707 rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
2708 if( SQLITE_OK!=rc ) goto trans_begun;
2710 pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;
2711 if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;
2712 do {
2713 /* Call lockBtree() until either pBt->pPage1 is populated or
2714 ** lockBtree() returns something other than SQLITE_OK. lockBtree()
2715 ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
2716 ** reading page 1 it discovers that the page-size of the database
2717 ** file is not pBt->pageSize. In this case lockBtree() will update
2718 ** pBt->pageSize to the page-size of the file on disk.
2720 while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
2722 if( rc==SQLITE_OK && wrflag ){
2723 if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){
2724 rc = SQLITE_READONLY;
2725 }else{
2726 rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
2727 if( rc==SQLITE_OK ){
2728 rc = newDatabase(pBt);
2733 if( rc!=SQLITE_OK ){
2734 unlockBtreeIfUnused(pBt);
2736 }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
2737 btreeInvokeBusyHandler(pBt) );
2739 if( rc==SQLITE_OK ){
2740 if( p->inTrans==TRANS_NONE ){
2741 pBt->nTransaction++;
2742 #ifndef SQLITE_OMIT_SHARED_CACHE
2743 if( p->sharable ){
2744 assert( p->lock.pBtree==p && p->lock.iTable==1 );
2745 p->lock.eLock = READ_LOCK;
2746 p->lock.pNext = pBt->pLock;
2747 pBt->pLock = &p->lock;
2749 #endif
2751 p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
2752 if( p->inTrans>pBt->inTransaction ){
2753 pBt->inTransaction = p->inTrans;
2755 if( wrflag ){
2756 MemPage *pPage1 = pBt->pPage1;
2757 #ifndef SQLITE_OMIT_SHARED_CACHE
2758 assert( !pBt->pWriter );
2759 pBt->pWriter = p;
2760 pBt->btsFlags &= ~BTS_EXCLUSIVE;
2761 if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;
2762 #endif
2764 /* If the db-size header field is incorrect (as it may be if an old
2765 ** client has been writing the database file), update it now. Doing
2766 ** this sooner rather than later means the database size can safely
2767 ** re-read the database size from page 1 if a savepoint or transaction
2768 ** rollback occurs within the transaction.
2770 if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
2771 rc = sqlite3PagerWrite(pPage1->pDbPage);
2772 if( rc==SQLITE_OK ){
2773 put4byte(&pPage1->aData[28], pBt->nPage);
2780 trans_begun:
2781 if( rc==SQLITE_OK && wrflag ){
2782 /* This call makes sure that the pager has the correct number of
2783 ** open savepoints. If the second parameter is greater than 0 and
2784 ** the sub-journal is not already open, then it will be opened here.
2786 rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
2789 btreeIntegrity(p);
2790 sqlite3BtreeLeave(p);
2791 return rc;
2794 #ifndef SQLITE_OMIT_AUTOVACUUM
2797 ** Set the pointer-map entries for all children of page pPage. Also, if
2798 ** pPage contains cells that point to overflow pages, set the pointer
2799 ** map entries for the overflow pages as well.
2801 static int setChildPtrmaps(MemPage *pPage){
2802 int i; /* Counter variable */
2803 int nCell; /* Number of cells in page pPage */
2804 int rc; /* Return code */
2805 BtShared *pBt = pPage->pBt;
2806 u8 isInitOrig = pPage->isInit;
2807 Pgno pgno = pPage->pgno;
2809 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
2810 rc = btreeInitPage(pPage);
2811 if( rc!=SQLITE_OK ){
2812 goto set_child_ptrmaps_out;
2814 nCell = pPage->nCell;
2816 for(i=0; i<nCell; i++){
2817 u8 *pCell = findCell(pPage, i);
2819 ptrmapPutOvflPtr(pPage, pCell, &rc);
2821 if( !pPage->leaf ){
2822 Pgno childPgno = get4byte(pCell);
2823 ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
2827 if( !pPage->leaf ){
2828 Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
2829 ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
2832 set_child_ptrmaps_out:
2833 pPage->isInit = isInitOrig;
2834 return rc;
2838 ** Somewhere on pPage is a pointer to page iFrom. Modify this pointer so
2839 ** that it points to iTo. Parameter eType describes the type of pointer to
2840 ** be modified, as follows:
2842 ** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child
2843 ** page of pPage.
2845 ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
2846 ** page pointed to by one of the cells on pPage.
2848 ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
2849 ** overflow page in the list.
2851 static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
2852 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
2853 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
2854 if( eType==PTRMAP_OVERFLOW2 ){
2855 /* The pointer is always the first 4 bytes of the page in this case. */
2856 if( get4byte(pPage->aData)!=iFrom ){
2857 return SQLITE_CORRUPT_BKPT;
2859 put4byte(pPage->aData, iTo);
2860 }else{
2861 u8 isInitOrig = pPage->isInit;
2862 int i;
2863 int nCell;
2865 btreeInitPage(pPage);
2866 nCell = pPage->nCell;
2868 for(i=0; i<nCell; i++){
2869 u8 *pCell = findCell(pPage, i);
2870 if( eType==PTRMAP_OVERFLOW1 ){
2871 CellInfo info;
2872 btreeParseCellPtr(pPage, pCell, &info);
2873 if( info.iOverflow
2874 && pCell+info.iOverflow+3<=pPage->aData+pPage->maskPage
2875 && iFrom==get4byte(&pCell[info.iOverflow])
2877 put4byte(&pCell[info.iOverflow], iTo);
2878 break;
2880 }else{
2881 if( get4byte(pCell)==iFrom ){
2882 put4byte(pCell, iTo);
2883 break;
2888 if( i==nCell ){
2889 if( eType!=PTRMAP_BTREE ||
2890 get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
2891 return SQLITE_CORRUPT_BKPT;
2893 put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
2896 pPage->isInit = isInitOrig;
2898 return SQLITE_OK;
2903 ** Move the open database page pDbPage to location iFreePage in the
2904 ** database. The pDbPage reference remains valid.
2906 ** The isCommit flag indicates that there is no need to remember that
2907 ** the journal needs to be sync()ed before database page pDbPage->pgno
2908 ** can be written to. The caller has already promised not to write to that
2909 ** page.
2911 static int relocatePage(
2912 BtShared *pBt, /* Btree */
2913 MemPage *pDbPage, /* Open page to move */
2914 u8 eType, /* Pointer map 'type' entry for pDbPage */
2915 Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */
2916 Pgno iFreePage, /* The location to move pDbPage to */
2917 int isCommit /* isCommit flag passed to sqlite3PagerMovepage */
2919 MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */
2920 Pgno iDbPage = pDbPage->pgno;
2921 Pager *pPager = pBt->pPager;
2922 int rc;
2924 assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
2925 eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
2926 assert( sqlite3_mutex_held(pBt->mutex) );
2927 assert( pDbPage->pBt==pBt );
2929 /* Move page iDbPage from its current location to page number iFreePage */
2930 TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
2931 iDbPage, iFreePage, iPtrPage, eType));
2932 rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
2933 if( rc!=SQLITE_OK ){
2934 return rc;
2936 pDbPage->pgno = iFreePage;
2938 /* If pDbPage was a btree-page, then it may have child pages and/or cells
2939 ** that point to overflow pages. The pointer map entries for all these
2940 ** pages need to be changed.
2942 ** If pDbPage is an overflow page, then the first 4 bytes may store a
2943 ** pointer to a subsequent overflow page. If this is the case, then
2944 ** the pointer map needs to be updated for the subsequent overflow page.
2946 if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
2947 rc = setChildPtrmaps(pDbPage);
2948 if( rc!=SQLITE_OK ){
2949 return rc;
2951 }else{
2952 Pgno nextOvfl = get4byte(pDbPage->aData);
2953 if( nextOvfl!=0 ){
2954 ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
2955 if( rc!=SQLITE_OK ){
2956 return rc;
2961 /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
2962 ** that it points at iFreePage. Also fix the pointer map entry for
2963 ** iPtrPage.
2965 if( eType!=PTRMAP_ROOTPAGE ){
2966 rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0, 0);
2967 if( rc!=SQLITE_OK ){
2968 return rc;
2970 rc = sqlite3PagerWrite(pPtrPage->pDbPage);
2971 if( rc!=SQLITE_OK ){
2972 releasePage(pPtrPage);
2973 return rc;
2975 rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
2976 releasePage(pPtrPage);
2977 if( rc==SQLITE_OK ){
2978 ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
2981 return rc;
2984 /* Forward declaration required by incrVacuumStep(). */
2985 static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
2988 ** Perform a single step of an incremental-vacuum. If successful, return
2989 ** SQLITE_OK. If there is no work to do (and therefore no point in
2990 ** calling this function again), return SQLITE_DONE. Or, if an error
2991 ** occurs, return some other error code.
2993 ** More specificly, this function attempts to re-organize the database so
2994 ** that the last page of the file currently in use is no longer in use.
2996 ** Parameter nFin is the number of pages that this database would contain
2997 ** were this function called until it returns SQLITE_DONE.
2999 ** If the bCommit parameter is non-zero, this function assumes that the
3000 ** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE
3001 ** or an error. bCommit is passed true for an auto-vacuum-on-commmit
3002 ** operation, or false for an incremental vacuum.
3004 static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){
3005 Pgno nFreeList; /* Number of pages still on the free-list */
3006 int rc;
3008 assert( sqlite3_mutex_held(pBt->mutex) );
3009 assert( iLastPg>nFin );
3011 if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
3012 u8 eType;
3013 Pgno iPtrPage;
3015 nFreeList = get4byte(&pBt->pPage1->aData[36]);
3016 if( nFreeList==0 ){
3017 return SQLITE_DONE;
3020 rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
3021 if( rc!=SQLITE_OK ){
3022 return rc;
3024 if( eType==PTRMAP_ROOTPAGE ){
3025 return SQLITE_CORRUPT_BKPT;
3028 if( eType==PTRMAP_FREEPAGE ){
3029 if( bCommit==0 ){
3030 /* Remove the page from the files free-list. This is not required
3031 ** if bCommit is non-zero. In that case, the free-list will be
3032 ** truncated to zero after this function returns, so it doesn't
3033 ** matter if it still contains some garbage entries.
3035 Pgno iFreePg;
3036 MemPage *pFreePg;
3037 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, BTALLOC_EXACT);
3038 if( rc!=SQLITE_OK ){
3039 return rc;
3041 assert( iFreePg==iLastPg );
3042 releasePage(pFreePg);
3044 } else {
3045 Pgno iFreePg; /* Index of free page to move pLastPg to */
3046 MemPage *pLastPg;
3047 u8 eMode = BTALLOC_ANY; /* Mode parameter for allocateBtreePage() */
3048 Pgno iNear = 0; /* nearby parameter for allocateBtreePage() */
3050 rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0, 0);
3051 if( rc!=SQLITE_OK ){
3052 return rc;
3055 /* If bCommit is zero, this loop runs exactly once and page pLastPg
3056 ** is swapped with the first free page pulled off the free list.
3058 ** On the other hand, if bCommit is greater than zero, then keep
3059 ** looping until a free-page located within the first nFin pages
3060 ** of the file is found.
3062 if( bCommit==0 ){
3063 eMode = BTALLOC_LE;
3064 iNear = nFin;
3066 do {
3067 MemPage *pFreePg;
3068 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iNear, eMode);
3069 if( rc!=SQLITE_OK ){
3070 releasePage(pLastPg);
3071 return rc;
3073 releasePage(pFreePg);
3074 }while( bCommit && iFreePg>nFin );
3075 assert( iFreePg<iLastPg );
3077 rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, bCommit);
3078 releasePage(pLastPg);
3079 if( rc!=SQLITE_OK ){
3080 return rc;
3085 if( bCommit==0 ){
3086 do {
3087 iLastPg--;
3088 }while( iLastPg==PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, iLastPg) );
3089 pBt->bDoTruncate = 1;
3090 pBt->nPage = iLastPg;
3092 return SQLITE_OK;
3096 ** The database opened by the first argument is an auto-vacuum database
3097 ** nOrig pages in size containing nFree free pages. Return the expected
3098 ** size of the database in pages following an auto-vacuum operation.
3100 static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){
3101 int nEntry; /* Number of entries on one ptrmap page */
3102 Pgno nPtrmap; /* Number of PtrMap pages to be freed */
3103 Pgno nFin; /* Return value */
3105 nEntry = pBt->usableSize/5;
3106 nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
3107 nFin = nOrig - nFree - nPtrmap;
3108 if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
3109 nFin--;
3111 while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
3112 nFin--;
3115 return nFin;
3119 ** A write-transaction must be opened before calling this function.
3120 ** It performs a single unit of work towards an incremental vacuum.
3122 ** If the incremental vacuum is finished after this function has run,
3123 ** SQLITE_DONE is returned. If it is not finished, but no error occurred,
3124 ** SQLITE_OK is returned. Otherwise an SQLite error code.
3126 int sqlite3BtreeIncrVacuum(Btree *p){
3127 int rc;
3128 BtShared *pBt = p->pBt;
3130 sqlite3BtreeEnter(p);
3131 assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
3132 if( !pBt->autoVacuum ){
3133 rc = SQLITE_DONE;
3134 }else{
3135 Pgno nOrig = btreePagecount(pBt);
3136 Pgno nFree = get4byte(&pBt->pPage1->aData[36]);
3137 Pgno nFin = finalDbSize(pBt, nOrig, nFree);
3139 if( nOrig<nFin ){
3140 rc = SQLITE_CORRUPT_BKPT;
3141 }else if( nFree>0 ){
3142 rc = saveAllCursors(pBt, 0, 0);
3143 if( rc==SQLITE_OK ){
3144 invalidateAllOverflowCache(pBt);
3145 rc = incrVacuumStep(pBt, nFin, nOrig, 0);
3147 if( rc==SQLITE_OK ){
3148 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
3149 put4byte(&pBt->pPage1->aData[28], pBt->nPage);
3151 }else{
3152 rc = SQLITE_DONE;
3155 sqlite3BtreeLeave(p);
3156 return rc;
3160 ** This routine is called prior to sqlite3PagerCommit when a transaction
3161 ** is commited for an auto-vacuum database.
3163 ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
3164 ** the database file should be truncated to during the commit process.
3165 ** i.e. the database has been reorganized so that only the first *pnTrunc
3166 ** pages are in use.
3168 static int autoVacuumCommit(BtShared *pBt){
3169 int rc = SQLITE_OK;
3170 Pager *pPager = pBt->pPager;
3171 VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager) );
3173 assert( sqlite3_mutex_held(pBt->mutex) );
3174 invalidateAllOverflowCache(pBt);
3175 assert(pBt->autoVacuum);
3176 if( !pBt->incrVacuum ){
3177 Pgno nFin; /* Number of pages in database after autovacuuming */
3178 Pgno nFree; /* Number of pages on the freelist initially */
3179 Pgno iFree; /* The next page to be freed */
3180 Pgno nOrig; /* Database size before freeing */
3182 nOrig = btreePagecount(pBt);
3183 if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
3184 /* It is not possible to create a database for which the final page
3185 ** is either a pointer-map page or the pending-byte page. If one
3186 ** is encountered, this indicates corruption.
3188 return SQLITE_CORRUPT_BKPT;
3191 nFree = get4byte(&pBt->pPage1->aData[36]);
3192 nFin = finalDbSize(pBt, nOrig, nFree);
3193 if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
3194 if( nFin<nOrig ){
3195 rc = saveAllCursors(pBt, 0, 0);
3197 for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
3198 rc = incrVacuumStep(pBt, nFin, iFree, 1);
3200 if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
3201 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
3202 put4byte(&pBt->pPage1->aData[32], 0);
3203 put4byte(&pBt->pPage1->aData[36], 0);
3204 put4byte(&pBt->pPage1->aData[28], nFin);
3205 pBt->bDoTruncate = 1;
3206 pBt->nPage = nFin;
3208 if( rc!=SQLITE_OK ){
3209 sqlite3PagerRollback(pPager);
3213 assert( nRef>=sqlite3PagerRefcount(pPager) );
3214 return rc;
3217 #else /* ifndef SQLITE_OMIT_AUTOVACUUM */
3218 # define setChildPtrmaps(x) SQLITE_OK
3219 #endif
3222 ** This routine does the first phase of a two-phase commit. This routine
3223 ** causes a rollback journal to be created (if it does not already exist)
3224 ** and populated with enough information so that if a power loss occurs
3225 ** the database can be restored to its original state by playing back
3226 ** the journal. Then the contents of the journal are flushed out to
3227 ** the disk. After the journal is safely on oxide, the changes to the
3228 ** database are written into the database file and flushed to oxide.
3229 ** At the end of this call, the rollback journal still exists on the
3230 ** disk and we are still holding all locks, so the transaction has not
3231 ** committed. See sqlite3BtreeCommitPhaseTwo() for the second phase of the
3232 ** commit process.
3234 ** This call is a no-op if no write-transaction is currently active on pBt.
3236 ** Otherwise, sync the database file for the btree pBt. zMaster points to
3237 ** the name of a master journal file that should be written into the
3238 ** individual journal file, or is NULL, indicating no master journal file
3239 ** (single database transaction).
3241 ** When this is called, the master journal should already have been
3242 ** created, populated with this journal pointer and synced to disk.
3244 ** Once this is routine has returned, the only thing required to commit
3245 ** the write-transaction for this database file is to delete the journal.
3247 int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
3248 int rc = SQLITE_OK;
3249 if( p->inTrans==TRANS_WRITE ){
3250 BtShared *pBt = p->pBt;
3251 sqlite3BtreeEnter(p);
3252 #ifndef SQLITE_OMIT_AUTOVACUUM
3253 if( pBt->autoVacuum ){
3254 rc = autoVacuumCommit(pBt);
3255 if( rc!=SQLITE_OK ){
3256 sqlite3BtreeLeave(p);
3257 return rc;
3260 if( pBt->bDoTruncate ){
3261 sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage);
3263 #endif
3264 rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
3265 sqlite3BtreeLeave(p);
3267 return rc;
3271 ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
3272 ** at the conclusion of a transaction.
3274 static void btreeEndTransaction(Btree *p){
3275 BtShared *pBt = p->pBt;
3276 assert( sqlite3BtreeHoldsMutex(p) );
3278 #ifndef SQLITE_OMIT_AUTOVACUUM
3279 pBt->bDoTruncate = 0;
3280 #endif
3281 if( p->inTrans>TRANS_NONE && p->db->activeVdbeCnt>1 ){
3282 /* If there are other active statements that belong to this database
3283 ** handle, downgrade to a read-only transaction. The other statements
3284 ** may still be reading from the database. */
3285 downgradeAllSharedCacheTableLocks(p);
3286 p->inTrans = TRANS_READ;
3287 }else{
3288 /* If the handle had any kind of transaction open, decrement the
3289 ** transaction count of the shared btree. If the transaction count
3290 ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
3291 ** call below will unlock the pager. */
3292 if( p->inTrans!=TRANS_NONE ){
3293 clearAllSharedCacheTableLocks(p);
3294 pBt->nTransaction--;
3295 if( 0==pBt->nTransaction ){
3296 pBt->inTransaction = TRANS_NONE;
3300 /* Set the current transaction state to TRANS_NONE and unlock the
3301 ** pager if this call closed the only read or write transaction. */
3302 p->inTrans = TRANS_NONE;
3303 unlockBtreeIfUnused(pBt);
3306 btreeIntegrity(p);
3310 ** Commit the transaction currently in progress.
3312 ** This routine implements the second phase of a 2-phase commit. The
3313 ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
3314 ** be invoked prior to calling this routine. The sqlite3BtreeCommitPhaseOne()
3315 ** routine did all the work of writing information out to disk and flushing the
3316 ** contents so that they are written onto the disk platter. All this
3317 ** routine has to do is delete or truncate or zero the header in the
3318 ** the rollback journal (which causes the transaction to commit) and
3319 ** drop locks.
3321 ** Normally, if an error occurs while the pager layer is attempting to
3322 ** finalize the underlying journal file, this function returns an error and
3323 ** the upper layer will attempt a rollback. However, if the second argument
3324 ** is non-zero then this b-tree transaction is part of a multi-file
3325 ** transaction. In this case, the transaction has already been committed
3326 ** (by deleting a master journal file) and the caller will ignore this
3327 ** functions return code. So, even if an error occurs in the pager layer,
3328 ** reset the b-tree objects internal state to indicate that the write
3329 ** transaction has been closed. This is quite safe, as the pager will have
3330 ** transitioned to the error state.
3332 ** This will release the write lock on the database file. If there
3333 ** are no active cursors, it also releases the read lock.
3335 int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
3337 if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
3338 sqlite3BtreeEnter(p);
3339 btreeIntegrity(p);
3341 /* If the handle has a write-transaction open, commit the shared-btrees
3342 ** transaction and set the shared state to TRANS_READ.
3344 if( p->inTrans==TRANS_WRITE ){
3345 int rc;
3346 BtShared *pBt = p->pBt;
3347 assert( pBt->inTransaction==TRANS_WRITE );
3348 assert( pBt->nTransaction>0 );
3349 rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
3350 if( rc!=SQLITE_OK && bCleanup==0 ){
3351 sqlite3BtreeLeave(p);
3352 return rc;
3354 pBt->inTransaction = TRANS_READ;
3355 btreeClearHasContent(pBt);
3358 btreeEndTransaction(p);
3359 sqlite3BtreeLeave(p);
3360 return SQLITE_OK;
3364 ** Do both phases of a commit.
3366 int sqlite3BtreeCommit(Btree *p){
3367 int rc;
3368 sqlite3BtreeEnter(p);
3369 rc = sqlite3BtreeCommitPhaseOne(p, 0);
3370 if( rc==SQLITE_OK ){
3371 rc = sqlite3BtreeCommitPhaseTwo(p, 0);
3373 sqlite3BtreeLeave(p);
3374 return rc;
3378 ** This routine sets the state to CURSOR_FAULT and the error
3379 ** code to errCode for every cursor on BtShared that pBtree
3380 ** references.
3382 ** Every cursor is tripped, including cursors that belong
3383 ** to other database connections that happen to be sharing
3384 ** the cache with pBtree.
3386 ** This routine gets called when a rollback occurs.
3387 ** All cursors using the same cache must be tripped
3388 ** to prevent them from trying to use the btree after
3389 ** the rollback. The rollback may have deleted tables
3390 ** or moved root pages, so it is not sufficient to
3391 ** save the state of the cursor. The cursor must be
3392 ** invalidated.
3394 void sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode){
3395 BtCursor *p;
3396 if( pBtree==0 ) return;
3397 sqlite3BtreeEnter(pBtree);
3398 for(p=pBtree->pBt->pCursor; p; p=p->pNext){
3399 int i;
3400 sqlite3BtreeClearCursor(p);
3401 p->eState = CURSOR_FAULT;
3402 p->skipNext = errCode;
3403 for(i=0; i<=p->iPage; i++){
3404 releasePage(p->apPage[i]);
3405 p->apPage[i] = 0;
3408 sqlite3BtreeLeave(pBtree);
3412 ** Rollback the transaction in progress. All cursors will be
3413 ** invalided by this operation. Any attempt to use a cursor
3414 ** that was open at the beginning of this operation will result
3415 ** in an error.
3417 ** This will release the write lock on the database file. If there
3418 ** are no active cursors, it also releases the read lock.
3420 int sqlite3BtreeRollback(Btree *p, int tripCode){
3421 int rc;
3422 BtShared *pBt = p->pBt;
3423 MemPage *pPage1;
3425 sqlite3BtreeEnter(p);
3426 if( tripCode==SQLITE_OK ){
3427 rc = tripCode = saveAllCursors(pBt, 0, 0);
3428 }else{
3429 rc = SQLITE_OK;
3431 if( tripCode ){
3432 sqlite3BtreeTripAllCursors(p, tripCode);
3434 btreeIntegrity(p);
3436 if( p->inTrans==TRANS_WRITE ){
3437 int rc2;
3439 assert( TRANS_WRITE==pBt->inTransaction );
3440 rc2 = sqlite3PagerRollback(pBt->pPager);
3441 if( rc2!=SQLITE_OK ){
3442 rc = rc2;
3445 /* The rollback may have destroyed the pPage1->aData value. So
3446 ** call btreeGetPage() on page 1 again to make
3447 ** sure pPage1->aData is set correctly. */
3448 if( btreeGetPage(pBt, 1, &pPage1, 0, 0)==SQLITE_OK ){
3449 int nPage = get4byte(28+(u8*)pPage1->aData);
3450 testcase( nPage==0 );
3451 if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
3452 testcase( pBt->nPage!=nPage );
3453 pBt->nPage = nPage;
3454 releasePage(pPage1);
3456 assert( countValidCursors(pBt, 1)==0 );
3457 pBt->inTransaction = TRANS_READ;
3458 btreeClearHasContent(pBt);
3461 btreeEndTransaction(p);
3462 sqlite3BtreeLeave(p);
3463 return rc;
3467 ** Start a statement subtransaction. The subtransaction can can be rolled
3468 ** back independently of the main transaction. You must start a transaction
3469 ** before starting a subtransaction. The subtransaction is ended automatically
3470 ** if the main transaction commits or rolls back.
3472 ** Statement subtransactions are used around individual SQL statements
3473 ** that are contained within a BEGIN...COMMIT block. If a constraint
3474 ** error occurs within the statement, the effect of that one statement
3475 ** can be rolled back without having to rollback the entire transaction.
3477 ** A statement sub-transaction is implemented as an anonymous savepoint. The
3478 ** value passed as the second parameter is the total number of savepoints,
3479 ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
3480 ** are no active savepoints and no other statement-transactions open,
3481 ** iStatement is 1. This anonymous savepoint can be released or rolled back
3482 ** using the sqlite3BtreeSavepoint() function.
3484 int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
3485 int rc;
3486 BtShared *pBt = p->pBt;
3487 sqlite3BtreeEnter(p);
3488 assert( p->inTrans==TRANS_WRITE );
3489 assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
3490 assert( iStatement>0 );
3491 assert( iStatement>p->db->nSavepoint );
3492 assert( pBt->inTransaction==TRANS_WRITE );
3493 /* At the pager level, a statement transaction is a savepoint with
3494 ** an index greater than all savepoints created explicitly using
3495 ** SQL statements. It is illegal to open, release or rollback any
3496 ** such savepoints while the statement transaction savepoint is active.
3498 rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
3499 sqlite3BtreeLeave(p);
3500 return rc;
3504 ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
3505 ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
3506 ** savepoint identified by parameter iSavepoint, depending on the value
3507 ** of op.
3509 ** Normally, iSavepoint is greater than or equal to zero. However, if op is
3510 ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
3511 ** contents of the entire transaction are rolled back. This is different
3512 ** from a normal transaction rollback, as no locks are released and the
3513 ** transaction remains open.
3515 int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
3516 int rc = SQLITE_OK;
3517 if( p && p->inTrans==TRANS_WRITE ){
3518 BtShared *pBt = p->pBt;
3519 assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
3520 assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
3521 sqlite3BtreeEnter(p);
3522 rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
3523 if( rc==SQLITE_OK ){
3524 if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
3525 pBt->nPage = 0;
3527 rc = newDatabase(pBt);
3528 pBt->nPage = get4byte(28 + pBt->pPage1->aData);
3530 /* The database size was written into the offset 28 of the header
3531 ** when the transaction started, so we know that the value at offset
3532 ** 28 is nonzero. */
3533 assert( pBt->nPage>0 );
3535 sqlite3BtreeLeave(p);
3537 return rc;
3541 ** Create a new cursor for the BTree whose root is on the page
3542 ** iTable. If a read-only cursor is requested, it is assumed that
3543 ** the caller already has at least a read-only transaction open
3544 ** on the database already. If a write-cursor is requested, then
3545 ** the caller is assumed to have an open write transaction.
3547 ** If wrFlag==0, then the cursor can only be used for reading.
3548 ** If wrFlag==1, then the cursor can be used for reading or for
3549 ** writing if other conditions for writing are also met. These
3550 ** are the conditions that must be met in order for writing to
3551 ** be allowed:
3553 ** 1: The cursor must have been opened with wrFlag==1
3555 ** 2: Other database connections that share the same pager cache
3556 ** but which are not in the READ_UNCOMMITTED state may not have
3557 ** cursors open with wrFlag==0 on the same table. Otherwise
3558 ** the changes made by this write cursor would be visible to
3559 ** the read cursors in the other database connection.
3561 ** 3: The database must be writable (not on read-only media)
3563 ** 4: There must be an active transaction.
3565 ** No checking is done to make sure that page iTable really is the
3566 ** root page of a b-tree. If it is not, then the cursor acquired
3567 ** will not work correctly.
3569 ** It is assumed that the sqlite3BtreeCursorZero() has been called
3570 ** on pCur to initialize the memory space prior to invoking this routine.
3572 static int btreeCursor(
3573 Btree *p, /* The btree */
3574 int iTable, /* Root page of table to open */
3575 int wrFlag, /* 1 to write. 0 read-only */
3576 struct KeyInfo *pKeyInfo, /* First arg to comparison function */
3577 BtCursor *pCur /* Space for new cursor */
3579 BtShared *pBt = p->pBt; /* Shared b-tree handle */
3581 assert( sqlite3BtreeHoldsMutex(p) );
3582 assert( wrFlag==0 || wrFlag==1 );
3584 /* The following assert statements verify that if this is a sharable
3585 ** b-tree database, the connection is holding the required table locks,
3586 ** and that no other connection has any open cursor that conflicts with
3587 ** this lock. */
3588 assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, wrFlag+1) );
3589 assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
3591 /* Assert that the caller has opened the required transaction. */
3592 assert( p->inTrans>TRANS_NONE );
3593 assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
3594 assert( pBt->pPage1 && pBt->pPage1->aData );
3596 if( NEVER(wrFlag && (pBt->btsFlags & BTS_READ_ONLY)!=0) ){
3597 return SQLITE_READONLY;
3599 if( iTable==1 && btreePagecount(pBt)==0 ){
3600 assert( wrFlag==0 );
3601 iTable = 0;
3604 /* Now that no other errors can occur, finish filling in the BtCursor
3605 ** variables and link the cursor into the BtShared list. */
3606 pCur->pgnoRoot = (Pgno)iTable;
3607 pCur->iPage = -1;
3608 pCur->pKeyInfo = pKeyInfo;
3609 pCur->pBtree = p;
3610 pCur->pBt = pBt;
3611 pCur->wrFlag = (u8)wrFlag;
3612 pCur->pNext = pBt->pCursor;
3613 if( pCur->pNext ){
3614 pCur->pNext->pPrev = pCur;
3616 pBt->pCursor = pCur;
3617 pCur->eState = CURSOR_INVALID;
3618 pCur->cachedRowid = 0;
3619 return SQLITE_OK;
3621 int sqlite3BtreeCursor(
3622 Btree *p, /* The btree */
3623 int iTable, /* Root page of table to open */
3624 int wrFlag, /* 1 to write. 0 read-only */
3625 struct KeyInfo *pKeyInfo, /* First arg to xCompare() */
3626 BtCursor *pCur /* Write new cursor here */
3628 int rc;
3629 sqlite3BtreeEnter(p);
3630 rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
3631 sqlite3BtreeLeave(p);
3632 return rc;
3636 ** Return the size of a BtCursor object in bytes.
3638 ** This interfaces is needed so that users of cursors can preallocate
3639 ** sufficient storage to hold a cursor. The BtCursor object is opaque
3640 ** to users so they cannot do the sizeof() themselves - they must call
3641 ** this routine.
3643 int sqlite3BtreeCursorSize(void){
3644 return ROUND8(sizeof(BtCursor));
3648 ** Initialize memory that will be converted into a BtCursor object.
3650 ** The simple approach here would be to memset() the entire object
3651 ** to zero. But it turns out that the apPage[] and aiIdx[] arrays
3652 ** do not need to be zeroed and they are large, so we can save a lot
3653 ** of run-time by skipping the initialization of those elements.
3655 void sqlite3BtreeCursorZero(BtCursor *p){
3656 memset(p, 0, offsetof(BtCursor, iPage));
3660 ** Set the cached rowid value of every cursor in the same database file
3661 ** as pCur and having the same root page number as pCur. The value is
3662 ** set to iRowid.
3664 ** Only positive rowid values are considered valid for this cache.
3665 ** The cache is initialized to zero, indicating an invalid cache.
3666 ** A btree will work fine with zero or negative rowids. We just cannot
3667 ** cache zero or negative rowids, which means tables that use zero or
3668 ** negative rowids might run a little slower. But in practice, zero
3669 ** or negative rowids are very uncommon so this should not be a problem.
3671 void sqlite3BtreeSetCachedRowid(BtCursor *pCur, sqlite3_int64 iRowid){
3672 BtCursor *p;
3673 for(p=pCur->pBt->pCursor; p; p=p->pNext){
3674 if( p->pgnoRoot==pCur->pgnoRoot ) p->cachedRowid = iRowid;
3676 assert( pCur->cachedRowid==iRowid );
3680 ** Return the cached rowid for the given cursor. A negative or zero
3681 ** return value indicates that the rowid cache is invalid and should be
3682 ** ignored. If the rowid cache has never before been set, then a
3683 ** zero is returned.
3685 sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor *pCur){
3686 return pCur->cachedRowid;
3690 ** Close a cursor. The read lock on the database file is released
3691 ** when the last cursor is closed.
3693 int sqlite3BtreeCloseCursor(BtCursor *pCur){
3694 Btree *pBtree = pCur->pBtree;
3695 if( pBtree ){
3696 int i;
3697 BtShared *pBt = pCur->pBt;
3698 sqlite3BtreeEnter(pBtree);
3699 sqlite3BtreeClearCursor(pCur);
3700 if( pCur->pPrev ){
3701 pCur->pPrev->pNext = pCur->pNext;
3702 }else{
3703 pBt->pCursor = pCur->pNext;
3705 if( pCur->pNext ){
3706 pCur->pNext->pPrev = pCur->pPrev;
3708 for(i=0; i<=pCur->iPage; i++){
3709 releasePage(pCur->apPage[i]);
3711 unlockBtreeIfUnused(pBt);
3712 invalidateOverflowCache(pCur);
3713 /* sqlite3_free(pCur); */
3714 sqlite3BtreeLeave(pBtree);
3716 return SQLITE_OK;
3720 ** Make sure the BtCursor* given in the argument has a valid
3721 ** BtCursor.info structure. If it is not already valid, call
3722 ** btreeParseCell() to fill it in.
3724 ** BtCursor.info is a cache of the information in the current cell.
3725 ** Using this cache reduces the number of calls to btreeParseCell().
3727 ** 2007-06-25: There is a bug in some versions of MSVC that cause the
3728 ** compiler to crash when getCellInfo() is implemented as a macro.
3729 ** But there is a measureable speed advantage to using the macro on gcc
3730 ** (when less compiler optimizations like -Os or -O0 are used and the
3731 ** compiler is not doing agressive inlining.) So we use a real function
3732 ** for MSVC and a macro for everything else. Ticket #2457.
3734 #ifndef NDEBUG
3735 static void assertCellInfo(BtCursor *pCur){
3736 CellInfo info;
3737 int iPage = pCur->iPage;
3738 memset(&info, 0, sizeof(info));
3739 btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
3740 assert( memcmp(&info, &pCur->info, sizeof(info))==0 );
3742 #else
3743 #define assertCellInfo(x)
3744 #endif
3745 #ifdef _MSC_VER
3746 /* Use a real function in MSVC to work around bugs in that compiler. */
3747 static void getCellInfo(BtCursor *pCur){
3748 if( pCur->info.nSize==0 ){
3749 int iPage = pCur->iPage;
3750 btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
3751 pCur->validNKey = 1;
3752 }else{
3753 assertCellInfo(pCur);
3756 #else /* if not _MSC_VER */
3757 /* Use a macro in all other compilers so that the function is inlined */
3758 #define getCellInfo(pCur) \
3759 if( pCur->info.nSize==0 ){ \
3760 int iPage = pCur->iPage; \
3761 btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info); \
3762 pCur->validNKey = 1; \
3763 }else{ \
3764 assertCellInfo(pCur); \
3766 #endif /* _MSC_VER */
3768 #ifndef NDEBUG /* The next routine used only within assert() statements */
3770 ** Return true if the given BtCursor is valid. A valid cursor is one
3771 ** that is currently pointing to a row in a (non-empty) table.
3772 ** This is a verification routine is used only within assert() statements.
3774 int sqlite3BtreeCursorIsValid(BtCursor *pCur){
3775 return pCur && pCur->eState==CURSOR_VALID;
3777 #endif /* NDEBUG */
3780 ** Set *pSize to the size of the buffer needed to hold the value of
3781 ** the key for the current entry. If the cursor is not pointing
3782 ** to a valid entry, *pSize is set to 0.
3784 ** For a table with the INTKEY flag set, this routine returns the key
3785 ** itself, not the number of bytes in the key.
3787 ** The caller must position the cursor prior to invoking this routine.
3789 ** This routine cannot fail. It always returns SQLITE_OK.
3791 int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
3792 assert( cursorHoldsMutex(pCur) );
3793 assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
3794 if( pCur->eState!=CURSOR_VALID ){
3795 *pSize = 0;
3796 }else{
3797 getCellInfo(pCur);
3798 *pSize = pCur->info.nKey;
3800 return SQLITE_OK;
3804 ** Set *pSize to the number of bytes of data in the entry the
3805 ** cursor currently points to.
3807 ** The caller must guarantee that the cursor is pointing to a non-NULL
3808 ** valid entry. In other words, the calling procedure must guarantee
3809 ** that the cursor has Cursor.eState==CURSOR_VALID.
3811 ** Failure is not possible. This function always returns SQLITE_OK.
3812 ** It might just as well be a procedure (returning void) but we continue
3813 ** to return an integer result code for historical reasons.
3815 int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
3816 assert( cursorHoldsMutex(pCur) );
3817 assert( pCur->eState==CURSOR_VALID );
3818 getCellInfo(pCur);
3819 *pSize = pCur->info.nData;
3820 return SQLITE_OK;
3824 ** Given the page number of an overflow page in the database (parameter
3825 ** ovfl), this function finds the page number of the next page in the
3826 ** linked list of overflow pages. If possible, it uses the auto-vacuum
3827 ** pointer-map data instead of reading the content of page ovfl to do so.
3829 ** If an error occurs an SQLite error code is returned. Otherwise:
3831 ** The page number of the next overflow page in the linked list is
3832 ** written to *pPgnoNext. If page ovfl is the last page in its linked
3833 ** list, *pPgnoNext is set to zero.
3835 ** If ppPage is not NULL, and a reference to the MemPage object corresponding
3836 ** to page number pOvfl was obtained, then *ppPage is set to point to that
3837 ** reference. It is the responsibility of the caller to call releasePage()
3838 ** on *ppPage to free the reference. In no reference was obtained (because
3839 ** the pointer-map was used to obtain the value for *pPgnoNext), then
3840 ** *ppPage is set to zero.
3842 static int getOverflowPage(
3843 BtShared *pBt, /* The database file */
3844 Pgno ovfl, /* Current overflow page number */
3845 MemPage **ppPage, /* OUT: MemPage handle (may be NULL) */
3846 Pgno *pPgnoNext /* OUT: Next overflow page number */
3848 Pgno next = 0;
3849 MemPage *pPage = 0;
3850 int rc = SQLITE_OK;
3852 assert( sqlite3_mutex_held(pBt->mutex) );
3853 assert(pPgnoNext);
3855 #ifndef SQLITE_OMIT_AUTOVACUUM
3856 /* Try to find the next page in the overflow list using the
3857 ** autovacuum pointer-map pages. Guess that the next page in
3858 ** the overflow list is page number (ovfl+1). If that guess turns
3859 ** out to be wrong, fall back to loading the data of page
3860 ** number ovfl to determine the next page number.
3862 if( pBt->autoVacuum ){
3863 Pgno pgno;
3864 Pgno iGuess = ovfl+1;
3865 u8 eType;
3867 while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
3868 iGuess++;
3871 if( iGuess<=btreePagecount(pBt) ){
3872 rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
3873 if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
3874 next = iGuess;
3875 rc = SQLITE_DONE;
3879 #endif
3881 assert( next==0 || rc==SQLITE_DONE );
3882 if( rc==SQLITE_OK ){
3883 rc = btreeGetPage(pBt, ovfl, &pPage, 0, (ppPage==0));
3884 assert( rc==SQLITE_OK || pPage==0 );
3885 if( rc==SQLITE_OK ){
3886 next = get4byte(pPage->aData);
3890 *pPgnoNext = next;
3891 if( ppPage ){
3892 *ppPage = pPage;
3893 }else{
3894 releasePage(pPage);
3896 return (rc==SQLITE_DONE ? SQLITE_OK : rc);
3900 ** Copy data from a buffer to a page, or from a page to a buffer.
3902 ** pPayload is a pointer to data stored on database page pDbPage.
3903 ** If argument eOp is false, then nByte bytes of data are copied
3904 ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
3905 ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
3906 ** of data are copied from the buffer pBuf to pPayload.
3908 ** SQLITE_OK is returned on success, otherwise an error code.
3910 static int copyPayload(
3911 void *pPayload, /* Pointer to page data */
3912 void *pBuf, /* Pointer to buffer */
3913 int nByte, /* Number of bytes to copy */
3914 int eOp, /* 0 -> copy from page, 1 -> copy to page */
3915 DbPage *pDbPage /* Page containing pPayload */
3917 if( eOp ){
3918 /* Copy data from buffer to page (a write operation) */
3919 int rc = sqlite3PagerWrite(pDbPage);
3920 if( rc!=SQLITE_OK ){
3921 return rc;
3923 memcpy(pPayload, pBuf, nByte);
3924 }else{
3925 /* Copy data from page to buffer (a read operation) */
3926 memcpy(pBuf, pPayload, nByte);
3928 return SQLITE_OK;
3932 ** This function is used to read or overwrite payload information
3933 ** for the entry that the pCur cursor is pointing to. If the eOp
3934 ** parameter is 0, this is a read operation (data copied into
3935 ** buffer pBuf). If it is non-zero, a write (data copied from
3936 ** buffer pBuf).
3938 ** A total of "amt" bytes are read or written beginning at "offset".
3939 ** Data is read to or from the buffer pBuf.
3941 ** The content being read or written might appear on the main page
3942 ** or be scattered out on multiple overflow pages.
3944 ** If the BtCursor.isIncrblobHandle flag is set, and the current
3945 ** cursor entry uses one or more overflow pages, this function
3946 ** allocates space for and lazily popluates the overflow page-list
3947 ** cache array (BtCursor.aOverflow). Subsequent calls use this
3948 ** cache to make seeking to the supplied offset more efficient.
3950 ** Once an overflow page-list cache has been allocated, it may be
3951 ** invalidated if some other cursor writes to the same table, or if
3952 ** the cursor is moved to a different row. Additionally, in auto-vacuum
3953 ** mode, the following events may invalidate an overflow page-list cache.
3955 ** * An incremental vacuum,
3956 ** * A commit in auto_vacuum="full" mode,
3957 ** * Creating a table (may require moving an overflow page).
3959 static int accessPayload(
3960 BtCursor *pCur, /* Cursor pointing to entry to read from */
3961 u32 offset, /* Begin reading this far into payload */
3962 u32 amt, /* Read this many bytes */
3963 unsigned char *pBuf, /* Write the bytes into this buffer */
3964 int eOp /* zero to read. non-zero to write. */
3966 unsigned char *aPayload;
3967 int rc = SQLITE_OK;
3968 u32 nKey;
3969 int iIdx = 0;
3970 MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
3971 BtShared *pBt = pCur->pBt; /* Btree this cursor belongs to */
3973 assert( pPage );
3974 assert( pCur->eState==CURSOR_VALID );
3975 assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
3976 assert( cursorHoldsMutex(pCur) );
3978 getCellInfo(pCur);
3979 aPayload = pCur->info.pCell + pCur->info.nHeader;
3980 nKey = (pPage->intKey ? 0 : (int)pCur->info.nKey);
3982 if( NEVER(offset+amt > nKey+pCur->info.nData)
3983 || &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
3985 /* Trying to read or write past the end of the data is an error */
3986 return SQLITE_CORRUPT_BKPT;
3989 /* Check if data must be read/written to/from the btree page itself. */
3990 if( offset<pCur->info.nLocal ){
3991 int a = amt;
3992 if( a+offset>pCur->info.nLocal ){
3993 a = pCur->info.nLocal - offset;
3995 rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
3996 offset = 0;
3997 pBuf += a;
3998 amt -= a;
3999 }else{
4000 offset -= pCur->info.nLocal;
4003 if( rc==SQLITE_OK && amt>0 ){
4004 const u32 ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */
4005 Pgno nextPage;
4007 nextPage = get4byte(&aPayload[pCur->info.nLocal]);
4009 #ifndef SQLITE_OMIT_INCRBLOB
4010 /* If the isIncrblobHandle flag is set and the BtCursor.aOverflow[]
4011 ** has not been allocated, allocate it now. The array is sized at
4012 ** one entry for each overflow page in the overflow chain. The
4013 ** page number of the first overflow page is stored in aOverflow[0],
4014 ** etc. A value of 0 in the aOverflow[] array means "not yet known"
4015 ** (the cache is lazily populated).
4017 if( pCur->isIncrblobHandle && !pCur->aOverflow ){
4018 int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
4019 pCur->aOverflow = (Pgno *)sqlite3MallocZero(sizeof(Pgno)*nOvfl);
4020 /* nOvfl is always positive. If it were zero, fetchPayload would have
4021 ** been used instead of this routine. */
4022 if( ALWAYS(nOvfl) && !pCur->aOverflow ){
4023 rc = SQLITE_NOMEM;
4027 /* If the overflow page-list cache has been allocated and the
4028 ** entry for the first required overflow page is valid, skip
4029 ** directly to it.
4031 if( pCur->aOverflow && pCur->aOverflow[offset/ovflSize] ){
4032 iIdx = (offset/ovflSize);
4033 nextPage = pCur->aOverflow[iIdx];
4034 offset = (offset%ovflSize);
4036 #endif
4038 for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
4040 #ifndef SQLITE_OMIT_INCRBLOB
4041 /* If required, populate the overflow page-list cache. */
4042 if( pCur->aOverflow ){
4043 assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
4044 pCur->aOverflow[iIdx] = nextPage;
4046 #endif
4048 if( offset>=ovflSize ){
4049 /* The only reason to read this page is to obtain the page
4050 ** number for the next page in the overflow chain. The page
4051 ** data is not required. So first try to lookup the overflow
4052 ** page-list cache, if any, then fall back to the getOverflowPage()
4053 ** function.
4055 #ifndef SQLITE_OMIT_INCRBLOB
4056 if( pCur->aOverflow && pCur->aOverflow[iIdx+1] ){
4057 nextPage = pCur->aOverflow[iIdx+1];
4058 } else
4059 #endif
4060 rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
4061 offset -= ovflSize;
4062 }else{
4063 /* Need to read this page properly. It contains some of the
4064 ** range of data that is being read (eOp==0) or written (eOp!=0).
4066 #ifdef SQLITE_DIRECT_OVERFLOW_READ
4067 sqlite3_file *fd;
4068 #endif
4069 int a = amt;
4070 if( a + offset > ovflSize ){
4071 a = ovflSize - offset;
4074 #ifdef SQLITE_DIRECT_OVERFLOW_READ
4075 /* If all the following are true:
4077 ** 1) this is a read operation, and
4078 ** 2) data is required from the start of this overflow page, and
4079 ** 3) the database is file-backed, and
4080 ** 4) there is no open write-transaction, and
4081 ** 5) the database is not a WAL database,
4083 ** then data can be read directly from the database file into the
4084 ** output buffer, bypassing the page-cache altogether. This speeds
4085 ** up loading large records that span many overflow pages.
4087 if( eOp==0 /* (1) */
4088 && offset==0 /* (2) */
4089 && pBt->inTransaction==TRANS_READ /* (4) */
4090 && (fd = sqlite3PagerFile(pBt->pPager))->pMethods /* (3) */
4091 && pBt->pPage1->aData[19]==0x01 /* (5) */
4093 u8 aSave[4];
4094 u8 *aWrite = &pBuf[-4];
4095 memcpy(aSave, aWrite, 4);
4096 rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
4097 nextPage = get4byte(aWrite);
4098 memcpy(aWrite, aSave, 4);
4099 }else
4100 #endif
4103 DbPage *pDbPage;
4104 rc = sqlite3PagerAcquire(pBt->pPager, nextPage, &pDbPage,
4105 (eOp==0 ? PAGER_ACQUIRE_READONLY : 0)
4107 if( rc==SQLITE_OK ){
4108 aPayload = sqlite3PagerGetData(pDbPage);
4109 nextPage = get4byte(aPayload);
4110 rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
4111 sqlite3PagerUnref(pDbPage);
4112 offset = 0;
4115 amt -= a;
4116 pBuf += a;
4121 if( rc==SQLITE_OK && amt>0 ){
4122 return SQLITE_CORRUPT_BKPT;
4124 return rc;
4128 ** Read part of the key associated with cursor pCur. Exactly
4129 ** "amt" bytes will be transfered into pBuf[]. The transfer
4130 ** begins at "offset".
4132 ** The caller must ensure that pCur is pointing to a valid row
4133 ** in the table.
4135 ** Return SQLITE_OK on success or an error code if anything goes
4136 ** wrong. An error is returned if "offset+amt" is larger than
4137 ** the available payload.
4139 int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
4140 assert( cursorHoldsMutex(pCur) );
4141 assert( pCur->eState==CURSOR_VALID );
4142 assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
4143 assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
4144 return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
4148 ** Read part of the data associated with cursor pCur. Exactly
4149 ** "amt" bytes will be transfered into pBuf[]. The transfer
4150 ** begins at "offset".
4152 ** Return SQLITE_OK on success or an error code if anything goes
4153 ** wrong. An error is returned if "offset+amt" is larger than
4154 ** the available payload.
4156 int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
4157 int rc;
4159 #ifndef SQLITE_OMIT_INCRBLOB
4160 if ( pCur->eState==CURSOR_INVALID ){
4161 return SQLITE_ABORT;
4163 #endif
4165 assert( cursorHoldsMutex(pCur) );
4166 rc = restoreCursorPosition(pCur);
4167 if( rc==SQLITE_OK ){
4168 assert( pCur->eState==CURSOR_VALID );
4169 assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
4170 assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
4171 rc = accessPayload(pCur, offset, amt, pBuf, 0);
4173 return rc;
4177 ** Return a pointer to payload information from the entry that the
4178 ** pCur cursor is pointing to. The pointer is to the beginning of
4179 ** the key if skipKey==0 and it points to the beginning of data if
4180 ** skipKey==1. The number of bytes of available key/data is written
4181 ** into *pAmt. If *pAmt==0, then the value returned will not be
4182 ** a valid pointer.
4184 ** This routine is an optimization. It is common for the entire key
4185 ** and data to fit on the local page and for there to be no overflow
4186 ** pages. When that is so, this routine can be used to access the
4187 ** key and data without making a copy. If the key and/or data spills
4188 ** onto overflow pages, then accessPayload() must be used to reassemble
4189 ** the key/data and copy it into a preallocated buffer.
4191 ** The pointer returned by this routine looks directly into the cached
4192 ** page of the database. The data might change or move the next time
4193 ** any btree routine is called.
4195 static const unsigned char *fetchPayload(
4196 BtCursor *pCur, /* Cursor pointing to entry to read from */
4197 int *pAmt, /* Write the number of available bytes here */
4198 int skipKey /* read beginning at data if this is true */
4200 unsigned char *aPayload;
4201 MemPage *pPage;
4202 u32 nKey;
4203 u32 nLocal;
4205 assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
4206 assert( pCur->eState==CURSOR_VALID );
4207 assert( cursorHoldsMutex(pCur) );
4208 pPage = pCur->apPage[pCur->iPage];
4209 assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
4210 if( NEVER(pCur->info.nSize==0) ){
4211 btreeParseCell(pCur->apPage[pCur->iPage], pCur->aiIdx[pCur->iPage],
4212 &pCur->info);
4214 aPayload = pCur->info.pCell;
4215 aPayload += pCur->info.nHeader;
4216 if( pPage->intKey ){
4217 nKey = 0;
4218 }else{
4219 nKey = (int)pCur->info.nKey;
4221 if( skipKey ){
4222 aPayload += nKey;
4223 nLocal = pCur->info.nLocal - nKey;
4224 }else{
4225 nLocal = pCur->info.nLocal;
4226 assert( nLocal<=nKey );
4228 *pAmt = nLocal;
4229 return aPayload;
4234 ** For the entry that cursor pCur is point to, return as
4235 ** many bytes of the key or data as are available on the local
4236 ** b-tree page. Write the number of available bytes into *pAmt.
4238 ** The pointer returned is ephemeral. The key/data may move
4239 ** or be destroyed on the next call to any Btree routine,
4240 ** including calls from other threads against the same cache.
4241 ** Hence, a mutex on the BtShared should be held prior to calling
4242 ** this routine.
4244 ** These routines is used to get quick access to key and data
4245 ** in the common case where no overflow pages are used.
4247 const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
4248 const void *p = 0;
4249 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
4250 assert( cursorHoldsMutex(pCur) );
4251 if( ALWAYS(pCur->eState==CURSOR_VALID) ){
4252 p = (const void*)fetchPayload(pCur, pAmt, 0);
4254 return p;
4256 const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
4257 const void *p = 0;
4258 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
4259 assert( cursorHoldsMutex(pCur) );
4260 if( ALWAYS(pCur->eState==CURSOR_VALID) ){
4261 p = (const void*)fetchPayload(pCur, pAmt, 1);
4263 return p;
4268 ** Move the cursor down to a new child page. The newPgno argument is the
4269 ** page number of the child page to move to.
4271 ** This function returns SQLITE_CORRUPT if the page-header flags field of
4272 ** the new child page does not match the flags field of the parent (i.e.
4273 ** if an intkey page appears to be the parent of a non-intkey page, or
4274 ** vice-versa).
4276 static int moveToChild(BtCursor *pCur, u32 newPgno){
4277 int rc;
4278 int i = pCur->iPage;
4279 MemPage *pNewPage;
4280 BtShared *pBt = pCur->pBt;
4282 assert( cursorHoldsMutex(pCur) );
4283 assert( pCur->eState==CURSOR_VALID );
4284 assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
4285 assert( pCur->iPage>=0 );
4286 if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
4287 return SQLITE_CORRUPT_BKPT;
4289 rc = getAndInitPage(pBt, newPgno, &pNewPage, (pCur->wrFlag==0));
4290 if( rc ) return rc;
4291 pCur->apPage[i+1] = pNewPage;
4292 pCur->aiIdx[i+1] = 0;
4293 pCur->iPage++;
4295 pCur->info.nSize = 0;
4296 pCur->validNKey = 0;
4297 if( pNewPage->nCell<1 || pNewPage->intKey!=pCur->apPage[i]->intKey ){
4298 return SQLITE_CORRUPT_BKPT;
4300 return SQLITE_OK;
4303 #if 0
4305 ** Page pParent is an internal (non-leaf) tree page. This function
4306 ** asserts that page number iChild is the left-child if the iIdx'th
4307 ** cell in page pParent. Or, if iIdx is equal to the total number of
4308 ** cells in pParent, that page number iChild is the right-child of
4309 ** the page.
4311 static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
4312 assert( iIdx<=pParent->nCell );
4313 if( iIdx==pParent->nCell ){
4314 assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
4315 }else{
4316 assert( get4byte(findCell(pParent, iIdx))==iChild );
4319 #else
4320 # define assertParentIndex(x,y,z)
4321 #endif
4324 ** Move the cursor up to the parent page.
4326 ** pCur->idx is set to the cell index that contains the pointer
4327 ** to the page we are coming from. If we are coming from the
4328 ** right-most child page then pCur->idx is set to one more than
4329 ** the largest cell index.
4331 static void moveToParent(BtCursor *pCur){
4332 assert( cursorHoldsMutex(pCur) );
4333 assert( pCur->eState==CURSOR_VALID );
4334 assert( pCur->iPage>0 );
4335 assert( pCur->apPage[pCur->iPage] );
4337 /* UPDATE: It is actually possible for the condition tested by the assert
4338 ** below to be untrue if the database file is corrupt. This can occur if
4339 ** one cursor has modified page pParent while a reference to it is held
4340 ** by a second cursor. Which can only happen if a single page is linked
4341 ** into more than one b-tree structure in a corrupt database. */
4342 #if 0
4343 assertParentIndex(
4344 pCur->apPage[pCur->iPage-1],
4345 pCur->aiIdx[pCur->iPage-1],
4346 pCur->apPage[pCur->iPage]->pgno
4348 #endif
4349 testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
4351 releasePage(pCur->apPage[pCur->iPage]);
4352 pCur->iPage--;
4353 pCur->info.nSize = 0;
4354 pCur->validNKey = 0;
4358 ** Move the cursor to point to the root page of its b-tree structure.
4360 ** If the table has a virtual root page, then the cursor is moved to point
4361 ** to the virtual root page instead of the actual root page. A table has a
4362 ** virtual root page when the actual root page contains no cells and a
4363 ** single child page. This can only happen with the table rooted at page 1.
4365 ** If the b-tree structure is empty, the cursor state is set to
4366 ** CURSOR_INVALID. Otherwise, the cursor is set to point to the first
4367 ** cell located on the root (or virtual root) page and the cursor state
4368 ** is set to CURSOR_VALID.
4370 ** If this function returns successfully, it may be assumed that the
4371 ** page-header flags indicate that the [virtual] root-page is the expected
4372 ** kind of b-tree page (i.e. if when opening the cursor the caller did not
4373 ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
4374 ** indicating a table b-tree, or if the caller did specify a KeyInfo
4375 ** structure the flags byte is set to 0x02 or 0x0A, indicating an index
4376 ** b-tree).
4378 static int moveToRoot(BtCursor *pCur){
4379 MemPage *pRoot;
4380 int rc = SQLITE_OK;
4381 Btree *p = pCur->pBtree;
4382 BtShared *pBt = p->pBt;
4384 assert( cursorHoldsMutex(pCur) );
4385 assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
4386 assert( CURSOR_VALID < CURSOR_REQUIRESEEK );
4387 assert( CURSOR_FAULT > CURSOR_REQUIRESEEK );
4388 if( pCur->eState>=CURSOR_REQUIRESEEK ){
4389 if( pCur->eState==CURSOR_FAULT ){
4390 assert( pCur->skipNext!=SQLITE_OK );
4391 return pCur->skipNext;
4393 sqlite3BtreeClearCursor(pCur);
4396 if( pCur->iPage>=0 ){
4397 int i;
4398 for(i=1; i<=pCur->iPage; i++){
4399 releasePage(pCur->apPage[i]);
4401 pCur->iPage = 0;
4402 }else if( pCur->pgnoRoot==0 ){
4403 pCur->eState = CURSOR_INVALID;
4404 return SQLITE_OK;
4405 }else{
4406 rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->apPage[0], pCur->wrFlag==0);
4407 if( rc!=SQLITE_OK ){
4408 pCur->eState = CURSOR_INVALID;
4409 return rc;
4411 pCur->iPage = 0;
4413 /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
4414 ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
4415 ** NULL, the caller expects a table b-tree. If this is not the case,
4416 ** return an SQLITE_CORRUPT error. */
4417 assert( pCur->apPage[0]->intKey==1 || pCur->apPage[0]->intKey==0 );
4418 if( (pCur->pKeyInfo==0)!=pCur->apPage[0]->intKey ){
4419 return SQLITE_CORRUPT_BKPT;
4423 /* Assert that the root page is of the correct type. This must be the
4424 ** case as the call to this function that loaded the root-page (either
4425 ** this call or a previous invocation) would have detected corruption
4426 ** if the assumption were not true, and it is not possible for the flags
4427 ** byte to have been modified while this cursor is holding a reference
4428 ** to the page. */
4429 pRoot = pCur->apPage[0];
4430 assert( pRoot->pgno==pCur->pgnoRoot );
4431 assert( pRoot->isInit && (pCur->pKeyInfo==0)==pRoot->intKey );
4433 pCur->aiIdx[0] = 0;
4434 pCur->info.nSize = 0;
4435 pCur->atLast = 0;
4436 pCur->validNKey = 0;
4438 if( pRoot->nCell==0 && !pRoot->leaf ){
4439 Pgno subpage;
4440 if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
4441 subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
4442 pCur->eState = CURSOR_VALID;
4443 rc = moveToChild(pCur, subpage);
4444 }else{
4445 pCur->eState = ((pRoot->nCell>0)?CURSOR_VALID:CURSOR_INVALID);
4447 return rc;
4451 ** Move the cursor down to the left-most leaf entry beneath the
4452 ** entry to which it is currently pointing.
4454 ** The left-most leaf is the one with the smallest key - the first
4455 ** in ascending order.
4457 static int moveToLeftmost(BtCursor *pCur){
4458 Pgno pgno;
4459 int rc = SQLITE_OK;
4460 MemPage *pPage;
4462 assert( cursorHoldsMutex(pCur) );
4463 assert( pCur->eState==CURSOR_VALID );
4464 while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
4465 assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
4466 pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
4467 rc = moveToChild(pCur, pgno);
4469 return rc;
4473 ** Move the cursor down to the right-most leaf entry beneath the
4474 ** page to which it is currently pointing. Notice the difference
4475 ** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
4476 ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
4477 ** finds the right-most entry beneath the *page*.
4479 ** The right-most entry is the one with the largest key - the last
4480 ** key in ascending order.
4482 static int moveToRightmost(BtCursor *pCur){
4483 Pgno pgno;
4484 int rc = SQLITE_OK;
4485 MemPage *pPage = 0;
4487 assert( cursorHoldsMutex(pCur) );
4488 assert( pCur->eState==CURSOR_VALID );
4489 while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
4490 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
4491 pCur->aiIdx[pCur->iPage] = pPage->nCell;
4492 rc = moveToChild(pCur, pgno);
4494 if( rc==SQLITE_OK ){
4495 pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
4496 pCur->info.nSize = 0;
4497 pCur->validNKey = 0;
4499 return rc;
4502 /* Move the cursor to the first entry in the table. Return SQLITE_OK
4503 ** on success. Set *pRes to 0 if the cursor actually points to something
4504 ** or set *pRes to 1 if the table is empty.
4506 int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
4507 int rc;
4509 assert( cursorHoldsMutex(pCur) );
4510 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
4511 rc = moveToRoot(pCur);
4512 if( rc==SQLITE_OK ){
4513 if( pCur->eState==CURSOR_INVALID ){
4514 assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
4515 *pRes = 1;
4516 }else{
4517 assert( pCur->apPage[pCur->iPage]->nCell>0 );
4518 *pRes = 0;
4519 rc = moveToLeftmost(pCur);
4522 return rc;
4525 /* Move the cursor to the last entry in the table. Return SQLITE_OK
4526 ** on success. Set *pRes to 0 if the cursor actually points to something
4527 ** or set *pRes to 1 if the table is empty.
4529 int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
4530 int rc;
4532 assert( cursorHoldsMutex(pCur) );
4533 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
4535 /* If the cursor already points to the last entry, this is a no-op. */
4536 if( CURSOR_VALID==pCur->eState && pCur->atLast ){
4537 #ifdef SQLITE_DEBUG
4538 /* This block serves to assert() that the cursor really does point
4539 ** to the last entry in the b-tree. */
4540 int ii;
4541 for(ii=0; ii<pCur->iPage; ii++){
4542 assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
4544 assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 );
4545 assert( pCur->apPage[pCur->iPage]->leaf );
4546 #endif
4547 return SQLITE_OK;
4550 rc = moveToRoot(pCur);
4551 if( rc==SQLITE_OK ){
4552 if( CURSOR_INVALID==pCur->eState ){
4553 assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
4554 *pRes = 1;
4555 }else{
4556 assert( pCur->eState==CURSOR_VALID );
4557 *pRes = 0;
4558 rc = moveToRightmost(pCur);
4559 pCur->atLast = rc==SQLITE_OK ?1:0;
4562 return rc;
4565 /* Move the cursor so that it points to an entry near the key
4566 ** specified by pIdxKey or intKey. Return a success code.
4568 ** For INTKEY tables, the intKey parameter is used. pIdxKey
4569 ** must be NULL. For index tables, pIdxKey is used and intKey
4570 ** is ignored.
4572 ** If an exact match is not found, then the cursor is always
4573 ** left pointing at a leaf page which would hold the entry if it
4574 ** were present. The cursor might point to an entry that comes
4575 ** before or after the key.
4577 ** An integer is written into *pRes which is the result of
4578 ** comparing the key with the entry to which the cursor is
4579 ** pointing. The meaning of the integer written into
4580 ** *pRes is as follows:
4582 ** *pRes<0 The cursor is left pointing at an entry that
4583 ** is smaller than intKey/pIdxKey or if the table is empty
4584 ** and the cursor is therefore left point to nothing.
4586 ** *pRes==0 The cursor is left pointing at an entry that
4587 ** exactly matches intKey/pIdxKey.
4589 ** *pRes>0 The cursor is left pointing at an entry that
4590 ** is larger than intKey/pIdxKey.
4593 int sqlite3BtreeMovetoUnpacked(
4594 BtCursor *pCur, /* The cursor to be moved */
4595 UnpackedRecord *pIdxKey, /* Unpacked index key */
4596 i64 intKey, /* The table key */
4597 int biasRight, /* If true, bias the search to the high end */
4598 int *pRes /* Write search results here */
4600 int rc;
4602 assert( cursorHoldsMutex(pCur) );
4603 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
4604 assert( pRes );
4605 assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
4607 /* If the cursor is already positioned at the point we are trying
4608 ** to move to, then just return without doing any work */
4609 if( pCur->eState==CURSOR_VALID && pCur->validNKey
4610 && pCur->apPage[0]->intKey
4612 if( pCur->info.nKey==intKey ){
4613 *pRes = 0;
4614 return SQLITE_OK;
4616 if( pCur->atLast && pCur->info.nKey<intKey ){
4617 *pRes = -1;
4618 return SQLITE_OK;
4622 rc = moveToRoot(pCur);
4623 if( rc ){
4624 return rc;
4626 assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage] );
4627 assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->isInit );
4628 assert( pCur->eState==CURSOR_INVALID || pCur->apPage[pCur->iPage]->nCell>0 );
4629 if( pCur->eState==CURSOR_INVALID ){
4630 *pRes = -1;
4631 assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
4632 return SQLITE_OK;
4634 assert( pCur->apPage[0]->intKey || pIdxKey );
4635 for(;;){
4636 int lwr, upr, idx;
4637 Pgno chldPg;
4638 MemPage *pPage = pCur->apPage[pCur->iPage];
4639 int c;
4641 /* pPage->nCell must be greater than zero. If this is the root-page
4642 ** the cursor would have been INVALID above and this for(;;) loop
4643 ** not run. If this is not the root-page, then the moveToChild() routine
4644 ** would have already detected db corruption. Similarly, pPage must
4645 ** be the right kind (index or table) of b-tree page. Otherwise
4646 ** a moveToChild() or moveToRoot() call would have detected corruption. */
4647 assert( pPage->nCell>0 );
4648 assert( pPage->intKey==(pIdxKey==0) );
4649 lwr = 0;
4650 upr = pPage->nCell-1;
4651 if( biasRight ){
4652 pCur->aiIdx[pCur->iPage] = (u16)(idx = upr);
4653 }else{
4654 pCur->aiIdx[pCur->iPage] = (u16)(idx = (upr+lwr)/2);
4656 for(;;){
4657 u8 *pCell; /* Pointer to current cell in pPage */
4659 assert( idx==pCur->aiIdx[pCur->iPage] );
4660 pCur->info.nSize = 0;
4661 pCell = findCell(pPage, idx) + pPage->childPtrSize;
4662 if( pPage->intKey ){
4663 i64 nCellKey;
4664 if( pPage->hasData ){
4665 u32 dummy;
4666 pCell += getVarint32(pCell, dummy);
4668 getVarint(pCell, (u64*)&nCellKey);
4669 if( nCellKey==intKey ){
4670 c = 0;
4671 }else if( nCellKey<intKey ){
4672 c = -1;
4673 }else{
4674 assert( nCellKey>intKey );
4675 c = +1;
4677 pCur->validNKey = 1;
4678 pCur->info.nKey = nCellKey;
4679 }else{
4680 /* The maximum supported page-size is 65536 bytes. This means that
4681 ** the maximum number of record bytes stored on an index B-Tree
4682 ** page is less than 16384 bytes and may be stored as a 2-byte
4683 ** varint. This information is used to attempt to avoid parsing
4684 ** the entire cell by checking for the cases where the record is
4685 ** stored entirely within the b-tree page by inspecting the first
4686 ** 2 bytes of the cell.
4688 int nCell = pCell[0];
4689 if( nCell<=pPage->max1bytePayload
4690 /* && (pCell+nCell)<pPage->aDataEnd */
4692 /* This branch runs if the record-size field of the cell is a
4693 ** single byte varint and the record fits entirely on the main
4694 ** b-tree page. */
4695 testcase( pCell+nCell+1==pPage->aDataEnd );
4696 c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
4697 }else if( !(pCell[1] & 0x80)
4698 && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
4699 /* && (pCell+nCell+2)<=pPage->aDataEnd */
4701 /* The record-size field is a 2 byte varint and the record
4702 ** fits entirely on the main b-tree page. */
4703 testcase( pCell+nCell+2==pPage->aDataEnd );
4704 c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
4705 }else{
4706 /* The record flows over onto one or more overflow pages. In
4707 ** this case the whole cell needs to be parsed, a buffer allocated
4708 ** and accessPayload() used to retrieve the record into the
4709 ** buffer before VdbeRecordCompare() can be called. */
4710 void *pCellKey;
4711 u8 * const pCellBody = pCell - pPage->childPtrSize;
4712 btreeParseCellPtr(pPage, pCellBody, &pCur->info);
4713 nCell = (int)pCur->info.nKey;
4714 pCellKey = sqlite3Malloc( nCell );
4715 if( pCellKey==0 ){
4716 rc = SQLITE_NOMEM;
4717 goto moveto_finish;
4719 rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
4720 if( rc ){
4721 sqlite3_free(pCellKey);
4722 goto moveto_finish;
4724 c = sqlite3VdbeRecordCompare(nCell, pCellKey, pIdxKey);
4725 sqlite3_free(pCellKey);
4728 if( c==0 ){
4729 if( pPage->intKey && !pPage->leaf ){
4730 lwr = idx;
4731 break;
4732 }else{
4733 *pRes = 0;
4734 rc = SQLITE_OK;
4735 goto moveto_finish;
4738 if( c<0 ){
4739 lwr = idx+1;
4740 }else{
4741 upr = idx-1;
4743 if( lwr>upr ){
4744 break;
4746 pCur->aiIdx[pCur->iPage] = (u16)(idx = (lwr+upr)/2);
4748 assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
4749 assert( pPage->isInit );
4750 if( pPage->leaf ){
4751 chldPg = 0;
4752 }else if( lwr>=pPage->nCell ){
4753 chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
4754 }else{
4755 chldPg = get4byte(findCell(pPage, lwr));
4757 if( chldPg==0 ){
4758 assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
4759 *pRes = c;
4760 rc = SQLITE_OK;
4761 goto moveto_finish;
4763 pCur->aiIdx[pCur->iPage] = (u16)lwr;
4764 pCur->info.nSize = 0;
4765 pCur->validNKey = 0;
4766 rc = moveToChild(pCur, chldPg);
4767 if( rc ) goto moveto_finish;
4769 moveto_finish:
4770 return rc;
4775 ** Return TRUE if the cursor is not pointing at an entry of the table.
4777 ** TRUE will be returned after a call to sqlite3BtreeNext() moves
4778 ** past the last entry in the table or sqlite3BtreePrev() moves past
4779 ** the first entry. TRUE is also returned if the table is empty.
4781 int sqlite3BtreeEof(BtCursor *pCur){
4782 /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
4783 ** have been deleted? This API will need to change to return an error code
4784 ** as well as the boolean result value.
4786 return (CURSOR_VALID!=pCur->eState);
4790 ** Advance the cursor to the next entry in the database. If
4791 ** successful then set *pRes=0. If the cursor
4792 ** was already pointing to the last entry in the database before
4793 ** this routine was called, then set *pRes=1.
4795 int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
4796 int rc;
4797 int idx;
4798 MemPage *pPage;
4800 assert( cursorHoldsMutex(pCur) );
4801 rc = restoreCursorPosition(pCur);
4802 if( rc!=SQLITE_OK ){
4803 return rc;
4805 assert( pRes!=0 );
4806 if( CURSOR_INVALID==pCur->eState ){
4807 *pRes = 1;
4808 return SQLITE_OK;
4810 if( pCur->skipNext>0 ){
4811 pCur->skipNext = 0;
4812 *pRes = 0;
4813 return SQLITE_OK;
4815 pCur->skipNext = 0;
4817 pPage = pCur->apPage[pCur->iPage];
4818 idx = ++pCur->aiIdx[pCur->iPage];
4819 assert( pPage->isInit );
4821 /* If the database file is corrupt, it is possible for the value of idx
4822 ** to be invalid here. This can only occur if a second cursor modifies
4823 ** the page while cursor pCur is holding a reference to it. Which can
4824 ** only happen if the database is corrupt in such a way as to link the
4825 ** page into more than one b-tree structure. */
4826 testcase( idx>pPage->nCell );
4828 pCur->info.nSize = 0;
4829 pCur->validNKey = 0;
4830 if( idx>=pPage->nCell ){
4831 if( !pPage->leaf ){
4832 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
4833 if( rc ) return rc;
4834 rc = moveToLeftmost(pCur);
4835 *pRes = 0;
4836 return rc;
4839 if( pCur->iPage==0 ){
4840 *pRes = 1;
4841 pCur->eState = CURSOR_INVALID;
4842 return SQLITE_OK;
4844 moveToParent(pCur);
4845 pPage = pCur->apPage[pCur->iPage];
4846 }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
4847 *pRes = 0;
4848 if( pPage->intKey ){
4849 rc = sqlite3BtreeNext(pCur, pRes);
4850 }else{
4851 rc = SQLITE_OK;
4853 return rc;
4855 *pRes = 0;
4856 if( pPage->leaf ){
4857 return SQLITE_OK;
4859 rc = moveToLeftmost(pCur);
4860 return rc;
4865 ** Step the cursor to the back to the previous entry in the database. If
4866 ** successful then set *pRes=0. If the cursor
4867 ** was already pointing to the first entry in the database before
4868 ** this routine was called, then set *pRes=1.
4870 int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
4871 int rc;
4872 MemPage *pPage;
4874 assert( cursorHoldsMutex(pCur) );
4875 rc = restoreCursorPosition(pCur);
4876 if( rc!=SQLITE_OK ){
4877 return rc;
4879 pCur->atLast = 0;
4880 if( CURSOR_INVALID==pCur->eState ){
4881 *pRes = 1;
4882 return SQLITE_OK;
4884 if( pCur->skipNext<0 ){
4885 pCur->skipNext = 0;
4886 *pRes = 0;
4887 return SQLITE_OK;
4889 pCur->skipNext = 0;
4891 pPage = pCur->apPage[pCur->iPage];
4892 assert( pPage->isInit );
4893 if( !pPage->leaf ){
4894 int idx = pCur->aiIdx[pCur->iPage];
4895 rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
4896 if( rc ){
4897 return rc;
4899 rc = moveToRightmost(pCur);
4900 }else{
4901 while( pCur->aiIdx[pCur->iPage]==0 ){
4902 if( pCur->iPage==0 ){
4903 pCur->eState = CURSOR_INVALID;
4904 *pRes = 1;
4905 return SQLITE_OK;
4907 moveToParent(pCur);
4909 pCur->info.nSize = 0;
4910 pCur->validNKey = 0;
4912 pCur->aiIdx[pCur->iPage]--;
4913 pPage = pCur->apPage[pCur->iPage];
4914 if( pPage->intKey && !pPage->leaf ){
4915 rc = sqlite3BtreePrevious(pCur, pRes);
4916 }else{
4917 rc = SQLITE_OK;
4920 *pRes = 0;
4921 return rc;
4925 ** Allocate a new page from the database file.
4927 ** The new page is marked as dirty. (In other words, sqlite3PagerWrite()
4928 ** has already been called on the new page.) The new page has also
4929 ** been referenced and the calling routine is responsible for calling
4930 ** sqlite3PagerUnref() on the new page when it is done.
4932 ** SQLITE_OK is returned on success. Any other return value indicates
4933 ** an error. *ppPage and *pPgno are undefined in the event of an error.
4934 ** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
4936 ** If the "nearby" parameter is not 0, then an effort is made to
4937 ** locate a page close to the page number "nearby". This can be used in an
4938 ** attempt to keep related pages close to each other in the database file,
4939 ** which in turn can make database access faster.
4941 ** If the eMode parameter is BTALLOC_EXACT and the nearby page exists
4942 ** anywhere on the free-list, then it is guaranteed to be returned. If
4943 ** eMode is BTALLOC_LT then the page returned will be less than or equal
4944 ** to nearby if any such page exists. If eMode is BTALLOC_ANY then there
4945 ** are no restrictions on which page is returned.
4947 static int allocateBtreePage(
4948 BtShared *pBt, /* The btree */
4949 MemPage **ppPage, /* Store pointer to the allocated page here */
4950 Pgno *pPgno, /* Store the page number here */
4951 Pgno nearby, /* Search for a page near this one */
4952 u8 eMode /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */
4954 MemPage *pPage1;
4955 int rc;
4956 u32 n; /* Number of pages on the freelist */
4957 u32 k; /* Number of leaves on the trunk of the freelist */
4958 MemPage *pTrunk = 0;
4959 MemPage *pPrevTrunk = 0;
4960 Pgno mxPage; /* Total size of the database file */
4962 assert( sqlite3_mutex_held(pBt->mutex) );
4963 assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) );
4964 pPage1 = pBt->pPage1;
4965 mxPage = btreePagecount(pBt);
4966 n = get4byte(&pPage1->aData[36]);
4967 testcase( n==mxPage-1 );
4968 if( n>=mxPage ){
4969 return SQLITE_CORRUPT_BKPT;
4971 if( n>0 ){
4972 /* There are pages on the freelist. Reuse one of those pages. */
4973 Pgno iTrunk;
4974 u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
4976 /* If eMode==BTALLOC_EXACT and a query of the pointer-map
4977 ** shows that the page 'nearby' is somewhere on the free-list, then
4978 ** the entire-list will be searched for that page.
4980 #ifndef SQLITE_OMIT_AUTOVACUUM
4981 if( eMode==BTALLOC_EXACT ){
4982 if( nearby<=mxPage ){
4983 u8 eType;
4984 assert( nearby>0 );
4985 assert( pBt->autoVacuum );
4986 rc = ptrmapGet(pBt, nearby, &eType, 0);
4987 if( rc ) return rc;
4988 if( eType==PTRMAP_FREEPAGE ){
4989 searchList = 1;
4992 }else if( eMode==BTALLOC_LE ){
4993 searchList = 1;
4995 #endif
4997 /* Decrement the free-list count by 1. Set iTrunk to the index of the
4998 ** first free-list trunk page. iPrevTrunk is initially 1.
5000 rc = sqlite3PagerWrite(pPage1->pDbPage);
5001 if( rc ) return rc;
5002 put4byte(&pPage1->aData[36], n-1);
5004 /* The code within this loop is run only once if the 'searchList' variable
5005 ** is not true. Otherwise, it runs once for each trunk-page on the
5006 ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT)
5007 ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT)
5009 do {
5010 pPrevTrunk = pTrunk;
5011 if( pPrevTrunk ){
5012 iTrunk = get4byte(&pPrevTrunk->aData[0]);
5013 }else{
5014 iTrunk = get4byte(&pPage1->aData[32]);
5016 testcase( iTrunk==mxPage );
5017 if( iTrunk>mxPage ){
5018 rc = SQLITE_CORRUPT_BKPT;
5019 }else{
5020 rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0, 0);
5022 if( rc ){
5023 pTrunk = 0;
5024 goto end_allocate_page;
5026 assert( pTrunk!=0 );
5027 assert( pTrunk->aData!=0 );
5029 k = get4byte(&pTrunk->aData[4]); /* # of leaves on this trunk page */
5030 if( k==0 && !searchList ){
5031 /* The trunk has no leaves and the list is not being searched.
5032 ** So extract the trunk page itself and use it as the newly
5033 ** allocated page */
5034 assert( pPrevTrunk==0 );
5035 rc = sqlite3PagerWrite(pTrunk->pDbPage);
5036 if( rc ){
5037 goto end_allocate_page;
5039 *pPgno = iTrunk;
5040 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
5041 *ppPage = pTrunk;
5042 pTrunk = 0;
5043 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
5044 }else if( k>(u32)(pBt->usableSize/4 - 2) ){
5045 /* Value of k is out of range. Database corruption */
5046 rc = SQLITE_CORRUPT_BKPT;
5047 goto end_allocate_page;
5048 #ifndef SQLITE_OMIT_AUTOVACUUM
5049 }else if( searchList
5050 && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE))
5052 /* The list is being searched and this trunk page is the page
5053 ** to allocate, regardless of whether it has leaves.
5055 *pPgno = iTrunk;
5056 *ppPage = pTrunk;
5057 searchList = 0;
5058 rc = sqlite3PagerWrite(pTrunk->pDbPage);
5059 if( rc ){
5060 goto end_allocate_page;
5062 if( k==0 ){
5063 if( !pPrevTrunk ){
5064 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
5065 }else{
5066 rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
5067 if( rc!=SQLITE_OK ){
5068 goto end_allocate_page;
5070 memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
5072 }else{
5073 /* The trunk page is required by the caller but it contains
5074 ** pointers to free-list leaves. The first leaf becomes a trunk
5075 ** page in this case.
5077 MemPage *pNewTrunk;
5078 Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
5079 if( iNewTrunk>mxPage ){
5080 rc = SQLITE_CORRUPT_BKPT;
5081 goto end_allocate_page;
5083 testcase( iNewTrunk==mxPage );
5084 rc = btreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0, 0);
5085 if( rc!=SQLITE_OK ){
5086 goto end_allocate_page;
5088 rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
5089 if( rc!=SQLITE_OK ){
5090 releasePage(pNewTrunk);
5091 goto end_allocate_page;
5093 memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
5094 put4byte(&pNewTrunk->aData[4], k-1);
5095 memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
5096 releasePage(pNewTrunk);
5097 if( !pPrevTrunk ){
5098 assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
5099 put4byte(&pPage1->aData[32], iNewTrunk);
5100 }else{
5101 rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
5102 if( rc ){
5103 goto end_allocate_page;
5105 put4byte(&pPrevTrunk->aData[0], iNewTrunk);
5108 pTrunk = 0;
5109 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
5110 #endif
5111 }else if( k>0 ){
5112 /* Extract a leaf from the trunk */
5113 u32 closest;
5114 Pgno iPage;
5115 unsigned char *aData = pTrunk->aData;
5116 if( nearby>0 ){
5117 u32 i;
5118 closest = 0;
5119 if( eMode==BTALLOC_LE ){
5120 for(i=0; i<k; i++){
5121 iPage = get4byte(&aData[8+i*4]);
5122 if( iPage<=nearby ){
5123 closest = i;
5124 break;
5127 }else{
5128 int dist;
5129 dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
5130 for(i=1; i<k; i++){
5131 int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
5132 if( d2<dist ){
5133 closest = i;
5134 dist = d2;
5138 }else{
5139 closest = 0;
5142 iPage = get4byte(&aData[8+closest*4]);
5143 testcase( iPage==mxPage );
5144 if( iPage>mxPage ){
5145 rc = SQLITE_CORRUPT_BKPT;
5146 goto end_allocate_page;
5148 testcase( iPage==mxPage );
5149 if( !searchList
5150 || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE))
5152 int noContent;
5153 *pPgno = iPage;
5154 TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
5155 ": %d more free pages\n",
5156 *pPgno, closest+1, k, pTrunk->pgno, n-1));
5157 rc = sqlite3PagerWrite(pTrunk->pDbPage);
5158 if( rc ) goto end_allocate_page;
5159 if( closest<k-1 ){
5160 memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
5162 put4byte(&aData[4], k-1);
5163 noContent = !btreeGetHasContent(pBt, *pPgno);
5164 rc = btreeGetPage(pBt, *pPgno, ppPage, noContent, 0);
5165 if( rc==SQLITE_OK ){
5166 rc = sqlite3PagerWrite((*ppPage)->pDbPage);
5167 if( rc!=SQLITE_OK ){
5168 releasePage(*ppPage);
5171 searchList = 0;
5174 releasePage(pPrevTrunk);
5175 pPrevTrunk = 0;
5176 }while( searchList );
5177 }else{
5178 /* There are no pages on the freelist, so append a new page to the
5179 ** database image.
5181 ** Normally, new pages allocated by this block can be requested from the
5182 ** pager layer with the 'no-content' flag set. This prevents the pager
5183 ** from trying to read the pages content from disk. However, if the
5184 ** current transaction has already run one or more incremental-vacuum
5185 ** steps, then the page we are about to allocate may contain content
5186 ** that is required in the event of a rollback. In this case, do
5187 ** not set the no-content flag. This causes the pager to load and journal
5188 ** the current page content before overwriting it.
5190 ** Note that the pager will not actually attempt to load or journal
5191 ** content for any page that really does lie past the end of the database
5192 ** file on disk. So the effects of disabling the no-content optimization
5193 ** here are confined to those pages that lie between the end of the
5194 ** database image and the end of the database file.
5196 int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate));
5198 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
5199 if( rc ) return rc;
5200 pBt->nPage++;
5201 if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
5203 #ifndef SQLITE_OMIT_AUTOVACUUM
5204 if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
5205 /* If *pPgno refers to a pointer-map page, allocate two new pages
5206 ** at the end of the file instead of one. The first allocated page
5207 ** becomes a new pointer-map page, the second is used by the caller.
5209 MemPage *pPg = 0;
5210 TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
5211 assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
5212 rc = btreeGetPage(pBt, pBt->nPage, &pPg, bNoContent, 0);
5213 if( rc==SQLITE_OK ){
5214 rc = sqlite3PagerWrite(pPg->pDbPage);
5215 releasePage(pPg);
5217 if( rc ) return rc;
5218 pBt->nPage++;
5219 if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
5221 #endif
5222 put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
5223 *pPgno = pBt->nPage;
5225 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
5226 rc = btreeGetPage(pBt, *pPgno, ppPage, bNoContent, 0);
5227 if( rc ) return rc;
5228 rc = sqlite3PagerWrite((*ppPage)->pDbPage);
5229 if( rc!=SQLITE_OK ){
5230 releasePage(*ppPage);
5232 TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
5235 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
5237 end_allocate_page:
5238 releasePage(pTrunk);
5239 releasePage(pPrevTrunk);
5240 if( rc==SQLITE_OK ){
5241 if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
5242 releasePage(*ppPage);
5243 return SQLITE_CORRUPT_BKPT;
5245 (*ppPage)->isInit = 0;
5246 }else{
5247 *ppPage = 0;
5249 assert( rc!=SQLITE_OK || sqlite3PagerIswriteable((*ppPage)->pDbPage) );
5250 return rc;
5254 ** This function is used to add page iPage to the database file free-list.
5255 ** It is assumed that the page is not already a part of the free-list.
5257 ** The value passed as the second argument to this function is optional.
5258 ** If the caller happens to have a pointer to the MemPage object
5259 ** corresponding to page iPage handy, it may pass it as the second value.
5260 ** Otherwise, it may pass NULL.
5262 ** If a pointer to a MemPage object is passed as the second argument,
5263 ** its reference count is not altered by this function.
5265 static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
5266 MemPage *pTrunk = 0; /* Free-list trunk page */
5267 Pgno iTrunk = 0; /* Page number of free-list trunk page */
5268 MemPage *pPage1 = pBt->pPage1; /* Local reference to page 1 */
5269 MemPage *pPage; /* Page being freed. May be NULL. */
5270 int rc; /* Return Code */
5271 int nFree; /* Initial number of pages on free-list */
5273 assert( sqlite3_mutex_held(pBt->mutex) );
5274 assert( iPage>1 );
5275 assert( !pMemPage || pMemPage->pgno==iPage );
5277 if( pMemPage ){
5278 pPage = pMemPage;
5279 sqlite3PagerRef(pPage->pDbPage);
5280 }else{
5281 pPage = btreePageLookup(pBt, iPage);
5284 /* Increment the free page count on pPage1 */
5285 rc = sqlite3PagerWrite(pPage1->pDbPage);
5286 if( rc ) goto freepage_out;
5287 nFree = get4byte(&pPage1->aData[36]);
5288 put4byte(&pPage1->aData[36], nFree+1);
5290 if( pBt->btsFlags & BTS_SECURE_DELETE ){
5291 /* If the secure_delete option is enabled, then
5292 ** always fully overwrite deleted information with zeros.
5294 if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0, 0))!=0) )
5295 || ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
5297 goto freepage_out;
5299 memset(pPage->aData, 0, pPage->pBt->pageSize);
5302 /* If the database supports auto-vacuum, write an entry in the pointer-map
5303 ** to indicate that the page is free.
5305 if( ISAUTOVACUUM ){
5306 ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
5307 if( rc ) goto freepage_out;
5310 /* Now manipulate the actual database free-list structure. There are two
5311 ** possibilities. If the free-list is currently empty, or if the first
5312 ** trunk page in the free-list is full, then this page will become a
5313 ** new free-list trunk page. Otherwise, it will become a leaf of the
5314 ** first trunk page in the current free-list. This block tests if it
5315 ** is possible to add the page as a new free-list leaf.
5317 if( nFree!=0 ){
5318 u32 nLeaf; /* Initial number of leaf cells on trunk page */
5320 iTrunk = get4byte(&pPage1->aData[32]);
5321 rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0, 0);
5322 if( rc!=SQLITE_OK ){
5323 goto freepage_out;
5326 nLeaf = get4byte(&pTrunk->aData[4]);
5327 assert( pBt->usableSize>32 );
5328 if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
5329 rc = SQLITE_CORRUPT_BKPT;
5330 goto freepage_out;
5332 if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
5333 /* In this case there is room on the trunk page to insert the page
5334 ** being freed as a new leaf.
5336 ** Note that the trunk page is not really full until it contains
5337 ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
5338 ** coded. But due to a coding error in versions of SQLite prior to
5339 ** 3.6.0, databases with freelist trunk pages holding more than
5340 ** usableSize/4 - 8 entries will be reported as corrupt. In order
5341 ** to maintain backwards compatibility with older versions of SQLite,
5342 ** we will continue to restrict the number of entries to usableSize/4 - 8
5343 ** for now. At some point in the future (once everyone has upgraded
5344 ** to 3.6.0 or later) we should consider fixing the conditional above
5345 ** to read "usableSize/4-2" instead of "usableSize/4-8".
5347 rc = sqlite3PagerWrite(pTrunk->pDbPage);
5348 if( rc==SQLITE_OK ){
5349 put4byte(&pTrunk->aData[4], nLeaf+1);
5350 put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
5351 if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
5352 sqlite3PagerDontWrite(pPage->pDbPage);
5354 rc = btreeSetHasContent(pBt, iPage);
5356 TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
5357 goto freepage_out;
5361 /* If control flows to this point, then it was not possible to add the
5362 ** the page being freed as a leaf page of the first trunk in the free-list.
5363 ** Possibly because the free-list is empty, or possibly because the
5364 ** first trunk in the free-list is full. Either way, the page being freed
5365 ** will become the new first trunk page in the free-list.
5367 if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0, 0)) ){
5368 goto freepage_out;
5370 rc = sqlite3PagerWrite(pPage->pDbPage);
5371 if( rc!=SQLITE_OK ){
5372 goto freepage_out;
5374 put4byte(pPage->aData, iTrunk);
5375 put4byte(&pPage->aData[4], 0);
5376 put4byte(&pPage1->aData[32], iPage);
5377 TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
5379 freepage_out:
5380 if( pPage ){
5381 pPage->isInit = 0;
5383 releasePage(pPage);
5384 releasePage(pTrunk);
5385 return rc;
5387 static void freePage(MemPage *pPage, int *pRC){
5388 if( (*pRC)==SQLITE_OK ){
5389 *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
5394 ** Free any overflow pages associated with the given Cell.
5396 static int clearCell(MemPage *pPage, unsigned char *pCell){
5397 BtShared *pBt = pPage->pBt;
5398 CellInfo info;
5399 Pgno ovflPgno;
5400 int rc;
5401 int nOvfl;
5402 u32 ovflPageSize;
5404 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
5405 btreeParseCellPtr(pPage, pCell, &info);
5406 if( info.iOverflow==0 ){
5407 return SQLITE_OK; /* No overflow pages. Return without doing anything */
5409 if( pCell+info.iOverflow+3 > pPage->aData+pPage->maskPage ){
5410 return SQLITE_CORRUPT_BKPT; /* Cell extends past end of page */
5412 ovflPgno = get4byte(&pCell[info.iOverflow]);
5413 assert( pBt->usableSize > 4 );
5414 ovflPageSize = pBt->usableSize - 4;
5415 nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
5416 assert( ovflPgno==0 || nOvfl>0 );
5417 while( nOvfl-- ){
5418 Pgno iNext = 0;
5419 MemPage *pOvfl = 0;
5420 if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
5421 /* 0 is not a legal page number and page 1 cannot be an
5422 ** overflow page. Therefore if ovflPgno<2 or past the end of the
5423 ** file the database must be corrupt. */
5424 return SQLITE_CORRUPT_BKPT;
5426 if( nOvfl ){
5427 rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
5428 if( rc ) return rc;
5431 if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
5432 && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
5434 /* There is no reason any cursor should have an outstanding reference
5435 ** to an overflow page belonging to a cell that is being deleted/updated.
5436 ** So if there exists more than one reference to this page, then it
5437 ** must not really be an overflow page and the database must be corrupt.
5438 ** It is helpful to detect this before calling freePage2(), as
5439 ** freePage2() may zero the page contents if secure-delete mode is
5440 ** enabled. If this 'overflow' page happens to be a page that the
5441 ** caller is iterating through or using in some other way, this
5442 ** can be problematic.
5444 rc = SQLITE_CORRUPT_BKPT;
5445 }else{
5446 rc = freePage2(pBt, pOvfl, ovflPgno);
5449 if( pOvfl ){
5450 sqlite3PagerUnref(pOvfl->pDbPage);
5452 if( rc ) return rc;
5453 ovflPgno = iNext;
5455 return SQLITE_OK;
5459 ** Create the byte sequence used to represent a cell on page pPage
5460 ** and write that byte sequence into pCell[]. Overflow pages are
5461 ** allocated and filled in as necessary. The calling procedure
5462 ** is responsible for making sure sufficient space has been allocated
5463 ** for pCell[].
5465 ** Note that pCell does not necessary need to point to the pPage->aData
5466 ** area. pCell might point to some temporary storage. The cell will
5467 ** be constructed in this temporary area then copied into pPage->aData
5468 ** later.
5470 static int fillInCell(
5471 MemPage *pPage, /* The page that contains the cell */
5472 unsigned char *pCell, /* Complete text of the cell */
5473 const void *pKey, i64 nKey, /* The key */
5474 const void *pData,int nData, /* The data */
5475 int nZero, /* Extra zero bytes to append to pData */
5476 int *pnSize /* Write cell size here */
5478 int nPayload;
5479 const u8 *pSrc;
5480 int nSrc, n, rc;
5481 int spaceLeft;
5482 MemPage *pOvfl = 0;
5483 MemPage *pToRelease = 0;
5484 unsigned char *pPrior;
5485 unsigned char *pPayload;
5486 BtShared *pBt = pPage->pBt;
5487 Pgno pgnoOvfl = 0;
5488 int nHeader;
5489 CellInfo info;
5491 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
5493 /* pPage is not necessarily writeable since pCell might be auxiliary
5494 ** buffer space that is separate from the pPage buffer area */
5495 assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
5496 || sqlite3PagerIswriteable(pPage->pDbPage) );
5498 /* Fill in the header. */
5499 nHeader = 0;
5500 if( !pPage->leaf ){
5501 nHeader += 4;
5503 if( pPage->hasData ){
5504 nHeader += putVarint(&pCell[nHeader], nData+nZero);
5505 }else{
5506 nData = nZero = 0;
5508 nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
5509 btreeParseCellPtr(pPage, pCell, &info);
5510 assert( info.nHeader==nHeader );
5511 assert( info.nKey==nKey );
5512 assert( info.nData==(u32)(nData+nZero) );
5514 /* Fill in the payload */
5515 nPayload = nData + nZero;
5516 if( pPage->intKey ){
5517 pSrc = pData;
5518 nSrc = nData;
5519 nData = 0;
5520 }else{
5521 if( NEVER(nKey>0x7fffffff || pKey==0) ){
5522 return SQLITE_CORRUPT_BKPT;
5524 nPayload += (int)nKey;
5525 pSrc = pKey;
5526 nSrc = (int)nKey;
5528 *pnSize = info.nSize;
5529 spaceLeft = info.nLocal;
5530 pPayload = &pCell[nHeader];
5531 pPrior = &pCell[info.iOverflow];
5533 while( nPayload>0 ){
5534 if( spaceLeft==0 ){
5535 #ifndef SQLITE_OMIT_AUTOVACUUM
5536 Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
5537 if( pBt->autoVacuum ){
5539 pgnoOvfl++;
5540 } while(
5541 PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
5544 #endif
5545 rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
5546 #ifndef SQLITE_OMIT_AUTOVACUUM
5547 /* If the database supports auto-vacuum, and the second or subsequent
5548 ** overflow page is being allocated, add an entry to the pointer-map
5549 ** for that page now.
5551 ** If this is the first overflow page, then write a partial entry
5552 ** to the pointer-map. If we write nothing to this pointer-map slot,
5553 ** then the optimistic overflow chain processing in clearCell()
5554 ** may misinterpret the uninitialized values and delete the
5555 ** wrong pages from the database.
5557 if( pBt->autoVacuum && rc==SQLITE_OK ){
5558 u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
5559 ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
5560 if( rc ){
5561 releasePage(pOvfl);
5564 #endif
5565 if( rc ){
5566 releasePage(pToRelease);
5567 return rc;
5570 /* If pToRelease is not zero than pPrior points into the data area
5571 ** of pToRelease. Make sure pToRelease is still writeable. */
5572 assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
5574 /* If pPrior is part of the data area of pPage, then make sure pPage
5575 ** is still writeable */
5576 assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
5577 || sqlite3PagerIswriteable(pPage->pDbPage) );
5579 put4byte(pPrior, pgnoOvfl);
5580 releasePage(pToRelease);
5581 pToRelease = pOvfl;
5582 pPrior = pOvfl->aData;
5583 put4byte(pPrior, 0);
5584 pPayload = &pOvfl->aData[4];
5585 spaceLeft = pBt->usableSize - 4;
5587 n = nPayload;
5588 if( n>spaceLeft ) n = spaceLeft;
5590 /* If pToRelease is not zero than pPayload points into the data area
5591 ** of pToRelease. Make sure pToRelease is still writeable. */
5592 assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
5594 /* If pPayload is part of the data area of pPage, then make sure pPage
5595 ** is still writeable */
5596 assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
5597 || sqlite3PagerIswriteable(pPage->pDbPage) );
5599 if( nSrc>0 ){
5600 if( n>nSrc ) n = nSrc;
5601 assert( pSrc );
5602 memcpy(pPayload, pSrc, n);
5603 }else{
5604 memset(pPayload, 0, n);
5606 nPayload -= n;
5607 pPayload += n;
5608 pSrc += n;
5609 nSrc -= n;
5610 spaceLeft -= n;
5611 if( nSrc==0 ){
5612 nSrc = nData;
5613 pSrc = pData;
5616 releasePage(pToRelease);
5617 return SQLITE_OK;
5621 ** Remove the i-th cell from pPage. This routine effects pPage only.
5622 ** The cell content is not freed or deallocated. It is assumed that
5623 ** the cell content has been copied someplace else. This routine just
5624 ** removes the reference to the cell from pPage.
5626 ** "sz" must be the number of bytes in the cell.
5628 static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
5629 u32 pc; /* Offset to cell content of cell being deleted */
5630 u8 *data; /* pPage->aData */
5631 u8 *ptr; /* Used to move bytes around within data[] */
5632 u8 *endPtr; /* End of loop */
5633 int rc; /* The return code */
5634 int hdr; /* Beginning of the header. 0 most pages. 100 page 1 */
5636 if( *pRC ) return;
5638 assert( idx>=0 && idx<pPage->nCell );
5639 assert( sz==cellSize(pPage, idx) );
5640 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
5641 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
5642 data = pPage->aData;
5643 ptr = &pPage->aCellIdx[2*idx];
5644 pc = get2byte(ptr);
5645 hdr = pPage->hdrOffset;
5646 testcase( pc==get2byte(&data[hdr+5]) );
5647 testcase( pc+sz==pPage->pBt->usableSize );
5648 if( pc < (u32)get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
5649 *pRC = SQLITE_CORRUPT_BKPT;
5650 return;
5652 rc = freeSpace(pPage, pc, sz);
5653 if( rc ){
5654 *pRC = rc;
5655 return;
5657 endPtr = &pPage->aCellIdx[2*pPage->nCell - 2];
5658 assert( (SQLITE_PTR_TO_INT(ptr)&1)==0 ); /* ptr is always 2-byte aligned */
5659 while( ptr<endPtr ){
5660 *(u16*)ptr = *(u16*)&ptr[2];
5661 ptr += 2;
5663 pPage->nCell--;
5664 put2byte(&data[hdr+3], pPage->nCell);
5665 pPage->nFree += 2;
5669 ** Insert a new cell on pPage at cell index "i". pCell points to the
5670 ** content of the cell.
5672 ** If the cell content will fit on the page, then put it there. If it
5673 ** will not fit, then make a copy of the cell content into pTemp if
5674 ** pTemp is not null. Regardless of pTemp, allocate a new entry
5675 ** in pPage->apOvfl[] and make it point to the cell content (either
5676 ** in pTemp or the original pCell) and also record its index.
5677 ** Allocating a new entry in pPage->aCell[] implies that
5678 ** pPage->nOverflow is incremented.
5680 ** If nSkip is non-zero, then do not copy the first nSkip bytes of the
5681 ** cell. The caller will overwrite them after this function returns. If
5682 ** nSkip is non-zero, then pCell may not point to an invalid memory location
5683 ** (but pCell+nSkip is always valid).
5685 static void insertCell(
5686 MemPage *pPage, /* Page into which we are copying */
5687 int i, /* New cell becomes the i-th cell of the page */
5688 u8 *pCell, /* Content of the new cell */
5689 int sz, /* Bytes of content in pCell */
5690 u8 *pTemp, /* Temp storage space for pCell, if needed */
5691 Pgno iChild, /* If non-zero, replace first 4 bytes with this value */
5692 int *pRC /* Read and write return code from here */
5694 int idx = 0; /* Where to write new cell content in data[] */
5695 int j; /* Loop counter */
5696 int end; /* First byte past the last cell pointer in data[] */
5697 int ins; /* Index in data[] where new cell pointer is inserted */
5698 int cellOffset; /* Address of first cell pointer in data[] */
5699 u8 *data; /* The content of the whole page */
5700 u8 *ptr; /* Used for moving information around in data[] */
5701 u8 *endPtr; /* End of the loop */
5703 int nSkip = (iChild ? 4 : 0);
5705 if( *pRC ) return;
5707 assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
5708 assert( pPage->nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=10921 );
5709 assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
5710 assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
5711 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
5712 /* The cell should normally be sized correctly. However, when moving a
5713 ** malformed cell from a leaf page to an interior page, if the cell size
5714 ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
5715 ** might be less than 8 (leaf-size + pointer) on the interior node. Hence
5716 ** the term after the || in the following assert(). */
5717 assert( sz==cellSizePtr(pPage, pCell) || (sz==8 && iChild>0) );
5718 if( pPage->nOverflow || sz+2>pPage->nFree ){
5719 if( pTemp ){
5720 memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
5721 pCell = pTemp;
5723 if( iChild ){
5724 put4byte(pCell, iChild);
5726 j = pPage->nOverflow++;
5727 assert( j<(int)(sizeof(pPage->apOvfl)/sizeof(pPage->apOvfl[0])) );
5728 pPage->apOvfl[j] = pCell;
5729 pPage->aiOvfl[j] = (u16)i;
5730 }else{
5731 int rc = sqlite3PagerWrite(pPage->pDbPage);
5732 if( rc!=SQLITE_OK ){
5733 *pRC = rc;
5734 return;
5736 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
5737 data = pPage->aData;
5738 cellOffset = pPage->cellOffset;
5739 end = cellOffset + 2*pPage->nCell;
5740 ins = cellOffset + 2*i;
5741 rc = allocateSpace(pPage, sz, &idx);
5742 if( rc ){ *pRC = rc; return; }
5743 /* The allocateSpace() routine guarantees the following two properties
5744 ** if it returns success */
5745 assert( idx >= end+2 );
5746 assert( idx+sz <= (int)pPage->pBt->usableSize );
5747 pPage->nCell++;
5748 pPage->nFree -= (u16)(2 + sz);
5749 memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
5750 if( iChild ){
5751 put4byte(&data[idx], iChild);
5753 ptr = &data[end];
5754 endPtr = &data[ins];
5755 assert( (SQLITE_PTR_TO_INT(ptr)&1)==0 ); /* ptr is always 2-byte aligned */
5756 while( ptr>endPtr ){
5757 *(u16*)ptr = *(u16*)&ptr[-2];
5758 ptr -= 2;
5760 put2byte(&data[ins], idx);
5761 put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
5762 #ifndef SQLITE_OMIT_AUTOVACUUM
5763 if( pPage->pBt->autoVacuum ){
5764 /* The cell may contain a pointer to an overflow page. If so, write
5765 ** the entry for the overflow page into the pointer map.
5767 ptrmapPutOvflPtr(pPage, pCell, pRC);
5769 #endif
5774 ** Add a list of cells to a page. The page should be initially empty.
5775 ** The cells are guaranteed to fit on the page.
5777 static void assemblePage(
5778 MemPage *pPage, /* The page to be assemblied */
5779 int nCell, /* The number of cells to add to this page */
5780 u8 **apCell, /* Pointers to cell bodies */
5781 u16 *aSize /* Sizes of the cells */
5783 int i; /* Loop counter */
5784 u8 *pCellptr; /* Address of next cell pointer */
5785 int cellbody; /* Address of next cell body */
5786 u8 * const data = pPage->aData; /* Pointer to data for pPage */
5787 const int hdr = pPage->hdrOffset; /* Offset of header on pPage */
5788 const int nUsable = pPage->pBt->usableSize; /* Usable size of page */
5790 assert( pPage->nOverflow==0 );
5791 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
5792 assert( nCell>=0 && nCell<=(int)MX_CELL(pPage->pBt)
5793 && (int)MX_CELL(pPage->pBt)<=10921);
5794 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
5796 /* Check that the page has just been zeroed by zeroPage() */
5797 assert( pPage->nCell==0 );
5798 assert( get2byteNotZero(&data[hdr+5])==nUsable );
5800 pCellptr = &pPage->aCellIdx[nCell*2];
5801 cellbody = nUsable;
5802 for(i=nCell-1; i>=0; i--){
5803 u16 sz = aSize[i];
5804 pCellptr -= 2;
5805 cellbody -= sz;
5806 put2byte(pCellptr, cellbody);
5807 memcpy(&data[cellbody], apCell[i], sz);
5809 put2byte(&data[hdr+3], nCell);
5810 put2byte(&data[hdr+5], cellbody);
5811 pPage->nFree -= (nCell*2 + nUsable - cellbody);
5812 pPage->nCell = (u16)nCell;
5816 ** The following parameters determine how many adjacent pages get involved
5817 ** in a balancing operation. NN is the number of neighbors on either side
5818 ** of the page that participate in the balancing operation. NB is the
5819 ** total number of pages that participate, including the target page and
5820 ** NN neighbors on either side.
5822 ** The minimum value of NN is 1 (of course). Increasing NN above 1
5823 ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
5824 ** in exchange for a larger degradation in INSERT and UPDATE performance.
5825 ** The value of NN appears to give the best results overall.
5827 #define NN 1 /* Number of neighbors on either side of pPage */
5828 #define NB (NN*2+1) /* Total pages involved in the balance */
5831 #ifndef SQLITE_OMIT_QUICKBALANCE
5833 ** This version of balance() handles the common special case where
5834 ** a new entry is being inserted on the extreme right-end of the
5835 ** tree, in other words, when the new entry will become the largest
5836 ** entry in the tree.
5838 ** Instead of trying to balance the 3 right-most leaf pages, just add
5839 ** a new page to the right-hand side and put the one new entry in
5840 ** that page. This leaves the right side of the tree somewhat
5841 ** unbalanced. But odds are that we will be inserting new entries
5842 ** at the end soon afterwards so the nearly empty page will quickly
5843 ** fill up. On average.
5845 ** pPage is the leaf page which is the right-most page in the tree.
5846 ** pParent is its parent. pPage must have a single overflow entry
5847 ** which is also the right-most entry on the page.
5849 ** The pSpace buffer is used to store a temporary copy of the divider
5850 ** cell that will be inserted into pParent. Such a cell consists of a 4
5851 ** byte page number followed by a variable length integer. In other
5852 ** words, at most 13 bytes. Hence the pSpace buffer must be at
5853 ** least 13 bytes in size.
5855 static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
5856 BtShared *const pBt = pPage->pBt; /* B-Tree Database */
5857 MemPage *pNew; /* Newly allocated page */
5858 int rc; /* Return Code */
5859 Pgno pgnoNew; /* Page number of pNew */
5861 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
5862 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
5863 assert( pPage->nOverflow==1 );
5865 /* This error condition is now caught prior to reaching this function */
5866 if( pPage->nCell==0 ) return SQLITE_CORRUPT_BKPT;
5868 /* Allocate a new page. This page will become the right-sibling of
5869 ** pPage. Make the parent page writable, so that the new divider cell
5870 ** may be inserted. If both these operations are successful, proceed.
5872 rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
5874 if( rc==SQLITE_OK ){
5876 u8 *pOut = &pSpace[4];
5877 u8 *pCell = pPage->apOvfl[0];
5878 u16 szCell = cellSizePtr(pPage, pCell);
5879 u8 *pStop;
5881 assert( sqlite3PagerIswriteable(pNew->pDbPage) );
5882 assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
5883 zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
5884 assemblePage(pNew, 1, &pCell, &szCell);
5886 /* If this is an auto-vacuum database, update the pointer map
5887 ** with entries for the new page, and any pointer from the
5888 ** cell on the page to an overflow page. If either of these
5889 ** operations fails, the return code is set, but the contents
5890 ** of the parent page are still manipulated by thh code below.
5891 ** That is Ok, at this point the parent page is guaranteed to
5892 ** be marked as dirty. Returning an error code will cause a
5893 ** rollback, undoing any changes made to the parent page.
5895 if( ISAUTOVACUUM ){
5896 ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
5897 if( szCell>pNew->minLocal ){
5898 ptrmapPutOvflPtr(pNew, pCell, &rc);
5902 /* Create a divider cell to insert into pParent. The divider cell
5903 ** consists of a 4-byte page number (the page number of pPage) and
5904 ** a variable length key value (which must be the same value as the
5905 ** largest key on pPage).
5907 ** To find the largest key value on pPage, first find the right-most
5908 ** cell on pPage. The first two fields of this cell are the
5909 ** record-length (a variable length integer at most 32-bits in size)
5910 ** and the key value (a variable length integer, may have any value).
5911 ** The first of the while(...) loops below skips over the record-length
5912 ** field. The second while(...) loop copies the key value from the
5913 ** cell on pPage into the pSpace buffer.
5915 pCell = findCell(pPage, pPage->nCell-1);
5916 pStop = &pCell[9];
5917 while( (*(pCell++)&0x80) && pCell<pStop );
5918 pStop = &pCell[9];
5919 while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
5921 /* Insert the new divider cell into pParent. */
5922 insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
5923 0, pPage->pgno, &rc);
5925 /* Set the right-child pointer of pParent to point to the new page. */
5926 put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
5928 /* Release the reference to the new page. */
5929 releasePage(pNew);
5932 return rc;
5934 #endif /* SQLITE_OMIT_QUICKBALANCE */
5936 #if 0
5938 ** This function does not contribute anything to the operation of SQLite.
5939 ** it is sometimes activated temporarily while debugging code responsible
5940 ** for setting pointer-map entries.
5942 static int ptrmapCheckPages(MemPage **apPage, int nPage){
5943 int i, j;
5944 for(i=0; i<nPage; i++){
5945 Pgno n;
5946 u8 e;
5947 MemPage *pPage = apPage[i];
5948 BtShared *pBt = pPage->pBt;
5949 assert( pPage->isInit );
5951 for(j=0; j<pPage->nCell; j++){
5952 CellInfo info;
5953 u8 *z;
5955 z = findCell(pPage, j);
5956 btreeParseCellPtr(pPage, z, &info);
5957 if( info.iOverflow ){
5958 Pgno ovfl = get4byte(&z[info.iOverflow]);
5959 ptrmapGet(pBt, ovfl, &e, &n);
5960 assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
5962 if( !pPage->leaf ){
5963 Pgno child = get4byte(z);
5964 ptrmapGet(pBt, child, &e, &n);
5965 assert( n==pPage->pgno && e==PTRMAP_BTREE );
5968 if( !pPage->leaf ){
5969 Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
5970 ptrmapGet(pBt, child, &e, &n);
5971 assert( n==pPage->pgno && e==PTRMAP_BTREE );
5974 return 1;
5976 #endif
5979 ** This function is used to copy the contents of the b-tree node stored
5980 ** on page pFrom to page pTo. If page pFrom was not a leaf page, then
5981 ** the pointer-map entries for each child page are updated so that the
5982 ** parent page stored in the pointer map is page pTo. If pFrom contained
5983 ** any cells with overflow page pointers, then the corresponding pointer
5984 ** map entries are also updated so that the parent page is page pTo.
5986 ** If pFrom is currently carrying any overflow cells (entries in the
5987 ** MemPage.apOvfl[] array), they are not copied to pTo.
5989 ** Before returning, page pTo is reinitialized using btreeInitPage().
5991 ** The performance of this function is not critical. It is only used by
5992 ** the balance_shallower() and balance_deeper() procedures, neither of
5993 ** which are called often under normal circumstances.
5995 static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
5996 if( (*pRC)==SQLITE_OK ){
5997 BtShared * const pBt = pFrom->pBt;
5998 u8 * const aFrom = pFrom->aData;
5999 u8 * const aTo = pTo->aData;
6000 int const iFromHdr = pFrom->hdrOffset;
6001 int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
6002 int rc;
6003 int iData;
6006 assert( pFrom->isInit );
6007 assert( pFrom->nFree>=iToHdr );
6008 assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
6010 /* Copy the b-tree node content from page pFrom to page pTo. */
6011 iData = get2byte(&aFrom[iFromHdr+5]);
6012 memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
6013 memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
6015 /* Reinitialize page pTo so that the contents of the MemPage structure
6016 ** match the new data. The initialization of pTo can actually fail under
6017 ** fairly obscure circumstances, even though it is a copy of initialized
6018 ** page pFrom.
6020 pTo->isInit = 0;
6021 rc = btreeInitPage(pTo);
6022 if( rc!=SQLITE_OK ){
6023 *pRC = rc;
6024 return;
6027 /* If this is an auto-vacuum database, update the pointer-map entries
6028 ** for any b-tree or overflow pages that pTo now contains the pointers to.
6030 if( ISAUTOVACUUM ){
6031 *pRC = setChildPtrmaps(pTo);
6037 ** This routine redistributes cells on the iParentIdx'th child of pParent
6038 ** (hereafter "the page") and up to 2 siblings so that all pages have about the
6039 ** same amount of free space. Usually a single sibling on either side of the
6040 ** page are used in the balancing, though both siblings might come from one
6041 ** side if the page is the first or last child of its parent. If the page
6042 ** has fewer than 2 siblings (something which can only happen if the page
6043 ** is a root page or a child of a root page) then all available siblings
6044 ** participate in the balancing.
6046 ** The number of siblings of the page might be increased or decreased by
6047 ** one or two in an effort to keep pages nearly full but not over full.
6049 ** Note that when this routine is called, some of the cells on the page
6050 ** might not actually be stored in MemPage.aData[]. This can happen
6051 ** if the page is overfull. This routine ensures that all cells allocated
6052 ** to the page and its siblings fit into MemPage.aData[] before returning.
6054 ** In the course of balancing the page and its siblings, cells may be
6055 ** inserted into or removed from the parent page (pParent). Doing so
6056 ** may cause the parent page to become overfull or underfull. If this
6057 ** happens, it is the responsibility of the caller to invoke the correct
6058 ** balancing routine to fix this problem (see the balance() routine).
6060 ** If this routine fails for any reason, it might leave the database
6061 ** in a corrupted state. So if this routine fails, the database should
6062 ** be rolled back.
6064 ** The third argument to this function, aOvflSpace, is a pointer to a
6065 ** buffer big enough to hold one page. If while inserting cells into the parent
6066 ** page (pParent) the parent page becomes overfull, this buffer is
6067 ** used to store the parent's overflow cells. Because this function inserts
6068 ** a maximum of four divider cells into the parent page, and the maximum
6069 ** size of a cell stored within an internal node is always less than 1/4
6070 ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
6071 ** enough for all overflow cells.
6073 ** If aOvflSpace is set to a null pointer, this function returns
6074 ** SQLITE_NOMEM.
6076 #if defined(_MSC_VER) && _MSC_VER >= 1700 && defined(_M_ARM)
6077 #pragma optimize("", off)
6078 #endif
6079 static int balance_nonroot(
6080 MemPage *pParent, /* Parent page of siblings being balanced */
6081 int iParentIdx, /* Index of "the page" in pParent */
6082 u8 *aOvflSpace, /* page-size bytes of space for parent ovfl */
6083 int isRoot, /* True if pParent is a root-page */
6084 int bBulk /* True if this call is part of a bulk load */
6086 BtShared *pBt; /* The whole database */
6087 int nCell = 0; /* Number of cells in apCell[] */
6088 int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */
6089 int nNew = 0; /* Number of pages in apNew[] */
6090 int nOld; /* Number of pages in apOld[] */
6091 int i, j, k; /* Loop counters */
6092 int nxDiv; /* Next divider slot in pParent->aCell[] */
6093 int rc = SQLITE_OK; /* The return code */
6094 u16 leafCorrection; /* 4 if pPage is a leaf. 0 if not */
6095 int leafData; /* True if pPage is a leaf of a LEAFDATA tree */
6096 int usableSpace; /* Bytes in pPage beyond the header */
6097 int pageFlags; /* Value of pPage->aData[0] */
6098 int subtotal; /* Subtotal of bytes in cells on one page */
6099 int iSpace1 = 0; /* First unused byte of aSpace1[] */
6100 int iOvflSpace = 0; /* First unused byte of aOvflSpace[] */
6101 int szScratch; /* Size of scratch memory requested */
6102 MemPage *apOld[NB]; /* pPage and up to two siblings */
6103 MemPage *apCopy[NB]; /* Private copies of apOld[] pages */
6104 MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */
6105 u8 *pRight; /* Location in parent of right-sibling pointer */
6106 u8 *apDiv[NB-1]; /* Divider cells in pParent */
6107 int cntNew[NB+2]; /* Index in aCell[] of cell after i-th page */
6108 int szNew[NB+2]; /* Combined size of cells place on i-th page */
6109 u8 **apCell = 0; /* All cells begin balanced */
6110 u16 *szCell; /* Local size of all cells in apCell[] */
6111 u8 *aSpace1; /* Space for copies of dividers cells */
6112 Pgno pgno; /* Temp var to store a page number in */
6114 pBt = pParent->pBt;
6115 assert( sqlite3_mutex_held(pBt->mutex) );
6116 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
6118 #if 0
6119 TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
6120 #endif
6122 /* At this point pParent may have at most one overflow cell. And if
6123 ** this overflow cell is present, it must be the cell with
6124 ** index iParentIdx. This scenario comes about when this function
6125 ** is called (indirectly) from sqlite3BtreeDelete().
6127 assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
6128 assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
6130 if( !aOvflSpace ){
6131 return SQLITE_NOMEM;
6134 /* Find the sibling pages to balance. Also locate the cells in pParent
6135 ** that divide the siblings. An attempt is made to find NN siblings on
6136 ** either side of pPage. More siblings are taken from one side, however,
6137 ** if there are fewer than NN siblings on the other side. If pParent
6138 ** has NB or fewer children then all children of pParent are taken.
6140 ** This loop also drops the divider cells from the parent page. This
6141 ** way, the remainder of the function does not have to deal with any
6142 ** overflow cells in the parent page, since if any existed they will
6143 ** have already been removed.
6145 i = pParent->nOverflow + pParent->nCell;
6146 if( i<2 ){
6147 nxDiv = 0;
6148 }else{
6149 assert( bBulk==0 || bBulk==1 );
6150 if( iParentIdx==0 ){
6151 nxDiv = 0;
6152 }else if( iParentIdx==i ){
6153 nxDiv = i-2+bBulk;
6154 }else{
6155 assert( bBulk==0 );
6156 nxDiv = iParentIdx-1;
6158 i = 2-bBulk;
6160 nOld = i+1;
6161 if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
6162 pRight = &pParent->aData[pParent->hdrOffset+8];
6163 }else{
6164 pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
6166 pgno = get4byte(pRight);
6167 while( 1 ){
6168 rc = getAndInitPage(pBt, pgno, &apOld[i], 0);
6169 if( rc ){
6170 memset(apOld, 0, (i+1)*sizeof(MemPage*));
6171 goto balance_cleanup;
6173 nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
6174 if( (i--)==0 ) break;
6176 if( i+nxDiv==pParent->aiOvfl[0] && pParent->nOverflow ){
6177 apDiv[i] = pParent->apOvfl[0];
6178 pgno = get4byte(apDiv[i]);
6179 szNew[i] = cellSizePtr(pParent, apDiv[i]);
6180 pParent->nOverflow = 0;
6181 }else{
6182 apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
6183 pgno = get4byte(apDiv[i]);
6184 szNew[i] = cellSizePtr(pParent, apDiv[i]);
6186 /* Drop the cell from the parent page. apDiv[i] still points to
6187 ** the cell within the parent, even though it has been dropped.
6188 ** This is safe because dropping a cell only overwrites the first
6189 ** four bytes of it, and this function does not need the first
6190 ** four bytes of the divider cell. So the pointer is safe to use
6191 ** later on.
6193 ** But not if we are in secure-delete mode. In secure-delete mode,
6194 ** the dropCell() routine will overwrite the entire cell with zeroes.
6195 ** In this case, temporarily copy the cell into the aOvflSpace[]
6196 ** buffer. It will be copied out again as soon as the aSpace[] buffer
6197 ** is allocated. */
6198 if( pBt->btsFlags & BTS_SECURE_DELETE ){
6199 int iOff;
6201 iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
6202 if( (iOff+szNew[i])>(int)pBt->usableSize ){
6203 rc = SQLITE_CORRUPT_BKPT;
6204 memset(apOld, 0, (i+1)*sizeof(MemPage*));
6205 goto balance_cleanup;
6206 }else{
6207 memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
6208 apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
6211 dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
6215 /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
6216 ** alignment */
6217 nMaxCells = (nMaxCells + 3)&~3;
6220 ** Allocate space for memory structures
6222 k = pBt->pageSize + ROUND8(sizeof(MemPage));
6223 szScratch =
6224 nMaxCells*sizeof(u8*) /* apCell */
6225 + nMaxCells*sizeof(u16) /* szCell */
6226 + pBt->pageSize /* aSpace1 */
6227 + k*nOld; /* Page copies (apCopy) */
6228 apCell = sqlite3ScratchMalloc( szScratch );
6229 if( apCell==0 ){
6230 rc = SQLITE_NOMEM;
6231 goto balance_cleanup;
6233 szCell = (u16*)&apCell[nMaxCells];
6234 aSpace1 = (u8*)&szCell[nMaxCells];
6235 assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
6238 ** Load pointers to all cells on sibling pages and the divider cells
6239 ** into the local apCell[] array. Make copies of the divider cells
6240 ** into space obtained from aSpace1[] and remove the divider cells
6241 ** from pParent.
6243 ** If the siblings are on leaf pages, then the child pointers of the
6244 ** divider cells are stripped from the cells before they are copied
6245 ** into aSpace1[]. In this way, all cells in apCell[] are without
6246 ** child pointers. If siblings are not leaves, then all cell in
6247 ** apCell[] include child pointers. Either way, all cells in apCell[]
6248 ** are alike.
6250 ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf.
6251 ** leafData: 1 if pPage holds key+data and pParent holds only keys.
6253 leafCorrection = apOld[0]->leaf*4;
6254 leafData = apOld[0]->hasData;
6255 for(i=0; i<nOld; i++){
6256 int limit;
6258 /* Before doing anything else, take a copy of the i'th original sibling
6259 ** The rest of this function will use data from the copies rather
6260 ** that the original pages since the original pages will be in the
6261 ** process of being overwritten. */
6262 MemPage *pOld = apCopy[i] = (MemPage*)&aSpace1[pBt->pageSize + k*i];
6263 memcpy(pOld, apOld[i], sizeof(MemPage));
6264 pOld->aData = (void*)&pOld[1];
6265 memcpy(pOld->aData, apOld[i]->aData, pBt->pageSize);
6267 limit = pOld->nCell+pOld->nOverflow;
6268 if( pOld->nOverflow>0 ){
6269 for(j=0; j<limit; j++){
6270 assert( nCell<nMaxCells );
6271 apCell[nCell] = findOverflowCell(pOld, j);
6272 szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
6273 nCell++;
6275 }else{
6276 u8 *aData = pOld->aData;
6277 u16 maskPage = pOld->maskPage;
6278 u16 cellOffset = pOld->cellOffset;
6279 for(j=0; j<limit; j++){
6280 assert( nCell<nMaxCells );
6281 apCell[nCell] = findCellv2(aData, maskPage, cellOffset, j);
6282 szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
6283 nCell++;
6286 if( i<nOld-1 && !leafData){
6287 u16 sz = (u16)szNew[i];
6288 u8 *pTemp;
6289 assert( nCell<nMaxCells );
6290 szCell[nCell] = sz;
6291 pTemp = &aSpace1[iSpace1];
6292 iSpace1 += sz;
6293 assert( sz<=pBt->maxLocal+23 );
6294 assert( iSpace1 <= (int)pBt->pageSize );
6295 memcpy(pTemp, apDiv[i], sz);
6296 apCell[nCell] = pTemp+leafCorrection;
6297 assert( leafCorrection==0 || leafCorrection==4 );
6298 szCell[nCell] = szCell[nCell] - leafCorrection;
6299 if( !pOld->leaf ){
6300 assert( leafCorrection==0 );
6301 assert( pOld->hdrOffset==0 );
6302 /* The right pointer of the child page pOld becomes the left
6303 ** pointer of the divider cell */
6304 memcpy(apCell[nCell], &pOld->aData[8], 4);
6305 }else{
6306 assert( leafCorrection==4 );
6307 if( szCell[nCell]<4 ){
6308 /* Do not allow any cells smaller than 4 bytes. */
6309 szCell[nCell] = 4;
6312 nCell++;
6317 ** Figure out the number of pages needed to hold all nCell cells.
6318 ** Store this number in "k". Also compute szNew[] which is the total
6319 ** size of all cells on the i-th page and cntNew[] which is the index
6320 ** in apCell[] of the cell that divides page i from page i+1.
6321 ** cntNew[k] should equal nCell.
6323 ** Values computed by this block:
6325 ** k: The total number of sibling pages
6326 ** szNew[i]: Spaced used on the i-th sibling page.
6327 ** cntNew[i]: Index in apCell[] and szCell[] for the first cell to
6328 ** the right of the i-th sibling page.
6329 ** usableSpace: Number of bytes of space available on each sibling.
6332 usableSpace = pBt->usableSize - 12 + leafCorrection;
6333 for(subtotal=k=i=0; i<nCell; i++){
6334 assert( i<nMaxCells );
6335 subtotal += szCell[i] + 2;
6336 if( subtotal > usableSpace ){
6337 szNew[k] = subtotal - szCell[i];
6338 cntNew[k] = i;
6339 if( leafData ){ i--; }
6340 subtotal = 0;
6341 k++;
6342 if( k>NB+1 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
6345 szNew[k] = subtotal;
6346 cntNew[k] = nCell;
6347 k++;
6350 ** The packing computed by the previous block is biased toward the siblings
6351 ** on the left side. The left siblings are always nearly full, while the
6352 ** right-most sibling might be nearly empty. This block of code attempts
6353 ** to adjust the packing of siblings to get a better balance.
6355 ** This adjustment is more than an optimization. The packing above might
6356 ** be so out of balance as to be illegal. For example, the right-most
6357 ** sibling might be completely empty. This adjustment is not optional.
6359 for(i=k-1; i>0; i--){
6360 int szRight = szNew[i]; /* Size of sibling on the right */
6361 int szLeft = szNew[i-1]; /* Size of sibling on the left */
6362 int r; /* Index of right-most cell in left sibling */
6363 int d; /* Index of first cell to the left of right sibling */
6365 r = cntNew[i-1] - 1;
6366 d = r + 1 - leafData;
6367 assert( d<nMaxCells );
6368 assert( r<nMaxCells );
6369 while( szRight==0
6370 || (!bBulk && szRight+szCell[d]+2<=szLeft-(szCell[r]+2))
6372 szRight += szCell[d] + 2;
6373 szLeft -= szCell[r] + 2;
6374 cntNew[i-1]--;
6375 r = cntNew[i-1] - 1;
6376 d = r + 1 - leafData;
6378 szNew[i] = szRight;
6379 szNew[i-1] = szLeft;
6382 /* Either we found one or more cells (cntnew[0])>0) or pPage is
6383 ** a virtual root page. A virtual root page is when the real root
6384 ** page is page 1 and we are the only child of that page.
6386 ** UPDATE: The assert() below is not necessarily true if the database
6387 ** file is corrupt. The corruption will be detected and reported later
6388 ** in this procedure so there is no need to act upon it now.
6390 #if 0
6391 assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
6392 #endif
6394 TRACE(("BALANCE: old: %d %d %d ",
6395 apOld[0]->pgno,
6396 nOld>=2 ? apOld[1]->pgno : 0,
6397 nOld>=3 ? apOld[2]->pgno : 0
6401 ** Allocate k new pages. Reuse old pages where possible.
6403 if( apOld[0]->pgno<=1 ){
6404 rc = SQLITE_CORRUPT_BKPT;
6405 goto balance_cleanup;
6407 pageFlags = apOld[0]->aData[0];
6408 for(i=0; i<k; i++){
6409 MemPage *pNew;
6410 if( i<nOld ){
6411 pNew = apNew[i] = apOld[i];
6412 apOld[i] = 0;
6413 rc = sqlite3PagerWrite(pNew->pDbPage);
6414 nNew++;
6415 if( rc ) goto balance_cleanup;
6416 }else{
6417 assert( i>0 );
6418 rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0);
6419 if( rc ) goto balance_cleanup;
6420 apNew[i] = pNew;
6421 nNew++;
6423 /* Set the pointer-map entry for the new sibling page. */
6424 if( ISAUTOVACUUM ){
6425 ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
6426 if( rc!=SQLITE_OK ){
6427 goto balance_cleanup;
6433 /* Free any old pages that were not reused as new pages.
6435 while( i<nOld ){
6436 freePage(apOld[i], &rc);
6437 if( rc ) goto balance_cleanup;
6438 releasePage(apOld[i]);
6439 apOld[i] = 0;
6440 i++;
6444 ** Put the new pages in accending order. This helps to
6445 ** keep entries in the disk file in order so that a scan
6446 ** of the table is a linear scan through the file. That
6447 ** in turn helps the operating system to deliver pages
6448 ** from the disk more rapidly.
6450 ** An O(n^2) insertion sort algorithm is used, but since
6451 ** n is never more than NB (a small constant), that should
6452 ** not be a problem.
6454 ** When NB==3, this one optimization makes the database
6455 ** about 25% faster for large insertions and deletions.
6457 for(i=0; i<k-1; i++){
6458 int minV = apNew[i]->pgno;
6459 int minI = i;
6460 for(j=i+1; j<k; j++){
6461 if( apNew[j]->pgno<(unsigned)minV ){
6462 minI = j;
6463 minV = apNew[j]->pgno;
6466 if( minI>i ){
6467 MemPage *pT;
6468 pT = apNew[i];
6469 apNew[i] = apNew[minI];
6470 apNew[minI] = pT;
6473 TRACE(("new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
6474 apNew[0]->pgno, szNew[0],
6475 nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
6476 nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
6477 nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
6478 nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0));
6480 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
6481 put4byte(pRight, apNew[nNew-1]->pgno);
6484 ** Evenly distribute the data in apCell[] across the new pages.
6485 ** Insert divider cells into pParent as necessary.
6487 j = 0;
6488 for(i=0; i<nNew; i++){
6489 /* Assemble the new sibling page. */
6490 MemPage *pNew = apNew[i];
6491 assert( j<nMaxCells );
6492 zeroPage(pNew, pageFlags);
6493 assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
6494 assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
6495 assert( pNew->nOverflow==0 );
6497 j = cntNew[i];
6499 /* If the sibling page assembled above was not the right-most sibling,
6500 ** insert a divider cell into the parent page.
6502 assert( i<nNew-1 || j==nCell );
6503 if( j<nCell ){
6504 u8 *pCell;
6505 u8 *pTemp;
6506 int sz;
6508 assert( j<nMaxCells );
6509 pCell = apCell[j];
6510 sz = szCell[j] + leafCorrection;
6511 pTemp = &aOvflSpace[iOvflSpace];
6512 if( !pNew->leaf ){
6513 memcpy(&pNew->aData[8], pCell, 4);
6514 }else if( leafData ){
6515 /* If the tree is a leaf-data tree, and the siblings are leaves,
6516 ** then there is no divider cell in apCell[]. Instead, the divider
6517 ** cell consists of the integer key for the right-most cell of
6518 ** the sibling-page assembled above only.
6520 CellInfo info;
6521 j--;
6522 btreeParseCellPtr(pNew, apCell[j], &info);
6523 pCell = pTemp;
6524 sz = 4 + putVarint(&pCell[4], info.nKey);
6525 pTemp = 0;
6526 }else{
6527 pCell -= 4;
6528 /* Obscure case for non-leaf-data trees: If the cell at pCell was
6529 ** previously stored on a leaf node, and its reported size was 4
6530 ** bytes, then it may actually be smaller than this
6531 ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
6532 ** any cell). But it is important to pass the correct size to
6533 ** insertCell(), so reparse the cell now.
6535 ** Note that this can never happen in an SQLite data file, as all
6536 ** cells are at least 4 bytes. It only happens in b-trees used
6537 ** to evaluate "IN (SELECT ...)" and similar clauses.
6539 if( szCell[j]==4 ){
6540 assert(leafCorrection==4);
6541 sz = cellSizePtr(pParent, pCell);
6544 iOvflSpace += sz;
6545 assert( sz<=pBt->maxLocal+23 );
6546 assert( iOvflSpace <= (int)pBt->pageSize );
6547 insertCell(pParent, nxDiv, pCell, sz, pTemp, pNew->pgno, &rc);
6548 if( rc!=SQLITE_OK ) goto balance_cleanup;
6549 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
6551 j++;
6552 nxDiv++;
6555 assert( j==nCell );
6556 assert( nOld>0 );
6557 assert( nNew>0 );
6558 if( (pageFlags & PTF_LEAF)==0 ){
6559 u8 *zChild = &apCopy[nOld-1]->aData[8];
6560 memcpy(&apNew[nNew-1]->aData[8], zChild, 4);
6563 if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
6564 /* The root page of the b-tree now contains no cells. The only sibling
6565 ** page is the right-child of the parent. Copy the contents of the
6566 ** child page into the parent, decreasing the overall height of the
6567 ** b-tree structure by one. This is described as the "balance-shallower"
6568 ** sub-algorithm in some documentation.
6570 ** If this is an auto-vacuum database, the call to copyNodeContent()
6571 ** sets all pointer-map entries corresponding to database image pages
6572 ** for which the pointer is stored within the content being copied.
6574 ** The second assert below verifies that the child page is defragmented
6575 ** (it must be, as it was just reconstructed using assemblePage()). This
6576 ** is important if the parent page happens to be page 1 of the database
6577 ** image. */
6578 assert( nNew==1 );
6579 assert( apNew[0]->nFree ==
6580 (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2)
6582 copyNodeContent(apNew[0], pParent, &rc);
6583 freePage(apNew[0], &rc);
6584 }else if( ISAUTOVACUUM ){
6585 /* Fix the pointer-map entries for all the cells that were shifted around.
6586 ** There are several different types of pointer-map entries that need to
6587 ** be dealt with by this routine. Some of these have been set already, but
6588 ** many have not. The following is a summary:
6590 ** 1) The entries associated with new sibling pages that were not
6591 ** siblings when this function was called. These have already
6592 ** been set. We don't need to worry about old siblings that were
6593 ** moved to the free-list - the freePage() code has taken care
6594 ** of those.
6596 ** 2) The pointer-map entries associated with the first overflow
6597 ** page in any overflow chains used by new divider cells. These
6598 ** have also already been taken care of by the insertCell() code.
6600 ** 3) If the sibling pages are not leaves, then the child pages of
6601 ** cells stored on the sibling pages may need to be updated.
6603 ** 4) If the sibling pages are not internal intkey nodes, then any
6604 ** overflow pages used by these cells may need to be updated
6605 ** (internal intkey nodes never contain pointers to overflow pages).
6607 ** 5) If the sibling pages are not leaves, then the pointer-map
6608 ** entries for the right-child pages of each sibling may need
6609 ** to be updated.
6611 ** Cases 1 and 2 are dealt with above by other code. The next
6612 ** block deals with cases 3 and 4 and the one after that, case 5. Since
6613 ** setting a pointer map entry is a relatively expensive operation, this
6614 ** code only sets pointer map entries for child or overflow pages that have
6615 ** actually moved between pages. */
6616 MemPage *pNew = apNew[0];
6617 MemPage *pOld = apCopy[0];
6618 int nOverflow = pOld->nOverflow;
6619 int iNextOld = pOld->nCell + nOverflow;
6620 int iOverflow = (nOverflow ? pOld->aiOvfl[0] : -1);
6621 j = 0; /* Current 'old' sibling page */
6622 k = 0; /* Current 'new' sibling page */
6623 for(i=0; i<nCell; i++){
6624 int isDivider = 0;
6625 while( i==iNextOld ){
6626 /* Cell i is the cell immediately following the last cell on old
6627 ** sibling page j. If the siblings are not leaf pages of an
6628 ** intkey b-tree, then cell i was a divider cell. */
6629 assert( j+1 < ArraySize(apCopy) );
6630 assert( j+1 < nOld );
6631 pOld = apCopy[++j];
6632 iNextOld = i + !leafData + pOld->nCell + pOld->nOverflow;
6633 if( pOld->nOverflow ){
6634 nOverflow = pOld->nOverflow;
6635 iOverflow = i + !leafData + pOld->aiOvfl[0];
6637 isDivider = !leafData;
6640 assert(nOverflow>0 || iOverflow<i );
6641 assert(nOverflow<2 || pOld->aiOvfl[0]==pOld->aiOvfl[1]-1);
6642 assert(nOverflow<3 || pOld->aiOvfl[1]==pOld->aiOvfl[2]-1);
6643 if( i==iOverflow ){
6644 isDivider = 1;
6645 if( (--nOverflow)>0 ){
6646 iOverflow++;
6650 if( i==cntNew[k] ){
6651 /* Cell i is the cell immediately following the last cell on new
6652 ** sibling page k. If the siblings are not leaf pages of an
6653 ** intkey b-tree, then cell i is a divider cell. */
6654 pNew = apNew[++k];
6655 if( !leafData ) continue;
6657 assert( j<nOld );
6658 assert( k<nNew );
6660 /* If the cell was originally divider cell (and is not now) or
6661 ** an overflow cell, or if the cell was located on a different sibling
6662 ** page before the balancing, then the pointer map entries associated
6663 ** with any child or overflow pages need to be updated. */
6664 if( isDivider || pOld->pgno!=pNew->pgno ){
6665 if( !leafCorrection ){
6666 ptrmapPut(pBt, get4byte(apCell[i]), PTRMAP_BTREE, pNew->pgno, &rc);
6668 if( szCell[i]>pNew->minLocal ){
6669 ptrmapPutOvflPtr(pNew, apCell[i], &rc);
6674 if( !leafCorrection ){
6675 for(i=0; i<nNew; i++){
6676 u32 key = get4byte(&apNew[i]->aData[8]);
6677 ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
6681 #if 0
6682 /* The ptrmapCheckPages() contains assert() statements that verify that
6683 ** all pointer map pages are set correctly. This is helpful while
6684 ** debugging. This is usually disabled because a corrupt database may
6685 ** cause an assert() statement to fail. */
6686 ptrmapCheckPages(apNew, nNew);
6687 ptrmapCheckPages(&pParent, 1);
6688 #endif
6691 assert( pParent->isInit );
6692 TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
6693 nOld, nNew, nCell));
6696 ** Cleanup before returning.
6698 balance_cleanup:
6699 sqlite3ScratchFree(apCell);
6700 for(i=0; i<nOld; i++){
6701 releasePage(apOld[i]);
6703 for(i=0; i<nNew; i++){
6704 releasePage(apNew[i]);
6707 return rc;
6709 #if defined(_MSC_VER) && _MSC_VER >= 1700 && defined(_M_ARM)
6710 #pragma optimize("", on)
6711 #endif
6715 ** This function is called when the root page of a b-tree structure is
6716 ** overfull (has one or more overflow pages).
6718 ** A new child page is allocated and the contents of the current root
6719 ** page, including overflow cells, are copied into the child. The root
6720 ** page is then overwritten to make it an empty page with the right-child
6721 ** pointer pointing to the new page.
6723 ** Before returning, all pointer-map entries corresponding to pages
6724 ** that the new child-page now contains pointers to are updated. The
6725 ** entry corresponding to the new right-child pointer of the root
6726 ** page is also updated.
6728 ** If successful, *ppChild is set to contain a reference to the child
6729 ** page and SQLITE_OK is returned. In this case the caller is required
6730 ** to call releasePage() on *ppChild exactly once. If an error occurs,
6731 ** an error code is returned and *ppChild is set to 0.
6733 static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
6734 int rc; /* Return value from subprocedures */
6735 MemPage *pChild = 0; /* Pointer to a new child page */
6736 Pgno pgnoChild = 0; /* Page number of the new child page */
6737 BtShared *pBt = pRoot->pBt; /* The BTree */
6739 assert( pRoot->nOverflow>0 );
6740 assert( sqlite3_mutex_held(pBt->mutex) );
6742 /* Make pRoot, the root page of the b-tree, writable. Allocate a new
6743 ** page that will become the new right-child of pPage. Copy the contents
6744 ** of the node stored on pRoot into the new child page.
6746 rc = sqlite3PagerWrite(pRoot->pDbPage);
6747 if( rc==SQLITE_OK ){
6748 rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
6749 copyNodeContent(pRoot, pChild, &rc);
6750 if( ISAUTOVACUUM ){
6751 ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
6754 if( rc ){
6755 *ppChild = 0;
6756 releasePage(pChild);
6757 return rc;
6759 assert( sqlite3PagerIswriteable(pChild->pDbPage) );
6760 assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
6761 assert( pChild->nCell==pRoot->nCell );
6763 TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
6765 /* Copy the overflow cells from pRoot to pChild */
6766 memcpy(pChild->aiOvfl, pRoot->aiOvfl,
6767 pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
6768 memcpy(pChild->apOvfl, pRoot->apOvfl,
6769 pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
6770 pChild->nOverflow = pRoot->nOverflow;
6772 /* Zero the contents of pRoot. Then install pChild as the right-child. */
6773 zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
6774 put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
6776 *ppChild = pChild;
6777 return SQLITE_OK;
6781 ** The page that pCur currently points to has just been modified in
6782 ** some way. This function figures out if this modification means the
6783 ** tree needs to be balanced, and if so calls the appropriate balancing
6784 ** routine. Balancing routines are:
6786 ** balance_quick()
6787 ** balance_deeper()
6788 ** balance_nonroot()
6790 static int balance(BtCursor *pCur){
6791 int rc = SQLITE_OK;
6792 const int nMin = pCur->pBt->usableSize * 2 / 3;
6793 u8 aBalanceQuickSpace[13];
6794 u8 *pFree = 0;
6796 TESTONLY( int balance_quick_called = 0 );
6797 TESTONLY( int balance_deeper_called = 0 );
6799 do {
6800 int iPage = pCur->iPage;
6801 MemPage *pPage = pCur->apPage[iPage];
6803 if( iPage==0 ){
6804 if( pPage->nOverflow ){
6805 /* The root page of the b-tree is overfull. In this case call the
6806 ** balance_deeper() function to create a new child for the root-page
6807 ** and copy the current contents of the root-page to it. The
6808 ** next iteration of the do-loop will balance the child page.
6810 assert( (balance_deeper_called++)==0 );
6811 rc = balance_deeper(pPage, &pCur->apPage[1]);
6812 if( rc==SQLITE_OK ){
6813 pCur->iPage = 1;
6814 pCur->aiIdx[0] = 0;
6815 pCur->aiIdx[1] = 0;
6816 assert( pCur->apPage[1]->nOverflow );
6818 }else{
6819 break;
6821 }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
6822 break;
6823 }else{
6824 MemPage * const pParent = pCur->apPage[iPage-1];
6825 int const iIdx = pCur->aiIdx[iPage-1];
6827 rc = sqlite3PagerWrite(pParent->pDbPage);
6828 if( rc==SQLITE_OK ){
6829 #ifndef SQLITE_OMIT_QUICKBALANCE
6830 if( pPage->hasData
6831 && pPage->nOverflow==1
6832 && pPage->aiOvfl[0]==pPage->nCell
6833 && pParent->pgno!=1
6834 && pParent->nCell==iIdx
6836 /* Call balance_quick() to create a new sibling of pPage on which
6837 ** to store the overflow cell. balance_quick() inserts a new cell
6838 ** into pParent, which may cause pParent overflow. If this
6839 ** happens, the next interation of the do-loop will balance pParent
6840 ** use either balance_nonroot() or balance_deeper(). Until this
6841 ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
6842 ** buffer.
6844 ** The purpose of the following assert() is to check that only a
6845 ** single call to balance_quick() is made for each call to this
6846 ** function. If this were not verified, a subtle bug involving reuse
6847 ** of the aBalanceQuickSpace[] might sneak in.
6849 assert( (balance_quick_called++)==0 );
6850 rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
6851 }else
6852 #endif
6854 /* In this case, call balance_nonroot() to redistribute cells
6855 ** between pPage and up to 2 of its sibling pages. This involves
6856 ** modifying the contents of pParent, which may cause pParent to
6857 ** become overfull or underfull. The next iteration of the do-loop
6858 ** will balance the parent page to correct this.
6860 ** If the parent page becomes overfull, the overflow cell or cells
6861 ** are stored in the pSpace buffer allocated immediately below.
6862 ** A subsequent iteration of the do-loop will deal with this by
6863 ** calling balance_nonroot() (balance_deeper() may be called first,
6864 ** but it doesn't deal with overflow cells - just moves them to a
6865 ** different page). Once this subsequent call to balance_nonroot()
6866 ** has completed, it is safe to release the pSpace buffer used by
6867 ** the previous call, as the overflow cell data will have been
6868 ** copied either into the body of a database page or into the new
6869 ** pSpace buffer passed to the latter call to balance_nonroot().
6871 u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
6872 rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1, pCur->hints);
6873 if( pFree ){
6874 /* If pFree is not NULL, it points to the pSpace buffer used
6875 ** by a previous call to balance_nonroot(). Its contents are
6876 ** now stored either on real database pages or within the
6877 ** new pSpace buffer, so it may be safely freed here. */
6878 sqlite3PageFree(pFree);
6881 /* The pSpace buffer will be freed after the next call to
6882 ** balance_nonroot(), or just before this function returns, whichever
6883 ** comes first. */
6884 pFree = pSpace;
6888 pPage->nOverflow = 0;
6890 /* The next iteration of the do-loop balances the parent page. */
6891 releasePage(pPage);
6892 pCur->iPage--;
6894 }while( rc==SQLITE_OK );
6896 if( pFree ){
6897 sqlite3PageFree(pFree);
6899 return rc;
6904 ** Insert a new record into the BTree. The key is given by (pKey,nKey)
6905 ** and the data is given by (pData,nData). The cursor is used only to
6906 ** define what table the record should be inserted into. The cursor
6907 ** is left pointing at a random location.
6909 ** For an INTKEY table, only the nKey value of the key is used. pKey is
6910 ** ignored. For a ZERODATA table, the pData and nData are both ignored.
6912 ** If the seekResult parameter is non-zero, then a successful call to
6913 ** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already
6914 ** been performed. seekResult is the search result returned (a negative
6915 ** number if pCur points at an entry that is smaller than (pKey, nKey), or
6916 ** a positive value if pCur points at an etry that is larger than
6917 ** (pKey, nKey)).
6919 ** If the seekResult parameter is non-zero, then the caller guarantees that
6920 ** cursor pCur is pointing at the existing copy of a row that is to be
6921 ** overwritten. If the seekResult parameter is 0, then cursor pCur may
6922 ** point to any entry or to no entry at all and so this function has to seek
6923 ** the cursor before the new key can be inserted.
6925 int sqlite3BtreeInsert(
6926 BtCursor *pCur, /* Insert data into the table of this cursor */
6927 const void *pKey, i64 nKey, /* The key of the new record */
6928 const void *pData, int nData, /* The data of the new record */
6929 int nZero, /* Number of extra 0 bytes to append to data */
6930 int appendBias, /* True if this is likely an append */
6931 int seekResult /* Result of prior MovetoUnpacked() call */
6933 int rc;
6934 int loc = seekResult; /* -1: before desired location +1: after */
6935 int szNew = 0;
6936 int idx;
6937 MemPage *pPage;
6938 Btree *p = pCur->pBtree;
6939 BtShared *pBt = p->pBt;
6940 unsigned char *oldCell;
6941 unsigned char *newCell = 0;
6943 if( pCur->eState==CURSOR_FAULT ){
6944 assert( pCur->skipNext!=SQLITE_OK );
6945 return pCur->skipNext;
6948 assert( cursorHoldsMutex(pCur) );
6949 assert( pCur->wrFlag && pBt->inTransaction==TRANS_WRITE
6950 && (pBt->btsFlags & BTS_READ_ONLY)==0 );
6951 assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
6953 /* Assert that the caller has been consistent. If this cursor was opened
6954 ** expecting an index b-tree, then the caller should be inserting blob
6955 ** keys with no associated data. If the cursor was opened expecting an
6956 ** intkey table, the caller should be inserting integer keys with a
6957 ** blob of associated data. */
6958 assert( (pKey==0)==(pCur->pKeyInfo==0) );
6960 /* Save the positions of any other cursors open on this table.
6962 ** In some cases, the call to btreeMoveto() below is a no-op. For
6963 ** example, when inserting data into a table with auto-generated integer
6964 ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
6965 ** integer key to use. It then calls this function to actually insert the
6966 ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
6967 ** that the cursor is already where it needs to be and returns without
6968 ** doing any work. To avoid thwarting these optimizations, it is important
6969 ** not to clear the cursor here.
6971 rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
6972 if( rc ) return rc;
6974 /* If this is an insert into a table b-tree, invalidate any incrblob
6975 ** cursors open on the row being replaced (assuming this is a replace
6976 ** operation - if it is not, the following is a no-op). */
6977 if( pCur->pKeyInfo==0 ){
6978 invalidateIncrblobCursors(p, nKey, 0);
6981 if( !loc ){
6982 rc = btreeMoveto(pCur, pKey, nKey, appendBias, &loc);
6983 if( rc ) return rc;
6985 assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
6987 pPage = pCur->apPage[pCur->iPage];
6988 assert( pPage->intKey || nKey>=0 );
6989 assert( pPage->leaf || !pPage->intKey );
6991 TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
6992 pCur->pgnoRoot, nKey, nData, pPage->pgno,
6993 loc==0 ? "overwrite" : "new entry"));
6994 assert( pPage->isInit );
6995 allocateTempSpace(pBt);
6996 newCell = pBt->pTmpSpace;
6997 if( newCell==0 ) return SQLITE_NOMEM;
6998 rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
6999 if( rc ) goto end_insert;
7000 assert( szNew==cellSizePtr(pPage, newCell) );
7001 assert( szNew <= MX_CELL_SIZE(pBt) );
7002 idx = pCur->aiIdx[pCur->iPage];
7003 if( loc==0 ){
7004 u16 szOld;
7005 assert( idx<pPage->nCell );
7006 rc = sqlite3PagerWrite(pPage->pDbPage);
7007 if( rc ){
7008 goto end_insert;
7010 oldCell = findCell(pPage, idx);
7011 if( !pPage->leaf ){
7012 memcpy(newCell, oldCell, 4);
7014 szOld = cellSizePtr(pPage, oldCell);
7015 rc = clearCell(pPage, oldCell);
7016 dropCell(pPage, idx, szOld, &rc);
7017 if( rc ) goto end_insert;
7018 }else if( loc<0 && pPage->nCell>0 ){
7019 assert( pPage->leaf );
7020 idx = ++pCur->aiIdx[pCur->iPage];
7021 }else{
7022 assert( pPage->leaf );
7024 insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
7025 assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
7027 /* If no error has occurred and pPage has an overflow cell, call balance()
7028 ** to redistribute the cells within the tree. Since balance() may move
7029 ** the cursor, zero the BtCursor.info.nSize and BtCursor.validNKey
7030 ** variables.
7032 ** Previous versions of SQLite called moveToRoot() to move the cursor
7033 ** back to the root page as balance() used to invalidate the contents
7034 ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
7035 ** set the cursor state to "invalid". This makes common insert operations
7036 ** slightly faster.
7038 ** There is a subtle but important optimization here too. When inserting
7039 ** multiple records into an intkey b-tree using a single cursor (as can
7040 ** happen while processing an "INSERT INTO ... SELECT" statement), it
7041 ** is advantageous to leave the cursor pointing to the last entry in
7042 ** the b-tree if possible. If the cursor is left pointing to the last
7043 ** entry in the table, and the next row inserted has an integer key
7044 ** larger than the largest existing key, it is possible to insert the
7045 ** row without seeking the cursor. This can be a big performance boost.
7047 pCur->info.nSize = 0;
7048 pCur->validNKey = 0;
7049 if( rc==SQLITE_OK && pPage->nOverflow ){
7050 rc = balance(pCur);
7052 /* Must make sure nOverflow is reset to zero even if the balance()
7053 ** fails. Internal data structure corruption will result otherwise.
7054 ** Also, set the cursor state to invalid. This stops saveCursorPosition()
7055 ** from trying to save the current position of the cursor. */
7056 pCur->apPage[pCur->iPage]->nOverflow = 0;
7057 pCur->eState = CURSOR_INVALID;
7059 assert( pCur->apPage[pCur->iPage]->nOverflow==0 );
7061 end_insert:
7062 return rc;
7066 ** Delete the entry that the cursor is pointing to. The cursor
7067 ** is left pointing at a arbitrary location.
7069 int sqlite3BtreeDelete(BtCursor *pCur){
7070 Btree *p = pCur->pBtree;
7071 BtShared *pBt = p->pBt;
7072 int rc; /* Return code */
7073 MemPage *pPage; /* Page to delete cell from */
7074 unsigned char *pCell; /* Pointer to cell to delete */
7075 int iCellIdx; /* Index of cell to delete */
7076 int iCellDepth; /* Depth of node containing pCell */
7078 assert( cursorHoldsMutex(pCur) );
7079 assert( pBt->inTransaction==TRANS_WRITE );
7080 assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
7081 assert( pCur->wrFlag );
7082 assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
7083 assert( !hasReadConflicts(p, pCur->pgnoRoot) );
7085 if( NEVER(pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell)
7086 || NEVER(pCur->eState!=CURSOR_VALID)
7088 return SQLITE_ERROR; /* Something has gone awry. */
7091 iCellDepth = pCur->iPage;
7092 iCellIdx = pCur->aiIdx[iCellDepth];
7093 pPage = pCur->apPage[iCellDepth];
7094 pCell = findCell(pPage, iCellIdx);
7096 /* If the page containing the entry to delete is not a leaf page, move
7097 ** the cursor to the largest entry in the tree that is smaller than
7098 ** the entry being deleted. This cell will replace the cell being deleted
7099 ** from the internal node. The 'previous' entry is used for this instead
7100 ** of the 'next' entry, as the previous entry is always a part of the
7101 ** sub-tree headed by the child page of the cell being deleted. This makes
7102 ** balancing the tree following the delete operation easier. */
7103 if( !pPage->leaf ){
7104 int notUsed;
7105 rc = sqlite3BtreePrevious(pCur, &notUsed);
7106 if( rc ) return rc;
7109 /* Save the positions of any other cursors open on this table before
7110 ** making any modifications. Make the page containing the entry to be
7111 ** deleted writable. Then free any overflow pages associated with the
7112 ** entry and finally remove the cell itself from within the page.
7114 rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
7115 if( rc ) return rc;
7117 /* If this is a delete operation to remove a row from a table b-tree,
7118 ** invalidate any incrblob cursors open on the row being deleted. */
7119 if( pCur->pKeyInfo==0 ){
7120 invalidateIncrblobCursors(p, pCur->info.nKey, 0);
7123 rc = sqlite3PagerWrite(pPage->pDbPage);
7124 if( rc ) return rc;
7125 rc = clearCell(pPage, pCell);
7126 dropCell(pPage, iCellIdx, cellSizePtr(pPage, pCell), &rc);
7127 if( rc ) return rc;
7129 /* If the cell deleted was not located on a leaf page, then the cursor
7130 ** is currently pointing to the largest entry in the sub-tree headed
7131 ** by the child-page of the cell that was just deleted from an internal
7132 ** node. The cell from the leaf node needs to be moved to the internal
7133 ** node to replace the deleted cell. */
7134 if( !pPage->leaf ){
7135 MemPage *pLeaf = pCur->apPage[pCur->iPage];
7136 int nCell;
7137 Pgno n = pCur->apPage[iCellDepth+1]->pgno;
7138 unsigned char *pTmp;
7140 pCell = findCell(pLeaf, pLeaf->nCell-1);
7141 nCell = cellSizePtr(pLeaf, pCell);
7142 assert( MX_CELL_SIZE(pBt) >= nCell );
7144 allocateTempSpace(pBt);
7145 pTmp = pBt->pTmpSpace;
7147 rc = sqlite3PagerWrite(pLeaf->pDbPage);
7148 insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
7149 dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
7150 if( rc ) return rc;
7153 /* Balance the tree. If the entry deleted was located on a leaf page,
7154 ** then the cursor still points to that page. In this case the first
7155 ** call to balance() repairs the tree, and the if(...) condition is
7156 ** never true.
7158 ** Otherwise, if the entry deleted was on an internal node page, then
7159 ** pCur is pointing to the leaf page from which a cell was removed to
7160 ** replace the cell deleted from the internal node. This is slightly
7161 ** tricky as the leaf node may be underfull, and the internal node may
7162 ** be either under or overfull. In this case run the balancing algorithm
7163 ** on the leaf node first. If the balance proceeds far enough up the
7164 ** tree that we can be sure that any problem in the internal node has
7165 ** been corrected, so be it. Otherwise, after balancing the leaf node,
7166 ** walk the cursor up the tree to the internal node and balance it as
7167 ** well. */
7168 rc = balance(pCur);
7169 if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
7170 while( pCur->iPage>iCellDepth ){
7171 releasePage(pCur->apPage[pCur->iPage--]);
7173 rc = balance(pCur);
7176 if( rc==SQLITE_OK ){
7177 moveToRoot(pCur);
7179 return rc;
7183 ** Create a new BTree table. Write into *piTable the page
7184 ** number for the root page of the new table.
7186 ** The type of type is determined by the flags parameter. Only the
7187 ** following values of flags are currently in use. Other values for
7188 ** flags might not work:
7190 ** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
7191 ** BTREE_ZERODATA Used for SQL indices
7193 static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
7194 BtShared *pBt = p->pBt;
7195 MemPage *pRoot;
7196 Pgno pgnoRoot;
7197 int rc;
7198 int ptfFlags; /* Page-type flage for the root page of new table */
7200 assert( sqlite3BtreeHoldsMutex(p) );
7201 assert( pBt->inTransaction==TRANS_WRITE );
7202 assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
7204 #ifdef SQLITE_OMIT_AUTOVACUUM
7205 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
7206 if( rc ){
7207 return rc;
7209 #else
7210 if( pBt->autoVacuum ){
7211 Pgno pgnoMove; /* Move a page here to make room for the root-page */
7212 MemPage *pPageMove; /* The page to move to. */
7214 /* Creating a new table may probably require moving an existing database
7215 ** to make room for the new tables root page. In case this page turns
7216 ** out to be an overflow page, delete all overflow page-map caches
7217 ** held by open cursors.
7219 invalidateAllOverflowCache(pBt);
7221 /* Read the value of meta[3] from the database to determine where the
7222 ** root page of the new table should go. meta[3] is the largest root-page
7223 ** created so far, so the new root-page is (meta[3]+1).
7225 sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
7226 pgnoRoot++;
7228 /* The new root-page may not be allocated on a pointer-map page, or the
7229 ** PENDING_BYTE page.
7231 while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
7232 pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
7233 pgnoRoot++;
7235 assert( pgnoRoot>=3 );
7237 /* Allocate a page. The page that currently resides at pgnoRoot will
7238 ** be moved to the allocated page (unless the allocated page happens
7239 ** to reside at pgnoRoot).
7241 rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT);
7242 if( rc!=SQLITE_OK ){
7243 return rc;
7246 if( pgnoMove!=pgnoRoot ){
7247 /* pgnoRoot is the page that will be used for the root-page of
7248 ** the new table (assuming an error did not occur). But we were
7249 ** allocated pgnoMove. If required (i.e. if it was not allocated
7250 ** by extending the file), the current page at position pgnoMove
7251 ** is already journaled.
7253 u8 eType = 0;
7254 Pgno iPtrPage = 0;
7256 /* Save the positions of any open cursors. This is required in
7257 ** case they are holding a reference to an xFetch reference
7258 ** corresponding to page pgnoRoot. */
7259 rc = saveAllCursors(pBt, 0, 0);
7260 releasePage(pPageMove);
7261 if( rc!=SQLITE_OK ){
7262 return rc;
7265 /* Move the page currently at pgnoRoot to pgnoMove. */
7266 rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0, 0);
7267 if( rc!=SQLITE_OK ){
7268 return rc;
7270 rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
7271 if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
7272 rc = SQLITE_CORRUPT_BKPT;
7274 if( rc!=SQLITE_OK ){
7275 releasePage(pRoot);
7276 return rc;
7278 assert( eType!=PTRMAP_ROOTPAGE );
7279 assert( eType!=PTRMAP_FREEPAGE );
7280 rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
7281 releasePage(pRoot);
7283 /* Obtain the page at pgnoRoot */
7284 if( rc!=SQLITE_OK ){
7285 return rc;
7287 rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0, 0);
7288 if( rc!=SQLITE_OK ){
7289 return rc;
7291 rc = sqlite3PagerWrite(pRoot->pDbPage);
7292 if( rc!=SQLITE_OK ){
7293 releasePage(pRoot);
7294 return rc;
7296 }else{
7297 pRoot = pPageMove;
7300 /* Update the pointer-map and meta-data with the new root-page number. */
7301 ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
7302 if( rc ){
7303 releasePage(pRoot);
7304 return rc;
7307 /* When the new root page was allocated, page 1 was made writable in
7308 ** order either to increase the database filesize, or to decrement the
7309 ** freelist count. Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
7311 assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
7312 rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
7313 if( NEVER(rc) ){
7314 releasePage(pRoot);
7315 return rc;
7318 }else{
7319 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
7320 if( rc ) return rc;
7322 #endif
7323 assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
7324 if( createTabFlags & BTREE_INTKEY ){
7325 ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
7326 }else{
7327 ptfFlags = PTF_ZERODATA | PTF_LEAF;
7329 zeroPage(pRoot, ptfFlags);
7330 sqlite3PagerUnref(pRoot->pDbPage);
7331 assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
7332 *piTable = (int)pgnoRoot;
7333 return SQLITE_OK;
7335 int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
7336 int rc;
7337 sqlite3BtreeEnter(p);
7338 rc = btreeCreateTable(p, piTable, flags);
7339 sqlite3BtreeLeave(p);
7340 return rc;
7344 ** Erase the given database page and all its children. Return
7345 ** the page to the freelist.
7347 static int clearDatabasePage(
7348 BtShared *pBt, /* The BTree that contains the table */
7349 Pgno pgno, /* Page number to clear */
7350 int freePageFlag, /* Deallocate page if true */
7351 int *pnChange /* Add number of Cells freed to this counter */
7353 MemPage *pPage;
7354 int rc;
7355 unsigned char *pCell;
7356 int i;
7358 assert( sqlite3_mutex_held(pBt->mutex) );
7359 if( pgno>btreePagecount(pBt) ){
7360 return SQLITE_CORRUPT_BKPT;
7363 rc = getAndInitPage(pBt, pgno, &pPage, 0);
7364 if( rc ) return rc;
7365 for(i=0; i<pPage->nCell; i++){
7366 pCell = findCell(pPage, i);
7367 if( !pPage->leaf ){
7368 rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
7369 if( rc ) goto cleardatabasepage_out;
7371 rc = clearCell(pPage, pCell);
7372 if( rc ) goto cleardatabasepage_out;
7374 if( !pPage->leaf ){
7375 rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), 1, pnChange);
7376 if( rc ) goto cleardatabasepage_out;
7377 }else if( pnChange ){
7378 assert( pPage->intKey );
7379 *pnChange += pPage->nCell;
7381 if( freePageFlag ){
7382 freePage(pPage, &rc);
7383 }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
7384 zeroPage(pPage, pPage->aData[0] | PTF_LEAF);
7387 cleardatabasepage_out:
7388 releasePage(pPage);
7389 return rc;
7393 ** Delete all information from a single table in the database. iTable is
7394 ** the page number of the root of the table. After this routine returns,
7395 ** the root page is empty, but still exists.
7397 ** This routine will fail with SQLITE_LOCKED if there are any open
7398 ** read cursors on the table. Open write cursors are moved to the
7399 ** root of the table.
7401 ** If pnChange is not NULL, then table iTable must be an intkey table. The
7402 ** integer value pointed to by pnChange is incremented by the number of
7403 ** entries in the table.
7405 int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
7406 int rc;
7407 BtShared *pBt = p->pBt;
7408 sqlite3BtreeEnter(p);
7409 assert( p->inTrans==TRANS_WRITE );
7411 rc = saveAllCursors(pBt, (Pgno)iTable, 0);
7413 if( SQLITE_OK==rc ){
7414 /* Invalidate all incrblob cursors open on table iTable (assuming iTable
7415 ** is the root of a table b-tree - if it is not, the following call is
7416 ** a no-op). */
7417 invalidateIncrblobCursors(p, 0, 1);
7418 rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
7420 sqlite3BtreeLeave(p);
7421 return rc;
7425 ** Erase all information in a table and add the root of the table to
7426 ** the freelist. Except, the root of the principle table (the one on
7427 ** page 1) is never added to the freelist.
7429 ** This routine will fail with SQLITE_LOCKED if there are any open
7430 ** cursors on the table.
7432 ** If AUTOVACUUM is enabled and the page at iTable is not the last
7433 ** root page in the database file, then the last root page
7434 ** in the database file is moved into the slot formerly occupied by
7435 ** iTable and that last slot formerly occupied by the last root page
7436 ** is added to the freelist instead of iTable. In this say, all
7437 ** root pages are kept at the beginning of the database file, which
7438 ** is necessary for AUTOVACUUM to work right. *piMoved is set to the
7439 ** page number that used to be the last root page in the file before
7440 ** the move. If no page gets moved, *piMoved is set to 0.
7441 ** The last root page is recorded in meta[3] and the value of
7442 ** meta[3] is updated by this procedure.
7444 static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
7445 int rc;
7446 MemPage *pPage = 0;
7447 BtShared *pBt = p->pBt;
7449 assert( sqlite3BtreeHoldsMutex(p) );
7450 assert( p->inTrans==TRANS_WRITE );
7452 /* It is illegal to drop a table if any cursors are open on the
7453 ** database. This is because in auto-vacuum mode the backend may
7454 ** need to move another root-page to fill a gap left by the deleted
7455 ** root page. If an open cursor was using this page a problem would
7456 ** occur.
7458 ** This error is caught long before control reaches this point.
7460 if( NEVER(pBt->pCursor) ){
7461 sqlite3ConnectionBlocked(p->db, pBt->pCursor->pBtree->db);
7462 return SQLITE_LOCKED_SHAREDCACHE;
7465 rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0, 0);
7466 if( rc ) return rc;
7467 rc = sqlite3BtreeClearTable(p, iTable, 0);
7468 if( rc ){
7469 releasePage(pPage);
7470 return rc;
7473 *piMoved = 0;
7475 if( iTable>1 ){
7476 #ifdef SQLITE_OMIT_AUTOVACUUM
7477 freePage(pPage, &rc);
7478 releasePage(pPage);
7479 #else
7480 if( pBt->autoVacuum ){
7481 Pgno maxRootPgno;
7482 sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
7484 if( iTable==maxRootPgno ){
7485 /* If the table being dropped is the table with the largest root-page
7486 ** number in the database, put the root page on the free list.
7488 freePage(pPage, &rc);
7489 releasePage(pPage);
7490 if( rc!=SQLITE_OK ){
7491 return rc;
7493 }else{
7494 /* The table being dropped does not have the largest root-page
7495 ** number in the database. So move the page that does into the
7496 ** gap left by the deleted root-page.
7498 MemPage *pMove;
7499 releasePage(pPage);
7500 rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0, 0);
7501 if( rc!=SQLITE_OK ){
7502 return rc;
7504 rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
7505 releasePage(pMove);
7506 if( rc!=SQLITE_OK ){
7507 return rc;
7509 pMove = 0;
7510 rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0, 0);
7511 freePage(pMove, &rc);
7512 releasePage(pMove);
7513 if( rc!=SQLITE_OK ){
7514 return rc;
7516 *piMoved = maxRootPgno;
7519 /* Set the new 'max-root-page' value in the database header. This
7520 ** is the old value less one, less one more if that happens to
7521 ** be a root-page number, less one again if that is the
7522 ** PENDING_BYTE_PAGE.
7524 maxRootPgno--;
7525 while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
7526 || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
7527 maxRootPgno--;
7529 assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
7531 rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
7532 }else{
7533 freePage(pPage, &rc);
7534 releasePage(pPage);
7536 #endif
7537 }else{
7538 /* If sqlite3BtreeDropTable was called on page 1.
7539 ** This really never should happen except in a corrupt
7540 ** database.
7542 zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
7543 releasePage(pPage);
7545 return rc;
7547 int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
7548 int rc;
7549 sqlite3BtreeEnter(p);
7550 rc = btreeDropTable(p, iTable, piMoved);
7551 sqlite3BtreeLeave(p);
7552 return rc;
7557 ** This function may only be called if the b-tree connection already
7558 ** has a read or write transaction open on the database.
7560 ** Read the meta-information out of a database file. Meta[0]
7561 ** is the number of free pages currently in the database. Meta[1]
7562 ** through meta[15] are available for use by higher layers. Meta[0]
7563 ** is read-only, the others are read/write.
7565 ** The schema layer numbers meta values differently. At the schema
7566 ** layer (and the SetCookie and ReadCookie opcodes) the number of
7567 ** free pages is not visible. So Cookie[0] is the same as Meta[1].
7569 void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
7570 BtShared *pBt = p->pBt;
7572 sqlite3BtreeEnter(p);
7573 assert( p->inTrans>TRANS_NONE );
7574 assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
7575 assert( pBt->pPage1 );
7576 assert( idx>=0 && idx<=15 );
7578 *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
7580 /* If auto-vacuum is disabled in this build and this is an auto-vacuum
7581 ** database, mark the database as read-only. */
7582 #ifdef SQLITE_OMIT_AUTOVACUUM
7583 if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){
7584 pBt->btsFlags |= BTS_READ_ONLY;
7586 #endif
7588 sqlite3BtreeLeave(p);
7592 ** Write meta-information back into the database. Meta[0] is
7593 ** read-only and may not be written.
7595 int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
7596 BtShared *pBt = p->pBt;
7597 unsigned char *pP1;
7598 int rc;
7599 assert( idx>=1 && idx<=15 );
7600 sqlite3BtreeEnter(p);
7601 assert( p->inTrans==TRANS_WRITE );
7602 assert( pBt->pPage1!=0 );
7603 pP1 = pBt->pPage1->aData;
7604 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
7605 if( rc==SQLITE_OK ){
7606 put4byte(&pP1[36 + idx*4], iMeta);
7607 #ifndef SQLITE_OMIT_AUTOVACUUM
7608 if( idx==BTREE_INCR_VACUUM ){
7609 assert( pBt->autoVacuum || iMeta==0 );
7610 assert( iMeta==0 || iMeta==1 );
7611 pBt->incrVacuum = (u8)iMeta;
7613 #endif
7615 sqlite3BtreeLeave(p);
7616 return rc;
7619 #ifndef SQLITE_OMIT_BTREECOUNT
7621 ** The first argument, pCur, is a cursor opened on some b-tree. Count the
7622 ** number of entries in the b-tree and write the result to *pnEntry.
7624 ** SQLITE_OK is returned if the operation is successfully executed.
7625 ** Otherwise, if an error is encountered (i.e. an IO error or database
7626 ** corruption) an SQLite error code is returned.
7628 int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
7629 i64 nEntry = 0; /* Value to return in *pnEntry */
7630 int rc; /* Return code */
7632 if( pCur->pgnoRoot==0 ){
7633 *pnEntry = 0;
7634 return SQLITE_OK;
7636 rc = moveToRoot(pCur);
7638 /* Unless an error occurs, the following loop runs one iteration for each
7639 ** page in the B-Tree structure (not including overflow pages).
7641 while( rc==SQLITE_OK ){
7642 int iIdx; /* Index of child node in parent */
7643 MemPage *pPage; /* Current page of the b-tree */
7645 /* If this is a leaf page or the tree is not an int-key tree, then
7646 ** this page contains countable entries. Increment the entry counter
7647 ** accordingly.
7649 pPage = pCur->apPage[pCur->iPage];
7650 if( pPage->leaf || !pPage->intKey ){
7651 nEntry += pPage->nCell;
7654 /* pPage is a leaf node. This loop navigates the cursor so that it
7655 ** points to the first interior cell that it points to the parent of
7656 ** the next page in the tree that has not yet been visited. The
7657 ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
7658 ** of the page, or to the number of cells in the page if the next page
7659 ** to visit is the right-child of its parent.
7661 ** If all pages in the tree have been visited, return SQLITE_OK to the
7662 ** caller.
7664 if( pPage->leaf ){
7665 do {
7666 if( pCur->iPage==0 ){
7667 /* All pages of the b-tree have been visited. Return successfully. */
7668 *pnEntry = nEntry;
7669 return SQLITE_OK;
7671 moveToParent(pCur);
7672 }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell );
7674 pCur->aiIdx[pCur->iPage]++;
7675 pPage = pCur->apPage[pCur->iPage];
7678 /* Descend to the child node of the cell that the cursor currently
7679 ** points at. This is the right-child if (iIdx==pPage->nCell).
7681 iIdx = pCur->aiIdx[pCur->iPage];
7682 if( iIdx==pPage->nCell ){
7683 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
7684 }else{
7685 rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
7689 /* An error has occurred. Return an error code. */
7690 return rc;
7692 #endif
7695 ** Return the pager associated with a BTree. This routine is used for
7696 ** testing and debugging only.
7698 Pager *sqlite3BtreePager(Btree *p){
7699 return p->pBt->pPager;
7702 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
7704 ** Append a message to the error message string.
7706 static void checkAppendMsg(
7707 IntegrityCk *pCheck,
7708 char *zMsg1,
7709 const char *zFormat,
7712 va_list ap;
7713 if( !pCheck->mxErr ) return;
7714 pCheck->mxErr--;
7715 pCheck->nErr++;
7716 va_start(ap, zFormat);
7717 if( pCheck->errMsg.nChar ){
7718 sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
7720 if( zMsg1 ){
7721 sqlite3StrAccumAppend(&pCheck->errMsg, zMsg1, -1);
7723 sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
7724 va_end(ap);
7725 if( pCheck->errMsg.mallocFailed ){
7726 pCheck->mallocFailed = 1;
7729 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
7731 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
7734 ** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that
7735 ** corresponds to page iPg is already set.
7737 static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){
7738 assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
7739 return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));
7743 ** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg.
7745 static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){
7746 assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
7747 pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));
7752 ** Add 1 to the reference count for page iPage. If this is the second
7753 ** reference to the page, add an error message to pCheck->zErrMsg.
7754 ** Return 1 if there are 2 ore more references to the page and 0 if
7755 ** if this is the first reference to the page.
7757 ** Also check that the page number is in bounds.
7759 static int checkRef(IntegrityCk *pCheck, Pgno iPage, char *zContext){
7760 if( iPage==0 ) return 1;
7761 if( iPage>pCheck->nPage ){
7762 checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
7763 return 1;
7765 if( getPageReferenced(pCheck, iPage) ){
7766 checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
7767 return 1;
7769 setPageReferenced(pCheck, iPage);
7770 return 0;
7773 #ifndef SQLITE_OMIT_AUTOVACUUM
7775 ** Check that the entry in the pointer-map for page iChild maps to
7776 ** page iParent, pointer type ptrType. If not, append an error message
7777 ** to pCheck.
7779 static void checkPtrmap(
7780 IntegrityCk *pCheck, /* Integrity check context */
7781 Pgno iChild, /* Child page number */
7782 u8 eType, /* Expected pointer map type */
7783 Pgno iParent, /* Expected pointer map parent page number */
7784 char *zContext /* Context description (used for error msg) */
7786 int rc;
7787 u8 ePtrmapType;
7788 Pgno iPtrmapParent;
7790 rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
7791 if( rc!=SQLITE_OK ){
7792 if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
7793 checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
7794 return;
7797 if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
7798 checkAppendMsg(pCheck, zContext,
7799 "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
7800 iChild, eType, iParent, ePtrmapType, iPtrmapParent);
7803 #endif
7806 ** Check the integrity of the freelist or of an overflow page list.
7807 ** Verify that the number of pages on the list is N.
7809 static void checkList(
7810 IntegrityCk *pCheck, /* Integrity checking context */
7811 int isFreeList, /* True for a freelist. False for overflow page list */
7812 int iPage, /* Page number for first page in the list */
7813 int N, /* Expected number of pages in the list */
7814 char *zContext /* Context for error messages */
7816 int i;
7817 int expected = N;
7818 int iFirst = iPage;
7819 while( N-- > 0 && pCheck->mxErr ){
7820 DbPage *pOvflPage;
7821 unsigned char *pOvflData;
7822 if( iPage<1 ){
7823 checkAppendMsg(pCheck, zContext,
7824 "%d of %d pages missing from overflow list starting at %d",
7825 N+1, expected, iFirst);
7826 break;
7828 if( checkRef(pCheck, iPage, zContext) ) break;
7829 if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
7830 checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
7831 break;
7833 pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
7834 if( isFreeList ){
7835 int n = get4byte(&pOvflData[4]);
7836 #ifndef SQLITE_OMIT_AUTOVACUUM
7837 if( pCheck->pBt->autoVacuum ){
7838 checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
7840 #endif
7841 if( n>(int)pCheck->pBt->usableSize/4-2 ){
7842 checkAppendMsg(pCheck, zContext,
7843 "freelist leaf count too big on page %d", iPage);
7844 N--;
7845 }else{
7846 for(i=0; i<n; i++){
7847 Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
7848 #ifndef SQLITE_OMIT_AUTOVACUUM
7849 if( pCheck->pBt->autoVacuum ){
7850 checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
7852 #endif
7853 checkRef(pCheck, iFreePage, zContext);
7855 N -= n;
7858 #ifndef SQLITE_OMIT_AUTOVACUUM
7859 else{
7860 /* If this database supports auto-vacuum and iPage is not the last
7861 ** page in this overflow list, check that the pointer-map entry for
7862 ** the following page matches iPage.
7864 if( pCheck->pBt->autoVacuum && N>0 ){
7865 i = get4byte(pOvflData);
7866 checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
7869 #endif
7870 iPage = get4byte(pOvflData);
7871 sqlite3PagerUnref(pOvflPage);
7874 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
7876 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
7878 ** Do various sanity checks on a single page of a tree. Return
7879 ** the tree depth. Root pages return 0. Parents of root pages
7880 ** return 1, and so forth.
7882 ** These checks are done:
7884 ** 1. Make sure that cells and freeblocks do not overlap
7885 ** but combine to completely cover the page.
7886 ** NO 2. Make sure cell keys are in order.
7887 ** NO 3. Make sure no key is less than or equal to zLowerBound.
7888 ** NO 4. Make sure no key is greater than or equal to zUpperBound.
7889 ** 5. Check the integrity of overflow pages.
7890 ** 6. Recursively call checkTreePage on all children.
7891 ** 7. Verify that the depth of all children is the same.
7892 ** 8. Make sure this page is at least 33% full or else it is
7893 ** the root of the tree.
7895 static int checkTreePage(
7896 IntegrityCk *pCheck, /* Context for the sanity check */
7897 int iPage, /* Page number of the page to check */
7898 char *zParentContext, /* Parent context */
7899 i64 *pnParentMinKey,
7900 i64 *pnParentMaxKey
7902 MemPage *pPage;
7903 int i, rc, depth, d2, pgno, cnt;
7904 int hdr, cellStart;
7905 int nCell;
7906 u8 *data;
7907 BtShared *pBt;
7908 int usableSize;
7909 char zContext[100];
7910 char *hit = 0;
7911 i64 nMinKey = 0;
7912 i64 nMaxKey = 0;
7914 sqlite3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage);
7916 /* Check that the page exists
7918 pBt = pCheck->pBt;
7919 usableSize = pBt->usableSize;
7920 if( iPage==0 ) return 0;
7921 if( checkRef(pCheck, iPage, zParentContext) ) return 0;
7922 if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0, 0))!=0 ){
7923 checkAppendMsg(pCheck, zContext,
7924 "unable to get the page. error code=%d", rc);
7925 return 0;
7928 /* Clear MemPage.isInit to make sure the corruption detection code in
7929 ** btreeInitPage() is executed. */
7930 pPage->isInit = 0;
7931 if( (rc = btreeInitPage(pPage))!=0 ){
7932 assert( rc==SQLITE_CORRUPT ); /* The only possible error from InitPage */
7933 checkAppendMsg(pCheck, zContext,
7934 "btreeInitPage() returns error code %d", rc);
7935 releasePage(pPage);
7936 return 0;
7939 /* Check out all the cells.
7941 depth = 0;
7942 for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
7943 u8 *pCell;
7944 u32 sz;
7945 CellInfo info;
7947 /* Check payload overflow pages
7949 sqlite3_snprintf(sizeof(zContext), zContext,
7950 "On tree page %d cell %d: ", iPage, i);
7951 pCell = findCell(pPage,i);
7952 btreeParseCellPtr(pPage, pCell, &info);
7953 sz = info.nData;
7954 if( !pPage->intKey ) sz += (int)info.nKey;
7955 /* For intKey pages, check that the keys are in order.
7957 else if( i==0 ) nMinKey = nMaxKey = info.nKey;
7958 else{
7959 if( info.nKey <= nMaxKey ){
7960 checkAppendMsg(pCheck, zContext,
7961 "Rowid %lld out of order (previous was %lld)", info.nKey, nMaxKey);
7963 nMaxKey = info.nKey;
7965 assert( sz==info.nPayload );
7966 if( (sz>info.nLocal)
7967 && (&pCell[info.iOverflow]<=&pPage->aData[pBt->usableSize])
7969 int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
7970 Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
7971 #ifndef SQLITE_OMIT_AUTOVACUUM
7972 if( pBt->autoVacuum ){
7973 checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
7975 #endif
7976 checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
7979 /* Check sanity of left child page.
7981 if( !pPage->leaf ){
7982 pgno = get4byte(pCell);
7983 #ifndef SQLITE_OMIT_AUTOVACUUM
7984 if( pBt->autoVacuum ){
7985 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
7987 #endif
7988 d2 = checkTreePage(pCheck, pgno, zContext, &nMinKey, i==0 ? NULL : &nMaxKey);
7989 if( i>0 && d2!=depth ){
7990 checkAppendMsg(pCheck, zContext, "Child page depth differs");
7992 depth = d2;
7996 if( !pPage->leaf ){
7997 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
7998 sqlite3_snprintf(sizeof(zContext), zContext,
7999 "On page %d at right child: ", iPage);
8000 #ifndef SQLITE_OMIT_AUTOVACUUM
8001 if( pBt->autoVacuum ){
8002 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
8004 #endif
8005 checkTreePage(pCheck, pgno, zContext, NULL, !pPage->nCell ? NULL : &nMaxKey);
8008 /* For intKey leaf pages, check that the min/max keys are in order
8009 ** with any left/parent/right pages.
8011 if( pPage->leaf && pPage->intKey ){
8012 /* if we are a left child page */
8013 if( pnParentMinKey ){
8014 /* if we are the left most child page */
8015 if( !pnParentMaxKey ){
8016 if( nMaxKey > *pnParentMinKey ){
8017 checkAppendMsg(pCheck, zContext,
8018 "Rowid %lld out of order (max larger than parent min of %lld)",
8019 nMaxKey, *pnParentMinKey);
8021 }else{
8022 if( nMinKey <= *pnParentMinKey ){
8023 checkAppendMsg(pCheck, zContext,
8024 "Rowid %lld out of order (min less than parent min of %lld)",
8025 nMinKey, *pnParentMinKey);
8027 if( nMaxKey > *pnParentMaxKey ){
8028 checkAppendMsg(pCheck, zContext,
8029 "Rowid %lld out of order (max larger than parent max of %lld)",
8030 nMaxKey, *pnParentMaxKey);
8032 *pnParentMinKey = nMaxKey;
8034 /* else if we're a right child page */
8035 } else if( pnParentMaxKey ){
8036 if( nMinKey <= *pnParentMaxKey ){
8037 checkAppendMsg(pCheck, zContext,
8038 "Rowid %lld out of order (min less than parent max of %lld)",
8039 nMinKey, *pnParentMaxKey);
8044 /* Check for complete coverage of the page
8046 data = pPage->aData;
8047 hdr = pPage->hdrOffset;
8048 hit = sqlite3PageMalloc( pBt->pageSize );
8049 if( hit==0 ){
8050 pCheck->mallocFailed = 1;
8051 }else{
8052 int contentOffset = get2byteNotZero(&data[hdr+5]);
8053 assert( contentOffset<=usableSize ); /* Enforced by btreeInitPage() */
8054 memset(hit+contentOffset, 0, usableSize-contentOffset);
8055 memset(hit, 1, contentOffset);
8056 nCell = get2byte(&data[hdr+3]);
8057 cellStart = hdr + 12 - 4*pPage->leaf;
8058 for(i=0; i<nCell; i++){
8059 int pc = get2byte(&data[cellStart+i*2]);
8060 u32 size = 65536;
8061 int j;
8062 if( pc<=usableSize-4 ){
8063 size = cellSizePtr(pPage, &data[pc]);
8065 if( (int)(pc+size-1)>=usableSize ){
8066 checkAppendMsg(pCheck, 0,
8067 "Corruption detected in cell %d on page %d",i,iPage);
8068 }else{
8069 for(j=pc+size-1; j>=pc; j--) hit[j]++;
8072 i = get2byte(&data[hdr+1]);
8073 while( i>0 ){
8074 int size, j;
8075 assert( i<=usableSize-4 ); /* Enforced by btreeInitPage() */
8076 size = get2byte(&data[i+2]);
8077 assert( i+size<=usableSize ); /* Enforced by btreeInitPage() */
8078 for(j=i+size-1; j>=i; j--) hit[j]++;
8079 j = get2byte(&data[i]);
8080 assert( j==0 || j>i+size ); /* Enforced by btreeInitPage() */
8081 assert( j<=usableSize-4 ); /* Enforced by btreeInitPage() */
8082 i = j;
8084 for(i=cnt=0; i<usableSize; i++){
8085 if( hit[i]==0 ){
8086 cnt++;
8087 }else if( hit[i]>1 ){
8088 checkAppendMsg(pCheck, 0,
8089 "Multiple uses for byte %d of page %d", i, iPage);
8090 break;
8093 if( cnt!=data[hdr+7] ){
8094 checkAppendMsg(pCheck, 0,
8095 "Fragmentation of %d bytes reported as %d on page %d",
8096 cnt, data[hdr+7], iPage);
8099 sqlite3PageFree(hit);
8100 releasePage(pPage);
8101 return depth+1;
8103 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
8105 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
8107 ** This routine does a complete check of the given BTree file. aRoot[] is
8108 ** an array of pages numbers were each page number is the root page of
8109 ** a table. nRoot is the number of entries in aRoot.
8111 ** A read-only or read-write transaction must be opened before calling
8112 ** this function.
8114 ** Write the number of error seen in *pnErr. Except for some memory
8115 ** allocation errors, an error message held in memory obtained from
8116 ** malloc is returned if *pnErr is non-zero. If *pnErr==0 then NULL is
8117 ** returned. If a memory allocation error occurs, NULL is returned.
8119 char *sqlite3BtreeIntegrityCheck(
8120 Btree *p, /* The btree to be checked */
8121 int *aRoot, /* An array of root pages numbers for individual trees */
8122 int nRoot, /* Number of entries in aRoot[] */
8123 int mxErr, /* Stop reporting errors after this many */
8124 int *pnErr /* Write number of errors seen to this variable */
8126 Pgno i;
8127 int nRef;
8128 IntegrityCk sCheck;
8129 BtShared *pBt = p->pBt;
8130 char zErr[100];
8132 sqlite3BtreeEnter(p);
8133 assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
8134 nRef = sqlite3PagerRefcount(pBt->pPager);
8135 sCheck.pBt = pBt;
8136 sCheck.pPager = pBt->pPager;
8137 sCheck.nPage = btreePagecount(sCheck.pBt);
8138 sCheck.mxErr = mxErr;
8139 sCheck.nErr = 0;
8140 sCheck.mallocFailed = 0;
8141 *pnErr = 0;
8142 if( sCheck.nPage==0 ){
8143 sqlite3BtreeLeave(p);
8144 return 0;
8147 sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1);
8148 if( !sCheck.aPgRef ){
8149 *pnErr = 1;
8150 sqlite3BtreeLeave(p);
8151 return 0;
8153 i = PENDING_BYTE_PAGE(pBt);
8154 if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i);
8155 sqlite3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), SQLITE_MAX_LENGTH);
8156 sCheck.errMsg.useMalloc = 2;
8158 /* Check the integrity of the freelist
8160 checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
8161 get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
8163 /* Check all the tables.
8165 for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
8166 if( aRoot[i]==0 ) continue;
8167 #ifndef SQLITE_OMIT_AUTOVACUUM
8168 if( pBt->autoVacuum && aRoot[i]>1 ){
8169 checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
8171 #endif
8172 checkTreePage(&sCheck, aRoot[i], "List of tree roots: ", NULL, NULL);
8175 /* Make sure every page in the file is referenced
8177 for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
8178 #ifdef SQLITE_OMIT_AUTOVACUUM
8179 if( getPageReferenced(&sCheck, i)==0 ){
8180 checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
8182 #else
8183 /* If the database supports auto-vacuum, make sure no tables contain
8184 ** references to pointer-map pages.
8186 if( getPageReferenced(&sCheck, i)==0 &&
8187 (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
8188 checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
8190 if( getPageReferenced(&sCheck, i)!=0 &&
8191 (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
8192 checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
8194 #endif
8197 /* Make sure this analysis did not leave any unref() pages.
8198 ** This is an internal consistency check; an integrity check
8199 ** of the integrity check.
8201 if( NEVER(nRef != sqlite3PagerRefcount(pBt->pPager)) ){
8202 checkAppendMsg(&sCheck, 0,
8203 "Outstanding page count goes from %d to %d during this analysis",
8204 nRef, sqlite3PagerRefcount(pBt->pPager)
8208 /* Clean up and report errors.
8210 sqlite3BtreeLeave(p);
8211 sqlite3_free(sCheck.aPgRef);
8212 if( sCheck.mallocFailed ){
8213 sqlite3StrAccumReset(&sCheck.errMsg);
8214 *pnErr = sCheck.nErr+1;
8215 return 0;
8217 *pnErr = sCheck.nErr;
8218 if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
8219 return sqlite3StrAccumFinish(&sCheck.errMsg);
8221 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
8224 ** Return the full pathname of the underlying database file. Return
8225 ** an empty string if the database is in-memory or a TEMP database.
8227 ** The pager filename is invariant as long as the pager is
8228 ** open so it is safe to access without the BtShared mutex.
8230 const char *sqlite3BtreeGetFilename(Btree *p){
8231 assert( p->pBt->pPager!=0 );
8232 return sqlite3PagerFilename(p->pBt->pPager, 1);
8236 ** Return the pathname of the journal file for this database. The return
8237 ** value of this routine is the same regardless of whether the journal file
8238 ** has been created or not.
8240 ** The pager journal filename is invariant as long as the pager is
8241 ** open so it is safe to access without the BtShared mutex.
8243 const char *sqlite3BtreeGetJournalname(Btree *p){
8244 assert( p->pBt->pPager!=0 );
8245 return sqlite3PagerJournalname(p->pBt->pPager);
8249 ** Return non-zero if a transaction is active.
8251 int sqlite3BtreeIsInTrans(Btree *p){
8252 assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
8253 return (p && (p->inTrans==TRANS_WRITE));
8256 #ifndef SQLITE_OMIT_WAL
8258 ** Run a checkpoint on the Btree passed as the first argument.
8260 ** Return SQLITE_LOCKED if this or any other connection has an open
8261 ** transaction on the shared-cache the argument Btree is connected to.
8263 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
8265 int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
8266 int rc = SQLITE_OK;
8267 if( p ){
8268 BtShared *pBt = p->pBt;
8269 sqlite3BtreeEnter(p);
8270 if( pBt->inTransaction!=TRANS_NONE ){
8271 rc = SQLITE_LOCKED;
8272 }else{
8273 rc = sqlite3PagerCheckpoint(pBt->pPager, eMode, pnLog, pnCkpt);
8275 sqlite3BtreeLeave(p);
8277 return rc;
8279 #endif
8282 ** Return non-zero if a read (or write) transaction is active.
8284 int sqlite3BtreeIsInReadTrans(Btree *p){
8285 assert( p );
8286 assert( sqlite3_mutex_held(p->db->mutex) );
8287 return p->inTrans!=TRANS_NONE;
8290 int sqlite3BtreeIsInBackup(Btree *p){
8291 assert( p );
8292 assert( sqlite3_mutex_held(p->db->mutex) );
8293 return p->nBackup!=0;
8297 ** This function returns a pointer to a blob of memory associated with
8298 ** a single shared-btree. The memory is used by client code for its own
8299 ** purposes (for example, to store a high-level schema associated with
8300 ** the shared-btree). The btree layer manages reference counting issues.
8302 ** The first time this is called on a shared-btree, nBytes bytes of memory
8303 ** are allocated, zeroed, and returned to the caller. For each subsequent
8304 ** call the nBytes parameter is ignored and a pointer to the same blob
8305 ** of memory returned.
8307 ** If the nBytes parameter is 0 and the blob of memory has not yet been
8308 ** allocated, a null pointer is returned. If the blob has already been
8309 ** allocated, it is returned as normal.
8311 ** Just before the shared-btree is closed, the function passed as the
8312 ** xFree argument when the memory allocation was made is invoked on the
8313 ** blob of allocated memory. The xFree function should not call sqlite3_free()
8314 ** on the memory, the btree layer does that.
8316 void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
8317 BtShared *pBt = p->pBt;
8318 sqlite3BtreeEnter(p);
8319 if( !pBt->pSchema && nBytes ){
8320 pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
8321 pBt->xFreeSchema = xFree;
8323 sqlite3BtreeLeave(p);
8324 return pBt->pSchema;
8328 ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
8329 ** btree as the argument handle holds an exclusive lock on the
8330 ** sqlite_master table. Otherwise SQLITE_OK.
8332 int sqlite3BtreeSchemaLocked(Btree *p){
8333 int rc;
8334 assert( sqlite3_mutex_held(p->db->mutex) );
8335 sqlite3BtreeEnter(p);
8336 rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
8337 assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
8338 sqlite3BtreeLeave(p);
8339 return rc;
8343 #ifndef SQLITE_OMIT_SHARED_CACHE
8345 ** Obtain a lock on the table whose root page is iTab. The
8346 ** lock is a write lock if isWritelock is true or a read lock
8347 ** if it is false.
8349 int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
8350 int rc = SQLITE_OK;
8351 assert( p->inTrans!=TRANS_NONE );
8352 if( p->sharable ){
8353 u8 lockType = READ_LOCK + isWriteLock;
8354 assert( READ_LOCK+1==WRITE_LOCK );
8355 assert( isWriteLock==0 || isWriteLock==1 );
8357 sqlite3BtreeEnter(p);
8358 rc = querySharedCacheTableLock(p, iTab, lockType);
8359 if( rc==SQLITE_OK ){
8360 rc = setSharedCacheTableLock(p, iTab, lockType);
8362 sqlite3BtreeLeave(p);
8364 return rc;
8366 #endif
8368 #ifndef SQLITE_OMIT_INCRBLOB
8370 ** Argument pCsr must be a cursor opened for writing on an
8371 ** INTKEY table currently pointing at a valid table entry.
8372 ** This function modifies the data stored as part of that entry.
8374 ** Only the data content may only be modified, it is not possible to
8375 ** change the length of the data stored. If this function is called with
8376 ** parameters that attempt to write past the end of the existing data,
8377 ** no modifications are made and SQLITE_CORRUPT is returned.
8379 int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
8380 int rc;
8381 assert( cursorHoldsMutex(pCsr) );
8382 assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
8383 assert( pCsr->isIncrblobHandle );
8385 rc = restoreCursorPosition(pCsr);
8386 if( rc!=SQLITE_OK ){
8387 return rc;
8389 assert( pCsr->eState!=CURSOR_REQUIRESEEK );
8390 if( pCsr->eState!=CURSOR_VALID ){
8391 return SQLITE_ABORT;
8394 /* Save the positions of all other cursors open on this table. This is
8395 ** required in case any of them are holding references to an xFetch
8396 ** version of the b-tree page modified by the accessPayload call below.
8398 ** Note that pCsr must be open on a BTREE_INTKEY table and saveCursorPosition()
8399 ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence
8400 ** saveAllCursors can only return SQLITE_OK.
8402 VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr);
8403 assert( rc==SQLITE_OK );
8405 /* Check some assumptions:
8406 ** (a) the cursor is open for writing,
8407 ** (b) there is a read/write transaction open,
8408 ** (c) the connection holds a write-lock on the table (if required),
8409 ** (d) there are no conflicting read-locks, and
8410 ** (e) the cursor points at a valid row of an intKey table.
8412 if( !pCsr->wrFlag ){
8413 return SQLITE_READONLY;
8415 assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
8416 && pCsr->pBt->inTransaction==TRANS_WRITE );
8417 assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
8418 assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
8419 assert( pCsr->apPage[pCsr->iPage]->intKey );
8421 return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
8425 ** Set a flag on this cursor to cache the locations of pages from the
8426 ** overflow list for the current row. This is used by cursors opened
8427 ** for incremental blob IO only.
8429 ** This function sets a flag only. The actual page location cache
8430 ** (stored in BtCursor.aOverflow[]) is allocated and used by function
8431 ** accessPayload() (the worker function for sqlite3BtreeData() and
8432 ** sqlite3BtreePutData()).
8434 void sqlite3BtreeCacheOverflow(BtCursor *pCur){
8435 assert( cursorHoldsMutex(pCur) );
8436 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
8437 invalidateOverflowCache(pCur);
8438 pCur->isIncrblobHandle = 1;
8440 #endif
8443 ** Set both the "read version" (single byte at byte offset 18) and
8444 ** "write version" (single byte at byte offset 19) fields in the database
8445 ** header to iVersion.
8447 int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
8448 BtShared *pBt = pBtree->pBt;
8449 int rc; /* Return code */
8451 assert( iVersion==1 || iVersion==2 );
8453 /* If setting the version fields to 1, do not automatically open the
8454 ** WAL connection, even if the version fields are currently set to 2.
8456 pBt->btsFlags &= ~BTS_NO_WAL;
8457 if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
8459 rc = sqlite3BtreeBeginTrans(pBtree, 0);
8460 if( rc==SQLITE_OK ){
8461 u8 *aData = pBt->pPage1->aData;
8462 if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
8463 rc = sqlite3BtreeBeginTrans(pBtree, 2);
8464 if( rc==SQLITE_OK ){
8465 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
8466 if( rc==SQLITE_OK ){
8467 aData[18] = (u8)iVersion;
8468 aData[19] = (u8)iVersion;
8474 pBt->btsFlags &= ~BTS_NO_WAL;
8475 return rc;
8479 ** set the mask of hint flags for cursor pCsr. Currently the only valid
8480 ** values are 0 and BTREE_BULKLOAD.
8482 void sqlite3BtreeCursorHints(BtCursor *pCsr, unsigned int mask){
8483 assert( mask==BTREE_BULKLOAD || mask==0 );
8484 pCsr->hints = mask;