Revert "change compilation / amalgamation order of sqlcipher sources"
[sqlcipher.git] / src / btree.c
blobfe2d1b103baa6c320e9b20707159691a7e2cadbd
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 an 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_MAIN.
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 #ifdef SQLITE_DEBUG
117 ** Return and reset the seek counter for a Btree object.
119 sqlite3_uint64 sqlite3BtreeSeekCount(Btree *pBt){
120 u64 n = pBt->nSeek;
121 pBt->nSeek = 0;
122 return n;
124 #endif
127 ** Implementation of the SQLITE_CORRUPT_PAGE() macro. Takes a single
128 ** (MemPage*) as an argument. The (MemPage*) must not be NULL.
130 ** If SQLITE_DEBUG is not defined, then this macro is equivalent to
131 ** SQLITE_CORRUPT_BKPT. Or, if SQLITE_DEBUG is set, then the log message
132 ** normally produced as a side-effect of SQLITE_CORRUPT_BKPT is augmented
133 ** with the page number and filename associated with the (MemPage*).
135 #ifdef SQLITE_DEBUG
136 int corruptPageError(int lineno, MemPage *p){
137 char *zMsg;
138 sqlite3BeginBenignMalloc();
139 zMsg = sqlite3_mprintf("database corruption page %d of %s",
140 (int)p->pgno, sqlite3PagerFilename(p->pBt->pPager, 0)
142 sqlite3EndBenignMalloc();
143 if( zMsg ){
144 sqlite3ReportError(SQLITE_CORRUPT, lineno, zMsg);
146 sqlite3_free(zMsg);
147 return SQLITE_CORRUPT_BKPT;
149 # define SQLITE_CORRUPT_PAGE(pMemPage) corruptPageError(__LINE__, pMemPage)
150 #else
151 # define SQLITE_CORRUPT_PAGE(pMemPage) SQLITE_CORRUPT_PGNO(pMemPage->pgno)
152 #endif
154 #ifndef SQLITE_OMIT_SHARED_CACHE
156 #ifdef SQLITE_DEBUG
158 **** This function is only used as part of an assert() statement. ***
160 ** Check to see if pBtree holds the required locks to read or write to the
161 ** table with root page iRoot. Return 1 if it does and 0 if not.
163 ** For example, when writing to a table with root-page iRoot via
164 ** Btree connection pBtree:
166 ** assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
168 ** When writing to an index that resides in a sharable database, the
169 ** caller should have first obtained a lock specifying the root page of
170 ** the corresponding table. This makes things a bit more complicated,
171 ** as this module treats each table as a separate structure. To determine
172 ** the table corresponding to the index being written, this
173 ** function has to search through the database schema.
175 ** Instead of a lock on the table/index rooted at page iRoot, the caller may
176 ** hold a write-lock on the schema table (root page 1). This is also
177 ** acceptable.
179 static int hasSharedCacheTableLock(
180 Btree *pBtree, /* Handle that must hold lock */
181 Pgno iRoot, /* Root page of b-tree */
182 int isIndex, /* True if iRoot is the root of an index b-tree */
183 int eLockType /* Required lock type (READ_LOCK or WRITE_LOCK) */
185 Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
186 Pgno iTab = 0;
187 BtLock *pLock;
189 /* If this database is not shareable, or if the client is reading
190 ** and has the read-uncommitted flag set, then no lock is required.
191 ** Return true immediately.
193 if( (pBtree->sharable==0)
194 || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommit))
196 return 1;
199 /* If the client is reading or writing an index and the schema is
200 ** not loaded, then it is too difficult to actually check to see if
201 ** the correct locks are held. So do not bother - just return true.
202 ** This case does not come up very often anyhow.
204 if( isIndex && (!pSchema || (pSchema->schemaFlags&DB_SchemaLoaded)==0) ){
205 return 1;
208 /* Figure out the root-page that the lock should be held on. For table
209 ** b-trees, this is just the root page of the b-tree being read or
210 ** written. For index b-trees, it is the root page of the associated
211 ** table. */
212 if( isIndex ){
213 HashElem *p;
214 int bSeen = 0;
215 for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
216 Index *pIdx = (Index *)sqliteHashData(p);
217 if( pIdx->tnum==(int)iRoot ){
218 if( bSeen ){
219 /* Two or more indexes share the same root page. There must
220 ** be imposter tables. So just return true. The assert is not
221 ** useful in that case. */
222 return 1;
224 iTab = pIdx->pTable->tnum;
225 bSeen = 1;
228 }else{
229 iTab = iRoot;
232 /* Search for the required lock. Either a write-lock on root-page iTab, a
233 ** write-lock on the schema table, or (if the client is reading) a
234 ** read-lock on iTab will suffice. Return 1 if any of these are found. */
235 for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
236 if( pLock->pBtree==pBtree
237 && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
238 && pLock->eLock>=eLockType
240 return 1;
244 /* Failed to find the required lock. */
245 return 0;
247 #endif /* SQLITE_DEBUG */
249 #ifdef SQLITE_DEBUG
251 **** This function may be used as part of assert() statements only. ****
253 ** Return true if it would be illegal for pBtree to write into the
254 ** table or index rooted at iRoot because other shared connections are
255 ** simultaneously reading that same table or index.
257 ** It is illegal for pBtree to write if some other Btree object that
258 ** shares the same BtShared object is currently reading or writing
259 ** the iRoot table. Except, if the other Btree object has the
260 ** read-uncommitted flag set, then it is OK for the other object to
261 ** have a read cursor.
263 ** For example, before writing to any part of the table or index
264 ** rooted at page iRoot, one should call:
266 ** assert( !hasReadConflicts(pBtree, iRoot) );
268 static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
269 BtCursor *p;
270 for(p=pBtree->pBt->pCursor; p; p=p->pNext){
271 if( p->pgnoRoot==iRoot
272 && p->pBtree!=pBtree
273 && 0==(p->pBtree->db->flags & SQLITE_ReadUncommit)
275 return 1;
278 return 0;
280 #endif /* #ifdef SQLITE_DEBUG */
283 ** Query to see if Btree handle p may obtain a lock of type eLock
284 ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
285 ** SQLITE_OK if the lock may be obtained (by calling
286 ** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
288 static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
289 BtShared *pBt = p->pBt;
290 BtLock *pIter;
292 assert( sqlite3BtreeHoldsMutex(p) );
293 assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
294 assert( p->db!=0 );
295 assert( !(p->db->flags&SQLITE_ReadUncommit)||eLock==WRITE_LOCK||iTab==1 );
297 /* If requesting a write-lock, then the Btree must have an open write
298 ** transaction on this file. And, obviously, for this to be so there
299 ** must be an open write transaction on the file itself.
301 assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
302 assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
304 /* This routine is a no-op if the shared-cache is not enabled */
305 if( !p->sharable ){
306 return SQLITE_OK;
309 /* If some other connection is holding an exclusive lock, the
310 ** requested lock may not be obtained.
312 if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){
313 sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
314 return SQLITE_LOCKED_SHAREDCACHE;
317 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
318 /* The condition (pIter->eLock!=eLock) in the following if(...)
319 ** statement is a simplification of:
321 ** (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
323 ** since we know that if eLock==WRITE_LOCK, then no other connection
324 ** may hold a WRITE_LOCK on any table in this file (since there can
325 ** only be a single writer).
327 assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
328 assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
329 if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
330 sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
331 if( eLock==WRITE_LOCK ){
332 assert( p==pBt->pWriter );
333 pBt->btsFlags |= BTS_PENDING;
335 return SQLITE_LOCKED_SHAREDCACHE;
338 return SQLITE_OK;
340 #endif /* !SQLITE_OMIT_SHARED_CACHE */
342 #ifndef SQLITE_OMIT_SHARED_CACHE
344 ** Add a lock on the table with root-page iTable to the shared-btree used
345 ** by Btree handle p. Parameter eLock must be either READ_LOCK or
346 ** WRITE_LOCK.
348 ** This function assumes the following:
350 ** (a) The specified Btree object p is connected to a sharable
351 ** database (one with the BtShared.sharable flag set), and
353 ** (b) No other Btree objects hold a lock that conflicts
354 ** with the requested lock (i.e. querySharedCacheTableLock() has
355 ** already been called and returned SQLITE_OK).
357 ** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM
358 ** is returned if a malloc attempt fails.
360 static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
361 BtShared *pBt = p->pBt;
362 BtLock *pLock = 0;
363 BtLock *pIter;
365 assert( sqlite3BtreeHoldsMutex(p) );
366 assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
367 assert( p->db!=0 );
369 /* A connection with the read-uncommitted flag set will never try to
370 ** obtain a read-lock using this function. The only read-lock obtained
371 ** by a connection in read-uncommitted mode is on the sqlite_schema
372 ** table, and that lock is obtained in BtreeBeginTrans(). */
373 assert( 0==(p->db->flags&SQLITE_ReadUncommit) || eLock==WRITE_LOCK );
375 /* This function should only be called on a sharable b-tree after it
376 ** has been determined that no other b-tree holds a conflicting lock. */
377 assert( p->sharable );
378 assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
380 /* First search the list for an existing lock on this table. */
381 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
382 if( pIter->iTable==iTable && pIter->pBtree==p ){
383 pLock = pIter;
384 break;
388 /* If the above search did not find a BtLock struct associating Btree p
389 ** with table iTable, allocate one and link it into the list.
391 if( !pLock ){
392 pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
393 if( !pLock ){
394 return SQLITE_NOMEM_BKPT;
396 pLock->iTable = iTable;
397 pLock->pBtree = p;
398 pLock->pNext = pBt->pLock;
399 pBt->pLock = pLock;
402 /* Set the BtLock.eLock variable to the maximum of the current lock
403 ** and the requested lock. This means if a write-lock was already held
404 ** and a read-lock requested, we don't incorrectly downgrade the lock.
406 assert( WRITE_LOCK>READ_LOCK );
407 if( eLock>pLock->eLock ){
408 pLock->eLock = eLock;
411 return SQLITE_OK;
413 #endif /* !SQLITE_OMIT_SHARED_CACHE */
415 #ifndef SQLITE_OMIT_SHARED_CACHE
417 ** Release all the table locks (locks obtained via calls to
418 ** the setSharedCacheTableLock() procedure) held by Btree object p.
420 ** This function assumes that Btree p has an open read or write
421 ** transaction. If it does not, then the BTS_PENDING flag
422 ** may be incorrectly cleared.
424 static void clearAllSharedCacheTableLocks(Btree *p){
425 BtShared *pBt = p->pBt;
426 BtLock **ppIter = &pBt->pLock;
428 assert( sqlite3BtreeHoldsMutex(p) );
429 assert( p->sharable || 0==*ppIter );
430 assert( p->inTrans>0 );
432 while( *ppIter ){
433 BtLock *pLock = *ppIter;
434 assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree );
435 assert( pLock->pBtree->inTrans>=pLock->eLock );
436 if( pLock->pBtree==p ){
437 *ppIter = pLock->pNext;
438 assert( pLock->iTable!=1 || pLock==&p->lock );
439 if( pLock->iTable!=1 ){
440 sqlite3_free(pLock);
442 }else{
443 ppIter = &pLock->pNext;
447 assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter );
448 if( pBt->pWriter==p ){
449 pBt->pWriter = 0;
450 pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
451 }else if( pBt->nTransaction==2 ){
452 /* This function is called when Btree p is concluding its
453 ** transaction. If there currently exists a writer, and p is not
454 ** that writer, then the number of locks held by connections other
455 ** than the writer must be about to drop to zero. In this case
456 ** set the BTS_PENDING flag to 0.
458 ** If there is not currently a writer, then BTS_PENDING must
459 ** be zero already. So this next line is harmless in that case.
461 pBt->btsFlags &= ~BTS_PENDING;
466 ** This function changes all write-locks held by Btree p into read-locks.
468 static void downgradeAllSharedCacheTableLocks(Btree *p){
469 BtShared *pBt = p->pBt;
470 if( pBt->pWriter==p ){
471 BtLock *pLock;
472 pBt->pWriter = 0;
473 pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
474 for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
475 assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
476 pLock->eLock = READ_LOCK;
481 #endif /* SQLITE_OMIT_SHARED_CACHE */
483 static void releasePage(MemPage *pPage); /* Forward reference */
484 static void releasePageOne(MemPage *pPage); /* Forward reference */
485 static void releasePageNotNull(MemPage *pPage); /* Forward reference */
488 ***** This routine is used inside of assert() only ****
490 ** Verify that the cursor holds the mutex on its BtShared
492 #ifdef SQLITE_DEBUG
493 static int cursorHoldsMutex(BtCursor *p){
494 return sqlite3_mutex_held(p->pBt->mutex);
497 /* Verify that the cursor and the BtShared agree about what is the current
498 ** database connetion. This is important in shared-cache mode. If the database
499 ** connection pointers get out-of-sync, it is possible for routines like
500 ** btreeInitPage() to reference an stale connection pointer that references a
501 ** a connection that has already closed. This routine is used inside assert()
502 ** statements only and for the purpose of double-checking that the btree code
503 ** does keep the database connection pointers up-to-date.
505 static int cursorOwnsBtShared(BtCursor *p){
506 assert( cursorHoldsMutex(p) );
507 return (p->pBtree->db==p->pBt->db);
509 #endif
512 ** Invalidate the overflow cache of the cursor passed as the first argument.
513 ** on the shared btree structure pBt.
515 #define invalidateOverflowCache(pCur) (pCur->curFlags &= ~BTCF_ValidOvfl)
518 ** Invalidate the overflow page-list cache for all cursors opened
519 ** on the shared btree structure pBt.
521 static void invalidateAllOverflowCache(BtShared *pBt){
522 BtCursor *p;
523 assert( sqlite3_mutex_held(pBt->mutex) );
524 for(p=pBt->pCursor; p; p=p->pNext){
525 invalidateOverflowCache(p);
529 #ifndef SQLITE_OMIT_INCRBLOB
531 ** This function is called before modifying the contents of a table
532 ** to invalidate any incrblob cursors that are open on the
533 ** row or one of the rows being modified.
535 ** If argument isClearTable is true, then the entire contents of the
536 ** table is about to be deleted. In this case invalidate all incrblob
537 ** cursors open on any row within the table with root-page pgnoRoot.
539 ** Otherwise, if argument isClearTable is false, then the row with
540 ** rowid iRow is being replaced or deleted. In this case invalidate
541 ** only those incrblob cursors open on that specific row.
543 static void invalidateIncrblobCursors(
544 Btree *pBtree, /* The database file to check */
545 Pgno pgnoRoot, /* The table that might be changing */
546 i64 iRow, /* The rowid that might be changing */
547 int isClearTable /* True if all rows are being deleted */
549 BtCursor *p;
550 assert( pBtree->hasIncrblobCur );
551 assert( sqlite3BtreeHoldsMutex(pBtree) );
552 pBtree->hasIncrblobCur = 0;
553 for(p=pBtree->pBt->pCursor; p; p=p->pNext){
554 if( (p->curFlags & BTCF_Incrblob)!=0 ){
555 pBtree->hasIncrblobCur = 1;
556 if( p->pgnoRoot==pgnoRoot && (isClearTable || p->info.nKey==iRow) ){
557 p->eState = CURSOR_INVALID;
563 #else
564 /* Stub function when INCRBLOB is omitted */
565 #define invalidateIncrblobCursors(w,x,y,z)
566 #endif /* SQLITE_OMIT_INCRBLOB */
569 ** Set bit pgno of the BtShared.pHasContent bitvec. This is called
570 ** when a page that previously contained data becomes a free-list leaf
571 ** page.
573 ** The BtShared.pHasContent bitvec exists to work around an obscure
574 ** bug caused by the interaction of two useful IO optimizations surrounding
575 ** free-list leaf pages:
577 ** 1) When all data is deleted from a page and the page becomes
578 ** a free-list leaf page, the page is not written to the database
579 ** (as free-list leaf pages contain no meaningful data). Sometimes
580 ** such a page is not even journalled (as it will not be modified,
581 ** why bother journalling it?).
583 ** 2) When a free-list leaf page is reused, its content is not read
584 ** from the database or written to the journal file (why should it
585 ** be, if it is not at all meaningful?).
587 ** By themselves, these optimizations work fine and provide a handy
588 ** performance boost to bulk delete or insert operations. However, if
589 ** a page is moved to the free-list and then reused within the same
590 ** transaction, a problem comes up. If the page is not journalled when
591 ** it is moved to the free-list and it is also not journalled when it
592 ** is extracted from the free-list and reused, then the original data
593 ** may be lost. In the event of a rollback, it may not be possible
594 ** to restore the database to its original configuration.
596 ** The solution is the BtShared.pHasContent bitvec. Whenever a page is
597 ** moved to become a free-list leaf page, the corresponding bit is
598 ** set in the bitvec. Whenever a leaf page is extracted from the free-list,
599 ** optimization 2 above is omitted if the corresponding bit is already
600 ** set in BtShared.pHasContent. The contents of the bitvec are cleared
601 ** at the end of every transaction.
603 static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
604 int rc = SQLITE_OK;
605 if( !pBt->pHasContent ){
606 assert( pgno<=pBt->nPage );
607 pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
608 if( !pBt->pHasContent ){
609 rc = SQLITE_NOMEM_BKPT;
612 if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
613 rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
615 return rc;
619 ** Query the BtShared.pHasContent vector.
621 ** This function is called when a free-list leaf page is removed from the
622 ** free-list for reuse. It returns false if it is safe to retrieve the
623 ** page from the pager layer with the 'no-content' flag set. True otherwise.
625 static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
626 Bitvec *p = pBt->pHasContent;
627 return p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTestNotNull(p, pgno));
631 ** Clear (destroy) the BtShared.pHasContent bitvec. This should be
632 ** invoked at the conclusion of each write-transaction.
634 static void btreeClearHasContent(BtShared *pBt){
635 sqlite3BitvecDestroy(pBt->pHasContent);
636 pBt->pHasContent = 0;
640 ** Release all of the apPage[] pages for a cursor.
642 static void btreeReleaseAllCursorPages(BtCursor *pCur){
643 int i;
644 if( pCur->iPage>=0 ){
645 for(i=0; i<pCur->iPage; i++){
646 releasePageNotNull(pCur->apPage[i]);
648 releasePageNotNull(pCur->pPage);
649 pCur->iPage = -1;
654 ** The cursor passed as the only argument must point to a valid entry
655 ** when this function is called (i.e. have eState==CURSOR_VALID). This
656 ** function saves the current cursor key in variables pCur->nKey and
657 ** pCur->pKey. SQLITE_OK is returned if successful or an SQLite error
658 ** code otherwise.
660 ** If the cursor is open on an intkey table, then the integer key
661 ** (the rowid) is stored in pCur->nKey and pCur->pKey is left set to
662 ** NULL. If the cursor is open on a non-intkey table, then pCur->pKey is
663 ** set to point to a malloced buffer pCur->nKey bytes in size containing
664 ** the key.
666 static int saveCursorKey(BtCursor *pCur){
667 int rc = SQLITE_OK;
668 assert( CURSOR_VALID==pCur->eState );
669 assert( 0==pCur->pKey );
670 assert( cursorHoldsMutex(pCur) );
672 if( pCur->curIntKey ){
673 /* Only the rowid is required for a table btree */
674 pCur->nKey = sqlite3BtreeIntegerKey(pCur);
675 }else{
676 /* For an index btree, save the complete key content. It is possible
677 ** that the current key is corrupt. In that case, it is possible that
678 ** the sqlite3VdbeRecordUnpack() function may overread the buffer by
679 ** up to the size of 1 varint plus 1 8-byte value when the cursor
680 ** position is restored. Hence the 17 bytes of padding allocated
681 ** below. */
682 void *pKey;
683 pCur->nKey = sqlite3BtreePayloadSize(pCur);
684 pKey = sqlite3Malloc( pCur->nKey + 9 + 8 );
685 if( pKey ){
686 rc = sqlite3BtreePayload(pCur, 0, (int)pCur->nKey, pKey);
687 if( rc==SQLITE_OK ){
688 memset(((u8*)pKey)+pCur->nKey, 0, 9+8);
689 pCur->pKey = pKey;
690 }else{
691 sqlite3_free(pKey);
693 }else{
694 rc = SQLITE_NOMEM_BKPT;
697 assert( !pCur->curIntKey || !pCur->pKey );
698 return rc;
702 ** Save the current cursor position in the variables BtCursor.nKey
703 ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
705 ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
706 ** prior to calling this routine.
708 static int saveCursorPosition(BtCursor *pCur){
709 int rc;
711 assert( CURSOR_VALID==pCur->eState || CURSOR_SKIPNEXT==pCur->eState );
712 assert( 0==pCur->pKey );
713 assert( cursorHoldsMutex(pCur) );
715 if( pCur->curFlags & BTCF_Pinned ){
716 return SQLITE_CONSTRAINT_PINNED;
718 if( pCur->eState==CURSOR_SKIPNEXT ){
719 pCur->eState = CURSOR_VALID;
720 }else{
721 pCur->skipNext = 0;
724 rc = saveCursorKey(pCur);
725 if( rc==SQLITE_OK ){
726 btreeReleaseAllCursorPages(pCur);
727 pCur->eState = CURSOR_REQUIRESEEK;
730 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl|BTCF_AtLast);
731 return rc;
734 /* Forward reference */
735 static int SQLITE_NOINLINE saveCursorsOnList(BtCursor*,Pgno,BtCursor*);
738 ** Save the positions of all cursors (except pExcept) that are open on
739 ** the table with root-page iRoot. "Saving the cursor position" means that
740 ** the location in the btree is remembered in such a way that it can be
741 ** moved back to the same spot after the btree has been modified. This
742 ** routine is called just before cursor pExcept is used to modify the
743 ** table, for example in BtreeDelete() or BtreeInsert().
745 ** If there are two or more cursors on the same btree, then all such
746 ** cursors should have their BTCF_Multiple flag set. The btreeCursor()
747 ** routine enforces that rule. This routine only needs to be called in
748 ** the uncommon case when pExpect has the BTCF_Multiple flag set.
750 ** If pExpect!=NULL and if no other cursors are found on the same root-page,
751 ** then the BTCF_Multiple flag on pExpect is cleared, to avoid another
752 ** pointless call to this routine.
754 ** Implementation note: This routine merely checks to see if any cursors
755 ** need to be saved. It calls out to saveCursorsOnList() in the (unusual)
756 ** event that cursors are in need to being saved.
758 static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
759 BtCursor *p;
760 assert( sqlite3_mutex_held(pBt->mutex) );
761 assert( pExcept==0 || pExcept->pBt==pBt );
762 for(p=pBt->pCursor; p; p=p->pNext){
763 if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ) break;
765 if( p ) return saveCursorsOnList(p, iRoot, pExcept);
766 if( pExcept ) pExcept->curFlags &= ~BTCF_Multiple;
767 return SQLITE_OK;
770 /* This helper routine to saveAllCursors does the actual work of saving
771 ** the cursors if and when a cursor is found that actually requires saving.
772 ** The common case is that no cursors need to be saved, so this routine is
773 ** broken out from its caller to avoid unnecessary stack pointer movement.
775 static int SQLITE_NOINLINE saveCursorsOnList(
776 BtCursor *p, /* The first cursor that needs saving */
777 Pgno iRoot, /* Only save cursor with this iRoot. Save all if zero */
778 BtCursor *pExcept /* Do not save this cursor */
781 if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ){
782 if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
783 int rc = saveCursorPosition(p);
784 if( SQLITE_OK!=rc ){
785 return rc;
787 }else{
788 testcase( p->iPage>=0 );
789 btreeReleaseAllCursorPages(p);
792 p = p->pNext;
793 }while( p );
794 return SQLITE_OK;
798 ** Clear the current cursor position.
800 void sqlite3BtreeClearCursor(BtCursor *pCur){
801 assert( cursorHoldsMutex(pCur) );
802 sqlite3_free(pCur->pKey);
803 pCur->pKey = 0;
804 pCur->eState = CURSOR_INVALID;
808 ** In this version of BtreeMoveto, pKey is a packed index record
809 ** such as is generated by the OP_MakeRecord opcode. Unpack the
810 ** record and then call BtreeMovetoUnpacked() to do the work.
812 static int btreeMoveto(
813 BtCursor *pCur, /* Cursor open on the btree to be searched */
814 const void *pKey, /* Packed key if the btree is an index */
815 i64 nKey, /* Integer key for tables. Size of pKey for indices */
816 int bias, /* Bias search to the high end */
817 int *pRes /* Write search results here */
819 int rc; /* Status code */
820 UnpackedRecord *pIdxKey; /* Unpacked index key */
822 if( pKey ){
823 KeyInfo *pKeyInfo = pCur->pKeyInfo;
824 assert( nKey==(i64)(int)nKey );
825 pIdxKey = sqlite3VdbeAllocUnpackedRecord(pKeyInfo);
826 if( pIdxKey==0 ) return SQLITE_NOMEM_BKPT;
827 sqlite3VdbeRecordUnpack(pKeyInfo, (int)nKey, pKey, pIdxKey);
828 if( pIdxKey->nField==0 || pIdxKey->nField>pKeyInfo->nAllField ){
829 rc = SQLITE_CORRUPT_BKPT;
830 }else{
831 rc = sqlite3BtreeIndexMoveto(pCur, pIdxKey, pRes);
833 sqlite3DbFree(pCur->pKeyInfo->db, pIdxKey);
834 }else{
835 pIdxKey = 0;
836 rc = sqlite3BtreeTableMoveto(pCur, nKey, bias, pRes);
838 return rc;
842 ** Restore the cursor to the position it was in (or as close to as possible)
843 ** when saveCursorPosition() was called. Note that this call deletes the
844 ** saved position info stored by saveCursorPosition(), so there can be
845 ** at most one effective restoreCursorPosition() call after each
846 ** saveCursorPosition().
848 static int btreeRestoreCursorPosition(BtCursor *pCur){
849 int rc;
850 int skipNext = 0;
851 assert( cursorOwnsBtShared(pCur) );
852 assert( pCur->eState>=CURSOR_REQUIRESEEK );
853 if( pCur->eState==CURSOR_FAULT ){
854 return pCur->skipNext;
856 pCur->eState = CURSOR_INVALID;
857 if( sqlite3FaultSim(410) ){
858 rc = SQLITE_IOERR;
859 }else{
860 rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &skipNext);
862 if( rc==SQLITE_OK ){
863 sqlite3_free(pCur->pKey);
864 pCur->pKey = 0;
865 assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
866 if( skipNext ) pCur->skipNext = skipNext;
867 if( pCur->skipNext && pCur->eState==CURSOR_VALID ){
868 pCur->eState = CURSOR_SKIPNEXT;
871 return rc;
874 #define restoreCursorPosition(p) \
875 (p->eState>=CURSOR_REQUIRESEEK ? \
876 btreeRestoreCursorPosition(p) : \
877 SQLITE_OK)
880 ** Determine whether or not a cursor has moved from the position where
881 ** it was last placed, or has been invalidated for any other reason.
882 ** Cursors can move when the row they are pointing at is deleted out
883 ** from under them, for example. Cursor might also move if a btree
884 ** is rebalanced.
886 ** Calling this routine with a NULL cursor pointer returns false.
888 ** Use the separate sqlite3BtreeCursorRestore() routine to restore a cursor
889 ** back to where it ought to be if this routine returns true.
891 int sqlite3BtreeCursorHasMoved(BtCursor *pCur){
892 assert( EIGHT_BYTE_ALIGNMENT(pCur)
893 || pCur==sqlite3BtreeFakeValidCursor() );
894 assert( offsetof(BtCursor, eState)==0 );
895 assert( sizeof(pCur->eState)==1 );
896 return CURSOR_VALID != *(u8*)pCur;
900 ** Return a pointer to a fake BtCursor object that will always answer
901 ** false to the sqlite3BtreeCursorHasMoved() routine above. The fake
902 ** cursor returned must not be used with any other Btree interface.
904 BtCursor *sqlite3BtreeFakeValidCursor(void){
905 static u8 fakeCursor = CURSOR_VALID;
906 assert( offsetof(BtCursor, eState)==0 );
907 return (BtCursor*)&fakeCursor;
911 ** This routine restores a cursor back to its original position after it
912 ** has been moved by some outside activity (such as a btree rebalance or
913 ** a row having been deleted out from under the cursor).
915 ** On success, the *pDifferentRow parameter is false if the cursor is left
916 ** pointing at exactly the same row. *pDifferntRow is the row the cursor
917 ** was pointing to has been deleted, forcing the cursor to point to some
918 ** nearby row.
920 ** This routine should only be called for a cursor that just returned
921 ** TRUE from sqlite3BtreeCursorHasMoved().
923 int sqlite3BtreeCursorRestore(BtCursor *pCur, int *pDifferentRow){
924 int rc;
926 assert( pCur!=0 );
927 assert( pCur->eState!=CURSOR_VALID );
928 rc = restoreCursorPosition(pCur);
929 if( rc ){
930 *pDifferentRow = 1;
931 return rc;
933 if( pCur->eState!=CURSOR_VALID ){
934 *pDifferentRow = 1;
935 }else{
936 *pDifferentRow = 0;
938 return SQLITE_OK;
941 #ifdef SQLITE_ENABLE_CURSOR_HINTS
943 ** Provide hints to the cursor. The particular hint given (and the type
944 ** and number of the varargs parameters) is determined by the eHintType
945 ** parameter. See the definitions of the BTREE_HINT_* macros for details.
947 void sqlite3BtreeCursorHint(BtCursor *pCur, int eHintType, ...){
948 /* Used only by system that substitute their own storage engine */
950 #endif
953 ** Provide flag hints to the cursor.
955 void sqlite3BtreeCursorHintFlags(BtCursor *pCur, unsigned x){
956 assert( x==BTREE_SEEK_EQ || x==BTREE_BULKLOAD || x==0 );
957 pCur->hints = x;
961 #ifndef SQLITE_OMIT_AUTOVACUUM
963 ** Given a page number of a regular database page, return the page
964 ** number for the pointer-map page that contains the entry for the
965 ** input page number.
967 ** Return 0 (not a valid page) for pgno==1 since there is
968 ** no pointer map associated with page 1. The integrity_check logic
969 ** requires that ptrmapPageno(*,1)!=1.
971 static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
972 int nPagesPerMapPage;
973 Pgno iPtrMap, ret;
974 assert( sqlite3_mutex_held(pBt->mutex) );
975 if( pgno<2 ) return 0;
976 nPagesPerMapPage = (pBt->usableSize/5)+1;
977 iPtrMap = (pgno-2)/nPagesPerMapPage;
978 ret = (iPtrMap*nPagesPerMapPage) + 2;
979 if( ret==PENDING_BYTE_PAGE(pBt) ){
980 ret++;
982 return ret;
986 ** Write an entry into the pointer map.
988 ** This routine updates the pointer map entry for page number 'key'
989 ** so that it maps to type 'eType' and parent page number 'pgno'.
991 ** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
992 ** a no-op. If an error occurs, the appropriate error code is written
993 ** into *pRC.
995 static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
996 DbPage *pDbPage; /* The pointer map page */
997 u8 *pPtrmap; /* The pointer map data */
998 Pgno iPtrmap; /* The pointer map page number */
999 int offset; /* Offset in pointer map page */
1000 int rc; /* Return code from subfunctions */
1002 if( *pRC ) return;
1004 assert( sqlite3_mutex_held(pBt->mutex) );
1005 /* The super-journal page number must never be used as a pointer map page */
1006 assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
1008 assert( pBt->autoVacuum );
1009 if( key==0 ){
1010 *pRC = SQLITE_CORRUPT_BKPT;
1011 return;
1013 iPtrmap = PTRMAP_PAGENO(pBt, key);
1014 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0);
1015 if( rc!=SQLITE_OK ){
1016 *pRC = rc;
1017 return;
1019 if( ((char*)sqlite3PagerGetExtra(pDbPage))[0]!=0 ){
1020 /* The first byte of the extra data is the MemPage.isInit byte.
1021 ** If that byte is set, it means this page is also being used
1022 ** as a btree page. */
1023 *pRC = SQLITE_CORRUPT_BKPT;
1024 goto ptrmap_exit;
1026 offset = PTRMAP_PTROFFSET(iPtrmap, key);
1027 if( offset<0 ){
1028 *pRC = SQLITE_CORRUPT_BKPT;
1029 goto ptrmap_exit;
1031 assert( offset <= (int)pBt->usableSize-5 );
1032 pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
1034 if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
1035 TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
1036 *pRC= rc = sqlite3PagerWrite(pDbPage);
1037 if( rc==SQLITE_OK ){
1038 pPtrmap[offset] = eType;
1039 put4byte(&pPtrmap[offset+1], parent);
1043 ptrmap_exit:
1044 sqlite3PagerUnref(pDbPage);
1048 ** Read an entry from the pointer map.
1050 ** This routine retrieves the pointer map entry for page 'key', writing
1051 ** the type and parent page number to *pEType and *pPgno respectively.
1052 ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
1054 static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
1055 DbPage *pDbPage; /* The pointer map page */
1056 int iPtrmap; /* Pointer map page index */
1057 u8 *pPtrmap; /* Pointer map page data */
1058 int offset; /* Offset of entry in pointer map */
1059 int rc;
1061 assert( sqlite3_mutex_held(pBt->mutex) );
1063 iPtrmap = PTRMAP_PAGENO(pBt, key);
1064 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0);
1065 if( rc!=0 ){
1066 return rc;
1068 pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
1070 offset = PTRMAP_PTROFFSET(iPtrmap, key);
1071 if( offset<0 ){
1072 sqlite3PagerUnref(pDbPage);
1073 return SQLITE_CORRUPT_BKPT;
1075 assert( offset <= (int)pBt->usableSize-5 );
1076 assert( pEType!=0 );
1077 *pEType = pPtrmap[offset];
1078 if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
1080 sqlite3PagerUnref(pDbPage);
1081 if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_PGNO(iPtrmap);
1082 return SQLITE_OK;
1085 #else /* if defined SQLITE_OMIT_AUTOVACUUM */
1086 #define ptrmapPut(w,x,y,z,rc)
1087 #define ptrmapGet(w,x,y,z) SQLITE_OK
1088 #define ptrmapPutOvflPtr(x, y, z, rc)
1089 #endif
1092 ** Given a btree page and a cell index (0 means the first cell on
1093 ** the page, 1 means the second cell, and so forth) return a pointer
1094 ** to the cell content.
1096 ** findCellPastPtr() does the same except it skips past the initial
1097 ** 4-byte child pointer found on interior pages, if there is one.
1099 ** This routine works only for pages that do not contain overflow cells.
1101 #define findCell(P,I) \
1102 ((P)->aData + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
1103 #define findCellPastPtr(P,I) \
1104 ((P)->aDataOfst + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
1108 ** This is common tail processing for btreeParseCellPtr() and
1109 ** btreeParseCellPtrIndex() for the case when the cell does not fit entirely
1110 ** on a single B-tree page. Make necessary adjustments to the CellInfo
1111 ** structure.
1113 static SQLITE_NOINLINE void btreeParseCellAdjustSizeForOverflow(
1114 MemPage *pPage, /* Page containing the cell */
1115 u8 *pCell, /* Pointer to the cell text. */
1116 CellInfo *pInfo /* Fill in this structure */
1118 /* If the payload will not fit completely on the local page, we have
1119 ** to decide how much to store locally and how much to spill onto
1120 ** overflow pages. The strategy is to minimize the amount of unused
1121 ** space on overflow pages while keeping the amount of local storage
1122 ** in between minLocal and maxLocal.
1124 ** Warning: changing the way overflow payload is distributed in any
1125 ** way will result in an incompatible file format.
1127 int minLocal; /* Minimum amount of payload held locally */
1128 int maxLocal; /* Maximum amount of payload held locally */
1129 int surplus; /* Overflow payload available for local storage */
1131 minLocal = pPage->minLocal;
1132 maxLocal = pPage->maxLocal;
1133 surplus = minLocal + (pInfo->nPayload - minLocal)%(pPage->pBt->usableSize-4);
1134 testcase( surplus==maxLocal );
1135 testcase( surplus==maxLocal+1 );
1136 if( surplus <= maxLocal ){
1137 pInfo->nLocal = (u16)surplus;
1138 }else{
1139 pInfo->nLocal = (u16)minLocal;
1141 pInfo->nSize = (u16)(&pInfo->pPayload[pInfo->nLocal] - pCell) + 4;
1145 ** Given a record with nPayload bytes of payload stored within btree
1146 ** page pPage, return the number of bytes of payload stored locally.
1148 static int btreePayloadToLocal(MemPage *pPage, i64 nPayload){
1149 int maxLocal; /* Maximum amount of payload held locally */
1150 maxLocal = pPage->maxLocal;
1151 if( nPayload<=maxLocal ){
1152 return nPayload;
1153 }else{
1154 int minLocal; /* Minimum amount of payload held locally */
1155 int surplus; /* Overflow payload available for local storage */
1156 minLocal = pPage->minLocal;
1157 surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize-4);
1158 return ( surplus <= maxLocal ) ? surplus : minLocal;
1163 ** The following routines are implementations of the MemPage.xParseCell()
1164 ** method.
1166 ** Parse a cell content block and fill in the CellInfo structure.
1168 ** btreeParseCellPtr() => table btree leaf nodes
1169 ** btreeParseCellNoPayload() => table btree internal nodes
1170 ** btreeParseCellPtrIndex() => index btree nodes
1172 ** There is also a wrapper function btreeParseCell() that works for
1173 ** all MemPage types and that references the cell by index rather than
1174 ** by pointer.
1176 static void btreeParseCellPtrNoPayload(
1177 MemPage *pPage, /* Page containing the cell */
1178 u8 *pCell, /* Pointer to the cell text. */
1179 CellInfo *pInfo /* Fill in this structure */
1181 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1182 assert( pPage->leaf==0 );
1183 assert( pPage->childPtrSize==4 );
1184 #ifndef SQLITE_DEBUG
1185 UNUSED_PARAMETER(pPage);
1186 #endif
1187 pInfo->nSize = 4 + getVarint(&pCell[4], (u64*)&pInfo->nKey);
1188 pInfo->nPayload = 0;
1189 pInfo->nLocal = 0;
1190 pInfo->pPayload = 0;
1191 return;
1193 static void btreeParseCellPtr(
1194 MemPage *pPage, /* Page containing the cell */
1195 u8 *pCell, /* Pointer to the cell text. */
1196 CellInfo *pInfo /* Fill in this structure */
1198 u8 *pIter; /* For scanning through pCell */
1199 u32 nPayload; /* Number of bytes of cell payload */
1200 u64 iKey; /* Extracted Key value */
1202 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1203 assert( pPage->leaf==0 || pPage->leaf==1 );
1204 assert( pPage->intKeyLeaf );
1205 assert( pPage->childPtrSize==0 );
1206 pIter = pCell;
1208 /* The next block of code is equivalent to:
1210 ** pIter += getVarint32(pIter, nPayload);
1212 ** The code is inlined to avoid a function call.
1214 nPayload = *pIter;
1215 if( nPayload>=0x80 ){
1216 u8 *pEnd = &pIter[8];
1217 nPayload &= 0x7f;
1219 nPayload = (nPayload<<7) | (*++pIter & 0x7f);
1220 }while( (*pIter)>=0x80 && pIter<pEnd );
1222 pIter++;
1224 /* The next block of code is equivalent to:
1226 ** pIter += getVarint(pIter, (u64*)&pInfo->nKey);
1228 ** The code is inlined to avoid a function call.
1230 iKey = *pIter;
1231 if( iKey>=0x80 ){
1232 u8 *pEnd = &pIter[7];
1233 iKey &= 0x7f;
1234 while(1){
1235 iKey = (iKey<<7) | (*++pIter & 0x7f);
1236 if( (*pIter)<0x80 ) break;
1237 if( pIter>=pEnd ){
1238 iKey = (iKey<<8) | *++pIter;
1239 break;
1243 pIter++;
1245 pInfo->nKey = *(i64*)&iKey;
1246 pInfo->nPayload = nPayload;
1247 pInfo->pPayload = pIter;
1248 testcase( nPayload==pPage->maxLocal );
1249 testcase( nPayload==(u32)pPage->maxLocal+1 );
1250 if( nPayload<=pPage->maxLocal ){
1251 /* This is the (easy) common case where the entire payload fits
1252 ** on the local page. No overflow is required.
1254 pInfo->nSize = nPayload + (u16)(pIter - pCell);
1255 if( pInfo->nSize<4 ) pInfo->nSize = 4;
1256 pInfo->nLocal = (u16)nPayload;
1257 }else{
1258 btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
1261 static void btreeParseCellPtrIndex(
1262 MemPage *pPage, /* Page containing the cell */
1263 u8 *pCell, /* Pointer to the cell text. */
1264 CellInfo *pInfo /* Fill in this structure */
1266 u8 *pIter; /* For scanning through pCell */
1267 u32 nPayload; /* Number of bytes of cell payload */
1269 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1270 assert( pPage->leaf==0 || pPage->leaf==1 );
1271 assert( pPage->intKeyLeaf==0 );
1272 pIter = pCell + pPage->childPtrSize;
1273 nPayload = *pIter;
1274 if( nPayload>=0x80 ){
1275 u8 *pEnd = &pIter[8];
1276 nPayload &= 0x7f;
1278 nPayload = (nPayload<<7) | (*++pIter & 0x7f);
1279 }while( *(pIter)>=0x80 && pIter<pEnd );
1281 pIter++;
1282 pInfo->nKey = nPayload;
1283 pInfo->nPayload = nPayload;
1284 pInfo->pPayload = pIter;
1285 testcase( nPayload==pPage->maxLocal );
1286 testcase( nPayload==(u32)pPage->maxLocal+1 );
1287 if( nPayload<=pPage->maxLocal ){
1288 /* This is the (easy) common case where the entire payload fits
1289 ** on the local page. No overflow is required.
1291 pInfo->nSize = nPayload + (u16)(pIter - pCell);
1292 if( pInfo->nSize<4 ) pInfo->nSize = 4;
1293 pInfo->nLocal = (u16)nPayload;
1294 }else{
1295 btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
1298 static void btreeParseCell(
1299 MemPage *pPage, /* Page containing the cell */
1300 int iCell, /* The cell index. First cell is 0 */
1301 CellInfo *pInfo /* Fill in this structure */
1303 pPage->xParseCell(pPage, findCell(pPage, iCell), pInfo);
1307 ** The following routines are implementations of the MemPage.xCellSize
1308 ** method.
1310 ** Compute the total number of bytes that a Cell needs in the cell
1311 ** data area of the btree-page. The return number includes the cell
1312 ** data header and the local payload, but not any overflow page or
1313 ** the space used by the cell pointer.
1315 ** cellSizePtrNoPayload() => table internal nodes
1316 ** cellSizePtr() => all index nodes & table leaf nodes
1318 static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
1319 u8 *pIter = pCell + pPage->childPtrSize; /* For looping over bytes of pCell */
1320 u8 *pEnd; /* End mark for a varint */
1321 u32 nSize; /* Size value to return */
1323 #ifdef SQLITE_DEBUG
1324 /* The value returned by this function should always be the same as
1325 ** the (CellInfo.nSize) value found by doing a full parse of the
1326 ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
1327 ** this function verifies that this invariant is not violated. */
1328 CellInfo debuginfo;
1329 pPage->xParseCell(pPage, pCell, &debuginfo);
1330 #endif
1332 nSize = *pIter;
1333 if( nSize>=0x80 ){
1334 pEnd = &pIter[8];
1335 nSize &= 0x7f;
1337 nSize = (nSize<<7) | (*++pIter & 0x7f);
1338 }while( *(pIter)>=0x80 && pIter<pEnd );
1340 pIter++;
1341 if( pPage->intKey ){
1342 /* pIter now points at the 64-bit integer key value, a variable length
1343 ** integer. The following block moves pIter to point at the first byte
1344 ** past the end of the key value. */
1345 pEnd = &pIter[9];
1346 while( (*pIter++)&0x80 && pIter<pEnd );
1348 testcase( nSize==pPage->maxLocal );
1349 testcase( nSize==(u32)pPage->maxLocal+1 );
1350 if( nSize<=pPage->maxLocal ){
1351 nSize += (u32)(pIter - pCell);
1352 if( nSize<4 ) nSize = 4;
1353 }else{
1354 int minLocal = pPage->minLocal;
1355 nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
1356 testcase( nSize==pPage->maxLocal );
1357 testcase( nSize==(u32)pPage->maxLocal+1 );
1358 if( nSize>pPage->maxLocal ){
1359 nSize = minLocal;
1361 nSize += 4 + (u16)(pIter - pCell);
1363 assert( nSize==debuginfo.nSize || CORRUPT_DB );
1364 return (u16)nSize;
1366 static u16 cellSizePtrNoPayload(MemPage *pPage, u8 *pCell){
1367 u8 *pIter = pCell + 4; /* For looping over bytes of pCell */
1368 u8 *pEnd; /* End mark for a varint */
1370 #ifdef SQLITE_DEBUG
1371 /* The value returned by this function should always be the same as
1372 ** the (CellInfo.nSize) value found by doing a full parse of the
1373 ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
1374 ** this function verifies that this invariant is not violated. */
1375 CellInfo debuginfo;
1376 pPage->xParseCell(pPage, pCell, &debuginfo);
1377 #else
1378 UNUSED_PARAMETER(pPage);
1379 #endif
1381 assert( pPage->childPtrSize==4 );
1382 pEnd = pIter + 9;
1383 while( (*pIter++)&0x80 && pIter<pEnd );
1384 assert( debuginfo.nSize==(u16)(pIter - pCell) || CORRUPT_DB );
1385 return (u16)(pIter - pCell);
1389 #ifdef SQLITE_DEBUG
1390 /* This variation on cellSizePtr() is used inside of assert() statements
1391 ** only. */
1392 static u16 cellSize(MemPage *pPage, int iCell){
1393 return pPage->xCellSize(pPage, findCell(pPage, iCell));
1395 #endif
1397 #ifndef SQLITE_OMIT_AUTOVACUUM
1399 ** The cell pCell is currently part of page pSrc but will ultimately be part
1400 ** of pPage. (pSrc and pPager are often the same.) If pCell contains a
1401 ** pointer to an overflow page, insert an entry into the pointer-map for
1402 ** the overflow page that will be valid after pCell has been moved to pPage.
1404 static void ptrmapPutOvflPtr(MemPage *pPage, MemPage *pSrc, u8 *pCell,int *pRC){
1405 CellInfo info;
1406 if( *pRC ) return;
1407 assert( pCell!=0 );
1408 pPage->xParseCell(pPage, pCell, &info);
1409 if( info.nLocal<info.nPayload ){
1410 Pgno ovfl;
1411 if( SQLITE_WITHIN(pSrc->aDataEnd, pCell, pCell+info.nLocal) ){
1412 testcase( pSrc!=pPage );
1413 *pRC = SQLITE_CORRUPT_BKPT;
1414 return;
1416 ovfl = get4byte(&pCell[info.nSize-4]);
1417 ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
1420 #endif
1424 ** Defragment the page given. This routine reorganizes cells within the
1425 ** page so that there are no free-blocks on the free-block list.
1427 ** Parameter nMaxFrag is the maximum amount of fragmented space that may be
1428 ** present in the page after this routine returns.
1430 ** EVIDENCE-OF: R-44582-60138 SQLite may from time to time reorganize a
1431 ** b-tree page so that there are no freeblocks or fragment bytes, all
1432 ** unused bytes are contained in the unallocated space region, and all
1433 ** cells are packed tightly at the end of the page.
1435 static int defragmentPage(MemPage *pPage, int nMaxFrag){
1436 int i; /* Loop counter */
1437 int pc; /* Address of the i-th cell */
1438 int hdr; /* Offset to the page header */
1439 int size; /* Size of a cell */
1440 int usableSize; /* Number of usable bytes on a page */
1441 int cellOffset; /* Offset to the cell pointer array */
1442 int cbrk; /* Offset to the cell content area */
1443 int nCell; /* Number of cells on the page */
1444 unsigned char *data; /* The page data */
1445 unsigned char *temp; /* Temp area for cell content */
1446 unsigned char *src; /* Source of content */
1447 int iCellFirst; /* First allowable cell index */
1448 int iCellLast; /* Last possible cell index */
1449 int iCellStart; /* First cell offset in input */
1451 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
1452 assert( pPage->pBt!=0 );
1453 assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
1454 assert( pPage->nOverflow==0 );
1455 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1456 temp = 0;
1457 src = data = pPage->aData;
1458 hdr = pPage->hdrOffset;
1459 cellOffset = pPage->cellOffset;
1460 nCell = pPage->nCell;
1461 assert( nCell==get2byte(&data[hdr+3]) || CORRUPT_DB );
1462 iCellFirst = cellOffset + 2*nCell;
1463 usableSize = pPage->pBt->usableSize;
1465 /* This block handles pages with two or fewer free blocks and nMaxFrag
1466 ** or fewer fragmented bytes. In this case it is faster to move the
1467 ** two (or one) blocks of cells using memmove() and add the required
1468 ** offsets to each pointer in the cell-pointer array than it is to
1469 ** reconstruct the entire page. */
1470 if( (int)data[hdr+7]<=nMaxFrag ){
1471 int iFree = get2byte(&data[hdr+1]);
1472 if( iFree>usableSize-4 ) return SQLITE_CORRUPT_PAGE(pPage);
1473 if( iFree ){
1474 int iFree2 = get2byte(&data[iFree]);
1475 if( iFree2>usableSize-4 ) return SQLITE_CORRUPT_PAGE(pPage);
1476 if( 0==iFree2 || (data[iFree2]==0 && data[iFree2+1]==0) ){
1477 u8 *pEnd = &data[cellOffset + nCell*2];
1478 u8 *pAddr;
1479 int sz2 = 0;
1480 int sz = get2byte(&data[iFree+2]);
1481 int top = get2byte(&data[hdr+5]);
1482 if( top>=iFree ){
1483 return SQLITE_CORRUPT_PAGE(pPage);
1485 if( iFree2 ){
1486 if( iFree+sz>iFree2 ) return SQLITE_CORRUPT_PAGE(pPage);
1487 sz2 = get2byte(&data[iFree2+2]);
1488 if( iFree2+sz2 > usableSize ) return SQLITE_CORRUPT_PAGE(pPage);
1489 memmove(&data[iFree+sz+sz2], &data[iFree+sz], iFree2-(iFree+sz));
1490 sz += sz2;
1491 }else if( NEVER(iFree+sz>usableSize) ){
1492 return SQLITE_CORRUPT_PAGE(pPage);
1495 cbrk = top+sz;
1496 assert( cbrk+(iFree-top) <= usableSize );
1497 memmove(&data[cbrk], &data[top], iFree-top);
1498 for(pAddr=&data[cellOffset]; pAddr<pEnd; pAddr+=2){
1499 pc = get2byte(pAddr);
1500 if( pc<iFree ){ put2byte(pAddr, pc+sz); }
1501 else if( pc<iFree2 ){ put2byte(pAddr, pc+sz2); }
1503 goto defragment_out;
1508 cbrk = usableSize;
1509 iCellLast = usableSize - 4;
1510 iCellStart = get2byte(&data[hdr+5]);
1511 for(i=0; i<nCell; i++){
1512 u8 *pAddr; /* The i-th cell pointer */
1513 pAddr = &data[cellOffset + i*2];
1514 pc = get2byte(pAddr);
1515 testcase( pc==iCellFirst );
1516 testcase( pc==iCellLast );
1517 /* These conditions have already been verified in btreeInitPage()
1518 ** if PRAGMA cell_size_check=ON.
1520 if( pc<iCellStart || pc>iCellLast ){
1521 return SQLITE_CORRUPT_PAGE(pPage);
1523 assert( pc>=iCellStart && pc<=iCellLast );
1524 size = pPage->xCellSize(pPage, &src[pc]);
1525 cbrk -= size;
1526 if( cbrk<iCellStart || pc+size>usableSize ){
1527 return SQLITE_CORRUPT_PAGE(pPage);
1529 assert( cbrk+size<=usableSize && cbrk>=iCellStart );
1530 testcase( cbrk+size==usableSize );
1531 testcase( pc+size==usableSize );
1532 put2byte(pAddr, cbrk);
1533 if( temp==0 ){
1534 if( cbrk==pc ) continue;
1535 temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
1536 memcpy(&temp[iCellStart], &data[iCellStart], usableSize - iCellStart);
1537 src = temp;
1539 memcpy(&data[cbrk], &src[pc], size);
1541 data[hdr+7] = 0;
1543 defragment_out:
1544 assert( pPage->nFree>=0 );
1545 if( data[hdr+7]+cbrk-iCellFirst!=pPage->nFree ){
1546 return SQLITE_CORRUPT_PAGE(pPage);
1548 assert( cbrk>=iCellFirst );
1549 put2byte(&data[hdr+5], cbrk);
1550 data[hdr+1] = 0;
1551 data[hdr+2] = 0;
1552 memset(&data[iCellFirst], 0, cbrk-iCellFirst);
1553 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
1554 return SQLITE_OK;
1558 ** Search the free-list on page pPg for space to store a cell nByte bytes in
1559 ** size. If one can be found, return a pointer to the space and remove it
1560 ** from the free-list.
1562 ** If no suitable space can be found on the free-list, return NULL.
1564 ** This function may detect corruption within pPg. If corruption is
1565 ** detected then *pRc is set to SQLITE_CORRUPT and NULL is returned.
1567 ** Slots on the free list that are between 1 and 3 bytes larger than nByte
1568 ** will be ignored if adding the extra space to the fragmentation count
1569 ** causes the fragmentation count to exceed 60.
1571 static u8 *pageFindSlot(MemPage *pPg, int nByte, int *pRc){
1572 const int hdr = pPg->hdrOffset; /* Offset to page header */
1573 u8 * const aData = pPg->aData; /* Page data */
1574 int iAddr = hdr + 1; /* Address of ptr to pc */
1575 int pc = get2byte(&aData[iAddr]); /* Address of a free slot */
1576 int x; /* Excess size of the slot */
1577 int maxPC = pPg->pBt->usableSize - nByte; /* Max address for a usable slot */
1578 int size; /* Size of the free slot */
1580 assert( pc>0 );
1581 while( pc<=maxPC ){
1582 /* EVIDENCE-OF: R-22710-53328 The third and fourth bytes of each
1583 ** freeblock form a big-endian integer which is the size of the freeblock
1584 ** in bytes, including the 4-byte header. */
1585 size = get2byte(&aData[pc+2]);
1586 if( (x = size - nByte)>=0 ){
1587 testcase( x==4 );
1588 testcase( x==3 );
1589 if( x<4 ){
1590 /* EVIDENCE-OF: R-11498-58022 In a well-formed b-tree page, the total
1591 ** number of bytes in fragments may not exceed 60. */
1592 if( aData[hdr+7]>57 ) return 0;
1594 /* Remove the slot from the free-list. Update the number of
1595 ** fragmented bytes within the page. */
1596 memcpy(&aData[iAddr], &aData[pc], 2);
1597 aData[hdr+7] += (u8)x;
1598 }else if( x+pc > maxPC ){
1599 /* This slot extends off the end of the usable part of the page */
1600 *pRc = SQLITE_CORRUPT_PAGE(pPg);
1601 return 0;
1602 }else{
1603 /* The slot remains on the free-list. Reduce its size to account
1604 ** for the portion used by the new allocation. */
1605 put2byte(&aData[pc+2], x);
1607 return &aData[pc + x];
1609 iAddr = pc;
1610 pc = get2byte(&aData[pc]);
1611 if( pc<=iAddr+size ){
1612 if( pc ){
1613 /* The next slot in the chain is not past the end of the current slot */
1614 *pRc = SQLITE_CORRUPT_PAGE(pPg);
1616 return 0;
1619 if( pc>maxPC+nByte-4 ){
1620 /* The free slot chain extends off the end of the page */
1621 *pRc = SQLITE_CORRUPT_PAGE(pPg);
1623 return 0;
1627 ** Allocate nByte bytes of space from within the B-Tree page passed
1628 ** as the first argument. Write into *pIdx the index into pPage->aData[]
1629 ** of the first byte of allocated space. Return either SQLITE_OK or
1630 ** an error code (usually SQLITE_CORRUPT).
1632 ** The caller guarantees that there is sufficient space to make the
1633 ** allocation. This routine might need to defragment in order to bring
1634 ** all the space together, however. This routine will avoid using
1635 ** the first two bytes past the cell pointer area since presumably this
1636 ** allocation is being made in order to insert a new cell, so we will
1637 ** also end up needing a new cell pointer.
1639 static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
1640 const int hdr = pPage->hdrOffset; /* Local cache of pPage->hdrOffset */
1641 u8 * const data = pPage->aData; /* Local cache of pPage->aData */
1642 int top; /* First byte of cell content area */
1643 int rc = SQLITE_OK; /* Integer return code */
1644 int gap; /* First byte of gap between cell pointers and cell content */
1646 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
1647 assert( pPage->pBt );
1648 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1649 assert( nByte>=0 ); /* Minimum cell size is 4 */
1650 assert( pPage->nFree>=nByte );
1651 assert( pPage->nOverflow==0 );
1652 assert( nByte < (int)(pPage->pBt->usableSize-8) );
1654 assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
1655 gap = pPage->cellOffset + 2*pPage->nCell;
1656 assert( gap<=65536 );
1657 /* EVIDENCE-OF: R-29356-02391 If the database uses a 65536-byte page size
1658 ** and the reserved space is zero (the usual value for reserved space)
1659 ** then the cell content offset of an empty page wants to be 65536.
1660 ** However, that integer is too large to be stored in a 2-byte unsigned
1661 ** integer, so a value of 0 is used in its place. */
1662 top = get2byte(&data[hdr+5]);
1663 assert( top<=(int)pPage->pBt->usableSize ); /* by btreeComputeFreeSpace() */
1664 if( gap>top ){
1665 if( top==0 && pPage->pBt->usableSize==65536 ){
1666 top = 65536;
1667 }else{
1668 return SQLITE_CORRUPT_PAGE(pPage);
1672 /* If there is enough space between gap and top for one more cell pointer,
1673 ** and if the freelist is not empty, then search the
1674 ** freelist looking for a slot big enough to satisfy the request.
1676 testcase( gap+2==top );
1677 testcase( gap+1==top );
1678 testcase( gap==top );
1679 if( (data[hdr+2] || data[hdr+1]) && gap+2<=top ){
1680 u8 *pSpace = pageFindSlot(pPage, nByte, &rc);
1681 if( pSpace ){
1682 int g2;
1683 assert( pSpace+nByte<=data+pPage->pBt->usableSize );
1684 *pIdx = g2 = (int)(pSpace-data);
1685 if( g2<=gap ){
1686 return SQLITE_CORRUPT_PAGE(pPage);
1687 }else{
1688 return SQLITE_OK;
1690 }else if( rc ){
1691 return rc;
1695 /* The request could not be fulfilled using a freelist slot. Check
1696 ** to see if defragmentation is necessary.
1698 testcase( gap+2+nByte==top );
1699 if( gap+2+nByte>top ){
1700 assert( pPage->nCell>0 || CORRUPT_DB );
1701 assert( pPage->nFree>=0 );
1702 rc = defragmentPage(pPage, MIN(4, pPage->nFree - (2+nByte)));
1703 if( rc ) return rc;
1704 top = get2byteNotZero(&data[hdr+5]);
1705 assert( gap+2+nByte<=top );
1709 /* Allocate memory from the gap in between the cell pointer array
1710 ** and the cell content area. The btreeComputeFreeSpace() call has already
1711 ** validated the freelist. Given that the freelist is valid, there
1712 ** is no way that the allocation can extend off the end of the page.
1713 ** The assert() below verifies the previous sentence.
1715 top -= nByte;
1716 put2byte(&data[hdr+5], top);
1717 assert( top+nByte <= (int)pPage->pBt->usableSize );
1718 *pIdx = top;
1719 return SQLITE_OK;
1723 ** Return a section of the pPage->aData to the freelist.
1724 ** The first byte of the new free block is pPage->aData[iStart]
1725 ** and the size of the block is iSize bytes.
1727 ** Adjacent freeblocks are coalesced.
1729 ** Even though the freeblock list was checked by btreeComputeFreeSpace(),
1730 ** that routine will not detect overlap between cells or freeblocks. Nor
1731 ** does it detect cells or freeblocks that encrouch into the reserved bytes
1732 ** at the end of the page. So do additional corruption checks inside this
1733 ** routine and return SQLITE_CORRUPT if any problems are found.
1735 static int freeSpace(MemPage *pPage, u16 iStart, u16 iSize){
1736 u16 iPtr; /* Address of ptr to next freeblock */
1737 u16 iFreeBlk; /* Address of the next freeblock */
1738 u8 hdr; /* Page header size. 0 or 100 */
1739 u8 nFrag = 0; /* Reduction in fragmentation */
1740 u16 iOrigSize = iSize; /* Original value of iSize */
1741 u16 x; /* Offset to cell content area */
1742 u32 iEnd = iStart + iSize; /* First byte past the iStart buffer */
1743 unsigned char *data = pPage->aData; /* Page content */
1745 assert( pPage->pBt!=0 );
1746 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
1747 assert( CORRUPT_DB || iStart>=pPage->hdrOffset+6+pPage->childPtrSize );
1748 assert( CORRUPT_DB || iEnd <= pPage->pBt->usableSize );
1749 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1750 assert( iSize>=4 ); /* Minimum cell size is 4 */
1751 assert( iStart<=pPage->pBt->usableSize-4 );
1753 /* The list of freeblocks must be in ascending order. Find the
1754 ** spot on the list where iStart should be inserted.
1756 hdr = pPage->hdrOffset;
1757 iPtr = hdr + 1;
1758 if( data[iPtr+1]==0 && data[iPtr]==0 ){
1759 iFreeBlk = 0; /* Shortcut for the case when the freelist is empty */
1760 }else{
1761 while( (iFreeBlk = get2byte(&data[iPtr]))<iStart ){
1762 if( iFreeBlk<iPtr+4 ){
1763 if( iFreeBlk==0 ) break; /* TH3: corrupt082.100 */
1764 return SQLITE_CORRUPT_PAGE(pPage);
1766 iPtr = iFreeBlk;
1768 if( iFreeBlk>pPage->pBt->usableSize-4 ){ /* TH3: corrupt081.100 */
1769 return SQLITE_CORRUPT_PAGE(pPage);
1771 assert( iFreeBlk>iPtr || iFreeBlk==0 );
1773 /* At this point:
1774 ** iFreeBlk: First freeblock after iStart, or zero if none
1775 ** iPtr: The address of a pointer to iFreeBlk
1777 ** Check to see if iFreeBlk should be coalesced onto the end of iStart.
1779 if( iFreeBlk && iEnd+3>=iFreeBlk ){
1780 nFrag = iFreeBlk - iEnd;
1781 if( iEnd>iFreeBlk ) return SQLITE_CORRUPT_PAGE(pPage);
1782 iEnd = iFreeBlk + get2byte(&data[iFreeBlk+2]);
1783 if( iEnd > pPage->pBt->usableSize ){
1784 return SQLITE_CORRUPT_PAGE(pPage);
1786 iSize = iEnd - iStart;
1787 iFreeBlk = get2byte(&data[iFreeBlk]);
1790 /* If iPtr is another freeblock (that is, if iPtr is not the freelist
1791 ** pointer in the page header) then check to see if iStart should be
1792 ** coalesced onto the end of iPtr.
1794 if( iPtr>hdr+1 ){
1795 int iPtrEnd = iPtr + get2byte(&data[iPtr+2]);
1796 if( iPtrEnd+3>=iStart ){
1797 if( iPtrEnd>iStart ) return SQLITE_CORRUPT_PAGE(pPage);
1798 nFrag += iStart - iPtrEnd;
1799 iSize = iEnd - iPtr;
1800 iStart = iPtr;
1803 if( nFrag>data[hdr+7] ) return SQLITE_CORRUPT_PAGE(pPage);
1804 data[hdr+7] -= nFrag;
1806 x = get2byte(&data[hdr+5]);
1807 if( iStart<=x ){
1808 /* The new freeblock is at the beginning of the cell content area,
1809 ** so just extend the cell content area rather than create another
1810 ** freelist entry */
1811 if( iStart<x ) return SQLITE_CORRUPT_PAGE(pPage);
1812 if( iPtr!=hdr+1 ) return SQLITE_CORRUPT_PAGE(pPage);
1813 put2byte(&data[hdr+1], iFreeBlk);
1814 put2byte(&data[hdr+5], iEnd);
1815 }else{
1816 /* Insert the new freeblock into the freelist */
1817 put2byte(&data[iPtr], iStart);
1819 if( pPage->pBt->btsFlags & BTS_FAST_SECURE ){
1820 /* Overwrite deleted information with zeros when the secure_delete
1821 ** option is enabled */
1822 memset(&data[iStart], 0, iSize);
1824 put2byte(&data[iStart], iFreeBlk);
1825 put2byte(&data[iStart+2], iSize);
1826 pPage->nFree += iOrigSize;
1827 return SQLITE_OK;
1831 ** Decode the flags byte (the first byte of the header) for a page
1832 ** and initialize fields of the MemPage structure accordingly.
1834 ** Only the following combinations are supported. Anything different
1835 ** indicates a corrupt database files:
1837 ** PTF_ZERODATA
1838 ** PTF_ZERODATA | PTF_LEAF
1839 ** PTF_LEAFDATA | PTF_INTKEY
1840 ** PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
1842 static int decodeFlags(MemPage *pPage, int flagByte){
1843 BtShared *pBt; /* A copy of pPage->pBt */
1845 assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
1846 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1847 pPage->leaf = (u8)(flagByte>>3); assert( PTF_LEAF == 1<<3 );
1848 flagByte &= ~PTF_LEAF;
1849 pPage->childPtrSize = 4-4*pPage->leaf;
1850 pPage->xCellSize = cellSizePtr;
1851 pBt = pPage->pBt;
1852 if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
1853 /* EVIDENCE-OF: R-07291-35328 A value of 5 (0x05) means the page is an
1854 ** interior table b-tree page. */
1855 assert( (PTF_LEAFDATA|PTF_INTKEY)==5 );
1856 /* EVIDENCE-OF: R-26900-09176 A value of 13 (0x0d) means the page is a
1857 ** leaf table b-tree page. */
1858 assert( (PTF_LEAFDATA|PTF_INTKEY|PTF_LEAF)==13 );
1859 pPage->intKey = 1;
1860 if( pPage->leaf ){
1861 pPage->intKeyLeaf = 1;
1862 pPage->xParseCell = btreeParseCellPtr;
1863 }else{
1864 pPage->intKeyLeaf = 0;
1865 pPage->xCellSize = cellSizePtrNoPayload;
1866 pPage->xParseCell = btreeParseCellPtrNoPayload;
1868 pPage->maxLocal = pBt->maxLeaf;
1869 pPage->minLocal = pBt->minLeaf;
1870 }else if( flagByte==PTF_ZERODATA ){
1871 /* EVIDENCE-OF: R-43316-37308 A value of 2 (0x02) means the page is an
1872 ** interior index b-tree page. */
1873 assert( (PTF_ZERODATA)==2 );
1874 /* EVIDENCE-OF: R-59615-42828 A value of 10 (0x0a) means the page is a
1875 ** leaf index b-tree page. */
1876 assert( (PTF_ZERODATA|PTF_LEAF)==10 );
1877 pPage->intKey = 0;
1878 pPage->intKeyLeaf = 0;
1879 pPage->xParseCell = btreeParseCellPtrIndex;
1880 pPage->maxLocal = pBt->maxLocal;
1881 pPage->minLocal = pBt->minLocal;
1882 }else{
1883 /* EVIDENCE-OF: R-47608-56469 Any other value for the b-tree page type is
1884 ** an error. */
1885 return SQLITE_CORRUPT_PAGE(pPage);
1887 pPage->max1bytePayload = pBt->max1bytePayload;
1888 return SQLITE_OK;
1892 ** Compute the amount of freespace on the page. In other words, fill
1893 ** in the pPage->nFree field.
1895 static int btreeComputeFreeSpace(MemPage *pPage){
1896 int pc; /* Address of a freeblock within pPage->aData[] */
1897 u8 hdr; /* Offset to beginning of page header */
1898 u8 *data; /* Equal to pPage->aData */
1899 int usableSize; /* Amount of usable space on each page */
1900 int nFree; /* Number of unused bytes on the page */
1901 int top; /* First byte of the cell content area */
1902 int iCellFirst; /* First allowable cell or freeblock offset */
1903 int iCellLast; /* Last possible cell or freeblock offset */
1905 assert( pPage->pBt!=0 );
1906 assert( pPage->pBt->db!=0 );
1907 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1908 assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
1909 assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
1910 assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
1911 assert( pPage->isInit==1 );
1912 assert( pPage->nFree<0 );
1914 usableSize = pPage->pBt->usableSize;
1915 hdr = pPage->hdrOffset;
1916 data = pPage->aData;
1917 /* EVIDENCE-OF: R-58015-48175 The two-byte integer at offset 5 designates
1918 ** the start of the cell content area. A zero value for this integer is
1919 ** interpreted as 65536. */
1920 top = get2byteNotZero(&data[hdr+5]);
1921 iCellFirst = hdr + 8 + pPage->childPtrSize + 2*pPage->nCell;
1922 iCellLast = usableSize - 4;
1924 /* Compute the total free space on the page
1925 ** EVIDENCE-OF: R-23588-34450 The two-byte integer at offset 1 gives the
1926 ** start of the first freeblock on the page, or is zero if there are no
1927 ** freeblocks. */
1928 pc = get2byte(&data[hdr+1]);
1929 nFree = data[hdr+7] + top; /* Init nFree to non-freeblock free space */
1930 if( pc>0 ){
1931 u32 next, size;
1932 if( pc<top ){
1933 /* EVIDENCE-OF: R-55530-52930 In a well-formed b-tree page, there will
1934 ** always be at least one cell before the first freeblock.
1936 return SQLITE_CORRUPT_PAGE(pPage);
1938 while( 1 ){
1939 if( pc>iCellLast ){
1940 /* Freeblock off the end of the page */
1941 return SQLITE_CORRUPT_PAGE(pPage);
1943 next = get2byte(&data[pc]);
1944 size = get2byte(&data[pc+2]);
1945 nFree = nFree + size;
1946 if( next<=pc+size+3 ) break;
1947 pc = next;
1949 if( next>0 ){
1950 /* Freeblock not in ascending order */
1951 return SQLITE_CORRUPT_PAGE(pPage);
1953 if( pc+size>(unsigned int)usableSize ){
1954 /* Last freeblock extends past page end */
1955 return SQLITE_CORRUPT_PAGE(pPage);
1959 /* At this point, nFree contains the sum of the offset to the start
1960 ** of the cell-content area plus the number of free bytes within
1961 ** the cell-content area. If this is greater than the usable-size
1962 ** of the page, then the page must be corrupted. This check also
1963 ** serves to verify that the offset to the start of the cell-content
1964 ** area, according to the page header, lies within the page.
1966 if( nFree>usableSize || nFree<iCellFirst ){
1967 return SQLITE_CORRUPT_PAGE(pPage);
1969 pPage->nFree = (u16)(nFree - iCellFirst);
1970 return SQLITE_OK;
1974 ** Do additional sanity check after btreeInitPage() if
1975 ** PRAGMA cell_size_check=ON
1977 static SQLITE_NOINLINE int btreeCellSizeCheck(MemPage *pPage){
1978 int iCellFirst; /* First allowable cell or freeblock offset */
1979 int iCellLast; /* Last possible cell or freeblock offset */
1980 int i; /* Index into the cell pointer array */
1981 int sz; /* Size of a cell */
1982 int pc; /* Address of a freeblock within pPage->aData[] */
1983 u8 *data; /* Equal to pPage->aData */
1984 int usableSize; /* Maximum usable space on the page */
1985 int cellOffset; /* Start of cell content area */
1987 iCellFirst = pPage->cellOffset + 2*pPage->nCell;
1988 usableSize = pPage->pBt->usableSize;
1989 iCellLast = usableSize - 4;
1990 data = pPage->aData;
1991 cellOffset = pPage->cellOffset;
1992 if( !pPage->leaf ) iCellLast--;
1993 for(i=0; i<pPage->nCell; i++){
1994 pc = get2byteAligned(&data[cellOffset+i*2]);
1995 testcase( pc==iCellFirst );
1996 testcase( pc==iCellLast );
1997 if( pc<iCellFirst || pc>iCellLast ){
1998 return SQLITE_CORRUPT_PAGE(pPage);
2000 sz = pPage->xCellSize(pPage, &data[pc]);
2001 testcase( pc+sz==usableSize );
2002 if( pc+sz>usableSize ){
2003 return SQLITE_CORRUPT_PAGE(pPage);
2006 return SQLITE_OK;
2010 ** Initialize the auxiliary information for a disk block.
2012 ** Return SQLITE_OK on success. If we see that the page does
2013 ** not contain a well-formed database page, then return
2014 ** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
2015 ** guarantee that the page is well-formed. It only shows that
2016 ** we failed to detect any corruption.
2018 static int btreeInitPage(MemPage *pPage){
2019 u8 *data; /* Equal to pPage->aData */
2020 BtShared *pBt; /* The main btree structure */
2022 assert( pPage->pBt!=0 );
2023 assert( pPage->pBt->db!=0 );
2024 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
2025 assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
2026 assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
2027 assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
2028 assert( pPage->isInit==0 );
2030 pBt = pPage->pBt;
2031 data = pPage->aData + pPage->hdrOffset;
2032 /* EVIDENCE-OF: R-28594-02890 The one-byte flag at offset 0 indicating
2033 ** the b-tree page type. */
2034 if( decodeFlags(pPage, data[0]) ){
2035 return SQLITE_CORRUPT_PAGE(pPage);
2037 assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
2038 pPage->maskPage = (u16)(pBt->pageSize - 1);
2039 pPage->nOverflow = 0;
2040 pPage->cellOffset = pPage->hdrOffset + 8 + pPage->childPtrSize;
2041 pPage->aCellIdx = data + pPage->childPtrSize + 8;
2042 pPage->aDataEnd = pPage->aData + pBt->usableSize;
2043 pPage->aDataOfst = pPage->aData + pPage->childPtrSize;
2044 /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
2045 ** number of cells on the page. */
2046 pPage->nCell = get2byte(&data[3]);
2047 if( pPage->nCell>MX_CELL(pBt) ){
2048 /* To many cells for a single page. The page must be corrupt */
2049 return SQLITE_CORRUPT_PAGE(pPage);
2051 testcase( pPage->nCell==MX_CELL(pBt) );
2052 /* EVIDENCE-OF: R-24089-57979 If a page contains no cells (which is only
2053 ** possible for a root page of a table that contains no rows) then the
2054 ** offset to the cell content area will equal the page size minus the
2055 ** bytes of reserved space. */
2056 assert( pPage->nCell>0
2057 || get2byteNotZero(&data[5])==(int)pBt->usableSize
2058 || CORRUPT_DB );
2059 pPage->nFree = -1; /* Indicate that this value is yet uncomputed */
2060 pPage->isInit = 1;
2061 if( pBt->db->flags & SQLITE_CellSizeCk ){
2062 return btreeCellSizeCheck(pPage);
2064 return SQLITE_OK;
2068 ** Set up a raw page so that it looks like a database page holding
2069 ** no entries.
2071 static void zeroPage(MemPage *pPage, int flags){
2072 unsigned char *data = pPage->aData;
2073 BtShared *pBt = pPage->pBt;
2074 u8 hdr = pPage->hdrOffset;
2075 u16 first;
2077 assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
2078 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
2079 assert( sqlite3PagerGetData(pPage->pDbPage) == data );
2080 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
2081 assert( sqlite3_mutex_held(pBt->mutex) );
2082 if( pBt->btsFlags & BTS_FAST_SECURE ){
2083 memset(&data[hdr], 0, pBt->usableSize - hdr);
2085 data[hdr] = (char)flags;
2086 first = hdr + ((flags&PTF_LEAF)==0 ? 12 : 8);
2087 memset(&data[hdr+1], 0, 4);
2088 data[hdr+7] = 0;
2089 put2byte(&data[hdr+5], pBt->usableSize);
2090 pPage->nFree = (u16)(pBt->usableSize - first);
2091 decodeFlags(pPage, flags);
2092 pPage->cellOffset = first;
2093 pPage->aDataEnd = &data[pBt->usableSize];
2094 pPage->aCellIdx = &data[first];
2095 pPage->aDataOfst = &data[pPage->childPtrSize];
2096 pPage->nOverflow = 0;
2097 assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
2098 pPage->maskPage = (u16)(pBt->pageSize - 1);
2099 pPage->nCell = 0;
2100 pPage->isInit = 1;
2105 ** Convert a DbPage obtained from the pager into a MemPage used by
2106 ** the btree layer.
2108 static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
2109 MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
2110 if( pgno!=pPage->pgno ){
2111 pPage->aData = sqlite3PagerGetData(pDbPage);
2112 pPage->pDbPage = pDbPage;
2113 pPage->pBt = pBt;
2114 pPage->pgno = pgno;
2115 pPage->hdrOffset = pgno==1 ? 100 : 0;
2117 assert( pPage->aData==sqlite3PagerGetData(pDbPage) );
2118 return pPage;
2122 ** Get a page from the pager. Initialize the MemPage.pBt and
2123 ** MemPage.aData elements if needed. See also: btreeGetUnusedPage().
2125 ** If the PAGER_GET_NOCONTENT flag is set, it means that we do not care
2126 ** about the content of the page at this time. So do not go to the disk
2127 ** to fetch the content. Just fill in the content with zeros for now.
2128 ** If in the future we call sqlite3PagerWrite() on this page, that
2129 ** means we have started to be concerned about content and the disk
2130 ** read should occur at that point.
2132 static int btreeGetPage(
2133 BtShared *pBt, /* The btree */
2134 Pgno pgno, /* Number of the page to fetch */
2135 MemPage **ppPage, /* Return the page in this parameter */
2136 int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
2138 int rc;
2139 DbPage *pDbPage;
2141 assert( flags==0 || flags==PAGER_GET_NOCONTENT || flags==PAGER_GET_READONLY );
2142 assert( sqlite3_mutex_held(pBt->mutex) );
2143 rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, flags);
2144 if( rc ) return rc;
2145 *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
2146 return SQLITE_OK;
2150 ** Retrieve a page from the pager cache. If the requested page is not
2151 ** already in the pager cache return NULL. Initialize the MemPage.pBt and
2152 ** MemPage.aData elements if needed.
2154 static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
2155 DbPage *pDbPage;
2156 assert( sqlite3_mutex_held(pBt->mutex) );
2157 pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
2158 if( pDbPage ){
2159 return btreePageFromDbPage(pDbPage, pgno, pBt);
2161 return 0;
2165 ** Return the size of the database file in pages. If there is any kind of
2166 ** error, return ((unsigned int)-1).
2168 static Pgno btreePagecount(BtShared *pBt){
2169 return pBt->nPage;
2171 Pgno sqlite3BtreeLastPage(Btree *p){
2172 assert( sqlite3BtreeHoldsMutex(p) );
2173 return btreePagecount(p->pBt);
2177 ** Get a page from the pager and initialize it.
2179 ** If pCur!=0 then the page is being fetched as part of a moveToChild()
2180 ** call. Do additional sanity checking on the page in this case.
2181 ** And if the fetch fails, this routine must decrement pCur->iPage.
2183 ** The page is fetched as read-write unless pCur is not NULL and is
2184 ** a read-only cursor.
2186 ** If an error occurs, then *ppPage is undefined. It
2187 ** may remain unchanged, or it may be set to an invalid value.
2189 static int getAndInitPage(
2190 BtShared *pBt, /* The database file */
2191 Pgno pgno, /* Number of the page to get */
2192 MemPage **ppPage, /* Write the page pointer here */
2193 BtCursor *pCur, /* Cursor to receive the page, or NULL */
2194 int bReadOnly /* True for a read-only page */
2196 int rc;
2197 DbPage *pDbPage;
2198 assert( sqlite3_mutex_held(pBt->mutex) );
2199 assert( pCur==0 || ppPage==&pCur->pPage );
2200 assert( pCur==0 || bReadOnly==pCur->curPagerFlags );
2201 assert( pCur==0 || pCur->iPage>0 );
2203 if( pgno>btreePagecount(pBt) ){
2204 rc = SQLITE_CORRUPT_BKPT;
2205 goto getAndInitPage_error1;
2207 rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, bReadOnly);
2208 if( rc ){
2209 goto getAndInitPage_error1;
2211 *ppPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
2212 if( (*ppPage)->isInit==0 ){
2213 btreePageFromDbPage(pDbPage, pgno, pBt);
2214 rc = btreeInitPage(*ppPage);
2215 if( rc!=SQLITE_OK ){
2216 goto getAndInitPage_error2;
2219 assert( (*ppPage)->pgno==pgno );
2220 assert( (*ppPage)->aData==sqlite3PagerGetData(pDbPage) );
2222 /* If obtaining a child page for a cursor, we must verify that the page is
2223 ** compatible with the root page. */
2224 if( pCur && ((*ppPage)->nCell<1 || (*ppPage)->intKey!=pCur->curIntKey) ){
2225 rc = SQLITE_CORRUPT_PGNO(pgno);
2226 goto getAndInitPage_error2;
2228 return SQLITE_OK;
2230 getAndInitPage_error2:
2231 releasePage(*ppPage);
2232 getAndInitPage_error1:
2233 if( pCur ){
2234 pCur->iPage--;
2235 pCur->pPage = pCur->apPage[pCur->iPage];
2237 testcase( pgno==0 );
2238 assert( pgno!=0 || rc==SQLITE_CORRUPT );
2239 return rc;
2243 ** Release a MemPage. This should be called once for each prior
2244 ** call to btreeGetPage.
2246 ** Page1 is a special case and must be released using releasePageOne().
2248 static void releasePageNotNull(MemPage *pPage){
2249 assert( pPage->aData );
2250 assert( pPage->pBt );
2251 assert( pPage->pDbPage!=0 );
2252 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
2253 assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
2254 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
2255 sqlite3PagerUnrefNotNull(pPage->pDbPage);
2257 static void releasePage(MemPage *pPage){
2258 if( pPage ) releasePageNotNull(pPage);
2260 static void releasePageOne(MemPage *pPage){
2261 assert( pPage!=0 );
2262 assert( pPage->aData );
2263 assert( pPage->pBt );
2264 assert( pPage->pDbPage!=0 );
2265 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
2266 assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
2267 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
2268 sqlite3PagerUnrefPageOne(pPage->pDbPage);
2272 ** Get an unused page.
2274 ** This works just like btreeGetPage() with the addition:
2276 ** * If the page is already in use for some other purpose, immediately
2277 ** release it and return an SQLITE_CURRUPT error.
2278 ** * Make sure the isInit flag is clear
2280 static int btreeGetUnusedPage(
2281 BtShared *pBt, /* The btree */
2282 Pgno pgno, /* Number of the page to fetch */
2283 MemPage **ppPage, /* Return the page in this parameter */
2284 int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
2286 int rc = btreeGetPage(pBt, pgno, ppPage, flags);
2287 if( rc==SQLITE_OK ){
2288 if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
2289 releasePage(*ppPage);
2290 *ppPage = 0;
2291 return SQLITE_CORRUPT_BKPT;
2293 (*ppPage)->isInit = 0;
2294 }else{
2295 *ppPage = 0;
2297 return rc;
2302 ** During a rollback, when the pager reloads information into the cache
2303 ** so that the cache is restored to its original state at the start of
2304 ** the transaction, for each page restored this routine is called.
2306 ** This routine needs to reset the extra data section at the end of the
2307 ** page to agree with the restored data.
2309 static void pageReinit(DbPage *pData){
2310 MemPage *pPage;
2311 pPage = (MemPage *)sqlite3PagerGetExtra(pData);
2312 assert( sqlite3PagerPageRefcount(pData)>0 );
2313 if( pPage->isInit ){
2314 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
2315 pPage->isInit = 0;
2316 if( sqlite3PagerPageRefcount(pData)>1 ){
2317 /* pPage might not be a btree page; it might be an overflow page
2318 ** or ptrmap page or a free page. In those cases, the following
2319 ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
2320 ** But no harm is done by this. And it is very important that
2321 ** btreeInitPage() be called on every btree page so we make
2322 ** the call for every page that comes in for re-initing. */
2323 btreeInitPage(pPage);
2329 ** Invoke the busy handler for a btree.
2331 static int btreeInvokeBusyHandler(void *pArg){
2332 BtShared *pBt = (BtShared*)pArg;
2333 assert( pBt->db );
2334 assert( sqlite3_mutex_held(pBt->db->mutex) );
2335 return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
2339 ** Open a database file.
2341 ** zFilename is the name of the database file. If zFilename is NULL
2342 ** then an ephemeral database is created. The ephemeral database might
2343 ** be exclusively in memory, or it might use a disk-based memory cache.
2344 ** Either way, the ephemeral database will be automatically deleted
2345 ** when sqlite3BtreeClose() is called.
2347 ** If zFilename is ":memory:" then an in-memory database is created
2348 ** that is automatically destroyed when it is closed.
2350 ** The "flags" parameter is a bitmask that might contain bits like
2351 ** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY.
2353 ** If the database is already opened in the same database connection
2354 ** and we are in shared cache mode, then the open will fail with an
2355 ** SQLITE_CONSTRAINT error. We cannot allow two or more BtShared
2356 ** objects in the same database connection since doing so will lead
2357 ** to problems with locking.
2359 int sqlite3BtreeOpen(
2360 sqlite3_vfs *pVfs, /* VFS to use for this b-tree */
2361 const char *zFilename, /* Name of the file containing the BTree database */
2362 sqlite3 *db, /* Associated database handle */
2363 Btree **ppBtree, /* Pointer to new Btree object written here */
2364 int flags, /* Options */
2365 int vfsFlags /* Flags passed through to sqlite3_vfs.xOpen() */
2367 BtShared *pBt = 0; /* Shared part of btree structure */
2368 Btree *p; /* Handle to return */
2369 sqlite3_mutex *mutexOpen = 0; /* Prevents a race condition. Ticket #3537 */
2370 int rc = SQLITE_OK; /* Result code from this function */
2371 u8 nReserve; /* Byte of unused space on each page */
2372 unsigned char zDbHeader[100]; /* Database header content */
2374 /* True if opening an ephemeral, temporary database */
2375 const int isTempDb = zFilename==0 || zFilename[0]==0;
2377 /* Set the variable isMemdb to true for an in-memory database, or
2378 ** false for a file-based database.
2380 #ifdef SQLITE_OMIT_MEMORYDB
2381 const int isMemdb = 0;
2382 #else
2383 const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
2384 || (isTempDb && sqlite3TempInMemory(db))
2385 || (vfsFlags & SQLITE_OPEN_MEMORY)!=0;
2386 #endif
2388 assert( db!=0 );
2389 assert( pVfs!=0 );
2390 assert( sqlite3_mutex_held(db->mutex) );
2391 assert( (flags&0xff)==flags ); /* flags fit in 8 bits */
2393 /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
2394 assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
2396 /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
2397 assert( (flags & BTREE_SINGLE)==0 || isTempDb );
2399 if( isMemdb ){
2400 flags |= BTREE_MEMORY;
2402 if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
2403 vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
2405 p = sqlite3MallocZero(sizeof(Btree));
2406 if( !p ){
2407 return SQLITE_NOMEM_BKPT;
2409 p->inTrans = TRANS_NONE;
2410 p->db = db;
2411 #ifndef SQLITE_OMIT_SHARED_CACHE
2412 p->lock.pBtree = p;
2413 p->lock.iTable = 1;
2414 #endif
2416 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
2418 ** If this Btree is a candidate for shared cache, try to find an
2419 ** existing BtShared object that we can share with
2421 if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){
2422 if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
2423 int nFilename = sqlite3Strlen30(zFilename)+1;
2424 int nFullPathname = pVfs->mxPathname+1;
2425 char *zFullPathname = sqlite3Malloc(MAX(nFullPathname,nFilename));
2426 MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
2428 p->sharable = 1;
2429 if( !zFullPathname ){
2430 sqlite3_free(p);
2431 return SQLITE_NOMEM_BKPT;
2433 if( isMemdb ){
2434 memcpy(zFullPathname, zFilename, nFilename);
2435 }else{
2436 rc = sqlite3OsFullPathname(pVfs, zFilename,
2437 nFullPathname, zFullPathname);
2438 if( rc ){
2439 if( rc==SQLITE_OK_SYMLINK ){
2440 rc = SQLITE_OK;
2441 }else{
2442 sqlite3_free(zFullPathname);
2443 sqlite3_free(p);
2444 return rc;
2448 #if SQLITE_THREADSAFE
2449 mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
2450 sqlite3_mutex_enter(mutexOpen);
2451 mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN);
2452 sqlite3_mutex_enter(mutexShared);
2453 #endif
2454 for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
2455 assert( pBt->nRef>0 );
2456 if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0))
2457 && sqlite3PagerVfs(pBt->pPager)==pVfs ){
2458 int iDb;
2459 for(iDb=db->nDb-1; iDb>=0; iDb--){
2460 Btree *pExisting = db->aDb[iDb].pBt;
2461 if( pExisting && pExisting->pBt==pBt ){
2462 sqlite3_mutex_leave(mutexShared);
2463 sqlite3_mutex_leave(mutexOpen);
2464 sqlite3_free(zFullPathname);
2465 sqlite3_free(p);
2466 return SQLITE_CONSTRAINT;
2469 p->pBt = pBt;
2470 pBt->nRef++;
2471 break;
2474 sqlite3_mutex_leave(mutexShared);
2475 sqlite3_free(zFullPathname);
2477 #ifdef SQLITE_DEBUG
2478 else{
2479 /* In debug mode, we mark all persistent databases as sharable
2480 ** even when they are not. This exercises the locking code and
2481 ** gives more opportunity for asserts(sqlite3_mutex_held())
2482 ** statements to find locking problems.
2484 p->sharable = 1;
2486 #endif
2488 #endif
2489 if( pBt==0 ){
2491 ** The following asserts make sure that structures used by the btree are
2492 ** the right size. This is to guard against size changes that result
2493 ** when compiling on a different architecture.
2495 assert( sizeof(i64)==8 );
2496 assert( sizeof(u64)==8 );
2497 assert( sizeof(u32)==4 );
2498 assert( sizeof(u16)==2 );
2499 assert( sizeof(Pgno)==4 );
2501 pBt = sqlite3MallocZero( sizeof(*pBt) );
2502 if( pBt==0 ){
2503 rc = SQLITE_NOMEM_BKPT;
2504 goto btree_open_out;
2506 rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
2507 sizeof(MemPage), flags, vfsFlags, pageReinit);
2508 if( rc==SQLITE_OK ){
2509 sqlite3PagerSetMmapLimit(pBt->pPager, db->szMmap);
2510 rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
2512 if( rc!=SQLITE_OK ){
2513 goto btree_open_out;
2515 pBt->openFlags = (u8)flags;
2516 pBt->db = db;
2517 sqlite3PagerSetBusyHandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
2518 p->pBt = pBt;
2520 pBt->pCursor = 0;
2521 pBt->pPage1 = 0;
2522 if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY;
2523 #if defined(SQLITE_SECURE_DELETE)
2524 pBt->btsFlags |= BTS_SECURE_DELETE;
2525 #elif defined(SQLITE_FAST_SECURE_DELETE)
2526 pBt->btsFlags |= BTS_OVERWRITE;
2527 #endif
2528 /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
2529 ** determined by the 2-byte integer located at an offset of 16 bytes from
2530 ** the beginning of the database file. */
2531 pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
2532 if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
2533 || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
2534 pBt->pageSize = 0;
2535 #ifndef SQLITE_OMIT_AUTOVACUUM
2536 /* If the magic name ":memory:" will create an in-memory database, then
2537 ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
2538 ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
2539 ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
2540 ** regular file-name. In this case the auto-vacuum applies as per normal.
2542 if( zFilename && !isMemdb ){
2543 pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
2544 pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
2546 #endif
2547 nReserve = 0;
2548 }else{
2549 /* EVIDENCE-OF: R-37497-42412 The size of the reserved region is
2550 ** determined by the one-byte unsigned integer found at an offset of 20
2551 ** into the database file header. */
2552 nReserve = zDbHeader[20];
2553 pBt->btsFlags |= BTS_PAGESIZE_FIXED;
2554 #ifndef SQLITE_OMIT_AUTOVACUUM
2555 pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
2556 pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
2557 #endif
2559 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
2560 if( rc ) goto btree_open_out;
2561 pBt->usableSize = pBt->pageSize - nReserve;
2562 assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */
2564 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
2565 /* Add the new BtShared object to the linked list sharable BtShareds.
2567 pBt->nRef = 1;
2568 if( p->sharable ){
2569 MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
2570 MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN);)
2571 if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
2572 pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
2573 if( pBt->mutex==0 ){
2574 rc = SQLITE_NOMEM_BKPT;
2575 goto btree_open_out;
2578 sqlite3_mutex_enter(mutexShared);
2579 pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
2580 GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
2581 sqlite3_mutex_leave(mutexShared);
2583 #endif
2586 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
2587 /* If the new Btree uses a sharable pBtShared, then link the new
2588 ** Btree into the list of all sharable Btrees for the same connection.
2589 ** The list is kept in ascending order by pBt address.
2591 if( p->sharable ){
2592 int i;
2593 Btree *pSib;
2594 for(i=0; i<db->nDb; i++){
2595 if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
2596 while( pSib->pPrev ){ pSib = pSib->pPrev; }
2597 if( (uptr)p->pBt<(uptr)pSib->pBt ){
2598 p->pNext = pSib;
2599 p->pPrev = 0;
2600 pSib->pPrev = p;
2601 }else{
2602 while( pSib->pNext && (uptr)pSib->pNext->pBt<(uptr)p->pBt ){
2603 pSib = pSib->pNext;
2605 p->pNext = pSib->pNext;
2606 p->pPrev = pSib;
2607 if( p->pNext ){
2608 p->pNext->pPrev = p;
2610 pSib->pNext = p;
2612 break;
2616 #endif
2617 *ppBtree = p;
2619 btree_open_out:
2620 if( rc!=SQLITE_OK ){
2621 if( pBt && pBt->pPager ){
2622 sqlite3PagerClose(pBt->pPager, 0);
2624 sqlite3_free(pBt);
2625 sqlite3_free(p);
2626 *ppBtree = 0;
2627 }else{
2628 sqlite3_file *pFile;
2630 /* If the B-Tree was successfully opened, set the pager-cache size to the
2631 ** default value. Except, when opening on an existing shared pager-cache,
2632 ** do not change the pager-cache size.
2634 if( sqlite3BtreeSchema(p, 0, 0)==0 ){
2635 sqlite3BtreeSetCacheSize(p, SQLITE_DEFAULT_CACHE_SIZE);
2638 pFile = sqlite3PagerFile(pBt->pPager);
2639 if( pFile->pMethods ){
2640 sqlite3OsFileControlHint(pFile, SQLITE_FCNTL_PDB, (void*)&pBt->db);
2643 if( mutexOpen ){
2644 assert( sqlite3_mutex_held(mutexOpen) );
2645 sqlite3_mutex_leave(mutexOpen);
2647 assert( rc!=SQLITE_OK || sqlite3BtreeConnectionCount(*ppBtree)>0 );
2648 return rc;
2652 ** Decrement the BtShared.nRef counter. When it reaches zero,
2653 ** remove the BtShared structure from the sharing list. Return
2654 ** true if the BtShared.nRef counter reaches zero and return
2655 ** false if it is still positive.
2657 static int removeFromSharingList(BtShared *pBt){
2658 #ifndef SQLITE_OMIT_SHARED_CACHE
2659 MUTEX_LOGIC( sqlite3_mutex *pMainMtx; )
2660 BtShared *pList;
2661 int removed = 0;
2663 assert( sqlite3_mutex_notheld(pBt->mutex) );
2664 MUTEX_LOGIC( pMainMtx = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN); )
2665 sqlite3_mutex_enter(pMainMtx);
2666 pBt->nRef--;
2667 if( pBt->nRef<=0 ){
2668 if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
2669 GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
2670 }else{
2671 pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
2672 while( ALWAYS(pList) && pList->pNext!=pBt ){
2673 pList=pList->pNext;
2675 if( ALWAYS(pList) ){
2676 pList->pNext = pBt->pNext;
2679 if( SQLITE_THREADSAFE ){
2680 sqlite3_mutex_free(pBt->mutex);
2682 removed = 1;
2684 sqlite3_mutex_leave(pMainMtx);
2685 return removed;
2686 #else
2687 return 1;
2688 #endif
2692 ** Make sure pBt->pTmpSpace points to an allocation of
2693 ** MX_CELL_SIZE(pBt) bytes with a 4-byte prefix for a left-child
2694 ** pointer.
2696 static void allocateTempSpace(BtShared *pBt){
2697 if( !pBt->pTmpSpace ){
2698 pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
2700 /* One of the uses of pBt->pTmpSpace is to format cells before
2701 ** inserting them into a leaf page (function fillInCell()). If
2702 ** a cell is less than 4 bytes in size, it is rounded up to 4 bytes
2703 ** by the various routines that manipulate binary cells. Which
2704 ** can mean that fillInCell() only initializes the first 2 or 3
2705 ** bytes of pTmpSpace, but that the first 4 bytes are copied from
2706 ** it into a database page. This is not actually a problem, but it
2707 ** does cause a valgrind error when the 1 or 2 bytes of unitialized
2708 ** data is passed to system call write(). So to avoid this error,
2709 ** zero the first 4 bytes of temp space here.
2711 ** Also: Provide four bytes of initialized space before the
2712 ** beginning of pTmpSpace as an area available to prepend the
2713 ** left-child pointer to the beginning of a cell.
2715 if( pBt->pTmpSpace ){
2716 memset(pBt->pTmpSpace, 0, 8);
2717 pBt->pTmpSpace += 4;
2723 ** Free the pBt->pTmpSpace allocation
2725 static void freeTempSpace(BtShared *pBt){
2726 if( pBt->pTmpSpace ){
2727 pBt->pTmpSpace -= 4;
2728 sqlite3PageFree(pBt->pTmpSpace);
2729 pBt->pTmpSpace = 0;
2734 ** Close an open database and invalidate all cursors.
2736 int sqlite3BtreeClose(Btree *p){
2737 BtShared *pBt = p->pBt;
2739 /* Close all cursors opened via this handle. */
2740 assert( sqlite3_mutex_held(p->db->mutex) );
2741 sqlite3BtreeEnter(p);
2743 /* Verify that no other cursors have this Btree open */
2744 #ifdef SQLITE_DEBUG
2746 BtCursor *pCur = pBt->pCursor;
2747 while( pCur ){
2748 BtCursor *pTmp = pCur;
2749 pCur = pCur->pNext;
2750 assert( pTmp->pBtree!=p );
2754 #endif
2756 /* Rollback any active transaction and free the handle structure.
2757 ** The call to sqlite3BtreeRollback() drops any table-locks held by
2758 ** this handle.
2760 sqlite3BtreeRollback(p, SQLITE_OK, 0);
2761 sqlite3BtreeLeave(p);
2763 /* If there are still other outstanding references to the shared-btree
2764 ** structure, return now. The remainder of this procedure cleans
2765 ** up the shared-btree.
2767 assert( p->wantToLock==0 && p->locked==0 );
2768 if( !p->sharable || removeFromSharingList(pBt) ){
2769 /* The pBt is no longer on the sharing list, so we can access
2770 ** it without having to hold the mutex.
2772 ** Clean out and delete the BtShared object.
2774 assert( !pBt->pCursor );
2775 sqlite3PagerClose(pBt->pPager, p->db);
2776 if( pBt->xFreeSchema && pBt->pSchema ){
2777 pBt->xFreeSchema(pBt->pSchema);
2779 sqlite3DbFree(0, pBt->pSchema);
2780 freeTempSpace(pBt);
2781 sqlite3_free(pBt);
2784 #ifndef SQLITE_OMIT_SHARED_CACHE
2785 assert( p->wantToLock==0 );
2786 assert( p->locked==0 );
2787 if( p->pPrev ) p->pPrev->pNext = p->pNext;
2788 if( p->pNext ) p->pNext->pPrev = p->pPrev;
2789 #endif
2791 sqlite3_free(p);
2792 return SQLITE_OK;
2796 ** Change the "soft" limit on the number of pages in the cache.
2797 ** Unused and unmodified pages will be recycled when the number of
2798 ** pages in the cache exceeds this soft limit. But the size of the
2799 ** cache is allowed to grow larger than this limit if it contains
2800 ** dirty pages or pages still in active use.
2802 int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
2803 BtShared *pBt = p->pBt;
2804 assert( sqlite3_mutex_held(p->db->mutex) );
2805 sqlite3BtreeEnter(p);
2806 sqlite3PagerSetCachesize(pBt->pPager, mxPage);
2807 sqlite3BtreeLeave(p);
2808 return SQLITE_OK;
2812 ** Change the "spill" limit on the number of pages in the cache.
2813 ** If the number of pages exceeds this limit during a write transaction,
2814 ** the pager might attempt to "spill" pages to the journal early in
2815 ** order to free up memory.
2817 ** The value returned is the current spill size. If zero is passed
2818 ** as an argument, no changes are made to the spill size setting, so
2819 ** using mxPage of 0 is a way to query the current spill size.
2821 int sqlite3BtreeSetSpillSize(Btree *p, int mxPage){
2822 BtShared *pBt = p->pBt;
2823 int res;
2824 assert( sqlite3_mutex_held(p->db->mutex) );
2825 sqlite3BtreeEnter(p);
2826 res = sqlite3PagerSetSpillsize(pBt->pPager, mxPage);
2827 sqlite3BtreeLeave(p);
2828 return res;
2831 #if SQLITE_MAX_MMAP_SIZE>0
2833 ** Change the limit on the amount of the database file that may be
2834 ** memory mapped.
2836 int sqlite3BtreeSetMmapLimit(Btree *p, sqlite3_int64 szMmap){
2837 BtShared *pBt = p->pBt;
2838 assert( sqlite3_mutex_held(p->db->mutex) );
2839 sqlite3BtreeEnter(p);
2840 sqlite3PagerSetMmapLimit(pBt->pPager, szMmap);
2841 sqlite3BtreeLeave(p);
2842 return SQLITE_OK;
2844 #endif /* SQLITE_MAX_MMAP_SIZE>0 */
2847 ** Change the way data is synced to disk in order to increase or decrease
2848 ** how well the database resists damage due to OS crashes and power
2849 ** failures. Level 1 is the same as asynchronous (no syncs() occur and
2850 ** there is a high probability of damage) Level 2 is the default. There
2851 ** is a very low but non-zero probability of damage. Level 3 reduces the
2852 ** probability of damage to near zero but with a write performance reduction.
2854 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
2855 int sqlite3BtreeSetPagerFlags(
2856 Btree *p, /* The btree to set the safety level on */
2857 unsigned pgFlags /* Various PAGER_* flags */
2859 BtShared *pBt = p->pBt;
2860 assert( sqlite3_mutex_held(p->db->mutex) );
2861 sqlite3BtreeEnter(p);
2862 sqlite3PagerSetFlags(pBt->pPager, pgFlags);
2863 sqlite3BtreeLeave(p);
2864 return SQLITE_OK;
2866 #endif
2869 ** Change the default pages size and the number of reserved bytes per page.
2870 ** Or, if the page size has already been fixed, return SQLITE_READONLY
2871 ** without changing anything.
2873 ** The page size must be a power of 2 between 512 and 65536. If the page
2874 ** size supplied does not meet this constraint then the page size is not
2875 ** changed.
2877 ** Page sizes are constrained to be a power of two so that the region
2878 ** of the database file used for locking (beginning at PENDING_BYTE,
2879 ** the first byte past the 1GB boundary, 0x40000000) needs to occur
2880 ** at the beginning of a page.
2882 ** If parameter nReserve is less than zero, then the number of reserved
2883 ** bytes per page is left unchanged.
2885 ** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size
2886 ** and autovacuum mode can no longer be changed.
2888 int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
2889 int rc = SQLITE_OK;
2890 int x;
2891 BtShared *pBt = p->pBt;
2892 assert( nReserve>=0 && nReserve<=255 );
2893 sqlite3BtreeEnter(p);
2894 pBt->nReserveWanted = nReserve;
2895 x = pBt->pageSize - pBt->usableSize;
2896 if( nReserve<x ) nReserve = x;
2897 if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){
2898 sqlite3BtreeLeave(p);
2899 return SQLITE_READONLY;
2901 assert( nReserve>=0 && nReserve<=255 );
2902 if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
2903 ((pageSize-1)&pageSize)==0 ){
2904 assert( (pageSize & 7)==0 );
2905 assert( !pBt->pCursor );
2906 if( nReserve>32 && pageSize==512 ) pageSize = 1024;
2907 pBt->pageSize = (u32)pageSize;
2908 freeTempSpace(pBt);
2910 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
2911 pBt->usableSize = pBt->pageSize - (u16)nReserve;
2912 if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED;
2913 sqlite3BtreeLeave(p);
2914 return rc;
2918 ** Return the currently defined page size
2920 int sqlite3BtreeGetPageSize(Btree *p){
2921 return p->pBt->pageSize;
2925 ** This function is similar to sqlite3BtreeGetReserve(), except that it
2926 ** may only be called if it is guaranteed that the b-tree mutex is already
2927 ** held.
2929 ** This is useful in one special case in the backup API code where it is
2930 ** known that the shared b-tree mutex is held, but the mutex on the
2931 ** database handle that owns *p is not. In this case if sqlite3BtreeEnter()
2932 ** were to be called, it might collide with some other operation on the
2933 ** database handle that owns *p, causing undefined behavior.
2935 int sqlite3BtreeGetReserveNoMutex(Btree *p){
2936 int n;
2937 assert( sqlite3_mutex_held(p->pBt->mutex) );
2938 n = p->pBt->pageSize - p->pBt->usableSize;
2939 return n;
2943 ** Return the number of bytes of space at the end of every page that
2944 ** are intentually left unused. This is the "reserved" space that is
2945 ** sometimes used by extensions.
2947 ** The value returned is the larger of the current reserve size and
2948 ** the latest reserve size requested by SQLITE_FILECTRL_RESERVE_BYTES.
2949 ** The amount of reserve can only grow - never shrink.
2951 int sqlite3BtreeGetRequestedReserve(Btree *p){
2952 int n1, n2;
2953 sqlite3BtreeEnter(p);
2954 n1 = (int)p->pBt->nReserveWanted;
2955 n2 = sqlite3BtreeGetReserveNoMutex(p);
2956 sqlite3BtreeLeave(p);
2957 return n1>n2 ? n1 : n2;
2962 ** Set the maximum page count for a database if mxPage is positive.
2963 ** No changes are made if mxPage is 0 or negative.
2964 ** Regardless of the value of mxPage, return the maximum page count.
2966 Pgno sqlite3BtreeMaxPageCount(Btree *p, Pgno mxPage){
2967 Pgno n;
2968 sqlite3BtreeEnter(p);
2969 n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
2970 sqlite3BtreeLeave(p);
2971 return n;
2975 ** Change the values for the BTS_SECURE_DELETE and BTS_OVERWRITE flags:
2977 ** newFlag==0 Both BTS_SECURE_DELETE and BTS_OVERWRITE are cleared
2978 ** newFlag==1 BTS_SECURE_DELETE set and BTS_OVERWRITE is cleared
2979 ** newFlag==2 BTS_SECURE_DELETE cleared and BTS_OVERWRITE is set
2980 ** newFlag==(-1) No changes
2982 ** This routine acts as a query if newFlag is less than zero
2984 ** With BTS_OVERWRITE set, deleted content is overwritten by zeros, but
2985 ** freelist leaf pages are not written back to the database. Thus in-page
2986 ** deleted content is cleared, but freelist deleted content is not.
2988 ** With BTS_SECURE_DELETE, operation is like BTS_OVERWRITE with the addition
2989 ** that freelist leaf pages are written back into the database, increasing
2990 ** the amount of disk I/O.
2992 int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
2993 int b;
2994 if( p==0 ) return 0;
2995 sqlite3BtreeEnter(p);
2996 assert( BTS_OVERWRITE==BTS_SECURE_DELETE*2 );
2997 assert( BTS_FAST_SECURE==(BTS_OVERWRITE|BTS_SECURE_DELETE) );
2998 if( newFlag>=0 ){
2999 p->pBt->btsFlags &= ~BTS_FAST_SECURE;
3000 p->pBt->btsFlags |= BTS_SECURE_DELETE*newFlag;
3002 b = (p->pBt->btsFlags & BTS_FAST_SECURE)/BTS_SECURE_DELETE;
3003 sqlite3BtreeLeave(p);
3004 return b;
3008 ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
3009 ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
3010 ** is disabled. The default value for the auto-vacuum property is
3011 ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
3013 int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
3014 #ifdef SQLITE_OMIT_AUTOVACUUM
3015 return SQLITE_READONLY;
3016 #else
3017 BtShared *pBt = p->pBt;
3018 int rc = SQLITE_OK;
3019 u8 av = (u8)autoVacuum;
3021 sqlite3BtreeEnter(p);
3022 if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){
3023 rc = SQLITE_READONLY;
3024 }else{
3025 pBt->autoVacuum = av ?1:0;
3026 pBt->incrVacuum = av==2 ?1:0;
3028 sqlite3BtreeLeave(p);
3029 return rc;
3030 #endif
3034 ** Return the value of the 'auto-vacuum' property. If auto-vacuum is
3035 ** enabled 1 is returned. Otherwise 0.
3037 int sqlite3BtreeGetAutoVacuum(Btree *p){
3038 #ifdef SQLITE_OMIT_AUTOVACUUM
3039 return BTREE_AUTOVACUUM_NONE;
3040 #else
3041 int rc;
3042 sqlite3BtreeEnter(p);
3043 rc = (
3044 (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
3045 (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
3046 BTREE_AUTOVACUUM_INCR
3048 sqlite3BtreeLeave(p);
3049 return rc;
3050 #endif
3054 ** If the user has not set the safety-level for this database connection
3055 ** using "PRAGMA synchronous", and if the safety-level is not already
3056 ** set to the value passed to this function as the second parameter,
3057 ** set it so.
3059 #if SQLITE_DEFAULT_SYNCHRONOUS!=SQLITE_DEFAULT_WAL_SYNCHRONOUS \
3060 && !defined(SQLITE_OMIT_WAL)
3061 static void setDefaultSyncFlag(BtShared *pBt, u8 safety_level){
3062 sqlite3 *db;
3063 Db *pDb;
3064 if( (db=pBt->db)!=0 && (pDb=db->aDb)!=0 ){
3065 while( pDb->pBt==0 || pDb->pBt->pBt!=pBt ){ pDb++; }
3066 if( pDb->bSyncSet==0
3067 && pDb->safety_level!=safety_level
3068 && pDb!=&db->aDb[1]
3070 pDb->safety_level = safety_level;
3071 sqlite3PagerSetFlags(pBt->pPager,
3072 pDb->safety_level | (db->flags & PAGER_FLAGS_MASK));
3076 #else
3077 # define setDefaultSyncFlag(pBt,safety_level)
3078 #endif
3080 /* Forward declaration */
3081 static int newDatabase(BtShared*);
3085 ** Get a reference to pPage1 of the database file. This will
3086 ** also acquire a readlock on that file.
3088 ** SQLITE_OK is returned on success. If the file is not a
3089 ** well-formed database file, then SQLITE_CORRUPT is returned.
3090 ** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
3091 ** is returned if we run out of memory.
3093 static int lockBtree(BtShared *pBt){
3094 int rc; /* Result code from subfunctions */
3095 MemPage *pPage1; /* Page 1 of the database file */
3096 u32 nPage; /* Number of pages in the database */
3097 u32 nPageFile = 0; /* Number of pages in the database file */
3099 assert( sqlite3_mutex_held(pBt->mutex) );
3100 assert( pBt->pPage1==0 );
3101 rc = sqlite3PagerSharedLock(pBt->pPager);
3102 if( rc!=SQLITE_OK ) return rc;
3103 rc = btreeGetPage(pBt, 1, &pPage1, 0);
3104 if( rc!=SQLITE_OK ) return rc;
3106 /* Do some checking to help insure the file we opened really is
3107 ** a valid database file.
3109 nPage = get4byte(28+(u8*)pPage1->aData);
3110 sqlite3PagerPagecount(pBt->pPager, (int*)&nPageFile);
3111 if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
3112 nPage = nPageFile;
3114 if( (pBt->db->flags & SQLITE_ResetDatabase)!=0 ){
3115 nPage = 0;
3117 if( nPage>0 ){
3118 u32 pageSize;
3119 u32 usableSize;
3120 u8 *page1 = pPage1->aData;
3121 rc = SQLITE_NOTADB;
3122 /* EVIDENCE-OF: R-43737-39999 Every valid SQLite database file begins
3123 ** with the following 16 bytes (in hex): 53 51 4c 69 74 65 20 66 6f 72 6d
3124 ** 61 74 20 33 00. */
3125 if( memcmp(page1, zMagicHeader, 16)!=0 ){
3126 goto page1_init_failed;
3129 #ifdef SQLITE_OMIT_WAL
3130 if( page1[18]>1 ){
3131 pBt->btsFlags |= BTS_READ_ONLY;
3133 if( page1[19]>1 ){
3134 goto page1_init_failed;
3136 #else
3137 if( page1[18]>2 ){
3138 pBt->btsFlags |= BTS_READ_ONLY;
3140 if( page1[19]>2 ){
3141 goto page1_init_failed;
3144 /* If the read version is set to 2, this database should be accessed
3145 ** in WAL mode. If the log is not already open, open it now. Then
3146 ** return SQLITE_OK and return without populating BtShared.pPage1.
3147 ** The caller detects this and calls this function again. This is
3148 ** required as the version of page 1 currently in the page1 buffer
3149 ** may not be the latest version - there may be a newer one in the log
3150 ** file.
3152 if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
3153 int isOpen = 0;
3154 rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
3155 if( rc!=SQLITE_OK ){
3156 goto page1_init_failed;
3157 }else{
3158 setDefaultSyncFlag(pBt, SQLITE_DEFAULT_WAL_SYNCHRONOUS+1);
3159 if( isOpen==0 ){
3160 releasePageOne(pPage1);
3161 return SQLITE_OK;
3164 rc = SQLITE_NOTADB;
3165 }else{
3166 setDefaultSyncFlag(pBt, SQLITE_DEFAULT_SYNCHRONOUS+1);
3168 #endif
3170 /* EVIDENCE-OF: R-15465-20813 The maximum and minimum embedded payload
3171 ** fractions and the leaf payload fraction values must be 64, 32, and 32.
3173 ** The original design allowed these amounts to vary, but as of
3174 ** version 3.6.0, we require them to be fixed.
3176 if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
3177 goto page1_init_failed;
3179 /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
3180 ** determined by the 2-byte integer located at an offset of 16 bytes from
3181 ** the beginning of the database file. */
3182 pageSize = (page1[16]<<8) | (page1[17]<<16);
3183 /* EVIDENCE-OF: R-25008-21688 The size of a page is a power of two
3184 ** between 512 and 65536 inclusive. */
3185 if( ((pageSize-1)&pageSize)!=0
3186 || pageSize>SQLITE_MAX_PAGE_SIZE
3187 || pageSize<=256
3189 goto page1_init_failed;
3191 pBt->btsFlags |= BTS_PAGESIZE_FIXED;
3192 assert( (pageSize & 7)==0 );
3193 /* EVIDENCE-OF: R-59310-51205 The "reserved space" size in the 1-byte
3194 ** integer at offset 20 is the number of bytes of space at the end of
3195 ** each page to reserve for extensions.
3197 ** EVIDENCE-OF: R-37497-42412 The size of the reserved region is
3198 ** determined by the one-byte unsigned integer found at an offset of 20
3199 ** into the database file header. */
3200 usableSize = pageSize - page1[20];
3201 if( (u32)pageSize!=pBt->pageSize ){
3202 /* After reading the first page of the database assuming a page size
3203 ** of BtShared.pageSize, we have discovered that the page-size is
3204 ** actually pageSize. Unlock the database, leave pBt->pPage1 at
3205 ** zero and return SQLITE_OK. The caller will call this function
3206 ** again with the correct page-size.
3208 releasePageOne(pPage1);
3209 pBt->usableSize = usableSize;
3210 pBt->pageSize = pageSize;
3211 freeTempSpace(pBt);
3212 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
3213 pageSize-usableSize);
3214 return rc;
3216 if( sqlite3WritableSchema(pBt->db)==0 && nPage>nPageFile ){
3217 rc = SQLITE_CORRUPT_BKPT;
3218 goto page1_init_failed;
3220 /* EVIDENCE-OF: R-28312-64704 However, the usable size is not allowed to
3221 ** be less than 480. In other words, if the page size is 512, then the
3222 ** reserved space size cannot exceed 32. */
3223 if( usableSize<480 ){
3224 goto page1_init_failed;
3226 pBt->pageSize = pageSize;
3227 pBt->usableSize = usableSize;
3228 #ifndef SQLITE_OMIT_AUTOVACUUM
3229 pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
3230 pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
3231 #endif
3234 /* maxLocal is the maximum amount of payload to store locally for
3235 ** a cell. Make sure it is small enough so that at least minFanout
3236 ** cells can will fit on one page. We assume a 10-byte page header.
3237 ** Besides the payload, the cell must store:
3238 ** 2-byte pointer to the cell
3239 ** 4-byte child pointer
3240 ** 9-byte nKey value
3241 ** 4-byte nData value
3242 ** 4-byte overflow page pointer
3243 ** So a cell consists of a 2-byte pointer, a header which is as much as
3244 ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
3245 ** page pointer.
3247 pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
3248 pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
3249 pBt->maxLeaf = (u16)(pBt->usableSize - 35);
3250 pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
3251 if( pBt->maxLocal>127 ){
3252 pBt->max1bytePayload = 127;
3253 }else{
3254 pBt->max1bytePayload = (u8)pBt->maxLocal;
3256 assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
3257 pBt->pPage1 = pPage1;
3258 pBt->nPage = nPage;
3259 return SQLITE_OK;
3261 page1_init_failed:
3262 releasePageOne(pPage1);
3263 pBt->pPage1 = 0;
3264 return rc;
3267 #ifndef NDEBUG
3269 ** Return the number of cursors open on pBt. This is for use
3270 ** in assert() expressions, so it is only compiled if NDEBUG is not
3271 ** defined.
3273 ** Only write cursors are counted if wrOnly is true. If wrOnly is
3274 ** false then all cursors are counted.
3276 ** For the purposes of this routine, a cursor is any cursor that
3277 ** is capable of reading or writing to the database. Cursors that
3278 ** have been tripped into the CURSOR_FAULT state are not counted.
3280 static int countValidCursors(BtShared *pBt, int wrOnly){
3281 BtCursor *pCur;
3282 int r = 0;
3283 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
3284 if( (wrOnly==0 || (pCur->curFlags & BTCF_WriteFlag)!=0)
3285 && pCur->eState!=CURSOR_FAULT ) r++;
3287 return r;
3289 #endif
3292 ** If there are no outstanding cursors and we are not in the middle
3293 ** of a transaction but there is a read lock on the database, then
3294 ** this routine unrefs the first page of the database file which
3295 ** has the effect of releasing the read lock.
3297 ** If there is a transaction in progress, this routine is a no-op.
3299 static void unlockBtreeIfUnused(BtShared *pBt){
3300 assert( sqlite3_mutex_held(pBt->mutex) );
3301 assert( countValidCursors(pBt,0)==0 || pBt->inTransaction>TRANS_NONE );
3302 if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
3303 MemPage *pPage1 = pBt->pPage1;
3304 assert( pPage1->aData );
3305 assert( sqlite3PagerRefcount(pBt->pPager)==1 );
3306 pBt->pPage1 = 0;
3307 releasePageOne(pPage1);
3312 ** If pBt points to an empty file then convert that empty file
3313 ** into a new empty database by initializing the first page of
3314 ** the database.
3316 static int newDatabase(BtShared *pBt){
3317 MemPage *pP1;
3318 unsigned char *data;
3319 int rc;
3321 assert( sqlite3_mutex_held(pBt->mutex) );
3322 if( pBt->nPage>0 ){
3323 return SQLITE_OK;
3325 pP1 = pBt->pPage1;
3326 assert( pP1!=0 );
3327 data = pP1->aData;
3328 rc = sqlite3PagerWrite(pP1->pDbPage);
3329 if( rc ) return rc;
3330 memcpy(data, zMagicHeader, sizeof(zMagicHeader));
3331 assert( sizeof(zMagicHeader)==16 );
3332 data[16] = (u8)((pBt->pageSize>>8)&0xff);
3333 data[17] = (u8)((pBt->pageSize>>16)&0xff);
3334 data[18] = 1;
3335 data[19] = 1;
3336 assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
3337 data[20] = (u8)(pBt->pageSize - pBt->usableSize);
3338 data[21] = 64;
3339 data[22] = 32;
3340 data[23] = 32;
3341 memset(&data[24], 0, 100-24);
3342 zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
3343 pBt->btsFlags |= BTS_PAGESIZE_FIXED;
3344 #ifndef SQLITE_OMIT_AUTOVACUUM
3345 assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
3346 assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
3347 put4byte(&data[36 + 4*4], pBt->autoVacuum);
3348 put4byte(&data[36 + 7*4], pBt->incrVacuum);
3349 #endif
3350 pBt->nPage = 1;
3351 data[31] = 1;
3352 return SQLITE_OK;
3356 ** Initialize the first page of the database file (creating a database
3357 ** consisting of a single page and no schema objects). Return SQLITE_OK
3358 ** if successful, or an SQLite error code otherwise.
3360 int sqlite3BtreeNewDb(Btree *p){
3361 int rc;
3362 sqlite3BtreeEnter(p);
3363 p->pBt->nPage = 0;
3364 rc = newDatabase(p->pBt);
3365 sqlite3BtreeLeave(p);
3366 return rc;
3370 ** Attempt to start a new transaction. A write-transaction
3371 ** is started if the second argument is nonzero, otherwise a read-
3372 ** transaction. If the second argument is 2 or more and exclusive
3373 ** transaction is started, meaning that no other process is allowed
3374 ** to access the database. A preexisting transaction may not be
3375 ** upgraded to exclusive by calling this routine a second time - the
3376 ** exclusivity flag only works for a new transaction.
3378 ** A write-transaction must be started before attempting any
3379 ** changes to the database. None of the following routines
3380 ** will work unless a transaction is started first:
3382 ** sqlite3BtreeCreateTable()
3383 ** sqlite3BtreeCreateIndex()
3384 ** sqlite3BtreeClearTable()
3385 ** sqlite3BtreeDropTable()
3386 ** sqlite3BtreeInsert()
3387 ** sqlite3BtreeDelete()
3388 ** sqlite3BtreeUpdateMeta()
3390 ** If an initial attempt to acquire the lock fails because of lock contention
3391 ** and the database was previously unlocked, then invoke the busy handler
3392 ** if there is one. But if there was previously a read-lock, do not
3393 ** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is
3394 ** returned when there is already a read-lock in order to avoid a deadlock.
3396 ** Suppose there are two processes A and B. A has a read lock and B has
3397 ** a reserved lock. B tries to promote to exclusive but is blocked because
3398 ** of A's read lock. A tries to promote to reserved but is blocked by B.
3399 ** One or the other of the two processes must give way or there can be
3400 ** no progress. By returning SQLITE_BUSY and not invoking the busy callback
3401 ** when A already has a read lock, we encourage A to give up and let B
3402 ** proceed.
3404 int sqlite3BtreeBeginTrans(Btree *p, int wrflag, int *pSchemaVersion){
3405 BtShared *pBt = p->pBt;
3406 Pager *pPager = pBt->pPager;
3407 int rc = SQLITE_OK;
3409 sqlite3BtreeEnter(p);
3410 btreeIntegrity(p);
3412 /* If the btree is already in a write-transaction, or it
3413 ** is already in a read-transaction and a read-transaction
3414 ** is requested, this is a no-op.
3416 if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
3417 goto trans_begun;
3419 assert( pBt->inTransaction==TRANS_WRITE || IfNotOmitAV(pBt->bDoTruncate)==0 );
3421 if( (p->db->flags & SQLITE_ResetDatabase)
3422 && sqlite3PagerIsreadonly(pPager)==0
3424 pBt->btsFlags &= ~BTS_READ_ONLY;
3427 /* Write transactions are not possible on a read-only database */
3428 if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){
3429 rc = SQLITE_READONLY;
3430 goto trans_begun;
3433 #ifndef SQLITE_OMIT_SHARED_CACHE
3435 sqlite3 *pBlock = 0;
3436 /* If another database handle has already opened a write transaction
3437 ** on this shared-btree structure and a second write transaction is
3438 ** requested, return SQLITE_LOCKED.
3440 if( (wrflag && pBt->inTransaction==TRANS_WRITE)
3441 || (pBt->btsFlags & BTS_PENDING)!=0
3443 pBlock = pBt->pWriter->db;
3444 }else if( wrflag>1 ){
3445 BtLock *pIter;
3446 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
3447 if( pIter->pBtree!=p ){
3448 pBlock = pIter->pBtree->db;
3449 break;
3453 if( pBlock ){
3454 sqlite3ConnectionBlocked(p->db, pBlock);
3455 rc = SQLITE_LOCKED_SHAREDCACHE;
3456 goto trans_begun;
3459 #endif
3461 /* Any read-only or read-write transaction implies a read-lock on
3462 ** page 1. So if some other shared-cache client already has a write-lock
3463 ** on page 1, the transaction cannot be opened. */
3464 rc = querySharedCacheTableLock(p, SCHEMA_ROOT, READ_LOCK);
3465 if( SQLITE_OK!=rc ) goto trans_begun;
3467 pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;
3468 if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;
3469 do {
3470 sqlite3PagerWalDb(pPager, p->db);
3472 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
3473 /* If transitioning from no transaction directly to a write transaction,
3474 ** block for the WRITER lock first if possible. */
3475 if( pBt->pPage1==0 && wrflag ){
3476 assert( pBt->inTransaction==TRANS_NONE );
3477 rc = sqlite3PagerWalWriteLock(pPager, 1);
3478 if( rc!=SQLITE_BUSY && rc!=SQLITE_OK ) break;
3480 #endif
3482 /* Call lockBtree() until either pBt->pPage1 is populated or
3483 ** lockBtree() returns something other than SQLITE_OK. lockBtree()
3484 ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
3485 ** reading page 1 it discovers that the page-size of the database
3486 ** file is not pBt->pageSize. In this case lockBtree() will update
3487 ** pBt->pageSize to the page-size of the file on disk.
3489 while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
3491 if( rc==SQLITE_OK && wrflag ){
3492 if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){
3493 rc = SQLITE_READONLY;
3494 }else{
3495 rc = sqlite3PagerBegin(pPager, wrflag>1, sqlite3TempInMemory(p->db));
3496 if( rc==SQLITE_OK ){
3497 rc = newDatabase(pBt);
3498 }else if( rc==SQLITE_BUSY_SNAPSHOT && pBt->inTransaction==TRANS_NONE ){
3499 /* if there was no transaction opened when this function was
3500 ** called and SQLITE_BUSY_SNAPSHOT is returned, change the error
3501 ** code to SQLITE_BUSY. */
3502 rc = SQLITE_BUSY;
3507 if( rc!=SQLITE_OK ){
3508 (void)sqlite3PagerWalWriteLock(pPager, 0);
3509 unlockBtreeIfUnused(pBt);
3511 }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
3512 btreeInvokeBusyHandler(pBt) );
3513 sqlite3PagerWalDb(pPager, 0);
3514 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
3515 if( rc==SQLITE_BUSY_TIMEOUT ) rc = SQLITE_BUSY;
3516 #endif
3518 if( rc==SQLITE_OK ){
3519 if( p->inTrans==TRANS_NONE ){
3520 pBt->nTransaction++;
3521 #ifndef SQLITE_OMIT_SHARED_CACHE
3522 if( p->sharable ){
3523 assert( p->lock.pBtree==p && p->lock.iTable==1 );
3524 p->lock.eLock = READ_LOCK;
3525 p->lock.pNext = pBt->pLock;
3526 pBt->pLock = &p->lock;
3528 #endif
3530 p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
3531 if( p->inTrans>pBt->inTransaction ){
3532 pBt->inTransaction = p->inTrans;
3534 if( wrflag ){
3535 MemPage *pPage1 = pBt->pPage1;
3536 #ifndef SQLITE_OMIT_SHARED_CACHE
3537 assert( !pBt->pWriter );
3538 pBt->pWriter = p;
3539 pBt->btsFlags &= ~BTS_EXCLUSIVE;
3540 if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;
3541 #endif
3543 /* If the db-size header field is incorrect (as it may be if an old
3544 ** client has been writing the database file), update it now. Doing
3545 ** this sooner rather than later means the database size can safely
3546 ** re-read the database size from page 1 if a savepoint or transaction
3547 ** rollback occurs within the transaction.
3549 if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
3550 rc = sqlite3PagerWrite(pPage1->pDbPage);
3551 if( rc==SQLITE_OK ){
3552 put4byte(&pPage1->aData[28], pBt->nPage);
3558 trans_begun:
3559 if( rc==SQLITE_OK ){
3560 if( pSchemaVersion ){
3561 *pSchemaVersion = get4byte(&pBt->pPage1->aData[40]);
3563 if( wrflag ){
3564 /* This call makes sure that the pager has the correct number of
3565 ** open savepoints. If the second parameter is greater than 0 and
3566 ** the sub-journal is not already open, then it will be opened here.
3568 rc = sqlite3PagerOpenSavepoint(pPager, p->db->nSavepoint);
3572 btreeIntegrity(p);
3573 sqlite3BtreeLeave(p);
3574 return rc;
3577 #ifndef SQLITE_OMIT_AUTOVACUUM
3580 ** Set the pointer-map entries for all children of page pPage. Also, if
3581 ** pPage contains cells that point to overflow pages, set the pointer
3582 ** map entries for the overflow pages as well.
3584 static int setChildPtrmaps(MemPage *pPage){
3585 int i; /* Counter variable */
3586 int nCell; /* Number of cells in page pPage */
3587 int rc; /* Return code */
3588 BtShared *pBt = pPage->pBt;
3589 Pgno pgno = pPage->pgno;
3591 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
3592 rc = pPage->isInit ? SQLITE_OK : btreeInitPage(pPage);
3593 if( rc!=SQLITE_OK ) return rc;
3594 nCell = pPage->nCell;
3596 for(i=0; i<nCell; i++){
3597 u8 *pCell = findCell(pPage, i);
3599 ptrmapPutOvflPtr(pPage, pPage, pCell, &rc);
3601 if( !pPage->leaf ){
3602 Pgno childPgno = get4byte(pCell);
3603 ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
3607 if( !pPage->leaf ){
3608 Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
3609 ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
3612 return rc;
3616 ** Somewhere on pPage is a pointer to page iFrom. Modify this pointer so
3617 ** that it points to iTo. Parameter eType describes the type of pointer to
3618 ** be modified, as follows:
3620 ** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child
3621 ** page of pPage.
3623 ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
3624 ** page pointed to by one of the cells on pPage.
3626 ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
3627 ** overflow page in the list.
3629 static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
3630 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
3631 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
3632 if( eType==PTRMAP_OVERFLOW2 ){
3633 /* The pointer is always the first 4 bytes of the page in this case. */
3634 if( get4byte(pPage->aData)!=iFrom ){
3635 return SQLITE_CORRUPT_PAGE(pPage);
3637 put4byte(pPage->aData, iTo);
3638 }else{
3639 int i;
3640 int nCell;
3641 int rc;
3643 rc = pPage->isInit ? SQLITE_OK : btreeInitPage(pPage);
3644 if( rc ) return rc;
3645 nCell = pPage->nCell;
3647 for(i=0; i<nCell; i++){
3648 u8 *pCell = findCell(pPage, i);
3649 if( eType==PTRMAP_OVERFLOW1 ){
3650 CellInfo info;
3651 pPage->xParseCell(pPage, pCell, &info);
3652 if( info.nLocal<info.nPayload ){
3653 if( pCell+info.nSize > pPage->aData+pPage->pBt->usableSize ){
3654 return SQLITE_CORRUPT_PAGE(pPage);
3656 if( iFrom==get4byte(pCell+info.nSize-4) ){
3657 put4byte(pCell+info.nSize-4, iTo);
3658 break;
3661 }else{
3662 if( get4byte(pCell)==iFrom ){
3663 put4byte(pCell, iTo);
3664 break;
3669 if( i==nCell ){
3670 if( eType!=PTRMAP_BTREE ||
3671 get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
3672 return SQLITE_CORRUPT_PAGE(pPage);
3674 put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
3677 return SQLITE_OK;
3682 ** Move the open database page pDbPage to location iFreePage in the
3683 ** database. The pDbPage reference remains valid.
3685 ** The isCommit flag indicates that there is no need to remember that
3686 ** the journal needs to be sync()ed before database page pDbPage->pgno
3687 ** can be written to. The caller has already promised not to write to that
3688 ** page.
3690 static int relocatePage(
3691 BtShared *pBt, /* Btree */
3692 MemPage *pDbPage, /* Open page to move */
3693 u8 eType, /* Pointer map 'type' entry for pDbPage */
3694 Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */
3695 Pgno iFreePage, /* The location to move pDbPage to */
3696 int isCommit /* isCommit flag passed to sqlite3PagerMovepage */
3698 MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */
3699 Pgno iDbPage = pDbPage->pgno;
3700 Pager *pPager = pBt->pPager;
3701 int rc;
3703 assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
3704 eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
3705 assert( sqlite3_mutex_held(pBt->mutex) );
3706 assert( pDbPage->pBt==pBt );
3707 if( iDbPage<3 ) return SQLITE_CORRUPT_BKPT;
3709 /* Move page iDbPage from its current location to page number iFreePage */
3710 TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
3711 iDbPage, iFreePage, iPtrPage, eType));
3712 rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
3713 if( rc!=SQLITE_OK ){
3714 return rc;
3716 pDbPage->pgno = iFreePage;
3718 /* If pDbPage was a btree-page, then it may have child pages and/or cells
3719 ** that point to overflow pages. The pointer map entries for all these
3720 ** pages need to be changed.
3722 ** If pDbPage is an overflow page, then the first 4 bytes may store a
3723 ** pointer to a subsequent overflow page. If this is the case, then
3724 ** the pointer map needs to be updated for the subsequent overflow page.
3726 if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
3727 rc = setChildPtrmaps(pDbPage);
3728 if( rc!=SQLITE_OK ){
3729 return rc;
3731 }else{
3732 Pgno nextOvfl = get4byte(pDbPage->aData);
3733 if( nextOvfl!=0 ){
3734 ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
3735 if( rc!=SQLITE_OK ){
3736 return rc;
3741 /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
3742 ** that it points at iFreePage. Also fix the pointer map entry for
3743 ** iPtrPage.
3745 if( eType!=PTRMAP_ROOTPAGE ){
3746 rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
3747 if( rc!=SQLITE_OK ){
3748 return rc;
3750 rc = sqlite3PagerWrite(pPtrPage->pDbPage);
3751 if( rc!=SQLITE_OK ){
3752 releasePage(pPtrPage);
3753 return rc;
3755 rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
3756 releasePage(pPtrPage);
3757 if( rc==SQLITE_OK ){
3758 ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
3761 return rc;
3764 /* Forward declaration required by incrVacuumStep(). */
3765 static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
3768 ** Perform a single step of an incremental-vacuum. If successful, return
3769 ** SQLITE_OK. If there is no work to do (and therefore no point in
3770 ** calling this function again), return SQLITE_DONE. Or, if an error
3771 ** occurs, return some other error code.
3773 ** More specifically, this function attempts to re-organize the database so
3774 ** that the last page of the file currently in use is no longer in use.
3776 ** Parameter nFin is the number of pages that this database would contain
3777 ** were this function called until it returns SQLITE_DONE.
3779 ** If the bCommit parameter is non-zero, this function assumes that the
3780 ** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE
3781 ** or an error. bCommit is passed true for an auto-vacuum-on-commit
3782 ** operation, or false for an incremental vacuum.
3784 static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){
3785 Pgno nFreeList; /* Number of pages still on the free-list */
3786 int rc;
3788 assert( sqlite3_mutex_held(pBt->mutex) );
3789 assert( iLastPg>nFin );
3791 if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
3792 u8 eType;
3793 Pgno iPtrPage;
3795 nFreeList = get4byte(&pBt->pPage1->aData[36]);
3796 if( nFreeList==0 ){
3797 return SQLITE_DONE;
3800 rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
3801 if( rc!=SQLITE_OK ){
3802 return rc;
3804 if( eType==PTRMAP_ROOTPAGE ){
3805 return SQLITE_CORRUPT_BKPT;
3808 if( eType==PTRMAP_FREEPAGE ){
3809 if( bCommit==0 ){
3810 /* Remove the page from the files free-list. This is not required
3811 ** if bCommit is non-zero. In that case, the free-list will be
3812 ** truncated to zero after this function returns, so it doesn't
3813 ** matter if it still contains some garbage entries.
3815 Pgno iFreePg;
3816 MemPage *pFreePg;
3817 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, BTALLOC_EXACT);
3818 if( rc!=SQLITE_OK ){
3819 return rc;
3821 assert( iFreePg==iLastPg );
3822 releasePage(pFreePg);
3824 } else {
3825 Pgno iFreePg; /* Index of free page to move pLastPg to */
3826 MemPage *pLastPg;
3827 u8 eMode = BTALLOC_ANY; /* Mode parameter for allocateBtreePage() */
3828 Pgno iNear = 0; /* nearby parameter for allocateBtreePage() */
3830 rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
3831 if( rc!=SQLITE_OK ){
3832 return rc;
3835 /* If bCommit is zero, this loop runs exactly once and page pLastPg
3836 ** is swapped with the first free page pulled off the free list.
3838 ** On the other hand, if bCommit is greater than zero, then keep
3839 ** looping until a free-page located within the first nFin pages
3840 ** of the file is found.
3842 if( bCommit==0 ){
3843 eMode = BTALLOC_LE;
3844 iNear = nFin;
3846 do {
3847 MemPage *pFreePg;
3848 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iNear, eMode);
3849 if( rc!=SQLITE_OK ){
3850 releasePage(pLastPg);
3851 return rc;
3853 releasePage(pFreePg);
3854 }while( bCommit && iFreePg>nFin );
3855 assert( iFreePg<iLastPg );
3857 rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, bCommit);
3858 releasePage(pLastPg);
3859 if( rc!=SQLITE_OK ){
3860 return rc;
3865 if( bCommit==0 ){
3866 do {
3867 iLastPg--;
3868 }while( iLastPg==PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, iLastPg) );
3869 pBt->bDoTruncate = 1;
3870 pBt->nPage = iLastPg;
3872 return SQLITE_OK;
3876 ** The database opened by the first argument is an auto-vacuum database
3877 ** nOrig pages in size containing nFree free pages. Return the expected
3878 ** size of the database in pages following an auto-vacuum operation.
3880 static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){
3881 int nEntry; /* Number of entries on one ptrmap page */
3882 Pgno nPtrmap; /* Number of PtrMap pages to be freed */
3883 Pgno nFin; /* Return value */
3885 nEntry = pBt->usableSize/5;
3886 nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
3887 nFin = nOrig - nFree - nPtrmap;
3888 if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
3889 nFin--;
3891 while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
3892 nFin--;
3895 return nFin;
3899 ** A write-transaction must be opened before calling this function.
3900 ** It performs a single unit of work towards an incremental vacuum.
3902 ** If the incremental vacuum is finished after this function has run,
3903 ** SQLITE_DONE is returned. If it is not finished, but no error occurred,
3904 ** SQLITE_OK is returned. Otherwise an SQLite error code.
3906 int sqlite3BtreeIncrVacuum(Btree *p){
3907 int rc;
3908 BtShared *pBt = p->pBt;
3910 sqlite3BtreeEnter(p);
3911 assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
3912 if( !pBt->autoVacuum ){
3913 rc = SQLITE_DONE;
3914 }else{
3915 Pgno nOrig = btreePagecount(pBt);
3916 Pgno nFree = get4byte(&pBt->pPage1->aData[36]);
3917 Pgno nFin = finalDbSize(pBt, nOrig, nFree);
3919 if( nOrig<nFin || nFree>=nOrig ){
3920 rc = SQLITE_CORRUPT_BKPT;
3921 }else if( nFree>0 ){
3922 rc = saveAllCursors(pBt, 0, 0);
3923 if( rc==SQLITE_OK ){
3924 invalidateAllOverflowCache(pBt);
3925 rc = incrVacuumStep(pBt, nFin, nOrig, 0);
3927 if( rc==SQLITE_OK ){
3928 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
3929 put4byte(&pBt->pPage1->aData[28], pBt->nPage);
3931 }else{
3932 rc = SQLITE_DONE;
3935 sqlite3BtreeLeave(p);
3936 return rc;
3940 ** This routine is called prior to sqlite3PagerCommit when a transaction
3941 ** is committed for an auto-vacuum database.
3943 static int autoVacuumCommit(Btree *p){
3944 int rc = SQLITE_OK;
3945 Pager *pPager;
3946 BtShared *pBt;
3947 sqlite3 *db;
3948 VVA_ONLY( int nRef );
3950 assert( p!=0 );
3951 pBt = p->pBt;
3952 pPager = pBt->pPager;
3953 VVA_ONLY( nRef = sqlite3PagerRefcount(pPager); )
3955 assert( sqlite3_mutex_held(pBt->mutex) );
3956 invalidateAllOverflowCache(pBt);
3957 assert(pBt->autoVacuum);
3958 if( !pBt->incrVacuum ){
3959 Pgno nFin; /* Number of pages in database after autovacuuming */
3960 Pgno nFree; /* Number of pages on the freelist initially */
3961 Pgno nVac; /* Number of pages to vacuum */
3962 Pgno iFree; /* The next page to be freed */
3963 Pgno nOrig; /* Database size before freeing */
3965 nOrig = btreePagecount(pBt);
3966 if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
3967 /* It is not possible to create a database for which the final page
3968 ** is either a pointer-map page or the pending-byte page. If one
3969 ** is encountered, this indicates corruption.
3971 return SQLITE_CORRUPT_BKPT;
3974 nFree = get4byte(&pBt->pPage1->aData[36]);
3975 db = p->db;
3976 if( db->xAutovacPages ){
3977 int iDb;
3978 for(iDb=0; ALWAYS(iDb<db->nDb); iDb++){
3979 if( db->aDb[iDb].pBt==p ) break;
3981 nVac = db->xAutovacPages(
3982 db->pAutovacPagesArg,
3983 db->aDb[iDb].zDbSName,
3984 nOrig,
3985 nFree,
3986 pBt->pageSize
3988 if( nVac>nFree ){
3989 nVac = nFree;
3991 if( nVac==0 ){
3992 return SQLITE_OK;
3994 }else{
3995 nVac = nFree;
3997 nFin = finalDbSize(pBt, nOrig, nVac);
3998 if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
3999 if( nFin<nOrig ){
4000 rc = saveAllCursors(pBt, 0, 0);
4002 for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
4003 rc = incrVacuumStep(pBt, nFin, iFree, nVac==nFree);
4005 if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
4006 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
4007 if( nVac==nFree ){
4008 put4byte(&pBt->pPage1->aData[32], 0);
4009 put4byte(&pBt->pPage1->aData[36], 0);
4011 put4byte(&pBt->pPage1->aData[28], nFin);
4012 pBt->bDoTruncate = 1;
4013 pBt->nPage = nFin;
4015 if( rc!=SQLITE_OK ){
4016 sqlite3PagerRollback(pPager);
4020 assert( nRef>=sqlite3PagerRefcount(pPager) );
4021 return rc;
4024 #else /* ifndef SQLITE_OMIT_AUTOVACUUM */
4025 # define setChildPtrmaps(x) SQLITE_OK
4026 #endif
4029 ** This routine does the first phase of a two-phase commit. This routine
4030 ** causes a rollback journal to be created (if it does not already exist)
4031 ** and populated with enough information so that if a power loss occurs
4032 ** the database can be restored to its original state by playing back
4033 ** the journal. Then the contents of the journal are flushed out to
4034 ** the disk. After the journal is safely on oxide, the changes to the
4035 ** database are written into the database file and flushed to oxide.
4036 ** At the end of this call, the rollback journal still exists on the
4037 ** disk and we are still holding all locks, so the transaction has not
4038 ** committed. See sqlite3BtreeCommitPhaseTwo() for the second phase of the
4039 ** commit process.
4041 ** This call is a no-op if no write-transaction is currently active on pBt.
4043 ** Otherwise, sync the database file for the btree pBt. zSuperJrnl points to
4044 ** the name of a super-journal file that should be written into the
4045 ** individual journal file, or is NULL, indicating no super-journal file
4046 ** (single database transaction).
4048 ** When this is called, the super-journal should already have been
4049 ** created, populated with this journal pointer and synced to disk.
4051 ** Once this is routine has returned, the only thing required to commit
4052 ** the write-transaction for this database file is to delete the journal.
4054 int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zSuperJrnl){
4055 int rc = SQLITE_OK;
4056 if( p->inTrans==TRANS_WRITE ){
4057 BtShared *pBt = p->pBt;
4058 sqlite3BtreeEnter(p);
4059 #ifndef SQLITE_OMIT_AUTOVACUUM
4060 if( pBt->autoVacuum ){
4061 rc = autoVacuumCommit(p);
4062 if( rc!=SQLITE_OK ){
4063 sqlite3BtreeLeave(p);
4064 return rc;
4067 if( pBt->bDoTruncate ){
4068 sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage);
4070 #endif
4071 rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zSuperJrnl, 0);
4072 sqlite3BtreeLeave(p);
4074 return rc;
4078 ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
4079 ** at the conclusion of a transaction.
4081 static void btreeEndTransaction(Btree *p){
4082 BtShared *pBt = p->pBt;
4083 sqlite3 *db = p->db;
4084 assert( sqlite3BtreeHoldsMutex(p) );
4086 #ifndef SQLITE_OMIT_AUTOVACUUM
4087 pBt->bDoTruncate = 0;
4088 #endif
4089 if( p->inTrans>TRANS_NONE && db->nVdbeRead>1 ){
4090 /* If there are other active statements that belong to this database
4091 ** handle, downgrade to a read-only transaction. The other statements
4092 ** may still be reading from the database. */
4093 downgradeAllSharedCacheTableLocks(p);
4094 p->inTrans = TRANS_READ;
4095 }else{
4096 /* If the handle had any kind of transaction open, decrement the
4097 ** transaction count of the shared btree. If the transaction count
4098 ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
4099 ** call below will unlock the pager. */
4100 if( p->inTrans!=TRANS_NONE ){
4101 clearAllSharedCacheTableLocks(p);
4102 pBt->nTransaction--;
4103 if( 0==pBt->nTransaction ){
4104 pBt->inTransaction = TRANS_NONE;
4108 /* Set the current transaction state to TRANS_NONE and unlock the
4109 ** pager if this call closed the only read or write transaction. */
4110 p->inTrans = TRANS_NONE;
4111 unlockBtreeIfUnused(pBt);
4114 btreeIntegrity(p);
4118 ** Commit the transaction currently in progress.
4120 ** This routine implements the second phase of a 2-phase commit. The
4121 ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
4122 ** be invoked prior to calling this routine. The sqlite3BtreeCommitPhaseOne()
4123 ** routine did all the work of writing information out to disk and flushing the
4124 ** contents so that they are written onto the disk platter. All this
4125 ** routine has to do is delete or truncate or zero the header in the
4126 ** the rollback journal (which causes the transaction to commit) and
4127 ** drop locks.
4129 ** Normally, if an error occurs while the pager layer is attempting to
4130 ** finalize the underlying journal file, this function returns an error and
4131 ** the upper layer will attempt a rollback. However, if the second argument
4132 ** is non-zero then this b-tree transaction is part of a multi-file
4133 ** transaction. In this case, the transaction has already been committed
4134 ** (by deleting a super-journal file) and the caller will ignore this
4135 ** functions return code. So, even if an error occurs in the pager layer,
4136 ** reset the b-tree objects internal state to indicate that the write
4137 ** transaction has been closed. This is quite safe, as the pager will have
4138 ** transitioned to the error state.
4140 ** This will release the write lock on the database file. If there
4141 ** are no active cursors, it also releases the read lock.
4143 int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
4145 if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
4146 sqlite3BtreeEnter(p);
4147 btreeIntegrity(p);
4149 /* If the handle has a write-transaction open, commit the shared-btrees
4150 ** transaction and set the shared state to TRANS_READ.
4152 if( p->inTrans==TRANS_WRITE ){
4153 int rc;
4154 BtShared *pBt = p->pBt;
4155 assert( pBt->inTransaction==TRANS_WRITE );
4156 assert( pBt->nTransaction>0 );
4157 rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
4158 if( rc!=SQLITE_OK && bCleanup==0 ){
4159 sqlite3BtreeLeave(p);
4160 return rc;
4162 p->iBDataVersion--; /* Compensate for pPager->iDataVersion++; */
4163 pBt->inTransaction = TRANS_READ;
4164 btreeClearHasContent(pBt);
4167 btreeEndTransaction(p);
4168 sqlite3BtreeLeave(p);
4169 return SQLITE_OK;
4173 ** Do both phases of a commit.
4175 int sqlite3BtreeCommit(Btree *p){
4176 int rc;
4177 sqlite3BtreeEnter(p);
4178 rc = sqlite3BtreeCommitPhaseOne(p, 0);
4179 if( rc==SQLITE_OK ){
4180 rc = sqlite3BtreeCommitPhaseTwo(p, 0);
4182 sqlite3BtreeLeave(p);
4183 return rc;
4187 ** This routine sets the state to CURSOR_FAULT and the error
4188 ** code to errCode for every cursor on any BtShared that pBtree
4189 ** references. Or if the writeOnly flag is set to 1, then only
4190 ** trip write cursors and leave read cursors unchanged.
4192 ** Every cursor is a candidate to be tripped, including cursors
4193 ** that belong to other database connections that happen to be
4194 ** sharing the cache with pBtree.
4196 ** This routine gets called when a rollback occurs. If the writeOnly
4197 ** flag is true, then only write-cursors need be tripped - read-only
4198 ** cursors save their current positions so that they may continue
4199 ** following the rollback. Or, if writeOnly is false, all cursors are
4200 ** tripped. In general, writeOnly is false if the transaction being
4201 ** rolled back modified the database schema. In this case b-tree root
4202 ** pages may be moved or deleted from the database altogether, making
4203 ** it unsafe for read cursors to continue.
4205 ** If the writeOnly flag is true and an error is encountered while
4206 ** saving the current position of a read-only cursor, all cursors,
4207 ** including all read-cursors are tripped.
4209 ** SQLITE_OK is returned if successful, or if an error occurs while
4210 ** saving a cursor position, an SQLite error code.
4212 int sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode, int writeOnly){
4213 BtCursor *p;
4214 int rc = SQLITE_OK;
4216 assert( (writeOnly==0 || writeOnly==1) && BTCF_WriteFlag==1 );
4217 if( pBtree ){
4218 sqlite3BtreeEnter(pBtree);
4219 for(p=pBtree->pBt->pCursor; p; p=p->pNext){
4220 if( writeOnly && (p->curFlags & BTCF_WriteFlag)==0 ){
4221 if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
4222 rc = saveCursorPosition(p);
4223 if( rc!=SQLITE_OK ){
4224 (void)sqlite3BtreeTripAllCursors(pBtree, rc, 0);
4225 break;
4228 }else{
4229 sqlite3BtreeClearCursor(p);
4230 p->eState = CURSOR_FAULT;
4231 p->skipNext = errCode;
4233 btreeReleaseAllCursorPages(p);
4235 sqlite3BtreeLeave(pBtree);
4237 return rc;
4241 ** Set the pBt->nPage field correctly, according to the current
4242 ** state of the database. Assume pBt->pPage1 is valid.
4244 static void btreeSetNPage(BtShared *pBt, MemPage *pPage1){
4245 int nPage = get4byte(&pPage1->aData[28]);
4246 testcase( nPage==0 );
4247 if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
4248 testcase( pBt->nPage!=(u32)nPage );
4249 pBt->nPage = nPage;
4253 ** Rollback the transaction in progress.
4255 ** If tripCode is not SQLITE_OK then cursors will be invalidated (tripped).
4256 ** Only write cursors are tripped if writeOnly is true but all cursors are
4257 ** tripped if writeOnly is false. Any attempt to use
4258 ** a tripped cursor will result in an error.
4260 ** This will release the write lock on the database file. If there
4261 ** are no active cursors, it also releases the read lock.
4263 int sqlite3BtreeRollback(Btree *p, int tripCode, int writeOnly){
4264 int rc;
4265 BtShared *pBt = p->pBt;
4266 MemPage *pPage1;
4268 assert( writeOnly==1 || writeOnly==0 );
4269 assert( tripCode==SQLITE_ABORT_ROLLBACK || tripCode==SQLITE_OK );
4270 sqlite3BtreeEnter(p);
4271 if( tripCode==SQLITE_OK ){
4272 rc = tripCode = saveAllCursors(pBt, 0, 0);
4273 if( rc ) writeOnly = 0;
4274 }else{
4275 rc = SQLITE_OK;
4277 if( tripCode ){
4278 int rc2 = sqlite3BtreeTripAllCursors(p, tripCode, writeOnly);
4279 assert( rc==SQLITE_OK || (writeOnly==0 && rc2==SQLITE_OK) );
4280 if( rc2!=SQLITE_OK ) rc = rc2;
4282 btreeIntegrity(p);
4284 if( p->inTrans==TRANS_WRITE ){
4285 int rc2;
4287 assert( TRANS_WRITE==pBt->inTransaction );
4288 rc2 = sqlite3PagerRollback(pBt->pPager);
4289 if( rc2!=SQLITE_OK ){
4290 rc = rc2;
4293 /* The rollback may have destroyed the pPage1->aData value. So
4294 ** call btreeGetPage() on page 1 again to make
4295 ** sure pPage1->aData is set correctly. */
4296 if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
4297 btreeSetNPage(pBt, pPage1);
4298 releasePageOne(pPage1);
4300 assert( countValidCursors(pBt, 1)==0 );
4301 pBt->inTransaction = TRANS_READ;
4302 btreeClearHasContent(pBt);
4305 btreeEndTransaction(p);
4306 sqlite3BtreeLeave(p);
4307 return rc;
4311 ** Start a statement subtransaction. The subtransaction can be rolled
4312 ** back independently of the main transaction. You must start a transaction
4313 ** before starting a subtransaction. The subtransaction is ended automatically
4314 ** if the main transaction commits or rolls back.
4316 ** Statement subtransactions are used around individual SQL statements
4317 ** that are contained within a BEGIN...COMMIT block. If a constraint
4318 ** error occurs within the statement, the effect of that one statement
4319 ** can be rolled back without having to rollback the entire transaction.
4321 ** A statement sub-transaction is implemented as an anonymous savepoint. The
4322 ** value passed as the second parameter is the total number of savepoints,
4323 ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
4324 ** are no active savepoints and no other statement-transactions open,
4325 ** iStatement is 1. This anonymous savepoint can be released or rolled back
4326 ** using the sqlite3BtreeSavepoint() function.
4328 int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
4329 int rc;
4330 BtShared *pBt = p->pBt;
4331 sqlite3BtreeEnter(p);
4332 assert( p->inTrans==TRANS_WRITE );
4333 assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
4334 assert( iStatement>0 );
4335 assert( iStatement>p->db->nSavepoint );
4336 assert( pBt->inTransaction==TRANS_WRITE );
4337 /* At the pager level, a statement transaction is a savepoint with
4338 ** an index greater than all savepoints created explicitly using
4339 ** SQL statements. It is illegal to open, release or rollback any
4340 ** such savepoints while the statement transaction savepoint is active.
4342 rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
4343 sqlite3BtreeLeave(p);
4344 return rc;
4348 ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
4349 ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
4350 ** savepoint identified by parameter iSavepoint, depending on the value
4351 ** of op.
4353 ** Normally, iSavepoint is greater than or equal to zero. However, if op is
4354 ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
4355 ** contents of the entire transaction are rolled back. This is different
4356 ** from a normal transaction rollback, as no locks are released and the
4357 ** transaction remains open.
4359 int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
4360 int rc = SQLITE_OK;
4361 if( p && p->inTrans==TRANS_WRITE ){
4362 BtShared *pBt = p->pBt;
4363 assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
4364 assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
4365 sqlite3BtreeEnter(p);
4366 if( op==SAVEPOINT_ROLLBACK ){
4367 rc = saveAllCursors(pBt, 0, 0);
4369 if( rc==SQLITE_OK ){
4370 rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
4372 if( rc==SQLITE_OK ){
4373 if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
4374 pBt->nPage = 0;
4376 rc = newDatabase(pBt);
4377 btreeSetNPage(pBt, pBt->pPage1);
4379 /* pBt->nPage might be zero if the database was corrupt when
4380 ** the transaction was started. Otherwise, it must be at least 1. */
4381 assert( CORRUPT_DB || pBt->nPage>0 );
4383 sqlite3BtreeLeave(p);
4385 return rc;
4389 ** Create a new cursor for the BTree whose root is on the page
4390 ** iTable. If a read-only cursor is requested, it is assumed that
4391 ** the caller already has at least a read-only transaction open
4392 ** on the database already. If a write-cursor is requested, then
4393 ** the caller is assumed to have an open write transaction.
4395 ** If the BTREE_WRCSR bit of wrFlag is clear, then the cursor can only
4396 ** be used for reading. If the BTREE_WRCSR bit is set, then the cursor
4397 ** can be used for reading or for writing if other conditions for writing
4398 ** are also met. These are the conditions that must be met in order
4399 ** for writing to be allowed:
4401 ** 1: The cursor must have been opened with wrFlag containing BTREE_WRCSR
4403 ** 2: Other database connections that share the same pager cache
4404 ** but which are not in the READ_UNCOMMITTED state may not have
4405 ** cursors open with wrFlag==0 on the same table. Otherwise
4406 ** the changes made by this write cursor would be visible to
4407 ** the read cursors in the other database connection.
4409 ** 3: The database must be writable (not on read-only media)
4411 ** 4: There must be an active transaction.
4413 ** The BTREE_FORDELETE bit of wrFlag may optionally be set if BTREE_WRCSR
4414 ** is set. If FORDELETE is set, that is a hint to the implementation that
4415 ** this cursor will only be used to seek to and delete entries of an index
4416 ** as part of a larger DELETE statement. The FORDELETE hint is not used by
4417 ** this implementation. But in a hypothetical alternative storage engine
4418 ** in which index entries are automatically deleted when corresponding table
4419 ** rows are deleted, the FORDELETE flag is a hint that all SEEK and DELETE
4420 ** operations on this cursor can be no-ops and all READ operations can
4421 ** return a null row (2-bytes: 0x01 0x00).
4423 ** No checking is done to make sure that page iTable really is the
4424 ** root page of a b-tree. If it is not, then the cursor acquired
4425 ** will not work correctly.
4427 ** It is assumed that the sqlite3BtreeCursorZero() has been called
4428 ** on pCur to initialize the memory space prior to invoking this routine.
4430 static int btreeCursor(
4431 Btree *p, /* The btree */
4432 Pgno iTable, /* Root page of table to open */
4433 int wrFlag, /* 1 to write. 0 read-only */
4434 struct KeyInfo *pKeyInfo, /* First arg to comparison function */
4435 BtCursor *pCur /* Space for new cursor */
4437 BtShared *pBt = p->pBt; /* Shared b-tree handle */
4438 BtCursor *pX; /* Looping over other all cursors */
4440 assert( sqlite3BtreeHoldsMutex(p) );
4441 assert( wrFlag==0
4442 || wrFlag==BTREE_WRCSR
4443 || wrFlag==(BTREE_WRCSR|BTREE_FORDELETE)
4446 /* The following assert statements verify that if this is a sharable
4447 ** b-tree database, the connection is holding the required table locks,
4448 ** and that no other connection has any open cursor that conflicts with
4449 ** this lock. The iTable<1 term disables the check for corrupt schemas. */
4450 assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, (wrFlag?2:1))
4451 || iTable<1 );
4452 assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
4454 /* Assert that the caller has opened the required transaction. */
4455 assert( p->inTrans>TRANS_NONE );
4456 assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
4457 assert( pBt->pPage1 && pBt->pPage1->aData );
4458 assert( wrFlag==0 || (pBt->btsFlags & BTS_READ_ONLY)==0 );
4460 if( wrFlag ){
4461 allocateTempSpace(pBt);
4462 if( pBt->pTmpSpace==0 ) return SQLITE_NOMEM_BKPT;
4464 if( iTable<=1 ){
4465 if( iTable<1 ){
4466 return SQLITE_CORRUPT_BKPT;
4467 }else if( btreePagecount(pBt)==0 ){
4468 assert( wrFlag==0 );
4469 iTable = 0;
4473 /* Now that no other errors can occur, finish filling in the BtCursor
4474 ** variables and link the cursor into the BtShared list. */
4475 pCur->pgnoRoot = iTable;
4476 pCur->iPage = -1;
4477 pCur->pKeyInfo = pKeyInfo;
4478 pCur->pBtree = p;
4479 pCur->pBt = pBt;
4480 pCur->curFlags = wrFlag ? BTCF_WriteFlag : 0;
4481 pCur->curPagerFlags = wrFlag ? 0 : PAGER_GET_READONLY;
4482 /* If there are two or more cursors on the same btree, then all such
4483 ** cursors *must* have the BTCF_Multiple flag set. */
4484 for(pX=pBt->pCursor; pX; pX=pX->pNext){
4485 if( pX->pgnoRoot==iTable ){
4486 pX->curFlags |= BTCF_Multiple;
4487 pCur->curFlags |= BTCF_Multiple;
4490 pCur->pNext = pBt->pCursor;
4491 pBt->pCursor = pCur;
4492 pCur->eState = CURSOR_INVALID;
4493 return SQLITE_OK;
4495 static int btreeCursorWithLock(
4496 Btree *p, /* The btree */
4497 Pgno iTable, /* Root page of table to open */
4498 int wrFlag, /* 1 to write. 0 read-only */
4499 struct KeyInfo *pKeyInfo, /* First arg to comparison function */
4500 BtCursor *pCur /* Space for new cursor */
4502 int rc;
4503 sqlite3BtreeEnter(p);
4504 rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
4505 sqlite3BtreeLeave(p);
4506 return rc;
4508 int sqlite3BtreeCursor(
4509 Btree *p, /* The btree */
4510 Pgno iTable, /* Root page of table to open */
4511 int wrFlag, /* 1 to write. 0 read-only */
4512 struct KeyInfo *pKeyInfo, /* First arg to xCompare() */
4513 BtCursor *pCur /* Write new cursor here */
4515 if( p->sharable ){
4516 return btreeCursorWithLock(p, iTable, wrFlag, pKeyInfo, pCur);
4517 }else{
4518 return btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
4523 ** Return the size of a BtCursor object in bytes.
4525 ** This interfaces is needed so that users of cursors can preallocate
4526 ** sufficient storage to hold a cursor. The BtCursor object is opaque
4527 ** to users so they cannot do the sizeof() themselves - they must call
4528 ** this routine.
4530 int sqlite3BtreeCursorSize(void){
4531 return ROUND8(sizeof(BtCursor));
4535 ** Initialize memory that will be converted into a BtCursor object.
4537 ** The simple approach here would be to memset() the entire object
4538 ** to zero. But it turns out that the apPage[] and aiIdx[] arrays
4539 ** do not need to be zeroed and they are large, so we can save a lot
4540 ** of run-time by skipping the initialization of those elements.
4542 void sqlite3BtreeCursorZero(BtCursor *p){
4543 memset(p, 0, offsetof(BtCursor, BTCURSOR_FIRST_UNINIT));
4547 ** Close a cursor. The read lock on the database file is released
4548 ** when the last cursor is closed.
4550 int sqlite3BtreeCloseCursor(BtCursor *pCur){
4551 Btree *pBtree = pCur->pBtree;
4552 if( pBtree ){
4553 BtShared *pBt = pCur->pBt;
4554 sqlite3BtreeEnter(pBtree);
4555 assert( pBt->pCursor!=0 );
4556 if( pBt->pCursor==pCur ){
4557 pBt->pCursor = pCur->pNext;
4558 }else{
4559 BtCursor *pPrev = pBt->pCursor;
4561 if( pPrev->pNext==pCur ){
4562 pPrev->pNext = pCur->pNext;
4563 break;
4565 pPrev = pPrev->pNext;
4566 }while( ALWAYS(pPrev) );
4568 btreeReleaseAllCursorPages(pCur);
4569 unlockBtreeIfUnused(pBt);
4570 sqlite3_free(pCur->aOverflow);
4571 sqlite3_free(pCur->pKey);
4572 if( (pBt->openFlags & BTREE_SINGLE) && pBt->pCursor==0 ){
4573 /* Since the BtShared is not sharable, there is no need to
4574 ** worry about the missing sqlite3BtreeLeave() call here. */
4575 assert( pBtree->sharable==0 );
4576 sqlite3BtreeClose(pBtree);
4577 }else{
4578 sqlite3BtreeLeave(pBtree);
4580 pCur->pBtree = 0;
4582 return SQLITE_OK;
4586 ** Make sure the BtCursor* given in the argument has a valid
4587 ** BtCursor.info structure. If it is not already valid, call
4588 ** btreeParseCell() to fill it in.
4590 ** BtCursor.info is a cache of the information in the current cell.
4591 ** Using this cache reduces the number of calls to btreeParseCell().
4593 #ifndef NDEBUG
4594 static int cellInfoEqual(CellInfo *a, CellInfo *b){
4595 if( a->nKey!=b->nKey ) return 0;
4596 if( a->pPayload!=b->pPayload ) return 0;
4597 if( a->nPayload!=b->nPayload ) return 0;
4598 if( a->nLocal!=b->nLocal ) return 0;
4599 if( a->nSize!=b->nSize ) return 0;
4600 return 1;
4602 static void assertCellInfo(BtCursor *pCur){
4603 CellInfo info;
4604 memset(&info, 0, sizeof(info));
4605 btreeParseCell(pCur->pPage, pCur->ix, &info);
4606 assert( CORRUPT_DB || cellInfoEqual(&info, &pCur->info) );
4608 #else
4609 #define assertCellInfo(x)
4610 #endif
4611 static SQLITE_NOINLINE void getCellInfo(BtCursor *pCur){
4612 if( pCur->info.nSize==0 ){
4613 pCur->curFlags |= BTCF_ValidNKey;
4614 btreeParseCell(pCur->pPage,pCur->ix,&pCur->info);
4615 }else{
4616 assertCellInfo(pCur);
4620 #ifndef NDEBUG /* The next routine used only within assert() statements */
4622 ** Return true if the given BtCursor is valid. A valid cursor is one
4623 ** that is currently pointing to a row in a (non-empty) table.
4624 ** This is a verification routine is used only within assert() statements.
4626 int sqlite3BtreeCursorIsValid(BtCursor *pCur){
4627 return pCur && pCur->eState==CURSOR_VALID;
4629 #endif /* NDEBUG */
4630 int sqlite3BtreeCursorIsValidNN(BtCursor *pCur){
4631 assert( pCur!=0 );
4632 return pCur->eState==CURSOR_VALID;
4636 ** Return the value of the integer key or "rowid" for a table btree.
4637 ** This routine is only valid for a cursor that is pointing into a
4638 ** ordinary table btree. If the cursor points to an index btree or
4639 ** is invalid, the result of this routine is undefined.
4641 i64 sqlite3BtreeIntegerKey(BtCursor *pCur){
4642 assert( cursorHoldsMutex(pCur) );
4643 assert( pCur->eState==CURSOR_VALID );
4644 assert( pCur->curIntKey );
4645 getCellInfo(pCur);
4646 return pCur->info.nKey;
4650 ** Pin or unpin a cursor.
4652 void sqlite3BtreeCursorPin(BtCursor *pCur){
4653 assert( (pCur->curFlags & BTCF_Pinned)==0 );
4654 pCur->curFlags |= BTCF_Pinned;
4656 void sqlite3BtreeCursorUnpin(BtCursor *pCur){
4657 assert( (pCur->curFlags & BTCF_Pinned)!=0 );
4658 pCur->curFlags &= ~BTCF_Pinned;
4661 #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
4663 ** Return the offset into the database file for the start of the
4664 ** payload to which the cursor is pointing.
4666 i64 sqlite3BtreeOffset(BtCursor *pCur){
4667 assert( cursorHoldsMutex(pCur) );
4668 assert( pCur->eState==CURSOR_VALID );
4669 getCellInfo(pCur);
4670 return (i64)pCur->pBt->pageSize*((i64)pCur->pPage->pgno - 1) +
4671 (i64)(pCur->info.pPayload - pCur->pPage->aData);
4673 #endif /* SQLITE_ENABLE_OFFSET_SQL_FUNC */
4676 ** Return the number of bytes of payload for the entry that pCur is
4677 ** currently pointing to. For table btrees, this will be the amount
4678 ** of data. For index btrees, this will be the size of the key.
4680 ** The caller must guarantee that the cursor is pointing to a non-NULL
4681 ** valid entry. In other words, the calling procedure must guarantee
4682 ** that the cursor has Cursor.eState==CURSOR_VALID.
4684 u32 sqlite3BtreePayloadSize(BtCursor *pCur){
4685 assert( cursorHoldsMutex(pCur) );
4686 assert( pCur->eState==CURSOR_VALID );
4687 getCellInfo(pCur);
4688 return pCur->info.nPayload;
4692 ** Return an upper bound on the size of any record for the table
4693 ** that the cursor is pointing into.
4695 ** This is an optimization. Everything will still work if this
4696 ** routine always returns 2147483647 (which is the largest record
4697 ** that SQLite can handle) or more. But returning a smaller value might
4698 ** prevent large memory allocations when trying to interpret a
4699 ** corrupt datrabase.
4701 ** The current implementation merely returns the size of the underlying
4702 ** database file.
4704 sqlite3_int64 sqlite3BtreeMaxRecordSize(BtCursor *pCur){
4705 assert( cursorHoldsMutex(pCur) );
4706 assert( pCur->eState==CURSOR_VALID );
4707 return pCur->pBt->pageSize * (sqlite3_int64)pCur->pBt->nPage;
4711 ** Given the page number of an overflow page in the database (parameter
4712 ** ovfl), this function finds the page number of the next page in the
4713 ** linked list of overflow pages. If possible, it uses the auto-vacuum
4714 ** pointer-map data instead of reading the content of page ovfl to do so.
4716 ** If an error occurs an SQLite error code is returned. Otherwise:
4718 ** The page number of the next overflow page in the linked list is
4719 ** written to *pPgnoNext. If page ovfl is the last page in its linked
4720 ** list, *pPgnoNext is set to zero.
4722 ** If ppPage is not NULL, and a reference to the MemPage object corresponding
4723 ** to page number pOvfl was obtained, then *ppPage is set to point to that
4724 ** reference. It is the responsibility of the caller to call releasePage()
4725 ** on *ppPage to free the reference. In no reference was obtained (because
4726 ** the pointer-map was used to obtain the value for *pPgnoNext), then
4727 ** *ppPage is set to zero.
4729 static int getOverflowPage(
4730 BtShared *pBt, /* The database file */
4731 Pgno ovfl, /* Current overflow page number */
4732 MemPage **ppPage, /* OUT: MemPage handle (may be NULL) */
4733 Pgno *pPgnoNext /* OUT: Next overflow page number */
4735 Pgno next = 0;
4736 MemPage *pPage = 0;
4737 int rc = SQLITE_OK;
4739 assert( sqlite3_mutex_held(pBt->mutex) );
4740 assert(pPgnoNext);
4742 #ifndef SQLITE_OMIT_AUTOVACUUM
4743 /* Try to find the next page in the overflow list using the
4744 ** autovacuum pointer-map pages. Guess that the next page in
4745 ** the overflow list is page number (ovfl+1). If that guess turns
4746 ** out to be wrong, fall back to loading the data of page
4747 ** number ovfl to determine the next page number.
4749 if( pBt->autoVacuum ){
4750 Pgno pgno;
4751 Pgno iGuess = ovfl+1;
4752 u8 eType;
4754 while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
4755 iGuess++;
4758 if( iGuess<=btreePagecount(pBt) ){
4759 rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
4760 if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
4761 next = iGuess;
4762 rc = SQLITE_DONE;
4766 #endif
4768 assert( next==0 || rc==SQLITE_DONE );
4769 if( rc==SQLITE_OK ){
4770 rc = btreeGetPage(pBt, ovfl, &pPage, (ppPage==0) ? PAGER_GET_READONLY : 0);
4771 assert( rc==SQLITE_OK || pPage==0 );
4772 if( rc==SQLITE_OK ){
4773 next = get4byte(pPage->aData);
4777 *pPgnoNext = next;
4778 if( ppPage ){
4779 *ppPage = pPage;
4780 }else{
4781 releasePage(pPage);
4783 return (rc==SQLITE_DONE ? SQLITE_OK : rc);
4787 ** Copy data from a buffer to a page, or from a page to a buffer.
4789 ** pPayload is a pointer to data stored on database page pDbPage.
4790 ** If argument eOp is false, then nByte bytes of data are copied
4791 ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
4792 ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
4793 ** of data are copied from the buffer pBuf to pPayload.
4795 ** SQLITE_OK is returned on success, otherwise an error code.
4797 static int copyPayload(
4798 void *pPayload, /* Pointer to page data */
4799 void *pBuf, /* Pointer to buffer */
4800 int nByte, /* Number of bytes to copy */
4801 int eOp, /* 0 -> copy from page, 1 -> copy to page */
4802 DbPage *pDbPage /* Page containing pPayload */
4804 if( eOp ){
4805 /* Copy data from buffer to page (a write operation) */
4806 int rc = sqlite3PagerWrite(pDbPage);
4807 if( rc!=SQLITE_OK ){
4808 return rc;
4810 memcpy(pPayload, pBuf, nByte);
4811 }else{
4812 /* Copy data from page to buffer (a read operation) */
4813 memcpy(pBuf, pPayload, nByte);
4815 return SQLITE_OK;
4819 ** This function is used to read or overwrite payload information
4820 ** for the entry that the pCur cursor is pointing to. The eOp
4821 ** argument is interpreted as follows:
4823 ** 0: The operation is a read. Populate the overflow cache.
4824 ** 1: The operation is a write. Populate the overflow cache.
4826 ** A total of "amt" bytes are read or written beginning at "offset".
4827 ** Data is read to or from the buffer pBuf.
4829 ** The content being read or written might appear on the main page
4830 ** or be scattered out on multiple overflow pages.
4832 ** If the current cursor entry uses one or more overflow pages
4833 ** this function may allocate space for and lazily populate
4834 ** the overflow page-list cache array (BtCursor.aOverflow).
4835 ** Subsequent calls use this cache to make seeking to the supplied offset
4836 ** more efficient.
4838 ** Once an overflow page-list cache has been allocated, it must be
4839 ** invalidated if some other cursor writes to the same table, or if
4840 ** the cursor is moved to a different row. Additionally, in auto-vacuum
4841 ** mode, the following events may invalidate an overflow page-list cache.
4843 ** * An incremental vacuum,
4844 ** * A commit in auto_vacuum="full" mode,
4845 ** * Creating a table (may require moving an overflow page).
4847 static int accessPayload(
4848 BtCursor *pCur, /* Cursor pointing to entry to read from */
4849 u32 offset, /* Begin reading this far into payload */
4850 u32 amt, /* Read this many bytes */
4851 unsigned char *pBuf, /* Write the bytes into this buffer */
4852 int eOp /* zero to read. non-zero to write. */
4854 unsigned char *aPayload;
4855 int rc = SQLITE_OK;
4856 int iIdx = 0;
4857 MemPage *pPage = pCur->pPage; /* Btree page of current entry */
4858 BtShared *pBt = pCur->pBt; /* Btree this cursor belongs to */
4859 #ifdef SQLITE_DIRECT_OVERFLOW_READ
4860 unsigned char * const pBufStart = pBuf; /* Start of original out buffer */
4861 #endif
4863 assert( pPage );
4864 assert( eOp==0 || eOp==1 );
4865 assert( pCur->eState==CURSOR_VALID );
4866 if( pCur->ix>=pPage->nCell ){
4867 return SQLITE_CORRUPT_PAGE(pPage);
4869 assert( cursorHoldsMutex(pCur) );
4871 getCellInfo(pCur);
4872 aPayload = pCur->info.pPayload;
4873 assert( offset+amt <= pCur->info.nPayload );
4875 assert( aPayload > pPage->aData );
4876 if( (uptr)(aPayload - pPage->aData) > (pBt->usableSize - pCur->info.nLocal) ){
4877 /* Trying to read or write past the end of the data is an error. The
4878 ** conditional above is really:
4879 ** &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
4880 ** but is recast into its current form to avoid integer overflow problems
4882 return SQLITE_CORRUPT_PAGE(pPage);
4885 /* Check if data must be read/written to/from the btree page itself. */
4886 if( offset<pCur->info.nLocal ){
4887 int a = amt;
4888 if( a+offset>pCur->info.nLocal ){
4889 a = pCur->info.nLocal - offset;
4891 rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
4892 offset = 0;
4893 pBuf += a;
4894 amt -= a;
4895 }else{
4896 offset -= pCur->info.nLocal;
4900 if( rc==SQLITE_OK && amt>0 ){
4901 const u32 ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */
4902 Pgno nextPage;
4904 nextPage = get4byte(&aPayload[pCur->info.nLocal]);
4906 /* If the BtCursor.aOverflow[] has not been allocated, allocate it now.
4908 ** The aOverflow[] array is sized at one entry for each overflow page
4909 ** in the overflow chain. The page number of the first overflow page is
4910 ** stored in aOverflow[0], etc. A value of 0 in the aOverflow[] array
4911 ** means "not yet known" (the cache is lazily populated).
4913 if( (pCur->curFlags & BTCF_ValidOvfl)==0 ){
4914 int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
4915 if( pCur->aOverflow==0
4916 || nOvfl*(int)sizeof(Pgno) > sqlite3MallocSize(pCur->aOverflow)
4918 Pgno *aNew = (Pgno*)sqlite3Realloc(
4919 pCur->aOverflow, nOvfl*2*sizeof(Pgno)
4921 if( aNew==0 ){
4922 return SQLITE_NOMEM_BKPT;
4923 }else{
4924 pCur->aOverflow = aNew;
4927 memset(pCur->aOverflow, 0, nOvfl*sizeof(Pgno));
4928 pCur->curFlags |= BTCF_ValidOvfl;
4929 }else{
4930 /* If the overflow page-list cache has been allocated and the
4931 ** entry for the first required overflow page is valid, skip
4932 ** directly to it.
4934 if( pCur->aOverflow[offset/ovflSize] ){
4935 iIdx = (offset/ovflSize);
4936 nextPage = pCur->aOverflow[iIdx];
4937 offset = (offset%ovflSize);
4941 assert( rc==SQLITE_OK && amt>0 );
4942 while( nextPage ){
4943 /* If required, populate the overflow page-list cache. */
4944 if( nextPage > pBt->nPage ) return SQLITE_CORRUPT_BKPT;
4945 assert( pCur->aOverflow[iIdx]==0
4946 || pCur->aOverflow[iIdx]==nextPage
4947 || CORRUPT_DB );
4948 pCur->aOverflow[iIdx] = nextPage;
4950 if( offset>=ovflSize ){
4951 /* The only reason to read this page is to obtain the page
4952 ** number for the next page in the overflow chain. The page
4953 ** data is not required. So first try to lookup the overflow
4954 ** page-list cache, if any, then fall back to the getOverflowPage()
4955 ** function.
4957 assert( pCur->curFlags & BTCF_ValidOvfl );
4958 assert( pCur->pBtree->db==pBt->db );
4959 if( pCur->aOverflow[iIdx+1] ){
4960 nextPage = pCur->aOverflow[iIdx+1];
4961 }else{
4962 rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
4964 offset -= ovflSize;
4965 }else{
4966 /* Need to read this page properly. It contains some of the
4967 ** range of data that is being read (eOp==0) or written (eOp!=0).
4969 int a = amt;
4970 if( a + offset > ovflSize ){
4971 a = ovflSize - offset;
4974 #ifdef SQLITE_DIRECT_OVERFLOW_READ
4975 /* If all the following are true:
4977 ** 1) this is a read operation, and
4978 ** 2) data is required from the start of this overflow page, and
4979 ** 3) there are no dirty pages in the page-cache
4980 ** 4) the database is file-backed, and
4981 ** 5) the page is not in the WAL file
4982 ** 6) at least 4 bytes have already been read into the output buffer
4984 ** then data can be read directly from the database file into the
4985 ** output buffer, bypassing the page-cache altogether. This speeds
4986 ** up loading large records that span many overflow pages.
4988 if( eOp==0 /* (1) */
4989 && offset==0 /* (2) */
4990 && sqlite3PagerDirectReadOk(pBt->pPager, nextPage) /* (3,4,5) */
4991 && &pBuf[-4]>=pBufStart /* (6) */
4993 sqlite3_file *fd = sqlite3PagerFile(pBt->pPager);
4994 u8 aSave[4];
4995 u8 *aWrite = &pBuf[-4];
4996 assert( aWrite>=pBufStart ); /* due to (6) */
4997 memcpy(aSave, aWrite, 4);
4998 rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
4999 if( rc && nextPage>pBt->nPage ) rc = SQLITE_CORRUPT_BKPT;
5000 nextPage = get4byte(aWrite);
5001 memcpy(aWrite, aSave, 4);
5002 }else
5003 #endif
5006 DbPage *pDbPage;
5007 rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage,
5008 (eOp==0 ? PAGER_GET_READONLY : 0)
5010 if( rc==SQLITE_OK ){
5011 aPayload = sqlite3PagerGetData(pDbPage);
5012 nextPage = get4byte(aPayload);
5013 rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
5014 sqlite3PagerUnref(pDbPage);
5015 offset = 0;
5018 amt -= a;
5019 if( amt==0 ) return rc;
5020 pBuf += a;
5022 if( rc ) break;
5023 iIdx++;
5027 if( rc==SQLITE_OK && amt>0 ){
5028 /* Overflow chain ends prematurely */
5029 return SQLITE_CORRUPT_PAGE(pPage);
5031 return rc;
5035 ** Read part of the payload for the row at which that cursor pCur is currently
5036 ** pointing. "amt" bytes will be transferred into pBuf[]. The transfer
5037 ** begins at "offset".
5039 ** pCur can be pointing to either a table or an index b-tree.
5040 ** If pointing to a table btree, then the content section is read. If
5041 ** pCur is pointing to an index b-tree then the key section is read.
5043 ** For sqlite3BtreePayload(), the caller must ensure that pCur is pointing
5044 ** to a valid row in the table. For sqlite3BtreePayloadChecked(), the
5045 ** cursor might be invalid or might need to be restored before being read.
5047 ** Return SQLITE_OK on success or an error code if anything goes
5048 ** wrong. An error is returned if "offset+amt" is larger than
5049 ** the available payload.
5051 int sqlite3BtreePayload(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
5052 assert( cursorHoldsMutex(pCur) );
5053 assert( pCur->eState==CURSOR_VALID );
5054 assert( pCur->iPage>=0 && pCur->pPage );
5055 return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
5059 ** This variant of sqlite3BtreePayload() works even if the cursor has not
5060 ** in the CURSOR_VALID state. It is only used by the sqlite3_blob_read()
5061 ** interface.
5063 #ifndef SQLITE_OMIT_INCRBLOB
5064 static SQLITE_NOINLINE int accessPayloadChecked(
5065 BtCursor *pCur,
5066 u32 offset,
5067 u32 amt,
5068 void *pBuf
5070 int rc;
5071 if ( pCur->eState==CURSOR_INVALID ){
5072 return SQLITE_ABORT;
5074 assert( cursorOwnsBtShared(pCur) );
5075 rc = btreeRestoreCursorPosition(pCur);
5076 return rc ? rc : accessPayload(pCur, offset, amt, pBuf, 0);
5078 int sqlite3BtreePayloadChecked(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
5079 if( pCur->eState==CURSOR_VALID ){
5080 assert( cursorOwnsBtShared(pCur) );
5081 return accessPayload(pCur, offset, amt, pBuf, 0);
5082 }else{
5083 return accessPayloadChecked(pCur, offset, amt, pBuf);
5086 #endif /* SQLITE_OMIT_INCRBLOB */
5089 ** Return a pointer to payload information from the entry that the
5090 ** pCur cursor is pointing to. The pointer is to the beginning of
5091 ** the key if index btrees (pPage->intKey==0) and is the data for
5092 ** table btrees (pPage->intKey==1). The number of bytes of available
5093 ** key/data is written into *pAmt. If *pAmt==0, then the value
5094 ** returned will not be a valid pointer.
5096 ** This routine is an optimization. It is common for the entire key
5097 ** and data to fit on the local page and for there to be no overflow
5098 ** pages. When that is so, this routine can be used to access the
5099 ** key and data without making a copy. If the key and/or data spills
5100 ** onto overflow pages, then accessPayload() must be used to reassemble
5101 ** the key/data and copy it into a preallocated buffer.
5103 ** The pointer returned by this routine looks directly into the cached
5104 ** page of the database. The data might change or move the next time
5105 ** any btree routine is called.
5107 static const void *fetchPayload(
5108 BtCursor *pCur, /* Cursor pointing to entry to read from */
5109 u32 *pAmt /* Write the number of available bytes here */
5111 int amt;
5112 assert( pCur!=0 && pCur->iPage>=0 && pCur->pPage);
5113 assert( pCur->eState==CURSOR_VALID );
5114 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
5115 assert( cursorOwnsBtShared(pCur) );
5116 assert( pCur->ix<pCur->pPage->nCell || CORRUPT_DB );
5117 assert( pCur->info.nSize>0 );
5118 assert( pCur->info.pPayload>pCur->pPage->aData || CORRUPT_DB );
5119 assert( pCur->info.pPayload<pCur->pPage->aDataEnd ||CORRUPT_DB);
5120 amt = pCur->info.nLocal;
5121 if( amt>(int)(pCur->pPage->aDataEnd - pCur->info.pPayload) ){
5122 /* There is too little space on the page for the expected amount
5123 ** of local content. Database must be corrupt. */
5124 assert( CORRUPT_DB );
5125 amt = MAX(0, (int)(pCur->pPage->aDataEnd - pCur->info.pPayload));
5127 *pAmt = (u32)amt;
5128 return (void*)pCur->info.pPayload;
5133 ** For the entry that cursor pCur is point to, return as
5134 ** many bytes of the key or data as are available on the local
5135 ** b-tree page. Write the number of available bytes into *pAmt.
5137 ** The pointer returned is ephemeral. The key/data may move
5138 ** or be destroyed on the next call to any Btree routine,
5139 ** including calls from other threads against the same cache.
5140 ** Hence, a mutex on the BtShared should be held prior to calling
5141 ** this routine.
5143 ** These routines is used to get quick access to key and data
5144 ** in the common case where no overflow pages are used.
5146 const void *sqlite3BtreePayloadFetch(BtCursor *pCur, u32 *pAmt){
5147 return fetchPayload(pCur, pAmt);
5152 ** Move the cursor down to a new child page. The newPgno argument is the
5153 ** page number of the child page to move to.
5155 ** This function returns SQLITE_CORRUPT if the page-header flags field of
5156 ** the new child page does not match the flags field of the parent (i.e.
5157 ** if an intkey page appears to be the parent of a non-intkey page, or
5158 ** vice-versa).
5160 static int moveToChild(BtCursor *pCur, u32 newPgno){
5161 BtShared *pBt = pCur->pBt;
5163 assert( cursorOwnsBtShared(pCur) );
5164 assert( pCur->eState==CURSOR_VALID );
5165 assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
5166 assert( pCur->iPage>=0 );
5167 if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
5168 return SQLITE_CORRUPT_BKPT;
5170 pCur->info.nSize = 0;
5171 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
5172 pCur->aiIdx[pCur->iPage] = pCur->ix;
5173 pCur->apPage[pCur->iPage] = pCur->pPage;
5174 pCur->ix = 0;
5175 pCur->iPage++;
5176 return getAndInitPage(pBt, newPgno, &pCur->pPage, pCur, pCur->curPagerFlags);
5179 #ifdef SQLITE_DEBUG
5181 ** Page pParent is an internal (non-leaf) tree page. This function
5182 ** asserts that page number iChild is the left-child if the iIdx'th
5183 ** cell in page pParent. Or, if iIdx is equal to the total number of
5184 ** cells in pParent, that page number iChild is the right-child of
5185 ** the page.
5187 static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
5188 if( CORRUPT_DB ) return; /* The conditions tested below might not be true
5189 ** in a corrupt database */
5190 assert( iIdx<=pParent->nCell );
5191 if( iIdx==pParent->nCell ){
5192 assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
5193 }else{
5194 assert( get4byte(findCell(pParent, iIdx))==iChild );
5197 #else
5198 # define assertParentIndex(x,y,z)
5199 #endif
5202 ** Move the cursor up to the parent page.
5204 ** pCur->idx is set to the cell index that contains the pointer
5205 ** to the page we are coming from. If we are coming from the
5206 ** right-most child page then pCur->idx is set to one more than
5207 ** the largest cell index.
5209 static void moveToParent(BtCursor *pCur){
5210 MemPage *pLeaf;
5211 assert( cursorOwnsBtShared(pCur) );
5212 assert( pCur->eState==CURSOR_VALID );
5213 assert( pCur->iPage>0 );
5214 assert( pCur->pPage );
5215 assertParentIndex(
5216 pCur->apPage[pCur->iPage-1],
5217 pCur->aiIdx[pCur->iPage-1],
5218 pCur->pPage->pgno
5220 testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
5221 pCur->info.nSize = 0;
5222 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
5223 pCur->ix = pCur->aiIdx[pCur->iPage-1];
5224 pLeaf = pCur->pPage;
5225 pCur->pPage = pCur->apPage[--pCur->iPage];
5226 releasePageNotNull(pLeaf);
5230 ** Move the cursor to point to the root page of its b-tree structure.
5232 ** If the table has a virtual root page, then the cursor is moved to point
5233 ** to the virtual root page instead of the actual root page. A table has a
5234 ** virtual root page when the actual root page contains no cells and a
5235 ** single child page. This can only happen with the table rooted at page 1.
5237 ** If the b-tree structure is empty, the cursor state is set to
5238 ** CURSOR_INVALID and this routine returns SQLITE_EMPTY. Otherwise,
5239 ** the cursor is set to point to the first cell located on the root
5240 ** (or virtual root) page and the cursor state is set to CURSOR_VALID.
5242 ** If this function returns successfully, it may be assumed that the
5243 ** page-header flags indicate that the [virtual] root-page is the expected
5244 ** kind of b-tree page (i.e. if when opening the cursor the caller did not
5245 ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
5246 ** indicating a table b-tree, or if the caller did specify a KeyInfo
5247 ** structure the flags byte is set to 0x02 or 0x0A, indicating an index
5248 ** b-tree).
5250 static int moveToRoot(BtCursor *pCur){
5251 MemPage *pRoot;
5252 int rc = SQLITE_OK;
5254 assert( cursorOwnsBtShared(pCur) );
5255 assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
5256 assert( CURSOR_VALID < CURSOR_REQUIRESEEK );
5257 assert( CURSOR_FAULT > CURSOR_REQUIRESEEK );
5258 assert( pCur->eState < CURSOR_REQUIRESEEK || pCur->iPage<0 );
5259 assert( pCur->pgnoRoot>0 || pCur->iPage<0 );
5261 if( pCur->iPage>=0 ){
5262 if( pCur->iPage ){
5263 releasePageNotNull(pCur->pPage);
5264 while( --pCur->iPage ){
5265 releasePageNotNull(pCur->apPage[pCur->iPage]);
5267 pCur->pPage = pCur->apPage[0];
5268 goto skip_init;
5270 }else if( pCur->pgnoRoot==0 ){
5271 pCur->eState = CURSOR_INVALID;
5272 return SQLITE_EMPTY;
5273 }else{
5274 assert( pCur->iPage==(-1) );
5275 if( pCur->eState>=CURSOR_REQUIRESEEK ){
5276 if( pCur->eState==CURSOR_FAULT ){
5277 assert( pCur->skipNext!=SQLITE_OK );
5278 return pCur->skipNext;
5280 sqlite3BtreeClearCursor(pCur);
5282 rc = getAndInitPage(pCur->pBtree->pBt, pCur->pgnoRoot, &pCur->pPage,
5283 0, pCur->curPagerFlags);
5284 if( rc!=SQLITE_OK ){
5285 pCur->eState = CURSOR_INVALID;
5286 return rc;
5288 pCur->iPage = 0;
5289 pCur->curIntKey = pCur->pPage->intKey;
5291 pRoot = pCur->pPage;
5292 assert( pRoot->pgno==pCur->pgnoRoot );
5294 /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
5295 ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
5296 ** NULL, the caller expects a table b-tree. If this is not the case,
5297 ** return an SQLITE_CORRUPT error.
5299 ** Earlier versions of SQLite assumed that this test could not fail
5300 ** if the root page was already loaded when this function was called (i.e.
5301 ** if pCur->iPage>=0). But this is not so if the database is corrupted
5302 ** in such a way that page pRoot is linked into a second b-tree table
5303 ** (or the freelist). */
5304 assert( pRoot->intKey==1 || pRoot->intKey==0 );
5305 if( pRoot->isInit==0 || (pCur->pKeyInfo==0)!=pRoot->intKey ){
5306 return SQLITE_CORRUPT_PAGE(pCur->pPage);
5309 skip_init:
5310 pCur->ix = 0;
5311 pCur->info.nSize = 0;
5312 pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidNKey|BTCF_ValidOvfl);
5314 pRoot = pCur->pPage;
5315 if( pRoot->nCell>0 ){
5316 pCur->eState = CURSOR_VALID;
5317 }else if( !pRoot->leaf ){
5318 Pgno subpage;
5319 if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
5320 subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
5321 pCur->eState = CURSOR_VALID;
5322 rc = moveToChild(pCur, subpage);
5323 }else{
5324 pCur->eState = CURSOR_INVALID;
5325 rc = SQLITE_EMPTY;
5327 return rc;
5331 ** Move the cursor down to the left-most leaf entry beneath the
5332 ** entry to which it is currently pointing.
5334 ** The left-most leaf is the one with the smallest key - the first
5335 ** in ascending order.
5337 static int moveToLeftmost(BtCursor *pCur){
5338 Pgno pgno;
5339 int rc = SQLITE_OK;
5340 MemPage *pPage;
5342 assert( cursorOwnsBtShared(pCur) );
5343 assert( pCur->eState==CURSOR_VALID );
5344 while( rc==SQLITE_OK && !(pPage = pCur->pPage)->leaf ){
5345 assert( pCur->ix<pPage->nCell );
5346 pgno = get4byte(findCell(pPage, pCur->ix));
5347 rc = moveToChild(pCur, pgno);
5349 return rc;
5353 ** Move the cursor down to the right-most leaf entry beneath the
5354 ** page to which it is currently pointing. Notice the difference
5355 ** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
5356 ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
5357 ** finds the right-most entry beneath the *page*.
5359 ** The right-most entry is the one with the largest key - the last
5360 ** key in ascending order.
5362 static int moveToRightmost(BtCursor *pCur){
5363 Pgno pgno;
5364 int rc = SQLITE_OK;
5365 MemPage *pPage = 0;
5367 assert( cursorOwnsBtShared(pCur) );
5368 assert( pCur->eState==CURSOR_VALID );
5369 while( !(pPage = pCur->pPage)->leaf ){
5370 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
5371 pCur->ix = pPage->nCell;
5372 rc = moveToChild(pCur, pgno);
5373 if( rc ) return rc;
5375 pCur->ix = pPage->nCell-1;
5376 assert( pCur->info.nSize==0 );
5377 assert( (pCur->curFlags & BTCF_ValidNKey)==0 );
5378 return SQLITE_OK;
5381 /* Move the cursor to the first entry in the table. Return SQLITE_OK
5382 ** on success. Set *pRes to 0 if the cursor actually points to something
5383 ** or set *pRes to 1 if the table is empty.
5385 int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
5386 int rc;
5388 assert( cursorOwnsBtShared(pCur) );
5389 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
5390 rc = moveToRoot(pCur);
5391 if( rc==SQLITE_OK ){
5392 assert( pCur->pPage->nCell>0 );
5393 *pRes = 0;
5394 rc = moveToLeftmost(pCur);
5395 }else if( rc==SQLITE_EMPTY ){
5396 assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
5397 *pRes = 1;
5398 rc = SQLITE_OK;
5400 return rc;
5403 /* Move the cursor to the last entry in the table. Return SQLITE_OK
5404 ** on success. Set *pRes to 0 if the cursor actually points to something
5405 ** or set *pRes to 1 if the table is empty.
5407 int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
5408 int rc;
5410 assert( cursorOwnsBtShared(pCur) );
5411 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
5413 /* If the cursor already points to the last entry, this is a no-op. */
5414 if( CURSOR_VALID==pCur->eState && (pCur->curFlags & BTCF_AtLast)!=0 ){
5415 #ifdef SQLITE_DEBUG
5416 /* This block serves to assert() that the cursor really does point
5417 ** to the last entry in the b-tree. */
5418 int ii;
5419 for(ii=0; ii<pCur->iPage; ii++){
5420 assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
5422 assert( pCur->ix==pCur->pPage->nCell-1 || CORRUPT_DB );
5423 testcase( pCur->ix!=pCur->pPage->nCell-1 );
5424 /* ^-- dbsqlfuzz b92b72e4de80b5140c30ab71372ca719b8feb618 */
5425 assert( pCur->pPage->leaf );
5426 #endif
5427 *pRes = 0;
5428 return SQLITE_OK;
5431 rc = moveToRoot(pCur);
5432 if( rc==SQLITE_OK ){
5433 assert( pCur->eState==CURSOR_VALID );
5434 *pRes = 0;
5435 rc = moveToRightmost(pCur);
5436 if( rc==SQLITE_OK ){
5437 pCur->curFlags |= BTCF_AtLast;
5438 }else{
5439 pCur->curFlags &= ~BTCF_AtLast;
5441 }else if( rc==SQLITE_EMPTY ){
5442 assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
5443 *pRes = 1;
5444 rc = SQLITE_OK;
5446 return rc;
5449 /* Move the cursor so that it points to an entry in a table (a.k.a INTKEY)
5450 ** table near the key intKey. Return a success code.
5452 ** If an exact match is not found, then the cursor is always
5453 ** left pointing at a leaf page which would hold the entry if it
5454 ** were present. The cursor might point to an entry that comes
5455 ** before or after the key.
5457 ** An integer is written into *pRes which is the result of
5458 ** comparing the key with the entry to which the cursor is
5459 ** pointing. The meaning of the integer written into
5460 ** *pRes is as follows:
5462 ** *pRes<0 The cursor is left pointing at an entry that
5463 ** is smaller than intKey or if the table is empty
5464 ** and the cursor is therefore left point to nothing.
5466 ** *pRes==0 The cursor is left pointing at an entry that
5467 ** exactly matches intKey.
5469 ** *pRes>0 The cursor is left pointing at an entry that
5470 ** is larger than intKey.
5472 int sqlite3BtreeTableMoveto(
5473 BtCursor *pCur, /* The cursor to be moved */
5474 i64 intKey, /* The table key */
5475 int biasRight, /* If true, bias the search to the high end */
5476 int *pRes /* Write search results here */
5478 int rc;
5480 assert( cursorOwnsBtShared(pCur) );
5481 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
5482 assert( pRes );
5483 assert( pCur->pKeyInfo==0 );
5484 assert( pCur->eState!=CURSOR_VALID || pCur->curIntKey!=0 );
5486 /* If the cursor is already positioned at the point we are trying
5487 ** to move to, then just return without doing any work */
5488 if( pCur->eState==CURSOR_VALID && (pCur->curFlags & BTCF_ValidNKey)!=0 ){
5489 if( pCur->info.nKey==intKey ){
5490 *pRes = 0;
5491 return SQLITE_OK;
5493 if( pCur->info.nKey<intKey ){
5494 if( (pCur->curFlags & BTCF_AtLast)!=0 ){
5495 *pRes = -1;
5496 return SQLITE_OK;
5498 /* If the requested key is one more than the previous key, then
5499 ** try to get there using sqlite3BtreeNext() rather than a full
5500 ** binary search. This is an optimization only. The correct answer
5501 ** is still obtained without this case, only a little more slowely */
5502 if( pCur->info.nKey+1==intKey ){
5503 *pRes = 0;
5504 rc = sqlite3BtreeNext(pCur, 0);
5505 if( rc==SQLITE_OK ){
5506 getCellInfo(pCur);
5507 if( pCur->info.nKey==intKey ){
5508 return SQLITE_OK;
5510 }else if( rc!=SQLITE_DONE ){
5511 return rc;
5517 #ifdef SQLITE_DEBUG
5518 pCur->pBtree->nSeek++; /* Performance measurement during testing */
5519 #endif
5521 rc = moveToRoot(pCur);
5522 if( rc ){
5523 if( rc==SQLITE_EMPTY ){
5524 assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
5525 *pRes = -1;
5526 return SQLITE_OK;
5528 return rc;
5530 assert( pCur->pPage );
5531 assert( pCur->pPage->isInit );
5532 assert( pCur->eState==CURSOR_VALID );
5533 assert( pCur->pPage->nCell > 0 );
5534 assert( pCur->iPage==0 || pCur->apPage[0]->intKey==pCur->curIntKey );
5535 assert( pCur->curIntKey );
5537 for(;;){
5538 int lwr, upr, idx, c;
5539 Pgno chldPg;
5540 MemPage *pPage = pCur->pPage;
5541 u8 *pCell; /* Pointer to current cell in pPage */
5543 /* pPage->nCell must be greater than zero. If this is the root-page
5544 ** the cursor would have been INVALID above and this for(;;) loop
5545 ** not run. If this is not the root-page, then the moveToChild() routine
5546 ** would have already detected db corruption. Similarly, pPage must
5547 ** be the right kind (index or table) of b-tree page. Otherwise
5548 ** a moveToChild() or moveToRoot() call would have detected corruption. */
5549 assert( pPage->nCell>0 );
5550 assert( pPage->intKey );
5551 lwr = 0;
5552 upr = pPage->nCell-1;
5553 assert( biasRight==0 || biasRight==1 );
5554 idx = upr>>(1-biasRight); /* idx = biasRight ? upr : (lwr+upr)/2; */
5555 pCur->ix = (u16)idx;
5556 for(;;){
5557 i64 nCellKey;
5558 pCell = findCellPastPtr(pPage, idx);
5559 if( pPage->intKeyLeaf ){
5560 while( 0x80 <= *(pCell++) ){
5561 if( pCell>=pPage->aDataEnd ){
5562 return SQLITE_CORRUPT_PAGE(pPage);
5566 getVarint(pCell, (u64*)&nCellKey);
5567 if( nCellKey<intKey ){
5568 lwr = idx+1;
5569 if( lwr>upr ){ c = -1; break; }
5570 }else if( nCellKey>intKey ){
5571 upr = idx-1;
5572 if( lwr>upr ){ c = +1; break; }
5573 }else{
5574 assert( nCellKey==intKey );
5575 pCur->ix = (u16)idx;
5576 if( !pPage->leaf ){
5577 lwr = idx;
5578 goto moveto_table_next_layer;
5579 }else{
5580 pCur->curFlags |= BTCF_ValidNKey;
5581 pCur->info.nKey = nCellKey;
5582 pCur->info.nSize = 0;
5583 *pRes = 0;
5584 return SQLITE_OK;
5587 assert( lwr+upr>=0 );
5588 idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2; */
5590 assert( lwr==upr+1 || !pPage->leaf );
5591 assert( pPage->isInit );
5592 if( pPage->leaf ){
5593 assert( pCur->ix<pCur->pPage->nCell );
5594 pCur->ix = (u16)idx;
5595 *pRes = c;
5596 rc = SQLITE_OK;
5597 goto moveto_table_finish;
5599 moveto_table_next_layer:
5600 if( lwr>=pPage->nCell ){
5601 chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
5602 }else{
5603 chldPg = get4byte(findCell(pPage, lwr));
5605 pCur->ix = (u16)lwr;
5606 rc = moveToChild(pCur, chldPg);
5607 if( rc ) break;
5609 moveto_table_finish:
5610 pCur->info.nSize = 0;
5611 assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
5612 return rc;
5615 /* Move the cursor so that it points to an entry in an index table
5616 ** near the key pIdxKey. Return a success code.
5618 ** If an exact match is not found, then the cursor is always
5619 ** left pointing at a leaf page which would hold the entry if it
5620 ** were present. The cursor might point to an entry that comes
5621 ** before or after the key.
5623 ** An integer is written into *pRes which is the result of
5624 ** comparing the key with the entry to which the cursor is
5625 ** pointing. The meaning of the integer written into
5626 ** *pRes is as follows:
5628 ** *pRes<0 The cursor is left pointing at an entry that
5629 ** is smaller than pIdxKey or if the table is empty
5630 ** and the cursor is therefore left point to nothing.
5632 ** *pRes==0 The cursor is left pointing at an entry that
5633 ** exactly matches pIdxKey.
5635 ** *pRes>0 The cursor is left pointing at an entry that
5636 ** is larger than pIdxKey.
5638 ** The pIdxKey->eqSeen field is set to 1 if there
5639 ** exists an entry in the table that exactly matches pIdxKey.
5641 int sqlite3BtreeIndexMoveto(
5642 BtCursor *pCur, /* The cursor to be moved */
5643 UnpackedRecord *pIdxKey, /* Unpacked index key */
5644 int *pRes /* Write search results here */
5646 int rc;
5647 RecordCompare xRecordCompare;
5649 assert( cursorOwnsBtShared(pCur) );
5650 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
5651 assert( pRes );
5652 assert( pCur->pKeyInfo!=0 );
5654 #ifdef SQLITE_DEBUG
5655 pCur->pBtree->nSeek++; /* Performance measurement during testing */
5656 #endif
5658 xRecordCompare = sqlite3VdbeFindCompare(pIdxKey);
5659 pIdxKey->errCode = 0;
5660 assert( pIdxKey->default_rc==1
5661 || pIdxKey->default_rc==0
5662 || pIdxKey->default_rc==-1
5665 rc = moveToRoot(pCur);
5666 if( rc ){
5667 if( rc==SQLITE_EMPTY ){
5668 assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
5669 *pRes = -1;
5670 return SQLITE_OK;
5672 return rc;
5674 assert( pCur->pPage );
5675 assert( pCur->pPage->isInit );
5676 assert( pCur->eState==CURSOR_VALID );
5677 assert( pCur->pPage->nCell > 0 );
5678 assert( pCur->iPage==0 || pCur->apPage[0]->intKey==pCur->curIntKey );
5679 assert( pCur->curIntKey || pIdxKey );
5680 for(;;){
5681 int lwr, upr, idx, c;
5682 Pgno chldPg;
5683 MemPage *pPage = pCur->pPage;
5684 u8 *pCell; /* Pointer to current cell in pPage */
5686 /* pPage->nCell must be greater than zero. If this is the root-page
5687 ** the cursor would have been INVALID above and this for(;;) loop
5688 ** not run. If this is not the root-page, then the moveToChild() routine
5689 ** would have already detected db corruption. Similarly, pPage must
5690 ** be the right kind (index or table) of b-tree page. Otherwise
5691 ** a moveToChild() or moveToRoot() call would have detected corruption. */
5692 assert( pPage->nCell>0 );
5693 assert( pPage->intKey==(pIdxKey==0) );
5694 lwr = 0;
5695 upr = pPage->nCell-1;
5696 idx = upr>>1; /* idx = (lwr+upr)/2; */
5697 pCur->ix = (u16)idx;
5698 for(;;){
5699 int nCell; /* Size of the pCell cell in bytes */
5700 pCell = findCellPastPtr(pPage, idx);
5702 /* The maximum supported page-size is 65536 bytes. This means that
5703 ** the maximum number of record bytes stored on an index B-Tree
5704 ** page is less than 16384 bytes and may be stored as a 2-byte
5705 ** varint. This information is used to attempt to avoid parsing
5706 ** the entire cell by checking for the cases where the record is
5707 ** stored entirely within the b-tree page by inspecting the first
5708 ** 2 bytes of the cell.
5710 nCell = pCell[0];
5711 if( nCell<=pPage->max1bytePayload ){
5712 /* This branch runs if the record-size field of the cell is a
5713 ** single byte varint and the record fits entirely on the main
5714 ** b-tree page. */
5715 testcase( pCell+nCell+1==pPage->aDataEnd );
5716 c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
5717 }else if( !(pCell[1] & 0x80)
5718 && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
5720 /* The record-size field is a 2 byte varint and the record
5721 ** fits entirely on the main b-tree page. */
5722 testcase( pCell+nCell+2==pPage->aDataEnd );
5723 c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
5724 }else{
5725 /* The record flows over onto one or more overflow pages. In
5726 ** this case the whole cell needs to be parsed, a buffer allocated
5727 ** and accessPayload() used to retrieve the record into the
5728 ** buffer before VdbeRecordCompare() can be called.
5730 ** If the record is corrupt, the xRecordCompare routine may read
5731 ** up to two varints past the end of the buffer. An extra 18
5732 ** bytes of padding is allocated at the end of the buffer in
5733 ** case this happens. */
5734 void *pCellKey;
5735 u8 * const pCellBody = pCell - pPage->childPtrSize;
5736 const int nOverrun = 18; /* Size of the overrun padding */
5737 pPage->xParseCell(pPage, pCellBody, &pCur->info);
5738 nCell = (int)pCur->info.nKey;
5739 testcase( nCell<0 ); /* True if key size is 2^32 or more */
5740 testcase( nCell==0 ); /* Invalid key size: 0x80 0x80 0x00 */
5741 testcase( nCell==1 ); /* Invalid key size: 0x80 0x80 0x01 */
5742 testcase( nCell==2 ); /* Minimum legal index key size */
5743 if( nCell<2 || nCell/pCur->pBt->usableSize>pCur->pBt->nPage ){
5744 rc = SQLITE_CORRUPT_PAGE(pPage);
5745 goto moveto_index_finish;
5747 pCellKey = sqlite3Malloc( nCell+nOverrun );
5748 if( pCellKey==0 ){
5749 rc = SQLITE_NOMEM_BKPT;
5750 goto moveto_index_finish;
5752 pCur->ix = (u16)idx;
5753 rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
5754 memset(((u8*)pCellKey)+nCell,0,nOverrun); /* Fix uninit warnings */
5755 pCur->curFlags &= ~BTCF_ValidOvfl;
5756 if( rc ){
5757 sqlite3_free(pCellKey);
5758 goto moveto_index_finish;
5760 c = sqlite3VdbeRecordCompare(nCell, pCellKey, pIdxKey);
5761 sqlite3_free(pCellKey);
5763 assert(
5764 (pIdxKey->errCode!=SQLITE_CORRUPT || c==0)
5765 && (pIdxKey->errCode!=SQLITE_NOMEM || pCur->pBtree->db->mallocFailed)
5767 if( c<0 ){
5768 lwr = idx+1;
5769 }else if( c>0 ){
5770 upr = idx-1;
5771 }else{
5772 assert( c==0 );
5773 *pRes = 0;
5774 rc = SQLITE_OK;
5775 pCur->ix = (u16)idx;
5776 if( pIdxKey->errCode ) rc = SQLITE_CORRUPT_BKPT;
5777 goto moveto_index_finish;
5779 if( lwr>upr ) break;
5780 assert( lwr+upr>=0 );
5781 idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2 */
5783 assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
5784 assert( pPage->isInit );
5785 if( pPage->leaf ){
5786 assert( pCur->ix<pCur->pPage->nCell );
5787 pCur->ix = (u16)idx;
5788 *pRes = c;
5789 rc = SQLITE_OK;
5790 goto moveto_index_finish;
5792 if( lwr>=pPage->nCell ){
5793 chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
5794 }else{
5795 chldPg = get4byte(findCell(pPage, lwr));
5797 pCur->ix = (u16)lwr;
5798 rc = moveToChild(pCur, chldPg);
5799 if( rc ) break;
5801 moveto_index_finish:
5802 pCur->info.nSize = 0;
5803 assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
5804 return rc;
5809 ** Return TRUE if the cursor is not pointing at an entry of the table.
5811 ** TRUE will be returned after a call to sqlite3BtreeNext() moves
5812 ** past the last entry in the table or sqlite3BtreePrev() moves past
5813 ** the first entry. TRUE is also returned if the table is empty.
5815 int sqlite3BtreeEof(BtCursor *pCur){
5816 /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
5817 ** have been deleted? This API will need to change to return an error code
5818 ** as well as the boolean result value.
5820 return (CURSOR_VALID!=pCur->eState);
5824 ** Return an estimate for the number of rows in the table that pCur is
5825 ** pointing to. Return a negative number if no estimate is currently
5826 ** available.
5828 i64 sqlite3BtreeRowCountEst(BtCursor *pCur){
5829 i64 n;
5830 u8 i;
5832 assert( cursorOwnsBtShared(pCur) );
5833 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
5835 /* Currently this interface is only called by the OP_IfSmaller
5836 ** opcode, and it that case the cursor will always be valid and
5837 ** will always point to a leaf node. */
5838 if( NEVER(pCur->eState!=CURSOR_VALID) ) return -1;
5839 if( NEVER(pCur->pPage->leaf==0) ) return -1;
5841 n = pCur->pPage->nCell;
5842 for(i=0; i<pCur->iPage; i++){
5843 n *= pCur->apPage[i]->nCell;
5845 return n;
5849 ** Advance the cursor to the next entry in the database.
5850 ** Return value:
5852 ** SQLITE_OK success
5853 ** SQLITE_DONE cursor is already pointing at the last element
5854 ** otherwise some kind of error occurred
5856 ** The main entry point is sqlite3BtreeNext(). That routine is optimized
5857 ** for the common case of merely incrementing the cell counter BtCursor.aiIdx
5858 ** to the next cell on the current page. The (slower) btreeNext() helper
5859 ** routine is called when it is necessary to move to a different page or
5860 ** to restore the cursor.
5862 ** If bit 0x01 of the F argument in sqlite3BtreeNext(C,F) is 1, then the
5863 ** cursor corresponds to an SQL index and this routine could have been
5864 ** skipped if the SQL index had been a unique index. The F argument
5865 ** is a hint to the implement. SQLite btree implementation does not use
5866 ** this hint, but COMDB2 does.
5868 static SQLITE_NOINLINE int btreeNext(BtCursor *pCur){
5869 int rc;
5870 int idx;
5871 MemPage *pPage;
5873 assert( cursorOwnsBtShared(pCur) );
5874 if( pCur->eState!=CURSOR_VALID ){
5875 assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
5876 rc = restoreCursorPosition(pCur);
5877 if( rc!=SQLITE_OK ){
5878 return rc;
5880 if( CURSOR_INVALID==pCur->eState ){
5881 return SQLITE_DONE;
5883 if( pCur->eState==CURSOR_SKIPNEXT ){
5884 pCur->eState = CURSOR_VALID;
5885 if( pCur->skipNext>0 ) return SQLITE_OK;
5889 pPage = pCur->pPage;
5890 idx = ++pCur->ix;
5891 if( !pPage->isInit || sqlite3FaultSim(412) ){
5892 /* The only known way for this to happen is for there to be a
5893 ** recursive SQL function that does a DELETE operation as part of a
5894 ** SELECT which deletes content out from under an active cursor
5895 ** in a corrupt database file where the table being DELETE-ed from
5896 ** has pages in common with the table being queried. See TH3
5897 ** module cov1/btree78.test testcase 220 (2018-06-08) for an
5898 ** example. */
5899 return SQLITE_CORRUPT_BKPT;
5902 if( idx>=pPage->nCell ){
5903 if( !pPage->leaf ){
5904 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
5905 if( rc ) return rc;
5906 return moveToLeftmost(pCur);
5909 if( pCur->iPage==0 ){
5910 pCur->eState = CURSOR_INVALID;
5911 return SQLITE_DONE;
5913 moveToParent(pCur);
5914 pPage = pCur->pPage;
5915 }while( pCur->ix>=pPage->nCell );
5916 if( pPage->intKey ){
5917 return sqlite3BtreeNext(pCur, 0);
5918 }else{
5919 return SQLITE_OK;
5922 if( pPage->leaf ){
5923 return SQLITE_OK;
5924 }else{
5925 return moveToLeftmost(pCur);
5928 int sqlite3BtreeNext(BtCursor *pCur, int flags){
5929 MemPage *pPage;
5930 UNUSED_PARAMETER( flags ); /* Used in COMDB2 but not native SQLite */
5931 assert( cursorOwnsBtShared(pCur) );
5932 assert( flags==0 || flags==1 );
5933 pCur->info.nSize = 0;
5934 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
5935 if( pCur->eState!=CURSOR_VALID ) return btreeNext(pCur);
5936 pPage = pCur->pPage;
5937 if( (++pCur->ix)>=pPage->nCell ){
5938 pCur->ix--;
5939 return btreeNext(pCur);
5941 if( pPage->leaf ){
5942 return SQLITE_OK;
5943 }else{
5944 return moveToLeftmost(pCur);
5949 ** Step the cursor to the back to the previous entry in the database.
5950 ** Return values:
5952 ** SQLITE_OK success
5953 ** SQLITE_DONE the cursor is already on the first element of the table
5954 ** otherwise some kind of error occurred
5956 ** The main entry point is sqlite3BtreePrevious(). That routine is optimized
5957 ** for the common case of merely decrementing the cell counter BtCursor.aiIdx
5958 ** to the previous cell on the current page. The (slower) btreePrevious()
5959 ** helper routine is called when it is necessary to move to a different page
5960 ** or to restore the cursor.
5962 ** If bit 0x01 of the F argument to sqlite3BtreePrevious(C,F) is 1, then
5963 ** the cursor corresponds to an SQL index and this routine could have been
5964 ** skipped if the SQL index had been a unique index. The F argument is a
5965 ** hint to the implement. The native SQLite btree implementation does not
5966 ** use this hint, but COMDB2 does.
5968 static SQLITE_NOINLINE int btreePrevious(BtCursor *pCur){
5969 int rc;
5970 MemPage *pPage;
5972 assert( cursorOwnsBtShared(pCur) );
5973 assert( (pCur->curFlags & (BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey))==0 );
5974 assert( pCur->info.nSize==0 );
5975 if( pCur->eState!=CURSOR_VALID ){
5976 rc = restoreCursorPosition(pCur);
5977 if( rc!=SQLITE_OK ){
5978 return rc;
5980 if( CURSOR_INVALID==pCur->eState ){
5981 return SQLITE_DONE;
5983 if( CURSOR_SKIPNEXT==pCur->eState ){
5984 pCur->eState = CURSOR_VALID;
5985 if( pCur->skipNext<0 ) return SQLITE_OK;
5989 pPage = pCur->pPage;
5990 assert( pPage->isInit );
5991 if( !pPage->leaf ){
5992 int idx = pCur->ix;
5993 rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
5994 if( rc ) return rc;
5995 rc = moveToRightmost(pCur);
5996 }else{
5997 while( pCur->ix==0 ){
5998 if( pCur->iPage==0 ){
5999 pCur->eState = CURSOR_INVALID;
6000 return SQLITE_DONE;
6002 moveToParent(pCur);
6004 assert( pCur->info.nSize==0 );
6005 assert( (pCur->curFlags & (BTCF_ValidOvfl))==0 );
6007 pCur->ix--;
6008 pPage = pCur->pPage;
6009 if( pPage->intKey && !pPage->leaf ){
6010 rc = sqlite3BtreePrevious(pCur, 0);
6011 }else{
6012 rc = SQLITE_OK;
6015 return rc;
6017 int sqlite3BtreePrevious(BtCursor *pCur, int flags){
6018 assert( cursorOwnsBtShared(pCur) );
6019 assert( flags==0 || flags==1 );
6020 UNUSED_PARAMETER( flags ); /* Used in COMDB2 but not native SQLite */
6021 pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey);
6022 pCur->info.nSize = 0;
6023 if( pCur->eState!=CURSOR_VALID
6024 || pCur->ix==0
6025 || pCur->pPage->leaf==0
6027 return btreePrevious(pCur);
6029 pCur->ix--;
6030 return SQLITE_OK;
6034 ** Allocate a new page from the database file.
6036 ** The new page is marked as dirty. (In other words, sqlite3PagerWrite()
6037 ** has already been called on the new page.) The new page has also
6038 ** been referenced and the calling routine is responsible for calling
6039 ** sqlite3PagerUnref() on the new page when it is done.
6041 ** SQLITE_OK is returned on success. Any other return value indicates
6042 ** an error. *ppPage is set to NULL in the event of an error.
6044 ** If the "nearby" parameter is not 0, then an effort is made to
6045 ** locate a page close to the page number "nearby". This can be used in an
6046 ** attempt to keep related pages close to each other in the database file,
6047 ** which in turn can make database access faster.
6049 ** If the eMode parameter is BTALLOC_EXACT and the nearby page exists
6050 ** anywhere on the free-list, then it is guaranteed to be returned. If
6051 ** eMode is BTALLOC_LT then the page returned will be less than or equal
6052 ** to nearby if any such page exists. If eMode is BTALLOC_ANY then there
6053 ** are no restrictions on which page is returned.
6055 static int allocateBtreePage(
6056 BtShared *pBt, /* The btree */
6057 MemPage **ppPage, /* Store pointer to the allocated page here */
6058 Pgno *pPgno, /* Store the page number here */
6059 Pgno nearby, /* Search for a page near this one */
6060 u8 eMode /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */
6062 MemPage *pPage1;
6063 int rc;
6064 u32 n; /* Number of pages on the freelist */
6065 u32 k; /* Number of leaves on the trunk of the freelist */
6066 MemPage *pTrunk = 0;
6067 MemPage *pPrevTrunk = 0;
6068 Pgno mxPage; /* Total size of the database file */
6070 assert( sqlite3_mutex_held(pBt->mutex) );
6071 assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) );
6072 pPage1 = pBt->pPage1;
6073 mxPage = btreePagecount(pBt);
6074 /* EVIDENCE-OF: R-05119-02637 The 4-byte big-endian integer at offset 36
6075 ** stores stores the total number of pages on the freelist. */
6076 n = get4byte(&pPage1->aData[36]);
6077 testcase( n==mxPage-1 );
6078 if( n>=mxPage ){
6079 return SQLITE_CORRUPT_BKPT;
6081 if( n>0 ){
6082 /* There are pages on the freelist. Reuse one of those pages. */
6083 Pgno iTrunk;
6084 u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
6085 u32 nSearch = 0; /* Count of the number of search attempts */
6087 /* If eMode==BTALLOC_EXACT and a query of the pointer-map
6088 ** shows that the page 'nearby' is somewhere on the free-list, then
6089 ** the entire-list will be searched for that page.
6091 #ifndef SQLITE_OMIT_AUTOVACUUM
6092 if( eMode==BTALLOC_EXACT ){
6093 if( nearby<=mxPage ){
6094 u8 eType;
6095 assert( nearby>0 );
6096 assert( pBt->autoVacuum );
6097 rc = ptrmapGet(pBt, nearby, &eType, 0);
6098 if( rc ) return rc;
6099 if( eType==PTRMAP_FREEPAGE ){
6100 searchList = 1;
6103 }else if( eMode==BTALLOC_LE ){
6104 searchList = 1;
6106 #endif
6108 /* Decrement the free-list count by 1. Set iTrunk to the index of the
6109 ** first free-list trunk page. iPrevTrunk is initially 1.
6111 rc = sqlite3PagerWrite(pPage1->pDbPage);
6112 if( rc ) return rc;
6113 put4byte(&pPage1->aData[36], n-1);
6115 /* The code within this loop is run only once if the 'searchList' variable
6116 ** is not true. Otherwise, it runs once for each trunk-page on the
6117 ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT)
6118 ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT)
6120 do {
6121 pPrevTrunk = pTrunk;
6122 if( pPrevTrunk ){
6123 /* EVIDENCE-OF: R-01506-11053 The first integer on a freelist trunk page
6124 ** is the page number of the next freelist trunk page in the list or
6125 ** zero if this is the last freelist trunk page. */
6126 iTrunk = get4byte(&pPrevTrunk->aData[0]);
6127 }else{
6128 /* EVIDENCE-OF: R-59841-13798 The 4-byte big-endian integer at offset 32
6129 ** stores the page number of the first page of the freelist, or zero if
6130 ** the freelist is empty. */
6131 iTrunk = get4byte(&pPage1->aData[32]);
6133 testcase( iTrunk==mxPage );
6134 if( iTrunk>mxPage || nSearch++ > n ){
6135 rc = SQLITE_CORRUPT_PGNO(pPrevTrunk ? pPrevTrunk->pgno : 1);
6136 }else{
6137 rc = btreeGetUnusedPage(pBt, iTrunk, &pTrunk, 0);
6139 if( rc ){
6140 pTrunk = 0;
6141 goto end_allocate_page;
6143 assert( pTrunk!=0 );
6144 assert( pTrunk->aData!=0 );
6145 /* EVIDENCE-OF: R-13523-04394 The second integer on a freelist trunk page
6146 ** is the number of leaf page pointers to follow. */
6147 k = get4byte(&pTrunk->aData[4]);
6148 if( k==0 && !searchList ){
6149 /* The trunk has no leaves and the list is not being searched.
6150 ** So extract the trunk page itself and use it as the newly
6151 ** allocated page */
6152 assert( pPrevTrunk==0 );
6153 rc = sqlite3PagerWrite(pTrunk->pDbPage);
6154 if( rc ){
6155 goto end_allocate_page;
6157 *pPgno = iTrunk;
6158 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
6159 *ppPage = pTrunk;
6160 pTrunk = 0;
6161 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
6162 }else if( k>(u32)(pBt->usableSize/4 - 2) ){
6163 /* Value of k is out of range. Database corruption */
6164 rc = SQLITE_CORRUPT_PGNO(iTrunk);
6165 goto end_allocate_page;
6166 #ifndef SQLITE_OMIT_AUTOVACUUM
6167 }else if( searchList
6168 && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE))
6170 /* The list is being searched and this trunk page is the page
6171 ** to allocate, regardless of whether it has leaves.
6173 *pPgno = iTrunk;
6174 *ppPage = pTrunk;
6175 searchList = 0;
6176 rc = sqlite3PagerWrite(pTrunk->pDbPage);
6177 if( rc ){
6178 goto end_allocate_page;
6180 if( k==0 ){
6181 if( !pPrevTrunk ){
6182 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
6183 }else{
6184 rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
6185 if( rc!=SQLITE_OK ){
6186 goto end_allocate_page;
6188 memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
6190 }else{
6191 /* The trunk page is required by the caller but it contains
6192 ** pointers to free-list leaves. The first leaf becomes a trunk
6193 ** page in this case.
6195 MemPage *pNewTrunk;
6196 Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
6197 if( iNewTrunk>mxPage ){
6198 rc = SQLITE_CORRUPT_PGNO(iTrunk);
6199 goto end_allocate_page;
6201 testcase( iNewTrunk==mxPage );
6202 rc = btreeGetUnusedPage(pBt, iNewTrunk, &pNewTrunk, 0);
6203 if( rc!=SQLITE_OK ){
6204 goto end_allocate_page;
6206 rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
6207 if( rc!=SQLITE_OK ){
6208 releasePage(pNewTrunk);
6209 goto end_allocate_page;
6211 memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
6212 put4byte(&pNewTrunk->aData[4], k-1);
6213 memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
6214 releasePage(pNewTrunk);
6215 if( !pPrevTrunk ){
6216 assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
6217 put4byte(&pPage1->aData[32], iNewTrunk);
6218 }else{
6219 rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
6220 if( rc ){
6221 goto end_allocate_page;
6223 put4byte(&pPrevTrunk->aData[0], iNewTrunk);
6226 pTrunk = 0;
6227 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
6228 #endif
6229 }else if( k>0 ){
6230 /* Extract a leaf from the trunk */
6231 u32 closest;
6232 Pgno iPage;
6233 unsigned char *aData = pTrunk->aData;
6234 if( nearby>0 ){
6235 u32 i;
6236 closest = 0;
6237 if( eMode==BTALLOC_LE ){
6238 for(i=0; i<k; i++){
6239 iPage = get4byte(&aData[8+i*4]);
6240 if( iPage<=nearby ){
6241 closest = i;
6242 break;
6245 }else{
6246 int dist;
6247 dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
6248 for(i=1; i<k; i++){
6249 int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
6250 if( d2<dist ){
6251 closest = i;
6252 dist = d2;
6256 }else{
6257 closest = 0;
6260 iPage = get4byte(&aData[8+closest*4]);
6261 testcase( iPage==mxPage );
6262 if( iPage>mxPage || iPage<2 ){
6263 rc = SQLITE_CORRUPT_PGNO(iTrunk);
6264 goto end_allocate_page;
6266 testcase( iPage==mxPage );
6267 if( !searchList
6268 || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE))
6270 int noContent;
6271 *pPgno = iPage;
6272 TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
6273 ": %d more free pages\n",
6274 *pPgno, closest+1, k, pTrunk->pgno, n-1));
6275 rc = sqlite3PagerWrite(pTrunk->pDbPage);
6276 if( rc ) goto end_allocate_page;
6277 if( closest<k-1 ){
6278 memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
6280 put4byte(&aData[4], k-1);
6281 noContent = !btreeGetHasContent(pBt, *pPgno)? PAGER_GET_NOCONTENT : 0;
6282 rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, noContent);
6283 if( rc==SQLITE_OK ){
6284 rc = sqlite3PagerWrite((*ppPage)->pDbPage);
6285 if( rc!=SQLITE_OK ){
6286 releasePage(*ppPage);
6287 *ppPage = 0;
6290 searchList = 0;
6293 releasePage(pPrevTrunk);
6294 pPrevTrunk = 0;
6295 }while( searchList );
6296 }else{
6297 /* There are no pages on the freelist, so append a new page to the
6298 ** database image.
6300 ** Normally, new pages allocated by this block can be requested from the
6301 ** pager layer with the 'no-content' flag set. This prevents the pager
6302 ** from trying to read the pages content from disk. However, if the
6303 ** current transaction has already run one or more incremental-vacuum
6304 ** steps, then the page we are about to allocate may contain content
6305 ** that is required in the event of a rollback. In this case, do
6306 ** not set the no-content flag. This causes the pager to load and journal
6307 ** the current page content before overwriting it.
6309 ** Note that the pager will not actually attempt to load or journal
6310 ** content for any page that really does lie past the end of the database
6311 ** file on disk. So the effects of disabling the no-content optimization
6312 ** here are confined to those pages that lie between the end of the
6313 ** database image and the end of the database file.
6315 int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate))? PAGER_GET_NOCONTENT:0;
6317 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
6318 if( rc ) return rc;
6319 pBt->nPage++;
6320 if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
6322 #ifndef SQLITE_OMIT_AUTOVACUUM
6323 if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
6324 /* If *pPgno refers to a pointer-map page, allocate two new pages
6325 ** at the end of the file instead of one. The first allocated page
6326 ** becomes a new pointer-map page, the second is used by the caller.
6328 MemPage *pPg = 0;
6329 TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
6330 assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
6331 rc = btreeGetUnusedPage(pBt, pBt->nPage, &pPg, bNoContent);
6332 if( rc==SQLITE_OK ){
6333 rc = sqlite3PagerWrite(pPg->pDbPage);
6334 releasePage(pPg);
6336 if( rc ) return rc;
6337 pBt->nPage++;
6338 if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
6340 #endif
6341 put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
6342 *pPgno = pBt->nPage;
6344 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
6345 rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, bNoContent);
6346 if( rc ) return rc;
6347 rc = sqlite3PagerWrite((*ppPage)->pDbPage);
6348 if( rc!=SQLITE_OK ){
6349 releasePage(*ppPage);
6350 *ppPage = 0;
6352 TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
6355 assert( CORRUPT_DB || *pPgno!=PENDING_BYTE_PAGE(pBt) );
6357 end_allocate_page:
6358 releasePage(pTrunk);
6359 releasePage(pPrevTrunk);
6360 assert( rc!=SQLITE_OK || sqlite3PagerPageRefcount((*ppPage)->pDbPage)<=1 );
6361 assert( rc!=SQLITE_OK || (*ppPage)->isInit==0 );
6362 return rc;
6366 ** This function is used to add page iPage to the database file free-list.
6367 ** It is assumed that the page is not already a part of the free-list.
6369 ** The value passed as the second argument to this function is optional.
6370 ** If the caller happens to have a pointer to the MemPage object
6371 ** corresponding to page iPage handy, it may pass it as the second value.
6372 ** Otherwise, it may pass NULL.
6374 ** If a pointer to a MemPage object is passed as the second argument,
6375 ** its reference count is not altered by this function.
6377 static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
6378 MemPage *pTrunk = 0; /* Free-list trunk page */
6379 Pgno iTrunk = 0; /* Page number of free-list trunk page */
6380 MemPage *pPage1 = pBt->pPage1; /* Local reference to page 1 */
6381 MemPage *pPage; /* Page being freed. May be NULL. */
6382 int rc; /* Return Code */
6383 u32 nFree; /* Initial number of pages on free-list */
6385 assert( sqlite3_mutex_held(pBt->mutex) );
6386 assert( CORRUPT_DB || iPage>1 );
6387 assert( !pMemPage || pMemPage->pgno==iPage );
6389 if( NEVER(iPage<2) || iPage>pBt->nPage ){
6390 return SQLITE_CORRUPT_BKPT;
6392 if( pMemPage ){
6393 pPage = pMemPage;
6394 sqlite3PagerRef(pPage->pDbPage);
6395 }else{
6396 pPage = btreePageLookup(pBt, iPage);
6399 /* Increment the free page count on pPage1 */
6400 rc = sqlite3PagerWrite(pPage1->pDbPage);
6401 if( rc ) goto freepage_out;
6402 nFree = get4byte(&pPage1->aData[36]);
6403 put4byte(&pPage1->aData[36], nFree+1);
6405 if( pBt->btsFlags & BTS_SECURE_DELETE ){
6406 /* If the secure_delete option is enabled, then
6407 ** always fully overwrite deleted information with zeros.
6409 if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
6410 || ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
6412 goto freepage_out;
6414 memset(pPage->aData, 0, pPage->pBt->pageSize);
6417 /* If the database supports auto-vacuum, write an entry in the pointer-map
6418 ** to indicate that the page is free.
6420 if( ISAUTOVACUUM ){
6421 ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
6422 if( rc ) goto freepage_out;
6425 /* Now manipulate the actual database free-list structure. There are two
6426 ** possibilities. If the free-list is currently empty, or if the first
6427 ** trunk page in the free-list is full, then this page will become a
6428 ** new free-list trunk page. Otherwise, it will become a leaf of the
6429 ** first trunk page in the current free-list. This block tests if it
6430 ** is possible to add the page as a new free-list leaf.
6432 if( nFree!=0 ){
6433 u32 nLeaf; /* Initial number of leaf cells on trunk page */
6435 iTrunk = get4byte(&pPage1->aData[32]);
6436 if( iTrunk>btreePagecount(pBt) ){
6437 rc = SQLITE_CORRUPT_BKPT;
6438 goto freepage_out;
6440 rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
6441 if( rc!=SQLITE_OK ){
6442 goto freepage_out;
6445 nLeaf = get4byte(&pTrunk->aData[4]);
6446 assert( pBt->usableSize>32 );
6447 if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
6448 rc = SQLITE_CORRUPT_BKPT;
6449 goto freepage_out;
6451 if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
6452 /* In this case there is room on the trunk page to insert the page
6453 ** being freed as a new leaf.
6455 ** Note that the trunk page is not really full until it contains
6456 ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
6457 ** coded. But due to a coding error in versions of SQLite prior to
6458 ** 3.6.0, databases with freelist trunk pages holding more than
6459 ** usableSize/4 - 8 entries will be reported as corrupt. In order
6460 ** to maintain backwards compatibility with older versions of SQLite,
6461 ** we will continue to restrict the number of entries to usableSize/4 - 8
6462 ** for now. At some point in the future (once everyone has upgraded
6463 ** to 3.6.0 or later) we should consider fixing the conditional above
6464 ** to read "usableSize/4-2" instead of "usableSize/4-8".
6466 ** EVIDENCE-OF: R-19920-11576 However, newer versions of SQLite still
6467 ** avoid using the last six entries in the freelist trunk page array in
6468 ** order that database files created by newer versions of SQLite can be
6469 ** read by older versions of SQLite.
6471 rc = sqlite3PagerWrite(pTrunk->pDbPage);
6472 if( rc==SQLITE_OK ){
6473 put4byte(&pTrunk->aData[4], nLeaf+1);
6474 put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
6475 if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
6476 sqlite3PagerDontWrite(pPage->pDbPage);
6478 rc = btreeSetHasContent(pBt, iPage);
6480 TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
6481 goto freepage_out;
6485 /* If control flows to this point, then it was not possible to add the
6486 ** the page being freed as a leaf page of the first trunk in the free-list.
6487 ** Possibly because the free-list is empty, or possibly because the
6488 ** first trunk in the free-list is full. Either way, the page being freed
6489 ** will become the new first trunk page in the free-list.
6491 if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
6492 goto freepage_out;
6494 rc = sqlite3PagerWrite(pPage->pDbPage);
6495 if( rc!=SQLITE_OK ){
6496 goto freepage_out;
6498 put4byte(pPage->aData, iTrunk);
6499 put4byte(&pPage->aData[4], 0);
6500 put4byte(&pPage1->aData[32], iPage);
6501 TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
6503 freepage_out:
6504 if( pPage ){
6505 pPage->isInit = 0;
6507 releasePage(pPage);
6508 releasePage(pTrunk);
6509 return rc;
6511 static void freePage(MemPage *pPage, int *pRC){
6512 if( (*pRC)==SQLITE_OK ){
6513 *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
6518 ** Free the overflow pages associated with the given Cell.
6520 static SQLITE_NOINLINE int clearCellOverflow(
6521 MemPage *pPage, /* The page that contains the Cell */
6522 unsigned char *pCell, /* First byte of the Cell */
6523 CellInfo *pInfo /* Size information about the cell */
6525 BtShared *pBt;
6526 Pgno ovflPgno;
6527 int rc;
6528 int nOvfl;
6529 u32 ovflPageSize;
6531 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
6532 assert( pInfo->nLocal!=pInfo->nPayload );
6533 testcase( pCell + pInfo->nSize == pPage->aDataEnd );
6534 testcase( pCell + (pInfo->nSize-1) == pPage->aDataEnd );
6535 if( pCell + pInfo->nSize > pPage->aDataEnd ){
6536 /* Cell extends past end of page */
6537 return SQLITE_CORRUPT_PAGE(pPage);
6539 ovflPgno = get4byte(pCell + pInfo->nSize - 4);
6540 pBt = pPage->pBt;
6541 assert( pBt->usableSize > 4 );
6542 ovflPageSize = pBt->usableSize - 4;
6543 nOvfl = (pInfo->nPayload - pInfo->nLocal + ovflPageSize - 1)/ovflPageSize;
6544 assert( nOvfl>0 ||
6545 (CORRUPT_DB && (pInfo->nPayload + ovflPageSize)<ovflPageSize)
6547 while( nOvfl-- ){
6548 Pgno iNext = 0;
6549 MemPage *pOvfl = 0;
6550 if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
6551 /* 0 is not a legal page number and page 1 cannot be an
6552 ** overflow page. Therefore if ovflPgno<2 or past the end of the
6553 ** file the database must be corrupt. */
6554 return SQLITE_CORRUPT_BKPT;
6556 if( nOvfl ){
6557 rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
6558 if( rc ) return rc;
6561 if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
6562 && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
6564 /* There is no reason any cursor should have an outstanding reference
6565 ** to an overflow page belonging to a cell that is being deleted/updated.
6566 ** So if there exists more than one reference to this page, then it
6567 ** must not really be an overflow page and the database must be corrupt.
6568 ** It is helpful to detect this before calling freePage2(), as
6569 ** freePage2() may zero the page contents if secure-delete mode is
6570 ** enabled. If this 'overflow' page happens to be a page that the
6571 ** caller is iterating through or using in some other way, this
6572 ** can be problematic.
6574 rc = SQLITE_CORRUPT_BKPT;
6575 }else{
6576 rc = freePage2(pBt, pOvfl, ovflPgno);
6579 if( pOvfl ){
6580 sqlite3PagerUnref(pOvfl->pDbPage);
6582 if( rc ) return rc;
6583 ovflPgno = iNext;
6585 return SQLITE_OK;
6588 /* Call xParseCell to compute the size of a cell. If the cell contains
6589 ** overflow, then invoke cellClearOverflow to clear out that overflow.
6590 ** STore the result code (SQLITE_OK or some error code) in rc.
6592 ** Implemented as macro to force inlining for performance.
6594 #define BTREE_CLEAR_CELL(rc, pPage, pCell, sInfo) \
6595 pPage->xParseCell(pPage, pCell, &sInfo); \
6596 if( sInfo.nLocal!=sInfo.nPayload ){ \
6597 rc = clearCellOverflow(pPage, pCell, &sInfo); \
6598 }else{ \
6599 rc = SQLITE_OK; \
6604 ** Create the byte sequence used to represent a cell on page pPage
6605 ** and write that byte sequence into pCell[]. Overflow pages are
6606 ** allocated and filled in as necessary. The calling procedure
6607 ** is responsible for making sure sufficient space has been allocated
6608 ** for pCell[].
6610 ** Note that pCell does not necessary need to point to the pPage->aData
6611 ** area. pCell might point to some temporary storage. The cell will
6612 ** be constructed in this temporary area then copied into pPage->aData
6613 ** later.
6615 static int fillInCell(
6616 MemPage *pPage, /* The page that contains the cell */
6617 unsigned char *pCell, /* Complete text of the cell */
6618 const BtreePayload *pX, /* Payload with which to construct the cell */
6619 int *pnSize /* Write cell size here */
6621 int nPayload;
6622 const u8 *pSrc;
6623 int nSrc, n, rc, mn;
6624 int spaceLeft;
6625 MemPage *pToRelease;
6626 unsigned char *pPrior;
6627 unsigned char *pPayload;
6628 BtShared *pBt;
6629 Pgno pgnoOvfl;
6630 int nHeader;
6632 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
6634 /* pPage is not necessarily writeable since pCell might be auxiliary
6635 ** buffer space that is separate from the pPage buffer area */
6636 assert( pCell<pPage->aData || pCell>=&pPage->aData[pPage->pBt->pageSize]
6637 || sqlite3PagerIswriteable(pPage->pDbPage) );
6639 /* Fill in the header. */
6640 nHeader = pPage->childPtrSize;
6641 if( pPage->intKey ){
6642 nPayload = pX->nData + pX->nZero;
6643 pSrc = pX->pData;
6644 nSrc = pX->nData;
6645 assert( pPage->intKeyLeaf ); /* fillInCell() only called for leaves */
6646 nHeader += putVarint32(&pCell[nHeader], nPayload);
6647 nHeader += putVarint(&pCell[nHeader], *(u64*)&pX->nKey);
6648 }else{
6649 assert( pX->nKey<=0x7fffffff && pX->pKey!=0 );
6650 nSrc = nPayload = (int)pX->nKey;
6651 pSrc = pX->pKey;
6652 nHeader += putVarint32(&pCell[nHeader], nPayload);
6655 /* Fill in the payload */
6656 pPayload = &pCell[nHeader];
6657 if( nPayload<=pPage->maxLocal ){
6658 /* This is the common case where everything fits on the btree page
6659 ** and no overflow pages are required. */
6660 n = nHeader + nPayload;
6661 testcase( n==3 );
6662 testcase( n==4 );
6663 if( n<4 ) n = 4;
6664 *pnSize = n;
6665 assert( nSrc<=nPayload );
6666 testcase( nSrc<nPayload );
6667 memcpy(pPayload, pSrc, nSrc);
6668 memset(pPayload+nSrc, 0, nPayload-nSrc);
6669 return SQLITE_OK;
6672 /* If we reach this point, it means that some of the content will need
6673 ** to spill onto overflow pages.
6675 mn = pPage->minLocal;
6676 n = mn + (nPayload - mn) % (pPage->pBt->usableSize - 4);
6677 testcase( n==pPage->maxLocal );
6678 testcase( n==pPage->maxLocal+1 );
6679 if( n > pPage->maxLocal ) n = mn;
6680 spaceLeft = n;
6681 *pnSize = n + nHeader + 4;
6682 pPrior = &pCell[nHeader+n];
6683 pToRelease = 0;
6684 pgnoOvfl = 0;
6685 pBt = pPage->pBt;
6687 /* At this point variables should be set as follows:
6689 ** nPayload Total payload size in bytes
6690 ** pPayload Begin writing payload here
6691 ** spaceLeft Space available at pPayload. If nPayload>spaceLeft,
6692 ** that means content must spill into overflow pages.
6693 ** *pnSize Size of the local cell (not counting overflow pages)
6694 ** pPrior Where to write the pgno of the first overflow page
6696 ** Use a call to btreeParseCellPtr() to verify that the values above
6697 ** were computed correctly.
6699 #ifdef SQLITE_DEBUG
6701 CellInfo info;
6702 pPage->xParseCell(pPage, pCell, &info);
6703 assert( nHeader==(int)(info.pPayload - pCell) );
6704 assert( info.nKey==pX->nKey );
6705 assert( *pnSize == info.nSize );
6706 assert( spaceLeft == info.nLocal );
6708 #endif
6710 /* Write the payload into the local Cell and any extra into overflow pages */
6711 while( 1 ){
6712 n = nPayload;
6713 if( n>spaceLeft ) n = spaceLeft;
6715 /* If pToRelease is not zero than pPayload points into the data area
6716 ** of pToRelease. Make sure pToRelease is still writeable. */
6717 assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
6719 /* If pPayload is part of the data area of pPage, then make sure pPage
6720 ** is still writeable */
6721 assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
6722 || sqlite3PagerIswriteable(pPage->pDbPage) );
6724 if( nSrc>=n ){
6725 memcpy(pPayload, pSrc, n);
6726 }else if( nSrc>0 ){
6727 n = nSrc;
6728 memcpy(pPayload, pSrc, n);
6729 }else{
6730 memset(pPayload, 0, n);
6732 nPayload -= n;
6733 if( nPayload<=0 ) break;
6734 pPayload += n;
6735 pSrc += n;
6736 nSrc -= n;
6737 spaceLeft -= n;
6738 if( spaceLeft==0 ){
6739 MemPage *pOvfl = 0;
6740 #ifndef SQLITE_OMIT_AUTOVACUUM
6741 Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
6742 if( pBt->autoVacuum ){
6744 pgnoOvfl++;
6745 } while(
6746 PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
6749 #endif
6750 rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
6751 #ifndef SQLITE_OMIT_AUTOVACUUM
6752 /* If the database supports auto-vacuum, and the second or subsequent
6753 ** overflow page is being allocated, add an entry to the pointer-map
6754 ** for that page now.
6756 ** If this is the first overflow page, then write a partial entry
6757 ** to the pointer-map. If we write nothing to this pointer-map slot,
6758 ** then the optimistic overflow chain processing in clearCell()
6759 ** may misinterpret the uninitialized values and delete the
6760 ** wrong pages from the database.
6762 if( pBt->autoVacuum && rc==SQLITE_OK ){
6763 u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
6764 ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
6765 if( rc ){
6766 releasePage(pOvfl);
6769 #endif
6770 if( rc ){
6771 releasePage(pToRelease);
6772 return rc;
6775 /* If pToRelease is not zero than pPrior points into the data area
6776 ** of pToRelease. Make sure pToRelease is still writeable. */
6777 assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
6779 /* If pPrior is part of the data area of pPage, then make sure pPage
6780 ** is still writeable */
6781 assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
6782 || sqlite3PagerIswriteable(pPage->pDbPage) );
6784 put4byte(pPrior, pgnoOvfl);
6785 releasePage(pToRelease);
6786 pToRelease = pOvfl;
6787 pPrior = pOvfl->aData;
6788 put4byte(pPrior, 0);
6789 pPayload = &pOvfl->aData[4];
6790 spaceLeft = pBt->usableSize - 4;
6793 releasePage(pToRelease);
6794 return SQLITE_OK;
6798 ** Remove the i-th cell from pPage. This routine effects pPage only.
6799 ** The cell content is not freed or deallocated. It is assumed that
6800 ** the cell content has been copied someplace else. This routine just
6801 ** removes the reference to the cell from pPage.
6803 ** "sz" must be the number of bytes in the cell.
6805 static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
6806 u32 pc; /* Offset to cell content of cell being deleted */
6807 u8 *data; /* pPage->aData */
6808 u8 *ptr; /* Used to move bytes around within data[] */
6809 int rc; /* The return code */
6810 int hdr; /* Beginning of the header. 0 most pages. 100 page 1 */
6812 if( *pRC ) return;
6813 assert( idx>=0 );
6814 assert( idx<pPage->nCell );
6815 assert( CORRUPT_DB || sz==cellSize(pPage, idx) );
6816 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
6817 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
6818 assert( pPage->nFree>=0 );
6819 data = pPage->aData;
6820 ptr = &pPage->aCellIdx[2*idx];
6821 assert( pPage->pBt->usableSize > (int)(ptr-data) );
6822 pc = get2byte(ptr);
6823 hdr = pPage->hdrOffset;
6824 testcase( pc==(u32)get2byte(&data[hdr+5]) );
6825 testcase( pc+sz==pPage->pBt->usableSize );
6826 if( pc+sz > pPage->pBt->usableSize ){
6827 *pRC = SQLITE_CORRUPT_BKPT;
6828 return;
6830 rc = freeSpace(pPage, pc, sz);
6831 if( rc ){
6832 *pRC = rc;
6833 return;
6835 pPage->nCell--;
6836 if( pPage->nCell==0 ){
6837 memset(&data[hdr+1], 0, 4);
6838 data[hdr+7] = 0;
6839 put2byte(&data[hdr+5], pPage->pBt->usableSize);
6840 pPage->nFree = pPage->pBt->usableSize - pPage->hdrOffset
6841 - pPage->childPtrSize - 8;
6842 }else{
6843 memmove(ptr, ptr+2, 2*(pPage->nCell - idx));
6844 put2byte(&data[hdr+3], pPage->nCell);
6845 pPage->nFree += 2;
6850 ** Insert a new cell on pPage at cell index "i". pCell points to the
6851 ** content of the cell.
6853 ** If the cell content will fit on the page, then put it there. If it
6854 ** will not fit, then make a copy of the cell content into pTemp if
6855 ** pTemp is not null. Regardless of pTemp, allocate a new entry
6856 ** in pPage->apOvfl[] and make it point to the cell content (either
6857 ** in pTemp or the original pCell) and also record its index.
6858 ** Allocating a new entry in pPage->aCell[] implies that
6859 ** pPage->nOverflow is incremented.
6861 ** *pRC must be SQLITE_OK when this routine is called.
6863 static void insertCell(
6864 MemPage *pPage, /* Page into which we are copying */
6865 int i, /* New cell becomes the i-th cell of the page */
6866 u8 *pCell, /* Content of the new cell */
6867 int sz, /* Bytes of content in pCell */
6868 u8 *pTemp, /* Temp storage space for pCell, if needed */
6869 Pgno iChild, /* If non-zero, replace first 4 bytes with this value */
6870 int *pRC /* Read and write return code from here */
6872 int idx = 0; /* Where to write new cell content in data[] */
6873 int j; /* Loop counter */
6874 u8 *data; /* The content of the whole page */
6875 u8 *pIns; /* The point in pPage->aCellIdx[] where no cell inserted */
6877 assert( *pRC==SQLITE_OK );
6878 assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
6879 assert( MX_CELL(pPage->pBt)<=10921 );
6880 assert( pPage->nCell<=MX_CELL(pPage->pBt) || CORRUPT_DB );
6881 assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
6882 assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
6883 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
6884 assert( sz==pPage->xCellSize(pPage, pCell) || CORRUPT_DB );
6885 assert( pPage->nFree>=0 );
6886 if( pPage->nOverflow || sz+2>pPage->nFree ){
6887 if( pTemp ){
6888 memcpy(pTemp, pCell, sz);
6889 pCell = pTemp;
6891 if( iChild ){
6892 put4byte(pCell, iChild);
6894 j = pPage->nOverflow++;
6895 /* Comparison against ArraySize-1 since we hold back one extra slot
6896 ** as a contingency. In other words, never need more than 3 overflow
6897 ** slots but 4 are allocated, just to be safe. */
6898 assert( j < ArraySize(pPage->apOvfl)-1 );
6899 pPage->apOvfl[j] = pCell;
6900 pPage->aiOvfl[j] = (u16)i;
6902 /* When multiple overflows occur, they are always sequential and in
6903 ** sorted order. This invariants arise because multiple overflows can
6904 ** only occur when inserting divider cells into the parent page during
6905 ** balancing, and the dividers are adjacent and sorted.
6907 assert( j==0 || pPage->aiOvfl[j-1]<(u16)i ); /* Overflows in sorted order */
6908 assert( j==0 || i==pPage->aiOvfl[j-1]+1 ); /* Overflows are sequential */
6909 }else{
6910 int rc = sqlite3PagerWrite(pPage->pDbPage);
6911 if( rc!=SQLITE_OK ){
6912 *pRC = rc;
6913 return;
6915 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
6916 data = pPage->aData;
6917 assert( &data[pPage->cellOffset]==pPage->aCellIdx );
6918 rc = allocateSpace(pPage, sz, &idx);
6919 if( rc ){ *pRC = rc; return; }
6920 /* The allocateSpace() routine guarantees the following properties
6921 ** if it returns successfully */
6922 assert( idx >= 0 );
6923 assert( idx >= pPage->cellOffset+2*pPage->nCell+2 || CORRUPT_DB );
6924 assert( idx+sz <= (int)pPage->pBt->usableSize );
6925 pPage->nFree -= (u16)(2 + sz);
6926 if( iChild ){
6927 /* In a corrupt database where an entry in the cell index section of
6928 ** a btree page has a value of 3 or less, the pCell value might point
6929 ** as many as 4 bytes in front of the start of the aData buffer for
6930 ** the source page. Make sure this does not cause problems by not
6931 ** reading the first 4 bytes */
6932 memcpy(&data[idx+4], pCell+4, sz-4);
6933 put4byte(&data[idx], iChild);
6934 }else{
6935 memcpy(&data[idx], pCell, sz);
6937 pIns = pPage->aCellIdx + i*2;
6938 memmove(pIns+2, pIns, 2*(pPage->nCell - i));
6939 put2byte(pIns, idx);
6940 pPage->nCell++;
6941 /* increment the cell count */
6942 if( (++data[pPage->hdrOffset+4])==0 ) data[pPage->hdrOffset+3]++;
6943 assert( get2byte(&data[pPage->hdrOffset+3])==pPage->nCell || CORRUPT_DB );
6944 #ifndef SQLITE_OMIT_AUTOVACUUM
6945 if( pPage->pBt->autoVacuum ){
6946 /* The cell may contain a pointer to an overflow page. If so, write
6947 ** the entry for the overflow page into the pointer map.
6949 ptrmapPutOvflPtr(pPage, pPage, pCell, pRC);
6951 #endif
6956 ** The following parameters determine how many adjacent pages get involved
6957 ** in a balancing operation. NN is the number of neighbors on either side
6958 ** of the page that participate in the balancing operation. NB is the
6959 ** total number of pages that participate, including the target page and
6960 ** NN neighbors on either side.
6962 ** The minimum value of NN is 1 (of course). Increasing NN above 1
6963 ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
6964 ** in exchange for a larger degradation in INSERT and UPDATE performance.
6965 ** The value of NN appears to give the best results overall.
6967 ** (Later:) The description above makes it seem as if these values are
6968 ** tunable - as if you could change them and recompile and it would all work.
6969 ** But that is unlikely. NB has been 3 since the inception of SQLite and
6970 ** we have never tested any other value.
6972 #define NN 1 /* Number of neighbors on either side of pPage */
6973 #define NB 3 /* (NN*2+1): Total pages involved in the balance */
6976 ** A CellArray object contains a cache of pointers and sizes for a
6977 ** consecutive sequence of cells that might be held on multiple pages.
6979 ** The cells in this array are the divider cell or cells from the pParent
6980 ** page plus up to three child pages. There are a total of nCell cells.
6982 ** pRef is a pointer to one of the pages that contributes cells. This is
6983 ** used to access information such as MemPage.intKey and MemPage.pBt->pageSize
6984 ** which should be common to all pages that contribute cells to this array.
6986 ** apCell[] and szCell[] hold, respectively, pointers to the start of each
6987 ** cell and the size of each cell. Some of the apCell[] pointers might refer
6988 ** to overflow cells. In other words, some apCel[] pointers might not point
6989 ** to content area of the pages.
6991 ** A szCell[] of zero means the size of that cell has not yet been computed.
6993 ** The cells come from as many as four different pages:
6995 ** -----------
6996 ** | Parent |
6997 ** -----------
6998 ** / | \
6999 ** / | \
7000 ** --------- --------- ---------
7001 ** |Child-1| |Child-2| |Child-3|
7002 ** --------- --------- ---------
7004 ** The order of cells is in the array is for an index btree is:
7006 ** 1. All cells from Child-1 in order
7007 ** 2. The first divider cell from Parent
7008 ** 3. All cells from Child-2 in order
7009 ** 4. The second divider cell from Parent
7010 ** 5. All cells from Child-3 in order
7012 ** For a table-btree (with rowids) the items 2 and 4 are empty because
7013 ** content exists only in leaves and there are no divider cells.
7015 ** For an index btree, the apEnd[] array holds pointer to the end of page
7016 ** for Child-1, the Parent, Child-2, the Parent (again), and Child-3,
7017 ** respectively. The ixNx[] array holds the number of cells contained in
7018 ** each of these 5 stages, and all stages to the left. Hence:
7020 ** ixNx[0] = Number of cells in Child-1.
7021 ** ixNx[1] = Number of cells in Child-1 plus 1 for first divider.
7022 ** ixNx[2] = Number of cells in Child-1 and Child-2 + 1 for 1st divider.
7023 ** ixNx[3] = Number of cells in Child-1 and Child-2 + both divider cells
7024 ** ixNx[4] = Total number of cells.
7026 ** For a table-btree, the concept is similar, except only apEnd[0]..apEnd[2]
7027 ** are used and they point to the leaf pages only, and the ixNx value are:
7029 ** ixNx[0] = Number of cells in Child-1.
7030 ** ixNx[1] = Number of cells in Child-1 and Child-2.
7031 ** ixNx[2] = Total number of cells.
7033 ** Sometimes when deleting, a child page can have zero cells. In those
7034 ** cases, ixNx[] entries with higher indexes, and the corresponding apEnd[]
7035 ** entries, shift down. The end result is that each ixNx[] entry should
7036 ** be larger than the previous
7038 typedef struct CellArray CellArray;
7039 struct CellArray {
7040 int nCell; /* Number of cells in apCell[] */
7041 MemPage *pRef; /* Reference page */
7042 u8 **apCell; /* All cells begin balanced */
7043 u16 *szCell; /* Local size of all cells in apCell[] */
7044 u8 *apEnd[NB*2]; /* MemPage.aDataEnd values */
7045 int ixNx[NB*2]; /* Index of at which we move to the next apEnd[] */
7049 ** Make sure the cell sizes at idx, idx+1, ..., idx+N-1 have been
7050 ** computed.
7052 static void populateCellCache(CellArray *p, int idx, int N){
7053 assert( idx>=0 && idx+N<=p->nCell );
7054 while( N>0 ){
7055 assert( p->apCell[idx]!=0 );
7056 if( p->szCell[idx]==0 ){
7057 p->szCell[idx] = p->pRef->xCellSize(p->pRef, p->apCell[idx]);
7058 }else{
7059 assert( CORRUPT_DB ||
7060 p->szCell[idx]==p->pRef->xCellSize(p->pRef, p->apCell[idx]) );
7062 idx++;
7063 N--;
7068 ** Return the size of the Nth element of the cell array
7070 static SQLITE_NOINLINE u16 computeCellSize(CellArray *p, int N){
7071 assert( N>=0 && N<p->nCell );
7072 assert( p->szCell[N]==0 );
7073 p->szCell[N] = p->pRef->xCellSize(p->pRef, p->apCell[N]);
7074 return p->szCell[N];
7076 static u16 cachedCellSize(CellArray *p, int N){
7077 assert( N>=0 && N<p->nCell );
7078 if( p->szCell[N] ) return p->szCell[N];
7079 return computeCellSize(p, N);
7083 ** Array apCell[] contains pointers to nCell b-tree page cells. The
7084 ** szCell[] array contains the size in bytes of each cell. This function
7085 ** replaces the current contents of page pPg with the contents of the cell
7086 ** array.
7088 ** Some of the cells in apCell[] may currently be stored in pPg. This
7089 ** function works around problems caused by this by making a copy of any
7090 ** such cells before overwriting the page data.
7092 ** The MemPage.nFree field is invalidated by this function. It is the
7093 ** responsibility of the caller to set it correctly.
7095 static int rebuildPage(
7096 CellArray *pCArray, /* Content to be added to page pPg */
7097 int iFirst, /* First cell in pCArray to use */
7098 int nCell, /* Final number of cells on page */
7099 MemPage *pPg /* The page to be reconstructed */
7101 const int hdr = pPg->hdrOffset; /* Offset of header on pPg */
7102 u8 * const aData = pPg->aData; /* Pointer to data for pPg */
7103 const int usableSize = pPg->pBt->usableSize;
7104 u8 * const pEnd = &aData[usableSize];
7105 int i = iFirst; /* Which cell to copy from pCArray*/
7106 u32 j; /* Start of cell content area */
7107 int iEnd = i+nCell; /* Loop terminator */
7108 u8 *pCellptr = pPg->aCellIdx;
7109 u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
7110 u8 *pData;
7111 int k; /* Current slot in pCArray->apEnd[] */
7112 u8 *pSrcEnd; /* Current pCArray->apEnd[k] value */
7114 assert( i<iEnd );
7115 j = get2byte(&aData[hdr+5]);
7116 if( j>(u32)usableSize ){ j = 0; }
7117 memcpy(&pTmp[j], &aData[j], usableSize - j);
7119 for(k=0; pCArray->ixNx[k]<=i && ALWAYS(k<NB*2); k++){}
7120 pSrcEnd = pCArray->apEnd[k];
7122 pData = pEnd;
7123 while( 1/*exit by break*/ ){
7124 u8 *pCell = pCArray->apCell[i];
7125 u16 sz = pCArray->szCell[i];
7126 assert( sz>0 );
7127 if( SQLITE_WITHIN(pCell,aData+j,pEnd) ){
7128 if( ((uptr)(pCell+sz))>(uptr)pEnd ) return SQLITE_CORRUPT_BKPT;
7129 pCell = &pTmp[pCell - aData];
7130 }else if( (uptr)(pCell+sz)>(uptr)pSrcEnd
7131 && (uptr)(pCell)<(uptr)pSrcEnd
7133 return SQLITE_CORRUPT_BKPT;
7136 pData -= sz;
7137 put2byte(pCellptr, (pData - aData));
7138 pCellptr += 2;
7139 if( pData < pCellptr ) return SQLITE_CORRUPT_BKPT;
7140 memmove(pData, pCell, sz);
7141 assert( sz==pPg->xCellSize(pPg, pCell) || CORRUPT_DB );
7142 i++;
7143 if( i>=iEnd ) break;
7144 if( pCArray->ixNx[k]<=i ){
7145 k++;
7146 pSrcEnd = pCArray->apEnd[k];
7150 /* The pPg->nFree field is now set incorrectly. The caller will fix it. */
7151 pPg->nCell = nCell;
7152 pPg->nOverflow = 0;
7154 put2byte(&aData[hdr+1], 0);
7155 put2byte(&aData[hdr+3], pPg->nCell);
7156 put2byte(&aData[hdr+5], pData - aData);
7157 aData[hdr+7] = 0x00;
7158 return SQLITE_OK;
7162 ** The pCArray objects contains pointers to b-tree cells and the cell sizes.
7163 ** This function attempts to add the cells stored in the array to page pPg.
7164 ** If it cannot (because the page needs to be defragmented before the cells
7165 ** will fit), non-zero is returned. Otherwise, if the cells are added
7166 ** successfully, zero is returned.
7168 ** Argument pCellptr points to the first entry in the cell-pointer array
7169 ** (part of page pPg) to populate. After cell apCell[0] is written to the
7170 ** page body, a 16-bit offset is written to pCellptr. And so on, for each
7171 ** cell in the array. It is the responsibility of the caller to ensure
7172 ** that it is safe to overwrite this part of the cell-pointer array.
7174 ** When this function is called, *ppData points to the start of the
7175 ** content area on page pPg. If the size of the content area is extended,
7176 ** *ppData is updated to point to the new start of the content area
7177 ** before returning.
7179 ** Finally, argument pBegin points to the byte immediately following the
7180 ** end of the space required by this page for the cell-pointer area (for
7181 ** all cells - not just those inserted by the current call). If the content
7182 ** area must be extended to before this point in order to accomodate all
7183 ** cells in apCell[], then the cells do not fit and non-zero is returned.
7185 static int pageInsertArray(
7186 MemPage *pPg, /* Page to add cells to */
7187 u8 *pBegin, /* End of cell-pointer array */
7188 u8 **ppData, /* IN/OUT: Page content-area pointer */
7189 u8 *pCellptr, /* Pointer to cell-pointer area */
7190 int iFirst, /* Index of first cell to add */
7191 int nCell, /* Number of cells to add to pPg */
7192 CellArray *pCArray /* Array of cells */
7194 int i = iFirst; /* Loop counter - cell index to insert */
7195 u8 *aData = pPg->aData; /* Complete page */
7196 u8 *pData = *ppData; /* Content area. A subset of aData[] */
7197 int iEnd = iFirst + nCell; /* End of loop. One past last cell to ins */
7198 int k; /* Current slot in pCArray->apEnd[] */
7199 u8 *pEnd; /* Maximum extent of cell data */
7200 assert( CORRUPT_DB || pPg->hdrOffset==0 ); /* Never called on page 1 */
7201 if( iEnd<=iFirst ) return 0;
7202 for(k=0; pCArray->ixNx[k]<=i && ALWAYS(k<NB*2); k++){}
7203 pEnd = pCArray->apEnd[k];
7204 while( 1 /*Exit by break*/ ){
7205 int sz, rc;
7206 u8 *pSlot;
7207 assert( pCArray->szCell[i]!=0 );
7208 sz = pCArray->szCell[i];
7209 if( (aData[1]==0 && aData[2]==0) || (pSlot = pageFindSlot(pPg,sz,&rc))==0 ){
7210 if( (pData - pBegin)<sz ) return 1;
7211 pData -= sz;
7212 pSlot = pData;
7214 /* pSlot and pCArray->apCell[i] will never overlap on a well-formed
7215 ** database. But they might for a corrupt database. Hence use memmove()
7216 ** since memcpy() sends SIGABORT with overlapping buffers on OpenBSD */
7217 assert( (pSlot+sz)<=pCArray->apCell[i]
7218 || pSlot>=(pCArray->apCell[i]+sz)
7219 || CORRUPT_DB );
7220 if( (uptr)(pCArray->apCell[i]+sz)>(uptr)pEnd
7221 && (uptr)(pCArray->apCell[i])<(uptr)pEnd
7223 assert( CORRUPT_DB );
7224 (void)SQLITE_CORRUPT_BKPT;
7225 return 1;
7227 memmove(pSlot, pCArray->apCell[i], sz);
7228 put2byte(pCellptr, (pSlot - aData));
7229 pCellptr += 2;
7230 i++;
7231 if( i>=iEnd ) break;
7232 if( pCArray->ixNx[k]<=i ){
7233 k++;
7234 pEnd = pCArray->apEnd[k];
7237 *ppData = pData;
7238 return 0;
7242 ** The pCArray object contains pointers to b-tree cells and their sizes.
7244 ** This function adds the space associated with each cell in the array
7245 ** that is currently stored within the body of pPg to the pPg free-list.
7246 ** The cell-pointers and other fields of the page are not updated.
7248 ** This function returns the total number of cells added to the free-list.
7250 static int pageFreeArray(
7251 MemPage *pPg, /* Page to edit */
7252 int iFirst, /* First cell to delete */
7253 int nCell, /* Cells to delete */
7254 CellArray *pCArray /* Array of cells */
7256 u8 * const aData = pPg->aData;
7257 u8 * const pEnd = &aData[pPg->pBt->usableSize];
7258 u8 * const pStart = &aData[pPg->hdrOffset + 8 + pPg->childPtrSize];
7259 int nRet = 0;
7260 int i;
7261 int iEnd = iFirst + nCell;
7262 u8 *pFree = 0;
7263 int szFree = 0;
7265 for(i=iFirst; i<iEnd; i++){
7266 u8 *pCell = pCArray->apCell[i];
7267 if( SQLITE_WITHIN(pCell, pStart, pEnd) ){
7268 int sz;
7269 /* No need to use cachedCellSize() here. The sizes of all cells that
7270 ** are to be freed have already been computing while deciding which
7271 ** cells need freeing */
7272 sz = pCArray->szCell[i]; assert( sz>0 );
7273 if( pFree!=(pCell + sz) ){
7274 if( pFree ){
7275 assert( pFree>aData && (pFree - aData)<65536 );
7276 freeSpace(pPg, (u16)(pFree - aData), szFree);
7278 pFree = pCell;
7279 szFree = sz;
7280 if( pFree+sz>pEnd ){
7281 return 0;
7283 }else{
7284 pFree = pCell;
7285 szFree += sz;
7287 nRet++;
7290 if( pFree ){
7291 assert( pFree>aData && (pFree - aData)<65536 );
7292 freeSpace(pPg, (u16)(pFree - aData), szFree);
7294 return nRet;
7298 ** pCArray contains pointers to and sizes of all cells in the page being
7299 ** balanced. The current page, pPg, has pPg->nCell cells starting with
7300 ** pCArray->apCell[iOld]. After balancing, this page should hold nNew cells
7301 ** starting at apCell[iNew].
7303 ** This routine makes the necessary adjustments to pPg so that it contains
7304 ** the correct cells after being balanced.
7306 ** The pPg->nFree field is invalid when this function returns. It is the
7307 ** responsibility of the caller to set it correctly.
7309 static int editPage(
7310 MemPage *pPg, /* Edit this page */
7311 int iOld, /* Index of first cell currently on page */
7312 int iNew, /* Index of new first cell on page */
7313 int nNew, /* Final number of cells on page */
7314 CellArray *pCArray /* Array of cells and sizes */
7316 u8 * const aData = pPg->aData;
7317 const int hdr = pPg->hdrOffset;
7318 u8 *pBegin = &pPg->aCellIdx[nNew * 2];
7319 int nCell = pPg->nCell; /* Cells stored on pPg */
7320 u8 *pData;
7321 u8 *pCellptr;
7322 int i;
7323 int iOldEnd = iOld + pPg->nCell + pPg->nOverflow;
7324 int iNewEnd = iNew + nNew;
7326 #ifdef SQLITE_DEBUG
7327 u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
7328 memcpy(pTmp, aData, pPg->pBt->usableSize);
7329 #endif
7331 /* Remove cells from the start and end of the page */
7332 assert( nCell>=0 );
7333 if( iOld<iNew ){
7334 int nShift = pageFreeArray(pPg, iOld, iNew-iOld, pCArray);
7335 if( NEVER(nShift>nCell) ) return SQLITE_CORRUPT_BKPT;
7336 memmove(pPg->aCellIdx, &pPg->aCellIdx[nShift*2], nCell*2);
7337 nCell -= nShift;
7339 if( iNewEnd < iOldEnd ){
7340 int nTail = pageFreeArray(pPg, iNewEnd, iOldEnd - iNewEnd, pCArray);
7341 assert( nCell>=nTail );
7342 nCell -= nTail;
7345 pData = &aData[get2byteNotZero(&aData[hdr+5])];
7346 if( pData<pBegin ) goto editpage_fail;
7347 if( pData>pPg->aDataEnd ) goto editpage_fail;
7349 /* Add cells to the start of the page */
7350 if( iNew<iOld ){
7351 int nAdd = MIN(nNew,iOld-iNew);
7352 assert( (iOld-iNew)<nNew || nCell==0 || CORRUPT_DB );
7353 assert( nAdd>=0 );
7354 pCellptr = pPg->aCellIdx;
7355 memmove(&pCellptr[nAdd*2], pCellptr, nCell*2);
7356 if( pageInsertArray(
7357 pPg, pBegin, &pData, pCellptr,
7358 iNew, nAdd, pCArray
7359 ) ) goto editpage_fail;
7360 nCell += nAdd;
7363 /* Add any overflow cells */
7364 for(i=0; i<pPg->nOverflow; i++){
7365 int iCell = (iOld + pPg->aiOvfl[i]) - iNew;
7366 if( iCell>=0 && iCell<nNew ){
7367 pCellptr = &pPg->aCellIdx[iCell * 2];
7368 if( nCell>iCell ){
7369 memmove(&pCellptr[2], pCellptr, (nCell - iCell) * 2);
7371 nCell++;
7372 cachedCellSize(pCArray, iCell+iNew);
7373 if( pageInsertArray(
7374 pPg, pBegin, &pData, pCellptr,
7375 iCell+iNew, 1, pCArray
7376 ) ) goto editpage_fail;
7380 /* Append cells to the end of the page */
7381 assert( nCell>=0 );
7382 pCellptr = &pPg->aCellIdx[nCell*2];
7383 if( pageInsertArray(
7384 pPg, pBegin, &pData, pCellptr,
7385 iNew+nCell, nNew-nCell, pCArray
7386 ) ) goto editpage_fail;
7388 pPg->nCell = nNew;
7389 pPg->nOverflow = 0;
7391 put2byte(&aData[hdr+3], pPg->nCell);
7392 put2byte(&aData[hdr+5], pData - aData);
7394 #ifdef SQLITE_DEBUG
7395 for(i=0; i<nNew && !CORRUPT_DB; i++){
7396 u8 *pCell = pCArray->apCell[i+iNew];
7397 int iOff = get2byteAligned(&pPg->aCellIdx[i*2]);
7398 if( SQLITE_WITHIN(pCell, aData, &aData[pPg->pBt->usableSize]) ){
7399 pCell = &pTmp[pCell - aData];
7401 assert( 0==memcmp(pCell, &aData[iOff],
7402 pCArray->pRef->xCellSize(pCArray->pRef, pCArray->apCell[i+iNew])) );
7404 #endif
7406 return SQLITE_OK;
7407 editpage_fail:
7408 /* Unable to edit this page. Rebuild it from scratch instead. */
7409 populateCellCache(pCArray, iNew, nNew);
7410 return rebuildPage(pCArray, iNew, nNew, pPg);
7414 #ifndef SQLITE_OMIT_QUICKBALANCE
7416 ** This version of balance() handles the common special case where
7417 ** a new entry is being inserted on the extreme right-end of the
7418 ** tree, in other words, when the new entry will become the largest
7419 ** entry in the tree.
7421 ** Instead of trying to balance the 3 right-most leaf pages, just add
7422 ** a new page to the right-hand side and put the one new entry in
7423 ** that page. This leaves the right side of the tree somewhat
7424 ** unbalanced. But odds are that we will be inserting new entries
7425 ** at the end soon afterwards so the nearly empty page will quickly
7426 ** fill up. On average.
7428 ** pPage is the leaf page which is the right-most page in the tree.
7429 ** pParent is its parent. pPage must have a single overflow entry
7430 ** which is also the right-most entry on the page.
7432 ** The pSpace buffer is used to store a temporary copy of the divider
7433 ** cell that will be inserted into pParent. Such a cell consists of a 4
7434 ** byte page number followed by a variable length integer. In other
7435 ** words, at most 13 bytes. Hence the pSpace buffer must be at
7436 ** least 13 bytes in size.
7438 static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
7439 BtShared *const pBt = pPage->pBt; /* B-Tree Database */
7440 MemPage *pNew; /* Newly allocated page */
7441 int rc; /* Return Code */
7442 Pgno pgnoNew; /* Page number of pNew */
7444 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
7445 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
7446 assert( pPage->nOverflow==1 );
7448 if( pPage->nCell==0 ) return SQLITE_CORRUPT_BKPT; /* dbfuzz001.test */
7449 assert( pPage->nFree>=0 );
7450 assert( pParent->nFree>=0 );
7452 /* Allocate a new page. This page will become the right-sibling of
7453 ** pPage. Make the parent page writable, so that the new divider cell
7454 ** may be inserted. If both these operations are successful, proceed.
7456 rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
7458 if( rc==SQLITE_OK ){
7460 u8 *pOut = &pSpace[4];
7461 u8 *pCell = pPage->apOvfl[0];
7462 u16 szCell = pPage->xCellSize(pPage, pCell);
7463 u8 *pStop;
7464 CellArray b;
7466 assert( sqlite3PagerIswriteable(pNew->pDbPage) );
7467 assert( CORRUPT_DB || pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
7468 zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
7469 b.nCell = 1;
7470 b.pRef = pPage;
7471 b.apCell = &pCell;
7472 b.szCell = &szCell;
7473 b.apEnd[0] = pPage->aDataEnd;
7474 b.ixNx[0] = 2;
7475 rc = rebuildPage(&b, 0, 1, pNew);
7476 if( NEVER(rc) ){
7477 releasePage(pNew);
7478 return rc;
7480 pNew->nFree = pBt->usableSize - pNew->cellOffset - 2 - szCell;
7482 /* If this is an auto-vacuum database, update the pointer map
7483 ** with entries for the new page, and any pointer from the
7484 ** cell on the page to an overflow page. If either of these
7485 ** operations fails, the return code is set, but the contents
7486 ** of the parent page are still manipulated by thh code below.
7487 ** That is Ok, at this point the parent page is guaranteed to
7488 ** be marked as dirty. Returning an error code will cause a
7489 ** rollback, undoing any changes made to the parent page.
7491 if( ISAUTOVACUUM ){
7492 ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
7493 if( szCell>pNew->minLocal ){
7494 ptrmapPutOvflPtr(pNew, pNew, pCell, &rc);
7498 /* Create a divider cell to insert into pParent. The divider cell
7499 ** consists of a 4-byte page number (the page number of pPage) and
7500 ** a variable length key value (which must be the same value as the
7501 ** largest key on pPage).
7503 ** To find the largest key value on pPage, first find the right-most
7504 ** cell on pPage. The first two fields of this cell are the
7505 ** record-length (a variable length integer at most 32-bits in size)
7506 ** and the key value (a variable length integer, may have any value).
7507 ** The first of the while(...) loops below skips over the record-length
7508 ** field. The second while(...) loop copies the key value from the
7509 ** cell on pPage into the pSpace buffer.
7511 pCell = findCell(pPage, pPage->nCell-1);
7512 pStop = &pCell[9];
7513 while( (*(pCell++)&0x80) && pCell<pStop );
7514 pStop = &pCell[9];
7515 while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
7517 /* Insert the new divider cell into pParent. */
7518 if( rc==SQLITE_OK ){
7519 insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
7520 0, pPage->pgno, &rc);
7523 /* Set the right-child pointer of pParent to point to the new page. */
7524 put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
7526 /* Release the reference to the new page. */
7527 releasePage(pNew);
7530 return rc;
7532 #endif /* SQLITE_OMIT_QUICKBALANCE */
7534 #if 0
7536 ** This function does not contribute anything to the operation of SQLite.
7537 ** it is sometimes activated temporarily while debugging code responsible
7538 ** for setting pointer-map entries.
7540 static int ptrmapCheckPages(MemPage **apPage, int nPage){
7541 int i, j;
7542 for(i=0; i<nPage; i++){
7543 Pgno n;
7544 u8 e;
7545 MemPage *pPage = apPage[i];
7546 BtShared *pBt = pPage->pBt;
7547 assert( pPage->isInit );
7549 for(j=0; j<pPage->nCell; j++){
7550 CellInfo info;
7551 u8 *z;
7553 z = findCell(pPage, j);
7554 pPage->xParseCell(pPage, z, &info);
7555 if( info.nLocal<info.nPayload ){
7556 Pgno ovfl = get4byte(&z[info.nSize-4]);
7557 ptrmapGet(pBt, ovfl, &e, &n);
7558 assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
7560 if( !pPage->leaf ){
7561 Pgno child = get4byte(z);
7562 ptrmapGet(pBt, child, &e, &n);
7563 assert( n==pPage->pgno && e==PTRMAP_BTREE );
7566 if( !pPage->leaf ){
7567 Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
7568 ptrmapGet(pBt, child, &e, &n);
7569 assert( n==pPage->pgno && e==PTRMAP_BTREE );
7572 return 1;
7574 #endif
7577 ** This function is used to copy the contents of the b-tree node stored
7578 ** on page pFrom to page pTo. If page pFrom was not a leaf page, then
7579 ** the pointer-map entries for each child page are updated so that the
7580 ** parent page stored in the pointer map is page pTo. If pFrom contained
7581 ** any cells with overflow page pointers, then the corresponding pointer
7582 ** map entries are also updated so that the parent page is page pTo.
7584 ** If pFrom is currently carrying any overflow cells (entries in the
7585 ** MemPage.apOvfl[] array), they are not copied to pTo.
7587 ** Before returning, page pTo is reinitialized using btreeInitPage().
7589 ** The performance of this function is not critical. It is only used by
7590 ** the balance_shallower() and balance_deeper() procedures, neither of
7591 ** which are called often under normal circumstances.
7593 static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
7594 if( (*pRC)==SQLITE_OK ){
7595 BtShared * const pBt = pFrom->pBt;
7596 u8 * const aFrom = pFrom->aData;
7597 u8 * const aTo = pTo->aData;
7598 int const iFromHdr = pFrom->hdrOffset;
7599 int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
7600 int rc;
7601 int iData;
7604 assert( pFrom->isInit );
7605 assert( pFrom->nFree>=iToHdr );
7606 assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
7608 /* Copy the b-tree node content from page pFrom to page pTo. */
7609 iData = get2byte(&aFrom[iFromHdr+5]);
7610 memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
7611 memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
7613 /* Reinitialize page pTo so that the contents of the MemPage structure
7614 ** match the new data. The initialization of pTo can actually fail under
7615 ** fairly obscure circumstances, even though it is a copy of initialized
7616 ** page pFrom.
7618 pTo->isInit = 0;
7619 rc = btreeInitPage(pTo);
7620 if( rc==SQLITE_OK ) rc = btreeComputeFreeSpace(pTo);
7621 if( rc!=SQLITE_OK ){
7622 *pRC = rc;
7623 return;
7626 /* If this is an auto-vacuum database, update the pointer-map entries
7627 ** for any b-tree or overflow pages that pTo now contains the pointers to.
7629 if( ISAUTOVACUUM ){
7630 *pRC = setChildPtrmaps(pTo);
7636 ** This routine redistributes cells on the iParentIdx'th child of pParent
7637 ** (hereafter "the page") and up to 2 siblings so that all pages have about the
7638 ** same amount of free space. Usually a single sibling on either side of the
7639 ** page are used in the balancing, though both siblings might come from one
7640 ** side if the page is the first or last child of its parent. If the page
7641 ** has fewer than 2 siblings (something which can only happen if the page
7642 ** is a root page or a child of a root page) then all available siblings
7643 ** participate in the balancing.
7645 ** The number of siblings of the page might be increased or decreased by
7646 ** one or two in an effort to keep pages nearly full but not over full.
7648 ** Note that when this routine is called, some of the cells on the page
7649 ** might not actually be stored in MemPage.aData[]. This can happen
7650 ** if the page is overfull. This routine ensures that all cells allocated
7651 ** to the page and its siblings fit into MemPage.aData[] before returning.
7653 ** In the course of balancing the page and its siblings, cells may be
7654 ** inserted into or removed from the parent page (pParent). Doing so
7655 ** may cause the parent page to become overfull or underfull. If this
7656 ** happens, it is the responsibility of the caller to invoke the correct
7657 ** balancing routine to fix this problem (see the balance() routine).
7659 ** If this routine fails for any reason, it might leave the database
7660 ** in a corrupted state. So if this routine fails, the database should
7661 ** be rolled back.
7663 ** The third argument to this function, aOvflSpace, is a pointer to a
7664 ** buffer big enough to hold one page. If while inserting cells into the parent
7665 ** page (pParent) the parent page becomes overfull, this buffer is
7666 ** used to store the parent's overflow cells. Because this function inserts
7667 ** a maximum of four divider cells into the parent page, and the maximum
7668 ** size of a cell stored within an internal node is always less than 1/4
7669 ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
7670 ** enough for all overflow cells.
7672 ** If aOvflSpace is set to a null pointer, this function returns
7673 ** SQLITE_NOMEM.
7675 static int balance_nonroot(
7676 MemPage *pParent, /* Parent page of siblings being balanced */
7677 int iParentIdx, /* Index of "the page" in pParent */
7678 u8 *aOvflSpace, /* page-size bytes of space for parent ovfl */
7679 int isRoot, /* True if pParent is a root-page */
7680 int bBulk /* True if this call is part of a bulk load */
7682 BtShared *pBt; /* The whole database */
7683 int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */
7684 int nNew = 0; /* Number of pages in apNew[] */
7685 int nOld; /* Number of pages in apOld[] */
7686 int i, j, k; /* Loop counters */
7687 int nxDiv; /* Next divider slot in pParent->aCell[] */
7688 int rc = SQLITE_OK; /* The return code */
7689 u16 leafCorrection; /* 4 if pPage is a leaf. 0 if not */
7690 int leafData; /* True if pPage is a leaf of a LEAFDATA tree */
7691 int usableSpace; /* Bytes in pPage beyond the header */
7692 int pageFlags; /* Value of pPage->aData[0] */
7693 int iSpace1 = 0; /* First unused byte of aSpace1[] */
7694 int iOvflSpace = 0; /* First unused byte of aOvflSpace[] */
7695 int szScratch; /* Size of scratch memory requested */
7696 MemPage *apOld[NB]; /* pPage and up to two siblings */
7697 MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */
7698 u8 *pRight; /* Location in parent of right-sibling pointer */
7699 u8 *apDiv[NB-1]; /* Divider cells in pParent */
7700 int cntNew[NB+2]; /* Index in b.paCell[] of cell after i-th page */
7701 int cntOld[NB+2]; /* Old index in b.apCell[] */
7702 int szNew[NB+2]; /* Combined size of cells placed on i-th page */
7703 u8 *aSpace1; /* Space for copies of dividers cells */
7704 Pgno pgno; /* Temp var to store a page number in */
7705 u8 abDone[NB+2]; /* True after i'th new page is populated */
7706 Pgno aPgno[NB+2]; /* Page numbers of new pages before shuffling */
7707 Pgno aPgOrder[NB+2]; /* Copy of aPgno[] used for sorting pages */
7708 u16 aPgFlags[NB+2]; /* flags field of new pages before shuffling */
7709 CellArray b; /* Parsed information on cells being balanced */
7711 memset(abDone, 0, sizeof(abDone));
7712 memset(&b, 0, sizeof(b));
7713 pBt = pParent->pBt;
7714 assert( sqlite3_mutex_held(pBt->mutex) );
7715 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
7717 /* At this point pParent may have at most one overflow cell. And if
7718 ** this overflow cell is present, it must be the cell with
7719 ** index iParentIdx. This scenario comes about when this function
7720 ** is called (indirectly) from sqlite3BtreeDelete().
7722 assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
7723 assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
7725 if( !aOvflSpace ){
7726 return SQLITE_NOMEM_BKPT;
7728 assert( pParent->nFree>=0 );
7730 /* Find the sibling pages to balance. Also locate the cells in pParent
7731 ** that divide the siblings. An attempt is made to find NN siblings on
7732 ** either side of pPage. More siblings are taken from one side, however,
7733 ** if there are fewer than NN siblings on the other side. If pParent
7734 ** has NB or fewer children then all children of pParent are taken.
7736 ** This loop also drops the divider cells from the parent page. This
7737 ** way, the remainder of the function does not have to deal with any
7738 ** overflow cells in the parent page, since if any existed they will
7739 ** have already been removed.
7741 i = pParent->nOverflow + pParent->nCell;
7742 if( i<2 ){
7743 nxDiv = 0;
7744 }else{
7745 assert( bBulk==0 || bBulk==1 );
7746 if( iParentIdx==0 ){
7747 nxDiv = 0;
7748 }else if( iParentIdx==i ){
7749 nxDiv = i-2+bBulk;
7750 }else{
7751 nxDiv = iParentIdx-1;
7753 i = 2-bBulk;
7755 nOld = i+1;
7756 if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
7757 pRight = &pParent->aData[pParent->hdrOffset+8];
7758 }else{
7759 pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
7761 pgno = get4byte(pRight);
7762 while( 1 ){
7763 if( rc==SQLITE_OK ){
7764 rc = getAndInitPage(pBt, pgno, &apOld[i], 0, 0);
7766 if( rc ){
7767 memset(apOld, 0, (i+1)*sizeof(MemPage*));
7768 goto balance_cleanup;
7770 if( apOld[i]->nFree<0 ){
7771 rc = btreeComputeFreeSpace(apOld[i]);
7772 if( rc ){
7773 memset(apOld, 0, (i)*sizeof(MemPage*));
7774 goto balance_cleanup;
7777 nMaxCells += apOld[i]->nCell + ArraySize(pParent->apOvfl);
7778 if( (i--)==0 ) break;
7780 if( pParent->nOverflow && i+nxDiv==pParent->aiOvfl[0] ){
7781 apDiv[i] = pParent->apOvfl[0];
7782 pgno = get4byte(apDiv[i]);
7783 szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
7784 pParent->nOverflow = 0;
7785 }else{
7786 apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
7787 pgno = get4byte(apDiv[i]);
7788 szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
7790 /* Drop the cell from the parent page. apDiv[i] still points to
7791 ** the cell within the parent, even though it has been dropped.
7792 ** This is safe because dropping a cell only overwrites the first
7793 ** four bytes of it, and this function does not need the first
7794 ** four bytes of the divider cell. So the pointer is safe to use
7795 ** later on.
7797 ** But not if we are in secure-delete mode. In secure-delete mode,
7798 ** the dropCell() routine will overwrite the entire cell with zeroes.
7799 ** In this case, temporarily copy the cell into the aOvflSpace[]
7800 ** buffer. It will be copied out again as soon as the aSpace[] buffer
7801 ** is allocated. */
7802 if( pBt->btsFlags & BTS_FAST_SECURE ){
7803 int iOff;
7805 /* If the following if() condition is not true, the db is corrupted.
7806 ** The call to dropCell() below will detect this. */
7807 iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
7808 if( (iOff+szNew[i])<=(int)pBt->usableSize ){
7809 memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
7810 apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
7813 dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
7817 /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
7818 ** alignment */
7819 nMaxCells = (nMaxCells + 3)&~3;
7822 ** Allocate space for memory structures
7824 szScratch =
7825 nMaxCells*sizeof(u8*) /* b.apCell */
7826 + nMaxCells*sizeof(u16) /* b.szCell */
7827 + pBt->pageSize; /* aSpace1 */
7829 assert( szScratch<=7*(int)pBt->pageSize );
7830 b.apCell = sqlite3StackAllocRaw(0, szScratch );
7831 if( b.apCell==0 ){
7832 rc = SQLITE_NOMEM_BKPT;
7833 goto balance_cleanup;
7835 b.szCell = (u16*)&b.apCell[nMaxCells];
7836 aSpace1 = (u8*)&b.szCell[nMaxCells];
7837 assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
7840 ** Load pointers to all cells on sibling pages and the divider cells
7841 ** into the local b.apCell[] array. Make copies of the divider cells
7842 ** into space obtained from aSpace1[]. The divider cells have already
7843 ** been removed from pParent.
7845 ** If the siblings are on leaf pages, then the child pointers of the
7846 ** divider cells are stripped from the cells before they are copied
7847 ** into aSpace1[]. In this way, all cells in b.apCell[] are without
7848 ** child pointers. If siblings are not leaves, then all cell in
7849 ** b.apCell[] include child pointers. Either way, all cells in b.apCell[]
7850 ** are alike.
7852 ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf.
7853 ** leafData: 1 if pPage holds key+data and pParent holds only keys.
7855 b.pRef = apOld[0];
7856 leafCorrection = b.pRef->leaf*4;
7857 leafData = b.pRef->intKeyLeaf;
7858 for(i=0; i<nOld; i++){
7859 MemPage *pOld = apOld[i];
7860 int limit = pOld->nCell;
7861 u8 *aData = pOld->aData;
7862 u16 maskPage = pOld->maskPage;
7863 u8 *piCell = aData + pOld->cellOffset;
7864 u8 *piEnd;
7865 VVA_ONLY( int nCellAtStart = b.nCell; )
7867 /* Verify that all sibling pages are of the same "type" (table-leaf,
7868 ** table-interior, index-leaf, or index-interior).
7870 if( pOld->aData[0]!=apOld[0]->aData[0] ){
7871 rc = SQLITE_CORRUPT_BKPT;
7872 goto balance_cleanup;
7875 /* Load b.apCell[] with pointers to all cells in pOld. If pOld
7876 ** contains overflow cells, include them in the b.apCell[] array
7877 ** in the correct spot.
7879 ** Note that when there are multiple overflow cells, it is always the
7880 ** case that they are sequential and adjacent. This invariant arises
7881 ** because multiple overflows can only occurs when inserting divider
7882 ** cells into a parent on a prior balance, and divider cells are always
7883 ** adjacent and are inserted in order. There is an assert() tagged
7884 ** with "NOTE 1" in the overflow cell insertion loop to prove this
7885 ** invariant.
7887 ** This must be done in advance. Once the balance starts, the cell
7888 ** offset section of the btree page will be overwritten and we will no
7889 ** long be able to find the cells if a pointer to each cell is not saved
7890 ** first.
7892 memset(&b.szCell[b.nCell], 0, sizeof(b.szCell[0])*(limit+pOld->nOverflow));
7893 if( pOld->nOverflow>0 ){
7894 if( NEVER(limit<pOld->aiOvfl[0]) ){
7895 rc = SQLITE_CORRUPT_BKPT;
7896 goto balance_cleanup;
7898 limit = pOld->aiOvfl[0];
7899 for(j=0; j<limit; j++){
7900 b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
7901 piCell += 2;
7902 b.nCell++;
7904 for(k=0; k<pOld->nOverflow; k++){
7905 assert( k==0 || pOld->aiOvfl[k-1]+1==pOld->aiOvfl[k] );/* NOTE 1 */
7906 b.apCell[b.nCell] = pOld->apOvfl[k];
7907 b.nCell++;
7910 piEnd = aData + pOld->cellOffset + 2*pOld->nCell;
7911 while( piCell<piEnd ){
7912 assert( b.nCell<nMaxCells );
7913 b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
7914 piCell += 2;
7915 b.nCell++;
7917 assert( (b.nCell-nCellAtStart)==(pOld->nCell+pOld->nOverflow) );
7919 cntOld[i] = b.nCell;
7920 if( i<nOld-1 && !leafData){
7921 u16 sz = (u16)szNew[i];
7922 u8 *pTemp;
7923 assert( b.nCell<nMaxCells );
7924 b.szCell[b.nCell] = sz;
7925 pTemp = &aSpace1[iSpace1];
7926 iSpace1 += sz;
7927 assert( sz<=pBt->maxLocal+23 );
7928 assert( iSpace1 <= (int)pBt->pageSize );
7929 memcpy(pTemp, apDiv[i], sz);
7930 b.apCell[b.nCell] = pTemp+leafCorrection;
7931 assert( leafCorrection==0 || leafCorrection==4 );
7932 b.szCell[b.nCell] = b.szCell[b.nCell] - leafCorrection;
7933 if( !pOld->leaf ){
7934 assert( leafCorrection==0 );
7935 assert( pOld->hdrOffset==0 || CORRUPT_DB );
7936 /* The right pointer of the child page pOld becomes the left
7937 ** pointer of the divider cell */
7938 memcpy(b.apCell[b.nCell], &pOld->aData[8], 4);
7939 }else{
7940 assert( leafCorrection==4 );
7941 while( b.szCell[b.nCell]<4 ){
7942 /* Do not allow any cells smaller than 4 bytes. If a smaller cell
7943 ** does exist, pad it with 0x00 bytes. */
7944 assert( b.szCell[b.nCell]==3 || CORRUPT_DB );
7945 assert( b.apCell[b.nCell]==&aSpace1[iSpace1-3] || CORRUPT_DB );
7946 aSpace1[iSpace1++] = 0x00;
7947 b.szCell[b.nCell]++;
7950 b.nCell++;
7955 ** Figure out the number of pages needed to hold all b.nCell cells.
7956 ** Store this number in "k". Also compute szNew[] which is the total
7957 ** size of all cells on the i-th page and cntNew[] which is the index
7958 ** in b.apCell[] of the cell that divides page i from page i+1.
7959 ** cntNew[k] should equal b.nCell.
7961 ** Values computed by this block:
7963 ** k: The total number of sibling pages
7964 ** szNew[i]: Spaced used on the i-th sibling page.
7965 ** cntNew[i]: Index in b.apCell[] and b.szCell[] for the first cell to
7966 ** the right of the i-th sibling page.
7967 ** usableSpace: Number of bytes of space available on each sibling.
7970 usableSpace = pBt->usableSize - 12 + leafCorrection;
7971 for(i=k=0; i<nOld; i++, k++){
7972 MemPage *p = apOld[i];
7973 b.apEnd[k] = p->aDataEnd;
7974 b.ixNx[k] = cntOld[i];
7975 if( k && b.ixNx[k]==b.ixNx[k-1] ){
7976 k--; /* Omit b.ixNx[] entry for child pages with no cells */
7978 if( !leafData ){
7979 k++;
7980 b.apEnd[k] = pParent->aDataEnd;
7981 b.ixNx[k] = cntOld[i]+1;
7983 assert( p->nFree>=0 );
7984 szNew[i] = usableSpace - p->nFree;
7985 for(j=0; j<p->nOverflow; j++){
7986 szNew[i] += 2 + p->xCellSize(p, p->apOvfl[j]);
7988 cntNew[i] = cntOld[i];
7990 k = nOld;
7991 for(i=0; i<k; i++){
7992 int sz;
7993 while( szNew[i]>usableSpace ){
7994 if( i+1>=k ){
7995 k = i+2;
7996 if( k>NB+2 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
7997 szNew[k-1] = 0;
7998 cntNew[k-1] = b.nCell;
8000 sz = 2 + cachedCellSize(&b, cntNew[i]-1);
8001 szNew[i] -= sz;
8002 if( !leafData ){
8003 if( cntNew[i]<b.nCell ){
8004 sz = 2 + cachedCellSize(&b, cntNew[i]);
8005 }else{
8006 sz = 0;
8009 szNew[i+1] += sz;
8010 cntNew[i]--;
8012 while( cntNew[i]<b.nCell ){
8013 sz = 2 + cachedCellSize(&b, cntNew[i]);
8014 if( szNew[i]+sz>usableSpace ) break;
8015 szNew[i] += sz;
8016 cntNew[i]++;
8017 if( !leafData ){
8018 if( cntNew[i]<b.nCell ){
8019 sz = 2 + cachedCellSize(&b, cntNew[i]);
8020 }else{
8021 sz = 0;
8024 szNew[i+1] -= sz;
8026 if( cntNew[i]>=b.nCell ){
8027 k = i+1;
8028 }else if( cntNew[i] <= (i>0 ? cntNew[i-1] : 0) ){
8029 rc = SQLITE_CORRUPT_BKPT;
8030 goto balance_cleanup;
8035 ** The packing computed by the previous block is biased toward the siblings
8036 ** on the left side (siblings with smaller keys). The left siblings are
8037 ** always nearly full, while the right-most sibling might be nearly empty.
8038 ** The next block of code attempts to adjust the packing of siblings to
8039 ** get a better balance.
8041 ** This adjustment is more than an optimization. The packing above might
8042 ** be so out of balance as to be illegal. For example, the right-most
8043 ** sibling might be completely empty. This adjustment is not optional.
8045 for(i=k-1; i>0; i--){
8046 int szRight = szNew[i]; /* Size of sibling on the right */
8047 int szLeft = szNew[i-1]; /* Size of sibling on the left */
8048 int r; /* Index of right-most cell in left sibling */
8049 int d; /* Index of first cell to the left of right sibling */
8051 r = cntNew[i-1] - 1;
8052 d = r + 1 - leafData;
8053 (void)cachedCellSize(&b, d);
8055 assert( d<nMaxCells );
8056 assert( r<nMaxCells );
8057 (void)cachedCellSize(&b, r);
8058 if( szRight!=0
8059 && (bBulk || szRight+b.szCell[d]+2 > szLeft-(b.szCell[r]+(i==k-1?0:2)))){
8060 break;
8062 szRight += b.szCell[d] + 2;
8063 szLeft -= b.szCell[r] + 2;
8064 cntNew[i-1] = r;
8065 r--;
8066 d--;
8067 }while( r>=0 );
8068 szNew[i] = szRight;
8069 szNew[i-1] = szLeft;
8070 if( cntNew[i-1] <= (i>1 ? cntNew[i-2] : 0) ){
8071 rc = SQLITE_CORRUPT_BKPT;
8072 goto balance_cleanup;
8076 /* Sanity check: For a non-corrupt database file one of the follwing
8077 ** must be true:
8078 ** (1) We found one or more cells (cntNew[0])>0), or
8079 ** (2) pPage is a virtual root page. A virtual root page is when
8080 ** the real root page is page 1 and we are the only child of
8081 ** that page.
8083 assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) || CORRUPT_DB);
8084 TRACE(("BALANCE: old: %d(nc=%d) %d(nc=%d) %d(nc=%d)\n",
8085 apOld[0]->pgno, apOld[0]->nCell,
8086 nOld>=2 ? apOld[1]->pgno : 0, nOld>=2 ? apOld[1]->nCell : 0,
8087 nOld>=3 ? apOld[2]->pgno : 0, nOld>=3 ? apOld[2]->nCell : 0
8091 ** Allocate k new pages. Reuse old pages where possible.
8093 pageFlags = apOld[0]->aData[0];
8094 for(i=0; i<k; i++){
8095 MemPage *pNew;
8096 if( i<nOld ){
8097 pNew = apNew[i] = apOld[i];
8098 apOld[i] = 0;
8099 rc = sqlite3PagerWrite(pNew->pDbPage);
8100 nNew++;
8101 if( sqlite3PagerPageRefcount(pNew->pDbPage)!=1+(i==(iParentIdx-nxDiv))
8102 && rc==SQLITE_OK
8104 rc = SQLITE_CORRUPT_BKPT;
8106 if( rc ) goto balance_cleanup;
8107 }else{
8108 assert( i>0 );
8109 rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0);
8110 if( rc ) goto balance_cleanup;
8111 zeroPage(pNew, pageFlags);
8112 apNew[i] = pNew;
8113 nNew++;
8114 cntOld[i] = b.nCell;
8116 /* Set the pointer-map entry for the new sibling page. */
8117 if( ISAUTOVACUUM ){
8118 ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
8119 if( rc!=SQLITE_OK ){
8120 goto balance_cleanup;
8127 ** Reassign page numbers so that the new pages are in ascending order.
8128 ** This helps to keep entries in the disk file in order so that a scan
8129 ** of the table is closer to a linear scan through the file. That in turn
8130 ** helps the operating system to deliver pages from the disk more rapidly.
8132 ** An O(n^2) insertion sort algorithm is used, but since n is never more
8133 ** than (NB+2) (a small constant), that should not be a problem.
8135 ** When NB==3, this one optimization makes the database about 25% faster
8136 ** for large insertions and deletions.
8138 for(i=0; i<nNew; i++){
8139 aPgOrder[i] = aPgno[i] = apNew[i]->pgno;
8140 aPgFlags[i] = apNew[i]->pDbPage->flags;
8141 for(j=0; j<i; j++){
8142 if( NEVER(aPgno[j]==aPgno[i]) ){
8143 /* This branch is taken if the set of sibling pages somehow contains
8144 ** duplicate entries. This can happen if the database is corrupt.
8145 ** It would be simpler to detect this as part of the loop below, but
8146 ** we do the detection here in order to avoid populating the pager
8147 ** cache with two separate objects associated with the same
8148 ** page number. */
8149 assert( CORRUPT_DB );
8150 rc = SQLITE_CORRUPT_BKPT;
8151 goto balance_cleanup;
8155 for(i=0; i<nNew; i++){
8156 int iBest = 0; /* aPgno[] index of page number to use */
8157 for(j=1; j<nNew; j++){
8158 if( aPgOrder[j]<aPgOrder[iBest] ) iBest = j;
8160 pgno = aPgOrder[iBest];
8161 aPgOrder[iBest] = 0xffffffff;
8162 if( iBest!=i ){
8163 if( iBest>i ){
8164 sqlite3PagerRekey(apNew[iBest]->pDbPage, pBt->nPage+iBest+1, 0);
8166 sqlite3PagerRekey(apNew[i]->pDbPage, pgno, aPgFlags[iBest]);
8167 apNew[i]->pgno = pgno;
8171 TRACE(("BALANCE: new: %d(%d nc=%d) %d(%d nc=%d) %d(%d nc=%d) "
8172 "%d(%d nc=%d) %d(%d nc=%d)\n",
8173 apNew[0]->pgno, szNew[0], cntNew[0],
8174 nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
8175 nNew>=2 ? cntNew[1] - cntNew[0] - !leafData : 0,
8176 nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
8177 nNew>=3 ? cntNew[2] - cntNew[1] - !leafData : 0,
8178 nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
8179 nNew>=4 ? cntNew[3] - cntNew[2] - !leafData : 0,
8180 nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0,
8181 nNew>=5 ? cntNew[4] - cntNew[3] - !leafData : 0
8184 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
8185 assert( nNew>=1 && nNew<=ArraySize(apNew) );
8186 assert( apNew[nNew-1]!=0 );
8187 put4byte(pRight, apNew[nNew-1]->pgno);
8189 /* If the sibling pages are not leaves, ensure that the right-child pointer
8190 ** of the right-most new sibling page is set to the value that was
8191 ** originally in the same field of the right-most old sibling page. */
8192 if( (pageFlags & PTF_LEAF)==0 && nOld!=nNew ){
8193 MemPage *pOld = (nNew>nOld ? apNew : apOld)[nOld-1];
8194 memcpy(&apNew[nNew-1]->aData[8], &pOld->aData[8], 4);
8197 /* Make any required updates to pointer map entries associated with
8198 ** cells stored on sibling pages following the balance operation. Pointer
8199 ** map entries associated with divider cells are set by the insertCell()
8200 ** routine. The associated pointer map entries are:
8202 ** a) if the cell contains a reference to an overflow chain, the
8203 ** entry associated with the first page in the overflow chain, and
8205 ** b) if the sibling pages are not leaves, the child page associated
8206 ** with the cell.
8208 ** If the sibling pages are not leaves, then the pointer map entry
8209 ** associated with the right-child of each sibling may also need to be
8210 ** updated. This happens below, after the sibling pages have been
8211 ** populated, not here.
8213 if( ISAUTOVACUUM ){
8214 MemPage *pOld;
8215 MemPage *pNew = pOld = apNew[0];
8216 int cntOldNext = pNew->nCell + pNew->nOverflow;
8217 int iNew = 0;
8218 int iOld = 0;
8220 for(i=0; i<b.nCell; i++){
8221 u8 *pCell = b.apCell[i];
8222 while( i==cntOldNext ){
8223 iOld++;
8224 assert( iOld<nNew || iOld<nOld );
8225 assert( iOld>=0 && iOld<NB );
8226 pOld = iOld<nNew ? apNew[iOld] : apOld[iOld];
8227 cntOldNext += pOld->nCell + pOld->nOverflow + !leafData;
8229 if( i==cntNew[iNew] ){
8230 pNew = apNew[++iNew];
8231 if( !leafData ) continue;
8234 /* Cell pCell is destined for new sibling page pNew. Originally, it
8235 ** was either part of sibling page iOld (possibly an overflow cell),
8236 ** or else the divider cell to the left of sibling page iOld. So,
8237 ** if sibling page iOld had the same page number as pNew, and if
8238 ** pCell really was a part of sibling page iOld (not a divider or
8239 ** overflow cell), we can skip updating the pointer map entries. */
8240 if( iOld>=nNew
8241 || pNew->pgno!=aPgno[iOld]
8242 || !SQLITE_WITHIN(pCell,pOld->aData,pOld->aDataEnd)
8244 if( !leafCorrection ){
8245 ptrmapPut(pBt, get4byte(pCell), PTRMAP_BTREE, pNew->pgno, &rc);
8247 if( cachedCellSize(&b,i)>pNew->minLocal ){
8248 ptrmapPutOvflPtr(pNew, pOld, pCell, &rc);
8250 if( rc ) goto balance_cleanup;
8255 /* Insert new divider cells into pParent. */
8256 for(i=0; i<nNew-1; i++){
8257 u8 *pCell;
8258 u8 *pTemp;
8259 int sz;
8260 u8 *pSrcEnd;
8261 MemPage *pNew = apNew[i];
8262 j = cntNew[i];
8264 assert( j<nMaxCells );
8265 assert( b.apCell[j]!=0 );
8266 pCell = b.apCell[j];
8267 sz = b.szCell[j] + leafCorrection;
8268 pTemp = &aOvflSpace[iOvflSpace];
8269 if( !pNew->leaf ){
8270 memcpy(&pNew->aData[8], pCell, 4);
8271 }else if( leafData ){
8272 /* If the tree is a leaf-data tree, and the siblings are leaves,
8273 ** then there is no divider cell in b.apCell[]. Instead, the divider
8274 ** cell consists of the integer key for the right-most cell of
8275 ** the sibling-page assembled above only.
8277 CellInfo info;
8278 j--;
8279 pNew->xParseCell(pNew, b.apCell[j], &info);
8280 pCell = pTemp;
8281 sz = 4 + putVarint(&pCell[4], info.nKey);
8282 pTemp = 0;
8283 }else{
8284 pCell -= 4;
8285 /* Obscure case for non-leaf-data trees: If the cell at pCell was
8286 ** previously stored on a leaf node, and its reported size was 4
8287 ** bytes, then it may actually be smaller than this
8288 ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
8289 ** any cell). But it is important to pass the correct size to
8290 ** insertCell(), so reparse the cell now.
8292 ** This can only happen for b-trees used to evaluate "IN (SELECT ...)"
8293 ** and WITHOUT ROWID tables with exactly one column which is the
8294 ** primary key.
8296 if( b.szCell[j]==4 ){
8297 assert(leafCorrection==4);
8298 sz = pParent->xCellSize(pParent, pCell);
8301 iOvflSpace += sz;
8302 assert( sz<=pBt->maxLocal+23 );
8303 assert( iOvflSpace <= (int)pBt->pageSize );
8304 for(k=0; b.ixNx[k]<=i && ALWAYS(k<NB*2); k++){}
8305 pSrcEnd = b.apEnd[k];
8306 if( SQLITE_WITHIN(pSrcEnd, pCell, pCell+sz) ){
8307 rc = SQLITE_CORRUPT_BKPT;
8308 goto balance_cleanup;
8310 insertCell(pParent, nxDiv+i, pCell, sz, pTemp, pNew->pgno, &rc);
8311 if( rc!=SQLITE_OK ) goto balance_cleanup;
8312 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
8315 /* Now update the actual sibling pages. The order in which they are updated
8316 ** is important, as this code needs to avoid disrupting any page from which
8317 ** cells may still to be read. In practice, this means:
8319 ** (1) If cells are moving left (from apNew[iPg] to apNew[iPg-1])
8320 ** then it is not safe to update page apNew[iPg] until after
8321 ** the left-hand sibling apNew[iPg-1] has been updated.
8323 ** (2) If cells are moving right (from apNew[iPg] to apNew[iPg+1])
8324 ** then it is not safe to update page apNew[iPg] until after
8325 ** the right-hand sibling apNew[iPg+1] has been updated.
8327 ** If neither of the above apply, the page is safe to update.
8329 ** The iPg value in the following loop starts at nNew-1 goes down
8330 ** to 0, then back up to nNew-1 again, thus making two passes over
8331 ** the pages. On the initial downward pass, only condition (1) above
8332 ** needs to be tested because (2) will always be true from the previous
8333 ** step. On the upward pass, both conditions are always true, so the
8334 ** upwards pass simply processes pages that were missed on the downward
8335 ** pass.
8337 for(i=1-nNew; i<nNew; i++){
8338 int iPg = i<0 ? -i : i;
8339 assert( iPg>=0 && iPg<nNew );
8340 if( abDone[iPg] ) continue; /* Skip pages already processed */
8341 if( i>=0 /* On the upwards pass, or... */
8342 || cntOld[iPg-1]>=cntNew[iPg-1] /* Condition (1) is true */
8344 int iNew;
8345 int iOld;
8346 int nNewCell;
8348 /* Verify condition (1): If cells are moving left, update iPg
8349 ** only after iPg-1 has already been updated. */
8350 assert( iPg==0 || cntOld[iPg-1]>=cntNew[iPg-1] || abDone[iPg-1] );
8352 /* Verify condition (2): If cells are moving right, update iPg
8353 ** only after iPg+1 has already been updated. */
8354 assert( cntNew[iPg]>=cntOld[iPg] || abDone[iPg+1] );
8356 if( iPg==0 ){
8357 iNew = iOld = 0;
8358 nNewCell = cntNew[0];
8359 }else{
8360 iOld = iPg<nOld ? (cntOld[iPg-1] + !leafData) : b.nCell;
8361 iNew = cntNew[iPg-1] + !leafData;
8362 nNewCell = cntNew[iPg] - iNew;
8365 rc = editPage(apNew[iPg], iOld, iNew, nNewCell, &b);
8366 if( rc ) goto balance_cleanup;
8367 abDone[iPg]++;
8368 apNew[iPg]->nFree = usableSpace-szNew[iPg];
8369 assert( apNew[iPg]->nOverflow==0 );
8370 assert( apNew[iPg]->nCell==nNewCell );
8374 /* All pages have been processed exactly once */
8375 assert( memcmp(abDone, "\01\01\01\01\01", nNew)==0 );
8377 assert( nOld>0 );
8378 assert( nNew>0 );
8380 if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
8381 /* The root page of the b-tree now contains no cells. The only sibling
8382 ** page is the right-child of the parent. Copy the contents of the
8383 ** child page into the parent, decreasing the overall height of the
8384 ** b-tree structure by one. This is described as the "balance-shallower"
8385 ** sub-algorithm in some documentation.
8387 ** If this is an auto-vacuum database, the call to copyNodeContent()
8388 ** sets all pointer-map entries corresponding to database image pages
8389 ** for which the pointer is stored within the content being copied.
8391 ** It is critical that the child page be defragmented before being
8392 ** copied into the parent, because if the parent is page 1 then it will
8393 ** by smaller than the child due to the database header, and so all the
8394 ** free space needs to be up front.
8396 assert( nNew==1 || CORRUPT_DB );
8397 rc = defragmentPage(apNew[0], -1);
8398 testcase( rc!=SQLITE_OK );
8399 assert( apNew[0]->nFree ==
8400 (get2byteNotZero(&apNew[0]->aData[5]) - apNew[0]->cellOffset
8401 - apNew[0]->nCell*2)
8402 || rc!=SQLITE_OK
8404 copyNodeContent(apNew[0], pParent, &rc);
8405 freePage(apNew[0], &rc);
8406 }else if( ISAUTOVACUUM && !leafCorrection ){
8407 /* Fix the pointer map entries associated with the right-child of each
8408 ** sibling page. All other pointer map entries have already been taken
8409 ** care of. */
8410 for(i=0; i<nNew; i++){
8411 u32 key = get4byte(&apNew[i]->aData[8]);
8412 ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
8416 assert( pParent->isInit );
8417 TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
8418 nOld, nNew, b.nCell));
8420 /* Free any old pages that were not reused as new pages.
8422 for(i=nNew; i<nOld; i++){
8423 freePage(apOld[i], &rc);
8426 #if 0
8427 if( ISAUTOVACUUM && rc==SQLITE_OK && apNew[0]->isInit ){
8428 /* The ptrmapCheckPages() contains assert() statements that verify that
8429 ** all pointer map pages are set correctly. This is helpful while
8430 ** debugging. This is usually disabled because a corrupt database may
8431 ** cause an assert() statement to fail. */
8432 ptrmapCheckPages(apNew, nNew);
8433 ptrmapCheckPages(&pParent, 1);
8435 #endif
8438 ** Cleanup before returning.
8440 balance_cleanup:
8441 sqlite3StackFree(0, b.apCell);
8442 for(i=0; i<nOld; i++){
8443 releasePage(apOld[i]);
8445 for(i=0; i<nNew; i++){
8446 releasePage(apNew[i]);
8449 return rc;
8454 ** This function is called when the root page of a b-tree structure is
8455 ** overfull (has one or more overflow pages).
8457 ** A new child page is allocated and the contents of the current root
8458 ** page, including overflow cells, are copied into the child. The root
8459 ** page is then overwritten to make it an empty page with the right-child
8460 ** pointer pointing to the new page.
8462 ** Before returning, all pointer-map entries corresponding to pages
8463 ** that the new child-page now contains pointers to are updated. The
8464 ** entry corresponding to the new right-child pointer of the root
8465 ** page is also updated.
8467 ** If successful, *ppChild is set to contain a reference to the child
8468 ** page and SQLITE_OK is returned. In this case the caller is required
8469 ** to call releasePage() on *ppChild exactly once. If an error occurs,
8470 ** an error code is returned and *ppChild is set to 0.
8472 static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
8473 int rc; /* Return value from subprocedures */
8474 MemPage *pChild = 0; /* Pointer to a new child page */
8475 Pgno pgnoChild = 0; /* Page number of the new child page */
8476 BtShared *pBt = pRoot->pBt; /* The BTree */
8478 assert( pRoot->nOverflow>0 );
8479 assert( sqlite3_mutex_held(pBt->mutex) );
8481 /* Make pRoot, the root page of the b-tree, writable. Allocate a new
8482 ** page that will become the new right-child of pPage. Copy the contents
8483 ** of the node stored on pRoot into the new child page.
8485 rc = sqlite3PagerWrite(pRoot->pDbPage);
8486 if( rc==SQLITE_OK ){
8487 rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
8488 copyNodeContent(pRoot, pChild, &rc);
8489 if( ISAUTOVACUUM ){
8490 ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
8493 if( rc ){
8494 *ppChild = 0;
8495 releasePage(pChild);
8496 return rc;
8498 assert( sqlite3PagerIswriteable(pChild->pDbPage) );
8499 assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
8500 assert( pChild->nCell==pRoot->nCell || CORRUPT_DB );
8502 TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
8504 /* Copy the overflow cells from pRoot to pChild */
8505 memcpy(pChild->aiOvfl, pRoot->aiOvfl,
8506 pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
8507 memcpy(pChild->apOvfl, pRoot->apOvfl,
8508 pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
8509 pChild->nOverflow = pRoot->nOverflow;
8511 /* Zero the contents of pRoot. Then install pChild as the right-child. */
8512 zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
8513 put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
8515 *ppChild = pChild;
8516 return SQLITE_OK;
8520 ** Return SQLITE_CORRUPT if any cursor other than pCur is currently valid
8521 ** on the same B-tree as pCur.
8523 ** This can occur if a database is corrupt with two or more SQL tables
8524 ** pointing to the same b-tree. If an insert occurs on one SQL table
8525 ** and causes a BEFORE TRIGGER to do a secondary insert on the other SQL
8526 ** table linked to the same b-tree. If the secondary insert causes a
8527 ** rebalance, that can change content out from under the cursor on the
8528 ** first SQL table, violating invariants on the first insert.
8530 static int anotherValidCursor(BtCursor *pCur){
8531 BtCursor *pOther;
8532 for(pOther=pCur->pBt->pCursor; pOther; pOther=pOther->pNext){
8533 if( pOther!=pCur
8534 && pOther->eState==CURSOR_VALID
8535 && pOther->pPage==pCur->pPage
8537 return SQLITE_CORRUPT_BKPT;
8540 return SQLITE_OK;
8544 ** The page that pCur currently points to has just been modified in
8545 ** some way. This function figures out if this modification means the
8546 ** tree needs to be balanced, and if so calls the appropriate balancing
8547 ** routine. Balancing routines are:
8549 ** balance_quick()
8550 ** balance_deeper()
8551 ** balance_nonroot()
8553 static int balance(BtCursor *pCur){
8554 int rc = SQLITE_OK;
8555 const int nMin = pCur->pBt->usableSize * 2 / 3;
8556 u8 aBalanceQuickSpace[13];
8557 u8 *pFree = 0;
8559 VVA_ONLY( int balance_quick_called = 0 );
8560 VVA_ONLY( int balance_deeper_called = 0 );
8562 do {
8563 int iPage;
8564 MemPage *pPage = pCur->pPage;
8566 if( NEVER(pPage->nFree<0) && btreeComputeFreeSpace(pPage) ) break;
8567 if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
8568 break;
8569 }else if( (iPage = pCur->iPage)==0 ){
8570 if( pPage->nOverflow && (rc = anotherValidCursor(pCur))==SQLITE_OK ){
8571 /* The root page of the b-tree is overfull. In this case call the
8572 ** balance_deeper() function to create a new child for the root-page
8573 ** and copy the current contents of the root-page to it. The
8574 ** next iteration of the do-loop will balance the child page.
8576 assert( balance_deeper_called==0 );
8577 VVA_ONLY( balance_deeper_called++ );
8578 rc = balance_deeper(pPage, &pCur->apPage[1]);
8579 if( rc==SQLITE_OK ){
8580 pCur->iPage = 1;
8581 pCur->ix = 0;
8582 pCur->aiIdx[0] = 0;
8583 pCur->apPage[0] = pPage;
8584 pCur->pPage = pCur->apPage[1];
8585 assert( pCur->pPage->nOverflow );
8587 }else{
8588 break;
8590 }else{
8591 MemPage * const pParent = pCur->apPage[iPage-1];
8592 int const iIdx = pCur->aiIdx[iPage-1];
8594 rc = sqlite3PagerWrite(pParent->pDbPage);
8595 if( rc==SQLITE_OK && pParent->nFree<0 ){
8596 rc = btreeComputeFreeSpace(pParent);
8598 if( rc==SQLITE_OK ){
8599 #ifndef SQLITE_OMIT_QUICKBALANCE
8600 if( pPage->intKeyLeaf
8601 && pPage->nOverflow==1
8602 && pPage->aiOvfl[0]==pPage->nCell
8603 && pParent->pgno!=1
8604 && pParent->nCell==iIdx
8606 /* Call balance_quick() to create a new sibling of pPage on which
8607 ** to store the overflow cell. balance_quick() inserts a new cell
8608 ** into pParent, which may cause pParent overflow. If this
8609 ** happens, the next iteration of the do-loop will balance pParent
8610 ** use either balance_nonroot() or balance_deeper(). Until this
8611 ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
8612 ** buffer.
8614 ** The purpose of the following assert() is to check that only a
8615 ** single call to balance_quick() is made for each call to this
8616 ** function. If this were not verified, a subtle bug involving reuse
8617 ** of the aBalanceQuickSpace[] might sneak in.
8619 assert( balance_quick_called==0 );
8620 VVA_ONLY( balance_quick_called++ );
8621 rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
8622 }else
8623 #endif
8625 /* In this case, call balance_nonroot() to redistribute cells
8626 ** between pPage and up to 2 of its sibling pages. This involves
8627 ** modifying the contents of pParent, which may cause pParent to
8628 ** become overfull or underfull. The next iteration of the do-loop
8629 ** will balance the parent page to correct this.
8631 ** If the parent page becomes overfull, the overflow cell or cells
8632 ** are stored in the pSpace buffer allocated immediately below.
8633 ** A subsequent iteration of the do-loop will deal with this by
8634 ** calling balance_nonroot() (balance_deeper() may be called first,
8635 ** but it doesn't deal with overflow cells - just moves them to a
8636 ** different page). Once this subsequent call to balance_nonroot()
8637 ** has completed, it is safe to release the pSpace buffer used by
8638 ** the previous call, as the overflow cell data will have been
8639 ** copied either into the body of a database page or into the new
8640 ** pSpace buffer passed to the latter call to balance_nonroot().
8642 u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
8643 rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1,
8644 pCur->hints&BTREE_BULKLOAD);
8645 if( pFree ){
8646 /* If pFree is not NULL, it points to the pSpace buffer used
8647 ** by a previous call to balance_nonroot(). Its contents are
8648 ** now stored either on real database pages or within the
8649 ** new pSpace buffer, so it may be safely freed here. */
8650 sqlite3PageFree(pFree);
8653 /* The pSpace buffer will be freed after the next call to
8654 ** balance_nonroot(), or just before this function returns, whichever
8655 ** comes first. */
8656 pFree = pSpace;
8660 pPage->nOverflow = 0;
8662 /* The next iteration of the do-loop balances the parent page. */
8663 releasePage(pPage);
8664 pCur->iPage--;
8665 assert( pCur->iPage>=0 );
8666 pCur->pPage = pCur->apPage[pCur->iPage];
8668 }while( rc==SQLITE_OK );
8670 if( pFree ){
8671 sqlite3PageFree(pFree);
8673 return rc;
8676 /* Overwrite content from pX into pDest. Only do the write if the
8677 ** content is different from what is already there.
8679 static int btreeOverwriteContent(
8680 MemPage *pPage, /* MemPage on which writing will occur */
8681 u8 *pDest, /* Pointer to the place to start writing */
8682 const BtreePayload *pX, /* Source of data to write */
8683 int iOffset, /* Offset of first byte to write */
8684 int iAmt /* Number of bytes to be written */
8686 int nData = pX->nData - iOffset;
8687 if( nData<=0 ){
8688 /* Overwritting with zeros */
8689 int i;
8690 for(i=0; i<iAmt && pDest[i]==0; i++){}
8691 if( i<iAmt ){
8692 int rc = sqlite3PagerWrite(pPage->pDbPage);
8693 if( rc ) return rc;
8694 memset(pDest + i, 0, iAmt - i);
8696 }else{
8697 if( nData<iAmt ){
8698 /* Mixed read data and zeros at the end. Make a recursive call
8699 ** to write the zeros then fall through to write the real data */
8700 int rc = btreeOverwriteContent(pPage, pDest+nData, pX, iOffset+nData,
8701 iAmt-nData);
8702 if( rc ) return rc;
8703 iAmt = nData;
8705 if( memcmp(pDest, ((u8*)pX->pData) + iOffset, iAmt)!=0 ){
8706 int rc = sqlite3PagerWrite(pPage->pDbPage);
8707 if( rc ) return rc;
8708 /* In a corrupt database, it is possible for the source and destination
8709 ** buffers to overlap. This is harmless since the database is already
8710 ** corrupt but it does cause valgrind and ASAN warnings. So use
8711 ** memmove(). */
8712 memmove(pDest, ((u8*)pX->pData) + iOffset, iAmt);
8715 return SQLITE_OK;
8719 ** Overwrite the cell that cursor pCur is pointing to with fresh content
8720 ** contained in pX.
8722 static int btreeOverwriteCell(BtCursor *pCur, const BtreePayload *pX){
8723 int iOffset; /* Next byte of pX->pData to write */
8724 int nTotal = pX->nData + pX->nZero; /* Total bytes of to write */
8725 int rc; /* Return code */
8726 MemPage *pPage = pCur->pPage; /* Page being written */
8727 BtShared *pBt; /* Btree */
8728 Pgno ovflPgno; /* Next overflow page to write */
8729 u32 ovflPageSize; /* Size to write on overflow page */
8731 if( pCur->info.pPayload + pCur->info.nLocal > pPage->aDataEnd
8732 || pCur->info.pPayload < pPage->aData + pPage->cellOffset
8734 return SQLITE_CORRUPT_BKPT;
8736 /* Overwrite the local portion first */
8737 rc = btreeOverwriteContent(pPage, pCur->info.pPayload, pX,
8738 0, pCur->info.nLocal);
8739 if( rc ) return rc;
8740 if( pCur->info.nLocal==nTotal ) return SQLITE_OK;
8742 /* Now overwrite the overflow pages */
8743 iOffset = pCur->info.nLocal;
8744 assert( nTotal>=0 );
8745 assert( iOffset>=0 );
8746 ovflPgno = get4byte(pCur->info.pPayload + iOffset);
8747 pBt = pPage->pBt;
8748 ovflPageSize = pBt->usableSize - 4;
8750 rc = btreeGetPage(pBt, ovflPgno, &pPage, 0);
8751 if( rc ) return rc;
8752 if( sqlite3PagerPageRefcount(pPage->pDbPage)!=1 || pPage->isInit ){
8753 rc = SQLITE_CORRUPT_BKPT;
8754 }else{
8755 if( iOffset+ovflPageSize<(u32)nTotal ){
8756 ovflPgno = get4byte(pPage->aData);
8757 }else{
8758 ovflPageSize = nTotal - iOffset;
8760 rc = btreeOverwriteContent(pPage, pPage->aData+4, pX,
8761 iOffset, ovflPageSize);
8763 sqlite3PagerUnref(pPage->pDbPage);
8764 if( rc ) return rc;
8765 iOffset += ovflPageSize;
8766 }while( iOffset<nTotal );
8767 return SQLITE_OK;
8772 ** Insert a new record into the BTree. The content of the new record
8773 ** is described by the pX object. The pCur cursor is used only to
8774 ** define what table the record should be inserted into, and is left
8775 ** pointing at a random location.
8777 ** For a table btree (used for rowid tables), only the pX.nKey value of
8778 ** the key is used. The pX.pKey value must be NULL. The pX.nKey is the
8779 ** rowid or INTEGER PRIMARY KEY of the row. The pX.nData,pData,nZero fields
8780 ** hold the content of the row.
8782 ** For an index btree (used for indexes and WITHOUT ROWID tables), the
8783 ** key is an arbitrary byte sequence stored in pX.pKey,nKey. The
8784 ** pX.pData,nData,nZero fields must be zero.
8786 ** If the seekResult parameter is non-zero, then a successful call to
8787 ** MovetoUnpacked() to seek cursor pCur to (pKey,nKey) has already
8788 ** been performed. In other words, if seekResult!=0 then the cursor
8789 ** is currently pointing to a cell that will be adjacent to the cell
8790 ** to be inserted. If seekResult<0 then pCur points to a cell that is
8791 ** smaller then (pKey,nKey). If seekResult>0 then pCur points to a cell
8792 ** that is larger than (pKey,nKey).
8794 ** If seekResult==0, that means pCur is pointing at some unknown location.
8795 ** In that case, this routine must seek the cursor to the correct insertion
8796 ** point for (pKey,nKey) before doing the insertion. For index btrees,
8797 ** if pX->nMem is non-zero, then pX->aMem contains pointers to the unpacked
8798 ** key values and pX->aMem can be used instead of pX->pKey to avoid having
8799 ** to decode the key.
8801 int sqlite3BtreeInsert(
8802 BtCursor *pCur, /* Insert data into the table of this cursor */
8803 const BtreePayload *pX, /* Content of the row to be inserted */
8804 int flags, /* True if this is likely an append */
8805 int seekResult /* Result of prior MovetoUnpacked() call */
8807 int rc;
8808 int loc = seekResult; /* -1: before desired location +1: after */
8809 int szNew = 0;
8810 int idx;
8811 MemPage *pPage;
8812 Btree *p = pCur->pBtree;
8813 BtShared *pBt = p->pBt;
8814 unsigned char *oldCell;
8815 unsigned char *newCell = 0;
8817 assert( (flags & (BTREE_SAVEPOSITION|BTREE_APPEND|BTREE_PREFORMAT))==flags );
8818 assert( (flags & BTREE_PREFORMAT)==0 || seekResult || pCur->pKeyInfo==0 );
8820 if( pCur->eState==CURSOR_FAULT ){
8821 assert( pCur->skipNext!=SQLITE_OK );
8822 return pCur->skipNext;
8825 assert( cursorOwnsBtShared(pCur) );
8826 assert( (pCur->curFlags & BTCF_WriteFlag)!=0
8827 && pBt->inTransaction==TRANS_WRITE
8828 && (pBt->btsFlags & BTS_READ_ONLY)==0 );
8829 assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
8831 /* Assert that the caller has been consistent. If this cursor was opened
8832 ** expecting an index b-tree, then the caller should be inserting blob
8833 ** keys with no associated data. If the cursor was opened expecting an
8834 ** intkey table, the caller should be inserting integer keys with a
8835 ** blob of associated data. */
8836 assert( (flags & BTREE_PREFORMAT) || (pX->pKey==0)==(pCur->pKeyInfo==0) );
8838 /* Save the positions of any other cursors open on this table.
8840 ** In some cases, the call to btreeMoveto() below is a no-op. For
8841 ** example, when inserting data into a table with auto-generated integer
8842 ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
8843 ** integer key to use. It then calls this function to actually insert the
8844 ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
8845 ** that the cursor is already where it needs to be and returns without
8846 ** doing any work. To avoid thwarting these optimizations, it is important
8847 ** not to clear the cursor here.
8849 if( pCur->curFlags & BTCF_Multiple ){
8850 rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
8851 if( rc ) return rc;
8852 if( loc && pCur->iPage<0 ){
8853 /* This can only happen if the schema is corrupt such that there is more
8854 ** than one table or index with the same root page as used by the cursor.
8855 ** Which can only happen if the SQLITE_NoSchemaError flag was set when
8856 ** the schema was loaded. This cannot be asserted though, as a user might
8857 ** set the flag, load the schema, and then unset the flag. */
8858 return SQLITE_CORRUPT_BKPT;
8862 if( pCur->pKeyInfo==0 ){
8863 assert( pX->pKey==0 );
8864 /* If this is an insert into a table b-tree, invalidate any incrblob
8865 ** cursors open on the row being replaced */
8866 if( p->hasIncrblobCur ){
8867 invalidateIncrblobCursors(p, pCur->pgnoRoot, pX->nKey, 0);
8870 /* If BTREE_SAVEPOSITION is set, the cursor must already be pointing
8871 ** to a row with the same key as the new entry being inserted.
8873 #ifdef SQLITE_DEBUG
8874 if( flags & BTREE_SAVEPOSITION ){
8875 assert( pCur->curFlags & BTCF_ValidNKey );
8876 assert( pX->nKey==pCur->info.nKey );
8877 assert( loc==0 );
8879 #endif
8881 /* On the other hand, BTREE_SAVEPOSITION==0 does not imply
8882 ** that the cursor is not pointing to a row to be overwritten.
8883 ** So do a complete check.
8885 if( (pCur->curFlags&BTCF_ValidNKey)!=0 && pX->nKey==pCur->info.nKey ){
8886 /* The cursor is pointing to the entry that is to be
8887 ** overwritten */
8888 assert( pX->nData>=0 && pX->nZero>=0 );
8889 if( pCur->info.nSize!=0
8890 && pCur->info.nPayload==(u32)pX->nData+pX->nZero
8892 /* New entry is the same size as the old. Do an overwrite */
8893 return btreeOverwriteCell(pCur, pX);
8895 assert( loc==0 );
8896 }else if( loc==0 ){
8897 /* The cursor is *not* pointing to the cell to be overwritten, nor
8898 ** to an adjacent cell. Move the cursor so that it is pointing either
8899 ** to the cell to be overwritten or an adjacent cell.
8901 rc = sqlite3BtreeTableMoveto(pCur, pX->nKey,
8902 (flags & BTREE_APPEND)!=0, &loc);
8903 if( rc ) return rc;
8905 }else{
8906 /* This is an index or a WITHOUT ROWID table */
8908 /* If BTREE_SAVEPOSITION is set, the cursor must already be pointing
8909 ** to a row with the same key as the new entry being inserted.
8911 assert( (flags & BTREE_SAVEPOSITION)==0 || loc==0 );
8913 /* If the cursor is not already pointing either to the cell to be
8914 ** overwritten, or if a new cell is being inserted, if the cursor is
8915 ** not pointing to an immediately adjacent cell, then move the cursor
8916 ** so that it does.
8918 if( loc==0 && (flags & BTREE_SAVEPOSITION)==0 ){
8919 if( pX->nMem ){
8920 UnpackedRecord r;
8921 r.pKeyInfo = pCur->pKeyInfo;
8922 r.aMem = pX->aMem;
8923 r.nField = pX->nMem;
8924 r.default_rc = 0;
8925 r.eqSeen = 0;
8926 rc = sqlite3BtreeIndexMoveto(pCur, &r, &loc);
8927 }else{
8928 rc = btreeMoveto(pCur, pX->pKey, pX->nKey,
8929 (flags & BTREE_APPEND)!=0, &loc);
8931 if( rc ) return rc;
8934 /* If the cursor is currently pointing to an entry to be overwritten
8935 ** and the new content is the same as as the old, then use the
8936 ** overwrite optimization.
8938 if( loc==0 ){
8939 getCellInfo(pCur);
8940 if( pCur->info.nKey==pX->nKey ){
8941 BtreePayload x2;
8942 x2.pData = pX->pKey;
8943 x2.nData = pX->nKey;
8944 x2.nZero = 0;
8945 return btreeOverwriteCell(pCur, &x2);
8949 assert( pCur->eState==CURSOR_VALID
8950 || (pCur->eState==CURSOR_INVALID && loc)
8951 || CORRUPT_DB );
8953 pPage = pCur->pPage;
8954 assert( pPage->intKey || pX->nKey>=0 || (flags & BTREE_PREFORMAT) );
8955 assert( pPage->leaf || !pPage->intKey );
8956 if( pPage->nFree<0 ){
8957 if( NEVER(pCur->eState>CURSOR_INVALID) ){
8958 rc = SQLITE_CORRUPT_BKPT;
8959 }else{
8960 rc = btreeComputeFreeSpace(pPage);
8962 if( rc ) return rc;
8965 TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
8966 pCur->pgnoRoot, pX->nKey, pX->nData, pPage->pgno,
8967 loc==0 ? "overwrite" : "new entry"));
8968 assert( pPage->isInit );
8969 newCell = pBt->pTmpSpace;
8970 assert( newCell!=0 );
8971 if( flags & BTREE_PREFORMAT ){
8972 rc = SQLITE_OK;
8973 szNew = pBt->nPreformatSize;
8974 if( szNew<4 ) szNew = 4;
8975 if( ISAUTOVACUUM && szNew>pPage->maxLocal ){
8976 CellInfo info;
8977 pPage->xParseCell(pPage, newCell, &info);
8978 if( info.nPayload!=info.nLocal ){
8979 Pgno ovfl = get4byte(&newCell[szNew-4]);
8980 ptrmapPut(pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, &rc);
8983 }else{
8984 rc = fillInCell(pPage, newCell, pX, &szNew);
8986 if( rc ) goto end_insert;
8987 assert( szNew==pPage->xCellSize(pPage, newCell) );
8988 assert( szNew <= MX_CELL_SIZE(pBt) );
8989 idx = pCur->ix;
8990 if( loc==0 ){
8991 CellInfo info;
8992 assert( idx>=0 );
8993 if( idx>=pPage->nCell ){
8994 return SQLITE_CORRUPT_BKPT;
8996 rc = sqlite3PagerWrite(pPage->pDbPage);
8997 if( rc ){
8998 goto end_insert;
9000 oldCell = findCell(pPage, idx);
9001 if( !pPage->leaf ){
9002 memcpy(newCell, oldCell, 4);
9004 BTREE_CLEAR_CELL(rc, pPage, oldCell, info);
9005 testcase( pCur->curFlags & BTCF_ValidOvfl );
9006 invalidateOverflowCache(pCur);
9007 if( info.nSize==szNew && info.nLocal==info.nPayload
9008 && (!ISAUTOVACUUM || szNew<pPage->minLocal)
9010 /* Overwrite the old cell with the new if they are the same size.
9011 ** We could also try to do this if the old cell is smaller, then add
9012 ** the leftover space to the free list. But experiments show that
9013 ** doing that is no faster then skipping this optimization and just
9014 ** calling dropCell() and insertCell().
9016 ** This optimization cannot be used on an autovacuum database if the
9017 ** new entry uses overflow pages, as the insertCell() call below is
9018 ** necessary to add the PTRMAP_OVERFLOW1 pointer-map entry. */
9019 assert( rc==SQLITE_OK ); /* clearCell never fails when nLocal==nPayload */
9020 if( oldCell < pPage->aData+pPage->hdrOffset+10 ){
9021 return SQLITE_CORRUPT_BKPT;
9023 if( oldCell+szNew > pPage->aDataEnd ){
9024 return SQLITE_CORRUPT_BKPT;
9026 memcpy(oldCell, newCell, szNew);
9027 return SQLITE_OK;
9029 dropCell(pPage, idx, info.nSize, &rc);
9030 if( rc ) goto end_insert;
9031 }else if( loc<0 && pPage->nCell>0 ){
9032 assert( pPage->leaf );
9033 idx = ++pCur->ix;
9034 pCur->curFlags &= ~BTCF_ValidNKey;
9035 }else{
9036 assert( pPage->leaf );
9038 insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
9039 assert( pPage->nOverflow==0 || rc==SQLITE_OK );
9040 assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
9042 /* If no error has occurred and pPage has an overflow cell, call balance()
9043 ** to redistribute the cells within the tree. Since balance() may move
9044 ** the cursor, zero the BtCursor.info.nSize and BTCF_ValidNKey
9045 ** variables.
9047 ** Previous versions of SQLite called moveToRoot() to move the cursor
9048 ** back to the root page as balance() used to invalidate the contents
9049 ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
9050 ** set the cursor state to "invalid". This makes common insert operations
9051 ** slightly faster.
9053 ** There is a subtle but important optimization here too. When inserting
9054 ** multiple records into an intkey b-tree using a single cursor (as can
9055 ** happen while processing an "INSERT INTO ... SELECT" statement), it
9056 ** is advantageous to leave the cursor pointing to the last entry in
9057 ** the b-tree if possible. If the cursor is left pointing to the last
9058 ** entry in the table, and the next row inserted has an integer key
9059 ** larger than the largest existing key, it is possible to insert the
9060 ** row without seeking the cursor. This can be a big performance boost.
9062 pCur->info.nSize = 0;
9063 if( pPage->nOverflow ){
9064 assert( rc==SQLITE_OK );
9065 pCur->curFlags &= ~(BTCF_ValidNKey);
9066 rc = balance(pCur);
9068 /* Must make sure nOverflow is reset to zero even if the balance()
9069 ** fails. Internal data structure corruption will result otherwise.
9070 ** Also, set the cursor state to invalid. This stops saveCursorPosition()
9071 ** from trying to save the current position of the cursor. */
9072 pCur->pPage->nOverflow = 0;
9073 pCur->eState = CURSOR_INVALID;
9074 if( (flags & BTREE_SAVEPOSITION) && rc==SQLITE_OK ){
9075 btreeReleaseAllCursorPages(pCur);
9076 if( pCur->pKeyInfo ){
9077 assert( pCur->pKey==0 );
9078 pCur->pKey = sqlite3Malloc( pX->nKey );
9079 if( pCur->pKey==0 ){
9080 rc = SQLITE_NOMEM;
9081 }else{
9082 memcpy(pCur->pKey, pX->pKey, pX->nKey);
9085 pCur->eState = CURSOR_REQUIRESEEK;
9086 pCur->nKey = pX->nKey;
9089 assert( pCur->iPage<0 || pCur->pPage->nOverflow==0 );
9091 end_insert:
9092 return rc;
9096 ** This function is used as part of copying the current row from cursor
9097 ** pSrc into cursor pDest. If the cursors are open on intkey tables, then
9098 ** parameter iKey is used as the rowid value when the record is copied
9099 ** into pDest. Otherwise, the record is copied verbatim.
9101 ** This function does not actually write the new value to cursor pDest.
9102 ** Instead, it creates and populates any required overflow pages and
9103 ** writes the data for the new cell into the BtShared.pTmpSpace buffer
9104 ** for the destination database. The size of the cell, in bytes, is left
9105 ** in BtShared.nPreformatSize. The caller completes the insertion by
9106 ** calling sqlite3BtreeInsert() with the BTREE_PREFORMAT flag specified.
9108 ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
9110 int sqlite3BtreeTransferRow(BtCursor *pDest, BtCursor *pSrc, i64 iKey){
9111 int rc = SQLITE_OK;
9112 BtShared *pBt = pDest->pBt;
9113 u8 *aOut = pBt->pTmpSpace; /* Pointer to next output buffer */
9114 const u8 *aIn; /* Pointer to next input buffer */
9115 u32 nIn; /* Size of input buffer aIn[] */
9116 u32 nRem; /* Bytes of data still to copy */
9118 getCellInfo(pSrc);
9119 aOut += putVarint32(aOut, pSrc->info.nPayload);
9120 if( pDest->pKeyInfo==0 ) aOut += putVarint(aOut, iKey);
9121 nIn = pSrc->info.nLocal;
9122 aIn = pSrc->info.pPayload;
9123 if( aIn+nIn>pSrc->pPage->aDataEnd ){
9124 return SQLITE_CORRUPT_BKPT;
9126 nRem = pSrc->info.nPayload;
9127 if( nIn==nRem && nIn<pDest->pPage->maxLocal ){
9128 memcpy(aOut, aIn, nIn);
9129 pBt->nPreformatSize = nIn + (aOut - pBt->pTmpSpace);
9130 }else{
9131 Pager *pSrcPager = pSrc->pBt->pPager;
9132 u8 *pPgnoOut = 0;
9133 Pgno ovflIn = 0;
9134 DbPage *pPageIn = 0;
9135 MemPage *pPageOut = 0;
9136 u32 nOut; /* Size of output buffer aOut[] */
9138 nOut = btreePayloadToLocal(pDest->pPage, pSrc->info.nPayload);
9139 pBt->nPreformatSize = nOut + (aOut - pBt->pTmpSpace);
9140 if( nOut<pSrc->info.nPayload ){
9141 pPgnoOut = &aOut[nOut];
9142 pBt->nPreformatSize += 4;
9145 if( nRem>nIn ){
9146 if( aIn+nIn+4>pSrc->pPage->aDataEnd ){
9147 return SQLITE_CORRUPT_BKPT;
9149 ovflIn = get4byte(&pSrc->info.pPayload[nIn]);
9152 do {
9153 nRem -= nOut;
9155 assert( nOut>0 );
9156 if( nIn>0 ){
9157 int nCopy = MIN(nOut, nIn);
9158 memcpy(aOut, aIn, nCopy);
9159 nOut -= nCopy;
9160 nIn -= nCopy;
9161 aOut += nCopy;
9162 aIn += nCopy;
9164 if( nOut>0 ){
9165 sqlite3PagerUnref(pPageIn);
9166 pPageIn = 0;
9167 rc = sqlite3PagerGet(pSrcPager, ovflIn, &pPageIn, PAGER_GET_READONLY);
9168 if( rc==SQLITE_OK ){
9169 aIn = (const u8*)sqlite3PagerGetData(pPageIn);
9170 ovflIn = get4byte(aIn);
9171 aIn += 4;
9172 nIn = pSrc->pBt->usableSize - 4;
9175 }while( rc==SQLITE_OK && nOut>0 );
9177 if( rc==SQLITE_OK && nRem>0 && ALWAYS(pPgnoOut) ){
9178 Pgno pgnoNew;
9179 MemPage *pNew = 0;
9180 rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
9181 put4byte(pPgnoOut, pgnoNew);
9182 if( ISAUTOVACUUM && pPageOut ){
9183 ptrmapPut(pBt, pgnoNew, PTRMAP_OVERFLOW2, pPageOut->pgno, &rc);
9185 releasePage(pPageOut);
9186 pPageOut = pNew;
9187 if( pPageOut ){
9188 pPgnoOut = pPageOut->aData;
9189 put4byte(pPgnoOut, 0);
9190 aOut = &pPgnoOut[4];
9191 nOut = MIN(pBt->usableSize - 4, nRem);
9194 }while( nRem>0 && rc==SQLITE_OK );
9196 releasePage(pPageOut);
9197 sqlite3PagerUnref(pPageIn);
9200 return rc;
9204 ** Delete the entry that the cursor is pointing to.
9206 ** If the BTREE_SAVEPOSITION bit of the flags parameter is zero, then
9207 ** the cursor is left pointing at an arbitrary location after the delete.
9208 ** But if that bit is set, then the cursor is left in a state such that
9209 ** the next call to BtreeNext() or BtreePrev() moves it to the same row
9210 ** as it would have been on if the call to BtreeDelete() had been omitted.
9212 ** The BTREE_AUXDELETE bit of flags indicates that is one of several deletes
9213 ** associated with a single table entry and its indexes. Only one of those
9214 ** deletes is considered the "primary" delete. The primary delete occurs
9215 ** on a cursor that is not a BTREE_FORDELETE cursor. All but one delete
9216 ** operation on non-FORDELETE cursors is tagged with the AUXDELETE flag.
9217 ** The BTREE_AUXDELETE bit is a hint that is not used by this implementation,
9218 ** but which might be used by alternative storage engines.
9220 int sqlite3BtreeDelete(BtCursor *pCur, u8 flags){
9221 Btree *p = pCur->pBtree;
9222 BtShared *pBt = p->pBt;
9223 int rc; /* Return code */
9224 MemPage *pPage; /* Page to delete cell from */
9225 unsigned char *pCell; /* Pointer to cell to delete */
9226 int iCellIdx; /* Index of cell to delete */
9227 int iCellDepth; /* Depth of node containing pCell */
9228 CellInfo info; /* Size of the cell being deleted */
9229 int bSkipnext = 0; /* Leaf cursor in SKIPNEXT state */
9230 u8 bPreserve = flags & BTREE_SAVEPOSITION; /* Keep cursor valid */
9232 assert( cursorOwnsBtShared(pCur) );
9233 assert( pBt->inTransaction==TRANS_WRITE );
9234 assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
9235 assert( pCur->curFlags & BTCF_WriteFlag );
9236 assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
9237 assert( !hasReadConflicts(p, pCur->pgnoRoot) );
9238 assert( (flags & ~(BTREE_SAVEPOSITION | BTREE_AUXDELETE))==0 );
9239 if( pCur->eState==CURSOR_REQUIRESEEK ){
9240 rc = btreeRestoreCursorPosition(pCur);
9241 assert( rc!=SQLITE_OK || CORRUPT_DB || pCur->eState==CURSOR_VALID );
9242 if( rc || pCur->eState!=CURSOR_VALID ) return rc;
9244 assert( CORRUPT_DB || pCur->eState==CURSOR_VALID );
9246 iCellDepth = pCur->iPage;
9247 iCellIdx = pCur->ix;
9248 pPage = pCur->pPage;
9249 pCell = findCell(pPage, iCellIdx);
9250 if( pPage->nFree<0 && btreeComputeFreeSpace(pPage) ){
9251 return SQLITE_CORRUPT_BKPT;
9253 if( pPage->nCell<=iCellIdx ){
9254 return SQLITE_CORRUPT_BKPT;
9257 /* If the bPreserve flag is set to true, then the cursor position must
9258 ** be preserved following this delete operation. If the current delete
9259 ** will cause a b-tree rebalance, then this is done by saving the cursor
9260 ** key and leaving the cursor in CURSOR_REQUIRESEEK state before
9261 ** returning.
9263 ** Or, if the current delete will not cause a rebalance, then the cursor
9264 ** will be left in CURSOR_SKIPNEXT state pointing to the entry immediately
9265 ** before or after the deleted entry. In this case set bSkipnext to true. */
9266 if( bPreserve ){
9267 if( !pPage->leaf
9268 || (pPage->nFree+cellSizePtr(pPage,pCell)+2)>(int)(pBt->usableSize*2/3)
9269 || pPage->nCell==1 /* See dbfuzz001.test for a test case */
9271 /* A b-tree rebalance will be required after deleting this entry.
9272 ** Save the cursor key. */
9273 rc = saveCursorKey(pCur);
9274 if( rc ) return rc;
9275 }else{
9276 bSkipnext = 1;
9280 /* If the page containing the entry to delete is not a leaf page, move
9281 ** the cursor to the largest entry in the tree that is smaller than
9282 ** the entry being deleted. This cell will replace the cell being deleted
9283 ** from the internal node. The 'previous' entry is used for this instead
9284 ** of the 'next' entry, as the previous entry is always a part of the
9285 ** sub-tree headed by the child page of the cell being deleted. This makes
9286 ** balancing the tree following the delete operation easier. */
9287 if( !pPage->leaf ){
9288 rc = sqlite3BtreePrevious(pCur, 0);
9289 assert( rc!=SQLITE_DONE );
9290 if( rc ) return rc;
9293 /* Save the positions of any other cursors open on this table before
9294 ** making any modifications. */
9295 if( pCur->curFlags & BTCF_Multiple ){
9296 rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
9297 if( rc ) return rc;
9300 /* If this is a delete operation to remove a row from a table b-tree,
9301 ** invalidate any incrblob cursors open on the row being deleted. */
9302 if( pCur->pKeyInfo==0 && p->hasIncrblobCur ){
9303 invalidateIncrblobCursors(p, pCur->pgnoRoot, pCur->info.nKey, 0);
9306 /* Make the page containing the entry to be deleted writable. Then free any
9307 ** overflow pages associated with the entry and finally remove the cell
9308 ** itself from within the page. */
9309 rc = sqlite3PagerWrite(pPage->pDbPage);
9310 if( rc ) return rc;
9311 BTREE_CLEAR_CELL(rc, pPage, pCell, info);
9312 dropCell(pPage, iCellIdx, info.nSize, &rc);
9313 if( rc ) return rc;
9315 /* If the cell deleted was not located on a leaf page, then the cursor
9316 ** is currently pointing to the largest entry in the sub-tree headed
9317 ** by the child-page of the cell that was just deleted from an internal
9318 ** node. The cell from the leaf node needs to be moved to the internal
9319 ** node to replace the deleted cell. */
9320 if( !pPage->leaf ){
9321 MemPage *pLeaf = pCur->pPage;
9322 int nCell;
9323 Pgno n;
9324 unsigned char *pTmp;
9326 if( pLeaf->nFree<0 ){
9327 rc = btreeComputeFreeSpace(pLeaf);
9328 if( rc ) return rc;
9330 if( iCellDepth<pCur->iPage-1 ){
9331 n = pCur->apPage[iCellDepth+1]->pgno;
9332 }else{
9333 n = pCur->pPage->pgno;
9335 pCell = findCell(pLeaf, pLeaf->nCell-1);
9336 if( pCell<&pLeaf->aData[4] ) return SQLITE_CORRUPT_BKPT;
9337 nCell = pLeaf->xCellSize(pLeaf, pCell);
9338 assert( MX_CELL_SIZE(pBt) >= nCell );
9339 pTmp = pBt->pTmpSpace;
9340 assert( pTmp!=0 );
9341 rc = sqlite3PagerWrite(pLeaf->pDbPage);
9342 if( rc==SQLITE_OK ){
9343 insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
9345 dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
9346 if( rc ) return rc;
9349 /* Balance the tree. If the entry deleted was located on a leaf page,
9350 ** then the cursor still points to that page. In this case the first
9351 ** call to balance() repairs the tree, and the if(...) condition is
9352 ** never true.
9354 ** Otherwise, if the entry deleted was on an internal node page, then
9355 ** pCur is pointing to the leaf page from which a cell was removed to
9356 ** replace the cell deleted from the internal node. This is slightly
9357 ** tricky as the leaf node may be underfull, and the internal node may
9358 ** be either under or overfull. In this case run the balancing algorithm
9359 ** on the leaf node first. If the balance proceeds far enough up the
9360 ** tree that we can be sure that any problem in the internal node has
9361 ** been corrected, so be it. Otherwise, after balancing the leaf node,
9362 ** walk the cursor up the tree to the internal node and balance it as
9363 ** well. */
9364 rc = balance(pCur);
9365 if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
9366 releasePageNotNull(pCur->pPage);
9367 pCur->iPage--;
9368 while( pCur->iPage>iCellDepth ){
9369 releasePage(pCur->apPage[pCur->iPage--]);
9371 pCur->pPage = pCur->apPage[pCur->iPage];
9372 rc = balance(pCur);
9375 if( rc==SQLITE_OK ){
9376 if( bSkipnext ){
9377 assert( bPreserve && (pCur->iPage==iCellDepth || CORRUPT_DB) );
9378 assert( pPage==pCur->pPage || CORRUPT_DB );
9379 assert( (pPage->nCell>0 || CORRUPT_DB) && iCellIdx<=pPage->nCell );
9380 pCur->eState = CURSOR_SKIPNEXT;
9381 if( iCellIdx>=pPage->nCell ){
9382 pCur->skipNext = -1;
9383 pCur->ix = pPage->nCell-1;
9384 }else{
9385 pCur->skipNext = 1;
9387 }else{
9388 rc = moveToRoot(pCur);
9389 if( bPreserve ){
9390 btreeReleaseAllCursorPages(pCur);
9391 pCur->eState = CURSOR_REQUIRESEEK;
9393 if( rc==SQLITE_EMPTY ) rc = SQLITE_OK;
9396 return rc;
9400 ** Create a new BTree table. Write into *piTable the page
9401 ** number for the root page of the new table.
9403 ** The type of type is determined by the flags parameter. Only the
9404 ** following values of flags are currently in use. Other values for
9405 ** flags might not work:
9407 ** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
9408 ** BTREE_ZERODATA Used for SQL indices
9410 static int btreeCreateTable(Btree *p, Pgno *piTable, int createTabFlags){
9411 BtShared *pBt = p->pBt;
9412 MemPage *pRoot;
9413 Pgno pgnoRoot;
9414 int rc;
9415 int ptfFlags; /* Page-type flage for the root page of new table */
9417 assert( sqlite3BtreeHoldsMutex(p) );
9418 assert( pBt->inTransaction==TRANS_WRITE );
9419 assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
9421 #ifdef SQLITE_OMIT_AUTOVACUUM
9422 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
9423 if( rc ){
9424 return rc;
9426 #else
9427 if( pBt->autoVacuum ){
9428 Pgno pgnoMove; /* Move a page here to make room for the root-page */
9429 MemPage *pPageMove; /* The page to move to. */
9431 /* Creating a new table may probably require moving an existing database
9432 ** to make room for the new tables root page. In case this page turns
9433 ** out to be an overflow page, delete all overflow page-map caches
9434 ** held by open cursors.
9436 invalidateAllOverflowCache(pBt);
9438 /* Read the value of meta[3] from the database to determine where the
9439 ** root page of the new table should go. meta[3] is the largest root-page
9440 ** created so far, so the new root-page is (meta[3]+1).
9442 sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
9443 if( pgnoRoot>btreePagecount(pBt) ){
9444 return SQLITE_CORRUPT_BKPT;
9446 pgnoRoot++;
9448 /* The new root-page may not be allocated on a pointer-map page, or the
9449 ** PENDING_BYTE page.
9451 while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
9452 pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
9453 pgnoRoot++;
9455 assert( pgnoRoot>=3 );
9457 /* Allocate a page. The page that currently resides at pgnoRoot will
9458 ** be moved to the allocated page (unless the allocated page happens
9459 ** to reside at pgnoRoot).
9461 rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT);
9462 if( rc!=SQLITE_OK ){
9463 return rc;
9466 if( pgnoMove!=pgnoRoot ){
9467 /* pgnoRoot is the page that will be used for the root-page of
9468 ** the new table (assuming an error did not occur). But we were
9469 ** allocated pgnoMove. If required (i.e. if it was not allocated
9470 ** by extending the file), the current page at position pgnoMove
9471 ** is already journaled.
9473 u8 eType = 0;
9474 Pgno iPtrPage = 0;
9476 /* Save the positions of any open cursors. This is required in
9477 ** case they are holding a reference to an xFetch reference
9478 ** corresponding to page pgnoRoot. */
9479 rc = saveAllCursors(pBt, 0, 0);
9480 releasePage(pPageMove);
9481 if( rc!=SQLITE_OK ){
9482 return rc;
9485 /* Move the page currently at pgnoRoot to pgnoMove. */
9486 rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
9487 if( rc!=SQLITE_OK ){
9488 return rc;
9490 rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
9491 if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
9492 rc = SQLITE_CORRUPT_BKPT;
9494 if( rc!=SQLITE_OK ){
9495 releasePage(pRoot);
9496 return rc;
9498 assert( eType!=PTRMAP_ROOTPAGE );
9499 assert( eType!=PTRMAP_FREEPAGE );
9500 rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
9501 releasePage(pRoot);
9503 /* Obtain the page at pgnoRoot */
9504 if( rc!=SQLITE_OK ){
9505 return rc;
9507 rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
9508 if( rc!=SQLITE_OK ){
9509 return rc;
9511 rc = sqlite3PagerWrite(pRoot->pDbPage);
9512 if( rc!=SQLITE_OK ){
9513 releasePage(pRoot);
9514 return rc;
9516 }else{
9517 pRoot = pPageMove;
9520 /* Update the pointer-map and meta-data with the new root-page number. */
9521 ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
9522 if( rc ){
9523 releasePage(pRoot);
9524 return rc;
9527 /* When the new root page was allocated, page 1 was made writable in
9528 ** order either to increase the database filesize, or to decrement the
9529 ** freelist count. Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
9531 assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
9532 rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
9533 if( NEVER(rc) ){
9534 releasePage(pRoot);
9535 return rc;
9538 }else{
9539 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
9540 if( rc ) return rc;
9542 #endif
9543 assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
9544 if( createTabFlags & BTREE_INTKEY ){
9545 ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
9546 }else{
9547 ptfFlags = PTF_ZERODATA | PTF_LEAF;
9549 zeroPage(pRoot, ptfFlags);
9550 sqlite3PagerUnref(pRoot->pDbPage);
9551 assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
9552 *piTable = pgnoRoot;
9553 return SQLITE_OK;
9555 int sqlite3BtreeCreateTable(Btree *p, Pgno *piTable, int flags){
9556 int rc;
9557 sqlite3BtreeEnter(p);
9558 rc = btreeCreateTable(p, piTable, flags);
9559 sqlite3BtreeLeave(p);
9560 return rc;
9564 ** Erase the given database page and all its children. Return
9565 ** the page to the freelist.
9567 static int clearDatabasePage(
9568 BtShared *pBt, /* The BTree that contains the table */
9569 Pgno pgno, /* Page number to clear */
9570 int freePageFlag, /* Deallocate page if true */
9571 i64 *pnChange /* Add number of Cells freed to this counter */
9573 MemPage *pPage;
9574 int rc;
9575 unsigned char *pCell;
9576 int i;
9577 int hdr;
9578 CellInfo info;
9580 assert( sqlite3_mutex_held(pBt->mutex) );
9581 if( pgno>btreePagecount(pBt) ){
9582 return SQLITE_CORRUPT_BKPT;
9584 rc = getAndInitPage(pBt, pgno, &pPage, 0, 0);
9585 if( rc ) return rc;
9586 if( (pBt->openFlags & BTREE_SINGLE)==0
9587 && sqlite3PagerPageRefcount(pPage->pDbPage)!=1
9589 rc = SQLITE_CORRUPT_BKPT;
9590 goto cleardatabasepage_out;
9592 hdr = pPage->hdrOffset;
9593 for(i=0; i<pPage->nCell; i++){
9594 pCell = findCell(pPage, i);
9595 if( !pPage->leaf ){
9596 rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
9597 if( rc ) goto cleardatabasepage_out;
9599 BTREE_CLEAR_CELL(rc, pPage, pCell, info);
9600 if( rc ) goto cleardatabasepage_out;
9602 if( !pPage->leaf ){
9603 rc = clearDatabasePage(pBt, get4byte(&pPage->aData[hdr+8]), 1, pnChange);
9604 if( rc ) goto cleardatabasepage_out;
9605 if( pPage->intKey ) pnChange = 0;
9607 if( pnChange ){
9608 testcase( !pPage->intKey );
9609 *pnChange += pPage->nCell;
9611 if( freePageFlag ){
9612 freePage(pPage, &rc);
9613 }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
9614 zeroPage(pPage, pPage->aData[hdr] | PTF_LEAF);
9617 cleardatabasepage_out:
9618 releasePage(pPage);
9619 return rc;
9623 ** Delete all information from a single table in the database. iTable is
9624 ** the page number of the root of the table. After this routine returns,
9625 ** the root page is empty, but still exists.
9627 ** This routine will fail with SQLITE_LOCKED if there are any open
9628 ** read cursors on the table. Open write cursors are moved to the
9629 ** root of the table.
9631 ** If pnChange is not NULL, then the integer value pointed to by pnChange
9632 ** is incremented by the number of entries in the table.
9634 int sqlite3BtreeClearTable(Btree *p, int iTable, i64 *pnChange){
9635 int rc;
9636 BtShared *pBt = p->pBt;
9637 sqlite3BtreeEnter(p);
9638 assert( p->inTrans==TRANS_WRITE );
9640 rc = saveAllCursors(pBt, (Pgno)iTable, 0);
9642 if( SQLITE_OK==rc ){
9643 /* Invalidate all incrblob cursors open on table iTable (assuming iTable
9644 ** is the root of a table b-tree - if it is not, the following call is
9645 ** a no-op). */
9646 if( p->hasIncrblobCur ){
9647 invalidateIncrblobCursors(p, (Pgno)iTable, 0, 1);
9649 rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
9651 sqlite3BtreeLeave(p);
9652 return rc;
9656 ** Delete all information from the single table that pCur is open on.
9658 ** This routine only work for pCur on an ephemeral table.
9660 int sqlite3BtreeClearTableOfCursor(BtCursor *pCur){
9661 return sqlite3BtreeClearTable(pCur->pBtree, pCur->pgnoRoot, 0);
9665 ** Erase all information in a table and add the root of the table to
9666 ** the freelist. Except, the root of the principle table (the one on
9667 ** page 1) is never added to the freelist.
9669 ** This routine will fail with SQLITE_LOCKED if there are any open
9670 ** cursors on the table.
9672 ** If AUTOVACUUM is enabled and the page at iTable is not the last
9673 ** root page in the database file, then the last root page
9674 ** in the database file is moved into the slot formerly occupied by
9675 ** iTable and that last slot formerly occupied by the last root page
9676 ** is added to the freelist instead of iTable. In this say, all
9677 ** root pages are kept at the beginning of the database file, which
9678 ** is necessary for AUTOVACUUM to work right. *piMoved is set to the
9679 ** page number that used to be the last root page in the file before
9680 ** the move. If no page gets moved, *piMoved is set to 0.
9681 ** The last root page is recorded in meta[3] and the value of
9682 ** meta[3] is updated by this procedure.
9684 static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
9685 int rc;
9686 MemPage *pPage = 0;
9687 BtShared *pBt = p->pBt;
9689 assert( sqlite3BtreeHoldsMutex(p) );
9690 assert( p->inTrans==TRANS_WRITE );
9691 assert( iTable>=2 );
9692 if( iTable>btreePagecount(pBt) ){
9693 return SQLITE_CORRUPT_BKPT;
9696 rc = sqlite3BtreeClearTable(p, iTable, 0);
9697 if( rc ) return rc;
9698 rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
9699 if( NEVER(rc) ){
9700 releasePage(pPage);
9701 return rc;
9704 *piMoved = 0;
9706 #ifdef SQLITE_OMIT_AUTOVACUUM
9707 freePage(pPage, &rc);
9708 releasePage(pPage);
9709 #else
9710 if( pBt->autoVacuum ){
9711 Pgno maxRootPgno;
9712 sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
9714 if( iTable==maxRootPgno ){
9715 /* If the table being dropped is the table with the largest root-page
9716 ** number in the database, put the root page on the free list.
9718 freePage(pPage, &rc);
9719 releasePage(pPage);
9720 if( rc!=SQLITE_OK ){
9721 return rc;
9723 }else{
9724 /* The table being dropped does not have the largest root-page
9725 ** number in the database. So move the page that does into the
9726 ** gap left by the deleted root-page.
9728 MemPage *pMove;
9729 releasePage(pPage);
9730 rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
9731 if( rc!=SQLITE_OK ){
9732 return rc;
9734 rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
9735 releasePage(pMove);
9736 if( rc!=SQLITE_OK ){
9737 return rc;
9739 pMove = 0;
9740 rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
9741 freePage(pMove, &rc);
9742 releasePage(pMove);
9743 if( rc!=SQLITE_OK ){
9744 return rc;
9746 *piMoved = maxRootPgno;
9749 /* Set the new 'max-root-page' value in the database header. This
9750 ** is the old value less one, less one more if that happens to
9751 ** be a root-page number, less one again if that is the
9752 ** PENDING_BYTE_PAGE.
9754 maxRootPgno--;
9755 while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
9756 || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
9757 maxRootPgno--;
9759 assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
9761 rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
9762 }else{
9763 freePage(pPage, &rc);
9764 releasePage(pPage);
9766 #endif
9767 return rc;
9769 int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
9770 int rc;
9771 sqlite3BtreeEnter(p);
9772 rc = btreeDropTable(p, iTable, piMoved);
9773 sqlite3BtreeLeave(p);
9774 return rc;
9779 ** This function may only be called if the b-tree connection already
9780 ** has a read or write transaction open on the database.
9782 ** Read the meta-information out of a database file. Meta[0]
9783 ** is the number of free pages currently in the database. Meta[1]
9784 ** through meta[15] are available for use by higher layers. Meta[0]
9785 ** is read-only, the others are read/write.
9787 ** The schema layer numbers meta values differently. At the schema
9788 ** layer (and the SetCookie and ReadCookie opcodes) the number of
9789 ** free pages is not visible. So Cookie[0] is the same as Meta[1].
9791 ** This routine treats Meta[BTREE_DATA_VERSION] as a special case. Instead
9792 ** of reading the value out of the header, it instead loads the "DataVersion"
9793 ** from the pager. The BTREE_DATA_VERSION value is not actually stored in the
9794 ** database file. It is a number computed by the pager. But its access
9795 ** pattern is the same as header meta values, and so it is convenient to
9796 ** read it from this routine.
9798 void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
9799 BtShared *pBt = p->pBt;
9801 sqlite3BtreeEnter(p);
9802 assert( p->inTrans>TRANS_NONE );
9803 assert( SQLITE_OK==querySharedCacheTableLock(p, SCHEMA_ROOT, READ_LOCK) );
9804 assert( pBt->pPage1 );
9805 assert( idx>=0 && idx<=15 );
9807 if( idx==BTREE_DATA_VERSION ){
9808 *pMeta = sqlite3PagerDataVersion(pBt->pPager) + p->iBDataVersion;
9809 }else{
9810 *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
9813 /* If auto-vacuum is disabled in this build and this is an auto-vacuum
9814 ** database, mark the database as read-only. */
9815 #ifdef SQLITE_OMIT_AUTOVACUUM
9816 if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){
9817 pBt->btsFlags |= BTS_READ_ONLY;
9819 #endif
9821 sqlite3BtreeLeave(p);
9825 ** Write meta-information back into the database. Meta[0] is
9826 ** read-only and may not be written.
9828 int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
9829 BtShared *pBt = p->pBt;
9830 unsigned char *pP1;
9831 int rc;
9832 assert( idx>=1 && idx<=15 );
9833 sqlite3BtreeEnter(p);
9834 assert( p->inTrans==TRANS_WRITE );
9835 assert( pBt->pPage1!=0 );
9836 pP1 = pBt->pPage1->aData;
9837 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
9838 if( rc==SQLITE_OK ){
9839 put4byte(&pP1[36 + idx*4], iMeta);
9840 #ifndef SQLITE_OMIT_AUTOVACUUM
9841 if( idx==BTREE_INCR_VACUUM ){
9842 assert( pBt->autoVacuum || iMeta==0 );
9843 assert( iMeta==0 || iMeta==1 );
9844 pBt->incrVacuum = (u8)iMeta;
9846 #endif
9848 sqlite3BtreeLeave(p);
9849 return rc;
9853 ** The first argument, pCur, is a cursor opened on some b-tree. Count the
9854 ** number of entries in the b-tree and write the result to *pnEntry.
9856 ** SQLITE_OK is returned if the operation is successfully executed.
9857 ** Otherwise, if an error is encountered (i.e. an IO error or database
9858 ** corruption) an SQLite error code is returned.
9860 int sqlite3BtreeCount(sqlite3 *db, BtCursor *pCur, i64 *pnEntry){
9861 i64 nEntry = 0; /* Value to return in *pnEntry */
9862 int rc; /* Return code */
9864 rc = moveToRoot(pCur);
9865 if( rc==SQLITE_EMPTY ){
9866 *pnEntry = 0;
9867 return SQLITE_OK;
9870 /* Unless an error occurs, the following loop runs one iteration for each
9871 ** page in the B-Tree structure (not including overflow pages).
9873 while( rc==SQLITE_OK && !AtomicLoad(&db->u1.isInterrupted) ){
9874 int iIdx; /* Index of child node in parent */
9875 MemPage *pPage; /* Current page of the b-tree */
9877 /* If this is a leaf page or the tree is not an int-key tree, then
9878 ** this page contains countable entries. Increment the entry counter
9879 ** accordingly.
9881 pPage = pCur->pPage;
9882 if( pPage->leaf || !pPage->intKey ){
9883 nEntry += pPage->nCell;
9886 /* pPage is a leaf node. This loop navigates the cursor so that it
9887 ** points to the first interior cell that it points to the parent of
9888 ** the next page in the tree that has not yet been visited. The
9889 ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
9890 ** of the page, or to the number of cells in the page if the next page
9891 ** to visit is the right-child of its parent.
9893 ** If all pages in the tree have been visited, return SQLITE_OK to the
9894 ** caller.
9896 if( pPage->leaf ){
9897 do {
9898 if( pCur->iPage==0 ){
9899 /* All pages of the b-tree have been visited. Return successfully. */
9900 *pnEntry = nEntry;
9901 return moveToRoot(pCur);
9903 moveToParent(pCur);
9904 }while ( pCur->ix>=pCur->pPage->nCell );
9906 pCur->ix++;
9907 pPage = pCur->pPage;
9910 /* Descend to the child node of the cell that the cursor currently
9911 ** points at. This is the right-child if (iIdx==pPage->nCell).
9913 iIdx = pCur->ix;
9914 if( iIdx==pPage->nCell ){
9915 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
9916 }else{
9917 rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
9921 /* An error has occurred. Return an error code. */
9922 return rc;
9926 ** Return the pager associated with a BTree. This routine is used for
9927 ** testing and debugging only.
9929 Pager *sqlite3BtreePager(Btree *p){
9930 return p->pBt->pPager;
9933 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
9935 ** Append a message to the error message string.
9937 static void checkAppendMsg(
9938 IntegrityCk *pCheck,
9939 const char *zFormat,
9942 va_list ap;
9943 if( !pCheck->mxErr ) return;
9944 pCheck->mxErr--;
9945 pCheck->nErr++;
9946 va_start(ap, zFormat);
9947 if( pCheck->errMsg.nChar ){
9948 sqlite3_str_append(&pCheck->errMsg, "\n", 1);
9950 if( pCheck->zPfx ){
9951 sqlite3_str_appendf(&pCheck->errMsg, pCheck->zPfx, pCheck->v1, pCheck->v2);
9953 sqlite3_str_vappendf(&pCheck->errMsg, zFormat, ap);
9954 va_end(ap);
9955 if( pCheck->errMsg.accError==SQLITE_NOMEM ){
9956 pCheck->bOomFault = 1;
9959 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
9961 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
9964 ** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that
9965 ** corresponds to page iPg is already set.
9967 static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){
9968 assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
9969 return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));
9973 ** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg.
9975 static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){
9976 assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
9977 pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));
9982 ** Add 1 to the reference count for page iPage. If this is the second
9983 ** reference to the page, add an error message to pCheck->zErrMsg.
9984 ** Return 1 if there are 2 or more references to the page and 0 if
9985 ** if this is the first reference to the page.
9987 ** Also check that the page number is in bounds.
9989 static int checkRef(IntegrityCk *pCheck, Pgno iPage){
9990 if( iPage>pCheck->nPage || iPage==0 ){
9991 checkAppendMsg(pCheck, "invalid page number %d", iPage);
9992 return 1;
9994 if( getPageReferenced(pCheck, iPage) ){
9995 checkAppendMsg(pCheck, "2nd reference to page %d", iPage);
9996 return 1;
9998 if( AtomicLoad(&pCheck->db->u1.isInterrupted) ) return 1;
9999 setPageReferenced(pCheck, iPage);
10000 return 0;
10003 #ifndef SQLITE_OMIT_AUTOVACUUM
10005 ** Check that the entry in the pointer-map for page iChild maps to
10006 ** page iParent, pointer type ptrType. If not, append an error message
10007 ** to pCheck.
10009 static void checkPtrmap(
10010 IntegrityCk *pCheck, /* Integrity check context */
10011 Pgno iChild, /* Child page number */
10012 u8 eType, /* Expected pointer map type */
10013 Pgno iParent /* Expected pointer map parent page number */
10015 int rc;
10016 u8 ePtrmapType;
10017 Pgno iPtrmapParent;
10019 rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
10020 if( rc!=SQLITE_OK ){
10021 if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->bOomFault = 1;
10022 checkAppendMsg(pCheck, "Failed to read ptrmap key=%d", iChild);
10023 return;
10026 if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
10027 checkAppendMsg(pCheck,
10028 "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
10029 iChild, eType, iParent, ePtrmapType, iPtrmapParent);
10032 #endif
10035 ** Check the integrity of the freelist or of an overflow page list.
10036 ** Verify that the number of pages on the list is N.
10038 static void checkList(
10039 IntegrityCk *pCheck, /* Integrity checking context */
10040 int isFreeList, /* True for a freelist. False for overflow page list */
10041 Pgno iPage, /* Page number for first page in the list */
10042 u32 N /* Expected number of pages in the list */
10044 int i;
10045 u32 expected = N;
10046 int nErrAtStart = pCheck->nErr;
10047 while( iPage!=0 && pCheck->mxErr ){
10048 DbPage *pOvflPage;
10049 unsigned char *pOvflData;
10050 if( checkRef(pCheck, iPage) ) break;
10051 N--;
10052 if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage, 0) ){
10053 checkAppendMsg(pCheck, "failed to get page %d", iPage);
10054 break;
10056 pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
10057 if( isFreeList ){
10058 u32 n = (u32)get4byte(&pOvflData[4]);
10059 #ifndef SQLITE_OMIT_AUTOVACUUM
10060 if( pCheck->pBt->autoVacuum ){
10061 checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0);
10063 #endif
10064 if( n>pCheck->pBt->usableSize/4-2 ){
10065 checkAppendMsg(pCheck,
10066 "freelist leaf count too big on page %d", iPage);
10067 N--;
10068 }else{
10069 for(i=0; i<(int)n; i++){
10070 Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
10071 #ifndef SQLITE_OMIT_AUTOVACUUM
10072 if( pCheck->pBt->autoVacuum ){
10073 checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0);
10075 #endif
10076 checkRef(pCheck, iFreePage);
10078 N -= n;
10081 #ifndef SQLITE_OMIT_AUTOVACUUM
10082 else{
10083 /* If this database supports auto-vacuum and iPage is not the last
10084 ** page in this overflow list, check that the pointer-map entry for
10085 ** the following page matches iPage.
10087 if( pCheck->pBt->autoVacuum && N>0 ){
10088 i = get4byte(pOvflData);
10089 checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage);
10092 #endif
10093 iPage = get4byte(pOvflData);
10094 sqlite3PagerUnref(pOvflPage);
10096 if( N && nErrAtStart==pCheck->nErr ){
10097 checkAppendMsg(pCheck,
10098 "%s is %d but should be %d",
10099 isFreeList ? "size" : "overflow list length",
10100 expected-N, expected);
10103 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
10106 ** An implementation of a min-heap.
10108 ** aHeap[0] is the number of elements on the heap. aHeap[1] is the
10109 ** root element. The daughter nodes of aHeap[N] are aHeap[N*2]
10110 ** and aHeap[N*2+1].
10112 ** The heap property is this: Every node is less than or equal to both
10113 ** of its daughter nodes. A consequence of the heap property is that the
10114 ** root node aHeap[1] is always the minimum value currently in the heap.
10116 ** The btreeHeapInsert() routine inserts an unsigned 32-bit number onto
10117 ** the heap, preserving the heap property. The btreeHeapPull() routine
10118 ** removes the root element from the heap (the minimum value in the heap)
10119 ** and then moves other nodes around as necessary to preserve the heap
10120 ** property.
10122 ** This heap is used for cell overlap and coverage testing. Each u32
10123 ** entry represents the span of a cell or freeblock on a btree page.
10124 ** The upper 16 bits are the index of the first byte of a range and the
10125 ** lower 16 bits are the index of the last byte of that range.
10127 static void btreeHeapInsert(u32 *aHeap, u32 x){
10128 u32 j, i = ++aHeap[0];
10129 aHeap[i] = x;
10130 while( (j = i/2)>0 && aHeap[j]>aHeap[i] ){
10131 x = aHeap[j];
10132 aHeap[j] = aHeap[i];
10133 aHeap[i] = x;
10134 i = j;
10137 static int btreeHeapPull(u32 *aHeap, u32 *pOut){
10138 u32 j, i, x;
10139 if( (x = aHeap[0])==0 ) return 0;
10140 *pOut = aHeap[1];
10141 aHeap[1] = aHeap[x];
10142 aHeap[x] = 0xffffffff;
10143 aHeap[0]--;
10144 i = 1;
10145 while( (j = i*2)<=aHeap[0] ){
10146 if( aHeap[j]>aHeap[j+1] ) j++;
10147 if( aHeap[i]<aHeap[j] ) break;
10148 x = aHeap[i];
10149 aHeap[i] = aHeap[j];
10150 aHeap[j] = x;
10151 i = j;
10153 return 1;
10156 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
10158 ** Do various sanity checks on a single page of a tree. Return
10159 ** the tree depth. Root pages return 0. Parents of root pages
10160 ** return 1, and so forth.
10162 ** These checks are done:
10164 ** 1. Make sure that cells and freeblocks do not overlap
10165 ** but combine to completely cover the page.
10166 ** 2. Make sure integer cell keys are in order.
10167 ** 3. Check the integrity of overflow pages.
10168 ** 4. Recursively call checkTreePage on all children.
10169 ** 5. Verify that the depth of all children is the same.
10171 static int checkTreePage(
10172 IntegrityCk *pCheck, /* Context for the sanity check */
10173 Pgno iPage, /* Page number of the page to check */
10174 i64 *piMinKey, /* Write minimum integer primary key here */
10175 i64 maxKey /* Error if integer primary key greater than this */
10177 MemPage *pPage = 0; /* The page being analyzed */
10178 int i; /* Loop counter */
10179 int rc; /* Result code from subroutine call */
10180 int depth = -1, d2; /* Depth of a subtree */
10181 int pgno; /* Page number */
10182 int nFrag; /* Number of fragmented bytes on the page */
10183 int hdr; /* Offset to the page header */
10184 int cellStart; /* Offset to the start of the cell pointer array */
10185 int nCell; /* Number of cells */
10186 int doCoverageCheck = 1; /* True if cell coverage checking should be done */
10187 int keyCanBeEqual = 1; /* True if IPK can be equal to maxKey
10188 ** False if IPK must be strictly less than maxKey */
10189 u8 *data; /* Page content */
10190 u8 *pCell; /* Cell content */
10191 u8 *pCellIdx; /* Next element of the cell pointer array */
10192 BtShared *pBt; /* The BtShared object that owns pPage */
10193 u32 pc; /* Address of a cell */
10194 u32 usableSize; /* Usable size of the page */
10195 u32 contentOffset; /* Offset to the start of the cell content area */
10196 u32 *heap = 0; /* Min-heap used for checking cell coverage */
10197 u32 x, prev = 0; /* Next and previous entry on the min-heap */
10198 const char *saved_zPfx = pCheck->zPfx;
10199 int saved_v1 = pCheck->v1;
10200 int saved_v2 = pCheck->v2;
10201 u8 savedIsInit = 0;
10203 /* Check that the page exists
10205 pBt = pCheck->pBt;
10206 usableSize = pBt->usableSize;
10207 if( iPage==0 ) return 0;
10208 if( checkRef(pCheck, iPage) ) return 0;
10209 pCheck->zPfx = "Page %u: ";
10210 pCheck->v1 = iPage;
10211 if( (rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0 ){
10212 checkAppendMsg(pCheck,
10213 "unable to get the page. error code=%d", rc);
10214 goto end_of_check;
10217 /* Clear MemPage.isInit to make sure the corruption detection code in
10218 ** btreeInitPage() is executed. */
10219 savedIsInit = pPage->isInit;
10220 pPage->isInit = 0;
10221 if( (rc = btreeInitPage(pPage))!=0 ){
10222 assert( rc==SQLITE_CORRUPT ); /* The only possible error from InitPage */
10223 checkAppendMsg(pCheck,
10224 "btreeInitPage() returns error code %d", rc);
10225 goto end_of_check;
10227 if( (rc = btreeComputeFreeSpace(pPage))!=0 ){
10228 assert( rc==SQLITE_CORRUPT );
10229 checkAppendMsg(pCheck, "free space corruption", rc);
10230 goto end_of_check;
10232 data = pPage->aData;
10233 hdr = pPage->hdrOffset;
10235 /* Set up for cell analysis */
10236 pCheck->zPfx = "On tree page %u cell %d: ";
10237 contentOffset = get2byteNotZero(&data[hdr+5]);
10238 assert( contentOffset<=usableSize ); /* Enforced by btreeInitPage() */
10240 /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
10241 ** number of cells on the page. */
10242 nCell = get2byte(&data[hdr+3]);
10243 assert( pPage->nCell==nCell );
10245 /* EVIDENCE-OF: R-23882-45353 The cell pointer array of a b-tree page
10246 ** immediately follows the b-tree page header. */
10247 cellStart = hdr + 12 - 4*pPage->leaf;
10248 assert( pPage->aCellIdx==&data[cellStart] );
10249 pCellIdx = &data[cellStart + 2*(nCell-1)];
10251 if( !pPage->leaf ){
10252 /* Analyze the right-child page of internal pages */
10253 pgno = get4byte(&data[hdr+8]);
10254 #ifndef SQLITE_OMIT_AUTOVACUUM
10255 if( pBt->autoVacuum ){
10256 pCheck->zPfx = "On page %u at right child: ";
10257 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
10259 #endif
10260 depth = checkTreePage(pCheck, pgno, &maxKey, maxKey);
10261 keyCanBeEqual = 0;
10262 }else{
10263 /* For leaf pages, the coverage check will occur in the same loop
10264 ** as the other cell checks, so initialize the heap. */
10265 heap = pCheck->heap;
10266 heap[0] = 0;
10269 /* EVIDENCE-OF: R-02776-14802 The cell pointer array consists of K 2-byte
10270 ** integer offsets to the cell contents. */
10271 for(i=nCell-1; i>=0 && pCheck->mxErr; i--){
10272 CellInfo info;
10274 /* Check cell size */
10275 pCheck->v2 = i;
10276 assert( pCellIdx==&data[cellStart + i*2] );
10277 pc = get2byteAligned(pCellIdx);
10278 pCellIdx -= 2;
10279 if( pc<contentOffset || pc>usableSize-4 ){
10280 checkAppendMsg(pCheck, "Offset %d out of range %d..%d",
10281 pc, contentOffset, usableSize-4);
10282 doCoverageCheck = 0;
10283 continue;
10285 pCell = &data[pc];
10286 pPage->xParseCell(pPage, pCell, &info);
10287 if( pc+info.nSize>usableSize ){
10288 checkAppendMsg(pCheck, "Extends off end of page");
10289 doCoverageCheck = 0;
10290 continue;
10293 /* Check for integer primary key out of range */
10294 if( pPage->intKey ){
10295 if( keyCanBeEqual ? (info.nKey > maxKey) : (info.nKey >= maxKey) ){
10296 checkAppendMsg(pCheck, "Rowid %lld out of order", info.nKey);
10298 maxKey = info.nKey;
10299 keyCanBeEqual = 0; /* Only the first key on the page may ==maxKey */
10302 /* Check the content overflow list */
10303 if( info.nPayload>info.nLocal ){
10304 u32 nPage; /* Number of pages on the overflow chain */
10305 Pgno pgnoOvfl; /* First page of the overflow chain */
10306 assert( pc + info.nSize - 4 <= usableSize );
10307 nPage = (info.nPayload - info.nLocal + usableSize - 5)/(usableSize - 4);
10308 pgnoOvfl = get4byte(&pCell[info.nSize - 4]);
10309 #ifndef SQLITE_OMIT_AUTOVACUUM
10310 if( pBt->autoVacuum ){
10311 checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage);
10313 #endif
10314 checkList(pCheck, 0, pgnoOvfl, nPage);
10317 if( !pPage->leaf ){
10318 /* Check sanity of left child page for internal pages */
10319 pgno = get4byte(pCell);
10320 #ifndef SQLITE_OMIT_AUTOVACUUM
10321 if( pBt->autoVacuum ){
10322 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
10324 #endif
10325 d2 = checkTreePage(pCheck, pgno, &maxKey, maxKey);
10326 keyCanBeEqual = 0;
10327 if( d2!=depth ){
10328 checkAppendMsg(pCheck, "Child page depth differs");
10329 depth = d2;
10331 }else{
10332 /* Populate the coverage-checking heap for leaf pages */
10333 btreeHeapInsert(heap, (pc<<16)|(pc+info.nSize-1));
10336 *piMinKey = maxKey;
10338 /* Check for complete coverage of the page
10340 pCheck->zPfx = 0;
10341 if( doCoverageCheck && pCheck->mxErr>0 ){
10342 /* For leaf pages, the min-heap has already been initialized and the
10343 ** cells have already been inserted. But for internal pages, that has
10344 ** not yet been done, so do it now */
10345 if( !pPage->leaf ){
10346 heap = pCheck->heap;
10347 heap[0] = 0;
10348 for(i=nCell-1; i>=0; i--){
10349 u32 size;
10350 pc = get2byteAligned(&data[cellStart+i*2]);
10351 size = pPage->xCellSize(pPage, &data[pc]);
10352 btreeHeapInsert(heap, (pc<<16)|(pc+size-1));
10355 /* Add the freeblocks to the min-heap
10357 ** EVIDENCE-OF: R-20690-50594 The second field of the b-tree page header
10358 ** is the offset of the first freeblock, or zero if there are no
10359 ** freeblocks on the page.
10361 i = get2byte(&data[hdr+1]);
10362 while( i>0 ){
10363 int size, j;
10364 assert( (u32)i<=usableSize-4 ); /* Enforced by btreeComputeFreeSpace() */
10365 size = get2byte(&data[i+2]);
10366 assert( (u32)(i+size)<=usableSize ); /* due to btreeComputeFreeSpace() */
10367 btreeHeapInsert(heap, (((u32)i)<<16)|(i+size-1));
10368 /* EVIDENCE-OF: R-58208-19414 The first 2 bytes of a freeblock are a
10369 ** big-endian integer which is the offset in the b-tree page of the next
10370 ** freeblock in the chain, or zero if the freeblock is the last on the
10371 ** chain. */
10372 j = get2byte(&data[i]);
10373 /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of
10374 ** increasing offset. */
10375 assert( j==0 || j>i+size ); /* Enforced by btreeComputeFreeSpace() */
10376 assert( (u32)j<=usableSize-4 ); /* Enforced by btreeComputeFreeSpace() */
10377 i = j;
10379 /* Analyze the min-heap looking for overlap between cells and/or
10380 ** freeblocks, and counting the number of untracked bytes in nFrag.
10382 ** Each min-heap entry is of the form: (start_address<<16)|end_address.
10383 ** There is an implied first entry the covers the page header, the cell
10384 ** pointer index, and the gap between the cell pointer index and the start
10385 ** of cell content.
10387 ** The loop below pulls entries from the min-heap in order and compares
10388 ** the start_address against the previous end_address. If there is an
10389 ** overlap, that means bytes are used multiple times. If there is a gap,
10390 ** that gap is added to the fragmentation count.
10392 nFrag = 0;
10393 prev = contentOffset - 1; /* Implied first min-heap entry */
10394 while( btreeHeapPull(heap,&x) ){
10395 if( (prev&0xffff)>=(x>>16) ){
10396 checkAppendMsg(pCheck,
10397 "Multiple uses for byte %u of page %u", x>>16, iPage);
10398 break;
10399 }else{
10400 nFrag += (x>>16) - (prev&0xffff) - 1;
10401 prev = x;
10404 nFrag += usableSize - (prev&0xffff) - 1;
10405 /* EVIDENCE-OF: R-43263-13491 The total number of bytes in all fragments
10406 ** is stored in the fifth field of the b-tree page header.
10407 ** EVIDENCE-OF: R-07161-27322 The one-byte integer at offset 7 gives the
10408 ** number of fragmented free bytes within the cell content area.
10410 if( heap[0]==0 && nFrag!=data[hdr+7] ){
10411 checkAppendMsg(pCheck,
10412 "Fragmentation of %d bytes reported as %d on page %u",
10413 nFrag, data[hdr+7], iPage);
10417 end_of_check:
10418 if( !doCoverageCheck ) pPage->isInit = savedIsInit;
10419 releasePage(pPage);
10420 pCheck->zPfx = saved_zPfx;
10421 pCheck->v1 = saved_v1;
10422 pCheck->v2 = saved_v2;
10423 return depth+1;
10425 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
10427 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
10429 ** This routine does a complete check of the given BTree file. aRoot[] is
10430 ** an array of pages numbers were each page number is the root page of
10431 ** a table. nRoot is the number of entries in aRoot.
10433 ** A read-only or read-write transaction must be opened before calling
10434 ** this function.
10436 ** Write the number of error seen in *pnErr. Except for some memory
10437 ** allocation errors, an error message held in memory obtained from
10438 ** malloc is returned if *pnErr is non-zero. If *pnErr==0 then NULL is
10439 ** returned. If a memory allocation error occurs, NULL is returned.
10441 ** If the first entry in aRoot[] is 0, that indicates that the list of
10442 ** root pages is incomplete. This is a "partial integrity-check". This
10443 ** happens when performing an integrity check on a single table. The
10444 ** zero is skipped, of course. But in addition, the freelist checks
10445 ** and the checks to make sure every page is referenced are also skipped,
10446 ** since obviously it is not possible to know which pages are covered by
10447 ** the unverified btrees. Except, if aRoot[1] is 1, then the freelist
10448 ** checks are still performed.
10450 char *sqlite3BtreeIntegrityCheck(
10451 sqlite3 *db, /* Database connection that is running the check */
10452 Btree *p, /* The btree to be checked */
10453 Pgno *aRoot, /* An array of root pages numbers for individual trees */
10454 int nRoot, /* Number of entries in aRoot[] */
10455 int mxErr, /* Stop reporting errors after this many */
10456 int *pnErr /* Write number of errors seen to this variable */
10458 Pgno i;
10459 IntegrityCk sCheck;
10460 BtShared *pBt = p->pBt;
10461 u64 savedDbFlags = pBt->db->flags;
10462 char zErr[100];
10463 int bPartial = 0; /* True if not checking all btrees */
10464 int bCkFreelist = 1; /* True to scan the freelist */
10465 VVA_ONLY( int nRef );
10466 assert( nRoot>0 );
10468 /* aRoot[0]==0 means this is a partial check */
10469 if( aRoot[0]==0 ){
10470 assert( nRoot>1 );
10471 bPartial = 1;
10472 if( aRoot[1]!=1 ) bCkFreelist = 0;
10475 sqlite3BtreeEnter(p);
10476 assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
10477 VVA_ONLY( nRef = sqlite3PagerRefcount(pBt->pPager) );
10478 assert( nRef>=0 );
10479 sCheck.db = db;
10480 sCheck.pBt = pBt;
10481 sCheck.pPager = pBt->pPager;
10482 sCheck.nPage = btreePagecount(sCheck.pBt);
10483 sCheck.mxErr = mxErr;
10484 sCheck.nErr = 0;
10485 sCheck.bOomFault = 0;
10486 sCheck.zPfx = 0;
10487 sCheck.v1 = 0;
10488 sCheck.v2 = 0;
10489 sCheck.aPgRef = 0;
10490 sCheck.heap = 0;
10491 sqlite3StrAccumInit(&sCheck.errMsg, 0, zErr, sizeof(zErr), SQLITE_MAX_LENGTH);
10492 sCheck.errMsg.printfFlags = SQLITE_PRINTF_INTERNAL;
10493 if( sCheck.nPage==0 ){
10494 goto integrity_ck_cleanup;
10497 sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1);
10498 if( !sCheck.aPgRef ){
10499 sCheck.bOomFault = 1;
10500 goto integrity_ck_cleanup;
10502 sCheck.heap = (u32*)sqlite3PageMalloc( pBt->pageSize );
10503 if( sCheck.heap==0 ){
10504 sCheck.bOomFault = 1;
10505 goto integrity_ck_cleanup;
10508 i = PENDING_BYTE_PAGE(pBt);
10509 if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i);
10511 /* Check the integrity of the freelist
10513 if( bCkFreelist ){
10514 sCheck.zPfx = "Main freelist: ";
10515 checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
10516 get4byte(&pBt->pPage1->aData[36]));
10517 sCheck.zPfx = 0;
10520 /* Check all the tables.
10522 #ifndef SQLITE_OMIT_AUTOVACUUM
10523 if( !bPartial ){
10524 if( pBt->autoVacuum ){
10525 Pgno mx = 0;
10526 Pgno mxInHdr;
10527 for(i=0; (int)i<nRoot; i++) if( mx<aRoot[i] ) mx = aRoot[i];
10528 mxInHdr = get4byte(&pBt->pPage1->aData[52]);
10529 if( mx!=mxInHdr ){
10530 checkAppendMsg(&sCheck,
10531 "max rootpage (%d) disagrees with header (%d)",
10532 mx, mxInHdr
10535 }else if( get4byte(&pBt->pPage1->aData[64])!=0 ){
10536 checkAppendMsg(&sCheck,
10537 "incremental_vacuum enabled with a max rootpage of zero"
10541 #endif
10542 testcase( pBt->db->flags & SQLITE_CellSizeCk );
10543 pBt->db->flags &= ~(u64)SQLITE_CellSizeCk;
10544 for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
10545 i64 notUsed;
10546 if( aRoot[i]==0 ) continue;
10547 #ifndef SQLITE_OMIT_AUTOVACUUM
10548 if( pBt->autoVacuum && aRoot[i]>1 && !bPartial ){
10549 checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0);
10551 #endif
10552 checkTreePage(&sCheck, aRoot[i], &notUsed, LARGEST_INT64);
10554 pBt->db->flags = savedDbFlags;
10556 /* Make sure every page in the file is referenced
10558 if( !bPartial ){
10559 for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
10560 #ifdef SQLITE_OMIT_AUTOVACUUM
10561 if( getPageReferenced(&sCheck, i)==0 ){
10562 checkAppendMsg(&sCheck, "Page %d is never used", i);
10564 #else
10565 /* If the database supports auto-vacuum, make sure no tables contain
10566 ** references to pointer-map pages.
10568 if( getPageReferenced(&sCheck, i)==0 &&
10569 (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
10570 checkAppendMsg(&sCheck, "Page %d is never used", i);
10572 if( getPageReferenced(&sCheck, i)!=0 &&
10573 (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
10574 checkAppendMsg(&sCheck, "Pointer map page %d is referenced", i);
10576 #endif
10580 /* Clean up and report errors.
10582 integrity_ck_cleanup:
10583 sqlite3PageFree(sCheck.heap);
10584 sqlite3_free(sCheck.aPgRef);
10585 if( sCheck.bOomFault ){
10586 sqlite3_str_reset(&sCheck.errMsg);
10587 sCheck.nErr++;
10589 *pnErr = sCheck.nErr;
10590 if( sCheck.nErr==0 ) sqlite3_str_reset(&sCheck.errMsg);
10591 /* Make sure this analysis did not leave any unref() pages. */
10592 assert( nRef==sqlite3PagerRefcount(pBt->pPager) );
10593 sqlite3BtreeLeave(p);
10594 return sqlite3StrAccumFinish(&sCheck.errMsg);
10596 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
10599 ** Return the full pathname of the underlying database file. Return
10600 ** an empty string if the database is in-memory or a TEMP database.
10602 ** The pager filename is invariant as long as the pager is
10603 ** open so it is safe to access without the BtShared mutex.
10605 const char *sqlite3BtreeGetFilename(Btree *p){
10606 assert( p->pBt->pPager!=0 );
10607 return sqlite3PagerFilename(p->pBt->pPager, 1);
10611 ** Return the pathname of the journal file for this database. The return
10612 ** value of this routine is the same regardless of whether the journal file
10613 ** has been created or not.
10615 ** The pager journal filename is invariant as long as the pager is
10616 ** open so it is safe to access without the BtShared mutex.
10618 const char *sqlite3BtreeGetJournalname(Btree *p){
10619 assert( p->pBt->pPager!=0 );
10620 return sqlite3PagerJournalname(p->pBt->pPager);
10624 ** Return one of SQLITE_TXN_NONE, SQLITE_TXN_READ, or SQLITE_TXN_WRITE
10625 ** to describe the current transaction state of Btree p.
10627 int sqlite3BtreeTxnState(Btree *p){
10628 assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
10629 return p ? p->inTrans : 0;
10632 #ifndef SQLITE_OMIT_WAL
10634 ** Run a checkpoint on the Btree passed as the first argument.
10636 ** Return SQLITE_LOCKED if this or any other connection has an open
10637 ** transaction on the shared-cache the argument Btree is connected to.
10639 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
10641 int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
10642 int rc = SQLITE_OK;
10643 if( p ){
10644 BtShared *pBt = p->pBt;
10645 sqlite3BtreeEnter(p);
10646 if( pBt->inTransaction!=TRANS_NONE ){
10647 rc = SQLITE_LOCKED;
10648 }else{
10649 rc = sqlite3PagerCheckpoint(pBt->pPager, p->db, eMode, pnLog, pnCkpt);
10651 sqlite3BtreeLeave(p);
10653 return rc;
10655 #endif
10658 ** Return true if there is currently a backup running on Btree p.
10660 int sqlite3BtreeIsInBackup(Btree *p){
10661 assert( p );
10662 assert( sqlite3_mutex_held(p->db->mutex) );
10663 return p->nBackup!=0;
10667 ** This function returns a pointer to a blob of memory associated with
10668 ** a single shared-btree. The memory is used by client code for its own
10669 ** purposes (for example, to store a high-level schema associated with
10670 ** the shared-btree). The btree layer manages reference counting issues.
10672 ** The first time this is called on a shared-btree, nBytes bytes of memory
10673 ** are allocated, zeroed, and returned to the caller. For each subsequent
10674 ** call the nBytes parameter is ignored and a pointer to the same blob
10675 ** of memory returned.
10677 ** If the nBytes parameter is 0 and the blob of memory has not yet been
10678 ** allocated, a null pointer is returned. If the blob has already been
10679 ** allocated, it is returned as normal.
10681 ** Just before the shared-btree is closed, the function passed as the
10682 ** xFree argument when the memory allocation was made is invoked on the
10683 ** blob of allocated memory. The xFree function should not call sqlite3_free()
10684 ** on the memory, the btree layer does that.
10686 void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
10687 BtShared *pBt = p->pBt;
10688 sqlite3BtreeEnter(p);
10689 if( !pBt->pSchema && nBytes ){
10690 pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
10691 pBt->xFreeSchema = xFree;
10693 sqlite3BtreeLeave(p);
10694 return pBt->pSchema;
10698 ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
10699 ** btree as the argument handle holds an exclusive lock on the
10700 ** sqlite_schema table. Otherwise SQLITE_OK.
10702 int sqlite3BtreeSchemaLocked(Btree *p){
10703 int rc;
10704 assert( sqlite3_mutex_held(p->db->mutex) );
10705 sqlite3BtreeEnter(p);
10706 rc = querySharedCacheTableLock(p, SCHEMA_ROOT, READ_LOCK);
10707 assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
10708 sqlite3BtreeLeave(p);
10709 return rc;
10713 #ifndef SQLITE_OMIT_SHARED_CACHE
10715 ** Obtain a lock on the table whose root page is iTab. The
10716 ** lock is a write lock if isWritelock is true or a read lock
10717 ** if it is false.
10719 int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
10720 int rc = SQLITE_OK;
10721 assert( p->inTrans!=TRANS_NONE );
10722 if( p->sharable ){
10723 u8 lockType = READ_LOCK + isWriteLock;
10724 assert( READ_LOCK+1==WRITE_LOCK );
10725 assert( isWriteLock==0 || isWriteLock==1 );
10727 sqlite3BtreeEnter(p);
10728 rc = querySharedCacheTableLock(p, iTab, lockType);
10729 if( rc==SQLITE_OK ){
10730 rc = setSharedCacheTableLock(p, iTab, lockType);
10732 sqlite3BtreeLeave(p);
10734 return rc;
10736 #endif
10738 #ifndef SQLITE_OMIT_INCRBLOB
10740 ** Argument pCsr must be a cursor opened for writing on an
10741 ** INTKEY table currently pointing at a valid table entry.
10742 ** This function modifies the data stored as part of that entry.
10744 ** Only the data content may only be modified, it is not possible to
10745 ** change the length of the data stored. If this function is called with
10746 ** parameters that attempt to write past the end of the existing data,
10747 ** no modifications are made and SQLITE_CORRUPT is returned.
10749 int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
10750 int rc;
10751 assert( cursorOwnsBtShared(pCsr) );
10752 assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
10753 assert( pCsr->curFlags & BTCF_Incrblob );
10755 rc = restoreCursorPosition(pCsr);
10756 if( rc!=SQLITE_OK ){
10757 return rc;
10759 assert( pCsr->eState!=CURSOR_REQUIRESEEK );
10760 if( pCsr->eState!=CURSOR_VALID ){
10761 return SQLITE_ABORT;
10764 /* Save the positions of all other cursors open on this table. This is
10765 ** required in case any of them are holding references to an xFetch
10766 ** version of the b-tree page modified by the accessPayload call below.
10768 ** Note that pCsr must be open on a INTKEY table and saveCursorPosition()
10769 ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence
10770 ** saveAllCursors can only return SQLITE_OK.
10772 VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr);
10773 assert( rc==SQLITE_OK );
10775 /* Check some assumptions:
10776 ** (a) the cursor is open for writing,
10777 ** (b) there is a read/write transaction open,
10778 ** (c) the connection holds a write-lock on the table (if required),
10779 ** (d) there are no conflicting read-locks, and
10780 ** (e) the cursor points at a valid row of an intKey table.
10782 if( (pCsr->curFlags & BTCF_WriteFlag)==0 ){
10783 return SQLITE_READONLY;
10785 assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
10786 && pCsr->pBt->inTransaction==TRANS_WRITE );
10787 assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
10788 assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
10789 assert( pCsr->pPage->intKey );
10791 return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
10795 ** Mark this cursor as an incremental blob cursor.
10797 void sqlite3BtreeIncrblobCursor(BtCursor *pCur){
10798 pCur->curFlags |= BTCF_Incrblob;
10799 pCur->pBtree->hasIncrblobCur = 1;
10801 #endif
10804 ** Set both the "read version" (single byte at byte offset 18) and
10805 ** "write version" (single byte at byte offset 19) fields in the database
10806 ** header to iVersion.
10808 int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
10809 BtShared *pBt = pBtree->pBt;
10810 int rc; /* Return code */
10812 assert( iVersion==1 || iVersion==2 );
10814 /* If setting the version fields to 1, do not automatically open the
10815 ** WAL connection, even if the version fields are currently set to 2.
10817 pBt->btsFlags &= ~BTS_NO_WAL;
10818 if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
10820 rc = sqlite3BtreeBeginTrans(pBtree, 0, 0);
10821 if( rc==SQLITE_OK ){
10822 u8 *aData = pBt->pPage1->aData;
10823 if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
10824 rc = sqlite3BtreeBeginTrans(pBtree, 2, 0);
10825 if( rc==SQLITE_OK ){
10826 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
10827 if( rc==SQLITE_OK ){
10828 aData[18] = (u8)iVersion;
10829 aData[19] = (u8)iVersion;
10835 pBt->btsFlags &= ~BTS_NO_WAL;
10836 return rc;
10840 ** Return true if the cursor has a hint specified. This routine is
10841 ** only used from within assert() statements
10843 int sqlite3BtreeCursorHasHint(BtCursor *pCsr, unsigned int mask){
10844 return (pCsr->hints & mask)!=0;
10848 ** Return true if the given Btree is read-only.
10850 int sqlite3BtreeIsReadonly(Btree *p){
10851 return (p->pBt->btsFlags & BTS_READ_ONLY)!=0;
10855 ** Return the size of the header added to each page by this module.
10857 int sqlite3HeaderSizeBtree(void){ return ROUND8(sizeof(MemPage)); }
10859 #if !defined(SQLITE_OMIT_SHARED_CACHE)
10861 ** Return true if the Btree passed as the only argument is sharable.
10863 int sqlite3BtreeSharable(Btree *p){
10864 return p->sharable;
10868 ** Return the number of connections to the BtShared object accessed by
10869 ** the Btree handle passed as the only argument. For private caches
10870 ** this is always 1. For shared caches it may be 1 or greater.
10872 int sqlite3BtreeConnectionCount(Btree *p){
10873 testcase( p->sharable );
10874 return p->pBt->nRef;
10876 #endif